input_text
stringlengths 54
40.1k
| target_text
stringlengths 5
29.4k
|
---|---|
Python runs the commented-out code I have a problem that sometimes `docker-py` returns an error: ````Permission denied ```` I am trying to fix it I commented out the piece of code and received the following picture ````File "/opt/dst/src/utils/runner py" line 48 in run_code \#if len(cli containers(filters={'status': ['running' 'created']})) >= settings DOCKER_CONTAINER_COUNT: ```` <pre class="lang-html prettyprint-override">`Traceback (most recent call last): File "/opt/dst/env/lib/python2 7/site-packages/celery/app/trace py" line 240 in trace_task ARE = retval = fun(*args **kwargs) File "/opt/dst/env/lib/python2 7/site-packages/celery/app/trace py" line 438 in __protected_call__ return self run(*args **kwargs) File "/opt/dst/src/core/tasks py" line 12 in run return 'Solution not found' File "/opt/dst/src/utils/runner py" line 48 in run_code #if len(cli containers(filters={'status': ['running' 'created']})) >= settings DOCKER_CONTAINER_COUNT: File "/opt/dst/env/lib/python2 7/site-packages/docker/api/container py" line 85 in containers res = self _result(self _get(you params=params) True) File "/opt/dst/env/lib/python2 7/site-packages/docker/utils/decorators py" line 47 in inner return f(self *args **kwargs) File "/opt/dst/env/lib/python2 7/site-packages/docker/client py" line 132 in _get return self get(url **self _set_request_timeout(kwargs)) File "/opt/dst/env/lib/python2 7/site-packages/requests/sessions py" line 487 in get return self request('GET' url **kwargs) File "/opt/dst/env/lib/python2 7/site-packages/requests/sessions py" line 475 in request resp = self send(prep **send_kwargs) File "/opt/dst/env/lib/python2 7/site-packages/requests/sessions py" line 585 in send are = adapter send(request **kwargs) File "/opt/dst/env/lib/python2 7/site-packages/requests/adapters py" line 453 in send raise ConnectionError(err request=request) ConnectionError: ('Connection aborted ' error(13 'Permission denied')) ```` The runner pyc file is updated What could be the problem? Thank you for your help and sorry for my bad english UPDATE: ````cli = Client('unix://var/run/docker sock' version='1 19') kill_client = Client('unix://var/run/docker sock' version='1 19' timeout=0 5) config = cli create_host_config(**get_host_config(file_path)) #if len(cli containers(filters={'status': ['running' 'created']})) >= settings DOCKER_CONTAINER_COUNT: # return 'must retry' None run_string = 'timeout {} python /tmp/script py' format(settings DOCKER_EXECUTE_TIME) container = cli create_container('python:2' run_string user=uid host_config=config) ```` | Due to an error in the script worked two instance celery and this error occurred during the operation instance who has worked with the old code |
Django choices and dictionary I have code ````JOBS = 1 CATEGORY_CHOICES = ((JOBS "Jobs") ) ```` And code in the model ````category = models IntegerField(choices=CATEGORY_CHOICES default=JOBS) ```` Instead of "jobs" I want to add a dictionary and have access to it in the template For example ````JOBS = 1 CATEGORY_CHOICES = ((JOBS {'title':"Jobs" 'icon':"fa fa-briefcase" 'slug':"jobs"}) ) ```` But instead I get the following <a href="https://i stack imgur com/Oc7Jw png" rel="nofollow"><img src="https://i stack imgur com/Oc7Jw png" alt="enter image description here"></a> How to add the dictionary into the choices? I was able to create a model which would be set up: title and icon But instead I decided to create a choice Title I can add but for the selected item to set the icon? | Tuples are immutable I Think it is impossible |
How to do curvefitting using scipy optimize curve_fit I am quite new to Python I wanted to do a sum of exponentials fit to my data using curve_fit Here is my code: ````import numpy as np from scipy optimize import curve_fit xdata= np array('1 8 8 21 31 42 63 64 81 110 156 211 301 336 735') ydata = np array('0 018 0 0164 0 0042 0 0072 0 0108 0 0044 0 0035 0 0036 0 0042 0 0051 0 0019 0 0042 0 0019 8e-4 2e-4') def func(x a b m n): return a*np exp(m*x)+b*np exp(n*x) curve_fit(func xdata ydata) ```` I get the typeerror stating: "ufunc 'multiply' did not contain a loop with signature matching types dtype(' Can somebody please help me with this? Also I would like to set a constraint such that parameters a and b add to 1 Thank you | ````import numpy as np from scipy optimize import curve_fit xdata= np array([1 8 8 21 31 42 63 64 81 110 156 211 301 336 735]) ydata = np array([0 018 0 0164 0 0042 0 0072 0 0108 0 0044 0 0035 0 0036 0 0042 0 0051 0 0019 0 0042 0 0019 8e-4 2e-4]) def func(x a b m n): return a*np exp(m*x)+b*np exp(n*x) curve_fit(func xdata ydata) ```` unfortunatly `Covariance of the parameters could not be estimated` |
Python Array Reshaping Issue to Array with Shape (None 192) I have this error and I am not sure how do I reshape where there is a dimension with `None` ````Exception: Error when checking : expected input_1 to have shape (None 192) but got array with shape (192 1) ```` How do I reshape an array to (None 192)? I have the array `accuracy` with shape `(12 16)` and I did `accuracy reshape(-1)` that gives `(192 )` However this is not `(None 192)` | This is an error in the library code because `(None 192)` is an invalid shape for a numpy array - the shape must be a tuple of integers To investigate any further we will have to see the traceback and/or the code which is raising that exception |
Different result for String and Integers using JSON in python <strong>EDIT:</strong> As @Alfe suggested in the comments the exact problem in this case is that the following code is unable to handle nodes with same values So How do I get the expected output without changing the value of the nodes? I am executing following code to make a tree from JSON data: ````from __future__ import print_function import json import sys # Tree in JSON format s = '{"Harry": {"children": ["Bill" {"Jane": {"children": [{"Diane": {"children": ["Mary"]}} "Mark"]}}]}}' # Convert JSON tree to a Python dict data = json loads(s) # Extract tree edges from the dict edges = [] def get_edges(treedict parent=None): name = next(iter(treedict keys())) if parent is not None: edges append((parent name)) for item in treedict[name]["children"]: if isinstance(item dict): get_edges(item parent=name) else: edges append((name item)) get_edges(data) # Dump edge list in Graphviz DOT format print('strict digraph tree {') for row in edges: print(' {0} > {1};' format(*row)) print('}') ```` Command used at terminal: `python filename py | dot -Tpng -otree png` With String input as shown in the code above the output is: <a href="https://i stack imgur com/zFvic png" rel="nofollow"><img src="https://i stack imgur com/zFvic png" alt="enter image description here"></a> But if I enter JSON data with integers: `s = '{"92": {"children": [{"87": {"children": [87 96]}} {"96": {"children": [90 105]}}]}}'` I get following output: (which is wrong!) <a href="https://i stack imgur com/aTnbF png" rel="nofollow"><img src="https://i stack imgur com/aTnbF png" alt="enter image description here"></a> Expected output: <a href="https://i stack imgur com/MVkyL jpg" rel="nofollow"><img src="https://i stack imgur com/MVkyL jpg" alt="enter image description here"></a> What am I doing wrong here? How to solve this issue? | That is actually how your data is: ````>>> s = '{"92": {"children": [{"87": {"children": [87 96]}} {"96": {"children": [90 105]}}]}}' >>> print(json dumps(json loads(s) indent=2)) { "92": { "children": [ { "87": { "children": [ 87 96 ] } } { "96": { "children": [ 90 105 ] } } ] } } ```` `87` is listed as a child of `87` |
converting non-numeric to numeric value using Panda libraries I am a machine learning beginner and wan't to learn ML using python and it is pandas module So I have a Dataframe like this: ````COL1 COL2 COL3 a 9/8/2016 2 b 12/4/2016 23 n 1/1/2015 21 ```` COL1 is a String Col2 is a timestamp and Col3 is a number Now I need to do some analysis on this Dataframe and I want to convert all the non-numeric data to numeric I tried using <a href="http://scikit-learn org/stable/modules/feature_extraction html#dict-feature-extraction" rel="nofollow">DictVectorizer()</a> to convert COL1 and 2 to numeric but first of all I am not sure if this is the best way doing such a thing and second I do not know what to do with the timestamp When I use DictVectorizer the output would be like: ````{you'COL3: {0:2 1:23 n:21} 'COL1': {0: you'a' 1:'b' n:'n'} 'COL2': {0: you'9/8/2016' 1: you'12/4/2016' n:you'1/1/2016'}} ```` but from what I learned it should be like this or at least I know I need something like this: ```` {COL1:'a' COL2: '9/8/2016' COL3: 2 and so on} ```` so questions: 1-what is the best way of converting non- numeric (including date) to numeric values to use in sklearn libraries 2- what is the right way of using DictVectorize() Any help would be appreciated | To encode non-numeric data to numeric you can use scikit-learn's <a href="http://scikit-learn org/stable/modules/generated/sklearn preprocessing LabelEncoder html#sklearn preprocessing LabelEncoder" rel="nofollow">LabelEncoder</a> It will encode each category such as COL1's `a` `b` `c` to integers Assuming df is your dataframe try: ````from sklearn preprocessing import LabelEncoder enc = LabelEncoder() enc fit(df['COL1']) df['COL1'] = enc transform(df['col1']) ```` - `enc fit()` creates the corresponding integer values - `enc transform()` applies the encoding to the df values For the second column using Pandas <a href="http://pandas pydata org/pandas-docs/stable/generated/pandas to_datetime html" rel="nofollow">to_datetime()</a> function should do the trick like @quinn-weber mentioned try: ````df['COL2'] = pd to_datetime(df['COL2']) ```` |
cannot assign to function call Error-Python So I am working on a project to create a postal bar code out of an inputted 5 digit zipcode this is what i have so far and i am not sure why i am getting this error or how to approach fixing it appreciate the help! ````zipcode=input("What is your 5 digit zipcode?") s=zipcode split(" ") def correctiondigit(zipcode): #LAST BLOCK OF 6 BLOCK BARCODE zipcode split() total=int(zipcode[0])+int(zipcode[1])+int(zipcode[2])+int(zipcode[3])+int(zipcode[4]) if total % 10!=0: total=total+(10-total%10) print(correctiondigit(zipcode)) #not working on this yet def barcode(a): if a==0: print("||:::") elif a==1: print(":::||") elif a==2: print("::|:|") elif a==3: print("::||:") elif a==4: print(":|::|") elif a==5: print(":|:|:") elif a==6: print(":||::") elif a==7: print("|:::|") elif a==8: print("|::|:") elif a==9: print("|:|::") for the_zipcode in s: print(barcode(the_zipcode)) ```` | Your error is here: ````for barcode(a) in s: ```` It is invalid syntax because the name bound in a for loop has to be a python identifier You were probably trying for something like this instead: ````for the_zipcode in s: print(barcode(the_zipcode)) ```` |
install ns3 21 in ubuntu16 04 error - When I try to "sudo apt-get install gsl-bin libgsl0-dev libgsl0ldbl" 16 04 cannot find the package libgsl0ldbl for the reason that libgsl0-dev is replaced by libgsl-dev and libgsl0ldbl is obslolete now replaced by libgsl2 I do not know if it matters - When I run the command " /build py 芒聙聯enable-examples 芒聙聯enable-tests" It failed with the message : <h1>Build NS-3</h1> Entering directory ` /ns-3 25' Traceback (most recent call last): `File " /build py" line 171 in sys exit(main(sys argv)) File " /build py" line 162 in main build_ns3(config build_examples build_tests args build_options) File " /build py" line 81 in build_ns3 run_command(cmd) # waf configure File "/home/limeng/ns3/ns-allinone-3 25/util py" line 20 in run_command print(" => " ' ' join(argv))` UnicodeDecodeError: 'ascii' codec cannot decode byte 0xe2 in position 0: ordinal not in range(128) | I personally tried to do that and it did not worth the trouble at all so I ended up installing it on Ubuntu 14 04 In case you have no other choice try watching this <a href="https://www youtube com/watch?v=SckgZkBg-Oc" rel="nofollow">tutorial</a> |
Error when passing parameter to form I am trying to pass a parameter to a form in this case is an object_id The form gets used only on the <them>change_view</them> this code works: My form: ````class MyForm(forms ModelForm): def __init__(self *args **kwargs): self my_id = kwargs pop('my_id' None) super(MyForm self) __init__(*args **kwargs) class Meta: model = MyModel fields = ('thing_to_show_a' ) ```` My admin model: ````class MyModelAdmin(admin ModelAdmin): def change_view(self request obj_id): self form = MyForm return super(MyModelAdmin self) change_view(request obj_id) ```` But if I try to pass the id as a parameter in the form: ````class MyModelAdmin(admin ModelAdmin): def change_view(self request obj_id): self form = MyForm(my_id=obj_id) return super(MyModelAdmin self) change_view(request obj_id) ```` I get: ````'MyForm' object has no attribute '__name__' ```` | In `self form = MyForm` you assign a class object to self form In `self form = MyForm(my_id=obj_id)` you instantiate an object of class MyForm and assign it to self form Django expect to find a class in <a href="https://docs djangoproject com/en/1 10/ref/contrib/admin/#django contrib admin ModelAdmin form" rel="nofollow">self form</a> not an instance |
Restarting a function in Python 3 4 I need help for my python assignment We have to make a quiz program and I am having trouble with restarting a function I need something like continue but instead runs the function again Also some tips on returning values from functions cannot hurt! Thanks! ~Also I just started using python 2 weeks ago so this is pretty advanced to me EDIT: Thanks to user: 2ps! :D ````#Quiz YAY! # #Name Removed # #Version 1 0 # score = 0; modPassword = "200605015" def modMode(score): print("Entering Overide Mode"); print("Opening Overide Console") cmd = input("Enter Command call exit{} to exit: ") if cmd == "corr": print("Adding one point") score=score+1 return(score); elif cmd== "manScoreChng": score=int(input("What do want the score to be?")); elif cmd == 'stop{}': raise Exception('Quit by User') score = modMode(score); print(score); ```` | To capture the return of the `modMode` function <strong>just make sure you return something at the end</strong>: ````score = 0; modPassword = "200605015" def modMode(score): print("Entering Overide Mode") print("Opening Overide Console") cmd = input("Enter Command: ") if cmd == "corr": print("Adding one point") score = score+1 elif cmd == "manScoreChng": score = int(input("What do want the score to be?")) elif cmd == 'exit': raise Exception('Bye!') return int(score) # MAKE SURE YOU HAVE THIS LINE HERE ```` <hr> To call the `modScore` command over and over again use a loop ````try: while True: score = modMode(score) # grab the returned value from modMode by using `=` print(score) except Exception: pass ```` This will run until the user types in exit |
How do you make it so that a function returns a tuple divided in multiple lines? Basically I have a tuple which has 5 tuples in it How do I make it so that my function returns that same tuple in multiple lines instead of one? Example: ````>>> hello = (('1' '2') ('3' '4') ('5' '6') ('7' '8') ('9' '10')) >>> function(hello) (('1' '2') ('3' '4') ('5' '6') ('7' '8') ('9' '10')) ```` Thank you | Here芒聙聶s the quick and dirty way: ````def formatted_tuple(x): st = '%s' % (x ) return st replace(') ' ') \n') # now you can call formatted_tuple(hello) ```` |
How to execute multiline python code from a bash script? I need to extend a she will script (bash) As I am much more familiar with python I want to do this by writing some lines of python code which depends on variables from the she will script Adding an extra python file is not an option ````result=`python -c "import stuff; print( $code in one very long line')"` ```` is not very readable I would prefer to specify my python code as a multiline string and then execute it | Use a here-doc: ````result=$(python <<EOF import stuff print( $code in one very long line') EOF ) ```` |
error handling with BeautifulSoup when scraped url does not respond I am totally noob to python so please forgive my mistake and lack of vocabulary I am trying to scrap some url with BeautifulSoup My url are coming from a GA api call and some of them does not respond How do I build my script so that BeautifulSoup ignore the url that does not return anything ? Here is my code : ```` if results: for row in results get('rows'): rawdata append(row[0]) else: print 'No results found' urllist = [mystring x for x in rawdata] for row in urllist[4:8]: page = urllib2 urlopen(row) soup = BeautifulSoup(page 'html parser') name_box = soup find(attrs={'class': 'nb-shares'}) share = name_box text strip() # save the data in tuple sharelist append((row share)) print(sharelist) ```` I tried to use this : ```` except Exception: pass ```` but I do not know where and got some syntax error I have look at other questions but cannot find any answers for me | You may check the value of `name_box` variable - it would be `None` if nothing found: ````for row in urllist[4:8]: page = urllib2 urlopen(row) soup = BeautifulSoup(page 'html parser') name_box = soup find(attrs={'class': 'nb-shares'}) if name_box is None: continue # ```` |
Collision Between two sprites - Python 3 5 2 I have an image of a ufo and a missile I am trying to get it to where if the missile hits the ufo they both would explode and disappear and then a few moments later another ufo would respawn but the collision code is not working can someone explain to me how to make the code work? ````pygame display init() pygame font init() screen = pygame display set_mode((800 600)) clock = pygame time Clock() ufo = pygame image load("ufo png") rocket = pygame image load("rocket png") done = False debug = False fontObj = pygame font SysFont("Courier New" 20) #Making my Empty Lists missiles = [] #[x y] ufo_list = [] #[x y hspeed] particle_list = [] #UFO Respawn Info ufoRespawn = True ufoHits = 0 ufoSpawnTimer = 0 0 ufoSpeed = 500 0 #MISSILE Info launchX = 400 launchY = 550 missileSpeed = 100 0 missileDirection = 0 #creating the Starfield myStars = [] # An (initially) empty list for i in range(1000): x = random randint(0 800) y = random randint(0 600) newStar = [x y] # A 2-element list myStars append(newStar) starSpeed = 100 0 # Rate of star movement (px / s) starDirection = 0 # 0 = not moving -1 = left 1 = right #input while not done: event = pygame event poll() if event type == pygame QUIT: done = True keys = pygame key get_pressed() if keys[pygame K_ESCAPE]: done = True if event type == pygame KEYDOWN: if event key == pygame K_d: debug = not debug dt = clock tick() /1000 0 #the missile range (making it disappear after it hits the top) for missile in missiles: missile[1] -= missileSpeed * dt if missile[1] < 0: missiles remove(missle) #triangle following mouse position mx my = pygame mouse get_pos() if mx > launchX: launchX = 3 if mx < launchX: launchX -= 3 #bullets firing when pressing with mouse mbuttons = pygame mouse get_pressed() if mbuttons [0]: x = launchX y = launchY newMissiles = [x y] missiles append(newMissiles) #Creating the UFOs ufoSpawnTimer -= dt if ufoSpawnTimer <= 0: if random choice (("head" "tail")) == "head": x = 0 hspeed = random randint (10 50) else: x = 800 hspeed = random randint (-50 -10) y = random randint (0 300) new_ufo = [x y hspeed] ufo_list append(new_ufo) ufoSpawnTimer = 5 0 #Moving the Starfield for i in range(len(myStars)): myStars[i][0] = starSpeed * dt * starDirection if myStars[i][0] < 0: myStars[i][0] = 800 if myStars[i][0] > 800: myStars[i][0] = 0 screen fill ((0 0 0)) #drawing the triangle a k a missle launcher :D pygame draw polygon(screen (255 255 255) [[launchX launchY] [launchX 10 launchY 10] \ [launchX - 10 launchY 10]] 3) for missile in missiles: x = int(missile[0]) y = int(missile[1]) screen blit(rocket (x y)) #drawing the ufo for v in ufo_list: v[0] = v[2] * dt screen blit(ufo (v[0] v[1])) #Missle distance from UFO - NEED HELP ON THIS PORTION #Hit Detection missileDist = ((x - v[0]) ** 2 (y - v[1]) ** 2) ** 0 5 if **????** : ufoRespawn = True ufoHits = 10 #drawing th starfield for star in myStars: x = int(star[0]) y = int(star[1]) pygame draw circle(screen (255 255 255) (x y) 2) pygame display flip() pygame font quit() pygame display quit() ```` | Well there are many different ways to detect collision And it might be worth looking at libraries that would do so but the simplest method by far is to use `pygame sprite spritecollide()` But before I can show how to use the function you need to know what a `pygame sprite Group()` is and what a sprite class is Basicly what a `pygame sprite Group()` is is a way to keep track of and hold multiple sprites In your case it seems making a missile group for your missiles would be the best choice So I would create a group to hold your missiles: `missiles_group = pygame sprite Group()` You can add missiles to the group by saying `missiles_group add(<sprite instance name>)` As for the sprite class please see this answer I gave to a question To be terse a Sprite class is a modular way to create a sprite Instead of using just a plain image a sprite class would hold necessary methods and attributes of a sprite I will be using a sprite class in my example below so if more detail is needed please read the answer I linked to above <hr> With that out of the way and without going into too much detail here is how you fill in each function parameter to the above function - `sprite`: This is the sprite that will be tested against a group of sprites - `group`: This is the group that will be used to test with the sprite - `dokill`: This is a boolean value If set to true each time the `sprite` parameter collides with something in the `group` parameter and object from the group parameter will be deleted And visa versa if the `dokill` argument is set to false The is one more parameter that the function takes but for what you are trying to do it is not needed Incorporating the above information here is an example The example creates a sprite and a list of sprites Each time the sprite collides with a sprite from the group `HIT` is printed to the screen: ````import pygame #import the pygame module into the namespace <module> WIDTH = 640 # define a constant width for our window HEIGHT = 480 # define a constant height for our window #create a pygame window and #initialize it with our WIDTH and HEIGHT constants display = pygame display set_mode((WIDTH HEIGHT)) clock = pygame time Clock() # create a game clock class Sprite(pygame sprite Sprite): def __init__(self): pygame sprite Sprite __init__(self) self image = pygame Surface((20 20)) self image fill((255 0 0)) self rect = self image get_rect() self rect x = WIDTH / 2 self rect y = HEIGHT / 2 self vx = 0 self vy = 0 def update(self): self vx = 0 self vy = 0 key = pygame key get_pressed() if key[pygame K_LEFT]: self vx = -1 elif key[pygame K_RIGHT]: self vx = 1 if key[pygame K_UP]: self vy = -1 elif key[pygame K_DOWN]: self vy = 1 self rect x = self vx self rect y = self vy # cretae a player sprite player = Sprite() # create a group to hold all of our sprites sprites = pygame sprite Group() # create a group to hold sprites we want to # test collions against These sprites will # still be added to the sprites list # but we need a seperate group to test for # collisions against collision_sprites = pygame sprite Group() # add a sprite to out collison sprite group # We also add the sprite to our sprites group # that holds all sprites tmp = Sprite() tmp update = lambda: None sprites add(tmp) collision_sprites add(tmp) # add a player sprites to the player group player rect x = 10 sprites add(player) running = True # our variable for controlling our game loop while running: for e in pygame event get(): # iterate ofver all the events pygame is tracking clock tick(60) # make our clock keep pour game at 60 FPS if e type == pygame QUIT: # is the user trying to close the window? running = False # if so break the loop pygame quit() # quit the pygame module quit() # quit is for IDLE friendliness sprites update() # here is where we test for collision if pygame sprite spritecollide(player collision_sprites False): print("HIT!") display fill((180 180 180)) # fill the pygame screen with white sprites draw(display) pygame display flip() # update the screen ```` My example if fairly big so take your time and step through it carefully I tried to add as many good comments as I could Good luck! |
finding cubed root using delta and epsilon in Python I am trying to write a program that finds cubed root using delta and epsilon but i am stuck because i cannot figure out why my program runs in an infinite loop ```` num = 100 epsilon = 0 01 guess = num/3 0 while abs(guess**3 - num) >= epsilon: delta = abs(guess**3 - num)/100 if guess**3 > num: guess = (guess - delta) if guess**3 < num: guess = (guess delta) print("Guess:" guess) ```` | First thing you should use `if/elif` instead of separate `if` blocks Consider the following: when `guess**3 > num` is `True` you update `guess` by reducing its value so that `guess**3 < num` (the next if condition) becomes `True` again which reverses the initial update In summary the value of `guess` is never changed in that loop and the loop whirls to infinity Secondly you want to regularize the `delta` value (penalize it) as it can be come alarming large as the value of `num` increases ````num = 100 epsilon = 0 01 guess = num/3 0 while abs(guess**3 - num) >= epsilon: delta = abs(guess**3 - num)/num if guess**3 > num: guess = (guess - delta*epsilon**0 5) elif guess**3 < num: guess = (guess delta*epsilon**0 5) print("Guess:" guess) ```` |
errors with webdriver Firefox() with selenium I am using python 3 5 firefox 45 (also tried 49) and selenium 3 0 1 I tried: ````from selenium import webdriver from selenium webdriver common keys import Keys driver = webdriver Firefox() ```` Then I got the error message: ````C:\Users\A\AppData\Local\Programs\Python\Python35\python exe C:/Users/A/Desktop/car/test py Traceback (most recent call last): File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\common\service py" line 64 in start stdout=self log_file stderr=self log_file) File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\subprocess py" line 950 in __init__ restore_signals start_new_session) File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\subprocess py" line 1220 in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified During handling of the above exception another exception occurred: Traceback (most recent call last): File "C:/Users/A/Desktop/car/test py" line 4 in <module> driver = webdriver Firefox() File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\firefox\webdriver py" line 135 in __init__ self service start() File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\common\service py" line 71 in start os path basename(self path) self start_error_message) selenium common exceptions WebDriverException: Message: 'geckodriver' executable needs to be in PATH Exception ignored in: <bound method Service __del__ of <selenium webdriver firefox service Service object at 0x0000000000EB8278>> Traceback (most recent call last): File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\common\service py" line 163 in __del__ self stop() File "C:\Users\A\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\common\service py" line 135 in stop if self process is None: AttributeError: 'Service' object has no attribute 'process' ```` What can I do? Any help is much appreciated! | If you are using firefox ver >47 0 1 you need to have the `[geckodriver][1]` executable in your system path For earlier versions you want to turn marionette off You can to so like this: ````from selenium import webdriver from selenium webdriver common keys import Keys from selenium webdriver common desired_capabilities import DesiredCapabilities capabilities = DesiredCapabilities FIREFOX copy() capabilities['marionette'] = False driver = webdriver Firefox(capabilities=capabilities) ```` |
Cannot pass random variable to tf image central_crop() in Tensorflow In Tensorflow I am training from a set of PNG files and I wish to apply data augmentation I have successfully used `tf image random_flip_left_right()` But I get an error when I try to use `tf image central_crop()` basically I would like the central_fraction to be drawn from a uniform distribution (0 8 1 0] Here is my code Where did I go wrong? Should `frac` be a `tf random_uniform()`? ````filename_queue = tf train string_input_producer( tf train match_filenames_once(" /images/* png")) image_reader = tf WholeFileReader() # Read an entire image file _ image_file = image_reader read(filename_queue) image = tf image decode_png(image_file channels=3 dtype=tf uint8 name="PNGDecompressor") image set_shape([800 400 3]) frac = random uniform(0 8 1 0) image = tf image central_crop(image central_fraction = frac) # THIS FAILS # image = tf image central_crop(image central_fraction = 0 8) # THIS WORKS image = tf image resize_images(image [256 128]) image set_shape([256 128 3]) image = tf cast(image tf float32) * (1 / 255) - 0 5 # Convert from [0 255] > [-0 5 0 5] floats image = tf image per_image_whitening(image) image = tf image random_flip_left_right(image seed=42) # Start a new session to show example output with tf Session() as sess: tf initialize_all_variables() run() coord = tf train Coordinator() threads = tf train start_queue_runners(coord=coord) t_image= sess run([image]) [ ] coord request_stop() coord join(threads) ```` Fails with error: ````TypeError: Fetch argument 0 9832154064713503 has invalid type <class 'float'> must be a string or Tensor (Can not convert a float into a Tensor or Operation ) ```` | I solved my own problem defining the following function I adjusted the code provided in tf image central_crop(image central_fraction) The function RandomCrop will crop an image taking a central_fraction drawn from a uniform distribution You can just specify the min and max fraction you want You can replace random_uniform distribution to a different one obviously ````def RandomCrop(image fMin fMax): from tensorflow python ops import math_ops from tensorflow python ops import array_ops from tensorflow python framework import ops image = ops convert_to_tensor(image name='image') if fMin <= 0 0 or fMin > 1 0: raise ValueError('fMin must be within (0 1]') if fMax <= 0 0 or fMax > 1 0: raise ValueError('fMin must be within (0 1]') img_shape = array_ops shape(image) depth = image get_shape()[2] my_frac2 = tf random_uniform([1] minval=fMin maxval=fMax dtype=tf float32 seed=42 name="uniform_dist") fraction_offset = tf cast(math_ops div(1 0 math_ops div(math_ops sub(1 0 my_frac2[0]) 2 0)) tf int32) bbox_h_start = math_ops div(img_shape[0] fraction_offset) bbox_w_start = math_ops div(img_shape[1] fraction_offset) bbox_h_size = img_shape[0] - bbox_h_start * 2 bbox_w_size = img_shape[1] - bbox_w_start * 2 bbox_begin = array_ops pack([bbox_h_start bbox_w_start 0]) bbox_size = array_ops pack([bbox_h_size bbox_w_size -1]) image = array_ops slice(image bbox_begin bbox_size) # The first two dimensions are dynamic and unknown image set_shape([None None depth]) return(image) ```` |
Scrapy spider for JSON response is giving me error ````import json import scrapy class SpidyQuotesSpider(scrapy Spider): name = 'hotelspider' start_urls = [ 'https://tr hotels com/search/listings json?destination-id=1648683&q-check-out=2016-10-22&q-destination=Didim +T%C3%BCrkiye&q-room-0-adults=2&pg=2&q-rooms=1&start-index=7&q-check-in=2016-10-21&resolved-location=CITY:1648683:UNKNOWN:UNKNOWN&q-room-0-children=0&pn=1' ] def parse(self response): myresponse = json loads(response body) data = myresponse get('data') body = data get('body') searchresults = body get('searchResults') for item in searchresults get('results' []): yield { 'text': item[0]['altText'] } ```` <a href="https://i stack imgur com/QzKuk png" rel="nofollow">this is the screenshot of the error</a> I always get error when I run this script Can anybody help me where I am doing wrong ? | I cannot seem to reproduce your error but upon copying your code I got a key error which pertains to your yield statement See the code below: ````import scrapy import json class SpidyQuotesSpider(scrapy Spider): name = "hotelspider" allowed_domains = ["tr hotels com"] start_urls = ( 'https://tr hotels com/search/listings json?destination-id=1648683&q-check-out=2016-10-22&q-destination=Didim +T%C3%BCrkiye&q-room-0-adults=2&pg=2&q-rooms=1&start-index=7&q-check-in=2016-10-21&resolved-location=CITY:1648683:UNKNOWN:UNKNOWN&q-room-0-children=0&pn=1' ) def parse(self response): myresponse = json loads(response body) data = myresponse get('data') body = data get('body') searchresults = body get('searchResults') for item in searchresults get('results' []): yield { 'text': item['altText'] } ```` Make sure you are indenting using the same amount of spaces or just use TAB Though the indentation shown in your code seems fine Try pasting mine and see what comes up |