sonic | 🦔 Fast, lightweight & schema-less search backend. An alternative to Elasticsearch that runs on a fe | Search Engine library
kandi X-RAY | sonic Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
sonic Key Features
sonic Examples and Code Snippets
Trending Discussions on sonic
Trending Discussions on sonic
QUESTION
I am trying to create a table (150 rows, 165 columns) in which :
- Each row is the name of a Pokemon (original Pokemon, 150)
- Each column is the name of an "attack" that any of these Pokemon can learn (first generation)
- Each element is either "1" or "0", indicating if that Pokemon can learn that "attack" (e.g. 1 = yes, 0 = no)
I was able to manually create this table in R:
Here are all the names:
names
[1] "Bulbasaur" "Ivysaur" "Venusaur" "Charmander" "Charmeleon" "Charizard" "Squirtle" "Wartortle" "Blastoise" "Caterpie" "Metapod" "Butterfree" "Weedle" "Kakuna" "Beedrill" "Pidgey" "Pidgeotto"
[18] "Pidgeot" "Rattata" "Raticate" "Spearow" "Fearow" "Ekans" "Arbok" "Pikachu" "Raichu" "Sandshrew" "Sandslash" "Nidoran" "Nidorina" "Nidoqueen" "Nidorino" "Nidoking" "Clefairy"
[35] "Clefable" "Vulpix" "Ninetales" "Jigglypuff" "Wigglytuff" "Zubat" "Golbat" "Oddish" "Gloom" "Vileplume" "Paras" "Parasect" "Venonat" "Venomoth" "Diglett" "Dugtrio" "Meowth"
[52] "Persian" "Psyduck" "Golduck" "Mankey" "Primeape" "Growlithe" "Arcanine" "Poliwag" "Poliwhirl" "Poliwrath" "Abra" "Kadabra" "Alakazam" "Machop" "Machoke" "Machamp" "Bellsprout"
[69] "Weepinbell" "Victreebel" "Tentacool" "Tentacruel" "Geodude" "Graveler" "Golem" "Ponyta" "Rapidash" "Slowpoke" "Slowbro" "Magnemite" "Magneton" "Farfetch’d" "Doduo" "Dodrio" "Seel"
[86] "Dewgong" "Grimer" "Muk" "Shellder" "Cloyster" "Gastly" "Haunter" "Gengar" "Onix" "Drowzee" "Hypno" "Krabby" "Kingler" "Voltorb" "Electrode" "Exeggcute" "Exeggutor"
[103] "Cubone" "Marowak" "Hitmonlee" "Hitmonchan" "Lickitung" "Koffing" "Weezing" "Rhyhorn" "Rhydon" "Chansey" "Tangela" "Kangaskhan" "Horsea" "Seadra" "Goldeen" "Seaking" "Staryu"
[120] "Starmie" "Mr.Mime" "Scyther" "Jynx" "Electabuzz" "Magmar" "Pinsir" "Tauros" "Magikarp" "Gyarados" "Lapras" "Ditto" "Eevee" "Vaporeon" "Jolteon" "Flareon" "Porygon"
[137] "Omanyte" "Omastar" "Kabuto" "Kabutops" "Aerodactyl" "Snorlax" "Articuno" "Zapdos" "Moltres" "Dratini" "Dragonair" "Dragonite" "Mewtwo" "Mew"
Here are all the attacks:
[1] "Absorb" "Acid " "Acid Armor " "Agility " "Amnesia " "Aurora Beam " "Barrage " "Barrier " "Bide " "Bind " "Bite " "Blizzard "
[13] "Body Slam " "Bone Club " "Bonemerang " "Bubble " "Bubble Beam " "Clamp " "Comet Punch " "Confuse Ray " "Confusion " "Constrict " "Conversion " "Counter "
[25] "Crabhammer " "Cut " "Defense Curl " "Dig " "Disable " "Dizzy Punch " "Double Kick " "Double Slap " "Double Team " "Double-Edge " "Dragon Rage " "Dream Eater "
[37] "Drill Peck " "Earthquake " "Egg Bomb " "Ember " "Explosion " "Fire Blast " "Fire Punch " "Fire Spin " "Fissure " "Flamethrower " "Flash " "Fly "
[49] "Focus Energy " "Fury Attack " "Fury Swipes " "Glare " "Growl " "Growth " "Guillotine " "Gust " "Harden " "Haze " "Headbutt " "High Jump Kick "
[61] "Horn Attack " "Horn Drill " "Hydro Pump " "Hyper Beam " "Hyper Fang " "Hypnosis " "Ice Beam " "Ice Punch " "Jump Kick " "Karate Chop " "Kinesis " "Leech Life "
[73] "Leech Seed " "Leer " "Lick " "Light Screen " "Lovely Kiss " "Low Kick " "Meditate " "Mega Drain " "Mega Kick " "Mega Punch " "Metronome " "Mimic "
[85] "Minimize " "Mirror Move " "Mist " "Night Shade " "Pay Day " "Peck " "Petal Dance " "Pin Missile " "Poison Gas " "Poison Powder " "Poison Sting " "Pound "
[97] "Psybeam " "Psychic " "Psywave " "Quick Attack " "Rage " "Razor Leaf " "Razor Wind " "Recover " "Reflect " "Rest " "Roar " "Rock Slide "
[109] "Rock Throw " "Rolling Kick " "Sand Attack " "Scratch " "Screech " "Seismic Toss " "Self-Destruct " "Sharpen " "Sing " "Skull Bash " "Sky Attack " "Slam "
[121] "Slash " "Sleep Powder " "Sludge " "Smog " "Smokescreen " "Soft-Boiled " "Solar Beam " "Sonic Boom " "Spike Cannon " "Splash " "Spore " "Stomp "
[133] "Strength " "String Shot " "Struggle " "Stun Spore " "Submission " "Substitute " "Super Fang " "Supersonic " "Surf " "Swift " "Swords Dance " "Tackle "
[145] "Tail Whip " "Take Down " "Teleport " "Thrash " "Thunder " "Thunder Punch " "Thunder Shock " "Thunder Wave " "Thunderbolt " "Toxic " "Transform " "Tri Attack "
[157] "Twineedle " "Vine Whip " "Vise Grip " "Water Gun " "Waterfall " "Whirlwind " "Wing Attack " "Withdraw " "Wrap "
Then I put them together into a table:
m <- data.frame(matrix(0, ncol = 165, nrow = 150))
rownames(m) <- names
colnames(m) <- moves
From a previous question (Webscraping Pokemon Data), I was able to figure out how to identify all 150 websites that contain information on which attack can be learned by which Pokemon:
template_1 = rep("https://pokemondb.net/pokedex/",150)
template_2 = rep("/moves/1",150)
pokemon_websites = data.frame(template_1, names, template_2)
pokemon_websites$full_website = paste(pokemon_websites$template_1, pokemon_websites$names, pokemon_websites$template_2)
library(stringr)
pokemon_websites$full_website = str_remove_all( pokemon_websites$full_website," ")
For example, here are the websites for the first 6 Pokemon:
head(pokemon_websites$full_website)
[1] "https://pokemondb.net/pokedex/Bulbasaur/moves/1" "https://pokemondb.net/pokedex/Ivysaur/moves/1" "https://pokemondb.net/pokedex/Venusaur/moves/1" "https://pokemondb.net/pokedex/Charmander/moves/1"
[5] "https://pokemondb.net/pokedex/Charmeleon/moves/1" "https://pokemondb.net/pokedex/Charizard/moves/1"
For instance, the first Pokemon "Bulbasaur" can learn the following moves (https://pokemondb.net/pokedex/Bulbasaur/moves/1):
This means that the following columns of "m" for the first row should replaced with "1":
growl = 1
tackle = 1
`Leech Seed ` = 1
`Vine Whip ` = 1
`Poison Power ` = 1
`Razor Leaf ` = 1
`Growth ` = 1
`Sleep Power ` = 1
`Solar Beam `= 1
Cut = 1
`Swords Dance`= 1
Toxic = 1
`Body Slam ` = 1
`Take Down ` = 1
`Double-Edge ` = 1
Rage = 1
`Mega Drain ` = 1
`Solar Beam ` = 1
Mimic = 1
`Double Team ` = 1
Reflect = 1
Bide = 1
Rest = 1
Substitute = 1
Is it possible to:
- Webscrape the list of 150 websites to find out which Pokemon can learn which attacks?
- When a Pokemon can learn that attack, replace the corresponding element to 1?
Thank you!
ANSWER
Answered 2022-Apr-04 at 22:59Here is the a solution taking the list of url to webpages of interest, collecting the moves from each table and creating a dataframe with the "1s".
Then combining the individual tables into the final answer
library(rvest)
library(dplyr)
urls <- c("https://pokemondb.net/pokedex/Bulbasaur/moves/1", "https://pokemondb.net/pokedex/Ivysaur/moves/1")
movedfs <- lapply(urls, function(url){
#read page
page <- read_html(url)
#get the tables
tables <- page %>% html_elements("table") %>% html_table()
#process the 3 tables
moves<-lapply(tables[1:3], function(table){
table$Move
})
foundmoves <- unique(trimws(unlist(moves)))
#make dataframe with the list of moves
tempdf <- data.frame(moves=t(foundmoves))
#make column names and value row
names(tempdf)<-foundmoves
tempdf[1,] <- 1
tempdf #return valye
})
#make final table
finaltable <- bind_rows(movedfs)
#replace the NA with 0
finaltable <- apply(finaltable, 2, function(x){
ifelse(is.na(x), 0, 1)
})
QUESTION
I want to perform the following task using fastfooddataset from
openintro` package in R.
a) Create a correlation matrix for the relations between calories, total_fat, sugar, and calcium for all items at Sonic, Subway, and Taco Bell, omitting missing values with na.omit().
b) Create a regression predicting whether or not a restaurant is McDonalds or Subway based on calories, sodium, and protein.
c) Run a regression predicting calories from saturated fat, fiber, and sugar. Based on standardized regression coefficients, identify the strongest predictor.
here is my code:
library(tidyverse)
library(openintro)
library(lm.beta)
fastfood <- openintro::fastfood
head(fastfood)
fastfood.corr <- cor(fastfood$calories, fastfood$total_fat, fastfood$sugar, fastfood$calcium,use="pairwise.complete.obs" ,method = "pearson")
but I'm getting errors Error in match.arg(alternative) : 'arg' must be NULL or a character vector:
ANSWER
Answered 2022-Feb-25 at 08:20You probably should apply cor
on a subset of your data frame columns like so:
cor(fastfood[c('calories', 'total_fat', 'sugar', 'calcium')],
use="pairwise.complete.obs", method="pearson")
# calories total_fat sugar calcium
# calories 1.0000000 0.9004937 0.4377113 0.3512067
# total_fat 0.9004937 1.0000000 0.2593702 0.1688170
# sugar 0.4377113 0.2593702 1.0000000 0.3105594
# calcium 0.3512067 0.1688170 0.3105594 1.0000000
You may also subset for specific rows (e.g. restaurants). (The difference to above is that when we subset without commas, data[j]
, columns are selected, and when we use a comma data[i, j]
, i
are rows and j
are columns. See ?Extract
.)
cor(fastfood[fastfood$restaurant %in% c("Sonic", "Subway", "Taco Bell"),
c('calories', 'total_fat', 'sugar', 'calcium')],
use="pairwise.complete.obs", method="pearson")
# calories total_fat sugar calcium
# calories 1.0000000 0.8402781 0.5150627 0.6127083
# total_fat 0.8402781 1.0000000 0.2234985 0.2415309
# sugar 0.5150627 0.2234985 1.0000000 0.6690489
# calcium 0.6127083 0.2415309 0.6690489 1.0000000
You could also use dplyr
syntax, but it's more code.
library(dplyr)
fastfood %>%
filter(restaurant %in% c("Sonic", "Subway", "Taco Bell")) %>%
select(calories, total_fat, sugar, calcium) %>%
cor(use="pairwise.complete.obs", method="pearson")
# calories total_fat sugar calcium
# calories 1.0000000 0.8402781 0.5150627 0.6127083
# total_fat 0.8402781 1.0000000 0.2234985 0.2415309
# sugar 0.5150627 0.2234985 1.0000000 0.6690489
# calcium 0.6127083 0.2415309 0.6690489 1.0000000
Data:
fastfood <- openintro::fastfood
QUESTION
I have a std::vector
containing sound data. Without copying its data, I'd like to use this vector as input to the sonicChangeFloatSpeed function of the Sonic library. This method expects a float*
as first argument and mutates the input array. After completion, the pointer in first argument would point to the result data.
data
gives me access to the internal array of a C++ vector and with assign
, I can replace the vector's contents. Hence, I tried the following:
float* ptr = vec.data();
int num_samples = sonicChangeFloatSpeed(ptr, vec.size(), 1., 1.5, 1., 1., 0, 41000, 1);
vec.assign(ptr, ptr + num_samples);
But when I run this program, I get the error double free or corruption (!prev)
with a SIGABRT
at this location. What is the problem of this approach and how would this question be solved more appropriately?
ANSWER
Answered 2022-Feb-21 at 01:42As I mentioned, I solved this problem by not using sonicChangeFloatSpeed
at all, but the code within it. Before reading the results from the stream into vec
, I do vec.resize(numSamples)
:
sonicStream stream = sonicCreateStream(16000, 1);
sonicSetSpeed(stream, speed);
sonicSetPitch(stream, pitch);
sonicSetVolume(stream, volume);
sonicSetRate(stream, rate);
auto length = static_cast(vec.size());
sonicWriteFloatToStream(stream, vec.data(), length);
sonicFlushStream(stream);
int numSamples = sonicSamplesAvailable(stream);
vec.resize(numSamples);
sonicReadFloatFromStream(stream, vec.data(), length);
sonicDestroyStream(stream);
QUESTION
I receive a file everyday that I need to insert data into then process and format it to get a useful report. I am very new to PowerShell, but I am trying to automate this to save some time, and learn as I go.
The issue I am running into now is Column A has numeric values stored as text. While manually formatting it, I would normally click the popup next to the cell, which then gives an option of "Convert to Number". How do I emulate this using PowerShell? I have attempted a few different methods that have allowed me to format the text number, but none of them have managed to convert it from text to number. Another way of manually doing it is by going to Data -> Text to Columns, but even manually this doesn't seem like the appropriate way of doing this.
I need this as a number and not text because later in the process it will be used in a vlookup. Also this column is in the initial report I receive, which is a .xlsx file, not part of the data I am pulling from our database.
$date = (Get-Date).tostring("yyyy.MM.dd.")
$dbserver = "server"
$dbdatabase = "database"
$dbuser = "user"
$dbpass = "password"
$conn = New-Object system.data.sqlclient.sqlconnection
$conn.connectionstring = "server=$dbserver;database=$dbdatabase;user id=$dbuser;password=$dbpass;"
$query = @"
SELECT DISTINCT
ORS.Reference2 AS 'CDL OrderID',
ORS.PKID AS 'Sonic Tracking',
D.DisplayCode AS 'HUB',
ZRZ.RouteID AS 'Default Route',
ORS.ROUTEID AS 'Assigned Route',
CAST(ORS.CREATEDWHEN AS DATE) AS 'Order Created Date',
p2.createdwhen AS 'RECEIVE Scan Date',
CASE WHEN p2.createdby like 'driver 9[0-9][0-9][0-9]' then 'Y'
ELSE ''
END AS 'Scanned?',
ORS.POSTDATE AS 'Post Date',
ors.pod AS 'POD',
ORS.COMPLETEDTIME AS 'CompletedTime',
(STUFF((SELECT ', ', EC.ExceptionDesc, ' ( Added: ', OSC.createdWhen, ' By: ',OSC.createdBy, ') '
FROM tblOrderRouteStops_StatusCodes OSC
LEFT JOIN tblexceptioncodes ec on osc.statuscode = ec.exceptionid
WHERE OSC.ORSID = ORS.PKID
ORDER BY osc.createdwhen
FOR XML PATH(''), TYPE).value('.', 'varchar(max)'), 1, 1, ' ') )
AS 'Status Code'
FROM tblOrderRouteStops ORS
LEFT JOIN tblParcel P ON ORS.PKID = P.ORDERID and p.reference like '128%AP1'
Left Join tblParcel p2 on p.reference = p2.reference and p2.createdby like 'driver 9[0-9][0-9][0-9]'
LEFT JOIN tblZones Z ON ORS.Zip = Z.Zip
LEFT JOIN tblDepots D ON Z.DepotID = D.DepotID
LEFT JOIN tblZonesRouteZones ZRZ ON Z.ZoneID = ZRZ.ZoneID AND ZRZ.ROUTELOOKUPID = 1
LEFT JOIN tblOrderRouteStops_StatusCodes OSC ON ORS.PKID = OSC.ORSID
LEFT JOIN tblExceptionCodes EC ON OSC.statusCode = EC.ExceptionID
WHERE 1=1
AND ORS.CUSTID = 3919
AND ORS.CREATEDWHEN > '2021-06-10'
AND ORS.REFERENCE2 <> ''
ORDER BY ORS.pkid DESC
"@
$sqlcmd = New-Object system.data.sqlclient.sqlcommand
$sqlcmd.CommandText = $query
$sqlcmd.Connection = $conn
$sqladpt = New-Object system.data.sqlclient.sqldataadapter
$sqladpt.selectcommand = $sqlcmd
$data = new-object system.data.dataset
$sqladpt.fill($data)
$dataset = $data.Tables[0]
#$wb = 'C:\Users\jthompson\Desktop\CDL Daily\' + $date + 'ReviewOrders.xlsx'
$wb = 'C:\Users\jthompson\Desktop\CDL Daily\test.xlsx'
$excel = new-object -ComObject excel.application
$excel.visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.workbooks.open($wb)
$ws1 = $wb.worksheets.item(1)
$ws2 = $wb.worksheets.add()
$dataset | convertto-csv -notype -delimiter `t | clip
[void]$ws2.cells.item(1).pastespecial()
$ws2.usedrange.entirecolumn.autofit()
$ws1.UsedRange.horizontalalignment = -4131
$ws2.UsedRange.horizontalalignment = -4131
$ws2.columns.item(6).numberformat = "MM/dd/yyy"
$ws2.columns.item(7).numberformat = "MM/dd/yyy"
$ws2.columns.item(9).numberformat = "MM/dd/yyy"
$ws2.columns.item(1).numberformat = "0.000001"
//this will format it with the correct decimals, but does not change it from text to number
$ws1.columns.item(1).numberformat = 0.000001
$wb.Save()
$wb.close()
$excel.Quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel)
Remove-Variable excel
Edit
Message stating number in cell is formatted as text
To clarify, after I use numberFormat, in the "Format Cells" dialogue box it states they are formatted as decimals with 6 places. However they still have the green triangle, and the popup with the message " The number in this cell is formatted as text or preceded by an apostrophe". Even when I manually format it the only way I have found to change it from text to numeric is by clicking "Convert to Number" or "Text to Column". Changing the format in "Format Cells" seems to have no effect on this.
No it is not a table and it is not linked to a data import. I receive this report from a customer, so it has no connections or dependencies.
ANSWER
Answered 2021-Aug-26 at 17:52NumberFormat
is the correct property - try out:
$excel = new-object -ComObject excel.application
$excel.visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.workbooks.open('c:\temp\test.xlsx')
$ws1 = $wb.worksheets.item(1)
$ws1.Columns.Item(1).NumberFormat = "#,##0.000000"
$wb.Save()
$wb.close()
$excel.Quit()
I tested this with a very simple .xlsx doc:
A B
- -
1 A
2 B
3 C
before changing the format, I verified the numbers got saved in General format using $ws1.Columns.Item(1).NumberFormat
. It returns General before the change, and returned Number format after saving and re-opening the file.
QUESTION
So I am doing a project where I have to make a game that gives the user three lives and each time the beamrect's rectangle collides with the player's, it subtracts a life and puts them in the original position. When lives == 0: there will be a death screen displayed. But for some reason, the death screen isn't being displayed even though I made sure that every time the player rect (being zonicrect) and the beamrect collided, it would subtract 1 from the life variable.
# Your header should go here, each comment should be initialed -DK
import pygame, sys
import os
# https://youtu.be/jO6qQDNa2UY
pygame.init()
FPS = 60
# Useful Variables
# Size
size = height, width = 900, 500
zonhw = zheight, zwidth = 70, 70
scale2 = height2, width2 = 600, 300
lscale = lheight, lwidth = 80, 80
beamsz = bheight, bwidth = 50,25
platz = pheight, pwidth = 10, 70
# RGB
white = (255, 255, 255)
black = (0,0,0)
blue = (0, 0, 128)
green = (0, 255, 0)
brown = (165,42,42)
# Speed
VEL = 5
beamspeed = 3
# Position
laserpos = posx, posy = 500,250
#other
i = 0
life = 3
score = 0
# graphics
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Zonic bootleg")
font = pygame.font.Font('freesansbold.ttf', 32)
zonic = pygame.image.load(os.path.join("image","zonic.gif"))
zonic = pygame.transform.scale(zonic, zonhw)
bg = pygame.image.load(os.path.join("image","sonic-back.jpg"))
bg = pygame.transform.scale(bg, size)
gg = pygame.image.load(os.path.join("image","gg.jpg"))
gg= pygame.transform.scale(gg, size)
lazerz = pygame.image.load(os.path.join("image","Lazerz.gif"))
lazerz = pygame.transform.scale(lazerz, lscale)
beam = pygame.image.load(os.path.join("image","laserbeam.jpg"))
beam = pygame.transform.scale(beam, beamsz)
lives = pygame.image.load(os.path.join("image","health.png"))
lives = pygame.transform.scale(lives,(40,40))
# zoncz = pygame.image.load(os.path.join("image","zoncz.png"))
# zoncz = pygame.transform.scale(zoncz, scale2)
#coalitions
def collider(life,beamrect,zonicrect,lazerect):
beamrect.x -= beamspeed
if zonicrect.colliderect(beamrect):
beamrect.x = lazerect.x+21
zonicrect.x = 0
if beamrect.x <-60:
#screen.blit(beam, (posx, posy))
beamrect.x += 550
def updating(score, beamrect):
if beamrect.x == 0:
score += 1
#Death
def death():
while life <= 0:
death = font.render("Death", True, white)
screen.fill(black)
screen.blit(death,(250, 250))
# zonic movement
def KWS(keyvar, zonicrect,flip):
if keyvar[pygame.K_RIGHT]: # right
zonicrect.x += VEL
flip = False
if zonicrect.x > 500:
zonicrect.x -= VEL
if keyvar[pygame.K_LEFT] and zonicrect.x + VEL > 0: # left
zonicrect.x -= VEL
flip = True
def flipx(flip,zonicrect):
if flip:
screen.blit(pygame.transform.flip(zonic,True,False),(zonicrect.x,zonicrect.y))
if flip == False:
screen.blit(pygame.transform.flip(zonic,False,False),(zonicrect.x,zonicrect.y))
# text = font.render('Lives: {0}'.format(life), True, green, blue)
def heart(beamrect,zonicrect,lazerect):
x = 1
i = -33
while life >= x:
x +=1
i+=32
screen.blit(lives, (2+i,0))
# draw
def drawingfunc(zonicrect,lazerect, beamrect,flip, zonczrect):
#screen.blit(death,(0,0))
screen.blit(bg, (0, 0))
heart(beamrect,zonicrect,lazerect)
flipx(flip,zonicrect)
#screen.blit(zonic,(zonicrect.x, zonicrect.y))
screen.blit(beam, (beamrect.x, beamrect.y+15))
screen.blit(lazerz, (lazerect.x+21,lazerect.y))
# score = font.render('Score: ')
# screen.blit(zonic, (zonczrect.x, zonczrect.y))
sore = font.render("Score: {0}".format(score), True, black, white)
screen.blit(sore, (30, 70))
pygame.draw.rect(screen, brown, pygame.Rect(200, 200, 100, 50))
pygame.display.update()
# mainloop and refresh rate
def main():
jump = False
jumpCount = 0
jumpMax = 15
flip = False
zonicrect = pygame.Rect(10, 250, zheight, zwidth)
lazerect = pygame.Rect(posx, posy, lheight, lwidth)
beamrect = pygame.Rect(posx, posy, bheight, bwidth)
zonczrect = pygame.Rect(50, 25, height2, width2)
# (30,0,32,32)
# livesrect = pygame.Rect(0,0,10,10)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if not jump and event.key == pygame.K_SPACE:
jump = True
jumpCount = jumpMax
death()
collider(life,beamrect,zonicrect,lazerect)
keyspressed = pygame.key.get_pressed()
KWS(keyspressed, zonicrect,flip)
updating(score, beamrect)
drawingfunc(zonicrect,lazerect, beamrect,flip, zonczrect)
flipx(flip, zonicrect)
if jump:
zonicrect.y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
pygame.quit()
# calling function NOTE: needs to always be at the end of file
if __name__ == "__main__":
main()
ANSWER
Answered 2022-Jan-26 at 18:36In your death
function, you forgot to call pygame.display.update()
at the bottom of your loop. That's why you cannot see the death screen even when life
is less than or equal to zero. Also, you need to add an event loop in your death
function, so that the window will keep responding to events while the loop is running.
def death():
while life <= 0:
death = font.render("Death", True, white)
screen.fill(black)
screen.blit(death, (250, 250))
def death():
while life <= 0:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
death = font.render("Death", True, white)
screen.fill(black)
screen.blit(death, (250, 250))
pygame.display.update()
# Your header should go here, each comment should be initialed -DK
import pygame, sys
import os
# https://youtu.be/jO6qQDNa2UY
pygame.init()
FPS = 60
# Useful Variables
# Size
size = height, width = 900, 500
zonhw = zheight, zwidth = 70, 70
scale2 = height2, width2 = 600, 300
lscale = lheight, lwidth = 80, 80
beamsz = bheight, bwidth = 50, 25
platz = pheight, pwidth = 10, 70
# RGB
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 128)
green = (0, 255, 0)
brown = (165, 42, 42)
# Speed
VEL = 5
beamspeed = 3
# Position
laserpos = posx, posy = 500, 250
# other
i = 0
life = 3
score = 0
# graphics
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Zonic bootleg")
font = pygame.font.Font('freesansbold.ttf', 32)
zonic = pygame.image.load(os.path.join("image", "zonic.gif"))
zonic = pygame.transform.scale(zonic, zonhw)
bg = pygame.image.load(os.path.join("image", "sonic-back.jpg"))
bg = pygame.transform.scale(bg, size)
gg = pygame.image.load(os.path.join("image", "gg.jpg"))
gg = pygame.transform.scale(gg, size)
lazerz = pygame.image.load(os.path.join("image", "Lazerz.gif"))
lazerz = pygame.transform.scale(lazerz, lscale)
beam = pygame.image.load(os.path.join("image", "laserbeam.jpg"))
beam = pygame.transform.scale(beam, beamsz)
lives = pygame.image.load(os.path.join("image", "health.png"))
lives = pygame.transform.scale(lives, (40, 40))
# zoncz = pygame.image.load(os.path.join("image","zoncz.png"))
# zoncz = pygame.transform.scale(zoncz, scale2)
# coalitions
def collider(life, beamrect, zonicrect, lazerect):
beamrect.x -= beamspeed
if zonicrect.colliderect(beamrect):
beamrect.x = lazerect.x + 21
zonicrect.x = 0
if beamrect.x < -60:
# screen.blit(beam, (posx, posy))
beamrect.x += 550
def updating(score, beamrect):
if beamrect.x == 0:
score += 1
# Death
def death():
while life <= 0:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
death = font.render("Death", True, white)
screen.fill(black)
screen.blit(death, (250, 250))
pygame.display.update()
# zonic movement
def KWS(keyvar, zonicrect, flip):
if keyvar[pygame.K_RIGHT]: # right
zonicrect.x += VEL
flip = False
if zonicrect.x > 500:
zonicrect.x -= VEL
if keyvar[pygame.K_LEFT] and zonicrect.x + VEL > 0: # left
zonicrect.x -= VEL
flip = True
def flipx(flip, zonicrect):
if flip:
screen.blit(pygame.transform.flip(zonic, True, False), (zonicrect.x, zonicrect.y))
if flip == False:
screen.blit(pygame.transform.flip(zonic, False, False), (zonicrect.x, zonicrect.y))
# text = font.render('Lives: {0}'.format(life), True, green, blue)
def heart(beamrect, zonicrect, lazerect):
x = 1
i = -33
while life >= x:
x += 1
i += 32
screen.blit(lives, (2 + i, 0))
# draw
def drawingfunc(zonicrect, lazerect, beamrect, flip, zonczrect):
# screen.blit(death,(0,0))
screen.blit(bg, (0, 0))
heart(beamrect, zonicrect, lazerect)
flipx(flip, zonicrect)
# screen.blit(zonic,(zonicrect.x, zonicrect.y))
screen.blit(beam, (beamrect.x, beamrect.y + 15))
screen.blit(lazerz, (lazerect.x + 21, lazerect.y))
# score = font.render('Score: ')
# screen.blit(zonic, (zonczrect.x, zonczrect.y))
sore = font.render("Score: {0}".format(score), True, black, white)
screen.blit(sore, (30, 70))
pygame.draw.rect(screen, brown, pygame.Rect(200, 200, 100, 50))
pygame.display.update()
# mainloop and refresh rate
def main():
jump = False
jumpCount = 0
jumpMax = 15
flip = False
zonicrect = pygame.Rect(10, 250, zheight, zwidth)
lazerect = pygame.Rect(posx, posy, lheight, lwidth)
beamrect = pygame.Rect(posx, posy, bheight, bwidth)
zonczrect = pygame.Rect(50, 25, height2, width2)
# (30,0,32,32)
# livesrect = pygame.Rect(0,0,10,10)
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if not jump and event.key == pygame.K_SPACE:
jump = True
jumpCount = jumpMax
death()
collider(life, beamrect, zonicrect, lazerect)
keyspressed = pygame.key.get_pressed()
KWS(keyspressed, zonicrect, flip)
updating(score, beamrect)
drawingfunc(zonicrect, lazerect, beamrect, flip, zonczrect)
flipx(flip, zonicrect)
if jump:
zonicrect.y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
pygame.quit()
sys.exit(0)
# calling function NOTE: needs to always be at the end of file
if __name__ == "__main__":
main()
QUESTION
I am in need of assistance with my program. I have to code a three-round word scramble program using 10 keywords that will appear scrambled to the user for them to guess it. My problem is that after one word the code just simply exits the loop. My intention is for the loop to be used again for a second and third time before exiting.
Here is the code:
#include
#include
#include
#include
using namespace std;
int main() {
while (true) {
enum fields { KEY, HINT, Locked };
const int NUM_WORDS = 10;
const string WORDS[NUM_WORDS][Locked] = {
{"MITCHELL", "NICKNAME IS MITCH,SO WHAT IS MY NAME?"},
{"PIZZA", "MY FAVORITE FOOD, IS ITALY."},
{"ROYCE", "SOME TUMBLE AND SOME ROLLS...?"},
{"INFINITY", "THE IMAGINARY NUMBER IS?"},
{"AMY", "FAVORITE SONIC CHARACTER IS ?"},
{"FIAT", "CRYPTO OVER; THIS TYPE OF CURRENCY?"},
{"RUSSIA", "SAINT PETERSBURG IS IN ?"},
{"DONETELLO", "TEENAGE MUTANT NINJA TURTLES"},
{"SON", "BROOKLYN PEOPLE SAY THIS WORD"},
{"FUN", "FEELING HAPPY"}
};
srand(static_cast(time(0)));
int choice = (rand() % NUM_WORDS);
string theWord = WORDS[choice][KEY]; // GUESSING THE WORDS
string theHint = WORDS[choice][HINT]; // Hint for Words
// Randomizing using the string; swapping charcters equal to the length of the words
string Jumble = theWord; // jumbled version of word
int length = Jumble.size();
for (int i = 0; i < length; ++i) {
int index1 = (rand() % length); // Random
int index2 = (rand() % length); // Random
char temp = Jumble[index1];
Jumble[index1] = Jumble[index2]; // Swapping charcters
Jumble[index2] = temp;
}
cout << "\t\t\Welcome to Word Jumble!\n\n"; // USING CARRIAGE RETURN; USING TITLE
cout << "Unscramble the letters to make a word.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "Enter 'quit' to quit the game.\n\n";
cout << "The jumble is:" << Jumble;
string guess;
cout << "\n\nYour guess:";
cin >> guess;
while ((guess != theWord) && (guess != "quit")) {
if (guess == "hint") {
cout << theHint;
} else {
cout << "Sorry, that's not it.";
}
cout << "\n\nYour guess:";
cin >> guess;
}
if (guess == theWord) {
cout << "\nTHat's it! You guessed it!\n";
}
cout << "\nThanks for playing.\n";
return 0;
}
}
ANSWER
Answered 2022-Jan-22 at 04:53#include
#include
#include
#include
using namespace std;
int main() {
while (true) {
enum fields { KEY, HINT, Locked };
const int NUM_WORDS = 10;
const string WORDS[NUM_WORDS][Locked] = {
{"MITCHELL", "NICKNAME IS MITCH,SO WHAT IS MY NAME?"},
{"PIZZA", "MY FAVORITE FOOD, IS ITALY."},
{"ROYCE", "SOME TUMBLE AND SOME ROLLS...?"},
{"INFINITY", "THE IMAGINARY NUMBER IS?"},
{"AMY", "FAVORITE SONIC CHARACTER IS ?"},
{"FIAT", "CRYPTO OVER; THIS TYPE OF CURRENCY?"},
{"RUSSIA", "SAINT PETERSBURG IS IN ?"},
{"DONETELLO", "TEENAGE MUTANT NINJA TURTLES"},
{"SON", "BROOKLYN PEOPLE SAY THIS WORD"},
{"FUN", "FEELING HAPPY"}
};
srand(static_cast(time(0)));
int choice = (rand() % NUM_WORDS);
string theWord = WORDS[choice][KEY]; // GUESSING THE WORDS
string theHint = WORDS[choice][HINT]; // Hint for Words
// Randomizing using the string; swapping charcters equal to the length of the words
string Jumble = theWord; // jumbled version of word
int length = Jumble.size();
for (int i = 0; i < length; ++i) {
int index1 = (rand() % length); // Random
int index2 = (rand() % length); // Random
char temp = Jumble[index1];
Jumble[index1] = Jumble[index2]; // Swapping charcters
Jumble[index2] = temp;
}
cout << "\t\t\Welcome to Word Jumble!\n\n"; // USING CARRIAGE RETURN; USING TITLE
cout << "Unscramble the letters to make a word.\n";
cout << "Enter 'hint' for a hint.\n";
cout << "Enter 'quit' to quit the game.\n\n";
cout << "The jumble is:" << Jumble;
string guess;
cout << "\n\nYour guess:";
cin >> guess;
while ((guess != theWord) && (guess != "quit")) {
if (guess == "hint") {
cout << theHint;
}
else {
cout << "Sorry, that's not it.";
}
cout << "\n\nYour guess:";
cin >> guess;
}
if (guess == theWord) {
cout << "\nTHat's it! You guessed it!\n";
}
cout << "\nThanks for playing.\n";
}
return 0;
}
QUESTION
I have some data in this form as below located at the start of the file
const _questions = [
{
'question': 'How long is New Zealand’s Ninety Mile Beach?',
'answers': [
'88km, so 55 miles long.',
'55km, so 34 miles long.',
'90km, so 56 miles long.'
],
'answer': 1,
},
{
'question':
'In which month does the German festival of Oktoberfest mostly take place?',
'answers': ['January', 'October', 'September'],
'answer': 2,
},
{
'question': 'Who composed the music for Sonic the Hedgehog 3?',
'answers': [
'Britney Spears',
'Timbaland',
'Michael Jackson',
],
'answer': 1,
},
]
I have a class like this
class QuestionNumber with ChangeNotifier {
List answerlist= [1, 2, 1];
}
I want to initialise the list to have all of the 'answer' numbers so that when that the list is initialised to List answerlist= [];
Thanks for any help!
ANSWER
Answered 2021-Dec-21 at 10:54You need a model class to handle this(easy approach), and in some cases you don't have answer
filed, for that I'm using default value 0,
Model Class
class Question {
final String question;
final List answers;
final int answer;
Question({
required this.question,
required this.answers,
required this.answer,
});
Map toMap() {
return {
'question': question,
'answers': answers,
'answer': answer,
};
}
factory Question.fromMap(Map map) {
return Question(
question: map['question'] ?? '',
answers: List.from(map['answers']),
answer: map['answer']?.toInt() ?? 0,
);
}
String toJson() => json.encode(toMap());
factory Question.fromJson(String source) =>
Question.fromMap(json.decode(source));
}
It is more like parsing json
Then do like
List questionlist =
_questions.map((q) => Question.fromMap(q)).toList();
List answerlist = [];
for (final q in questionlist) {
answerlist.add(q.answer);
}
Check on dartPad
QUESTION
I almost created the first game in Python, so I correct shortcomings. I added part of code in function def update(self)
to improve Sonic
Landing. the program shows error. What's wrong?
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
#[...]
def update(self):
hits_4 = pygame.sprite.collide_rect(player, platform4)
if self.vel.y > 0:
if hits_4:
if self.pos.y < hits_4[0].rect.bottom:
self.pos.y = hits_4[0].rect.top +1
self.vel.y = 0
def jump(self):
hits4 = pygame.sprite.collide_rect(self, platform4)
if hits4:
self.vel.y = -15 // 2
*Platform4
isn't iterable sprite. Error: File "C:\Users\дом\My project\Survival_with_Sonic.py", line 149, in update if self.pos.y < hits_4[0].rect.bottom: TypeError: 'bool' object is not subscriptable
ANSWER
Answered 2021-Dec-16 at 15:49pygame.sprite.collide_rect
returns True
or False
:
if pygame.sprite.collide_rect(player, platform4):
if 0 < self.pos.y < platform4.rect.bottom:
self.pos.y = platform4.rect.top +1
self.vel.y = 0
QUESTION
I am a complete beginner in using GCP functions/products. I have written the following code below, that takes a list of cities from a local folder, and call in weather data for each city in that list, eventually uploading those weather values into a table in BigQuery. I don't need to change the code anymore, as it creates new tables when a new week begins, now I would want to "deploy" (I am not even sure if this is called deploying a code) in the cloud for it to automatically run there. I tried using App Engine and Cloud Functions but faced issues in both places.
import requests, json, sqlite3, os, csv, datetime, re
from google.cloud import bigquery
#from google.cloud import storage
list_city = []
with open("list_of_cities.txt", "r") as pointer:
for line in pointer:
list_city.append(line.strip())
API_key = "PLACEHOLDER"
Base_URL = "http://api.weatherapi.com/v1/history.json?key="
yday = datetime.date.today() - datetime.timedelta(days = 1)
Date = yday.strftime("%Y-%m-%d")
table_id = f"sonic-cat-315013.weather_data.Historical_Weather_{yday.isocalendar()[0]}_{yday.isocalendar()[1]}"
credentials_path = r"PATH_TO_JSON_FILE"
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credentials_path
client = bigquery.Client()
try:
schema = [
bigquery.SchemaField("city", "STRING", mode="REQUIRED"),
bigquery.SchemaField("Date", "Date", mode="REQUIRED"),
bigquery.SchemaField("Hour", "INTEGER", mode="REQUIRED"),
bigquery.SchemaField("Temperature", "FLOAT", mode="REQUIRED"),
bigquery.SchemaField("Humidity", "FLOAT", mode="REQUIRED"),
bigquery.SchemaField("Condition", "STRING", mode="REQUIRED"),
bigquery.SchemaField("Chance_of_rain", "FLOAT", mode="REQUIRED"),
bigquery.SchemaField("Precipitation_mm", "FLOAT", mode="REQUIRED"),
bigquery.SchemaField("Cloud_coverage", "INTEGER", mode="REQUIRED"),
bigquery.SchemaField("Visibility_km", "FLOAT", mode="REQUIRED")
]
table = bigquery.Table(table_id, schema=schema)
table.time_partitioning = bigquery.TimePartitioning(
type_=bigquery.TimePartitioningType.DAY,
field="Date", # name of column to use for partitioning
)
table = client.create_table(table) # Make an API request.
print(
"Created table {}.{}.{}".format(table.project, table.dataset_id, table.table_id)
)
except:
print("Table {}_{} already exists".format(yday.isocalendar()[0], yday.isocalendar()[1]))
def get_weather():
try:
x["location"]
except:
print(f"API could not call city {city_name}")
global day, time, dailytemp, dailyhum, dailycond, chance_rain, Precipitation, Cloud_coverage, Visibility_km
day = []
time = []
dailytemp = []
dailyhum = []
dailycond = []
chance_rain = []
Precipitation = []
Cloud_coverage = []
Visibility_km = []
for i in range(24):
dayval = re.search("^\S*\s" ,x["forecast"]["forecastday"][0]["hour"][i]["time"])
timeval = re.search("\s(.*)" ,x["forecast"]["forecastday"][0]["hour"][i]["time"])
day.append(dayval.group()[:-1])
time.append(timeval.group()[1:])
dailytemp.append(x["forecast"]["forecastday"][0]["hour"][i]["temp_c"])
dailyhum.append(x["forecast"]["forecastday"][0]["hour"][i]["humidity"])
dailycond.append(x["forecast"]["forecastday"][0]["hour"][i]["condition"]["text"])
chance_rain.append(x["forecast"]["forecastday"][0]["hour"][i]["chance_of_rain"])
Precipitation.append(x["forecast"]["forecastday"][0]["hour"][i]["precip_mm"])
Cloud_coverage.append(x["forecast"]["forecastday"][0]["hour"][i]["cloud"])
Visibility_km.append(x["forecast"]["forecastday"][0]["hour"][i]["vis_km"])
for i in range(len(time)):
time[i] = int(time[i][:2])
def main():
i = 0
while i < len(list_city):
try:
global city_name
city_name = list_city[i]
complete_URL = Base_URL + API_key + "&q=" + city_name + "&dt=" + Date
response = requests.get(complete_URL, timeout = 10)
global x
x = response.json()
get_weather()
table = client.get_table(table_id)
varlist = []
for j in range(24):
variables = city_name, day[j], time[j], dailytemp[j], dailyhum[j], dailycond[j], chance_rain[j], Precipitation[j], Cloud_coverage[j], Visibility_km[j]
varlist.append(variables)
client.insert_rows(table, varlist)
print(f"City {city_name}, ({i+1} out of {len(list_city)}) successfully inserted")
i += 1
except Exception as e:
print(e)
continue
In the code, there is direct reference to two files that is located locally, one is the list of cities and the other is the JSON file containing the credentials to access my project in GCP. I believed that uploading these files in Cloud Storage and referencing them there won't be an issue, but then I realised that I can't actually access my Buckets in Cloud Storage without using the credential files.
This leads me to being unsure whether the entire process would be possible at all, how do I authenticate in the first place from the cloud, if I need to reference that first locally? Seems like an endless circle, where I'd authenticate from the file in Cloud Storage, but I'd need authentication first to access that file.
I'd really appreciate some help here, I have no idea where to go from this, and I also don't have great knowledge in SE/CS, I only know Python R and SQL.
ANSWER
Answered 2021-Dec-13 at 13:14There may be different flavors and options to deploy your application and these will depend on your application semantics and execution constraints.
It will be too hard to cover all of them and the official Google Cloud Platform documentation cover all of them in great details:
- Google Compute Engine
- Google Kubernetes Engine
- Google App Engine
- Google Cloud Functions
- Google Cloud Run
Based on my understanding of your application design, the most suitable ones would be:
- Google App Engine
- Google Cloud Functions
- Google Cloud Run: Check these criteria to see if you application is a good fit for this deployment style
I would suggest using Cloud Functions as you deployment option in which case your application will default to using the project App Engine service account to authenticate itself and perform allowed actions. Hence, you should only check if the default account PROJECT_ID@appspot.gserviceaccount.com under the IAM configuration section has proper access to needed APIs (BigQuery in your case).
In such a setup, you want need to push your service account key to Cloud Storage which I would recommend to avoid in either cases, and you want need to pull it either as the runtime will handle authentication the function for you.
QUESTION
How can I find the common combination of values in same columns of 2 dataframes? Basically same name
and same artistName
dat1<-structure(list(artistName = c("Adele", "Mariah Carey", "D-Block Europe",
"Wham!", "Ed Sheeran", "Adele", "Adele", "Elton John & Dua Lipa",
"ArrDee", "GAYLE", "Ed Sheeran", "The Pogues", "Ed Sheeran",
"Shakin' Stevens", "Leona Lewis", "Sam Fender", "Acraze", "Kelly Clarkson",
"Joel Corry", "SwitchOTR"), name = c("Easy On Me", "All I Want For Christmas Is You",
"Overseas (feat. Central Cee)", "Last Christmas", "Shivers",
"Oh My God", "I Drink Wine", "Cold Heart (PNAU Remix)", "Flowers (Say My Name)",
"abcdefu", "Bad Habits", "Fairytale of New York", "Overpass Graffiti",
"Merry Christmas Everyone", "One More Sleep", "Seventeen Going Under",
"Do It To It (feat. Cherish)", "Underneath the Tree", "I Wish (feat. Mabel)",
"Coming for You (feat. A1 x J1)")), row.names = c(NA, 20L), class = "data.frame")
dat2<-structure(list(artistName = c("Adele", "Rod Wave", "Kodak Black",
"Drake", "Nardo Wick", "Drake", "Adele", "Bruno Mars, Anderson .Paak & Silk Sonic",
"Adele", "Summer Walker & SZA", "Mariah Carey", "GAYLE", "Drake",
"Doja Cat", "Lil Nas X & Jack Harlow", "Taylor Swift", "The Kid LAROI & Justin Bieber",
"Adele", "Summer Walker", "Drake"), name = c("Easy On Me", "By Your Side",
"Super Gremlin", "Knife Talk (feat. 21 Savage & Project Pat)",
"Who Want Smoke?? (feat. G Herbo, Lil Durk & 21 Savage)", "Way 2 Sexy (feat. Future & Young Thug)",
"Oh My God", "Smokin Out The Window", "My Little Love", "No Love",
"All I Want For Christmas Is You", "abcdefu", "Girls Want Girls (feat. Lil Baby)",
"Need To Know", "INDUSTRY BABY", "All Too Well (10 Minute Version) (Taylor's Version) (From The Vault)",
"STAY", "I Drink Wine", "Insane", "Fair Trade (feat. Travis Scott)"
)), row.names = c(NA, 20L), class = "data.frame")
ANSWER
Answered 2021-Dec-02 at 22:32Is the following you are looking for?
dplyr::inner_join(dat1, dat2)
#> Joining, by = c("artistName", "name")
#> artistName name
#> 1 Adele Easy On Me
#> 2 Mariah Carey All I Want For Christmas Is You
#> 3 Adele Oh My God
#> 4 Adele I Drink Wine
#> 5 GAYLE abcdefu
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install sonic
channel.inet is set to 0.0.0.0:1491 (this lets Sonic be reached from outside the container)
store.kv.path is set to /var/lib/sonic/store/kv/ (this lets the external KV store directory be reached by Sonic)
store.fst.path is set to /var/lib/sonic/store/fst/ (this lets the external FST store directory be reached by Sonic)
Homebrew (macOS): brew install sonic ([see formula](https://formulae.brew.sh/formula/sonic))
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
Save this library and start creating your kit
Share this Page