qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
50,653,208
What I want to achieve is simple, in R I can do things like `paste0("https\\",1:10,"whatever",11:20)`, how to do such in Python? I found some things [here](https://stackoverflow.com/questions/28046408/equivalent-of-rs-paste-command-for-vector-of-numbers-in-python), but only allow for : `paste0("https\\",1:10)`. Anyone know how to figure this out, this must be easy to do but I can not find how.
2018/06/02
[ "https://Stackoverflow.com/questions/50653208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6113825/" ]
**@Jason**, I will suggest you to use any of these following 2 ways to do this task. ✓ By creating a list of texts using **list comprehension** and **zip()** function. > > **Note:** To print `\` on screen, use escape sequence `\\`. See [List of escape sequences and their use](https://msdn.microsoft.com/en-us/library/h21280bw.aspx). > > > Please comment if you think this answer doesn't satisfy your problem. I will change the answer based on your inputs and expected outputs. > > > ``` texts = ["https\\\\" + str(num1) + "whatever" + str(num2) for num1, num2 in zip(range(1,10),range(11, 20))] for text in texts: print(text) """ https\\1whatever11 https\\2whatever12 https\\3whatever13 https\\4whatever14 https\\5whatever15 https\\6whatever16 https\\7whatever17 https\\8whatever18 https\\9whatever19 """ ``` ✓ By defining a simple function **paste0()** that implements the above logic to return a list of texts. ``` import json def paste0(string1, range1, strring2, range2): texts = [string1 + str(num1) + string2 + str(num2) for num1, num2 in zip(range1, range2)] return texts texts = paste0("https\\\\", range(1, 10), "whatever", range(11, 20)) # Pretty printing the obtained list of texts using Jon module print(json.dumps(texts, indent=4)) """ [ "https\\\\1whatever11", "https\\\\2whatever12", "https\\\\3whatever13", "https\\\\4whatever14", "https\\\\5whatever15", "https\\\\6whatever16", "https\\\\7whatever17", "https\\\\8whatever18", "https\\\\9whatever19" ] """ ```
**Based on the link you provided,** this should work: ``` ["https://" + str(i) + "whatever" + str(i) for i in xrange(1,11)] ``` Gives the following output: ``` ['https://1whatever1', 'https://2whatever2', 'https://3whatever3', 'https://4whatever4', 'https://5whatever5', 'https://6whatever6', 'https://7whatever7', 'https://8whatever8', 'https://9whatever9', 'https://10whatever10'] ``` **EDIT:** This should work for `paste0("https\\",1:10,"whatever",11:20)` ``` paste_list = [] for i in xrange(1,11): # replace {0} with the value of i first_half = "https://{0}".format(i) for x in xrange(1,21): # replace {0} with the value of x second_half = "whatever{0}".format(x) # Concatenate the two halves of the string and append them to paste_list[] paste_list.append(first_half+second_half) print paste_list ```
29,219,814
Im kinda new to python, im trying to the basic task of splitting string data from a file using a double backslash (\\) delimiter. Its failing, so far: ``` from tkinter import filedialog import string import os #remove previous finalhostlist try: os.remove("finalhostlist.txt") except Exception as e: print (e) root = tk.Tk() root.withdraw() print ("choose hostname target list") file_path = filedialog.askopenfilename() with open("finalhostlist.txt", "wt") as rawhostlist: with open(file_path, "rt") as finhostlist: for line in finhostlist: ## rawhostlist.write("\n".join(line.split("\\\\"))) rawhostlist.write(line.replace(r'\\', '\n')) ``` I need the result to be from e.g. `\\Accounts01\\Accounts02` to `Accounts01 Accounts02` Can someone help me with this? I'm using python 3. **EDIT**: All good now, `strip("\\")` on its own did it for me. Thanks guys!
2015/03/23
[ "https://Stackoverflow.com/questions/29219814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3014488/" ]
write expects a string and you have passed it a list, if you want the contents written use `str.join`. ``` rawhostlist.write("\n".join(line.split("\\"))) ``` You also don't need to call close when you use `with`, it closes your file automatically and you actually never call close anyway as you are missing parens `rawhostlist.close -> rawhostlist.close()` It is not clear if you actually have 2,3 or 4 backslashes. Your original code has two, your edit has three so whichever it is you need to use to same amount to split. ``` In [66]: s = "\\Accounts01\\Accounts02" In [67]: "\n".join(s.split("\\\\")) Out[67]: '\\Accounts01\\Accounts02' In [68]: s = "\\\Accounts01\\\counts02" In [69]: "\n".join(s.split("\\\\")) Out[69]: '\nAccounts01\ncounts02' ``` If it varies then split with `\\` and filter empty strings. Looking at the file you posted, you have a single element on each line so simply use strip ``` with open("finalhostlist.txt", "wt") as f_out, open(infile, "rt") as f_in: for line in f_in: out.write(line.strip("\\")) ``` Output: ``` ACCOUNTS01 EXAMS01 EXAMS02 RECEPTION01 RECEPTION02 RECEPTION03 RECEPTION04 RECEPTION05 TEACHER01 TEACHER02 TEACHER03 TESTCENTRE-01 TESTCENTRE-02 TESTCENTRE-03 TESTCENTRE-04 TESTCENTRE-05 TESTCENTRE-06 TESTCENTRE-07 TESTCENTRE-08 TESTCENTRE-09 TESTCENTRE-10 TESTCENTRE-11 TESTCENTRE-12 TESTCENTRE-13 TESTCENTRE-14 TESTCENTRE-15 ```
if you want them written on separate lines: ``` for sub in line.split("\\"):rawhostlist.write(sub) ```
29,219,814
Im kinda new to python, im trying to the basic task of splitting string data from a file using a double backslash (\\) delimiter. Its failing, so far: ``` from tkinter import filedialog import string import os #remove previous finalhostlist try: os.remove("finalhostlist.txt") except Exception as e: print (e) root = tk.Tk() root.withdraw() print ("choose hostname target list") file_path = filedialog.askopenfilename() with open("finalhostlist.txt", "wt") as rawhostlist: with open(file_path, "rt") as finhostlist: for line in finhostlist: ## rawhostlist.write("\n".join(line.split("\\\\"))) rawhostlist.write(line.replace(r'\\', '\n')) ``` I need the result to be from e.g. `\\Accounts01\\Accounts02` to `Accounts01 Accounts02` Can someone help me with this? I'm using python 3. **EDIT**: All good now, `strip("\\")` on its own did it for me. Thanks guys!
2015/03/23
[ "https://Stackoverflow.com/questions/29219814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3014488/" ]
write expects a string and you have passed it a list, if you want the contents written use `str.join`. ``` rawhostlist.write("\n".join(line.split("\\"))) ``` You also don't need to call close when you use `with`, it closes your file automatically and you actually never call close anyway as you are missing parens `rawhostlist.close -> rawhostlist.close()` It is not clear if you actually have 2,3 or 4 backslashes. Your original code has two, your edit has three so whichever it is you need to use to same amount to split. ``` In [66]: s = "\\Accounts01\\Accounts02" In [67]: "\n".join(s.split("\\\\")) Out[67]: '\\Accounts01\\Accounts02' In [68]: s = "\\\Accounts01\\\counts02" In [69]: "\n".join(s.split("\\\\")) Out[69]: '\nAccounts01\ncounts02' ``` If it varies then split with `\\` and filter empty strings. Looking at the file you posted, you have a single element on each line so simply use strip ``` with open("finalhostlist.txt", "wt") as f_out, open(infile, "rt") as f_in: for line in f_in: out.write(line.strip("\\")) ``` Output: ``` ACCOUNTS01 EXAMS01 EXAMS02 RECEPTION01 RECEPTION02 RECEPTION03 RECEPTION04 RECEPTION05 TEACHER01 TEACHER02 TEACHER03 TESTCENTRE-01 TESTCENTRE-02 TESTCENTRE-03 TESTCENTRE-04 TESTCENTRE-05 TESTCENTRE-06 TESTCENTRE-07 TESTCENTRE-08 TESTCENTRE-09 TESTCENTRE-10 TESTCENTRE-11 TESTCENTRE-12 TESTCENTRE-13 TESTCENTRE-14 TESTCENTRE-15 ```
I would do `rawhostlist.write(line.replace(r'\\', '\n'))`. If you want a little more efficiency feel free to use `re.sub()` instead, but I don't think it will make much of a difference here. There's no need to call `.write()` for each line. And there is definitely no need to convert the string into a list -- just to convert it back into a string!
29,219,814
Im kinda new to python, im trying to the basic task of splitting string data from a file using a double backslash (\\) delimiter. Its failing, so far: ``` from tkinter import filedialog import string import os #remove previous finalhostlist try: os.remove("finalhostlist.txt") except Exception as e: print (e) root = tk.Tk() root.withdraw() print ("choose hostname target list") file_path = filedialog.askopenfilename() with open("finalhostlist.txt", "wt") as rawhostlist: with open(file_path, "rt") as finhostlist: for line in finhostlist: ## rawhostlist.write("\n".join(line.split("\\\\"))) rawhostlist.write(line.replace(r'\\', '\n')) ``` I need the result to be from e.g. `\\Accounts01\\Accounts02` to `Accounts01 Accounts02` Can someone help me with this? I'm using python 3. **EDIT**: All good now, `strip("\\")` on its own did it for me. Thanks guys!
2015/03/23
[ "https://Stackoverflow.com/questions/29219814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3014488/" ]
I would do `rawhostlist.write(line.replace(r'\\', '\n'))`. If you want a little more efficiency feel free to use `re.sub()` instead, but I don't think it will make much of a difference here. There's no need to call `.write()` for each line. And there is definitely no need to convert the string into a list -- just to convert it back into a string!
if you want them written on separate lines: ``` for sub in line.split("\\"):rawhostlist.write(sub) ```
20,369,642
I'm trying to get the keyboard code of a character pressed in python. For this, I need to see if a keypad number is pressed. *This is not what I'm looking for*: ``` import tty, sys tty.setcbreak(sys.stdin) def main(): tty.setcbreak(sys.stdin) while True: c = ord(sys.stdin.read(1)) if c == ord('q'): break if c: print c ``` which outputs the ascii code of the character. this means, i get the same ord for a keypad 1 as as a normal 1. I've also tried a similar setup using the `curses` library and `raw`, with the same results. I'm trying to get the raw keyboard code. How does one do this?
2013/12/04
[ "https://Stackoverflow.com/questions/20369642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1224926/" ]
As synthesizerpatel said, I need to go to a lower level. Using pyusb: ``` import usb.core, usb.util, usb.control dev = usb.core.find(idVendor=0x045e, idProduct=0x0780) try: if dev is None: raise ValueError('device not found') cfg = dev.get_active_configuration() interface_number = cfg[(0,0)].bInterfaceNumber intf = usb.util.find_descriptor( cfg, bInterfaceNumber=interface_number) dev.is_kernel_driver_active(intf): dev.detach_kernel_driver(intf) ep = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN) while True: try: # lsusb -v : find wMaxPacketSize (8 in my case) a = ep.read(8, timeout=2000) except usb.core.USBError: pass print a except: raise ``` This gives you an output: `array('B', [0, 0, 0, 0, 0, 0, 0, 0])` array pos: 0: AND of modifier keys (1 - control, 2 - shift, 4 - meta, 8 - super) 1: No idea 2 -7: key code of keys pushed. so: ``` [3, 0 , 89, 90, 91, 92, 93, 94] ``` is: ``` ctrl+shift+numpad1+numpad2+numpad3+numpad4+numpad5+numpad6 ``` If anyone knows what the second index stores, that would be awesome.
To get raw keyboard input from Python you need to snoop at a lower level than reading stdin. For OSX check this answer: [OS X - Python Keylogger - letters in double](https://stackoverflow.com/questions/13806829/os-x-python-keylogger-letters-in-double) For Windows, this might work: <http://www.daniweb.com/software-development/python/threads/229564/python-keylogger> [monitor keyboard events with python in windows 7](https://stackoverflow.com/questions/3476183/monitor-keyboard-events-with-python-in-windows-7)
20,369,642
I'm trying to get the keyboard code of a character pressed in python. For this, I need to see if a keypad number is pressed. *This is not what I'm looking for*: ``` import tty, sys tty.setcbreak(sys.stdin) def main(): tty.setcbreak(sys.stdin) while True: c = ord(sys.stdin.read(1)) if c == ord('q'): break if c: print c ``` which outputs the ascii code of the character. this means, i get the same ord for a keypad 1 as as a normal 1. I've also tried a similar setup using the `curses` library and `raw`, with the same results. I'm trying to get the raw keyboard code. How does one do this?
2013/12/04
[ "https://Stackoverflow.com/questions/20369642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1224926/" ]
To get raw keyboard input from Python you need to snoop at a lower level than reading stdin. For OSX check this answer: [OS X - Python Keylogger - letters in double](https://stackoverflow.com/questions/13806829/os-x-python-keylogger-letters-in-double) For Windows, this might work: <http://www.daniweb.com/software-development/python/threads/229564/python-keylogger> [monitor keyboard events with python in windows 7](https://stackoverflow.com/questions/3476183/monitor-keyboard-events-with-python-in-windows-7)
if you have opencv check this simple code: ``` import cv2, numpy as np img = np.ones((100,100))*100 while True: cv2.imshow('tracking',img) keyboard = cv2.waitKey(1) & 0xFF if keyboard !=255: print keyboard if keyboard==27: break cv2.destroyAllWindows() ``` now when the blank window opens press any keyboard key. ESC breaks the loop
20,369,642
I'm trying to get the keyboard code of a character pressed in python. For this, I need to see if a keypad number is pressed. *This is not what I'm looking for*: ``` import tty, sys tty.setcbreak(sys.stdin) def main(): tty.setcbreak(sys.stdin) while True: c = ord(sys.stdin.read(1)) if c == ord('q'): break if c: print c ``` which outputs the ascii code of the character. this means, i get the same ord for a keypad 1 as as a normal 1. I've also tried a similar setup using the `curses` library and `raw`, with the same results. I'm trying to get the raw keyboard code. How does one do this?
2013/12/04
[ "https://Stackoverflow.com/questions/20369642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1224926/" ]
As synthesizerpatel said, I need to go to a lower level. Using pyusb: ``` import usb.core, usb.util, usb.control dev = usb.core.find(idVendor=0x045e, idProduct=0x0780) try: if dev is None: raise ValueError('device not found') cfg = dev.get_active_configuration() interface_number = cfg[(0,0)].bInterfaceNumber intf = usb.util.find_descriptor( cfg, bInterfaceNumber=interface_number) dev.is_kernel_driver_active(intf): dev.detach_kernel_driver(intf) ep = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN) while True: try: # lsusb -v : find wMaxPacketSize (8 in my case) a = ep.read(8, timeout=2000) except usb.core.USBError: pass print a except: raise ``` This gives you an output: `array('B', [0, 0, 0, 0, 0, 0, 0, 0])` array pos: 0: AND of modifier keys (1 - control, 2 - shift, 4 - meta, 8 - super) 1: No idea 2 -7: key code of keys pushed. so: ``` [3, 0 , 89, 90, 91, 92, 93, 94] ``` is: ``` ctrl+shift+numpad1+numpad2+numpad3+numpad4+numpad5+numpad6 ``` If anyone knows what the second index stores, that would be awesome.
if you have opencv check this simple code: ``` import cv2, numpy as np img = np.ones((100,100))*100 while True: cv2.imshow('tracking',img) keyboard = cv2.waitKey(1) & 0xFF if keyboard !=255: print keyboard if keyboard==27: break cv2.destroyAllWindows() ``` now when the blank window opens press any keyboard key. ESC breaks the loop
54,229,785
How to check whether a folder exists in google drive with name using python? I have tried with the following code: ``` import requests import json access_token = 'token' url = 'https://www.googleapis.com/drive/v3/files' headers = { 'Authorization': 'Bearer' + access_token } response = requests.get(url, headers=headers) print(response.text) ```
2019/01/17
[ "https://Stackoverflow.com/questions/54229785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10506357/" ]
* You want to know whether a folder is existing in Google Drive using the folder name. * You want to achieve it using the access token and `requests.get()`. If my understanding is correct, how about this modification? Please think of this as just one of several answers. ### Modification points: * You can search the folder using the query for filtering the file of drive.files.list. + In your case, the query is as follows. - `name='filename' and mimeType='application/vnd.google-apps.folder'` + If you don't want to search in the trash box, please add `and trashed=false` to the query. * In order to confirm whether the folder is existing, in this case, it checks the property of `files`. This property is an array. If the folder is existing, the array has elements. ### Modified script: ``` import requests import json foldername = '#####' # Put folder name here. access_token = 'token' url = 'https://www.googleapis.com/drive/v3/files' headers = {'Authorization': 'Bearer ' + access_token} # Modified query = {'q': "name='" + foldername + "' and mimeType='application/vnd.google-apps.folder'"} # Added response = requests.get(url, headers=headers, params=query) # Modified obj = response.json() # Added if obj['files']: # Added print('Existing.') # Folder is existing. else: print('Not existing.') # Folder is not existing. ``` ### References: * [drive.files.list](https://developers.google.com/drive/api/v3/reference/files/list) * [Search for Files](https://developers.google.com/drive/api/v3/search-parameters) If I misunderstood your question, please tell me. I would like to modify it.
You may see this [sample code](https://gist.github.com/jmlrt/f524e1a45205a0b9f169eb713a223330) on how to check if destination folder exists and return its ID. ``` def get_folder_id(drive, parent_folder_id, folder_name): """ Check if destination folder exists and return it's ID """ # Auto-iterate through all files in the parent folder. file_list = GoogleDriveFileList() try: file_list = drive.ListFile( {'q': "'{0}' in parents and trashed=false".format(parent_folder_id)} ).GetList() # Exit if the parent folder doesn't exist except googleapiclient.errors.HttpError as err: # Parse error message message = ast.literal_eval(err.content)['error']['message'] if message == 'File not found: ': print(message + folder_name) exit(1) # Exit with stacktrace in case of other error else: raise # Find the the destination folder in the parent folder's files for file1 in file_list: if file1['title'] == folder_name: print('title: %s, id: %s' % (file1['title'], file1['id'])) return file1['id'] ``` Also from this [tutorial](https://www.programcreek.com/python/example/88814/pydrive.drive.GoogleDrive), you can check if folder exists and if not, then create one with the given name.
43,223,017
I am attempting to understand the excellent Code given as a guide by Andrej Karpathy: <https://gist.github.com/karpathy/d4dee566867f8291f086> I am new to python, still learning! I am doing the best I can to understand the following code from the link: ``` # perform parameter update with Adagrad for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update ``` I have read up on the [zip function](https://docs.python.org/3.3/library/functions.html#zip) and done some short tests to try to understand how this works. What I know so far, 5 Iterations, param == Wxh on the first iteration but not there on... Ideally I am trying to convert this code to C#, and to do that I need to understand it. In referring to [Python iterator and zip](https://stackoverflow.com/questions/38024554/python-iterator-and-zip) it appears as we are multiplying each item of each array: ``` param = Wxh * dWxh * mWxh ``` But then the variables `param` `dparam` and `mem` are being modified outside the zip function. How do these variables function in this for loop scenario?
2017/04/05
[ "https://Stackoverflow.com/questions/43223017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183804/" ]
Write a simple for loop with zip will help you learn a lot. for example: ``` for a, b, c in zip([1,2,3], [4,5,6], [7,8,9]): print a print b print c print "/" ``` This function will print: 1 4 7 / 2 5 8 / 3 6 7 So that the zip function just put those three lists together, and then using three variables param, dparam, mem to refer to different list. In each iteration, those three variables refer to certain item in their corresponding lists, just like `for i in [1, 2, 3]:`. In this way, you only need to write one for loop instead of three, to update grads for each parameters: Wxh, Whh, Why, bh, by. In the first iteration, only Wxh is updated using dWxh and mWxh following the adagrad rule. And secondly, update Whh using dWhh and mWhh, and so on.
Python treats the variables merely as *labels* or name tags. Since you have zipped those inside a `list` of lists, it doesn't matter where they are, as long as you address them by their name / label correctly. Kindly note, this may not work for immutable types like `int` or `str`, etc. Refer to this answer for more explanation - [Immutable vs Mutable types](https://stackoverflow.com/questions/8056130/immutable-vs-mutable-types).
43,223,017
I am attempting to understand the excellent Code given as a guide by Andrej Karpathy: <https://gist.github.com/karpathy/d4dee566867f8291f086> I am new to python, still learning! I am doing the best I can to understand the following code from the link: ``` # perform parameter update with Adagrad for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update ``` I have read up on the [zip function](https://docs.python.org/3.3/library/functions.html#zip) and done some short tests to try to understand how this works. What I know so far, 5 Iterations, param == Wxh on the first iteration but not there on... Ideally I am trying to convert this code to C#, and to do that I need to understand it. In referring to [Python iterator and zip](https://stackoverflow.com/questions/38024554/python-iterator-and-zip) it appears as we are multiplying each item of each array: ``` param = Wxh * dWxh * mWxh ``` But then the variables `param` `dparam` and `mem` are being modified outside the zip function. How do these variables function in this for loop scenario?
2017/04/05
[ "https://Stackoverflow.com/questions/43223017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183804/" ]
What does `zip` do? Quoting from the official documentation: > > Zip returns a list of tuples, where the i-th tuple contains the i-th > element from each of the argument sequences or iterables. The returned > list is truncated in length to the length of the shortest argument > sequence. > > > It means, ``` >>> zip(["A", "B"], ["C", "D"], ["E", "F"]) [('A', 'C', 'E'), ('B', 'D', 'F')] ``` So now, when you are looping through, you actually have a list of tuples. With Content like. ``` # These are strings here but in your case these are objects [('Wxh', 'dWxh', 'mWxh'), ('Whh', 'dWhh', 'mWhh'), ('Why', 'dWhy', 'mWhy'), ('bh', 'dbh', 'mbh'),('by', 'dby', 'mby')] ``` > > What I know so far, 5 Iterations, param == Wxh on the first iteration > but not there on... > > > You are right, Now lets analyze your loop. ``` for param, dparam, mem in m: print(param, dparam, mem) # Which prints ('Wxh', 'dWxh', 'mWxh') ('Whh', 'dWhh', 'mWhh') ('Why', 'dWhy', 'mWhy') ('bh', 'dbh', 'mbh') ('by', 'dby', 'mby') ``` Which means, on every iteration, the `params` get the zeroth index tuple value, `dparam` get the first and `mem` gets the second. Now when I type `param` out of the scope of for loop, I get ``` >>> param 'by' ``` It means params still holds the reference to `by` object. From official documentation: > > The for-loop makes assignments to the variables(s) in the target > list. [...] Names in the target list are not deleted when the loop is > finished, but if the sequence is empty, they will not have been > assigned to at all by the loop. > > >
Python treats the variables merely as *labels* or name tags. Since you have zipped those inside a `list` of lists, it doesn't matter where they are, as long as you address them by their name / label correctly. Kindly note, this may not work for immutable types like `int` or `str`, etc. Refer to this answer for more explanation - [Immutable vs Mutable types](https://stackoverflow.com/questions/8056130/immutable-vs-mutable-types).
43,223,017
I am attempting to understand the excellent Code given as a guide by Andrej Karpathy: <https://gist.github.com/karpathy/d4dee566867f8291f086> I am new to python, still learning! I am doing the best I can to understand the following code from the link: ``` # perform parameter update with Adagrad for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update ``` I have read up on the [zip function](https://docs.python.org/3.3/library/functions.html#zip) and done some short tests to try to understand how this works. What I know so far, 5 Iterations, param == Wxh on the first iteration but not there on... Ideally I am trying to convert this code to C#, and to do that I need to understand it. In referring to [Python iterator and zip](https://stackoverflow.com/questions/38024554/python-iterator-and-zip) it appears as we are multiplying each item of each array: ``` param = Wxh * dWxh * mWxh ``` But then the variables `param` `dparam` and `mem` are being modified outside the zip function. How do these variables function in this for loop scenario?
2017/04/05
[ "https://Stackoverflow.com/questions/43223017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183804/" ]
Any sequence (or iterable) can be unpacked into variables using a simple assignment operation. The only requirement is that the number of variables and structure match the sequence. For example: ``` t = (2, 4) x, y = t ``` In this case zip() as per standard documentation is " zip() Make an iterator that aggregates elements from each of the iterables.Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. So, for your case ``` for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) lets say: iterable1 = [Wxh, Whh, Why, bh, by] iterable2 = [dWxh, dWhh, dWhy, dbh, dby] iterable3 = [mWxh, mWhh, mWhy, mbh, mby] here zip() returns [(Wxh, dWxh, mWxh), (Whh, dWhh, mWhh), (Why, dWhy, mWhy), (bh, dbh, mbh), (by, dby, mby)] on 1st iteration: param, dparam, mem = (Wxh, dWxh, mWxh) so, param = Wxh dparam = dWxh mem = mWxh mem = mem + (dparam * dparam) = mWxh + (dWxh * dWxh) param = param + (-learning_rate * dparam / np.sqrt(mem + 1e-8)) = Wxh + (-learning_rate * dWxh / np.sqrt(mWxh + (dWxh * dWxh) + 1e-8) on 2nd iteration: param, dparam, mem = (Whh, dWhh, mWhh) so, param = Whh dparam = dWhh mem = mWhh an so on. ```
Python treats the variables merely as *labels* or name tags. Since you have zipped those inside a `list` of lists, it doesn't matter where they are, as long as you address them by their name / label correctly. Kindly note, this may not work for immutable types like `int` or `str`, etc. Refer to this answer for more explanation - [Immutable vs Mutable types](https://stackoverflow.com/questions/8056130/immutable-vs-mutable-types).
43,223,017
I am attempting to understand the excellent Code given as a guide by Andrej Karpathy: <https://gist.github.com/karpathy/d4dee566867f8291f086> I am new to python, still learning! I am doing the best I can to understand the following code from the link: ``` # perform parameter update with Adagrad for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update ``` I have read up on the [zip function](https://docs.python.org/3.3/library/functions.html#zip) and done some short tests to try to understand how this works. What I know so far, 5 Iterations, param == Wxh on the first iteration but not there on... Ideally I am trying to convert this code to C#, and to do that I need to understand it. In referring to [Python iterator and zip](https://stackoverflow.com/questions/38024554/python-iterator-and-zip) it appears as we are multiplying each item of each array: ``` param = Wxh * dWxh * mWxh ``` But then the variables `param` `dparam` and `mem` are being modified outside the zip function. How do these variables function in this for loop scenario?
2017/04/05
[ "https://Stackoverflow.com/questions/43223017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183804/" ]
Any sequence (or iterable) can be unpacked into variables using a simple assignment operation. The only requirement is that the number of variables and structure match the sequence. For example: ``` t = (2, 4) x, y = t ``` In this case zip() as per standard documentation is " zip() Make an iterator that aggregates elements from each of the iterables.Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. So, for your case ``` for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) lets say: iterable1 = [Wxh, Whh, Why, bh, by] iterable2 = [dWxh, dWhh, dWhy, dbh, dby] iterable3 = [mWxh, mWhh, mWhy, mbh, mby] here zip() returns [(Wxh, dWxh, mWxh), (Whh, dWhh, mWhh), (Why, dWhy, mWhy), (bh, dbh, mbh), (by, dby, mby)] on 1st iteration: param, dparam, mem = (Wxh, dWxh, mWxh) so, param = Wxh dparam = dWxh mem = mWxh mem = mem + (dparam * dparam) = mWxh + (dWxh * dWxh) param = param + (-learning_rate * dparam / np.sqrt(mem + 1e-8)) = Wxh + (-learning_rate * dWxh / np.sqrt(mWxh + (dWxh * dWxh) + 1e-8) on 2nd iteration: param, dparam, mem = (Whh, dWhh, mWhh) so, param = Whh dparam = dWhh mem = mWhh an so on. ```
Write a simple for loop with zip will help you learn a lot. for example: ``` for a, b, c in zip([1,2,3], [4,5,6], [7,8,9]): print a print b print c print "/" ``` This function will print: 1 4 7 / 2 5 8 / 3 6 7 So that the zip function just put those three lists together, and then using three variables param, dparam, mem to refer to different list. In each iteration, those three variables refer to certain item in their corresponding lists, just like `for i in [1, 2, 3]:`. In this way, you only need to write one for loop instead of three, to update grads for each parameters: Wxh, Whh, Why, bh, by. In the first iteration, only Wxh is updated using dWxh and mWxh following the adagrad rule. And secondly, update Whh using dWhh and mWhh, and so on.
43,223,017
I am attempting to understand the excellent Code given as a guide by Andrej Karpathy: <https://gist.github.com/karpathy/d4dee566867f8291f086> I am new to python, still learning! I am doing the best I can to understand the following code from the link: ``` # perform parameter update with Adagrad for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update ``` I have read up on the [zip function](https://docs.python.org/3.3/library/functions.html#zip) and done some short tests to try to understand how this works. What I know so far, 5 Iterations, param == Wxh on the first iteration but not there on... Ideally I am trying to convert this code to C#, and to do that I need to understand it. In referring to [Python iterator and zip](https://stackoverflow.com/questions/38024554/python-iterator-and-zip) it appears as we are multiplying each item of each array: ``` param = Wxh * dWxh * mWxh ``` But then the variables `param` `dparam` and `mem` are being modified outside the zip function. How do these variables function in this for loop scenario?
2017/04/05
[ "https://Stackoverflow.com/questions/43223017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183804/" ]
Write a simple for loop with zip will help you learn a lot. for example: ``` for a, b, c in zip([1,2,3], [4,5,6], [7,8,9]): print a print b print c print "/" ``` This function will print: 1 4 7 / 2 5 8 / 3 6 7 So that the zip function just put those three lists together, and then using three variables param, dparam, mem to refer to different list. In each iteration, those three variables refer to certain item in their corresponding lists, just like `for i in [1, 2, 3]:`. In this way, you only need to write one for loop instead of three, to update grads for each parameters: Wxh, Whh, Why, bh, by. In the first iteration, only Wxh is updated using dWxh and mWxh following the adagrad rule. And secondly, update Whh using dWhh and mWhh, and so on.
Thank you all for excellent answers! My python skill is poor, so I am sorry for that! ``` import numpy as np print('----------------------------------------') print('Before modification:') a = np.random.randn(1, 3) * 1.0 print('a: ', a) b = np.random.randn(1, 3) * 1.0 print('b: ', b) c = np.random.randn(1, 3) * 1.0 print('c: ', c) print('----------------------------------------') for a1, b1, c1 in zip([a, b, c], [a, b, c], [a, b, c]): a1 += 10 * 0.01 b1 += 10 * 0.01 c1 += 10 * 0.01 print('a1 is Equal to a: ', np.array_equal(a1, a)) print('a1 is Equal to b: ', np.array_equal(a1, b)) print('a1 is Equal to c: ', np.array_equal(a1, c)) print('----------------------------------------') print('After modification:') print('a: ', a) print('b: ', b) print('c: ', c) print('----------------------------------------') ``` Outputs: ``` ---------------------------------------- Before modification: a: [[-0.79535459 -0.08678677 1.46957521]] b: [[-1.05908792 -0.90121069 1.07055281]] c: [[ 1.18976226 0.24700716 -0.08481322]] ---------------------------------------- a1 is Equal to a: True a1 is Equal to b: False a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: True a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: False a1 is Equal to c: True ---------------------------------------- After modification: a: [[-0.69535459 0.01321323 1.56957521]] b: [[-0.95908792 -0.80121069 1.17055281]] c: [[ 1.28976226 0.34700716 0.01518678]] ``` jyotish is exactly right, and answered what I was missing! Thank You! For C# I think I will look at a `Parallel.For` implementation here. EDIT: For others learning also, I also found it helpful to see this code work: ``` import numpy as np print('----------------------------------------') print('Before modification:') a = np.random.randn(1, 3) * 1.0 print('a: ', a) b = np.random.randn(1, 3) * 1.0 print('b: ', b) c = np.random.randn(1, 3) * 1.0 print('c: ', c) print('----------------------------------------') for a1, b1, c1 in zip([a, b, c], [a, b, c], [a, b, c]): a1[0][0] = 10 * 0.01 print('a1 is Equal to a: ', np.array_equal(a1, a)) print('a1 is Equal to b: ', np.array_equal(a1, b)) print('a1 is Equal to c: ', np.array_equal(a1, c)) print('----------------------------------------') print('After modification:') print('a: ', a) print('b: ', b) print('c: ', c) print('----------------------------------------') ``` Outputs: ``` ---------------------------------------- Before modification: a: [[-0.78734047 -0.04803815 0.20810081]] b: [[ 1.88121331 0.91649695 0.02482977]] c: [[-0.24219954 -0.10183608 0.85180522]] ---------------------------------------- a1 is Equal to a: True a1 is Equal to b: False a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: True a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: False a1 is Equal to c: True ---------------------------------------- After modification: a: [[ 0.1 -0.04803815 0.20810081]] b: [[ 0.1 0.91649695 0.02482977]] c: [[ 0.1 -0.10183608 0.85180522]] ---------------------------------------- ``` As you can see, only modifying the first column of the `<class 'numpy.ndarray'>` data type that I am using. Its a reasonably deep operation.
43,223,017
I am attempting to understand the excellent Code given as a guide by Andrej Karpathy: <https://gist.github.com/karpathy/d4dee566867f8291f086> I am new to python, still learning! I am doing the best I can to understand the following code from the link: ``` # perform parameter update with Adagrad for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update ``` I have read up on the [zip function](https://docs.python.org/3.3/library/functions.html#zip) and done some short tests to try to understand how this works. What I know so far, 5 Iterations, param == Wxh on the first iteration but not there on... Ideally I am trying to convert this code to C#, and to do that I need to understand it. In referring to [Python iterator and zip](https://stackoverflow.com/questions/38024554/python-iterator-and-zip) it appears as we are multiplying each item of each array: ``` param = Wxh * dWxh * mWxh ``` But then the variables `param` `dparam` and `mem` are being modified outside the zip function. How do these variables function in this for loop scenario?
2017/04/05
[ "https://Stackoverflow.com/questions/43223017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183804/" ]
Any sequence (or iterable) can be unpacked into variables using a simple assignment operation. The only requirement is that the number of variables and structure match the sequence. For example: ``` t = (2, 4) x, y = t ``` In this case zip() as per standard documentation is " zip() Make an iterator that aggregates elements from each of the iterables.Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. So, for your case ``` for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) lets say: iterable1 = [Wxh, Whh, Why, bh, by] iterable2 = [dWxh, dWhh, dWhy, dbh, dby] iterable3 = [mWxh, mWhh, mWhy, mbh, mby] here zip() returns [(Wxh, dWxh, mWxh), (Whh, dWhh, mWhh), (Why, dWhy, mWhy), (bh, dbh, mbh), (by, dby, mby)] on 1st iteration: param, dparam, mem = (Wxh, dWxh, mWxh) so, param = Wxh dparam = dWxh mem = mWxh mem = mem + (dparam * dparam) = mWxh + (dWxh * dWxh) param = param + (-learning_rate * dparam / np.sqrt(mem + 1e-8)) = Wxh + (-learning_rate * dWxh / np.sqrt(mWxh + (dWxh * dWxh) + 1e-8) on 2nd iteration: param, dparam, mem = (Whh, dWhh, mWhh) so, param = Whh dparam = dWhh mem = mWhh an so on. ```
What does `zip` do? Quoting from the official documentation: > > Zip returns a list of tuples, where the i-th tuple contains the i-th > element from each of the argument sequences or iterables. The returned > list is truncated in length to the length of the shortest argument > sequence. > > > It means, ``` >>> zip(["A", "B"], ["C", "D"], ["E", "F"]) [('A', 'C', 'E'), ('B', 'D', 'F')] ``` So now, when you are looping through, you actually have a list of tuples. With Content like. ``` # These are strings here but in your case these are objects [('Wxh', 'dWxh', 'mWxh'), ('Whh', 'dWhh', 'mWhh'), ('Why', 'dWhy', 'mWhy'), ('bh', 'dbh', 'mbh'),('by', 'dby', 'mby')] ``` > > What I know so far, 5 Iterations, param == Wxh on the first iteration > but not there on... > > > You are right, Now lets analyze your loop. ``` for param, dparam, mem in m: print(param, dparam, mem) # Which prints ('Wxh', 'dWxh', 'mWxh') ('Whh', 'dWhh', 'mWhh') ('Why', 'dWhy', 'mWhy') ('bh', 'dbh', 'mbh') ('by', 'dby', 'mby') ``` Which means, on every iteration, the `params` get the zeroth index tuple value, `dparam` get the first and `mem` gets the second. Now when I type `param` out of the scope of for loop, I get ``` >>> param 'by' ``` It means params still holds the reference to `by` object. From official documentation: > > The for-loop makes assignments to the variables(s) in the target > list. [...] Names in the target list are not deleted when the loop is > finished, but if the sequence is empty, they will not have been > assigned to at all by the loop. > > >
43,223,017
I am attempting to understand the excellent Code given as a guide by Andrej Karpathy: <https://gist.github.com/karpathy/d4dee566867f8291f086> I am new to python, still learning! I am doing the best I can to understand the following code from the link: ``` # perform parameter update with Adagrad for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update ``` I have read up on the [zip function](https://docs.python.org/3.3/library/functions.html#zip) and done some short tests to try to understand how this works. What I know so far, 5 Iterations, param == Wxh on the first iteration but not there on... Ideally I am trying to convert this code to C#, and to do that I need to understand it. In referring to [Python iterator and zip](https://stackoverflow.com/questions/38024554/python-iterator-and-zip) it appears as we are multiplying each item of each array: ``` param = Wxh * dWxh * mWxh ``` But then the variables `param` `dparam` and `mem` are being modified outside the zip function. How do these variables function in this for loop scenario?
2017/04/05
[ "https://Stackoverflow.com/questions/43223017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183804/" ]
What does `zip` do? Quoting from the official documentation: > > Zip returns a list of tuples, where the i-th tuple contains the i-th > element from each of the argument sequences or iterables. The returned > list is truncated in length to the length of the shortest argument > sequence. > > > It means, ``` >>> zip(["A", "B"], ["C", "D"], ["E", "F"]) [('A', 'C', 'E'), ('B', 'D', 'F')] ``` So now, when you are looping through, you actually have a list of tuples. With Content like. ``` # These are strings here but in your case these are objects [('Wxh', 'dWxh', 'mWxh'), ('Whh', 'dWhh', 'mWhh'), ('Why', 'dWhy', 'mWhy'), ('bh', 'dbh', 'mbh'),('by', 'dby', 'mby')] ``` > > What I know so far, 5 Iterations, param == Wxh on the first iteration > but not there on... > > > You are right, Now lets analyze your loop. ``` for param, dparam, mem in m: print(param, dparam, mem) # Which prints ('Wxh', 'dWxh', 'mWxh') ('Whh', 'dWhh', 'mWhh') ('Why', 'dWhy', 'mWhy') ('bh', 'dbh', 'mbh') ('by', 'dby', 'mby') ``` Which means, on every iteration, the `params` get the zeroth index tuple value, `dparam` get the first and `mem` gets the second. Now when I type `param` out of the scope of for loop, I get ``` >>> param 'by' ``` It means params still holds the reference to `by` object. From official documentation: > > The for-loop makes assignments to the variables(s) in the target > list. [...] Names in the target list are not deleted when the loop is > finished, but if the sequence is empty, they will not have been > assigned to at all by the loop. > > >
Thank you all for excellent answers! My python skill is poor, so I am sorry for that! ``` import numpy as np print('----------------------------------------') print('Before modification:') a = np.random.randn(1, 3) * 1.0 print('a: ', a) b = np.random.randn(1, 3) * 1.0 print('b: ', b) c = np.random.randn(1, 3) * 1.0 print('c: ', c) print('----------------------------------------') for a1, b1, c1 in zip([a, b, c], [a, b, c], [a, b, c]): a1 += 10 * 0.01 b1 += 10 * 0.01 c1 += 10 * 0.01 print('a1 is Equal to a: ', np.array_equal(a1, a)) print('a1 is Equal to b: ', np.array_equal(a1, b)) print('a1 is Equal to c: ', np.array_equal(a1, c)) print('----------------------------------------') print('After modification:') print('a: ', a) print('b: ', b) print('c: ', c) print('----------------------------------------') ``` Outputs: ``` ---------------------------------------- Before modification: a: [[-0.79535459 -0.08678677 1.46957521]] b: [[-1.05908792 -0.90121069 1.07055281]] c: [[ 1.18976226 0.24700716 -0.08481322]] ---------------------------------------- a1 is Equal to a: True a1 is Equal to b: False a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: True a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: False a1 is Equal to c: True ---------------------------------------- After modification: a: [[-0.69535459 0.01321323 1.56957521]] b: [[-0.95908792 -0.80121069 1.17055281]] c: [[ 1.28976226 0.34700716 0.01518678]] ``` jyotish is exactly right, and answered what I was missing! Thank You! For C# I think I will look at a `Parallel.For` implementation here. EDIT: For others learning also, I also found it helpful to see this code work: ``` import numpy as np print('----------------------------------------') print('Before modification:') a = np.random.randn(1, 3) * 1.0 print('a: ', a) b = np.random.randn(1, 3) * 1.0 print('b: ', b) c = np.random.randn(1, 3) * 1.0 print('c: ', c) print('----------------------------------------') for a1, b1, c1 in zip([a, b, c], [a, b, c], [a, b, c]): a1[0][0] = 10 * 0.01 print('a1 is Equal to a: ', np.array_equal(a1, a)) print('a1 is Equal to b: ', np.array_equal(a1, b)) print('a1 is Equal to c: ', np.array_equal(a1, c)) print('----------------------------------------') print('After modification:') print('a: ', a) print('b: ', b) print('c: ', c) print('----------------------------------------') ``` Outputs: ``` ---------------------------------------- Before modification: a: [[-0.78734047 -0.04803815 0.20810081]] b: [[ 1.88121331 0.91649695 0.02482977]] c: [[-0.24219954 -0.10183608 0.85180522]] ---------------------------------------- a1 is Equal to a: True a1 is Equal to b: False a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: True a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: False a1 is Equal to c: True ---------------------------------------- After modification: a: [[ 0.1 -0.04803815 0.20810081]] b: [[ 0.1 0.91649695 0.02482977]] c: [[ 0.1 -0.10183608 0.85180522]] ---------------------------------------- ``` As you can see, only modifying the first column of the `<class 'numpy.ndarray'>` data type that I am using. Its a reasonably deep operation.
43,223,017
I am attempting to understand the excellent Code given as a guide by Andrej Karpathy: <https://gist.github.com/karpathy/d4dee566867f8291f086> I am new to python, still learning! I am doing the best I can to understand the following code from the link: ``` # perform parameter update with Adagrad for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update ``` I have read up on the [zip function](https://docs.python.org/3.3/library/functions.html#zip) and done some short tests to try to understand how this works. What I know so far, 5 Iterations, param == Wxh on the first iteration but not there on... Ideally I am trying to convert this code to C#, and to do that I need to understand it. In referring to [Python iterator and zip](https://stackoverflow.com/questions/38024554/python-iterator-and-zip) it appears as we are multiplying each item of each array: ``` param = Wxh * dWxh * mWxh ``` But then the variables `param` `dparam` and `mem` are being modified outside the zip function. How do these variables function in this for loop scenario?
2017/04/05
[ "https://Stackoverflow.com/questions/43223017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183804/" ]
Any sequence (or iterable) can be unpacked into variables using a simple assignment operation. The only requirement is that the number of variables and structure match the sequence. For example: ``` t = (2, 4) x, y = t ``` In this case zip() as per standard documentation is " zip() Make an iterator that aggregates elements from each of the iterables.Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. So, for your case ``` for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]): mem += dparam * dparam param += -learning_rate * dparam / np.sqrt(mem + 1e-8) lets say: iterable1 = [Wxh, Whh, Why, bh, by] iterable2 = [dWxh, dWhh, dWhy, dbh, dby] iterable3 = [mWxh, mWhh, mWhy, mbh, mby] here zip() returns [(Wxh, dWxh, mWxh), (Whh, dWhh, mWhh), (Why, dWhy, mWhy), (bh, dbh, mbh), (by, dby, mby)] on 1st iteration: param, dparam, mem = (Wxh, dWxh, mWxh) so, param = Wxh dparam = dWxh mem = mWxh mem = mem + (dparam * dparam) = mWxh + (dWxh * dWxh) param = param + (-learning_rate * dparam / np.sqrt(mem + 1e-8)) = Wxh + (-learning_rate * dWxh / np.sqrt(mWxh + (dWxh * dWxh) + 1e-8) on 2nd iteration: param, dparam, mem = (Whh, dWhh, mWhh) so, param = Whh dparam = dWhh mem = mWhh an so on. ```
Thank you all for excellent answers! My python skill is poor, so I am sorry for that! ``` import numpy as np print('----------------------------------------') print('Before modification:') a = np.random.randn(1, 3) * 1.0 print('a: ', a) b = np.random.randn(1, 3) * 1.0 print('b: ', b) c = np.random.randn(1, 3) * 1.0 print('c: ', c) print('----------------------------------------') for a1, b1, c1 in zip([a, b, c], [a, b, c], [a, b, c]): a1 += 10 * 0.01 b1 += 10 * 0.01 c1 += 10 * 0.01 print('a1 is Equal to a: ', np.array_equal(a1, a)) print('a1 is Equal to b: ', np.array_equal(a1, b)) print('a1 is Equal to c: ', np.array_equal(a1, c)) print('----------------------------------------') print('After modification:') print('a: ', a) print('b: ', b) print('c: ', c) print('----------------------------------------') ``` Outputs: ``` ---------------------------------------- Before modification: a: [[-0.79535459 -0.08678677 1.46957521]] b: [[-1.05908792 -0.90121069 1.07055281]] c: [[ 1.18976226 0.24700716 -0.08481322]] ---------------------------------------- a1 is Equal to a: True a1 is Equal to b: False a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: True a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: False a1 is Equal to c: True ---------------------------------------- After modification: a: [[-0.69535459 0.01321323 1.56957521]] b: [[-0.95908792 -0.80121069 1.17055281]] c: [[ 1.28976226 0.34700716 0.01518678]] ``` jyotish is exactly right, and answered what I was missing! Thank You! For C# I think I will look at a `Parallel.For` implementation here. EDIT: For others learning also, I also found it helpful to see this code work: ``` import numpy as np print('----------------------------------------') print('Before modification:') a = np.random.randn(1, 3) * 1.0 print('a: ', a) b = np.random.randn(1, 3) * 1.0 print('b: ', b) c = np.random.randn(1, 3) * 1.0 print('c: ', c) print('----------------------------------------') for a1, b1, c1 in zip([a, b, c], [a, b, c], [a, b, c]): a1[0][0] = 10 * 0.01 print('a1 is Equal to a: ', np.array_equal(a1, a)) print('a1 is Equal to b: ', np.array_equal(a1, b)) print('a1 is Equal to c: ', np.array_equal(a1, c)) print('----------------------------------------') print('After modification:') print('a: ', a) print('b: ', b) print('c: ', c) print('----------------------------------------') ``` Outputs: ``` ---------------------------------------- Before modification: a: [[-0.78734047 -0.04803815 0.20810081]] b: [[ 1.88121331 0.91649695 0.02482977]] c: [[-0.24219954 -0.10183608 0.85180522]] ---------------------------------------- a1 is Equal to a: True a1 is Equal to b: False a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: True a1 is Equal to c: False ---------------------------------------- a1 is Equal to a: False a1 is Equal to b: False a1 is Equal to c: True ---------------------------------------- After modification: a: [[ 0.1 -0.04803815 0.20810081]] b: [[ 0.1 0.91649695 0.02482977]] c: [[ 0.1 -0.10183608 0.85180522]] ---------------------------------------- ``` As you can see, only modifying the first column of the `<class 'numpy.ndarray'>` data type that I am using. Its a reasonably deep operation.
73,425,359
I am running Ubuntu 22.04 with xorg. I need to find a way to compile microbit python code locally to a firmware hex file. Firstly, I followed the guide here <https://microbit-micropython.readthedocs.io/en/latest/devguide/flashfirmware.html>. After a lot of debugging, I got to this point: <https://pastebin.com/MGShD31N> However, the file platform.h does exist. ``` sawntoe@uwubuntu:~/Documents/Assignments/2022/TVP/micropython$ ls /home/sawntoe/Documents/Assignments/2022/TVP/micropython/yotta_modules/mbed-classic/api/platform.h /home/sawntoe/Documents/Assignments/2022/TVP/micropython/yotta_modules/mbed-classic/api/platform.h sawntoe@uwubuntu:~/Documents/Assignments/2022/TVP/micropython$ ``` At this point, I gave up on this and tried using Mu editor with the AppImage. However, Mu requires wayland, and I am on xorg. Does anyone have any idea if this is possible? Thanks.
2022/08/20
[ "https://Stackoverflow.com/questions/73425359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12625930/" ]
Mu and the uflash command are able to retrieve your Python code from .hex files. Using uflash you can do the following for example: ``` uflash my_script.py ``` I think that you want is somehow possible to do, but its harder than just using their web python editor: <https://python.microbit.org/v/2>
**Working Ubuntu 22.04 host CLI setup with Carlos Atencio's Docker to build your own firmware** After trying to setup the toolchain for a while, I finally decided to Google for a Docker image with the toolchain, and found <https://github.com/carlosperate/docker-microbit-toolchain> [at this commit](https://github.com/carlosperate/docker-microbit-toolchain/blob/ad2e52620d47f98c225647855432a854f65d9140/requirements.txt) from Carlos Atencio, a Micro:Bit foundation employee, and that just absolutely worked: ``` # Get examples. git clone https://github.com/bbcmicrobit/micropython cd micropython git checkout 7fc33d13b31a915cbe90dc5d515c6337b5fa1660 # Get Docker image. docker pull ghcr.io/carlosperate/microbit-toolchain:latest # Build setup to be run once. docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest yt target bbc-microbit-classic-gcc-nosd@https://github.com/lancaster-university/yotta-target-bbc-microbit-classic-gcc-nosd docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest make all # Build one example. docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest \ tools/makecombinedhex.py build/firmware.hex examples/counter.py -o build/counter.hex # Build all examples. docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest \ bash -c 'for f in examples/*; do b="$(basename "$f")"; echo $b; tools/makecombinedhex.py build/firmware.hex "$f" -o "build/${b%.py}.hex"; done' ``` And you can then flash the example you want to run with: ``` cp build/counter.hex "/media/$USER/MICROBIT/" ``` Some further comments at: [Generating micropython + python code `.hex` file from the command line for the BBC micro:bit](https://stackoverflow.com/questions/52691853/generating-micropython-python-code-hex-file-from-commandline/73877468#73877468)
73,425,359
I am running Ubuntu 22.04 with xorg. I need to find a way to compile microbit python code locally to a firmware hex file. Firstly, I followed the guide here <https://microbit-micropython.readthedocs.io/en/latest/devguide/flashfirmware.html>. After a lot of debugging, I got to this point: <https://pastebin.com/MGShD31N> However, the file platform.h does exist. ``` sawntoe@uwubuntu:~/Documents/Assignments/2022/TVP/micropython$ ls /home/sawntoe/Documents/Assignments/2022/TVP/micropython/yotta_modules/mbed-classic/api/platform.h /home/sawntoe/Documents/Assignments/2022/TVP/micropython/yotta_modules/mbed-classic/api/platform.h sawntoe@uwubuntu:~/Documents/Assignments/2022/TVP/micropython$ ``` At this point, I gave up on this and tried using Mu editor with the AppImage. However, Mu requires wayland, and I am on xorg. Does anyone have any idea if this is possible? Thanks.
2022/08/20
[ "https://Stackoverflow.com/questions/73425359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12625930/" ]
Okay, so elaborating on Peter Till's answer. Firstly, you can use uflash: ``` uflash path/to/your/code . ``` Or, you can use microfs: ``` ufs put path/to/main.py ```
**Working Ubuntu 22.04 host CLI setup with Carlos Atencio's Docker to build your own firmware** After trying to setup the toolchain for a while, I finally decided to Google for a Docker image with the toolchain, and found <https://github.com/carlosperate/docker-microbit-toolchain> [at this commit](https://github.com/carlosperate/docker-microbit-toolchain/blob/ad2e52620d47f98c225647855432a854f65d9140/requirements.txt) from Carlos Atencio, a Micro:Bit foundation employee, and that just absolutely worked: ``` # Get examples. git clone https://github.com/bbcmicrobit/micropython cd micropython git checkout 7fc33d13b31a915cbe90dc5d515c6337b5fa1660 # Get Docker image. docker pull ghcr.io/carlosperate/microbit-toolchain:latest # Build setup to be run once. docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest yt target bbc-microbit-classic-gcc-nosd@https://github.com/lancaster-university/yotta-target-bbc-microbit-classic-gcc-nosd docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest make all # Build one example. docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest \ tools/makecombinedhex.py build/firmware.hex examples/counter.py -o build/counter.hex # Build all examples. docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest \ bash -c 'for f in examples/*; do b="$(basename "$f")"; echo $b; tools/makecombinedhex.py build/firmware.hex "$f" -o "build/${b%.py}.hex"; done' ``` And you can then flash the example you want to run with: ``` cp build/counter.hex "/media/$USER/MICROBIT/" ``` Some further comments at: [Generating micropython + python code `.hex` file from the command line for the BBC micro:bit](https://stackoverflow.com/questions/52691853/generating-micropython-python-code-hex-file-from-commandline/73877468#73877468)
73,425,359
I am running Ubuntu 22.04 with xorg. I need to find a way to compile microbit python code locally to a firmware hex file. Firstly, I followed the guide here <https://microbit-micropython.readthedocs.io/en/latest/devguide/flashfirmware.html>. After a lot of debugging, I got to this point: <https://pastebin.com/MGShD31N> However, the file platform.h does exist. ``` sawntoe@uwubuntu:~/Documents/Assignments/2022/TVP/micropython$ ls /home/sawntoe/Documents/Assignments/2022/TVP/micropython/yotta_modules/mbed-classic/api/platform.h /home/sawntoe/Documents/Assignments/2022/TVP/micropython/yotta_modules/mbed-classic/api/platform.h sawntoe@uwubuntu:~/Documents/Assignments/2022/TVP/micropython$ ``` At this point, I gave up on this and tried using Mu editor with the AppImage. However, Mu requires wayland, and I am on xorg. Does anyone have any idea if this is possible? Thanks.
2022/08/20
[ "https://Stackoverflow.com/questions/73425359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12625930/" ]
Peter Till answers the original question. The additional below adds to this answer by showing how to automate the build and load process. I use Debian. The original question states that Ubuntu is used, which is built on Debian. A script to find and mount the micro:bit ======================================== When code is loaded to the micro:bit, the board is dismounted from the system. So each time you have new code to load, you have to remount the board. I modified a script to find and mount the micro:bit. ``` #!/bin/bash BASEPATH="/media/$(whoami)/" MICRO="MICROBIT" if [ $# -eq 0 ] then echo "no argument supplied, use 'mount' or 'unmount'" exit 1 fi if [ $1 == "--help" ] then echo "mounts or unmounts a BBC micro:bit" echo "args: mount - mount the microbit, unmout - unmount the microbit" fi # how many MICRO found in udiksctl dump RESULTS=$(udisksctl dump | grep IdLabel | grep -c -i $MICRO) case "$RESULTS" in 0 ) echo "no $MICRO found in 'udkisksctl dump'" exit 0 ;; 1 ) DEVICELABEL=$(udisksctl dump | grep IdLabel | grep -i $MICRO | cut -d ":" -f 2 | sed 's/^[ \t]*//') DEVICE=$(udisksctl dump | grep -i "IdLabel: \+$DEVICELABEL" -B 12 | grep " Device:" | cut -d ":" -f 2 | sed 's/^[ \t]*//') DEVICEPATH="$BASEPATH""$DEVICELABEL" echo "found one $MICRO, device: $DEVICE" if [[ -z $(mount | grep "$DEVICE") ]] then echo "$DEVICELABEL was unmounted" if [ $1 == "mount" ] then udisksctl mount -b "$DEVICE" exit 0 fi else echo "$DEVICELABEL was mounted" if [ $1 == "unmount" ] then udisksctl unmount -b "$DEVICE" exit 0 fi fi ;; * ) echo "more than one $MICRO found" ;; esac echo "exiting without doing anything" ``` I alias this script to **mm** in my .bashrc file. Automate mounting the micro:bit and flashing the python file ============================================================ I use the **inotifywait** command to run mm and to then run uflash to load the .py file I am working on. Each time that the python file is saved, the aliased command mm is run followed by the uflash command. ``` while inotifywait -e modify <your_file>.py ; do mm && uflash <your_file>.py ; done ```
**Working Ubuntu 22.04 host CLI setup with Carlos Atencio's Docker to build your own firmware** After trying to setup the toolchain for a while, I finally decided to Google for a Docker image with the toolchain, and found <https://github.com/carlosperate/docker-microbit-toolchain> [at this commit](https://github.com/carlosperate/docker-microbit-toolchain/blob/ad2e52620d47f98c225647855432a854f65d9140/requirements.txt) from Carlos Atencio, a Micro:Bit foundation employee, and that just absolutely worked: ``` # Get examples. git clone https://github.com/bbcmicrobit/micropython cd micropython git checkout 7fc33d13b31a915cbe90dc5d515c6337b5fa1660 # Get Docker image. docker pull ghcr.io/carlosperate/microbit-toolchain:latest # Build setup to be run once. docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest yt target bbc-microbit-classic-gcc-nosd@https://github.com/lancaster-university/yotta-target-bbc-microbit-classic-gcc-nosd docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest make all # Build one example. docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest \ tools/makecombinedhex.py build/firmware.hex examples/counter.py -o build/counter.hex # Build all examples. docker run -v $(pwd):/home --rm ghcr.io/carlosperate/microbit-toolchain:latest \ bash -c 'for f in examples/*; do b="$(basename "$f")"; echo $b; tools/makecombinedhex.py build/firmware.hex "$f" -o "build/${b%.py}.hex"; done' ``` And you can then flash the example you want to run with: ``` cp build/counter.hex "/media/$USER/MICROBIT/" ``` Some further comments at: [Generating micropython + python code `.hex` file from the command line for the BBC micro:bit](https://stackoverflow.com/questions/52691853/generating-micropython-python-code-hex-file-from-commandline/73877468#73877468)
9,725,737
> > **Possible Duplicate:** > > [Tool to convert python indentation from spaces to tabs?](https://stackoverflow.com/questions/338767/tool-to-convert-python-indentation-from-spaces-to-tabs) > > > I have a number of python files (>1000) that need to be reformatted so indentation is done only with tabs (yes, i know PEP-8, but this is a coding standard of a company). What is the easiest way to do so? Maybe some script in Python that will `os.walk` over files and do some magic? I can't just `grep` file content since file can be malformed (mixed tab and spaces, different amount of spaces) but Python will still run it and i get it back working after conversion.
2012/03/15
[ "https://Stackoverflow.com/questions/9725737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69882/" ]
I would suggest using this [Reindent](http://pypi.python.org/pypi/Reindent/0.1.0) script on PyPI to convert all of your horribly inconsistent files to a consistent PEP-8 (4-space indents) version. At this point try one more time to convince whoever decided on tabs that the company coding standard is stupid and PEP-8 style should be used, if this fails then you could use sed (as in hc\_'s answer) or create a Python script to replace 4 spaces with a single tab at the beginning of every line.
How about ``` find . -type f -iname \*.py -print0 | xargs -0 sed -i 's/^ /\t/' ``` This command finds all .py files below the current directory and replaces every four consecutive spaces it finds inside of them with a tab. Just noticed Spacedman's comment. This approach will not handle spaces at the beginning of a line inside a """ string correctly.
37,817,559
I've packaged a [this simple flask app](https://github.com/SimplyAhmazing/pyinstaller-tut) using PyInstaller but my OSX executable fails to run and shows the following executable, ``` Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found ``` My guess is that PyInstaller is not packaging Python with my app. Here's what I ran, ``` $ pyinstaller hello_flask.spec --onedir 83 INFO: PyInstaller: 3.2 83 INFO: Python: 3.4.3 87 INFO: Platform: Darwin-13.4.0-x86_64-i386-64bit 89 INFO: UPX is not available. 90 INFO: Extending PYTHONPATH with paths ['/Users/ahmed/Code/play/py-install-tut', '/Users/ahmed/Code/play/py-install-tut'] 90 INFO: checking Analysis 99 INFO: checking PYZ 104 INFO: checking PKG 105 INFO: Building because toc changed 105 INFO: Building PKG (CArchive) out00-PKG.pkg 144 INFO: Bootloader /opt/boxen/pyenv/versions/3.4.3/Python.framework/Versions/3.4/lib/python3.4/site-packages/PyInstaller/bootloader/Darwin-64bit/run_d 144 INFO: checking EXE 145 INFO: Building because toc changed 145 INFO: Building EXE from out00-EXE.toc 145 INFO: Appending archive to EXE /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 155 INFO: Fixing EXE for code signing /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 164 INFO: checking COLLECT WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/hello_flask" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 1591 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/hello_flask 1597 INFO: Building COLLECT out00-COLLECT.toc 2203 INFO: checking BUNDLE WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/myscript.app" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 3947 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/myscript.app 3948 INFO: Building BUNDLE out00-BUNDLE.toc 3972 INFO: moving BUNDLE data files to Resource directory ``` When I open the contents of the packaged app in OSX I get the following files, ``` myscript.app/Contents/MacOS/ _struct.cpython-34m.so hello_flask zlib.cpython-34m.so ``` When I double click the above `hello_flask` executable I get the following output in my terminal, ``` /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask ; exit; PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is NULL LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Extracting binaries LOADER: Executing self as child LOADER: set _MEIPASS2 to /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Already in the child - running user's code. LOADER: Python library: /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found LOADER: Back to parent (RC: 255) LOADER: Doing cleanup LOADER: Freeing archive status for /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask [Process completed] ``` I've also tried running this on a co-workers mac OSX and I get the same issue.
2016/06/14
[ "https://Stackoverflow.com/questions/37817559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/772401/" ]
The minimum deployment target with Xcode 8 is iOS 8. To support target the iOS SDK 7.x and below, use Xcode 7. If you try to use a deployment target of iOS 7.x or below, Xcode will suggest you change your target to iOS 8: [![Xcode Warning](https://i.stack.imgur.com/LGe5e.png)](https://i.stack.imgur.com/LGe5e.png)
Apple has changed so much since iOS 7 until now. The easiest way of not having to deal with backward compatibility is to make the old OS's obsolete. ~~So you have 2 choices. You can leave the setting as is and deal with the warning message,~~ or you can change the setting and not support iOS 7 or lower any longer. There are pros and cons to each... ~~Leave the setting: If you chose to leave the Min OS setting as is your app will have a larger user base. But since new OS adoption rate is very very high this is not as much of an issue with iOS devices as it would be with Android devices. You would also have to deal with supporting iOS 7. That means that if you decide to use any new features not available in iOS 7 you would have to deal with the iOS 7 case. Possible app crashes, inconsistent UI, etc...~~ Change the setting: If you chose to change the setting then you no longer have to support iOS 7 (you can create much simpler and more consistent code with new features). You also slightly shrink your customer base (very very slightly). It's up to you what you would like to do, but really all devices that can run 7 can also run 8. So if they want your app they can just upgrade OS's and be fine (not like the iPad 1 that stopped at iOS 5). My customers are all large businesses that need to run through lots of red tape to upgrade their fleet of devices. So I have to support iOS 7 (for now, xCode 8 may give me the sway to force those who haven't to upgrade).
37,817,559
I've packaged a [this simple flask app](https://github.com/SimplyAhmazing/pyinstaller-tut) using PyInstaller but my OSX executable fails to run and shows the following executable, ``` Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found ``` My guess is that PyInstaller is not packaging Python with my app. Here's what I ran, ``` $ pyinstaller hello_flask.spec --onedir 83 INFO: PyInstaller: 3.2 83 INFO: Python: 3.4.3 87 INFO: Platform: Darwin-13.4.0-x86_64-i386-64bit 89 INFO: UPX is not available. 90 INFO: Extending PYTHONPATH with paths ['/Users/ahmed/Code/play/py-install-tut', '/Users/ahmed/Code/play/py-install-tut'] 90 INFO: checking Analysis 99 INFO: checking PYZ 104 INFO: checking PKG 105 INFO: Building because toc changed 105 INFO: Building PKG (CArchive) out00-PKG.pkg 144 INFO: Bootloader /opt/boxen/pyenv/versions/3.4.3/Python.framework/Versions/3.4/lib/python3.4/site-packages/PyInstaller/bootloader/Darwin-64bit/run_d 144 INFO: checking EXE 145 INFO: Building because toc changed 145 INFO: Building EXE from out00-EXE.toc 145 INFO: Appending archive to EXE /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 155 INFO: Fixing EXE for code signing /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 164 INFO: checking COLLECT WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/hello_flask" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 1591 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/hello_flask 1597 INFO: Building COLLECT out00-COLLECT.toc 2203 INFO: checking BUNDLE WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/myscript.app" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 3947 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/myscript.app 3948 INFO: Building BUNDLE out00-BUNDLE.toc 3972 INFO: moving BUNDLE data files to Resource directory ``` When I open the contents of the packaged app in OSX I get the following files, ``` myscript.app/Contents/MacOS/ _struct.cpython-34m.so hello_flask zlib.cpython-34m.so ``` When I double click the above `hello_flask` executable I get the following output in my terminal, ``` /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask ; exit; PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is NULL LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Extracting binaries LOADER: Executing self as child LOADER: set _MEIPASS2 to /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Already in the child - running user's code. LOADER: Python library: /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found LOADER: Back to parent (RC: 255) LOADER: Doing cleanup LOADER: Freeing archive status for /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask [Process completed] ``` I've also tried running this on a co-workers mac OSX and I get the same issue.
2016/06/14
[ "https://Stackoverflow.com/questions/37817559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/772401/" ]
I think if the app has many users who are using iOS 7, it would be necessary to adjust project to support iOS 7. I have tried build, debug, archive with deployment target 7.0 using Xcode 8 Beta(8S128d). All succeeded. Also successfully export and install the ipa on my iPhone 4 (iOS 7.1.2(11D257)) . I did the followings to change my project deployment target to 7.0 and remove the suggestion warning. 1. Manually input "7.0" in the "iOS Deployment Target" text box. [![Manually change iOS deployment target](https://i.stack.imgur.com/X3vsr.png)](https://i.stack.imgur.com/X3vsr.png) 2. Uncheck the "Update iOS Deployment Target" and press "Perform Changes" / "Done" button, then the recommended suggestion warning will disappear. [![Recommended Suggestion](https://i.stack.imgur.com/oWKtl.png)](https://i.stack.imgur.com/oWKtl.png) **Edit**: ### Make Xcode 8.x debug your apps on iOS 7.x devices. 1. You need **Xcode 7.x** . You can download it from [Apple Developer Site](https://developer.apple.com/download/more/). 2. **Open** Finder, and **go** to "**Xcode 7.x**.app/Contents/Developer/Platforms/iPhoneOS.platform/**DeviceSupport**/". 3. **Copy** "**7.0**" and "**7.1**" folders and **paste** them to "**Xcode 8.x**.app/Contents/Developer/Platforms/iPhoneOS.platform/**DeviceSupport**/". [![enter image description here](https://i.stack.imgur.com/eYwWn.png)](https://i.stack.imgur.com/eYwWn.png) 4. **Open** "**Xcode 8.x**.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/**SDKSettings.plist**" [![enter image description here](https://i.stack.imgur.com/wPr8N.png)](https://i.stack.imgur.com/wPr8N.png) 5. **Add** values, "**7.0**" and "**7.1**", to key, "Root/DefaultProperties/**DEPLOYMENT\_TARGET\_SUGGESTED\_VALUES**", according to the following screenshot. [![enter image description here](https://i.stack.imgur.com/BVslF.png)](https://i.stack.imgur.com/BVslF.png) 6. **Restart Xcode 8.x**. 7. Now you can choose "**7.0**" or "**7.1**" in the "**iOS Deployment Target**" text box list and debug your apps on iOS 7.x devices.
The minimum deployment target with Xcode 8 is iOS 8. To support target the iOS SDK 7.x and below, use Xcode 7. If you try to use a deployment target of iOS 7.x or below, Xcode will suggest you change your target to iOS 8: [![Xcode Warning](https://i.stack.imgur.com/LGe5e.png)](https://i.stack.imgur.com/LGe5e.png)
37,817,559
I've packaged a [this simple flask app](https://github.com/SimplyAhmazing/pyinstaller-tut) using PyInstaller but my OSX executable fails to run and shows the following executable, ``` Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found ``` My guess is that PyInstaller is not packaging Python with my app. Here's what I ran, ``` $ pyinstaller hello_flask.spec --onedir 83 INFO: PyInstaller: 3.2 83 INFO: Python: 3.4.3 87 INFO: Platform: Darwin-13.4.0-x86_64-i386-64bit 89 INFO: UPX is not available. 90 INFO: Extending PYTHONPATH with paths ['/Users/ahmed/Code/play/py-install-tut', '/Users/ahmed/Code/play/py-install-tut'] 90 INFO: checking Analysis 99 INFO: checking PYZ 104 INFO: checking PKG 105 INFO: Building because toc changed 105 INFO: Building PKG (CArchive) out00-PKG.pkg 144 INFO: Bootloader /opt/boxen/pyenv/versions/3.4.3/Python.framework/Versions/3.4/lib/python3.4/site-packages/PyInstaller/bootloader/Darwin-64bit/run_d 144 INFO: checking EXE 145 INFO: Building because toc changed 145 INFO: Building EXE from out00-EXE.toc 145 INFO: Appending archive to EXE /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 155 INFO: Fixing EXE for code signing /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 164 INFO: checking COLLECT WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/hello_flask" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 1591 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/hello_flask 1597 INFO: Building COLLECT out00-COLLECT.toc 2203 INFO: checking BUNDLE WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/myscript.app" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 3947 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/myscript.app 3948 INFO: Building BUNDLE out00-BUNDLE.toc 3972 INFO: moving BUNDLE data files to Resource directory ``` When I open the contents of the packaged app in OSX I get the following files, ``` myscript.app/Contents/MacOS/ _struct.cpython-34m.so hello_flask zlib.cpython-34m.so ``` When I double click the above `hello_flask` executable I get the following output in my terminal, ``` /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask ; exit; PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is NULL LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Extracting binaries LOADER: Executing self as child LOADER: set _MEIPASS2 to /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Already in the child - running user's code. LOADER: Python library: /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found LOADER: Back to parent (RC: 255) LOADER: Doing cleanup LOADER: Freeing archive status for /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask [Process completed] ``` I've also tried running this on a co-workers mac OSX and I get the same issue.
2016/06/14
[ "https://Stackoverflow.com/questions/37817559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/772401/" ]
The minimum deployment target with Xcode 8 is iOS 8. To support target the iOS SDK 7.x and below, use Xcode 7. If you try to use a deployment target of iOS 7.x or below, Xcode will suggest you change your target to iOS 8: [![Xcode Warning](https://i.stack.imgur.com/LGe5e.png)](https://i.stack.imgur.com/LGe5e.png)
If you don't want to fiddle with XCode just update your project file for iOS 6 or 7. Right click .xcodeproj choose "Show package contents" and edit project.pbxproj in favorite text editor. Search for IPHONEOS\_DEPLOYMENT\_TARGET = 7.0;
37,817,559
I've packaged a [this simple flask app](https://github.com/SimplyAhmazing/pyinstaller-tut) using PyInstaller but my OSX executable fails to run and shows the following executable, ``` Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found ``` My guess is that PyInstaller is not packaging Python with my app. Here's what I ran, ``` $ pyinstaller hello_flask.spec --onedir 83 INFO: PyInstaller: 3.2 83 INFO: Python: 3.4.3 87 INFO: Platform: Darwin-13.4.0-x86_64-i386-64bit 89 INFO: UPX is not available. 90 INFO: Extending PYTHONPATH with paths ['/Users/ahmed/Code/play/py-install-tut', '/Users/ahmed/Code/play/py-install-tut'] 90 INFO: checking Analysis 99 INFO: checking PYZ 104 INFO: checking PKG 105 INFO: Building because toc changed 105 INFO: Building PKG (CArchive) out00-PKG.pkg 144 INFO: Bootloader /opt/boxen/pyenv/versions/3.4.3/Python.framework/Versions/3.4/lib/python3.4/site-packages/PyInstaller/bootloader/Darwin-64bit/run_d 144 INFO: checking EXE 145 INFO: Building because toc changed 145 INFO: Building EXE from out00-EXE.toc 145 INFO: Appending archive to EXE /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 155 INFO: Fixing EXE for code signing /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 164 INFO: checking COLLECT WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/hello_flask" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 1591 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/hello_flask 1597 INFO: Building COLLECT out00-COLLECT.toc 2203 INFO: checking BUNDLE WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/myscript.app" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 3947 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/myscript.app 3948 INFO: Building BUNDLE out00-BUNDLE.toc 3972 INFO: moving BUNDLE data files to Resource directory ``` When I open the contents of the packaged app in OSX I get the following files, ``` myscript.app/Contents/MacOS/ _struct.cpython-34m.so hello_flask zlib.cpython-34m.so ``` When I double click the above `hello_flask` executable I get the following output in my terminal, ``` /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask ; exit; PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is NULL LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Extracting binaries LOADER: Executing self as child LOADER: set _MEIPASS2 to /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Already in the child - running user's code. LOADER: Python library: /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found LOADER: Back to parent (RC: 255) LOADER: Doing cleanup LOADER: Freeing archive status for /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask [Process completed] ``` I've also tried running this on a co-workers mac OSX and I get the same issue.
2016/06/14
[ "https://Stackoverflow.com/questions/37817559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/772401/" ]
I think if the app has many users who are using iOS 7, it would be necessary to adjust project to support iOS 7. I have tried build, debug, archive with deployment target 7.0 using Xcode 8 Beta(8S128d). All succeeded. Also successfully export and install the ipa on my iPhone 4 (iOS 7.1.2(11D257)) . I did the followings to change my project deployment target to 7.0 and remove the suggestion warning. 1. Manually input "7.0" in the "iOS Deployment Target" text box. [![Manually change iOS deployment target](https://i.stack.imgur.com/X3vsr.png)](https://i.stack.imgur.com/X3vsr.png) 2. Uncheck the "Update iOS Deployment Target" and press "Perform Changes" / "Done" button, then the recommended suggestion warning will disappear. [![Recommended Suggestion](https://i.stack.imgur.com/oWKtl.png)](https://i.stack.imgur.com/oWKtl.png) **Edit**: ### Make Xcode 8.x debug your apps on iOS 7.x devices. 1. You need **Xcode 7.x** . You can download it from [Apple Developer Site](https://developer.apple.com/download/more/). 2. **Open** Finder, and **go** to "**Xcode 7.x**.app/Contents/Developer/Platforms/iPhoneOS.platform/**DeviceSupport**/". 3. **Copy** "**7.0**" and "**7.1**" folders and **paste** them to "**Xcode 8.x**.app/Contents/Developer/Platforms/iPhoneOS.platform/**DeviceSupport**/". [![enter image description here](https://i.stack.imgur.com/eYwWn.png)](https://i.stack.imgur.com/eYwWn.png) 4. **Open** "**Xcode 8.x**.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/**SDKSettings.plist**" [![enter image description here](https://i.stack.imgur.com/wPr8N.png)](https://i.stack.imgur.com/wPr8N.png) 5. **Add** values, "**7.0**" and "**7.1**", to key, "Root/DefaultProperties/**DEPLOYMENT\_TARGET\_SUGGESTED\_VALUES**", according to the following screenshot. [![enter image description here](https://i.stack.imgur.com/BVslF.png)](https://i.stack.imgur.com/BVslF.png) 6. **Restart Xcode 8.x**. 7. Now you can choose "**7.0**" or "**7.1**" in the "**iOS Deployment Target**" text box list and debug your apps on iOS 7.x devices.
Apple has changed so much since iOS 7 until now. The easiest way of not having to deal with backward compatibility is to make the old OS's obsolete. ~~So you have 2 choices. You can leave the setting as is and deal with the warning message,~~ or you can change the setting and not support iOS 7 or lower any longer. There are pros and cons to each... ~~Leave the setting: If you chose to leave the Min OS setting as is your app will have a larger user base. But since new OS adoption rate is very very high this is not as much of an issue with iOS devices as it would be with Android devices. You would also have to deal with supporting iOS 7. That means that if you decide to use any new features not available in iOS 7 you would have to deal with the iOS 7 case. Possible app crashes, inconsistent UI, etc...~~ Change the setting: If you chose to change the setting then you no longer have to support iOS 7 (you can create much simpler and more consistent code with new features). You also slightly shrink your customer base (very very slightly). It's up to you what you would like to do, but really all devices that can run 7 can also run 8. So if they want your app they can just upgrade OS's and be fine (not like the iPad 1 that stopped at iOS 5). My customers are all large businesses that need to run through lots of red tape to upgrade their fleet of devices. So I have to support iOS 7 (for now, xCode 8 may give me the sway to force those who haven't to upgrade).
37,817,559
I've packaged a [this simple flask app](https://github.com/SimplyAhmazing/pyinstaller-tut) using PyInstaller but my OSX executable fails to run and shows the following executable, ``` Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found ``` My guess is that PyInstaller is not packaging Python with my app. Here's what I ran, ``` $ pyinstaller hello_flask.spec --onedir 83 INFO: PyInstaller: 3.2 83 INFO: Python: 3.4.3 87 INFO: Platform: Darwin-13.4.0-x86_64-i386-64bit 89 INFO: UPX is not available. 90 INFO: Extending PYTHONPATH with paths ['/Users/ahmed/Code/play/py-install-tut', '/Users/ahmed/Code/play/py-install-tut'] 90 INFO: checking Analysis 99 INFO: checking PYZ 104 INFO: checking PKG 105 INFO: Building because toc changed 105 INFO: Building PKG (CArchive) out00-PKG.pkg 144 INFO: Bootloader /opt/boxen/pyenv/versions/3.4.3/Python.framework/Versions/3.4/lib/python3.4/site-packages/PyInstaller/bootloader/Darwin-64bit/run_d 144 INFO: checking EXE 145 INFO: Building because toc changed 145 INFO: Building EXE from out00-EXE.toc 145 INFO: Appending archive to EXE /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 155 INFO: Fixing EXE for code signing /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 164 INFO: checking COLLECT WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/hello_flask" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 1591 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/hello_flask 1597 INFO: Building COLLECT out00-COLLECT.toc 2203 INFO: checking BUNDLE WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/myscript.app" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 3947 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/myscript.app 3948 INFO: Building BUNDLE out00-BUNDLE.toc 3972 INFO: moving BUNDLE data files to Resource directory ``` When I open the contents of the packaged app in OSX I get the following files, ``` myscript.app/Contents/MacOS/ _struct.cpython-34m.so hello_flask zlib.cpython-34m.so ``` When I double click the above `hello_flask` executable I get the following output in my terminal, ``` /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask ; exit; PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is NULL LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Extracting binaries LOADER: Executing self as child LOADER: set _MEIPASS2 to /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Already in the child - running user's code. LOADER: Python library: /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found LOADER: Back to parent (RC: 255) LOADER: Doing cleanup LOADER: Freeing archive status for /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask [Process completed] ``` I've also tried running this on a co-workers mac OSX and I get the same issue.
2016/06/14
[ "https://Stackoverflow.com/questions/37817559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/772401/" ]
Apple has changed so much since iOS 7 until now. The easiest way of not having to deal with backward compatibility is to make the old OS's obsolete. ~~So you have 2 choices. You can leave the setting as is and deal with the warning message,~~ or you can change the setting and not support iOS 7 or lower any longer. There are pros and cons to each... ~~Leave the setting: If you chose to leave the Min OS setting as is your app will have a larger user base. But since new OS adoption rate is very very high this is not as much of an issue with iOS devices as it would be with Android devices. You would also have to deal with supporting iOS 7. That means that if you decide to use any new features not available in iOS 7 you would have to deal with the iOS 7 case. Possible app crashes, inconsistent UI, etc...~~ Change the setting: If you chose to change the setting then you no longer have to support iOS 7 (you can create much simpler and more consistent code with new features). You also slightly shrink your customer base (very very slightly). It's up to you what you would like to do, but really all devices that can run 7 can also run 8. So if they want your app they can just upgrade OS's and be fine (not like the iPad 1 that stopped at iOS 5). My customers are all large businesses that need to run through lots of red tape to upgrade their fleet of devices. So I have to support iOS 7 (for now, xCode 8 may give me the sway to force those who haven't to upgrade).
If you don't want to fiddle with XCode just update your project file for iOS 6 or 7. Right click .xcodeproj choose "Show package contents" and edit project.pbxproj in favorite text editor. Search for IPHONEOS\_DEPLOYMENT\_TARGET = 7.0;
37,817,559
I've packaged a [this simple flask app](https://github.com/SimplyAhmazing/pyinstaller-tut) using PyInstaller but my OSX executable fails to run and shows the following executable, ``` Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found ``` My guess is that PyInstaller is not packaging Python with my app. Here's what I ran, ``` $ pyinstaller hello_flask.spec --onedir 83 INFO: PyInstaller: 3.2 83 INFO: Python: 3.4.3 87 INFO: Platform: Darwin-13.4.0-x86_64-i386-64bit 89 INFO: UPX is not available. 90 INFO: Extending PYTHONPATH with paths ['/Users/ahmed/Code/play/py-install-tut', '/Users/ahmed/Code/play/py-install-tut'] 90 INFO: checking Analysis 99 INFO: checking PYZ 104 INFO: checking PKG 105 INFO: Building because toc changed 105 INFO: Building PKG (CArchive) out00-PKG.pkg 144 INFO: Bootloader /opt/boxen/pyenv/versions/3.4.3/Python.framework/Versions/3.4/lib/python3.4/site-packages/PyInstaller/bootloader/Darwin-64bit/run_d 144 INFO: checking EXE 145 INFO: Building because toc changed 145 INFO: Building EXE from out00-EXE.toc 145 INFO: Appending archive to EXE /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 155 INFO: Fixing EXE for code signing /Users/ahmed/Code/play/py-install-tut/build/hello_flask/hello_flask 164 INFO: checking COLLECT WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/hello_flask" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 1591 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/hello_flask 1597 INFO: Building COLLECT out00-COLLECT.toc 2203 INFO: checking BUNDLE WARNING: The output directory "/Users/ahmed/Code/play/py-install-tut/dist/myscript.app" and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)y 3947 INFO: Removing dir /Users/ahmed/Code/play/py-install-tut/dist/myscript.app 3948 INFO: Building BUNDLE out00-BUNDLE.toc 3972 INFO: moving BUNDLE data files to Resource directory ``` When I open the contents of the packaged app in OSX I get the following files, ``` myscript.app/Contents/MacOS/ _struct.cpython-34m.so hello_flask zlib.cpython-34m.so ``` When I double click the above `hello_flask` executable I get the following output in my terminal, ``` /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask ; exit; PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is NULL LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Extracting binaries LOADER: Executing self as child LOADER: set _MEIPASS2 to /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS PyInstaller Bootloader 3.x LOADER: executable is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: homepath is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: _MEIPASS2 is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS LOADER: archivename is /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask LOADER: Already in the child - running user's code. LOADER: Python library: /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python, 10): image not found LOADER: Back to parent (RC: 255) LOADER: Doing cleanup LOADER: Freeing archive status for /Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/hello_flask [Process completed] ``` I've also tried running this on a co-workers mac OSX and I get the same issue.
2016/06/14
[ "https://Stackoverflow.com/questions/37817559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/772401/" ]
I think if the app has many users who are using iOS 7, it would be necessary to adjust project to support iOS 7. I have tried build, debug, archive with deployment target 7.0 using Xcode 8 Beta(8S128d). All succeeded. Also successfully export and install the ipa on my iPhone 4 (iOS 7.1.2(11D257)) . I did the followings to change my project deployment target to 7.0 and remove the suggestion warning. 1. Manually input "7.0" in the "iOS Deployment Target" text box. [![Manually change iOS deployment target](https://i.stack.imgur.com/X3vsr.png)](https://i.stack.imgur.com/X3vsr.png) 2. Uncheck the "Update iOS Deployment Target" and press "Perform Changes" / "Done" button, then the recommended suggestion warning will disappear. [![Recommended Suggestion](https://i.stack.imgur.com/oWKtl.png)](https://i.stack.imgur.com/oWKtl.png) **Edit**: ### Make Xcode 8.x debug your apps on iOS 7.x devices. 1. You need **Xcode 7.x** . You can download it from [Apple Developer Site](https://developer.apple.com/download/more/). 2. **Open** Finder, and **go** to "**Xcode 7.x**.app/Contents/Developer/Platforms/iPhoneOS.platform/**DeviceSupport**/". 3. **Copy** "**7.0**" and "**7.1**" folders and **paste** them to "**Xcode 8.x**.app/Contents/Developer/Platforms/iPhoneOS.platform/**DeviceSupport**/". [![enter image description here](https://i.stack.imgur.com/eYwWn.png)](https://i.stack.imgur.com/eYwWn.png) 4. **Open** "**Xcode 8.x**.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/**SDKSettings.plist**" [![enter image description here](https://i.stack.imgur.com/wPr8N.png)](https://i.stack.imgur.com/wPr8N.png) 5. **Add** values, "**7.0**" and "**7.1**", to key, "Root/DefaultProperties/**DEPLOYMENT\_TARGET\_SUGGESTED\_VALUES**", according to the following screenshot. [![enter image description here](https://i.stack.imgur.com/BVslF.png)](https://i.stack.imgur.com/BVslF.png) 6. **Restart Xcode 8.x**. 7. Now you can choose "**7.0**" or "**7.1**" in the "**iOS Deployment Target**" text box list and debug your apps on iOS 7.x devices.
If you don't want to fiddle with XCode just update your project file for iOS 6 or 7. Right click .xcodeproj choose "Show package contents" and edit project.pbxproj in favorite text editor. Search for IPHONEOS\_DEPLOYMENT\_TARGET = 7.0;
67,117,219
i am new to coding and python and i was wondering how to create a regex that will match all ip addresses that start with 192.168.1.xxx I have been looking online and have not yet been able to find a match. Here is some some sample data that i am trying to match them from. ``` /index.html HTTP/1.1" 404 208 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET / HTTP/1.1" 403 4897 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Light/OpenSans-Light.woff HTTP/1.1" 404 241 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Bold/OpenSans-Bold.woff HTTP/1.1" 404 239 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Light/OpenSans-Light.ttf HTTP/1.1" 404 240 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Bold/OpenSans-Bold.ttf HTTP/1.1" 404 238 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:53 -0400] "GET /first HTTP/1.1" 404 203 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "GET /HNAP1/ HTTP/1.1" 404 204 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "GET / HTTP/1.1" 403 4897 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "POST /JNAP/ HTTP/1.1" 404 203 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "POST /JNAP/ HTTP/1.1" 404 203 "-" "-" ```
2021/04/15
[ "https://Stackoverflow.com/questions/67117219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12920080/" ]
Here you go. Also, checkout <https://regexr.com/> `^192\.168\.1\.[0-9]{1,3}$`
I think here its best to use a combination of `regex` to grab any valid IP address from your data, row by row. Then use `ipaddress` to check if the address sits within the network you're looking for. This will provide much more flexibility in the case you need to check different networks, instead of rewriting the `regex` every single time, you can create an `ip_network` object instead. We could also create multiple networks, and check for existence in all of them. ``` import ipaddress import re data = '''/index.html HTTP/1.1" 404 208 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET / HTTP/1.1" 403 4897 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Light/OpenSans-Light.woff HTTP/1.1" 404 241 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Bold/OpenSans-Bold.woff HTTP/1.1" 404 239 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Light/OpenSans-Light.ttf HTTP/1.1" 404 240 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Bold/OpenSans-Bold.ttf HTTP/1.1" 404 238 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:53 -0400] "GET /first HTTP/1.1" 404 203 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "GET /HNAP1/ HTTP/1.1" 404 204 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "GET / HTTP/1.1" 403 4897 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "POST /JNAP/ HTTP/1.1" 404 203 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "POST /JNAP/ HTTP/1.1" 404 203 "-" "-"''' network = ipaddress.ip_network('192.168.1.0/24') # Pattern that matches any valid ipv4 address pattern = r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' for row in data.split(): if (ip := re.search(pattern, row)): if ipaddress.IPv4Address(ip.group()) in network: print(f'{ip.group()} exists in {network}') ``` --- Output ``` 192.168.1.142 exists in 192.168.1.0/24 192.168.1.142 exists in 192.168.1.0/24 192.168.1.142 exists in 192.168.1.0/24 192.168.1.142 exists in 192.168.1.0/24 192.168.1.142 exists in 192.168.1.0/24 192.168.1.142 exists in 192.168.1.0/24 192.168.1.1 exists in 192.168.1.0/24 192.168.1.1 exists in 192.168.1.0/24 192.168.1.1 exists in 192.168.1.0/24 192.168.1.1 exists in 192.168.1.0/24 ```
67,117,219
i am new to coding and python and i was wondering how to create a regex that will match all ip addresses that start with 192.168.1.xxx I have been looking online and have not yet been able to find a match. Here is some some sample data that i am trying to match them from. ``` /index.html HTTP/1.1" 404 208 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET / HTTP/1.1" 403 4897 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Light/OpenSans-Light.woff HTTP/1.1" 404 241 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Bold/OpenSans-Bold.woff HTTP/1.1" 404 239 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Light/OpenSans-Light.ttf HTTP/1.1" 404 240 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Bold/OpenSans-Bold.ttf HTTP/1.1" 404 238 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:53 -0400] "GET /first HTTP/1.1" 404 203 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "GET /HNAP1/ HTTP/1.1" 404 204 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "GET / HTTP/1.1" 403 4897 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "POST /JNAP/ HTTP/1.1" 404 203 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "POST /JNAP/ HTTP/1.1" 404 203 "-" "-" ```
2021/04/15
[ "https://Stackoverflow.com/questions/67117219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12920080/" ]
If you really only want to match '192.168.1.xxx', then you can use this regex to use this in python specifically: "192\.168\.1\.[0-9]{1,3}". I personally recommend using [regexr](https://regexr.com/) to get more familiar with regex. You can enter your data and on the left you can look at a cheatsheet to help you learn.
I think here its best to use a combination of `regex` to grab any valid IP address from your data, row by row. Then use `ipaddress` to check if the address sits within the network you're looking for. This will provide much more flexibility in the case you need to check different networks, instead of rewriting the `regex` every single time, you can create an `ip_network` object instead. We could also create multiple networks, and check for existence in all of them. ``` import ipaddress import re data = '''/index.html HTTP/1.1" 404 208 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET / HTTP/1.1" 403 4897 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Light/OpenSans-Light.woff HTTP/1.1" 404 241 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Bold/OpenSans-Bold.woff HTTP/1.1" 404 239 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Light/OpenSans-Light.ttf HTTP/1.1" 404 240 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:43 -0400] "GET /noindex/css/fonts/Bold/OpenSans-Bold.ttf HTTP/1.1" 404 238 "http://optiplex360/noindex/css/open-sans.css" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.142 - - [30/Sep/2016:16:18:53 -0400] "GET /first HTTP/1.1" 404 203 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "GET /HNAP1/ HTTP/1.1" 404 204 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "GET / HTTP/1.1" 403 4897 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "POST /JNAP/ HTTP/1.1" 404 203 "-" "-" 192.168.1.1 - - [30/Sep/2016:16:19:00 -0400] "POST /JNAP/ HTTP/1.1" 404 203 "-" "-"''' network = ipaddress.ip_network('192.168.1.0/24') # Pattern that matches any valid ipv4 address pattern = r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' for row in data.split(): if (ip := re.search(pattern, row)): if ipaddress.IPv4Address(ip.group()) in network: print(f'{ip.group()} exists in {network}') ``` --- Output ``` 192.168.1.142 exists in 192.168.1.0/24 192.168.1.142 exists in 192.168.1.0/24 192.168.1.142 exists in 192.168.1.0/24 192.168.1.142 exists in 192.168.1.0/24 192.168.1.142 exists in 192.168.1.0/24 192.168.1.142 exists in 192.168.1.0/24 192.168.1.1 exists in 192.168.1.0/24 192.168.1.1 exists in 192.168.1.0/24 192.168.1.1 exists in 192.168.1.0/24 192.168.1.1 exists in 192.168.1.0/24 ```
16,024,041
I'm having issues sending unicode to SQL Server via pymssql: ``` In [1]: import pymssql conn = pymssql.connect(host='hostname', user='me', password='password', database='db') cursor = conn.cursor() In [2]: s = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' In [3]: s Out [3]: u'Monsieur le Cur\xe9 of the \xabNotre-Dame-de-Gr\xe2ce\xbb neighborhood' In [4]: cursor.execute("INSERT INTO MyTable VALUES(%s)", s.encode('utf-8')) cursor.execute("INSERT INTO MyTable VALUES(" + s.encode('utf-8') + "')") conn.commit() ``` Both execute statements yield the same garbled text on the SQL Server side: ``` 'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' ``` Maybe something is wrong with the way I'm encoding, or with my syntax. Someone suggested a stored procedure, but I'm hoping not to have to go that route. [This](https://stackoverflow.com/questions/4791114/python-to-mssql-encoding-problem) seems to be a very similar problem, with no real response.
2013/04/15
[ "https://Stackoverflow.com/questions/16024041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599229/" ]
Ended up using pypyodbc instead. Needed some assistance to [connect](https://stackoverflow.com/questions/16024956/connecting-to-sql-server-with-pypyodbc), then used the [doc recipe](https://code.google.com/p/pypyodbc/wiki/A_HelloWorld_sample_to_access_mssql_with_python) for executing statements: ``` import pypyodbc conn = pypyodbc.connect("DRIVER={SQL Server};SERVER=my_server;UID=MyUserName;PWD=MyPassword;DATABASE=MyDB") cur = conn.cursor cur.execute('''INSERT INTO MyDB(rank,text,author) VALUES(?,?,?)''', (1, u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood', 'Charles S.')) cur.commit() ```
Here is something which worked for me: ``` # -*- coding: utf-8 -*- import pymssql conn = pymssql.connect(host='hostname', user='me', password='password', database='db') cursor = conn.cursor() s = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' cursor.execute("INSERT INTO MyTable(col1) VALUES(%s)", s.encode('latin-1', "ignore")) conn.commit() cursor.close() conn.close() ``` *MyTable* is of collation: Latin1\_General\_CI\_AS and the column *col1* in it is of type varchar(MAX) My environment is: SQL Server 2008 & Python 2.7.10
16,024,041
I'm having issues sending unicode to SQL Server via pymssql: ``` In [1]: import pymssql conn = pymssql.connect(host='hostname', user='me', password='password', database='db') cursor = conn.cursor() In [2]: s = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' In [3]: s Out [3]: u'Monsieur le Cur\xe9 of the \xabNotre-Dame-de-Gr\xe2ce\xbb neighborhood' In [4]: cursor.execute("INSERT INTO MyTable VALUES(%s)", s.encode('utf-8')) cursor.execute("INSERT INTO MyTable VALUES(" + s.encode('utf-8') + "')") conn.commit() ``` Both execute statements yield the same garbled text on the SQL Server side: ``` 'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' ``` Maybe something is wrong with the way I'm encoding, or with my syntax. Someone suggested a stored procedure, but I'm hoping not to have to go that route. [This](https://stackoverflow.com/questions/4791114/python-to-mssql-encoding-problem) seems to be a very similar problem, with no real response.
2013/04/15
[ "https://Stackoverflow.com/questions/16024041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599229/" ]
Ran into the same issue with pymssql and did not want to switch to pypyodbc For me, there was no issue in removing any accents seeing that I only needed first names as a reference. So this solution may not be for everyone. ``` import unicodedate firstName = u'René' firstName = unicodedata.normalize('NFKD', firstName).encode('ascii', 'ignore') print firstName ```
Here is something which worked for me: ``` # -*- coding: utf-8 -*- import pymssql conn = pymssql.connect(host='hostname', user='me', password='password', database='db') cursor = conn.cursor() s = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' cursor.execute("INSERT INTO MyTable(col1) VALUES(%s)", s.encode('latin-1', "ignore")) conn.commit() cursor.close() conn.close() ``` *MyTable* is of collation: Latin1\_General\_CI\_AS and the column *col1* in it is of type varchar(MAX) My environment is: SQL Server 2008 & Python 2.7.10
16,024,041
I'm having issues sending unicode to SQL Server via pymssql: ``` In [1]: import pymssql conn = pymssql.connect(host='hostname', user='me', password='password', database='db') cursor = conn.cursor() In [2]: s = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' In [3]: s Out [3]: u'Monsieur le Cur\xe9 of the \xabNotre-Dame-de-Gr\xe2ce\xbb neighborhood' In [4]: cursor.execute("INSERT INTO MyTable VALUES(%s)", s.encode('utf-8')) cursor.execute("INSERT INTO MyTable VALUES(" + s.encode('utf-8') + "')") conn.commit() ``` Both execute statements yield the same garbled text on the SQL Server side: ``` 'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' ``` Maybe something is wrong with the way I'm encoding, or with my syntax. Someone suggested a stored procedure, but I'm hoping not to have to go that route. [This](https://stackoverflow.com/questions/4791114/python-to-mssql-encoding-problem) seems to be a very similar problem, with no real response.
2013/04/15
[ "https://Stackoverflow.com/questions/16024041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599229/" ]
The following code samples have been tested and verified to work with both Python 2.7.5 and Python 3.4.3 using pymssql 2.1.1. For a Python source file saved with UTF-8 encoding: ```python # -*- coding: utf-8 -*- import pymssql cnxn = pymssql.connect( server='localhost', port='52865', user='sa', password='whatever', database='myDb') crsr = cnxn.cursor() crsr.execute("INSERT INTO MyTable (textcol) VALUES (%s)", (u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood')) cnxn.commit() crsr.close() cnxn.close() ``` For a Python source file saved with "ANSI" (Windows-1252) encoding: ```python # -*- coding: windows-1252 -*- import pymssql cnxn = pymssql.connect( server='localhost', port='52865', user='sa', password='whatever', database='myDb') crsr = cnxn.cursor() crsr.execute("INSERT INTO MyTable (textcol) VALUES (%s)", (u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood')) cnxn.commit() crsr.close() cnxn.close() ``` Note that the only difference between the two samples is the very first line to declare the encoding of the source file. To be clear, the table receiving the INSERT was: ```sql CREATE TABLE [dbo].[MyTable]( [id] [int] IDENTITY(1,1) NOT NULL, [textcol] [nvarchar](255) NULL, PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] ```
Here is something which worked for me: ``` # -*- coding: utf-8 -*- import pymssql conn = pymssql.connect(host='hostname', user='me', password='password', database='db') cursor = conn.cursor() s = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' cursor.execute("INSERT INTO MyTable(col1) VALUES(%s)", s.encode('latin-1', "ignore")) conn.commit() cursor.close() conn.close() ``` *MyTable* is of collation: Latin1\_General\_CI\_AS and the column *col1* in it is of type varchar(MAX) My environment is: SQL Server 2008 & Python 2.7.10
40,700,192
The Virt-Manager is capable of modifying network interfaces of running domains, for example changing the connected network. I want to script this in python with the libvirt-API. ``` import libvirt conn = libvirt.open('qemu:///system') deb = conn.lookupByName('Testdebian') xml = deb.XMLDesc() xml = replace('old-network-name', 'new-network-name') deb.undefine() deb = conn.defineXML(xml) ``` But that doesn't work. The network isn't changed. Can someone give me a tipp how to modify a running domain with libvirt? I couldn't find anything about that in the docs. But it must be possible as the Virt-Manager can do it. Thanks for any help. Edit: I managed to perform the network change via virsh: ``` virsh update-device 16 Testdebian.xml ``` Testdebian.xml must contain the interface device only, not the whole domain-XML. But how can I do this via the libvirt-API? There seems to be no method to perform update-device through the API....
2016/11/20
[ "https://Stackoverflow.com/questions/40700192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6204346/" ]
This is very easy in [c++17](/questions/tagged/c%2b%2b17 "show questions tagged 'c++17'"). ``` template<class Tuple> decltype(auto) sum_components(Tuple const& tuple) { auto sum_them = [](auto const&... e)->decltype(auto) { return (e+...); }; return std::apply( sum_them, tuple ); }; ``` or `(...+e)` for the opposite fold direction. In previous versions, the right approach would be to write your own `apply` rather than writing a bespoke implementation. When your compiler updates, you can then delete code. In [c++14](/questions/tagged/c%2b%2b14 "show questions tagged 'c++14'"), I might do this: ``` // namespace for utility code: namespace utility { template<std::size_t...Is> auto index_over( std::index_sequence<Is...> ) { return [](auto&&f)->decltype(auto){ return decltype(f)(f)( std::integral_constant<std::size_t,Is>{}... ); }; } template<std::size_t N> auto index_upto() { return index_over( std::make_index_sequence<N>{} ); } } // namespace for semantic-equivalent replacements of `std` code: namespace notstd { template<class F, class Tuple> decltype(auto) apply( F&& f, Tuple&& tuple ) { using dTuple = std::decay_t<Tuple>; auto index = ::utility::index_upto< std::tuple_size<dTuple>{} >(); return index( [&](auto...Is)->decltype(auto){ auto target=std::ref(f); return target( std::get<Is>( std::forward<Tuple>(tuple) )... ); } ); } } ``` which is pretty close to `std::apply` in [c++14](/questions/tagged/c%2b%2b14 "show questions tagged 'c++14'"). (I abuse `std::ref` to get `INVOKE` semantics). (It does not work perfectly with rvalue invokers, but that is very corner case). In [c++11](/questions/tagged/c%2b%2b11 "show questions tagged 'c++11'"), I would advise upgrading your compiler at this point. In [c++03](/questions/tagged/c%2b%2b03 "show questions tagged 'c++03'") I'd advise upgrading your job at this point. --- All of the above do right or left folds. In some cases, a binary tree fold might be better. This is trickier. If your `+` does expression templates, the above code won't work well due to lifetime issues. You may have to add another template type for "afterwards, cast-to" to cause the temporary expression tree to evaluate in some cases.
With C++1z it's pretty simple with [fold expressions](http://en.cppreference.com/w/cpp/language/fold). First, forward the tuple to an `_impl` function and provide it with index sequence to access all tuple elements, then sum: ``` template<typename T, size_t... Is> auto sum_components_impl(T const& t, std::index_sequence<Is...>) { return (std::get<Is>(t) + ...); } template <class Tuple> int sum_components(const Tuple& t) { constexpr auto size = std::tuple_size<Tuple>{}; return sum_components_impl(t, std::make_index_sequence<size>{}); } ``` [demo](http://melpon.org/wandbox/permlink/abxtgr4crzUyxy3Q) --- A C++14 approach would be to recursively sum a variadic pack: ``` int sum() { return 0; } template<typename T, typename... Us> auto sum(T&& t, Us&&... us) { return std::forward<T>(t) + sum(std::forward<Us>(us)...); } template<typename T, size_t... Is> auto sum_components_impl(T const& t, std::index_sequence<Is...>) { return sum(std::get<Is>(t)...); } template <class Tuple> int sum_components(const Tuple& t) { constexpr auto size = std::tuple_size<Tuple>{}; return sum_components_impl(t, std::make_index_sequence<size>{}); } ``` [demo](http://melpon.org/wandbox/permlink/2l5ivZY0sb2qwYaF) A C++11 approach would be the C++14 approach with custom implementation of `index_sequence`. For example from [here](https://stackoverflow.com/a/17426611/2456565). --- As @ildjarn pointed out in the comments, the above examples are both employing right folds, while many programmers expect left folds in their code. The C++1z version is trivially changeable: ``` template<typename T, size_t... Is> auto sum_components_impl(T const& t, std::index_sequence<Is...>) { return (... + std::get<Is>(t)); } ``` [demo](http://melpon.org/wandbox/permlink/uOvNgrUU240Ub6wt) And the C++14 isn't much worse, but there are more changes: ``` template<typename T, typename... Us> auto sum(T&& t, Us&&... us) { return sum(std::forward<Us>(us)...) + std::forward<T>(t); } template<typename T, size_t... Is> auto sum_components_impl(T const& t, std::index_sequence<Is...>) { constexpr auto last_index = sizeof...(Is) - 1; return sum(std::get<last_index - Is>(t)...); } ``` [demo](http://melpon.org/wandbox/permlink/J1LHuZKYFbn5AmYV)
43,628,733
I wrote this code to display contents of a list in grid form . It works fine for the alphabet list . But when i try to run it with a randomly generated list it gives an list index out of range error . Here is the full code: import random ``` #barebones 2d shell grid generator ''' Following list is a place holder you can add any list data to show in a grid pattern with this tool ''' lis = ['a','b','c','d','e','f','g','h','j','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] newLis = [] #generates random list def lisGen(): length = 20 # random.randint(10,20) for i in range(length): value = random.randint(1,9) newLis.append(str(value)) lisGen() askRow = input('Enter number of rows :') askColumns = input('Enter number of columns :') def gridGen(row,column): j=0 cnt = int(row) while (cnt>0): for i in range(int(column)): print(' '+'-',end='') print('\n',end='') #this is the output content loop for i in range(int(column)): if j<len(lis): print('|'+newLis[j],end='') j += 1 else: print('|'+' ',end='') print('|',end='') print('\n',end='') cnt -= 1 for i in range(int(column)): print(' '+'-',end='') print('\n',end='') gridGen(askRow,askColumns) ``` The expected/correct output ,using the alphabet list(lis): ``` Enter number of rows :7 Enter number of columns :7 - - - - - - - |a|b|c|d|e|f|g| - - - - - - - |h|j|i|j|k|l|m| - - - - - - - |n|o|p|q|r|s|t| - - - - - - - |u|v|w|x|y|z| | - - - - - - - | | | | | | | | - - - - - - - | | | | | | | | - - - - - - - | | | | | | | | - - - - - - - ``` The error output when used randomly generated list ( newLis ): ``` Enter number of rows :7 Enter number of columns :7 - - - - - - - |9|2|1|4|7|5|4| - - - - - - - |9|7|7|3|2|1|3| - - - - - - - |7|5|4|1|2|3Traceback (most recent call last): File "D:\01-Mywares\python\2d shell graphics\gridGen.py", line 56, in <module> gridGen(askRow,askColumns) File "D:\01-Mywares\python\2d shell graphics\gridGen.py", line 40, in gridGen print('|'+newLis[j],end='') IndexError: list index out of range ```
2017/04/26
[ "https://Stackoverflow.com/questions/43628733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5698361/" ]
I suggest you use the function '.load' rather than '.csv', something like this: ``` data = sc.read.load(path_to_file, format='com.databricks.spark.csv', header='true', inferSchema='true').cache() ``` Of you course you can add more options. Then you can simply get you want: ``` data.columns ``` Another way of doing this (to get the columns) is to use it this way: ``` data = sc.textFile(path_to_file) ``` And to get the headers (columns) just use ``` data.first() ``` Looks like you are trying to get your schema from your csv file without opening it! The above should help you to get them and hence manipulate whatever you like. Note: to use '.columns' your 'sc' should be configured as: ``` spark = SparkSession.builder \ .master("yarn") \ .appName("experiment-airbnb") \ .enableHiveSupport() \ .getOrCreate() sc = SQLContext(spark) ``` Good luck!
It would be good if you can provide some sample data next time. How should we know how your csv looks like. Concerning your question, it looks like that your csv column is not a decimal all the time. InferSchema takes the first row and assign a datatype, in your case, it is a [DecimalType](http://spark.apache.org/docs/2.1.0/api/python/_modules/pyspark/sql/types.html) but then in the second row you might have a text so that the error would occur. If you don't infer the schema then, of course, it would work since everything will be cast as a StringType.
43,628,733
I wrote this code to display contents of a list in grid form . It works fine for the alphabet list . But when i try to run it with a randomly generated list it gives an list index out of range error . Here is the full code: import random ``` #barebones 2d shell grid generator ''' Following list is a place holder you can add any list data to show in a grid pattern with this tool ''' lis = ['a','b','c','d','e','f','g','h','j','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] newLis = [] #generates random list def lisGen(): length = 20 # random.randint(10,20) for i in range(length): value = random.randint(1,9) newLis.append(str(value)) lisGen() askRow = input('Enter number of rows :') askColumns = input('Enter number of columns :') def gridGen(row,column): j=0 cnt = int(row) while (cnt>0): for i in range(int(column)): print(' '+'-',end='') print('\n',end='') #this is the output content loop for i in range(int(column)): if j<len(lis): print('|'+newLis[j],end='') j += 1 else: print('|'+' ',end='') print('|',end='') print('\n',end='') cnt -= 1 for i in range(int(column)): print(' '+'-',end='') print('\n',end='') gridGen(askRow,askColumns) ``` The expected/correct output ,using the alphabet list(lis): ``` Enter number of rows :7 Enter number of columns :7 - - - - - - - |a|b|c|d|e|f|g| - - - - - - - |h|j|i|j|k|l|m| - - - - - - - |n|o|p|q|r|s|t| - - - - - - - |u|v|w|x|y|z| | - - - - - - - | | | | | | | | - - - - - - - | | | | | | | | - - - - - - - | | | | | | | | - - - - - - - ``` The error output when used randomly generated list ( newLis ): ``` Enter number of rows :7 Enter number of columns :7 - - - - - - - |9|2|1|4|7|5|4| - - - - - - - |9|7|7|3|2|1|3| - - - - - - - |7|5|4|1|2|3Traceback (most recent call last): File "D:\01-Mywares\python\2d shell graphics\gridGen.py", line 56, in <module> gridGen(askRow,askColumns) File "D:\01-Mywares\python\2d shell graphics\gridGen.py", line 40, in gridGen print('|'+newLis[j],end='') IndexError: list index out of range ```
2017/04/26
[ "https://Stackoverflow.com/questions/43628733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5698361/" ]
Please try the below code and this infers the schema along with header ``` from pyspark.sql import SparkSession spark=SparkSession.builder.appName('operation').getOrCreate() df=spark.read.csv("C:/LEARNING//Spark_DataFrames/stock.csv ",inferSchema=True, header=True) df.show() ```
It would be good if you can provide some sample data next time. How should we know how your csv looks like. Concerning your question, it looks like that your csv column is not a decimal all the time. InferSchema takes the first row and assign a datatype, in your case, it is a [DecimalType](http://spark.apache.org/docs/2.1.0/api/python/_modules/pyspark/sql/types.html) but then in the second row you might have a text so that the error would occur. If you don't infer the schema then, of course, it would work since everything will be cast as a StringType.
43,628,733
I wrote this code to display contents of a list in grid form . It works fine for the alphabet list . But when i try to run it with a randomly generated list it gives an list index out of range error . Here is the full code: import random ``` #barebones 2d shell grid generator ''' Following list is a place holder you can add any list data to show in a grid pattern with this tool ''' lis = ['a','b','c','d','e','f','g','h','j','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] newLis = [] #generates random list def lisGen(): length = 20 # random.randint(10,20) for i in range(length): value = random.randint(1,9) newLis.append(str(value)) lisGen() askRow = input('Enter number of rows :') askColumns = input('Enter number of columns :') def gridGen(row,column): j=0 cnt = int(row) while (cnt>0): for i in range(int(column)): print(' '+'-',end='') print('\n',end='') #this is the output content loop for i in range(int(column)): if j<len(lis): print('|'+newLis[j],end='') j += 1 else: print('|'+' ',end='') print('|',end='') print('\n',end='') cnt -= 1 for i in range(int(column)): print(' '+'-',end='') print('\n',end='') gridGen(askRow,askColumns) ``` The expected/correct output ,using the alphabet list(lis): ``` Enter number of rows :7 Enter number of columns :7 - - - - - - - |a|b|c|d|e|f|g| - - - - - - - |h|j|i|j|k|l|m| - - - - - - - |n|o|p|q|r|s|t| - - - - - - - |u|v|w|x|y|z| | - - - - - - - | | | | | | | | - - - - - - - | | | | | | | | - - - - - - - | | | | | | | | - - - - - - - ``` The error output when used randomly generated list ( newLis ): ``` Enter number of rows :7 Enter number of columns :7 - - - - - - - |9|2|1|4|7|5|4| - - - - - - - |9|7|7|3|2|1|3| - - - - - - - |7|5|4|1|2|3Traceback (most recent call last): File "D:\01-Mywares\python\2d shell graphics\gridGen.py", line 56, in <module> gridGen(askRow,askColumns) File "D:\01-Mywares\python\2d shell graphics\gridGen.py", line 40, in gridGen print('|'+newLis[j],end='') IndexError: list index out of range ```
2017/04/26
[ "https://Stackoverflow.com/questions/43628733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5698361/" ]
I suggest you use the function '.load' rather than '.csv', something like this: ``` data = sc.read.load(path_to_file, format='com.databricks.spark.csv', header='true', inferSchema='true').cache() ``` Of you course you can add more options. Then you can simply get you want: ``` data.columns ``` Another way of doing this (to get the columns) is to use it this way: ``` data = sc.textFile(path_to_file) ``` And to get the headers (columns) just use ``` data.first() ``` Looks like you are trying to get your schema from your csv file without opening it! The above should help you to get them and hence manipulate whatever you like. Note: to use '.columns' your 'sc' should be configured as: ``` spark = SparkSession.builder \ .master("yarn") \ .appName("experiment-airbnb") \ .enableHiveSupport() \ .getOrCreate() sc = SQLContext(spark) ``` Good luck!
Please try the below code and this infers the schema along with header ``` from pyspark.sql import SparkSession spark=SparkSession.builder.appName('operation').getOrCreate() df=spark.read.csv("C:/LEARNING//Spark_DataFrames/stock.csv ",inferSchema=True, header=True) df.show() ```
48,761,673
I want to solve a case where i know what all will be contents of the string output.. but i am not sure about the order of the contents inside the output.. say, the expected contents of my output are `['this','output','can','be','jumbled','in','any','order']`.. and the output can be `'this can in any order jumbled output be'`, or `'this order in any can output jumbled be'` How do i write a regular expression in python to solve this case??
2018/02/13
[ "https://Stackoverflow.com/questions/48761673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7534349/" ]
Use [`contains(where:)`](https://developer.apple.com/documentation/swift/sequence/2905153-contains) on the dictionary values: ``` // Enable button if at least one value is not nil: button.isEnabled = dict.values.contains(where: { $0 != nil }) ``` Or ``` // Enable button if no value is nil: button.isEnabled = !dict.values.contains(where: { $0 == nil }) ```
You can use [`filter`](https://developer.apple.com/documentation/swift/sequence/2905694-filter) to check if any value is nil in a dictionary. ``` button.isEnabled = dict.filter { $1 == nil }.isEmpty ```
48,761,673
I want to solve a case where i know what all will be contents of the string output.. but i am not sure about the order of the contents inside the output.. say, the expected contents of my output are `['this','output','can','be','jumbled','in','any','order']`.. and the output can be `'this can in any order jumbled output be'`, or `'this order in any can output jumbled be'` How do i write a regular expression in python to solve this case??
2018/02/13
[ "https://Stackoverflow.com/questions/48761673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7534349/" ]
You can use [`filter`](https://developer.apple.com/documentation/swift/sequence/2905694-filter) to check if any value is nil in a dictionary. ``` button.isEnabled = dict.filter { $1 == nil }.isEmpty ```
I recommend to conform to the standard dictionary definition that a `nil` value indicates *no key* and declare the dictionary non-optional (`[String:Double]`). In this case the button will be enabled if all 12 keys are present. This is more efficient than `filter` or `contains` ``` button.isEnabled = dict.count == 12 ```
48,761,673
I want to solve a case where i know what all will be contents of the string output.. but i am not sure about the order of the contents inside the output.. say, the expected contents of my output are `['this','output','can','be','jumbled','in','any','order']`.. and the output can be `'this can in any order jumbled output be'`, or `'this order in any can output jumbled be'` How do i write a regular expression in python to solve this case??
2018/02/13
[ "https://Stackoverflow.com/questions/48761673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7534349/" ]
Use [`contains(where:)`](https://developer.apple.com/documentation/swift/sequence/2905153-contains) on the dictionary values: ``` // Enable button if at least one value is not nil: button.isEnabled = dict.values.contains(where: { $0 != nil }) ``` Or ``` // Enable button if no value is nil: button.isEnabled = !dict.values.contains(where: { $0 == nil }) ```
You've already been provided with similar solutions, but here you go: ``` dict.filter({$0.value == nil}).count != 0 ```
48,761,673
I want to solve a case where i know what all will be contents of the string output.. but i am not sure about the order of the contents inside the output.. say, the expected contents of my output are `['this','output','can','be','jumbled','in','any','order']`.. and the output can be `'this can in any order jumbled output be'`, or `'this order in any can output jumbled be'` How do i write a regular expression in python to solve this case??
2018/02/13
[ "https://Stackoverflow.com/questions/48761673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7534349/" ]
Use [`contains(where:)`](https://developer.apple.com/documentation/swift/sequence/2905153-contains) on the dictionary values: ``` // Enable button if at least one value is not nil: button.isEnabled = dict.values.contains(where: { $0 != nil }) ``` Or ``` // Enable button if no value is nil: button.isEnabled = !dict.values.contains(where: { $0 == nil }) ```
I recommend to conform to the standard dictionary definition that a `nil` value indicates *no key* and declare the dictionary non-optional (`[String:Double]`). In this case the button will be enabled if all 12 keys are present. This is more efficient than `filter` or `contains` ``` button.isEnabled = dict.count == 12 ```
48,761,673
I want to solve a case where i know what all will be contents of the string output.. but i am not sure about the order of the contents inside the output.. say, the expected contents of my output are `['this','output','can','be','jumbled','in','any','order']`.. and the output can be `'this can in any order jumbled output be'`, or `'this order in any can output jumbled be'` How do i write a regular expression in python to solve this case??
2018/02/13
[ "https://Stackoverflow.com/questions/48761673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7534349/" ]
You've already been provided with similar solutions, but here you go: ``` dict.filter({$0.value == nil}).count != 0 ```
I recommend to conform to the standard dictionary definition that a `nil` value indicates *no key* and declare the dictionary non-optional (`[String:Double]`). In this case the button will be enabled if all 12 keys are present. This is more efficient than `filter` or `contains` ``` button.isEnabled = dict.count == 12 ```
53,140,438
How to create cumulative sum (new\_supply)in dataframe python from demand column from table ``` item Date supply demand A 2018-01-01 0 10 A 2018-01-02 0 15 A 2018-01-03 100 30 A 2018-01-04 0 10 A 2018-01-05 0 40 A 2018-01-06 50 50 A 2018-01-07 0 10 B 2018-01-01 0 20 B 2018-01-02 0 30 B 2018-01-03 20 60 B 2018-01-04 0 20 B 2018-01-05 100 10 B 2018-01-06 0 20 B 2018-01-07 0 30 ``` New Desired table from the above table ``` item Date supply demand new_supply A 2018-01-01 0 10 0 A 2018-01-02 0 15 0 A 2018-01-03 100 30 55 A 2018-01-04 0 10 0 A 2018-01-05 0 40 0 A 2018-01-06 50 50 100 A 2018-01-07 0 10 0 B 2018-01-01 0 20 0 B 2018-01-02 0 30 0 B 2018-01-03 20 60 110 B 2018-01-04 0 20 0 B 2018-01-05 100 10 140 B 2018-01-06 0 20 0 B 2018-01-07 0 30 0 ```
2018/11/04
[ "https://Stackoverflow.com/questions/53140438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10603056/" ]
Make the python file executable chmod +x Test.py
Why do you have to include the logic inside a class? note = 10 if note >= 10: print("yes") else: print("NO") Just this will do, remove the class
53,140,438
How to create cumulative sum (new\_supply)in dataframe python from demand column from table ``` item Date supply demand A 2018-01-01 0 10 A 2018-01-02 0 15 A 2018-01-03 100 30 A 2018-01-04 0 10 A 2018-01-05 0 40 A 2018-01-06 50 50 A 2018-01-07 0 10 B 2018-01-01 0 20 B 2018-01-02 0 30 B 2018-01-03 20 60 B 2018-01-04 0 20 B 2018-01-05 100 10 B 2018-01-06 0 20 B 2018-01-07 0 30 ``` New Desired table from the above table ``` item Date supply demand new_supply A 2018-01-01 0 10 0 A 2018-01-02 0 15 0 A 2018-01-03 100 30 55 A 2018-01-04 0 10 0 A 2018-01-05 0 40 0 A 2018-01-06 50 50 100 A 2018-01-07 0 10 0 B 2018-01-01 0 20 0 B 2018-01-02 0 30 0 B 2018-01-03 20 60 110 B 2018-01-04 0 20 0 B 2018-01-05 100 10 140 B 2018-01-06 0 20 0 B 2018-01-07 0 30 0 ```
2018/11/04
[ "https://Stackoverflow.com/questions/53140438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10603056/" ]
Make the python file executable chmod +x Test.py
Why you use "env" from system directory? If you change first line of script code will working. May be some strange settings in you OS or you try strange using python env. ``` #!/usr/bin/python2.7 class Test: note = 10 if note >= 10: print("yes") else: print("NO") ```
3,885,846
I'd like to call a .py file from within python. It is in the same directory. Effectivly, I would like the same behavior as calling python foo.py from the command line without using any of the command line tools. How should I do this?
2010/10/07
[ "https://Stackoverflow.com/questions/3885846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450054/" ]
It's not quite clear (at least to me) what you mean by using "none of the command-line tools". To run a program in a subprocess, one usually uses the `subprocess` module. However, if both the calling and the callee are python scripts, there is another alternative, which is to use the `multiprocessing` module. For example, you can organize foo.py like this: ``` def main(): ... if __name__=='__main__': main() ``` Then in the calling script, test.py: ``` import multiprocessing as mp import foo proc=mp.Process(target=foo.main) proc.start() # Do stuff while foo.main is running # Wait until foo.main has ended proc.join() # Continue doing more stuff ```
``` execfile('foo.py') ``` See also: * [Further reading on execfile](http://docs.python.org/library/functions.html#execfile)
3,885,846
I'd like to call a .py file from within python. It is in the same directory. Effectivly, I would like the same behavior as calling python foo.py from the command line without using any of the command line tools. How should I do this?
2010/10/07
[ "https://Stackoverflow.com/questions/3885846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450054/" ]
It's not quite clear (at least to me) what you mean by using "none of the command-line tools". To run a program in a subprocess, one usually uses the `subprocess` module. However, if both the calling and the callee are python scripts, there is another alternative, which is to use the `multiprocessing` module. For example, you can organize foo.py like this: ``` def main(): ... if __name__=='__main__': main() ``` Then in the calling script, test.py: ``` import multiprocessing as mp import foo proc=mp.Process(target=foo.main) proc.start() # Do stuff while foo.main is running # Wait until foo.main has ended proc.join() # Continue doing more stuff ```
`import module` or `__import__("module")`, to load module.py. * [Modules - Python v2.7 documentation](http://docs.python.org/tutorial/modules.html) * [Importing Python modules](http://effbot.org/zone/import-confusion.htm)
61,270,154
I used to have my app on Heroku and the way it worked there was that I had 2 buildpacks. One for NodeJS and one for Python. Heroku ran `npm run build` and then Django served the files from the `build` folder. I use Code Pipeline on AWS to deploy a new version of my app every time there is a new push on my GitHub repository. Since I couldn't figure out how to run `npm run build` in a python environment in EB, I had a workaround. I ran `npm run build` and pushed it to my repository (removed the `build` folder from .gitignore) and then Django served the files on EB. However, this is not the best solution and I was wondering if anyone knows how to run `npm run build` the way Heroku can do it with their NodeJS buildpack for a python app on EB.
2020/04/17
[ "https://Stackoverflow.com/questions/61270154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11804213/" ]
So I figured out one solution that worked for me. Since I want to create the build version of my app on the server the way Heroku does it with the NodeJS buildpack, I had to create a command that installs node like this: ``` container_commands: 01_install_node: command: "curl -sL https://rpm.nodesource.com/setup_12.x | sudo bash - && sudo yum install nodejs" ignoreErrors: false ``` And then to create the build version of the react app on a Python Environment EB, I added the following command: ``` container_commands: 02_react: command: "npm install && npm run build" ignoreErrors: false ``` So of course, after the build version is created, you should collect static files, so here is how my working config file looked at the end: ``` option_settings: aws:elasticbeanstalk:container:python: WSGIPath: <project_name>/wsgi.py aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: <project_name>.settings aws:elasticbeanstalk:container:python:staticfiles: /static/: staticfiles/ container_commands: 01_install_node: command: "curl -sL https://rpm.nodesource.com/setup_12.x | sudo bash - && sudo yum install nodejs" ignoreErrors: false 02_react: command: "npm install && npm run build" ignoreErrors: false 03_collectstatic: command: "django-admin.py collectstatic --noinput" ``` Hope this helps anyone who encounters the same
I don't know exactly Python but I guess you can adapt for you case. Elastic Beanstalk for Node.js platform use by default `app.js`, then `server.js`, and then `npm start` (in that order) to start your application. You can change this behavior with **configuration files**. Below the steps to accomplish with Node.js: 1. Create the following file `.ebextensions/<your-config-file-name>.config` with the following content: ``` option_settings: aws:elasticbeanstalk:container:nodejs: NodeCommand: "npm run eb:prod" ``` 2. Edit your `package.json` to create the `eb:prod` command. For instance: ``` "scripts": { "start": "razzle start", "build": "razzle build", "test": "razzle test --env=jsdom", "start:prod": "NODE_ENV=production node build/server.js", "eb:prod": "npm run build && npm run start:prod" } ``` 3. You may faced permission denied errors during your build. To solve this problem you can create `.npmrc` file with the following content: ``` # Force npm to run node-gyp also as root unsafe-perm=true ``` If you need more details, I wrote a blogpost about it: [I deployed a server-side React app with AWS Elastic Beanstalk. Here’s what I learned.](https://medium.com/@johanrin/i-deployed-a-server-side-react-app-with-aws-elastic-beanstalk-heres-what-i-learned-34c8399079c5?source=friends_link&sk=6e05dee451fe68f3b290ff70c582bfb5)
29,648,412
I have a Python 3 installation of Anaconda and want to be able to switch quickly between python2 and 3 kernels. This is on OSX. My steps so far involved: ``` conda create -p ~/anaconda/envs/python2 python=2.7 source activate python2 conda install ipython ipython kernelspec install-self source deactivate ``` After this I have a python2 Kernel to choose from in the python3 IPython notebook, which however can't start. So I went ahead and modified /usr/local/share/jupyter/kernels/python2/kernel.json ``` { "display_name": "Python 2", "language": "python", "argv": [ "/Users/sonium/anaconda/envs/python2/bin/python", "-m", "IPython.kernel", "-f", "{connection_file}" ], "env":{"PYTHONHOME":"~/anaconda/envs/python2/:~/anaconda/envs/python2/lib/"} } ``` Now when I start the python2 kernel it fails with: ``` ImportError: No module named site ```
2015/04/15
[ "https://Stackoverflow.com/questions/29648412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1217949/" ]
Apparently IPython expects explicit pathnames, so no '~' instead of the home directory. It worked after changing the kernel.json to: ``` { "display_name": "Python 2", "language": "python", "argv": [ "/Users/sonium/anaconda/envs/python2/bin/python2.7", "-m", "IPython.kernel", "-f", "{connection_file}" ], "env":{"PYTHONHOME":"/Users/sonium/anaconda/envs/python2"} } ```
I install the Anaconda 3 in Win10. I am now focus on python 3, but I have lot projects written in python 2. If I want check them in juypter in python environment it's will failed, and shows "kernel error". The solution is almost like above, but something different. The path to find those two json files is : `C:\ProgramData\jupyter\kernels` Sometime it may be hidden. Another path you need check, after you create a python2 environment in Anaconda, try to find this path: `C:\Users\username\Anaconda3\envs\python2\python.exe` Copy it to your python2 kernel json file then it should be work.
16,033,348
I have a list of items that relate to each other, I know they end up building a graph but the data is not sorted in any way. ``` PMO-100 -> SA-300 SA-100 -> SA-300 SA-100 -> SA-200 PMO-100 -> SA-100 ``` In python examples for graphViz api I realize that you can pretty much generate a graph if you know it's top node and can run down the levels and build all the relations. Since I'm getting an assorted list (I only know that it is a graph since all relations are figured from a single point) - is there a way to build a graph on top of this data? **Update:** the first comment to this question identifies I haven't correctly explained what I'm after. Indeed the following code gets you a proper graph: ``` gr = pydot.Dot(graph_type='digraph') for link in graph.links: edge = pydot.Edge(link.outwardIssue.key, link.inwardIssue.key) gr.add_edge(edge) gr.write('graph.png',format='png') ``` my question really is - how can I color-rode individual nodes or change type of arrow for a specific edge?
2013/04/16
[ "https://Stackoverflow.com/questions/16033348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/220255/" ]
There is no need to identify a top node for graphviz. Just add all Nodes and edges and let it do the rest. For example: ``` import pydot graph = pydot.Dot('graphname', graph_type='digraph') pmo100 = pydot.Node("PMO-100") sa300 = pydot.Node("SA-300") sa100 = pydot.Node("SA-100") sa200 = pydot.Node("SA-200") graph.add_edge(pydot.Edge(pmo100, sa300)) graph.add_edge(pydot.Edge(sa100, sa300)) graph.add_edge(pydot.Edge(sa100, sa200)) graph.add_edge(pydot.Edge(pmo100, sa100)) graph.write_png('example1_graph.png') ``` This will result in the following image: ![result](https://i.stack.imgur.com/IJxg0.png) You can find more info at <http://pythonhaven.wordpress.com/2009/12/09/generating_graphs_with_pydot/>
Try out [pygraph](http://github.com/iamaziz/pygraph) package, it produces a directed graph based on relation statements (data). No matter if the data are sorted or not. So (as in your case) if we have the following data (in a triple relation), it is easy to produce the corresponding graph: ### First way ``` s1 = "PMO-100 -> SA-300" s2 = "SA-100 -> SA-300" s3 = "SA-100 -> SA-200" s4 = "PMO-100 -> SA-100" from pygraph.dgraph import PyGraph g = PyGraph() g.add_relation(s1) g.add_relation(s2) g.add_relation(s3) g.add_relation(s4) g.draw_graph(label=False) ``` It will produce: ![enter image description here](https://i.stack.imgur.com/qs0Dx.png) Or you can even read the relations from a file. ### Second way Say, you have `data.txt`: ``` PMO-100 -> SA-300 SA-100 -> SA-300 SA-100 -> SA-200 PMO-100 -> SA-100 ``` It is even easier in 4 loc,: ``` from pygraph.dgraph import PyGraph g = PyGraph() g.file_relations("data.txt") g.draw_graph(label=False) ``` In both ways the result is the same: ![enter image description here](https://i.stack.imgur.com/qs0Dx.png)
16,033,348
I have a list of items that relate to each other, I know they end up building a graph but the data is not sorted in any way. ``` PMO-100 -> SA-300 SA-100 -> SA-300 SA-100 -> SA-200 PMO-100 -> SA-100 ``` In python examples for graphViz api I realize that you can pretty much generate a graph if you know it's top node and can run down the levels and build all the relations. Since I'm getting an assorted list (I only know that it is a graph since all relations are figured from a single point) - is there a way to build a graph on top of this data? **Update:** the first comment to this question identifies I haven't correctly explained what I'm after. Indeed the following code gets you a proper graph: ``` gr = pydot.Dot(graph_type='digraph') for link in graph.links: edge = pydot.Edge(link.outwardIssue.key, link.inwardIssue.key) gr.add_edge(edge) gr.write('graph.png',format='png') ``` my question really is - how can I color-rode individual nodes or change type of arrow for a specific edge?
2013/04/16
[ "https://Stackoverflow.com/questions/16033348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/220255/" ]
How to change color of nodes: node.attr["color"] = 'red' to change the shape of arrowhead, same method edge.attr["arrowhead"] = "..."
Try out [pygraph](http://github.com/iamaziz/pygraph) package, it produces a directed graph based on relation statements (data). No matter if the data are sorted or not. So (as in your case) if we have the following data (in a triple relation), it is easy to produce the corresponding graph: ### First way ``` s1 = "PMO-100 -> SA-300" s2 = "SA-100 -> SA-300" s3 = "SA-100 -> SA-200" s4 = "PMO-100 -> SA-100" from pygraph.dgraph import PyGraph g = PyGraph() g.add_relation(s1) g.add_relation(s2) g.add_relation(s3) g.add_relation(s4) g.draw_graph(label=False) ``` It will produce: ![enter image description here](https://i.stack.imgur.com/qs0Dx.png) Or you can even read the relations from a file. ### Second way Say, you have `data.txt`: ``` PMO-100 -> SA-300 SA-100 -> SA-300 SA-100 -> SA-200 PMO-100 -> SA-100 ``` It is even easier in 4 loc,: ``` from pygraph.dgraph import PyGraph g = PyGraph() g.file_relations("data.txt") g.draw_graph(label=False) ``` In both ways the result is the same: ![enter image description here](https://i.stack.imgur.com/qs0Dx.png)
50,860,578
I have the following situation: ``` for x1 in range(x1, x2): for x2 in range(x3, x4): for x3 ... ... f(x1, x2, x3, ...) ``` How to convert this to a mechanism in which I only tell python to make *n* nested loops where the variable name is x1, x2, x3, x4, ...? I don't want to write every possibility manually of course, since there might be very many dimensions.
2018/06/14
[ "https://Stackoverflow.com/questions/50860578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8472333/" ]
What you want to do is iterate over a product. Use [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product). ``` import itertools ranges = [range(x1, x2), range(x3, x4), ...] for xs in itertools.product(*ranges): f(*xs) ``` Example ------- ``` import itertools ranges = [range(0, 2), range(1, 3), range(2, 4)] for xs in itertools.product(*ranges): print(*xs) ``` Output ------ ``` 0 1 2 0 1 3 0 2 2 0 2 3 1 1 2 1 1 3 1 2 2 1 2 3 ```
Recommended: itertools ---------------------- [`itertools`](https://docs.python.org/3/library/itertools.html) is an awesome package for everything related to iteration: ``` from itertools import product x1 = 3; x2 = 4 x3 = 0; x4 = 2 x5 = 42; x6 = 42 for x, y, z in product(range(x1, x2), range(x3, x4), range(x4, x5)): print(x, y, z) ``` gives ``` 3 0 2 3 0 3 3 0 4 3 0 5 3 0 6 3 0 7 3 0 8 3 0 9 3 0 10 3 0 11 3 0 12 3 0 13 3 0 14 3 0 15 3 0 16 3 0 17 3 0 18 3 0 19 3 0 20 3 0 21 3 0 22 3 0 23 3 0 24 3 0 25 3 0 26 3 0 27 3 0 28 3 0 29 3 0 30 3 0 31 3 0 32 3 0 33 3 0 34 3 0 35 3 0 36 3 0 37 3 0 38 3 0 39 3 0 40 3 0 41 3 1 2 3 1 3 3 1 4 3 1 5 3 1 6 3 1 7 3 1 8 3 1 9 3 1 10 3 1 11 3 1 12 3 1 13 3 1 14 3 1 15 3 1 16 3 1 17 3 1 18 3 1 19 3 1 20 3 1 21 3 1 22 3 1 23 3 1 24 3 1 25 3 1 26 3 1 27 3 1 28 3 1 29 3 1 30 3 1 31 3 1 32 3 1 33 3 1 34 3 1 35 3 1 36 3 1 37 3 1 38 3 1 39 3 1 40 3 1 41 ``` Create a cross-product function yourself ---------------------------------------- ``` def product(*args): pools = map(tuple, args) result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] for prod in result: yield tuple(prod) ```
50,860,578
I have the following situation: ``` for x1 in range(x1, x2): for x2 in range(x3, x4): for x3 ... ... f(x1, x2, x3, ...) ``` How to convert this to a mechanism in which I only tell python to make *n* nested loops where the variable name is x1, x2, x3, x4, ...? I don't want to write every possibility manually of course, since there might be very many dimensions.
2018/06/14
[ "https://Stackoverflow.com/questions/50860578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8472333/" ]
What you want to do is iterate over a product. Use [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product). ``` import itertools ranges = [range(x1, x2), range(x3, x4), ...] for xs in itertools.product(*ranges): f(*xs) ``` Example ------- ``` import itertools ranges = [range(0, 2), range(1, 3), range(2, 4)] for xs in itertools.product(*ranges): print(*xs) ``` Output ------ ``` 0 1 2 0 1 3 0 2 2 0 2 3 1 1 2 1 1 3 1 2 2 1 2 3 ```
Use multiprocessing! ``` import multiprocessing from itertools import product results = [] def callback(return_value): # this stores results results.append(return_value) if __name__=="__main__" : pool = multiprocessing.Pool(4) args = product(range1, range2, range) for x, y, z in args: pool.apply_async(f,(x,y,z),call_back=callback) pool.close() pool.join() ``` Now you can run your function while also taking advantage of the full capacity of your machine!
50,860,578
I have the following situation: ``` for x1 in range(x1, x2): for x2 in range(x3, x4): for x3 ... ... f(x1, x2, x3, ...) ``` How to convert this to a mechanism in which I only tell python to make *n* nested loops where the variable name is x1, x2, x3, x4, ...? I don't want to write every possibility manually of course, since there might be very many dimensions.
2018/06/14
[ "https://Stackoverflow.com/questions/50860578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8472333/" ]
What you want to do is iterate over a product. Use [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product). ``` import itertools ranges = [range(x1, x2), range(x3, x4), ...] for xs in itertools.product(*ranges): f(*xs) ``` Example ------- ``` import itertools ranges = [range(0, 2), range(1, 3), range(2, 4)] for xs in itertools.product(*ranges): print(*xs) ``` Output ------ ``` 0 1 2 0 1 3 0 2 2 0 2 3 1 1 2 1 1 3 1 2 2 1 2 3 ```
You could also use [`numpy.ndindex`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html) to achieve what you are looking for: ``` import numpy for y1, y2, y3 in numpy.ndindex(x2, x4, ...): ... ``` Thats especially useful when you are already using numpy for something else in your script. You would have to add the 'starting point' (i.e. x1, x2, ...) to each dimension though (if it's not 0).
50,860,578
I have the following situation: ``` for x1 in range(x1, x2): for x2 in range(x3, x4): for x3 ... ... f(x1, x2, x3, ...) ``` How to convert this to a mechanism in which I only tell python to make *n* nested loops where the variable name is x1, x2, x3, x4, ...? I don't want to write every possibility manually of course, since there might be very many dimensions.
2018/06/14
[ "https://Stackoverflow.com/questions/50860578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8472333/" ]
Recommended: itertools ---------------------- [`itertools`](https://docs.python.org/3/library/itertools.html) is an awesome package for everything related to iteration: ``` from itertools import product x1 = 3; x2 = 4 x3 = 0; x4 = 2 x5 = 42; x6 = 42 for x, y, z in product(range(x1, x2), range(x3, x4), range(x4, x5)): print(x, y, z) ``` gives ``` 3 0 2 3 0 3 3 0 4 3 0 5 3 0 6 3 0 7 3 0 8 3 0 9 3 0 10 3 0 11 3 0 12 3 0 13 3 0 14 3 0 15 3 0 16 3 0 17 3 0 18 3 0 19 3 0 20 3 0 21 3 0 22 3 0 23 3 0 24 3 0 25 3 0 26 3 0 27 3 0 28 3 0 29 3 0 30 3 0 31 3 0 32 3 0 33 3 0 34 3 0 35 3 0 36 3 0 37 3 0 38 3 0 39 3 0 40 3 0 41 3 1 2 3 1 3 3 1 4 3 1 5 3 1 6 3 1 7 3 1 8 3 1 9 3 1 10 3 1 11 3 1 12 3 1 13 3 1 14 3 1 15 3 1 16 3 1 17 3 1 18 3 1 19 3 1 20 3 1 21 3 1 22 3 1 23 3 1 24 3 1 25 3 1 26 3 1 27 3 1 28 3 1 29 3 1 30 3 1 31 3 1 32 3 1 33 3 1 34 3 1 35 3 1 36 3 1 37 3 1 38 3 1 39 3 1 40 3 1 41 ``` Create a cross-product function yourself ---------------------------------------- ``` def product(*args): pools = map(tuple, args) result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] for prod in result: yield tuple(prod) ```
Use multiprocessing! ``` import multiprocessing from itertools import product results = [] def callback(return_value): # this stores results results.append(return_value) if __name__=="__main__" : pool = multiprocessing.Pool(4) args = product(range1, range2, range) for x, y, z in args: pool.apply_async(f,(x,y,z),call_back=callback) pool.close() pool.join() ``` Now you can run your function while also taking advantage of the full capacity of your machine!
50,860,578
I have the following situation: ``` for x1 in range(x1, x2): for x2 in range(x3, x4): for x3 ... ... f(x1, x2, x3, ...) ``` How to convert this to a mechanism in which I only tell python to make *n* nested loops where the variable name is x1, x2, x3, x4, ...? I don't want to write every possibility manually of course, since there might be very many dimensions.
2018/06/14
[ "https://Stackoverflow.com/questions/50860578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8472333/" ]
Recommended: itertools ---------------------- [`itertools`](https://docs.python.org/3/library/itertools.html) is an awesome package for everything related to iteration: ``` from itertools import product x1 = 3; x2 = 4 x3 = 0; x4 = 2 x5 = 42; x6 = 42 for x, y, z in product(range(x1, x2), range(x3, x4), range(x4, x5)): print(x, y, z) ``` gives ``` 3 0 2 3 0 3 3 0 4 3 0 5 3 0 6 3 0 7 3 0 8 3 0 9 3 0 10 3 0 11 3 0 12 3 0 13 3 0 14 3 0 15 3 0 16 3 0 17 3 0 18 3 0 19 3 0 20 3 0 21 3 0 22 3 0 23 3 0 24 3 0 25 3 0 26 3 0 27 3 0 28 3 0 29 3 0 30 3 0 31 3 0 32 3 0 33 3 0 34 3 0 35 3 0 36 3 0 37 3 0 38 3 0 39 3 0 40 3 0 41 3 1 2 3 1 3 3 1 4 3 1 5 3 1 6 3 1 7 3 1 8 3 1 9 3 1 10 3 1 11 3 1 12 3 1 13 3 1 14 3 1 15 3 1 16 3 1 17 3 1 18 3 1 19 3 1 20 3 1 21 3 1 22 3 1 23 3 1 24 3 1 25 3 1 26 3 1 27 3 1 28 3 1 29 3 1 30 3 1 31 3 1 32 3 1 33 3 1 34 3 1 35 3 1 36 3 1 37 3 1 38 3 1 39 3 1 40 3 1 41 ``` Create a cross-product function yourself ---------------------------------------- ``` def product(*args): pools = map(tuple, args) result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] for prod in result: yield tuple(prod) ```
You could also use [`numpy.ndindex`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html) to achieve what you are looking for: ``` import numpy for y1, y2, y3 in numpy.ndindex(x2, x4, ...): ... ``` Thats especially useful when you are already using numpy for something else in your script. You would have to add the 'starting point' (i.e. x1, x2, ...) to each dimension though (if it's not 0).
50,860,578
I have the following situation: ``` for x1 in range(x1, x2): for x2 in range(x3, x4): for x3 ... ... f(x1, x2, x3, ...) ``` How to convert this to a mechanism in which I only tell python to make *n* nested loops where the variable name is x1, x2, x3, x4, ...? I don't want to write every possibility manually of course, since there might be very many dimensions.
2018/06/14
[ "https://Stackoverflow.com/questions/50860578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8472333/" ]
You could also use [`numpy.ndindex`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html) to achieve what you are looking for: ``` import numpy for y1, y2, y3 in numpy.ndindex(x2, x4, ...): ... ``` Thats especially useful when you are already using numpy for something else in your script. You would have to add the 'starting point' (i.e. x1, x2, ...) to each dimension though (if it's not 0).
Use multiprocessing! ``` import multiprocessing from itertools import product results = [] def callback(return_value): # this stores results results.append(return_value) if __name__=="__main__" : pool = multiprocessing.Pool(4) args = product(range1, range2, range) for x, y, z in args: pool.apply_async(f,(x,y,z),call_back=callback) pool.close() pool.join() ``` Now you can run your function while also taking advantage of the full capacity of your machine!
55,138,466
I'm scraping a [website](https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html). I'm trying to click on a link under `<li>` but it throws `NoSuchElementException` exception. And the links I want to click: [![enter image description here](https://i.stack.imgur.com/2BVsw.png)](https://i.stack.imgur.com/2BVsw.png) I'm using below code: ``` from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument('--start-maximized') chrome_options.add_argument('window-size=5000x2500') webdriver = webdriver.Chrome('chromedriver',chrome_options=chrome_options) url = "https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html" webdriver.get(url) webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click() time.sleep(5) webdriver.find_element_by_link_text('Préstamo Coche Nuevo').click() webdriver.save_screenshot('test1.png') ``` The error I got: > > > ``` > /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:10: DeprecationWarning: use options instead of chrome_options > # Remove the CWD from sys.path while we load stuff. > > --------------------------------------------------------------------------- > > NoSuchElementException Traceback (most recent call last) > > <ipython-input-44-f6608be53ab3> in <module>() > 13 webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click() > 14 time.sleep(5) > ---> 15 webdriver.find_element_by_link_text('Préstamo Coche Nuevo').click() > 16 webdriver.save_screenshot('test1.png') > > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in find\_element\_by\_link\_text(self, link\_text) > 426 element = driver.find\_element\_by\_link\_text('Sign In') > 427 """ > --> 428 return self.find\_element(by=By.LINK\_TEXT, value=link\_text) > 429 > 430 def find\_elements\_by\_link\_text(self, text): > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in find\_element(self, by, value) > 976 return self.execute(Command.FIND\_ELEMENT, { > 977 'using': by, > --> 978 'value': value})['value'] > 979 > 980 def find\_elements(self, by=By.ID, value=None): > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in execute(self, driver\_command, params) > 319 response = self.command\_executor.execute(driver\_command, params) > 320 if response: > --> 321 self.error\_handler.check\_response(response) > 322 response['value'] = self.\_unwrap\_value( > 323 response.get('value', None)) > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py > > ``` > > in check\_response(self, response) > 240 alert\_text = value['alert'].get('text') > 241 raise exception\_class(message, screen, stacktrace, alert\_text) > --> 242 raise exception\_class(message, screen, stacktrace) > 243 > 244 def \_value\_or\_default(self, obj, key, default): > > > > ``` > NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"Préstamo Coche Nuevo"} > (Session info: headless chrome=72.0.3626.121) > (Driver info: chromedriver=72.0.3626.121,platform=Linux 4.14.79+ x86_64) > > ``` > >
2019/03/13
[ "https://Stackoverflow.com/questions/55138466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11155464/" ]
onchange of the radio button select the input using document.querySelector and using setAttribute set the required attribute to the elements ```js function a() { document.querySelector('.one').setAttribute('required','required'); document.querySelector('.five').setAttribute('required','required'); } ``` ```html <input type="radio" name="customer" id="customer" onchange='a()' value="A customer">Customer<br> <input type="radio" name="customer" id="client" value="A client">Customer<br> <input type="radio" name="customer" id="other" value="Other">Customer<br> <input type="text" placeholder="bla bla" name="referenceno" class='one'> <input type="text" placeholder="bla bla" name="referenceno" class='2'> <input type="text" placeholder="bla bla" name="referenceno" class='3'> <input type="text" placeholder="bla bla" name="referenceno" class='4'> <input type="text" placeholder="bla bla" name="referenceno" class='five'> <input type="text" placeholder="bla bla" name="referenceno" class='5'> <input type="text" placeholder="bla bla" name="referenceno" class='7'> ```
You can add class to the input elements by matching the id of the radio button. Then on clicking on the button add the *required* attribute with that class name: ```js var radio = [].slice.call(document.querySelectorAll('[name=customer]')); radio.forEach(function(r){ r.addEventListener('click', function(){ var allInput = document.querySelectorAll('[type="text"]'); [].slice.call(allInput).forEach(function(el){ el.required = false; }); document.querySelector('.'+this.id).required = true; }); }); ``` ```html <form> <input type="radio" name="customer" id="customer" value="A customer">Customer<br> <input type="radio" name="customer" id="client" value="A client">Customer<br> <input type="radio" name="customer" id="other" value="Other">Customer<br> <input type="text" placeholder="bla bla" name="referenceno" class="customer"> <input type="text" placeholder="bla bla" name="referenceno" class="client"> <input type="text" placeholder="bla bla" name="referenceno" class="other"> <button type="submit">Login</button> </form> ```
55,138,466
I'm scraping a [website](https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html). I'm trying to click on a link under `<li>` but it throws `NoSuchElementException` exception. And the links I want to click: [![enter image description here](https://i.stack.imgur.com/2BVsw.png)](https://i.stack.imgur.com/2BVsw.png) I'm using below code: ``` from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument('--start-maximized') chrome_options.add_argument('window-size=5000x2500') webdriver = webdriver.Chrome('chromedriver',chrome_options=chrome_options) url = "https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html" webdriver.get(url) webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click() time.sleep(5) webdriver.find_element_by_link_text('Préstamo Coche Nuevo').click() webdriver.save_screenshot('test1.png') ``` The error I got: > > > ``` > /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:10: DeprecationWarning: use options instead of chrome_options > # Remove the CWD from sys.path while we load stuff. > > --------------------------------------------------------------------------- > > NoSuchElementException Traceback (most recent call last) > > <ipython-input-44-f6608be53ab3> in <module>() > 13 webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click() > 14 time.sleep(5) > ---> 15 webdriver.find_element_by_link_text('Préstamo Coche Nuevo').click() > 16 webdriver.save_screenshot('test1.png') > > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in find\_element\_by\_link\_text(self, link\_text) > 426 element = driver.find\_element\_by\_link\_text('Sign In') > 427 """ > --> 428 return self.find\_element(by=By.LINK\_TEXT, value=link\_text) > 429 > 430 def find\_elements\_by\_link\_text(self, text): > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in find\_element(self, by, value) > 976 return self.execute(Command.FIND\_ELEMENT, { > 977 'using': by, > --> 978 'value': value})['value'] > 979 > 980 def find\_elements(self, by=By.ID, value=None): > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in execute(self, driver\_command, params) > 319 response = self.command\_executor.execute(driver\_command, params) > 320 if response: > --> 321 self.error\_handler.check\_response(response) > 322 response['value'] = self.\_unwrap\_value( > 323 response.get('value', None)) > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py > > ``` > > in check\_response(self, response) > 240 alert\_text = value['alert'].get('text') > 241 raise exception\_class(message, screen, stacktrace, alert\_text) > --> 242 raise exception\_class(message, screen, stacktrace) > 243 > 244 def \_value\_or\_default(self, obj, key, default): > > > > ``` > NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"Préstamo Coche Nuevo"} > (Session info: headless chrome=72.0.3626.121) > (Driver info: chromedriver=72.0.3626.121,platform=Linux 4.14.79+ x86_64) > > ``` > >
2019/03/13
[ "https://Stackoverflow.com/questions/55138466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11155464/" ]
onchange of the radio button select the input using document.querySelector and using setAttribute set the required attribute to the elements ```js function a() { document.querySelector('.one').setAttribute('required','required'); document.querySelector('.five').setAttribute('required','required'); } ``` ```html <input type="radio" name="customer" id="customer" onchange='a()' value="A customer">Customer<br> <input type="radio" name="customer" id="client" value="A client">Customer<br> <input type="radio" name="customer" id="other" value="Other">Customer<br> <input type="text" placeholder="bla bla" name="referenceno" class='one'> <input type="text" placeholder="bla bla" name="referenceno" class='2'> <input type="text" placeholder="bla bla" name="referenceno" class='3'> <input type="text" placeholder="bla bla" name="referenceno" class='4'> <input type="text" placeholder="bla bla" name="referenceno" class='five'> <input type="text" placeholder="bla bla" name="referenceno" class='5'> <input type="text" placeholder="bla bla" name="referenceno" class='7'> ```
```html <form id="my-form"> <input type="radio" name="customer" id="customer" value="A customer">Customer<br> <input type="radio" name="customer" id="client" value="A client">Client<br> <input type="radio" name="customer" id="other" value="Other">Other<br> <input type="text" placeholder="reference no" name="referenceno"> <input type="text" placeholder="other field" name="other-field"> <button type="submit">Submit</button> </form> ``` ``` let selectedCustomer = null; const onCustomerSelected = (value) => { if (selectedCustomer === value) { return; } selectedCustomer = value; updateOnCustomerChanged(); }; const updateOnCustomerChanged = () => { const referenceNoInputField = document.querySelector('input[name=referenceno]'); referenceNoInputField.required = selectedCustomer === 'A customer'; }; document.querySelectorAll('[name=customer]') .forEach((el) => { el.addEventListener('change', () => { onCustomerSelected(el.value); }); }); ```
55,138,466
I'm scraping a [website](https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html). I'm trying to click on a link under `<li>` but it throws `NoSuchElementException` exception. And the links I want to click: [![enter image description here](https://i.stack.imgur.com/2BVsw.png)](https://i.stack.imgur.com/2BVsw.png) I'm using below code: ``` from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument('--start-maximized') chrome_options.add_argument('window-size=5000x2500') webdriver = webdriver.Chrome('chromedriver',chrome_options=chrome_options) url = "https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html" webdriver.get(url) webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click() time.sleep(5) webdriver.find_element_by_link_text('Préstamo Coche Nuevo').click() webdriver.save_screenshot('test1.png') ``` The error I got: > > > ``` > /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:10: DeprecationWarning: use options instead of chrome_options > # Remove the CWD from sys.path while we load stuff. > > --------------------------------------------------------------------------- > > NoSuchElementException Traceback (most recent call last) > > <ipython-input-44-f6608be53ab3> in <module>() > 13 webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click() > 14 time.sleep(5) > ---> 15 webdriver.find_element_by_link_text('Préstamo Coche Nuevo').click() > 16 webdriver.save_screenshot('test1.png') > > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in find\_element\_by\_link\_text(self, link\_text) > 426 element = driver.find\_element\_by\_link\_text('Sign In') > 427 """ > --> 428 return self.find\_element(by=By.LINK\_TEXT, value=link\_text) > 429 > 430 def find\_elements\_by\_link\_text(self, text): > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in find\_element(self, by, value) > 976 return self.execute(Command.FIND\_ELEMENT, { > 977 'using': by, > --> 978 'value': value})['value'] > 979 > 980 def find\_elements(self, by=By.ID, value=None): > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in execute(self, driver\_command, params) > 319 response = self.command\_executor.execute(driver\_command, params) > 320 if response: > --> 321 self.error\_handler.check\_response(response) > 322 response['value'] = self.\_unwrap\_value( > 323 response.get('value', None)) > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py > > ``` > > in check\_response(self, response) > 240 alert\_text = value['alert'].get('text') > 241 raise exception\_class(message, screen, stacktrace, alert\_text) > --> 242 raise exception\_class(message, screen, stacktrace) > 243 > 244 def \_value\_or\_default(self, obj, key, default): > > > > ``` > NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"Préstamo Coche Nuevo"} > (Session info: headless chrome=72.0.3626.121) > (Driver info: chromedriver=72.0.3626.121,platform=Linux 4.14.79+ x86_64) > > ``` > >
2019/03/13
[ "https://Stackoverflow.com/questions/55138466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11155464/" ]
onchange of the radio button select the input using document.querySelector and using setAttribute set the required attribute to the elements ```js function a() { document.querySelector('.one').setAttribute('required','required'); document.querySelector('.five').setAttribute('required','required'); } ``` ```html <input type="radio" name="customer" id="customer" onchange='a()' value="A customer">Customer<br> <input type="radio" name="customer" id="client" value="A client">Customer<br> <input type="radio" name="customer" id="other" value="Other">Customer<br> <input type="text" placeholder="bla bla" name="referenceno" class='one'> <input type="text" placeholder="bla bla" name="referenceno" class='2'> <input type="text" placeholder="bla bla" name="referenceno" class='3'> <input type="text" placeholder="bla bla" name="referenceno" class='4'> <input type="text" placeholder="bla bla" name="referenceno" class='five'> <input type="text" placeholder="bla bla" name="referenceno" class='5'> <input type="text" placeholder="bla bla" name="referenceno" class='7'> ```
``` <!DOCTYPE html> <html> <head> <title>Page Title</title> <style> body { background-color: black; text-align: center; color: white; font-family: Arial, Helvetica, sans-serif; } </style> </head> <body id="container_id"> <form> <input type="radio" name="customer" id="customer" value="A customer">Customer<br> <input type="radio" name="customer" id="client" value="A client">Customer<br> <input type="radio" name="customer" id="other" value="Other">Customer<br> <input type="text" placeholder="bla bla" name="referenceno" class="customer"> <input type="text" placeholder="bla bla" name="referenceno" class="client"> <input type="text" placeholder="bla bla" name="referenceno" class="other"> <button type="submit">Login</button> </form> <script> var radio = document.querySelectorAll('[name=customer]'); radio.forEach(function(r){ r.addEventListener('click', function(){ var x = document.querySelectorAll("input[type='text']"); var i; for (i = 0; i < x.length; i++) { x[i].required = false; } document.querySelector('.'+this.id).required = true; }); }); </script> </body> </html> ```
55,138,466
I'm scraping a [website](https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html). I'm trying to click on a link under `<li>` but it throws `NoSuchElementException` exception. And the links I want to click: [![enter image description here](https://i.stack.imgur.com/2BVsw.png)](https://i.stack.imgur.com/2BVsw.png) I'm using below code: ``` from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument('--start-maximized') chrome_options.add_argument('window-size=5000x2500') webdriver = webdriver.Chrome('chromedriver',chrome_options=chrome_options) url = "https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html" webdriver.get(url) webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click() time.sleep(5) webdriver.find_element_by_link_text('Préstamo Coche Nuevo').click() webdriver.save_screenshot('test1.png') ``` The error I got: > > > ``` > /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:10: DeprecationWarning: use options instead of chrome_options > # Remove the CWD from sys.path while we load stuff. > > --------------------------------------------------------------------------- > > NoSuchElementException Traceback (most recent call last) > > <ipython-input-44-f6608be53ab3> in <module>() > 13 webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click() > 14 time.sleep(5) > ---> 15 webdriver.find_element_by_link_text('Préstamo Coche Nuevo').click() > 16 webdriver.save_screenshot('test1.png') > > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in find\_element\_by\_link\_text(self, link\_text) > 426 element = driver.find\_element\_by\_link\_text('Sign In') > 427 """ > --> 428 return self.find\_element(by=By.LINK\_TEXT, value=link\_text) > 429 > 430 def find\_elements\_by\_link\_text(self, text): > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in find\_element(self, by, value) > 976 return self.execute(Command.FIND\_ELEMENT, { > 977 'using': by, > --> 978 'value': value})['value'] > 979 > 980 def find\_elements(self, by=By.ID, value=None): > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in execute(self, driver\_command, params) > 319 response = self.command\_executor.execute(driver\_command, params) > 320 if response: > --> 321 self.error\_handler.check\_response(response) > 322 response['value'] = self.\_unwrap\_value( > 323 response.get('value', None)) > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py > > ``` > > in check\_response(self, response) > 240 alert\_text = value['alert'].get('text') > 241 raise exception\_class(message, screen, stacktrace, alert\_text) > --> 242 raise exception\_class(message, screen, stacktrace) > 243 > 244 def \_value\_or\_default(self, obj, key, default): > > > > ``` > NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"Préstamo Coche Nuevo"} > (Session info: headless chrome=72.0.3626.121) > (Driver info: chromedriver=72.0.3626.121,platform=Linux 4.14.79+ x86_64) > > ``` > >
2019/03/13
[ "https://Stackoverflow.com/questions/55138466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11155464/" ]
You can add class to the input elements by matching the id of the radio button. Then on clicking on the button add the *required* attribute with that class name: ```js var radio = [].slice.call(document.querySelectorAll('[name=customer]')); radio.forEach(function(r){ r.addEventListener('click', function(){ var allInput = document.querySelectorAll('[type="text"]'); [].slice.call(allInput).forEach(function(el){ el.required = false; }); document.querySelector('.'+this.id).required = true; }); }); ``` ```html <form> <input type="radio" name="customer" id="customer" value="A customer">Customer<br> <input type="radio" name="customer" id="client" value="A client">Customer<br> <input type="radio" name="customer" id="other" value="Other">Customer<br> <input type="text" placeholder="bla bla" name="referenceno" class="customer"> <input type="text" placeholder="bla bla" name="referenceno" class="client"> <input type="text" placeholder="bla bla" name="referenceno" class="other"> <button type="submit">Login</button> </form> ```
```html <form id="my-form"> <input type="radio" name="customer" id="customer" value="A customer">Customer<br> <input type="radio" name="customer" id="client" value="A client">Client<br> <input type="radio" name="customer" id="other" value="Other">Other<br> <input type="text" placeholder="reference no" name="referenceno"> <input type="text" placeholder="other field" name="other-field"> <button type="submit">Submit</button> </form> ``` ``` let selectedCustomer = null; const onCustomerSelected = (value) => { if (selectedCustomer === value) { return; } selectedCustomer = value; updateOnCustomerChanged(); }; const updateOnCustomerChanged = () => { const referenceNoInputField = document.querySelector('input[name=referenceno]'); referenceNoInputField.required = selectedCustomer === 'A customer'; }; document.querySelectorAll('[name=customer]') .forEach((el) => { el.addEventListener('change', () => { onCustomerSelected(el.value); }); }); ```
55,138,466
I'm scraping a [website](https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html). I'm trying to click on a link under `<li>` but it throws `NoSuchElementException` exception. And the links I want to click: [![enter image description here](https://i.stack.imgur.com/2BVsw.png)](https://i.stack.imgur.com/2BVsw.png) I'm using below code: ``` from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument('--start-maximized') chrome_options.add_argument('window-size=5000x2500') webdriver = webdriver.Chrome('chromedriver',chrome_options=chrome_options) url = "https://www.cofidis.es/es/creditos-prestamos/financiacion-coche.html" webdriver.get(url) webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click() time.sleep(5) webdriver.find_element_by_link_text('Préstamo Coche Nuevo').click() webdriver.save_screenshot('test1.png') ``` The error I got: > > > ``` > /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:10: DeprecationWarning: use options instead of chrome_options > # Remove the CWD from sys.path while we load stuff. > > --------------------------------------------------------------------------- > > NoSuchElementException Traceback (most recent call last) > > <ipython-input-44-f6608be53ab3> in <module>() > 13 webdriver.find_element_by_xpath('//*[@id="btncerrar"]').click() > 14 time.sleep(5) > ---> 15 webdriver.find_element_by_link_text('Préstamo Coche Nuevo').click() > 16 webdriver.save_screenshot('test1.png') > > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in find\_element\_by\_link\_text(self, link\_text) > 426 element = driver.find\_element\_by\_link\_text('Sign In') > 427 """ > --> 428 return self.find\_element(by=By.LINK\_TEXT, value=link\_text) > 429 > 430 def find\_elements\_by\_link\_text(self, text): > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in find\_element(self, by, value) > 976 return self.execute(Command.FIND\_ELEMENT, { > 977 'using': by, > --> 978 'value': value})['value'] > 979 > 980 def find\_elements(self, by=By.ID, value=None): > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py > > ``` > > in execute(self, driver\_command, params) > 319 response = self.command\_executor.execute(driver\_command, params) > 320 if response: > --> 321 self.error\_handler.check\_response(response) > 322 response['value'] = self.\_unwrap\_value( > 323 response.get('value', None)) > > > > ``` > /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py > > ``` > > in check\_response(self, response) > 240 alert\_text = value['alert'].get('text') > 241 raise exception\_class(message, screen, stacktrace, alert\_text) > --> 242 raise exception\_class(message, screen, stacktrace) > 243 > 244 def \_value\_or\_default(self, obj, key, default): > > > > ``` > NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"Préstamo Coche Nuevo"} > (Session info: headless chrome=72.0.3626.121) > (Driver info: chromedriver=72.0.3626.121,platform=Linux 4.14.79+ x86_64) > > ``` > >
2019/03/13
[ "https://Stackoverflow.com/questions/55138466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11155464/" ]
You can add class to the input elements by matching the id of the radio button. Then on clicking on the button add the *required* attribute with that class name: ```js var radio = [].slice.call(document.querySelectorAll('[name=customer]')); radio.forEach(function(r){ r.addEventListener('click', function(){ var allInput = document.querySelectorAll('[type="text"]'); [].slice.call(allInput).forEach(function(el){ el.required = false; }); document.querySelector('.'+this.id).required = true; }); }); ``` ```html <form> <input type="radio" name="customer" id="customer" value="A customer">Customer<br> <input type="radio" name="customer" id="client" value="A client">Customer<br> <input type="radio" name="customer" id="other" value="Other">Customer<br> <input type="text" placeholder="bla bla" name="referenceno" class="customer"> <input type="text" placeholder="bla bla" name="referenceno" class="client"> <input type="text" placeholder="bla bla" name="referenceno" class="other"> <button type="submit">Login</button> </form> ```
``` <!DOCTYPE html> <html> <head> <title>Page Title</title> <style> body { background-color: black; text-align: center; color: white; font-family: Arial, Helvetica, sans-serif; } </style> </head> <body id="container_id"> <form> <input type="radio" name="customer" id="customer" value="A customer">Customer<br> <input type="radio" name="customer" id="client" value="A client">Customer<br> <input type="radio" name="customer" id="other" value="Other">Customer<br> <input type="text" placeholder="bla bla" name="referenceno" class="customer"> <input type="text" placeholder="bla bla" name="referenceno" class="client"> <input type="text" placeholder="bla bla" name="referenceno" class="other"> <button type="submit">Login</button> </form> <script> var radio = document.querySelectorAll('[name=customer]'); radio.forEach(function(r){ r.addEventListener('click', function(){ var x = document.querySelectorAll("input[type='text']"); var i; for (i = 0; i < x.length; i++) { x[i].required = false; } document.querySelector('.'+this.id).required = true; }); }); </script> </body> </html> ```
69,086,563
i am trying to read CT scan Dicom file using pydicom python library but i just can't get rid of this below error even when i install gdcm and pylibjpeg ``` RuntimeError: The following handlers are available to decode the pixel data however they are missing required dependencies: GDCM (req. ), pylibjpeg (req. ) ``` Here is my code ``` !pip install pylibjpeg pylibjpeg-libjpeg pylibjpeg-openjpeg !pip install python-gdcm import gdcm import pylibjpeg import numpy as np import pydicom from pydicom.pixel_data_handlers.util import apply_voi_lut import matplotlib.pyplot as plt %matplotlib inline def read_xray(path, voi_lut = True, fix_monochrome = True): dicom = pydicom.read_file(path) # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to "human-friendly" view if voi_lut: data = apply_voi_lut(dicom.pixel_array, dicom) else: data = dicom.pixel_array # depending on this value, X-ray may look inverted - fix that: if fix_monochrome and dicom.PhotometricInterpretation == "MONOCHROME1": data = np.amax(data) - data data = data - np.min(data) data = data / np.max(data) data = (data * 255).astype(np.uint8) return data img = read_xray('/content/ActiveTB/2018/09/17/1.2.392.200036.9116.2.6.1.44063.1797735841.1537157438.869027/1.2.392.200036.9116.2.6.1.44063.1797735841.1537157440.863887/1.2.392.200036.9116.2.6.1.44063.1797735841.1537154539.142332.dcm') plt.figure(figsize = (12,12)) plt.imshow(img) ``` Here is the image link on which i am trying to run this code ``` https://drive.google.com/file/d/1-xuryA5VlglaumU2HHV7-p6Yhgd6AaCC/view?usp=sharing ```
2021/09/07
[ "https://Stackoverflow.com/questions/69086563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15054164/" ]
Try running the following: ``` !pip install pylibjpeg !pip install gdcm ```
In a [similar problem](https://stackoverflow.com/questions/62159709/pydicom-read-file-is-only-working-with-some-dicom-images) as yours, we could see that the problem persists at the *Pixel Data* level. You need to [install one or more optional libraries](https://pydicom.github.io/pydicom/stable/tutorials/installation.html#install-the-optional-libraries), so that you can handle the various compressions. First, you should do: ``` $ pip uninstall pycocotools $ pip install pycocotools --no-binary :all: --no-build-isolation ``` From here, you should do as follows: ``` $ pip install pylibjpeg pylibjpeg-libjpeg pydicom ``` Then, your code should look like this: ``` from pydicom import dcmread import pylibjpeg import gdcm import numpy as np import pydicom from pydicom.pixel_data_handlers.util import apply_voi_lut import matplotlib.pyplot as plt %matplotlib inline def read_xray(path, voi_lut = True, fix_monochrome = True): dicom = dcmread(path) # VOI LUT (if available by DICOM device) is used to transform raw DICOM data to "human-friendly" view if voi_lut: data = apply_voi_lut(dicom.pixel_array, dicom) else: data = dicom.pixel_array # depending on this value, X-ray may look inverted - fix that: if fix_monochrome and dicom.PhotometricInterpretation == "MONOCHROME1": data = np.amax(data) - data data = data - np.min(data) data = data / np.max(data) data = (data * 255).astype(np.uint8) return data img = read_xray('/content/ActiveTB/2018/09/17/1.2.392.200036.9116.2.6.1.44063.1797735841.1537157438.869027/1.2.392.200036.9116.2.6.1.44063.1797735841.1537157440.863887/1.2.392.200036.9116.2.6.1.44063.1797735841.1537154539.142332.dcm') plt.figure(figsize = (12,12)) plt.imshow(img) ```
52,478,863
I have an input file *div.txt* that looks like this: ``` <div>a</div>b<div>c</div> <div>d</div> ``` Now I want to pick all the *div* tags and the text between them using *sed*: ``` sed -n 's:.*\(<div>.*</div>\).*:\1:p' < div.txt ``` The result I get: ``` <div>c</div> <div>d</div> ``` What I really want: ``` <div>a</div> <div>c</div> <div>d</div> ``` So the question is, how to match the same pattern n times on the same line? (do not suggest me to use perl or python, please)
2018/09/24
[ "https://Stackoverflow.com/questions/52478863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5459536/" ]
This might work for you (GNU sed): ``` sed 's/\(<\/div>\)[^<]*/\1\n/;/^</P;D' file ``` Replace a `</div>` followed by zero or more characters that are not a `<` by itself and a newline. Print only lines that begin with a `<`.
Sed is not the right tool to handle HTML. But if you really insist, and you know your input will always have properly closed pairs of div tags, you can just replace everything that's not inside a div by a newline: ``` sed 's=</div>.*<div>=</div>\n<div>=' ```
62,026,087
I have a simple Glue pythonshell job and for testing purpose I just have print("Hello World") in it. I have given it the required AWSGlueServiceRole. When I am trying to run the job it throws the following error: ``` Traceback (most recent call last): File "/tmp/runscript.py", line 114, in <module> temp_file_path = download_user_script(args.scriptLocation) File "/tmp/runscript.py", line 91, in download_user_script download_from_s3(args.scriptLocation, temp_file_path) File "/tmp/runscript.py", line 81, in download_from_s3 s3.download_file(bucket_name, s3_key, new_file_path) File "/usr/local/lib/python3.6/site-packages/boto3/s3/inject.py", line 172, in download_file extra_args=ExtraArgs, callback=Callback) File "/usr/local/lib/python3.6/site-packages/boto3/s3/transfer.py", line 307, in download_file future.result() File "/usr/local/lib/python3.6/site-packages/s3transfer/futures.py", line 106, in result return self._coordinator.result() File "/usr/local/lib/python3.6/site-packages/s3transfer/futures.py", line 265, in result raise self._exception File "/usr/local/lib/python3.6/site-packages/s3transfer/tasks.py", line 255, in _main self._submit(transfer_future=transfer_future, **kwargs) File "/usr/local/lib/python3.6/site-packages/s3transfer/download.py", line 345, in _submit **transfer_future.meta.call_args.extra_args File "/usr/local/lib/python3.6/site-packages/botocore/client.py", line 357, in _api_call return self._make_api_call(operation_name, kwargs) File "/usr/local/lib/python3.6/site-packages/botocore/client.py", line 661, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden ``` When I add S3 full access policy to the role, then the job runs successfully. I am not able to debug what is wrong
2020/05/26
[ "https://Stackoverflow.com/questions/62026087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10133469/" ]
In Glue you need to attach S3 policies to the Amazon Glue Role that you are using to run the job. When you define the job you select the role. In this example it is AWSGlueServiceRole-S3IAMRole. That does not have S3 access until you assign it. [![enter image description here](https://i.stack.imgur.com/AzqTa.png)](https://i.stack.imgur.com/AzqTa.png) ``` { "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": "s3:*", "Resource": "*" } ] } ```
You need to have the permissions to the bucket **and** the script resource. Try adding the following inline policy: ``` { "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:*" ], "Resource": "arn:aws:s3:::myBucket/*", "Effect": "Allow" }, { "Action": [ "s3:*" ], "Resource": "arn:aws:s3:::myBucket", "Effect": "Allow" } ] } ```
69,455,665
In python, if class C inherits from two other classes C(A,B), and A and B have methods with identical names but different return values, which value will that method return on C?
2021/10/05
[ "https://Stackoverflow.com/questions/69455665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
"Inherits two methods" isn't quite accurate. What happens is that `C` has a *method resolution order* (MRO), which is the list `[C, A, B, object]`. If you attempt to access a method that `C` does not define or override, the MRO determines which class will be checked next. If the desired method is defined in `A`, it shadows a method with the same name in `B`. ``` >>> class A: ... def foo(self): ... print("In A.foo") ... >>> class B: ... def foo(self): ... print("In B.foo") ... >>> class C(A, B): ... pass ... >>> C.mro() [<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>] >>> C().foo() In A.foo ```
MRO order will be followed now, if you inherit A and B in C, then preference order goes from left to right, so, A will be prefered and method of A will be called instead of B
28,747,456
I am trying to install a python package using pip in linux mint but keep getting this error message. Anyone know how to fix this? ``` alex@alex-Satellite-C660D ~ $ pip install django-registration-redux Downloading/unpacking django-registration-redux Downloading django-registration-redux-1.1.tar.gz (63kB): 63kB downloaded Running setup.py (path:/tmp/pip_build_alex/django-registration-redux/setup.py) egg_info for package django-registration-redux no previously-included directories found matching 'docs/_build' Installing collected packages: django-registration-redux Running setup.py install for django-registration-redux no previously-included directories found matching 'docs/_build' error: could not create '/usr/local/lib/python3.4/dist-packages/test_app': Permission denied Complete output from command /usr/bin/python3.4 -c "import setuptools, tokenize;__file__='/tmp/pip_build_alex/django-registration-redux/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-qi55qyaf-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib creating build/lib/test_app copying test_app/__init__.py -> build/lib/test_app copying test_app/models.py -> build/lib/test_app copying test_app/urls_simple.py -> build/lib/test_app copying test_app/settings.py -> build/lib/test_app copying test_app/urls_default.py -> build/lib/test_app copying test_app/settings_test.py -> build/lib/test_app creating build/lib/registration copying registration/users.py -> build/lib/registration copying registration/views.py -> build/lib/registration copying registration/signals.py -> build/lib/registration copying registration/__init__.py -> build/lib/registration copying registration/forms.py -> build/lib/registration copying registration/auth_urls.py -> build/lib/registration copying registration/urls.py -> build/lib/registration copying registration/models.py -> build/lib/registration copying registration/admin.py -> build/lib/registration creating build/lib/registration/management copying registration/management/__init__.py -> build/lib/registration/management creating build/lib/registration/tests copying registration/tests/__init__.py -> build/lib/registration/tests copying registration/tests/forms.py -> build/lib/registration/tests copying registration/tests/urls.py -> build/lib/registration/tests copying registration/tests/simple_backend.py -> build/lib/registration/tests copying registration/tests/models.py -> build/lib/registration/tests copying registration/tests/default_backend.py -> build/lib/registration/tests creating build/lib/registration/backends copying registration/backends/__init__.py -> build/lib/registration/backends creating build/lib/registration/management/commands copying registration/management/commands/__init__.py -> build/lib/registration/management/commands copying registration/management/commands/cleanupregistration.py -> build/lib/registration/management/commands creating build/lib/registration/backends/default copying registration/backends/default/views.py -> build/lib/registration/backends/default copying registration/backends/default/__init__.py -> build/lib/registration/backends/default copying registration/backends/default/urls.py -> build/lib/registration/backends/default creating build/lib/registration/backends/simple copying registration/backends/simple/views.py -> build/lib/registration/backends/simple copying registration/backends/simple/__init__.py -> build/lib/registration/backends/simple copying registration/backends/simple/urls.py -> build/lib/registration/backends/simple running egg_info writing top-level names to django_registration_redux.egg-info/top_level.txt writing django_registration_redux.egg-info/PKG-INFO writing dependency_links to django_registration_redux.egg-info/dependency_links.txt warning: manifest_maker: standard file '-c' not found reading manifest file 'django_registration_redux.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' no previously-included directories found matching 'docs/_build' writing manifest file 'django_registration_redux.egg-info/SOURCES.txt' creating build/lib/registration/locale creating build/lib/registration/locale/ar creating build/lib/registration/locale/ar/LC_MESSAGES copying registration/locale/ar/LC_MESSAGES/django.mo -> build/lib/registration/locale/ar/LC_MESSAGES copying registration/locale/ar/LC_MESSAGES/django.po -> build/lib/registration/locale/ar/LC_MESSAGES creating build/lib/registration/locale/bg creating build/lib/registration/locale/bg/LC_MESSAGES copying registration/locale/bg/LC_MESSAGES/django.mo -> build/lib/registration/locale/bg/LC_MESSAGES copying registration/locale/bg/LC_MESSAGES/django.po -> build/lib/registration/locale/bg/LC_MESSAGES creating build/lib/registration/locale/ca creating build/lib/registration/locale/ca/LC_MESSAGES copying registration/locale/ca/LC_MESSAGES/django.mo -> build/lib/registration/locale/ca/LC_MESSAGES copying registration/locale/ca/LC_MESSAGES/django.po -> build/lib/registration/locale/ca/LC_MESSAGES creating build/lib/registration/locale/cs creating build/lib/registration/locale/cs/LC_MESSAGES copying registration/locale/cs/LC_MESSAGES/django.mo -> build/lib/registration/locale/cs/LC_MESSAGES copying registration/locale/cs/LC_MESSAGES/django.po -> build/lib/registration/locale/cs/LC_MESSAGES creating build/lib/registration/locale/da creating build/lib/registration/locale/da/LC_MESSAGES copying registration/locale/da/LC_MESSAGES/django.mo -> build/lib/registration/locale/da/LC_MESSAGES copying registration/locale/da/LC_MESSAGES/django.po -> build/lib/registration/locale/da/LC_MESSAGES creating build/lib/registration/locale/de creating build/lib/registration/locale/de/LC_MESSAGES copying registration/locale/de/LC_MESSAGES/django.mo -> build/lib/registration/locale/de/LC_MESSAGES copying registration/locale/de/LC_MESSAGES/django.po -> build/lib/registration/locale/de/LC_MESSAGES creating build/lib/registration/locale/el creating build/lib/registration/locale/el/LC_MESSAGES copying registration/locale/el/LC_MESSAGES/django.mo -> build/lib/registration/locale/el/LC_MESSAGES copying registration/locale/el/LC_MESSAGES/django.po -> build/lib/registration/locale/el/LC_MESSAGES creating build/lib/registration/locale/en creating build/lib/registration/locale/en/LC_MESSAGES copying registration/locale/en/LC_MESSAGES/django.mo -> build/lib/registration/locale/en/LC_MESSAGES copying registration/locale/en/LC_MESSAGES/django.po -> build/lib/registration/locale/en/LC_MESSAGES creating build/lib/registration/locale/es creating build/lib/registration/locale/es/LC_MESSAGES copying registration/locale/es/LC_MESSAGES/django.mo -> build/lib/registration/locale/es/LC_MESSAGES copying registration/locale/es/LC_MESSAGES/django.po -> build/lib/registration/locale/es/LC_MESSAGES creating build/lib/registration/locale/es_AR creating build/lib/registration/locale/es_AR/LC_MESSAGES copying registration/locale/es_AR/LC_MESSAGES/django.mo -> build/lib/registration/locale/es_AR/LC_MESSAGES copying registration/locale/es_AR/LC_MESSAGES/django.po -> build/lib/registration/locale/es_AR/LC_MESSAGES creating build/lib/registration/locale/fa creating build/lib/registration/locale/fa/LC_MESSAGES copying registration/locale/fa/LC_MESSAGES/django.mo -> build/lib/registration/locale/fa/LC_MESSAGES copying registration/locale/fa/LC_MESSAGES/django.po -> build/lib/registration/locale/fa/LC_MESSAGES creating build/lib/registration/locale/fr creating build/lib/registration/locale/fr/LC_MESSAGES copying registration/locale/fr/LC_MESSAGES/django.mo -> build/lib/registration/locale/fr/LC_MESSAGES copying registration/locale/fr/LC_MESSAGES/django.po -> build/lib/registration/locale/fr/LC_MESSAGES creating build/lib/registration/locale/he creating build/lib/registration/locale/he/LC_MESSAGES copying registration/locale/he/LC_MESSAGES/django.mo -> build/lib/registration/locale/he/LC_MESSAGES copying registration/locale/he/LC_MESSAGES/django.po -> build/lib/registration/locale/he/LC_MESSAGES creating build/lib/registration/locale/hr creating build/lib/registration/locale/hr/LC_MESSAGES copying registration/locale/hr/LC_MESSAGES/django.mo -> build/lib/registration/locale/hr/LC_MESSAGES copying registration/locale/hr/LC_MESSAGES/django.po -> build/lib/registration/locale/hr/LC_MESSAGES creating build/lib/registration/locale/is creating build/lib/registration/locale/is/LC_MESSAGES copying registration/locale/is/LC_MESSAGES/django.mo -> build/lib/registration/locale/is/LC_MESSAGES copying registration/locale/is/LC_MESSAGES/django.po -> build/lib/registration/locale/is/LC_MESSAGES creating build/lib/registration/locale/it creating build/lib/registration/locale/it/LC_MESSAGES copying registration/locale/it/LC_MESSAGES/django.mo -> build/lib/registration/locale/it/LC_MESSAGES copying registration/locale/it/LC_MESSAGES/django.po -> build/lib/registration/locale/it/LC_MESSAGES creating build/lib/registration/locale/ja creating build/lib/registration/locale/ja/LC_MESSAGES copying registration/locale/ja/LC_MESSAGES/django.mo -> build/lib/registration/locale/ja/LC_MESSAGES copying registration/locale/ja/LC_MESSAGES/django.po -> build/lib/registration/locale/ja/LC_MESSAGES creating build/lib/registration/locale/ko creating build/lib/registration/locale/ko/LC_MESSAGES copying registration/locale/ko/LC_MESSAGES/django.mo -> build/lib/registration/locale/ko/LC_MESSAGES copying registration/locale/ko/LC_MESSAGES/django.po -> build/lib/registration/locale/ko/LC_MESSAGES creating build/lib/registration/locale/nb creating build/lib/registration/locale/nb/LC_MESSAGES copying registration/locale/nb/LC_MESSAGES/django.mo -> build/lib/registration/locale/nb/LC_MESSAGES copying registration/locale/nb/LC_MESSAGES/django.po -> build/lib/registration/locale/nb/LC_MESSAGES creating build/lib/registration/locale/nl creating build/lib/registration/locale/nl/LC_MESSAGES copying registration/locale/nl/LC_MESSAGES/django.mo -> build/lib/registration/locale/nl/LC_MESSAGES copying registration/locale/nl/LC_MESSAGES/django.po -> build/lib/registration/locale/nl/LC_MESSAGES creating build/lib/registration/locale/pl creating build/lib/registration/locale/pl/LC_MESSAGES copying registration/locale/pl/LC_MESSAGES/django.mo -> build/lib/registration/locale/pl/LC_MESSAGES copying registration/locale/pl/LC_MESSAGES/django.po -> build/lib/registration/locale/pl/LC_MESSAGES creating build/lib/registration/locale/pt creating build/lib/registration/locale/pt/LC_MESSAGES copying registration/locale/pt/LC_MESSAGES/django.mo -> build/lib/registration/locale/pt/LC_MESSAGES copying registration/locale/pt/LC_MESSAGES/django.po -> build/lib/registration/locale/pt/LC_MESSAGES creating build/lib/registration/locale/pt_BR creating build/lib/registration/locale/pt_BR/LC_MESSAGES copying registration/locale/pt_BR/LC_MESSAGES/django.mo -> build/lib/registration/locale/pt_BR/LC_MESSAGES copying registration/locale/pt_BR/LC_MESSAGES/django.po -> build/lib/registration/locale/pt_BR/LC_MESSAGES creating build/lib/registration/locale/ru creating build/lib/registration/locale/ru/LC_MESSAGES copying registration/locale/ru/LC_MESSAGES/django.mo -> build/lib/registration/locale/ru/LC_MESSAGES copying registration/locale/ru/LC_MESSAGES/django.po -> build/lib/registration/locale/ru/LC_MESSAGES creating build/lib/registration/locale/sl creating build/lib/registration/locale/sl/LC_MESSAGES copying registration/locale/sl/LC_MESSAGES/django.mo -> build/lib/registration/locale/sl/LC_MESSAGES copying registration/locale/sl/LC_MESSAGES/django.po -> build/lib/registration/locale/sl/LC_MESSAGES creating build/lib/registration/locale/sr creating build/lib/registration/locale/sr/LC_MESSAGES copying registration/locale/sr/LC_MESSAGES/django.mo -> build/lib/registration/locale/sr/LC_MESSAGES copying registration/locale/sr/LC_MESSAGES/django.po -> build/lib/registration/locale/sr/LC_MESSAGES creating build/lib/registration/locale/sv creating build/lib/registration/locale/sv/LC_MESSAGES copying registration/locale/sv/LC_MESSAGES/django.mo -> build/lib/registration/locale/sv/LC_MESSAGES copying registration/locale/sv/LC_MESSAGES/django.po -> build/lib/registration/locale/sv/LC_MESSAGES creating build/lib/registration/locale/tr_TR creating build/lib/registration/locale/tr_TR/LC_MESSAGES copying registration/locale/tr_TR/LC_MESSAGES/django.mo -> build/lib/registration/locale/tr_TR/LC_MESSAGES copying registration/locale/tr_TR/LC_MESSAGES/django.po -> build/lib/registration/locale/tr_TR/LC_MESSAGES creating build/lib/registration/locale/zh_CN creating build/lib/registration/locale/zh_CN/LC_MESSAGES copying registration/locale/zh_CN/LC_MESSAGES/django.mo -> build/lib/registration/locale/zh_CN/LC_MESSAGES copying registration/locale/zh_CN/LC_MESSAGES/django.po -> build/lib/registration/locale/zh_CN/LC_MESSAGES creating build/lib/registration/locale/zh_TW creating build/lib/registration/locale/zh_TW/LC_MESSAGES copying registration/locale/zh_TW/LC_MESSAGES/django.mo -> build/lib/registration/locale/zh_TW/LC_MESSAGES copying registration/locale/zh_TW/LC_MESSAGES/django.po -> build/lib/registration/locale/zh_TW/LC_MESSAGES running install_lib creating /usr/local/lib/python3.4/dist-packages/test_app error: could not create '/usr/local/lib/python3.4/dist-packages/test_app': Permission denied ---------------------------------------- Cleaning up... Command /usr/bin/python3.4 -c "import setuptools, tokenize;__file__='/tmp/pip_build_alex/django-registration-redux/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-qi55qyaf-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_alex/django-registration-redux Storing debug log for failure in /home/alex/.pip/pip.log ```
2015/02/26
[ "https://Stackoverflow.com/questions/28747456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3541209/" ]
Autoprefixer doesn't run on it's own. It needs to be run as part of postcss-cli like so: `postcss --use autoprefixer *.css -d build/` (from <https://github.com/postcss/autoprefixer#cli>) Save-dev postcss-cli and then reformat your build:css to match `postcss --use autoprefixer -b 'last 2 versions' <assets/styles/main.css | cssmin > dist/main.css` Then let us know if you're still having problems.
Installation: `npm install -g postcss-cli autoprefixer` Usage (order matters!): `postcss main.css -u autoprefixer -d dist/`
28,747,456
I am trying to install a python package using pip in linux mint but keep getting this error message. Anyone know how to fix this? ``` alex@alex-Satellite-C660D ~ $ pip install django-registration-redux Downloading/unpacking django-registration-redux Downloading django-registration-redux-1.1.tar.gz (63kB): 63kB downloaded Running setup.py (path:/tmp/pip_build_alex/django-registration-redux/setup.py) egg_info for package django-registration-redux no previously-included directories found matching 'docs/_build' Installing collected packages: django-registration-redux Running setup.py install for django-registration-redux no previously-included directories found matching 'docs/_build' error: could not create '/usr/local/lib/python3.4/dist-packages/test_app': Permission denied Complete output from command /usr/bin/python3.4 -c "import setuptools, tokenize;__file__='/tmp/pip_build_alex/django-registration-redux/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-qi55qyaf-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib creating build/lib/test_app copying test_app/__init__.py -> build/lib/test_app copying test_app/models.py -> build/lib/test_app copying test_app/urls_simple.py -> build/lib/test_app copying test_app/settings.py -> build/lib/test_app copying test_app/urls_default.py -> build/lib/test_app copying test_app/settings_test.py -> build/lib/test_app creating build/lib/registration copying registration/users.py -> build/lib/registration copying registration/views.py -> build/lib/registration copying registration/signals.py -> build/lib/registration copying registration/__init__.py -> build/lib/registration copying registration/forms.py -> build/lib/registration copying registration/auth_urls.py -> build/lib/registration copying registration/urls.py -> build/lib/registration copying registration/models.py -> build/lib/registration copying registration/admin.py -> build/lib/registration creating build/lib/registration/management copying registration/management/__init__.py -> build/lib/registration/management creating build/lib/registration/tests copying registration/tests/__init__.py -> build/lib/registration/tests copying registration/tests/forms.py -> build/lib/registration/tests copying registration/tests/urls.py -> build/lib/registration/tests copying registration/tests/simple_backend.py -> build/lib/registration/tests copying registration/tests/models.py -> build/lib/registration/tests copying registration/tests/default_backend.py -> build/lib/registration/tests creating build/lib/registration/backends copying registration/backends/__init__.py -> build/lib/registration/backends creating build/lib/registration/management/commands copying registration/management/commands/__init__.py -> build/lib/registration/management/commands copying registration/management/commands/cleanupregistration.py -> build/lib/registration/management/commands creating build/lib/registration/backends/default copying registration/backends/default/views.py -> build/lib/registration/backends/default copying registration/backends/default/__init__.py -> build/lib/registration/backends/default copying registration/backends/default/urls.py -> build/lib/registration/backends/default creating build/lib/registration/backends/simple copying registration/backends/simple/views.py -> build/lib/registration/backends/simple copying registration/backends/simple/__init__.py -> build/lib/registration/backends/simple copying registration/backends/simple/urls.py -> build/lib/registration/backends/simple running egg_info writing top-level names to django_registration_redux.egg-info/top_level.txt writing django_registration_redux.egg-info/PKG-INFO writing dependency_links to django_registration_redux.egg-info/dependency_links.txt warning: manifest_maker: standard file '-c' not found reading manifest file 'django_registration_redux.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' no previously-included directories found matching 'docs/_build' writing manifest file 'django_registration_redux.egg-info/SOURCES.txt' creating build/lib/registration/locale creating build/lib/registration/locale/ar creating build/lib/registration/locale/ar/LC_MESSAGES copying registration/locale/ar/LC_MESSAGES/django.mo -> build/lib/registration/locale/ar/LC_MESSAGES copying registration/locale/ar/LC_MESSAGES/django.po -> build/lib/registration/locale/ar/LC_MESSAGES creating build/lib/registration/locale/bg creating build/lib/registration/locale/bg/LC_MESSAGES copying registration/locale/bg/LC_MESSAGES/django.mo -> build/lib/registration/locale/bg/LC_MESSAGES copying registration/locale/bg/LC_MESSAGES/django.po -> build/lib/registration/locale/bg/LC_MESSAGES creating build/lib/registration/locale/ca creating build/lib/registration/locale/ca/LC_MESSAGES copying registration/locale/ca/LC_MESSAGES/django.mo -> build/lib/registration/locale/ca/LC_MESSAGES copying registration/locale/ca/LC_MESSAGES/django.po -> build/lib/registration/locale/ca/LC_MESSAGES creating build/lib/registration/locale/cs creating build/lib/registration/locale/cs/LC_MESSAGES copying registration/locale/cs/LC_MESSAGES/django.mo -> build/lib/registration/locale/cs/LC_MESSAGES copying registration/locale/cs/LC_MESSAGES/django.po -> build/lib/registration/locale/cs/LC_MESSAGES creating build/lib/registration/locale/da creating build/lib/registration/locale/da/LC_MESSAGES copying registration/locale/da/LC_MESSAGES/django.mo -> build/lib/registration/locale/da/LC_MESSAGES copying registration/locale/da/LC_MESSAGES/django.po -> build/lib/registration/locale/da/LC_MESSAGES creating build/lib/registration/locale/de creating build/lib/registration/locale/de/LC_MESSAGES copying registration/locale/de/LC_MESSAGES/django.mo -> build/lib/registration/locale/de/LC_MESSAGES copying registration/locale/de/LC_MESSAGES/django.po -> build/lib/registration/locale/de/LC_MESSAGES creating build/lib/registration/locale/el creating build/lib/registration/locale/el/LC_MESSAGES copying registration/locale/el/LC_MESSAGES/django.mo -> build/lib/registration/locale/el/LC_MESSAGES copying registration/locale/el/LC_MESSAGES/django.po -> build/lib/registration/locale/el/LC_MESSAGES creating build/lib/registration/locale/en creating build/lib/registration/locale/en/LC_MESSAGES copying registration/locale/en/LC_MESSAGES/django.mo -> build/lib/registration/locale/en/LC_MESSAGES copying registration/locale/en/LC_MESSAGES/django.po -> build/lib/registration/locale/en/LC_MESSAGES creating build/lib/registration/locale/es creating build/lib/registration/locale/es/LC_MESSAGES copying registration/locale/es/LC_MESSAGES/django.mo -> build/lib/registration/locale/es/LC_MESSAGES copying registration/locale/es/LC_MESSAGES/django.po -> build/lib/registration/locale/es/LC_MESSAGES creating build/lib/registration/locale/es_AR creating build/lib/registration/locale/es_AR/LC_MESSAGES copying registration/locale/es_AR/LC_MESSAGES/django.mo -> build/lib/registration/locale/es_AR/LC_MESSAGES copying registration/locale/es_AR/LC_MESSAGES/django.po -> build/lib/registration/locale/es_AR/LC_MESSAGES creating build/lib/registration/locale/fa creating build/lib/registration/locale/fa/LC_MESSAGES copying registration/locale/fa/LC_MESSAGES/django.mo -> build/lib/registration/locale/fa/LC_MESSAGES copying registration/locale/fa/LC_MESSAGES/django.po -> build/lib/registration/locale/fa/LC_MESSAGES creating build/lib/registration/locale/fr creating build/lib/registration/locale/fr/LC_MESSAGES copying registration/locale/fr/LC_MESSAGES/django.mo -> build/lib/registration/locale/fr/LC_MESSAGES copying registration/locale/fr/LC_MESSAGES/django.po -> build/lib/registration/locale/fr/LC_MESSAGES creating build/lib/registration/locale/he creating build/lib/registration/locale/he/LC_MESSAGES copying registration/locale/he/LC_MESSAGES/django.mo -> build/lib/registration/locale/he/LC_MESSAGES copying registration/locale/he/LC_MESSAGES/django.po -> build/lib/registration/locale/he/LC_MESSAGES creating build/lib/registration/locale/hr creating build/lib/registration/locale/hr/LC_MESSAGES copying registration/locale/hr/LC_MESSAGES/django.mo -> build/lib/registration/locale/hr/LC_MESSAGES copying registration/locale/hr/LC_MESSAGES/django.po -> build/lib/registration/locale/hr/LC_MESSAGES creating build/lib/registration/locale/is creating build/lib/registration/locale/is/LC_MESSAGES copying registration/locale/is/LC_MESSAGES/django.mo -> build/lib/registration/locale/is/LC_MESSAGES copying registration/locale/is/LC_MESSAGES/django.po -> build/lib/registration/locale/is/LC_MESSAGES creating build/lib/registration/locale/it creating build/lib/registration/locale/it/LC_MESSAGES copying registration/locale/it/LC_MESSAGES/django.mo -> build/lib/registration/locale/it/LC_MESSAGES copying registration/locale/it/LC_MESSAGES/django.po -> build/lib/registration/locale/it/LC_MESSAGES creating build/lib/registration/locale/ja creating build/lib/registration/locale/ja/LC_MESSAGES copying registration/locale/ja/LC_MESSAGES/django.mo -> build/lib/registration/locale/ja/LC_MESSAGES copying registration/locale/ja/LC_MESSAGES/django.po -> build/lib/registration/locale/ja/LC_MESSAGES creating build/lib/registration/locale/ko creating build/lib/registration/locale/ko/LC_MESSAGES copying registration/locale/ko/LC_MESSAGES/django.mo -> build/lib/registration/locale/ko/LC_MESSAGES copying registration/locale/ko/LC_MESSAGES/django.po -> build/lib/registration/locale/ko/LC_MESSAGES creating build/lib/registration/locale/nb creating build/lib/registration/locale/nb/LC_MESSAGES copying registration/locale/nb/LC_MESSAGES/django.mo -> build/lib/registration/locale/nb/LC_MESSAGES copying registration/locale/nb/LC_MESSAGES/django.po -> build/lib/registration/locale/nb/LC_MESSAGES creating build/lib/registration/locale/nl creating build/lib/registration/locale/nl/LC_MESSAGES copying registration/locale/nl/LC_MESSAGES/django.mo -> build/lib/registration/locale/nl/LC_MESSAGES copying registration/locale/nl/LC_MESSAGES/django.po -> build/lib/registration/locale/nl/LC_MESSAGES creating build/lib/registration/locale/pl creating build/lib/registration/locale/pl/LC_MESSAGES copying registration/locale/pl/LC_MESSAGES/django.mo -> build/lib/registration/locale/pl/LC_MESSAGES copying registration/locale/pl/LC_MESSAGES/django.po -> build/lib/registration/locale/pl/LC_MESSAGES creating build/lib/registration/locale/pt creating build/lib/registration/locale/pt/LC_MESSAGES copying registration/locale/pt/LC_MESSAGES/django.mo -> build/lib/registration/locale/pt/LC_MESSAGES copying registration/locale/pt/LC_MESSAGES/django.po -> build/lib/registration/locale/pt/LC_MESSAGES creating build/lib/registration/locale/pt_BR creating build/lib/registration/locale/pt_BR/LC_MESSAGES copying registration/locale/pt_BR/LC_MESSAGES/django.mo -> build/lib/registration/locale/pt_BR/LC_MESSAGES copying registration/locale/pt_BR/LC_MESSAGES/django.po -> build/lib/registration/locale/pt_BR/LC_MESSAGES creating build/lib/registration/locale/ru creating build/lib/registration/locale/ru/LC_MESSAGES copying registration/locale/ru/LC_MESSAGES/django.mo -> build/lib/registration/locale/ru/LC_MESSAGES copying registration/locale/ru/LC_MESSAGES/django.po -> build/lib/registration/locale/ru/LC_MESSAGES creating build/lib/registration/locale/sl creating build/lib/registration/locale/sl/LC_MESSAGES copying registration/locale/sl/LC_MESSAGES/django.mo -> build/lib/registration/locale/sl/LC_MESSAGES copying registration/locale/sl/LC_MESSAGES/django.po -> build/lib/registration/locale/sl/LC_MESSAGES creating build/lib/registration/locale/sr creating build/lib/registration/locale/sr/LC_MESSAGES copying registration/locale/sr/LC_MESSAGES/django.mo -> build/lib/registration/locale/sr/LC_MESSAGES copying registration/locale/sr/LC_MESSAGES/django.po -> build/lib/registration/locale/sr/LC_MESSAGES creating build/lib/registration/locale/sv creating build/lib/registration/locale/sv/LC_MESSAGES copying registration/locale/sv/LC_MESSAGES/django.mo -> build/lib/registration/locale/sv/LC_MESSAGES copying registration/locale/sv/LC_MESSAGES/django.po -> build/lib/registration/locale/sv/LC_MESSAGES creating build/lib/registration/locale/tr_TR creating build/lib/registration/locale/tr_TR/LC_MESSAGES copying registration/locale/tr_TR/LC_MESSAGES/django.mo -> build/lib/registration/locale/tr_TR/LC_MESSAGES copying registration/locale/tr_TR/LC_MESSAGES/django.po -> build/lib/registration/locale/tr_TR/LC_MESSAGES creating build/lib/registration/locale/zh_CN creating build/lib/registration/locale/zh_CN/LC_MESSAGES copying registration/locale/zh_CN/LC_MESSAGES/django.mo -> build/lib/registration/locale/zh_CN/LC_MESSAGES copying registration/locale/zh_CN/LC_MESSAGES/django.po -> build/lib/registration/locale/zh_CN/LC_MESSAGES creating build/lib/registration/locale/zh_TW creating build/lib/registration/locale/zh_TW/LC_MESSAGES copying registration/locale/zh_TW/LC_MESSAGES/django.mo -> build/lib/registration/locale/zh_TW/LC_MESSAGES copying registration/locale/zh_TW/LC_MESSAGES/django.po -> build/lib/registration/locale/zh_TW/LC_MESSAGES running install_lib creating /usr/local/lib/python3.4/dist-packages/test_app error: could not create '/usr/local/lib/python3.4/dist-packages/test_app': Permission denied ---------------------------------------- Cleaning up... Command /usr/bin/python3.4 -c "import setuptools, tokenize;__file__='/tmp/pip_build_alex/django-registration-redux/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-qi55qyaf-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_alex/django-registration-redux Storing debug log for failure in /home/alex/.pip/pip.log ```
2015/02/26
[ "https://Stackoverflow.com/questions/28747456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3541209/" ]
Autoprefixer doesn't run on it's own. It needs to be run as part of postcss-cli like so: `postcss --use autoprefixer *.css -d build/` (from <https://github.com/postcss/autoprefixer#cli>) Save-dev postcss-cli and then reformat your build:css to match `postcss --use autoprefixer -b 'last 2 versions' <assets/styles/main.css | cssmin > dist/main.css` Then let us know if you're still having problems.
In the case of autoprefixer 10 and before postcss-cli v8 released, just downgrade autoprefixer to ^9.8.6.
28,747,456
I am trying to install a python package using pip in linux mint but keep getting this error message. Anyone know how to fix this? ``` alex@alex-Satellite-C660D ~ $ pip install django-registration-redux Downloading/unpacking django-registration-redux Downloading django-registration-redux-1.1.tar.gz (63kB): 63kB downloaded Running setup.py (path:/tmp/pip_build_alex/django-registration-redux/setup.py) egg_info for package django-registration-redux no previously-included directories found matching 'docs/_build' Installing collected packages: django-registration-redux Running setup.py install for django-registration-redux no previously-included directories found matching 'docs/_build' error: could not create '/usr/local/lib/python3.4/dist-packages/test_app': Permission denied Complete output from command /usr/bin/python3.4 -c "import setuptools, tokenize;__file__='/tmp/pip_build_alex/django-registration-redux/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-qi55qyaf-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib creating build/lib/test_app copying test_app/__init__.py -> build/lib/test_app copying test_app/models.py -> build/lib/test_app copying test_app/urls_simple.py -> build/lib/test_app copying test_app/settings.py -> build/lib/test_app copying test_app/urls_default.py -> build/lib/test_app copying test_app/settings_test.py -> build/lib/test_app creating build/lib/registration copying registration/users.py -> build/lib/registration copying registration/views.py -> build/lib/registration copying registration/signals.py -> build/lib/registration copying registration/__init__.py -> build/lib/registration copying registration/forms.py -> build/lib/registration copying registration/auth_urls.py -> build/lib/registration copying registration/urls.py -> build/lib/registration copying registration/models.py -> build/lib/registration copying registration/admin.py -> build/lib/registration creating build/lib/registration/management copying registration/management/__init__.py -> build/lib/registration/management creating build/lib/registration/tests copying registration/tests/__init__.py -> build/lib/registration/tests copying registration/tests/forms.py -> build/lib/registration/tests copying registration/tests/urls.py -> build/lib/registration/tests copying registration/tests/simple_backend.py -> build/lib/registration/tests copying registration/tests/models.py -> build/lib/registration/tests copying registration/tests/default_backend.py -> build/lib/registration/tests creating build/lib/registration/backends copying registration/backends/__init__.py -> build/lib/registration/backends creating build/lib/registration/management/commands copying registration/management/commands/__init__.py -> build/lib/registration/management/commands copying registration/management/commands/cleanupregistration.py -> build/lib/registration/management/commands creating build/lib/registration/backends/default copying registration/backends/default/views.py -> build/lib/registration/backends/default copying registration/backends/default/__init__.py -> build/lib/registration/backends/default copying registration/backends/default/urls.py -> build/lib/registration/backends/default creating build/lib/registration/backends/simple copying registration/backends/simple/views.py -> build/lib/registration/backends/simple copying registration/backends/simple/__init__.py -> build/lib/registration/backends/simple copying registration/backends/simple/urls.py -> build/lib/registration/backends/simple running egg_info writing top-level names to django_registration_redux.egg-info/top_level.txt writing django_registration_redux.egg-info/PKG-INFO writing dependency_links to django_registration_redux.egg-info/dependency_links.txt warning: manifest_maker: standard file '-c' not found reading manifest file 'django_registration_redux.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' no previously-included directories found matching 'docs/_build' writing manifest file 'django_registration_redux.egg-info/SOURCES.txt' creating build/lib/registration/locale creating build/lib/registration/locale/ar creating build/lib/registration/locale/ar/LC_MESSAGES copying registration/locale/ar/LC_MESSAGES/django.mo -> build/lib/registration/locale/ar/LC_MESSAGES copying registration/locale/ar/LC_MESSAGES/django.po -> build/lib/registration/locale/ar/LC_MESSAGES creating build/lib/registration/locale/bg creating build/lib/registration/locale/bg/LC_MESSAGES copying registration/locale/bg/LC_MESSAGES/django.mo -> build/lib/registration/locale/bg/LC_MESSAGES copying registration/locale/bg/LC_MESSAGES/django.po -> build/lib/registration/locale/bg/LC_MESSAGES creating build/lib/registration/locale/ca creating build/lib/registration/locale/ca/LC_MESSAGES copying registration/locale/ca/LC_MESSAGES/django.mo -> build/lib/registration/locale/ca/LC_MESSAGES copying registration/locale/ca/LC_MESSAGES/django.po -> build/lib/registration/locale/ca/LC_MESSAGES creating build/lib/registration/locale/cs creating build/lib/registration/locale/cs/LC_MESSAGES copying registration/locale/cs/LC_MESSAGES/django.mo -> build/lib/registration/locale/cs/LC_MESSAGES copying registration/locale/cs/LC_MESSAGES/django.po -> build/lib/registration/locale/cs/LC_MESSAGES creating build/lib/registration/locale/da creating build/lib/registration/locale/da/LC_MESSAGES copying registration/locale/da/LC_MESSAGES/django.mo -> build/lib/registration/locale/da/LC_MESSAGES copying registration/locale/da/LC_MESSAGES/django.po -> build/lib/registration/locale/da/LC_MESSAGES creating build/lib/registration/locale/de creating build/lib/registration/locale/de/LC_MESSAGES copying registration/locale/de/LC_MESSAGES/django.mo -> build/lib/registration/locale/de/LC_MESSAGES copying registration/locale/de/LC_MESSAGES/django.po -> build/lib/registration/locale/de/LC_MESSAGES creating build/lib/registration/locale/el creating build/lib/registration/locale/el/LC_MESSAGES copying registration/locale/el/LC_MESSAGES/django.mo -> build/lib/registration/locale/el/LC_MESSAGES copying registration/locale/el/LC_MESSAGES/django.po -> build/lib/registration/locale/el/LC_MESSAGES creating build/lib/registration/locale/en creating build/lib/registration/locale/en/LC_MESSAGES copying registration/locale/en/LC_MESSAGES/django.mo -> build/lib/registration/locale/en/LC_MESSAGES copying registration/locale/en/LC_MESSAGES/django.po -> build/lib/registration/locale/en/LC_MESSAGES creating build/lib/registration/locale/es creating build/lib/registration/locale/es/LC_MESSAGES copying registration/locale/es/LC_MESSAGES/django.mo -> build/lib/registration/locale/es/LC_MESSAGES copying registration/locale/es/LC_MESSAGES/django.po -> build/lib/registration/locale/es/LC_MESSAGES creating build/lib/registration/locale/es_AR creating build/lib/registration/locale/es_AR/LC_MESSAGES copying registration/locale/es_AR/LC_MESSAGES/django.mo -> build/lib/registration/locale/es_AR/LC_MESSAGES copying registration/locale/es_AR/LC_MESSAGES/django.po -> build/lib/registration/locale/es_AR/LC_MESSAGES creating build/lib/registration/locale/fa creating build/lib/registration/locale/fa/LC_MESSAGES copying registration/locale/fa/LC_MESSAGES/django.mo -> build/lib/registration/locale/fa/LC_MESSAGES copying registration/locale/fa/LC_MESSAGES/django.po -> build/lib/registration/locale/fa/LC_MESSAGES creating build/lib/registration/locale/fr creating build/lib/registration/locale/fr/LC_MESSAGES copying registration/locale/fr/LC_MESSAGES/django.mo -> build/lib/registration/locale/fr/LC_MESSAGES copying registration/locale/fr/LC_MESSAGES/django.po -> build/lib/registration/locale/fr/LC_MESSAGES creating build/lib/registration/locale/he creating build/lib/registration/locale/he/LC_MESSAGES copying registration/locale/he/LC_MESSAGES/django.mo -> build/lib/registration/locale/he/LC_MESSAGES copying registration/locale/he/LC_MESSAGES/django.po -> build/lib/registration/locale/he/LC_MESSAGES creating build/lib/registration/locale/hr creating build/lib/registration/locale/hr/LC_MESSAGES copying registration/locale/hr/LC_MESSAGES/django.mo -> build/lib/registration/locale/hr/LC_MESSAGES copying registration/locale/hr/LC_MESSAGES/django.po -> build/lib/registration/locale/hr/LC_MESSAGES creating build/lib/registration/locale/is creating build/lib/registration/locale/is/LC_MESSAGES copying registration/locale/is/LC_MESSAGES/django.mo -> build/lib/registration/locale/is/LC_MESSAGES copying registration/locale/is/LC_MESSAGES/django.po -> build/lib/registration/locale/is/LC_MESSAGES creating build/lib/registration/locale/it creating build/lib/registration/locale/it/LC_MESSAGES copying registration/locale/it/LC_MESSAGES/django.mo -> build/lib/registration/locale/it/LC_MESSAGES copying registration/locale/it/LC_MESSAGES/django.po -> build/lib/registration/locale/it/LC_MESSAGES creating build/lib/registration/locale/ja creating build/lib/registration/locale/ja/LC_MESSAGES copying registration/locale/ja/LC_MESSAGES/django.mo -> build/lib/registration/locale/ja/LC_MESSAGES copying registration/locale/ja/LC_MESSAGES/django.po -> build/lib/registration/locale/ja/LC_MESSAGES creating build/lib/registration/locale/ko creating build/lib/registration/locale/ko/LC_MESSAGES copying registration/locale/ko/LC_MESSAGES/django.mo -> build/lib/registration/locale/ko/LC_MESSAGES copying registration/locale/ko/LC_MESSAGES/django.po -> build/lib/registration/locale/ko/LC_MESSAGES creating build/lib/registration/locale/nb creating build/lib/registration/locale/nb/LC_MESSAGES copying registration/locale/nb/LC_MESSAGES/django.mo -> build/lib/registration/locale/nb/LC_MESSAGES copying registration/locale/nb/LC_MESSAGES/django.po -> build/lib/registration/locale/nb/LC_MESSAGES creating build/lib/registration/locale/nl creating build/lib/registration/locale/nl/LC_MESSAGES copying registration/locale/nl/LC_MESSAGES/django.mo -> build/lib/registration/locale/nl/LC_MESSAGES copying registration/locale/nl/LC_MESSAGES/django.po -> build/lib/registration/locale/nl/LC_MESSAGES creating build/lib/registration/locale/pl creating build/lib/registration/locale/pl/LC_MESSAGES copying registration/locale/pl/LC_MESSAGES/django.mo -> build/lib/registration/locale/pl/LC_MESSAGES copying registration/locale/pl/LC_MESSAGES/django.po -> build/lib/registration/locale/pl/LC_MESSAGES creating build/lib/registration/locale/pt creating build/lib/registration/locale/pt/LC_MESSAGES copying registration/locale/pt/LC_MESSAGES/django.mo -> build/lib/registration/locale/pt/LC_MESSAGES copying registration/locale/pt/LC_MESSAGES/django.po -> build/lib/registration/locale/pt/LC_MESSAGES creating build/lib/registration/locale/pt_BR creating build/lib/registration/locale/pt_BR/LC_MESSAGES copying registration/locale/pt_BR/LC_MESSAGES/django.mo -> build/lib/registration/locale/pt_BR/LC_MESSAGES copying registration/locale/pt_BR/LC_MESSAGES/django.po -> build/lib/registration/locale/pt_BR/LC_MESSAGES creating build/lib/registration/locale/ru creating build/lib/registration/locale/ru/LC_MESSAGES copying registration/locale/ru/LC_MESSAGES/django.mo -> build/lib/registration/locale/ru/LC_MESSAGES copying registration/locale/ru/LC_MESSAGES/django.po -> build/lib/registration/locale/ru/LC_MESSAGES creating build/lib/registration/locale/sl creating build/lib/registration/locale/sl/LC_MESSAGES copying registration/locale/sl/LC_MESSAGES/django.mo -> build/lib/registration/locale/sl/LC_MESSAGES copying registration/locale/sl/LC_MESSAGES/django.po -> build/lib/registration/locale/sl/LC_MESSAGES creating build/lib/registration/locale/sr creating build/lib/registration/locale/sr/LC_MESSAGES copying registration/locale/sr/LC_MESSAGES/django.mo -> build/lib/registration/locale/sr/LC_MESSAGES copying registration/locale/sr/LC_MESSAGES/django.po -> build/lib/registration/locale/sr/LC_MESSAGES creating build/lib/registration/locale/sv creating build/lib/registration/locale/sv/LC_MESSAGES copying registration/locale/sv/LC_MESSAGES/django.mo -> build/lib/registration/locale/sv/LC_MESSAGES copying registration/locale/sv/LC_MESSAGES/django.po -> build/lib/registration/locale/sv/LC_MESSAGES creating build/lib/registration/locale/tr_TR creating build/lib/registration/locale/tr_TR/LC_MESSAGES copying registration/locale/tr_TR/LC_MESSAGES/django.mo -> build/lib/registration/locale/tr_TR/LC_MESSAGES copying registration/locale/tr_TR/LC_MESSAGES/django.po -> build/lib/registration/locale/tr_TR/LC_MESSAGES creating build/lib/registration/locale/zh_CN creating build/lib/registration/locale/zh_CN/LC_MESSAGES copying registration/locale/zh_CN/LC_MESSAGES/django.mo -> build/lib/registration/locale/zh_CN/LC_MESSAGES copying registration/locale/zh_CN/LC_MESSAGES/django.po -> build/lib/registration/locale/zh_CN/LC_MESSAGES creating build/lib/registration/locale/zh_TW creating build/lib/registration/locale/zh_TW/LC_MESSAGES copying registration/locale/zh_TW/LC_MESSAGES/django.mo -> build/lib/registration/locale/zh_TW/LC_MESSAGES copying registration/locale/zh_TW/LC_MESSAGES/django.po -> build/lib/registration/locale/zh_TW/LC_MESSAGES running install_lib creating /usr/local/lib/python3.4/dist-packages/test_app error: could not create '/usr/local/lib/python3.4/dist-packages/test_app': Permission denied ---------------------------------------- Cleaning up... Command /usr/bin/python3.4 -c "import setuptools, tokenize;__file__='/tmp/pip_build_alex/django-registration-redux/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-qi55qyaf-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_alex/django-registration-redux Storing debug log for failure in /home/alex/.pip/pip.log ```
2015/02/26
[ "https://Stackoverflow.com/questions/28747456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3541209/" ]
Installation: `npm install -g postcss-cli autoprefixer` Usage (order matters!): `postcss main.css -u autoprefixer -d dist/`
In the case of autoprefixer 10 and before postcss-cli v8 released, just downgrade autoprefixer to ^9.8.6.
11,729,662
``` print'Personal information, journal and more to come' x = raw_input() if x ==("Personal Information"): # wont print print' Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN: , SS:' elif x ==("Journal"): # wont print read = open('C:\\python\\foo.txt' , 'r') name = read.readline() print (name) ``` I start the program and `"Personal information, journal and more to come"` shows but when I type either `Personal information` or `journal neither` of them print the result and I'm not getting any errors.
2012/07/30
[ "https://Stackoverflow.com/questions/11729662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1564130/" ]
> > when i type either Personal information or journal > > > Well, yeah. It isn't expecting either of those; your case is wrong. To perform a case-insensitive comparison, convert both to the same case first. ``` if foo.lower() == bar.lower(): ```
Works for me. Are you writing "Personal Information" with a capital I? ``` print'Personal information, journal and more to come' x = raw_input() if x == ("Personal Information"): # wont print print' Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN: , SS:' elif x ==("Journal"): # wont print read = open('C:\\python\\foo.txt' , 'r') name = read.readline() print (name) ``` output: ``` [00:20: ~$] python py Personal information, journal and more to come Journal Traceback (most recent call last): File "py", line 8, in <module> read = open('C:\\python\\foo.txt' , 'r') IOError: [Errno 2] No such file or directory: 'C:\\python\\foo.txt' [00:20: ~$] python py Personal information, journal and more to come Personal Information Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN: , SS: [00:20: ~$] ``` Perhaps it's the formatting? I'm using 4 white spaces.
11,729,662
``` print'Personal information, journal and more to come' x = raw_input() if x ==("Personal Information"): # wont print print' Edward , Height: 5,10 , EYES: brown , STATE: IL TOWN: , SS:' elif x ==("Journal"): # wont print read = open('C:\\python\\foo.txt' , 'r') name = read.readline() print (name) ``` I start the program and `"Personal information, journal and more to come"` shows but when I type either `Personal information` or `journal neither` of them print the result and I'm not getting any errors.
2012/07/30
[ "https://Stackoverflow.com/questions/11729662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1564130/" ]
> > when i type either Personal information or journal > > > Well, yeah. It isn't expecting either of those; your case is wrong. To perform a case-insensitive comparison, convert both to the same case first. ``` if foo.lower() == bar.lower(): ```
You are typing in Personal information, when the if statement is expecting Personal Information (with a capital I for information). What you can do (what Ignacio above is eluding to) is do: ``` if x.lower() == ("Personal Information").lower(): ``` instead of: ``` if x == ("Personal Information"): ``` then any case, "Personal information", "personal information", "personAL infoRmation", and so on, will match and go into the if statement. The reason this works is because when this executes, it will take the value of x, and make it a lowercase string, and the string "Personal information" and make it a lowercase string, so now no matter what the case originally was, they both will be lowercase when comparing. foo and bar are examples, common programming nomenclature in programming. It is just an example of any variable, x, y, z, etc, could have been used just as easily, but foo and bar are just common variables to refer to.
47,705,274
I am learning bare metal programming in c++ and it often involves setting a portion of a 32 bit hardware register address to some combination. For example for an IO pin, I can set the 15th to 17th bit in a 32 bit address to `001` to mark the pin as an output pin. I have seen code that does this and I half understand it based on an explanation of another [SO question.](https://stackoverflow.com/a/6917002/1158977) ``` # here ra is a physical address # the 15th to 17th bits are being # cleared by AND-ing it with a value that is one everywhere # except in the 15th to 17th bits ra&=~(7<<12); ``` Another example is: ``` # this clears the 21st to 23rd bits of another address ra&=~(7<<21); ``` How do I choose the **7** and how do I choose the number of bits to shift left? I tried this out in **python** to see if I can figure it out ``` bin((7<<21)).lstrip('-0b').zfill(32) '00000000111000000000000000000000' # this has 8, 9 and 10 as the bits which is wrong ```
2017/12/07
[ "https://Stackoverflow.com/questions/47705274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1158977/" ]
The 7 (base 10) is chosen as its binary representation is 111 (7 in base 2). As for why it's bits 8, 9 and 10 set it's because you're reading from the wrong direction. Binary, just as normal base 10, counts right to left. (I'd left this as a comment but reputation isn't high enough.)
> > How do I choose the 7 > > > You want to clear three adjacent bits. Three adjacent bits at the bottom of a word is 1+2+4=7. > > and how do I choose the number of bits to shift left > > > You want to clear bits 21-23, not bits 1-3, so you shift left another 20. Both your examples are wrong. To clear 15-17 you need to shift left 14, and to clear 21-23 you need to shift left 20. > > this has 8, 9,and 10 ... > > > No it doesn't. You're counting from the wrong end.
47,705,274
I am learning bare metal programming in c++ and it often involves setting a portion of a 32 bit hardware register address to some combination. For example for an IO pin, I can set the 15th to 17th bit in a 32 bit address to `001` to mark the pin as an output pin. I have seen code that does this and I half understand it based on an explanation of another [SO question.](https://stackoverflow.com/a/6917002/1158977) ``` # here ra is a physical address # the 15th to 17th bits are being # cleared by AND-ing it with a value that is one everywhere # except in the 15th to 17th bits ra&=~(7<<12); ``` Another example is: ``` # this clears the 21st to 23rd bits of another address ra&=~(7<<21); ``` How do I choose the **7** and how do I choose the number of bits to shift left? I tried this out in **python** to see if I can figure it out ``` bin((7<<21)).lstrip('-0b').zfill(32) '00000000111000000000000000000000' # this has 8, 9 and 10 as the bits which is wrong ```
2017/12/07
[ "https://Stackoverflow.com/questions/47705274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1158977/" ]
If you want to isolate and change some bits in a register but not all you need to understand the bitwise operations like and and or and xor and not operate on a single bit column, bit 3 of each operand is used to determine bit 3 of the result, no other bits are involved. So I have some bits in binary represented by letters since they can each either be a 1 or zero ``` jklmnopq ``` The and operation truth table you can look up, anything anded with zero is a zero anything anded with one is itself ``` jklmnopq & 01110001 ============ 0klm000q ``` anything orred with one is a one anything orred with zero is itself. ``` jklmnopq | 01110001 ============ j111nop1 ``` so if you want to isolate and change two bits in this variable/register say bits 5 and 6 and change them to be a 0b10 (a 2 in decimal), the common method is to and them with zero then or them with the desired value ``` 76543210 jklmnopq & 10011111 ============ j00mnopq jklmnopq | 01000000 ============ j10mnopq ``` you could have orred bit 6 with a 1 and anded bit 5 with a zero, but that is specific to the value you wanted to change them to, generically we think I want to change those bits to a 2, so to use that value 2 you want to zero the bits then force the 2 onto those bits, and them to make them zero then orr the 2 onto the bits. generic. In c ``` x = read_register(blah); x = (x&(~(3<<5)))|(2<<5); write_register(blah,x); ``` lets dig into this (3 << 5) ``` 00000011 00000110 1 00001100 2 00011000 3 00110000 4 01100000 5 76543210 ``` that puts two ones on top of the bits we are interested in but anding with that value isolates the bits and messes up the others so to zero those and not mess with the other bits in the register we need to invert those bits using x = ~x inverts those bits a logical not operation. ``` 01100000 10011111 ``` Now we have the mask we want to and with our register as shown way above, zeroing the bits in question while leaving the others alone j00mnopq Now we need to prep the bits to or (2<<5) ``` 00000010 00000100 1 00001000 2 00010000 3 00100000 4 01000000 5 ``` Giving the bit pattern we want to orr in giving j10mnopq which we write back to the register. Again the j, m, n, ... bits are bits they are either a one or a zero and we dont want to change them so we do this extra masking and shifting work. You may/will sometimes see examples that simply write\_register(blah,2<<5); either because they know the state of the other bits, know they are not using those other bits and zero is okay/desired or dont know what they are doing. ``` x read_register(blah); //bits are jklmnopq x = (x&(~(3<<5)))|(2<<5); z = 3 z = z << 5 z = ~z x = x & z z = 2 z = z << 5 x = x | z z = 3 z = 00000011 z = z << 5 z = 01100000 z = ~z z = 10011111 x = x & z x = j00mnopq z = 2 z = 00000010 z = z << 5 z = 01000000 x = x | z x = j10mnopq ``` if you have a 3 bit field then the binary is 0b111 which in decimal is the number 7 or hex 0x7. a 4 bit field 0b1111 which is decimal 15 or hex 0xF, as you get past 7 it is easier to use hex IMO. 6 bit field 0x3F, 7 bit field 0x7F and so on. You can take this further in a way to try to be more generic. If there is a register that controls some function for gpio pins 0 through say 15. starting with bit 0. If you wanted to change the properties for gpio pin 5 then that would be bits 10 and 11, 5\*2 = 10 there are two pins so 10 and the next one 11. But generically you could: ``` x = (x&(~(0x3<<(pin*2)))) | (value<<(pin*2)); ``` since 2 is a power of 2 ``` x = (x&(~(0x3<<(pin<<1)))) | (value<<(pin<<1)); ``` an optimization the compiler might do for if pin cannot be reduced to a specific value at compile time. but if it were 3 bits per field and the fields start aligned with bit zero ``` x = (x&(~(0x7<<(pin*3)))) | (value<<(pin*3)); ``` which the compiler might do a multiply by 3 but maybe instead just pinshift = (pinshift<<1)|pinshift; to get the multiply by three. depends on the compiler and instruction set. overall this is called a read modify write as you read something, modify some of it, then write back (if you were modifying all of it you wouldnt need to bother with a read and a modify you would write the whole new value). And folks will say masking and shifting to generically cover isolating bits in a variable either for modification purposes or if you wanted to read/see what those two bits above were you would ``` x = read_register(blah); x = x >> 5; x = x & 0x3; ``` or mask first then shift ``` x = x & (0x3<<5); x = x >> 5; ``` six of one half a dozen of another, both are equal in general, some instruction sets one might be more efficient than another (or might be equal and then shift, or shift then and). One might make more sense visually to some folks rather than the other. Although technically this is an endian thing as some processors bit 0 is the most significant bit. In C AFAIK bit 0 is the least significant bit. If/when a manual shows the bits laid out left to right you want your right and left shifts to match that, so as above I showed 76543210 to indicate the documented bits and associated that with jklmnopq and that was the left to right information that mattered to continue the conversation about modifying bits 5 and 6. some documents will use verilog or vhdl style notation 6:5 (meaning bits 6 to 5 inclusive, makes more sense with say 4:2 meaning bits 4,3,2) or [6 downto 5], more likely to just see a visual picture with boxes or lines to show you what bits are what field.
> > How do I choose the 7 > > > You want to clear three adjacent bits. Three adjacent bits at the bottom of a word is 1+2+4=7. > > and how do I choose the number of bits to shift left > > > You want to clear bits 21-23, not bits 1-3, so you shift left another 20. Both your examples are wrong. To clear 15-17 you need to shift left 14, and to clear 21-23 you need to shift left 20. > > this has 8, 9,and 10 ... > > > No it doesn't. You're counting from the wrong end.
32,625,597
I am having trouble getting this python code to work right. it is a code to display pascal's triangle using binomials. I do not know what is wrong. The code looks like this ``` from math import factorial def binomial (n,k): if k==0: return 1 else: return int((factorial(n)//factorial(k))*factorial(n-k)) def pascals_triangle(rows): rows=20 for n in range (0,rows): for k in range (0,n+1): print(binomial(n,k)) print '\n' ``` This is what it keeps printing ``` 1 1 1 1 2 1 1 12 3 1 1 144 24 4 1 1 2880 360 40 5 1 1 86400 8640 720 60 6 1 1 3628800 302400 20160 1260 ``` and on and on. any help would be welcomed.!!
2015/09/17
[ "https://Stackoverflow.com/questions/32625597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345562/" ]
You can use ``` SELECT id, date, product_id, sales FROM sales LIMIT X OFFSET Y; ``` where X is the size of the batch you need and Y is current offset (X times number of current iterations for example)
To expand on akalikin's answer, you can use a stepped iteration to split the query into chunks, and then use LIMIT and OFFSET to execute the query. ``` cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT COUNT(*) FROM sales") for i in range(0,cur.fetchall(),5): cur2 = con.cursor(mdb.cursors.DictCursor) cur2.execute("SELECT id, date, product_id, sales FROM sales LIMIT %s OFFSET %s" %(5,i)) rows = cur2.fetchall() print rows ```
32,625,597
I am having trouble getting this python code to work right. it is a code to display pascal's triangle using binomials. I do not know what is wrong. The code looks like this ``` from math import factorial def binomial (n,k): if k==0: return 1 else: return int((factorial(n)//factorial(k))*factorial(n-k)) def pascals_triangle(rows): rows=20 for n in range (0,rows): for k in range (0,n+1): print(binomial(n,k)) print '\n' ``` This is what it keeps printing ``` 1 1 1 1 2 1 1 12 3 1 1 144 24 4 1 1 2880 360 40 5 1 1 86400 8640 720 60 6 1 1 3628800 302400 20160 1260 ``` and on and on. any help would be welcomed.!!
2015/09/17
[ "https://Stackoverflow.com/questions/32625597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345562/" ]
First point: a python `db-api.cursor` is an iterator, so unless you really **need** to load a whole batch in memory at once, you can just start with using this feature, ie instead of: ``` cursor.execute("SELECT * FROM mytable") rows = cursor.fetchall() for row in rows: do_something_with(row) ``` you could just: ``` cursor.execute("SELECT * FROM mytable") for row in cursor: do_something_with(row) ``` Then if your db connector's implementation still doesn't make proper use of this feature, it will be time to add LIMIT and OFFSET to the mix: ``` # py2 / py3 compat try: # xrange is defined in py2 only xrange except NameError: # py3 range is actually p2 xrange xrange = range cursor.execute("SELECT count(*) FROM mytable") count = cursor.fetchone()[0] batch_size = 42 # whatever for offset in xrange(0, count, batch_size): cursor.execute( "SELECT * FROM mytable LIMIT %s OFFSET %s", (batch_size, offset)) for row in cursor: do_something_with(row) ```
You can use ``` SELECT id, date, product_id, sales FROM sales LIMIT X OFFSET Y; ``` where X is the size of the batch you need and Y is current offset (X times number of current iterations for example)
32,625,597
I am having trouble getting this python code to work right. it is a code to display pascal's triangle using binomials. I do not know what is wrong. The code looks like this ``` from math import factorial def binomial (n,k): if k==0: return 1 else: return int((factorial(n)//factorial(k))*factorial(n-k)) def pascals_triangle(rows): rows=20 for n in range (0,rows): for k in range (0,n+1): print(binomial(n,k)) print '\n' ``` This is what it keeps printing ``` 1 1 1 1 2 1 1 12 3 1 1 144 24 4 1 1 2880 360 40 5 1 1 86400 8640 720 60 6 1 1 3628800 302400 20160 1260 ``` and on and on. any help would be welcomed.!!
2015/09/17
[ "https://Stackoverflow.com/questions/32625597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345562/" ]
You can use ``` SELECT id, date, product_id, sales FROM sales LIMIT X OFFSET Y; ``` where X is the size of the batch you need and Y is current offset (X times number of current iterations for example)
Thank you, here's how I implement it with your suggestions: ``` control = True index = 0 while control==True: getconn = conexiones() con = getconn.mysqlDWconnect() with con: cur = con.cursor(mdb.cursors.DictCursor) query = "SELECT id, date, product_id, sales FROM sales limit 10 OFFSET " + str(10 * (index)) cur.execute(query) rows = cur.fetchall() index = index+1 if len(rows)== 0: control=False for row in rows: dataset.append(row) ```
32,625,597
I am having trouble getting this python code to work right. it is a code to display pascal's triangle using binomials. I do not know what is wrong. The code looks like this ``` from math import factorial def binomial (n,k): if k==0: return 1 else: return int((factorial(n)//factorial(k))*factorial(n-k)) def pascals_triangle(rows): rows=20 for n in range (0,rows): for k in range (0,n+1): print(binomial(n,k)) print '\n' ``` This is what it keeps printing ``` 1 1 1 1 2 1 1 12 3 1 1 144 24 4 1 1 2880 360 40 5 1 1 86400 8640 720 60 6 1 1 3628800 302400 20160 1260 ``` and on and on. any help would be welcomed.!!
2015/09/17
[ "https://Stackoverflow.com/questions/32625597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345562/" ]
First point: a python `db-api.cursor` is an iterator, so unless you really **need** to load a whole batch in memory at once, you can just start with using this feature, ie instead of: ``` cursor.execute("SELECT * FROM mytable") rows = cursor.fetchall() for row in rows: do_something_with(row) ``` you could just: ``` cursor.execute("SELECT * FROM mytable") for row in cursor: do_something_with(row) ``` Then if your db connector's implementation still doesn't make proper use of this feature, it will be time to add LIMIT and OFFSET to the mix: ``` # py2 / py3 compat try: # xrange is defined in py2 only xrange except NameError: # py3 range is actually p2 xrange xrange = range cursor.execute("SELECT count(*) FROM mytable") count = cursor.fetchone()[0] batch_size = 42 # whatever for offset in xrange(0, count, batch_size): cursor.execute( "SELECT * FROM mytable LIMIT %s OFFSET %s", (batch_size, offset)) for row in cursor: do_something_with(row) ```
To expand on akalikin's answer, you can use a stepped iteration to split the query into chunks, and then use LIMIT and OFFSET to execute the query. ``` cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT COUNT(*) FROM sales") for i in range(0,cur.fetchall(),5): cur2 = con.cursor(mdb.cursors.DictCursor) cur2.execute("SELECT id, date, product_id, sales FROM sales LIMIT %s OFFSET %s" %(5,i)) rows = cur2.fetchall() print rows ```
32,625,597
I am having trouble getting this python code to work right. it is a code to display pascal's triangle using binomials. I do not know what is wrong. The code looks like this ``` from math import factorial def binomial (n,k): if k==0: return 1 else: return int((factorial(n)//factorial(k))*factorial(n-k)) def pascals_triangle(rows): rows=20 for n in range (0,rows): for k in range (0,n+1): print(binomial(n,k)) print '\n' ``` This is what it keeps printing ``` 1 1 1 1 2 1 1 12 3 1 1 144 24 4 1 1 2880 360 40 5 1 1 86400 8640 720 60 6 1 1 3628800 302400 20160 1260 ``` and on and on. any help would be welcomed.!!
2015/09/17
[ "https://Stackoverflow.com/questions/32625597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345562/" ]
To expand on akalikin's answer, you can use a stepped iteration to split the query into chunks, and then use LIMIT and OFFSET to execute the query. ``` cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT COUNT(*) FROM sales") for i in range(0,cur.fetchall(),5): cur2 = con.cursor(mdb.cursors.DictCursor) cur2.execute("SELECT id, date, product_id, sales FROM sales LIMIT %s OFFSET %s" %(5,i)) rows = cur2.fetchall() print rows ```
Thank you, here's how I implement it with your suggestions: ``` control = True index = 0 while control==True: getconn = conexiones() con = getconn.mysqlDWconnect() with con: cur = con.cursor(mdb.cursors.DictCursor) query = "SELECT id, date, product_id, sales FROM sales limit 10 OFFSET " + str(10 * (index)) cur.execute(query) rows = cur.fetchall() index = index+1 if len(rows)== 0: control=False for row in rows: dataset.append(row) ```
32,625,597
I am having trouble getting this python code to work right. it is a code to display pascal's triangle using binomials. I do not know what is wrong. The code looks like this ``` from math import factorial def binomial (n,k): if k==0: return 1 else: return int((factorial(n)//factorial(k))*factorial(n-k)) def pascals_triangle(rows): rows=20 for n in range (0,rows): for k in range (0,n+1): print(binomial(n,k)) print '\n' ``` This is what it keeps printing ``` 1 1 1 1 2 1 1 12 3 1 1 144 24 4 1 1 2880 360 40 5 1 1 86400 8640 720 60 6 1 1 3628800 302400 20160 1260 ``` and on and on. any help would be welcomed.!!
2015/09/17
[ "https://Stackoverflow.com/questions/32625597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345562/" ]
First point: a python `db-api.cursor` is an iterator, so unless you really **need** to load a whole batch in memory at once, you can just start with using this feature, ie instead of: ``` cursor.execute("SELECT * FROM mytable") rows = cursor.fetchall() for row in rows: do_something_with(row) ``` you could just: ``` cursor.execute("SELECT * FROM mytable") for row in cursor: do_something_with(row) ``` Then if your db connector's implementation still doesn't make proper use of this feature, it will be time to add LIMIT and OFFSET to the mix: ``` # py2 / py3 compat try: # xrange is defined in py2 only xrange except NameError: # py3 range is actually p2 xrange xrange = range cursor.execute("SELECT count(*) FROM mytable") count = cursor.fetchone()[0] batch_size = 42 # whatever for offset in xrange(0, count, batch_size): cursor.execute( "SELECT * FROM mytable LIMIT %s OFFSET %s", (batch_size, offset)) for row in cursor: do_something_with(row) ```
Thank you, here's how I implement it with your suggestions: ``` control = True index = 0 while control==True: getconn = conexiones() con = getconn.mysqlDWconnect() with con: cur = con.cursor(mdb.cursors.DictCursor) query = "SELECT id, date, product_id, sales FROM sales limit 10 OFFSET " + str(10 * (index)) cur.execute(query) rows = cur.fetchall() index = index+1 if len(rows)== 0: control=False for row in rows: dataset.append(row) ```
35,894,511
When i run ``` pip install --upgrade pip ``` I get this error message: ``` Collecting pip Downloading pip-8.1.0-py2.py3-none-any.whl (1.2MB) 100% |████████████████████████████████| 1.2MB 371kB/s Installing collected packages: pip Found existing installation: pip 8.0.2 Uninstalling pip-8.0.2: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 725, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 752, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py",line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 266, in renames shutil.move(old, new) File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site- packages/pip-8.0.2.dist-info/DESCRIPTION.rst' ``` Previously I had been struggling to install and run a couple of python modules so I remember moving files around a bit. Is that what has caused this error? How can I fix this? I am on Mac. I was trying to install bs4 prior to this and I got similar error messages. (But i suspect the bs4 install has more issues so that's another question for later). Also sorry for any format issues with the code. Have tried my best to make it look like it is on the terminal. Thanks.
2016/03/09
[ "https://Stackoverflow.com/questions/35894511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5827690/" ]
A permission issue means your user privileges don't allow you to write on the desired folder(`/Library/Python/2.7/site-packages/pip/`). There's basically two things you can do: 1. run pip as sudo: ``` sudo pip install --upgrade pip ``` 2. Configure pip to install only for the current user, as covered [here](https://stackoverflow.com/questions/7143077/how-can-i-install-packages-in-my-home-folder-with-pip) and [here](https://scicomp.stackexchange.com/questions/2987/what-is-the-simplest-way-to-do-a-user-local-install-of-a-python-package).
From administrator mode command prompt, you can run the following command, that should fix the issue: ``` python -m ensurepip --user ``` Replace python3 if your version supports that.
35,894,511
When i run ``` pip install --upgrade pip ``` I get this error message: ``` Collecting pip Downloading pip-8.1.0-py2.py3-none-any.whl (1.2MB) 100% |████████████████████████████████| 1.2MB 371kB/s Installing collected packages: pip Found existing installation: pip 8.0.2 Uninstalling pip-8.0.2: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 725, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 752, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py",line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 266, in renames shutil.move(old, new) File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site- packages/pip-8.0.2.dist-info/DESCRIPTION.rst' ``` Previously I had been struggling to install and run a couple of python modules so I remember moving files around a bit. Is that what has caused this error? How can I fix this? I am on Mac. I was trying to install bs4 prior to this and I got similar error messages. (But i suspect the bs4 install has more issues so that's another question for later). Also sorry for any format issues with the code. Have tried my best to make it look like it is on the terminal. Thanks.
2016/03/09
[ "https://Stackoverflow.com/questions/35894511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5827690/" ]
A permission issue means your user privileges don't allow you to write on the desired folder(`/Library/Python/2.7/site-packages/pip/`). There's basically two things you can do: 1. run pip as sudo: ``` sudo pip install --upgrade pip ``` 2. Configure pip to install only for the current user, as covered [here](https://stackoverflow.com/questions/7143077/how-can-i-install-packages-in-my-home-folder-with-pip) and [here](https://scicomp.stackexchange.com/questions/2987/what-is-the-simplest-way-to-do-a-user-local-install-of-a-python-package).
The best way to do it is as follows: ``` $ python3 -m pip install --upgrade pip ``` as it's generally not advised to use ``` $ sudo pip install ``` More answers can be found here: <https://github.com/pypa/pip/issues/5599>
35,894,511
When i run ``` pip install --upgrade pip ``` I get this error message: ``` Collecting pip Downloading pip-8.1.0-py2.py3-none-any.whl (1.2MB) 100% |████████████████████████████████| 1.2MB 371kB/s Installing collected packages: pip Found existing installation: pip 8.0.2 Uninstalling pip-8.0.2: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 725, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 752, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py",line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 266, in renames shutil.move(old, new) File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site- packages/pip-8.0.2.dist-info/DESCRIPTION.rst' ``` Previously I had been struggling to install and run a couple of python modules so I remember moving files around a bit. Is that what has caused this error? How can I fix this? I am on Mac. I was trying to install bs4 prior to this and I got similar error messages. (But i suspect the bs4 install has more issues so that's another question for later). Also sorry for any format issues with the code. Have tried my best to make it look like it is on the terminal. Thanks.
2016/03/09
[ "https://Stackoverflow.com/questions/35894511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5827690/" ]
A permission issue means your user privileges don't allow you to write on the desired folder(`/Library/Python/2.7/site-packages/pip/`). There's basically two things you can do: 1. run pip as sudo: ``` sudo pip install --upgrade pip ``` 2. Configure pip to install only for the current user, as covered [here](https://stackoverflow.com/questions/7143077/how-can-i-install-packages-in-my-home-folder-with-pip) and [here](https://scicomp.stackexchange.com/questions/2987/what-is-the-simplest-way-to-do-a-user-local-install-of-a-python-package).
``` DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirement.txt' WARNING: You are using pip version 19.2.3, however version 20.3.4 is available. You should consider upgrading via the 'pip install --upgrade pip' command. $ pip install pip Requirement already satisfied: pip in /data/data/com.termux/files/usr/lib/python3.9/site-packages (21.0.1) ``` Showing like this help !!!
35,894,511
When i run ``` pip install --upgrade pip ``` I get this error message: ``` Collecting pip Downloading pip-8.1.0-py2.py3-none-any.whl (1.2MB) 100% |████████████████████████████████| 1.2MB 371kB/s Installing collected packages: pip Found existing installation: pip 8.0.2 Uninstalling pip-8.0.2: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 725, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 752, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py",line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 266, in renames shutil.move(old, new) File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site- packages/pip-8.0.2.dist-info/DESCRIPTION.rst' ``` Previously I had been struggling to install and run a couple of python modules so I remember moving files around a bit. Is that what has caused this error? How can I fix this? I am on Mac. I was trying to install bs4 prior to this and I got similar error messages. (But i suspect the bs4 install has more issues so that's another question for later). Also sorry for any format issues with the code. Have tried my best to make it look like it is on the terminal. Thanks.
2016/03/09
[ "https://Stackoverflow.com/questions/35894511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5827690/" ]
The best way to do it is as follows: ``` $ python3 -m pip install --upgrade pip ``` as it's generally not advised to use ``` $ sudo pip install ``` More answers can be found here: <https://github.com/pypa/pip/issues/5599>
From administrator mode command prompt, you can run the following command, that should fix the issue: ``` python -m ensurepip --user ``` Replace python3 if your version supports that.
35,894,511
When i run ``` pip install --upgrade pip ``` I get this error message: ``` Collecting pip Downloading pip-8.1.0-py2.py3-none-any.whl (1.2MB) 100% |████████████████████████████████| 1.2MB 371kB/s Installing collected packages: pip Found existing installation: pip 8.0.2 Uninstalling pip-8.0.2: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 725, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 752, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py",line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 266, in renames shutil.move(old, new) File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site- packages/pip-8.0.2.dist-info/DESCRIPTION.rst' ``` Previously I had been struggling to install and run a couple of python modules so I remember moving files around a bit. Is that what has caused this error? How can I fix this? I am on Mac. I was trying to install bs4 prior to this and I got similar error messages. (But i suspect the bs4 install has more issues so that's another question for later). Also sorry for any format issues with the code. Have tried my best to make it look like it is on the terminal. Thanks.
2016/03/09
[ "https://Stackoverflow.com/questions/35894511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5827690/" ]
From administrator mode command prompt, you can run the following command, that should fix the issue: ``` python -m ensurepip --user ``` Replace python3 if your version supports that.
``` DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirement.txt' WARNING: You are using pip version 19.2.3, however version 20.3.4 is available. You should consider upgrading via the 'pip install --upgrade pip' command. $ pip install pip Requirement already satisfied: pip in /data/data/com.termux/files/usr/lib/python3.9/site-packages (21.0.1) ``` Showing like this help !!!
35,894,511
When i run ``` pip install --upgrade pip ``` I get this error message: ``` Collecting pip Downloading pip-8.1.0-py2.py3-none-any.whl (1.2MB) 100% |████████████████████████████████| 1.2MB 371kB/s Installing collected packages: pip Found existing installation: pip 8.0.2 Uninstalling pip-8.0.2: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 725, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 752, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py",line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 266, in renames shutil.move(old, new) File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site- packages/pip-8.0.2.dist-info/DESCRIPTION.rst' ``` Previously I had been struggling to install and run a couple of python modules so I remember moving files around a bit. Is that what has caused this error? How can I fix this? I am on Mac. I was trying to install bs4 prior to this and I got similar error messages. (But i suspect the bs4 install has more issues so that's another question for later). Also sorry for any format issues with the code. Have tried my best to make it look like it is on the terminal. Thanks.
2016/03/09
[ "https://Stackoverflow.com/questions/35894511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5827690/" ]
The best way to do it is as follows: ``` $ python3 -m pip install --upgrade pip ``` as it's generally not advised to use ``` $ sudo pip install ``` More answers can be found here: <https://github.com/pypa/pip/issues/5599>
``` DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirement.txt' WARNING: You are using pip version 19.2.3, however version 20.3.4 is available. You should consider upgrading via the 'pip install --upgrade pip' command. $ pip install pip Requirement already satisfied: pip in /data/data/com.termux/files/usr/lib/python3.9/site-packages (21.0.1) ``` Showing like this help !!!
10,838,596
The below piece of code is giving me a error for some reason, Can someone tell me what would be the problem.. Basically, I create 2 classes Point & Circle..THe circle is trying to inherit the Point class. ``` Code: class Point(): x = 0.0 y = 0.0 def __init__(self, x, y): self.x = x self.y = y print("Point constructor") def ToString(self): return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}" class Circle(Point): radius = 0.0 def __init__(self, x, y, radius): super(Point,self).__init__(x,y) self.radius = radius print("Circle constructor") def ToString(self): return super().ToString() + \ ",{RADIUS=" + str(self.radius) + "}" if __name__=='__main__': newpoint = Point(10,20) newcircle = Circle(10,20,0) ``` Error: ``` C:\Python27>python Point.py Point constructor Traceback (most recent call last): File "Point.py", line 29, in <module> newcircle = Circle(10,20,0) File "Point.py", line 18, in __init__ super().__init__(x,y) TypeError: super() takes at least 1 argument (0 given) ```
2012/05/31
[ "https://Stackoverflow.com/questions/10838596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050619/" ]
It looks like you already may have fixed the original error, which was caused by `super().__init__(x,y)` as the error message indicates, although your fix was slightly incorrect, instead of `super(Point, self)` from the `Circle` class you should use `super(Circle, self)`. Note that there is another place that calls `super()` incorrectly, inside of `Circle`'s `ToString()` method: ``` return super().ToString() + \ ",{RADIUS=" + str(self.radius) + "}" ``` This is valid code on Python 3, but on Python 2 `super()` requires arguments, rewrite this as the following: ``` return super(Circle, self).ToString() + \ ",{RADIUS=" + str(self.radius) + "}" ``` I would also recommend getting rid of the line continuation, see the [Maximum Line Length section of PEP 8](http://www.python.org/dev/peps/pep-0008/#maximum-line-length) for the recommended way of fixing this.
`super(..)` takes only new-style classes. To fix it, extend Point class from `object`. Like this: ``` class Point(object): ``` Also the correct way of using super(..) is like: ``` super(Circle,self).__init__(x,y) ```
10,838,596
The below piece of code is giving me a error for some reason, Can someone tell me what would be the problem.. Basically, I create 2 classes Point & Circle..THe circle is trying to inherit the Point class. ``` Code: class Point(): x = 0.0 y = 0.0 def __init__(self, x, y): self.x = x self.y = y print("Point constructor") def ToString(self): return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}" class Circle(Point): radius = 0.0 def __init__(self, x, y, radius): super(Point,self).__init__(x,y) self.radius = radius print("Circle constructor") def ToString(self): return super().ToString() + \ ",{RADIUS=" + str(self.radius) + "}" if __name__=='__main__': newpoint = Point(10,20) newcircle = Circle(10,20,0) ``` Error: ``` C:\Python27>python Point.py Point constructor Traceback (most recent call last): File "Point.py", line 29, in <module> newcircle = Circle(10,20,0) File "Point.py", line 18, in __init__ super().__init__(x,y) TypeError: super() takes at least 1 argument (0 given) ```
2012/05/31
[ "https://Stackoverflow.com/questions/10838596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050619/" ]
It looks like you already may have fixed the original error, which was caused by `super().__init__(x,y)` as the error message indicates, although your fix was slightly incorrect, instead of `super(Point, self)` from the `Circle` class you should use `super(Circle, self)`. Note that there is another place that calls `super()` incorrectly, inside of `Circle`'s `ToString()` method: ``` return super().ToString() + \ ",{RADIUS=" + str(self.radius) + "}" ``` This is valid code on Python 3, but on Python 2 `super()` requires arguments, rewrite this as the following: ``` return super(Circle, self).ToString() + \ ",{RADIUS=" + str(self.radius) + "}" ``` I would also recommend getting rid of the line continuation, see the [Maximum Line Length section of PEP 8](http://www.python.org/dev/peps/pep-0008/#maximum-line-length) for the recommended way of fixing this.
``` class Point(object): x = 0.0 y = 0.0 def __init__(self, x, y): self.x = x self.y = y print("Point constructor") def ToString(self): return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}" class Circle(Point,object): radius = 0.0 def __init__(self, x, y, radius): super(Circle,self).__init__(x,y) self.radius = radius print("Circle constructor") def ToString(self): return super(Circle, self).ToString() + \ ",{RADIUS=" + str(self.radius) + "}" if __name__=='__main__': newpoint = Point(10,20) newcircle = Circle(10,20,0) ```
10,838,596
The below piece of code is giving me a error for some reason, Can someone tell me what would be the problem.. Basically, I create 2 classes Point & Circle..THe circle is trying to inherit the Point class. ``` Code: class Point(): x = 0.0 y = 0.0 def __init__(self, x, y): self.x = x self.y = y print("Point constructor") def ToString(self): return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}" class Circle(Point): radius = 0.0 def __init__(self, x, y, radius): super(Point,self).__init__(x,y) self.radius = radius print("Circle constructor") def ToString(self): return super().ToString() + \ ",{RADIUS=" + str(self.radius) + "}" if __name__=='__main__': newpoint = Point(10,20) newcircle = Circle(10,20,0) ``` Error: ``` C:\Python27>python Point.py Point constructor Traceback (most recent call last): File "Point.py", line 29, in <module> newcircle = Circle(10,20,0) File "Point.py", line 18, in __init__ super().__init__(x,y) TypeError: super() takes at least 1 argument (0 given) ```
2012/05/31
[ "https://Stackoverflow.com/questions/10838596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1050619/" ]
`super(..)` takes only new-style classes. To fix it, extend Point class from `object`. Like this: ``` class Point(object): ``` Also the correct way of using super(..) is like: ``` super(Circle,self).__init__(x,y) ```
``` class Point(object): x = 0.0 y = 0.0 def __init__(self, x, y): self.x = x self.y = y print("Point constructor") def ToString(self): return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}" class Circle(Point,object): radius = 0.0 def __init__(self, x, y, radius): super(Circle,self).__init__(x,y) self.radius = radius print("Circle constructor") def ToString(self): return super(Circle, self).ToString() + \ ",{RADIUS=" + str(self.radius) + "}" if __name__=='__main__': newpoint = Point(10,20) newcircle = Circle(10,20,0) ```
71,391,688
pip install pygame==2.0.0.dev10 this package not installed in python 3.8.2 version.so when I run the gaming project so that time this error showing.instead of this I am install pip install pygame==2.0.0.dev12,this package is install but same error is showing. so can anyone give me a solution
2022/03/08
[ "https://Stackoverflow.com/questions/71391688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18405878/" ]
Redirect in htaccess does not matter if it is a pdf file or anything else just a **valid link**. This is an example of a 301 redirect code to the link you want `RedirectMatch 301 /subpage/ <https://www.mywebsite.com/upload/files/file.pdf>`
To target an HTML link to a specific page in a PDF file, add #page=[page number] to the end of the link's URL. For example, this HTML tag opens page 4 of a PDF file named myfile.pdf: ``` <A HREF="http://www.example.com/myfile.pdf#page=4"> ``` --- And If you want to redirect a single page to another you just need to insert this line in the .htaccess file: Redirect 301 /old-post <https://www.yourwebsite.com/myfiles/myfile.pdf> Going to replace the old and new addresses respectively. The code must be inserted after and before .
71,391,688
pip install pygame==2.0.0.dev10 this package not installed in python 3.8.2 version.so when I run the gaming project so that time this error showing.instead of this I am install pip install pygame==2.0.0.dev12,this package is install but same error is showing. so can anyone give me a solution
2022/03/08
[ "https://Stackoverflow.com/questions/71391688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18405878/" ]
You are getting a `404` probably because the URI `/subpage` doesn't exist or map to an existent file. The `Redirect` you are using doesn't redirect the `/subpage` to the PDF location because your WordPress `RewriteRules` override it. If you want to fix it , you will need to use `RewriteRule` directive instead of `Redirect` at the top of your htaccess : ``` RewriteEngine On RewriteRule ^/?subpage/? https://www.mywebsite.com/upload/files/file.pdf [R=301,L] ```
To target an HTML link to a specific page in a PDF file, add #page=[page number] to the end of the link's URL. For example, this HTML tag opens page 4 of a PDF file named myfile.pdf: ``` <A HREF="http://www.example.com/myfile.pdf#page=4"> ``` --- And If you want to redirect a single page to another you just need to insert this line in the .htaccess file: Redirect 301 /old-post <https://www.yourwebsite.com/myfiles/myfile.pdf> Going to replace the old and new addresses respectively. The code must be inserted after and before .
71,391,688
pip install pygame==2.0.0.dev10 this package not installed in python 3.8.2 version.so when I run the gaming project so that time this error showing.instead of this I am install pip install pygame==2.0.0.dev12,this package is install but same error is showing. so can anyone give me a solution
2022/03/08
[ "https://Stackoverflow.com/questions/71391688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18405878/" ]
You are getting a `404` probably because the URI `/subpage` doesn't exist or map to an existent file. The `Redirect` you are using doesn't redirect the `/subpage` to the PDF location because your WordPress `RewriteRules` override it. If you want to fix it , you will need to use `RewriteRule` directive instead of `Redirect` at the top of your htaccess : ``` RewriteEngine On RewriteRule ^/?subpage/? https://www.mywebsite.com/upload/files/file.pdf [R=301,L] ```
Redirect in htaccess does not matter if it is a pdf file or anything else just a **valid link**. This is an example of a 301 redirect code to the link you want `RedirectMatch 301 /subpage/ <https://www.mywebsite.com/upload/files/file.pdf>`
33,813,848
I only started using python, so i don't know it very well.Can you help how to say that the number should not be divisible by another integer given by me ? For example, if a is not divisible by 2.
2015/11/19
[ "https://Stackoverflow.com/questions/33813848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5583129/" ]
Check out the % operator. ``` if x%2 == 0: # x is divisible by 2 print x ```
"a is not divisible by 2": `(a % 2) != 0`
33,813,848
I only started using python, so i don't know it very well.Can you help how to say that the number should not be divisible by another integer given by me ? For example, if a is not divisible by 2.
2015/11/19
[ "https://Stackoverflow.com/questions/33813848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5583129/" ]
``` >>> def isDivis(divisor,num): return not num%divisor >>> isDivis(2,12) True >>> isDivis(2,21) False >>> isDivis(3,21) True >>> isDivis(3,14) False ```
"a is not divisible by 2": `(a % 2) != 0`
49,626,707
``` from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options import time chrome_options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_values.notifications" : 2} chrome_options.add_experimental_option("prefs",prefs) driver = webdriver.Chrome("C:\\chromedriver\\chromedriver.exe") driver.maximize_window() driver.get("https://www.arttoframe.com/") time.sleep(6) driver.close() ``` Console Logs : ``` C:\Users\Dell\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Dell/PycharmProjects/untitled/newaaa.py Process finished with exit code 0 ```
2018/04/03
[ "https://Stackoverflow.com/questions/49626707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9575127/" ]
As you have created an instance of `ChromeOptions()` as **chrome\_options** you need to pass it as an argument to put the configurations in effect while invoking `webdriver.Chrome()` as follows : ``` from selenium import webdriver from selenium.webdriver.chrome.options import Options import time chrome_options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_values.notifications" : 2} chrome_options.add_experimental_option("prefs", prefs) chrome_options.add_argument("start-maximized") driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=r'C:\path\to\chromedriver.exe') driver.get("https://www.arttoframe.com/") time.sleep(6) driver.quit() ``` **Note** : * To maximize the Chrome browser instead of `maximize_window()` use the `ChromeOptions()` class argument **start-maximized** * At the end of your program instead of `driver.close()` use **driver.quit()**.
``` driver.switch_to_alert().dismiss() driver.switch_to_alert().accept() ``` These can be used dismiss-right and accept-left
22,418,816
I'm trying to use multiprocessing to get a handle on my memory issues, however I can't get a function to pickle, and I have no idea why. My main code starts with ``` def main(): print "starting main" q = Queue() p = Process(target=file_unpacking,args=("hellow world",q)) p.start() p.join() if p.is_alive(): p.terminate() print "The results are in" Chan1 = q.get() Chan2 = q.get() Start_Header = q.get() Date = q.get() Time = q.get() return Chan1, Chan2, Start_Header, Date, Time def file_unpacking(args, q): print "starting unpacking" fileName1 = "050913-00012" unpacker = UnpackingClass() for fileNumber in range(0,44): fileName = fileName1 + str(fileNumber) + fileName3 header, data1, data2 = UnpackingClass.unpackFile(path,fileName) if header == None: logging.warning("curropted file found at " + fileName) Data_Sets1.append(temp_1) Data_Sets2.append(temp_2) Headers.append(temp_3) temp_1 = [] temp_2 = [] temp_3 = [] #for i in range(0,10000): # Chan1.append(0) # Chan2.append(0) else: logging.info(fileName + " is good!") temp_3.append(header) for i in range(0,10000): temp_1.append(data1[i]) temp_2.append(data2[i]) Data_Sets1.append(temp_1) Data_Sets2.append(temp_2) Headers.append(temp_3) temp_1 = [] temp_2 = [] temp_3 = [] lengths = [] for i in range(len(Data_Sets1)): lengths.append(len(Data_Sets1[i])) index = lengths.index(max(lengths)) Chan1 = Data_Sets1[index] Chan2 = Data_Sets2[index] Start_Header = Headers[index] Date = Start_Header[index][0] Time = Start_Header[index][1] print "done unpacking" q.put(Chan1) q.put(Chan2) q.put(Start_Header) q.put(Date) q.put(Time) ``` and currently I have the unpacking method in a separate python file that imports struct and os. This reads a part text part binary file, structures it, and then closes it. This is mostly leg work, so I won't post it yet, however if it helps I will. I will give the start ``` class UnpackingClass: def __init__(self): print "Unpacking Class" def unpackFile(path,fileName): import struct import os ....... ``` Then I simply call main() to get the party started, and I get nothing but a infinite loop of pickle errors. Long story short I don't have any clue how to pickle a function. Everything is defined at the top of files, so I'm at a loss. Here is the error message ``` Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\multiprocessing\forking.py", line 373, in main prepare(preparation_data) File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\multiprocessing\forking.py", line 488, in prepare '__parents_main__', file, path_name, etc File "A:\598\TestCode\test1.py", line 142, in <module> Chan1, Chan2, Start_Header, Date, Time = main() File "A:\598\TestCode\test1.py", line 43, in main p.start() File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\multiprocessing\process.py", line 130, in start self._popen = Popen(self) File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\multiprocessing\forking.py", line 271, in __init__ dump(process_obj, to_child, HIGHEST_PROTOCOL) File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\multiprocessing\forking.py", line 193, in dump ForkingPickler(file, protocol).dump(obj) File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\pickle.py", line 224, in dump self.save(obj) File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\pickle.py", line 331, in save self.save_reduce(obj=obj, *rv) File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\pickle.py", line 419, in save_reduce save(state) File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\pickle.py", line 649, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\pickle.py", line 681, in _batch_setitems save(v) File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "C:\Users\Casey\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.1.0.1371.win-x86_64\lib\pickle.py", line 748, in save_global (obj, module, name)) pickle.PicklingError: Can't pickle <function file_unpacking at 0x0000000007E1F048>: it's not found as __main__.file_unpacking ```
2014/03/15
[ "https://Stackoverflow.com/questions/22418816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2352742/" ]
Pickling a function is a very very relevant thing to do if you want to do any parallel computing. Python's `pickle` and `multiprocessing` are pretty broken for doing parallel computing, so if you aren't adverse to going outside of the standard library, I'd suggest `dill` for serialization, and `pathos.multiprocessing` as a `multiprocessing` replacement. `dill` can serialize almost anything in python, and `pathos.multiprocessing` uses `dill` to provide more robust parallel CPU use. For more information, see: [What can multiprocessing and dill do together?](https://stackoverflow.com/questions/19984152/what-can-multiprocessing-and-dill-do-together?rq=1) or this simple example: ``` Python 2.7.6 (default, Nov 12 2013, 13:26:39) [GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import dill >>> from pathos.multiprocessing import ProcessingPool >>> >>> def squared(x): ... return x**2 ... >>> pool = ProcessingPool(4) >>> pool.map(squared, range(10)) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> res = pool.amap(squared, range(10)) >>> res.get() [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> res = pool.imap(squared, range(10)) >>> list(res) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> >>> def add(x,y): ... return x+y ... >>> pool.map(add, range(10), range(10)) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>> res = pool.amap(add, range(10), range(10)) >>> res.get() [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>> res = pool.imap(add, range(10), range(10)) >>> list(res) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] ``` Both `dill` and `pathos` are available here: <https://github.com/uqfoundation>
You can technically pickle a function. But, it's only a name reference that's being saved. When you unpickle, you must set up the environment so that the name reference makes sense to python. Make sure to read [What can be pickled and unpicked](http://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled) carefully. If this doesn't answer your question, you'll need to provide us with the exact error messages. Also, please explain the purpose of pickling a function. Since you can only pickle a name reference and not the function itself, why can't you simply import and call the corresponding code?
38,947,967
I'm trying to mungle my data from the following data frame to the one following it where the values in column B and C are combined to column names for the values in D grouped by the values in A. Below is a reproducible example. ``` set.seed(10) fooDF <- data.frame(A = sample(1:4, 10, replace=TRUE), B = sample(letters[1:4], 10, replace=TRUE), C= sample(letters[1:4], 10, replace=TRUE), D = sample(1:4, 10, replace=TRUE)) fooDF[!duplicated(fooDF),] A B C D 1 4 c b 2 2 4 d a 2 3 2 a b 4 4 3 c a 1 5 4 a b 3 6 4 b a 2 7 1 b d 2 8 1 a d 4 9 2 b a 3 10 2 d c 2 newdata <- data.frame(A = 1:4) for(i in 1:nrow(fooDF)){ col_name <- paste(fooDF$B[i], fooDF$C[i], sep="") newdata[newdata$A == fooDF$A[i], col_name ] <- fooDF$D[i] } ``` The format I am trying to get it in. ``` > newdata A cb da ab ca ba bd ad dc 1 1 NA NA NA NA NA 2 4 NA 2 2 NA NA 4 NA 3 NA NA 2 3 3 NA NA NA 1 NA NA NA NA 4 4 2 2 3 NA 2 NA NA NA ``` Right now I am doing it line by line but that is unfeasible for a large csv containing 5 million + lines. Is there a way to do it faster in R or python?
2016/08/15
[ "https://Stackoverflow.com/questions/38947967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3329254/" ]
`my Tuple $t` creates a `$t` variable such that any (re)assignment or (re)binding to it must (re)pass the `Tuple` type check. `= [1, 2]` assigns a reference to an `Array` object. The `Tuple` type check is applied (and passes). `$t.append(3)` modifies the contents of the `Array` object held in `$t` but does not reassign or rebind `$t` so there's no type check. Mutating-method-call syntax -- `$t.=append(3)` instead of `$t.append(3)` -- will trigger the type check on `$t`. There is specific syntax for a bounds-checked array (`my @array[2]` etc.) but I'm guessing that's not the point of your question.
The type constraint is bound to the scalar container, but the object it contains is just a plain old array - and an array's `append` method is unaware you want it to trigger a type check. If you want to explicitly trigger the check again, you could do a reassignment like `$t = $t`.
38,947,967
I'm trying to mungle my data from the following data frame to the one following it where the values in column B and C are combined to column names for the values in D grouped by the values in A. Below is a reproducible example. ``` set.seed(10) fooDF <- data.frame(A = sample(1:4, 10, replace=TRUE), B = sample(letters[1:4], 10, replace=TRUE), C= sample(letters[1:4], 10, replace=TRUE), D = sample(1:4, 10, replace=TRUE)) fooDF[!duplicated(fooDF),] A B C D 1 4 c b 2 2 4 d a 2 3 2 a b 4 4 3 c a 1 5 4 a b 3 6 4 b a 2 7 1 b d 2 8 1 a d 4 9 2 b a 3 10 2 d c 2 newdata <- data.frame(A = 1:4) for(i in 1:nrow(fooDF)){ col_name <- paste(fooDF$B[i], fooDF$C[i], sep="") newdata[newdata$A == fooDF$A[i], col_name ] <- fooDF$D[i] } ``` The format I am trying to get it in. ``` > newdata A cb da ab ca ba bd ad dc 1 1 NA NA NA NA NA 2 4 NA 2 2 NA NA 4 NA 3 NA NA 2 3 3 NA NA NA 1 NA NA NA NA 4 4 2 2 3 NA 2 NA NA NA ``` Right now I am doing it line by line but that is unfeasible for a large csv containing 5 million + lines. Is there a way to do it faster in R or python?
2016/08/15
[ "https://Stackoverflow.com/questions/38947967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3329254/" ]
The type constraint is bound to the scalar container, but the object it contains is just a plain old array - and an array's `append` method is unaware you want it to trigger a type check. If you want to explicitly trigger the check again, you could do a reassignment like `$t = $t`.
If you really want an altered version of an [`Array`](https://docs.perl6.org/type/Array), you can simply create a class that inherits from it and overrides the methods that you want to behave differently. (There are probably much more elegant ways to do this, but this does work): ``` class Tuple is Array { method append ( *@val ) { fail '"append" is disabled for Tuples' } } my $t = Tuple.new(1,2); say $t; $t.append(3); ``` Then it will work like you expect: ``` [1 2] "append" is disabled for Tuples in method append at example.p6 line 2 in block <unit> at example.p6 line 11 Actually thrown at: in block <unit> at example.p6 line 11 ``` Alternately, to get something similar you could use a dimensioned array [as mentioned by raiph](https://stackoverflow.com/a/38951074/215487). Or, if you simply want something immutable that is similar to an array, you can then use a [`List`](https://docs.perl6.org/type/List).
38,947,967
I'm trying to mungle my data from the following data frame to the one following it where the values in column B and C are combined to column names for the values in D grouped by the values in A. Below is a reproducible example. ``` set.seed(10) fooDF <- data.frame(A = sample(1:4, 10, replace=TRUE), B = sample(letters[1:4], 10, replace=TRUE), C= sample(letters[1:4], 10, replace=TRUE), D = sample(1:4, 10, replace=TRUE)) fooDF[!duplicated(fooDF),] A B C D 1 4 c b 2 2 4 d a 2 3 2 a b 4 4 3 c a 1 5 4 a b 3 6 4 b a 2 7 1 b d 2 8 1 a d 4 9 2 b a 3 10 2 d c 2 newdata <- data.frame(A = 1:4) for(i in 1:nrow(fooDF)){ col_name <- paste(fooDF$B[i], fooDF$C[i], sep="") newdata[newdata$A == fooDF$A[i], col_name ] <- fooDF$D[i] } ``` The format I am trying to get it in. ``` > newdata A cb da ab ca ba bd ad dc 1 1 NA NA NA NA NA 2 4 NA 2 2 NA NA 4 NA 3 NA NA 2 3 3 NA NA NA 1 NA NA NA NA 4 4 2 2 3 NA 2 NA NA NA ``` Right now I am doing it line by line but that is unfeasible for a large csv containing 5 million + lines. Is there a way to do it faster in R or python?
2016/08/15
[ "https://Stackoverflow.com/questions/38947967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3329254/" ]
`my Tuple $t` creates a `$t` variable such that any (re)assignment or (re)binding to it must (re)pass the `Tuple` type check. `= [1, 2]` assigns a reference to an `Array` object. The `Tuple` type check is applied (and passes). `$t.append(3)` modifies the contents of the `Array` object held in `$t` but does not reassign or rebind `$t` so there's no type check. Mutating-method-call syntax -- `$t.=append(3)` instead of `$t.append(3)` -- will trigger the type check on `$t`. There is specific syntax for a bounds-checked array (`my @array[2]` etc.) but I'm guessing that's not the point of your question.
If you really want an altered version of an [`Array`](https://docs.perl6.org/type/Array), you can simply create a class that inherits from it and overrides the methods that you want to behave differently. (There are probably much more elegant ways to do this, but this does work): ``` class Tuple is Array { method append ( *@val ) { fail '"append" is disabled for Tuples' } } my $t = Tuple.new(1,2); say $t; $t.append(3); ``` Then it will work like you expect: ``` [1 2] "append" is disabled for Tuples in method append at example.p6 line 2 in block <unit> at example.p6 line 11 Actually thrown at: in block <unit> at example.p6 line 11 ``` Alternately, to get something similar you could use a dimensioned array [as mentioned by raiph](https://stackoverflow.com/a/38951074/215487). Or, if you simply want something immutable that is similar to an array, you can then use a [`List`](https://docs.perl6.org/type/List).
64,318,676
I am trying to scrape all email addresses from this index page - <http://www.uschess.org/assets/msa_joomla/AffiliateSearch/clubresultsnew.php?st=AL> I modified a python script to define the string, parse content with BS4 and save each unique address to an xls file: ``` import requests from bs4 import BeautifulSoup import xlwt wb = xlwt.Workbook() ws = wb.add_sheet('Emails') ws.write(0,0,'Emails') emailList= [] r=0 #add url of the page you want to scrape to urlString urlString='http://www.uschess.org/assets/msa_joomla/AffiliateSearch/clubresultsnew.php?st=AL' #function that extracts all emails from a page you provided and stores them in a list def emailExtractor(urlString): getH=requests.get(urlString) h=getH.content soup=BeautifulSoup(h,'html.parser') mailtos = soup.select('a[href^=mailto]') for i in mailtos: href=i['href'] try: str1, str2 = href.split(':') except ValueError: break emailList.append(str2) emailExtractor(urlString) #adding scraped emails to an excel sheet for email in emailList: r=r+1 ws.write(r,0,email) wb.save('emails.xls') ``` The xls file exports as expected, but with no email values. If anyone can explain why or how to simplify this solution it would be greatly appreciated!
2020/10/12
[ "https://Stackoverflow.com/questions/64318676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5705012/" ]
Your insert has 2 issues. Assuming the string '1,2,3,4' is the result of your decode (not at all clear on that) there is no new line ( chr(10)||chr(13) ) data in it. As a result there is only 1 value to be extracted. Perhaps the decoded result is actually a CSV. I proceed with that assumption. Your second issue is that the regexp parse routine produces 4 rows, not 4 columns. You will have to somehow convert those rows to columns before inserting. The most "natural" way to do that is the PIVOT operator. Note for demonstration I changed your data values from '1,2,3,4' to 'A,B,C,D'. See [fiddle](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=2197bc4ed7ce4738dd2e6e6fb313b830). ``` insert into demo(col1,col2,col3,col4) with decoded(res) as ( select 'A,B,C,D' from dual) select * from (select level lev , regexp_substr(res,'[^,]+', 1, level) itm from decoded connect by regexp_substr(res, '[^,]+', 1, level) is not null) pivot ( max(itm) for lev in (1,2,3,4) ); ```
``` PROCEDURE LOAD_SPM_ITEM_SYNC(P_ENCODED_STRING IN CLOB,truncateflag in varchar2) IS r_records varchar2(3000); BEGIN declare cursor c_records IS select regexp_substr(utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(P_ENCODED_STRING))), '[^'||CHR(10)||CHR(13)||']+', 1, level) from dual connect by regexp_substr(utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(P_ENCODED_STRING))), '[^'||CHR(10)||CHR(13)||']+', 1, level) is not null ; Begin OPEN c_records; loop FETCH c_records INTO r_records; exit when c_records%NOTFOUND; insert into demo(column_1,column_2,column_3,column_4) select regexp_substr(r_records, '\d+', 1, 1) , regexp_substr(r_records, '\d+', 1, 2) , regexp_substr(r_records, '\d+', 1, 3) , regexp_substr(r_records, '\d+', 1, 4) from dual; end loop; End; --loop end LOAD_SPM_ITEM_SYNC; ``` This code will convert encoded string to values and they will be inserted into 4 columns and we can add a new regex\_substsr if we want a new column.
50,330,893
I use python-telegram-bot and I don't understand how forward a message from the user to a telegram group, I have something like this: ``` def feed(bot, update): bot.send_message(chat_id=update.message.chat_id, text="reply this message" bot.forward_message(chat_id="telegram group", from_chat_id="username bot", message_id=?) ``` I need to forward the message the user shares the message and the reply must be sent to a group. How it is possible?
2018/05/14
[ "https://Stackoverflow.com/questions/50330893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9788313/" ]
From [documentation](https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html#telegram.Bot.forward_message): **chat\_id** - Unique identifier for the target chat ... **from\_chat\_id** - Unique identifier for the ***chat where the original message was sent*** ... **message\_id** - Message identifier in the chat specified in from\_chat\_id. Solution: ``` def feed(bot, update): # send reply to the user bot.send_message(chat_id=update.message.chat_id, text='reply this message') # forward user message to group # note: group ID with the negative sign bot.forward_message(chat_id='-1010101001010', from_chat_id=update.message.chat_id, message_id=update.message.message_id) ```
Its easy with `Telethon`. You need the `chat_id`, `from_chat_id`. You can add a bot and you will need the token.
25,044,403
I've had success with `mvn deploy` for about a week now, and suddenly it's not working. It used to prompt me for my passphrase (in a dialog window--I'm using Kleopatra on Windows 7, 32bit), but it's not any more. The only thing that's changed in the POM is the project's version number. There are two random outcomes, both bad: First, this output, which is printed *without me pressing any keys*: ``` R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava>mvn deploy [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building XBN-Java 0.1.4.1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava --- [INFO] [INFO] --- maven-gpg-plugin:1.5:sign (sign-artifacts) @ xbnjava --- You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 OK Your orders please OK OK OK OK OK D 4204 OK OK OK ``` After pressing enter, this is the response: ``` gpg: Invalid passphrase; please try again ... gpg: Invalid passphrase; please try again ... You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 OK Your orders please OK OK OK OK OK D 5220 OK gpg: AllowSetForegroundWindow(5220) failed: Access is denied. OK OK OK gpg: AllowSetForegroundWindow(5220) failed: Access is denied. ``` It freezes again here, at which point I cancel with Ctrl+C ``` Terminate batch job (Y/N)? y R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava> ``` I see the `AllowSetForegroundWindow(5220)`, and found [this about it](http://lists.wald.intevation.org/pipermail/gpg4win-users-en/2009-August/000354.html), but it doesn't say anything specific to do. I tried it again and got this: ``` R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava>mvn deploy [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building XBN-Java 0.1.4.1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava --- [INFO] [INFO] --- maven-gpg-plugin:1.5:sign (sign-artifacts) @ xbnjava --- You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 ``` I enter my passphrase here and press enter, but nothing happens. It's stuck. I cancel the process and it prints my passphrase in plain-text: ``` Terminate batch job (Y/N)? MY_PASSPHRASE_PRINTED_HERE Terminate batch job (Y/N)? y R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava> ``` I try it *again* and the original stuff happens again ("...OK Your orders please OK OK OK OK OK..."). I enter my passphrase, and it starts working (I'm not sure when it actually took, it seems now), meaning the jars are uploaded successfully, but at the end of the log, after the "BUILD SUCCESSFUL" message... ``` R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava>mvn deploy [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building XBN-Java 0.1.4.1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava --- [INFO] [INFO] --- maven-gpg-plugin:1.5:sign (sign-artifacts) @ xbnjava --- You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 [INFO] [INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava --- [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.pom [INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.jar [INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-javadoc.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-javadoc.jar [INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-sources.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-sources.jar [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\xbnjava-0.1.4.1.pom.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.pom.asc [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\gpg\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1.jar.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.jar.asc [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\gpg\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-javadoc.jar.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-javadoc.jar.asc [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\gpg\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-sources.jar.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-sources.jar.asc [INFO] [INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava --- Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom (6 KB at 4.2 KB/sec) Downloading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml Downloaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (314 B at 0.9 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (314 B at 1.4 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar (630 KB at 439.6 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar (5093 KB at 572.4 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar (10728 KB at 609.9 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom.asc (499 B at 2.0 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar.asc (499 B at 1.9 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar.asc (499 B at 2.0 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar.asc (499 B at 2.2 KB/sec) [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 37.724 s [INFO] Finished at: 2014-07-30T13:58:42-04:00 [INFO] Final Memory: 6M/17M [INFO] ------------------------------------------------------------------------ ``` It ends with this: ``` 'import site' failed; use -v for traceback Traceback (most recent call last): File "C:\applications\programming\python_341\Lib\cmd.py", line 45, in ? import string, sys File "C:\applications\programming\python_341\Lib\string.py", line 73 class Template(metaclass=_TemplateMetaclass): ^ SyntaxError: invalid syntax ``` Note that, with all those ``` You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 ``` I never touch the keyboard. --- Full settings.xml: ``` <?xml version="1.0" encoding="UTF-8"?> <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <servers> <server> <id>ossrh</id> <username>MY_SONATYPE_DOT_COM_USERNAME</username> <password>MY_SONATYPE_DOT_COM_PASSWORD</password> </server> </servers> <pluginGroups></pluginGroups> <proxies></proxies> <mirrors></mirrors> <profiles></profiles> </settings> ``` Full pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.aliteralmind</groupId> <artifactId>xbnjava</artifactId> <packaging>pom</packaging> <version>0.1.4.1</version> <name>XBN-Java</name> <url>https://github.com/aliteralmind/xbnjava</url> <inceptionYear>2014</inceptionYear> <organization> <name>Jeff Epstein</name> </organization> <description>XBN-Java is a collection of generically-useful backend (server side, non-GUI) programming utilities, featuring RegexReplacer and FilteredLineIterator. XBN-Java is the foundation of Codelet (http://codelet.aliteralmind.com).</description> <licenses> <license> <name>Lesser General Public License (LGPL) version 3.0</name> <url>https://www.gnu.org/licenses/lgpl-3.0.txt</url> </license> <license> <name>Apache Software License (ASL) version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> </license> </licenses> <developers> <developer> <name>Jeff Epstein</name> <email>aliteralmind-github@yahoo.com</email> <roles> <role>Lead Developer</role> </roles> </developer> </developers> <issueManagement> <system>GitHub Issue Tracker</system> <url>https://github.com/aliteralmind/xbnjava/issues</url> </issueManagement> <distributionManagement> <snapshotRepository> <id>ossrh</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> </snapshotRepository> <repository> <id>ossrh</id> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url> </repository> </distributionManagement> <scm> <connection>scm:git:git@github.com:aliteralmind/xbnjava.git</connection> <url>scm:git:git@github.com:aliteralmind/xbnjava.git</url> <developerConnection>scm:git:git@github.com:aliteralmind/xbnjava.git</developerConnection> </scm> <properties> <java.version>1.7</java.version> <jarprefix>R:\jeffy\programming\build\/${project.artifactId}-${project.version}/download/${project.artifactId}-${project.version}</jarprefix> </properties> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>attach-artifacts</id> <phase>package</phase> <goals> <goal>attach-artifact</goal> </goals> <configuration> <artifacts> <artifact> <file>${jarprefix}.jar</file> <type>jar</type> </artifact> <artifact> <file>${jarprefix}-javadoc.jar</file> <type>jar</type> <classifier>javadoc</classifier> </artifact> <artifact> <file>${jarprefix}-sources.jar</file> <type>jar</type> <classifier>sources</classifier> </artifact> </artifacts> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <version>1.5</version> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <!-- <profiles> This profile will sign the JAR file, sources file, and javadocs file using the GPG key on the local machine. See: https://docs.sonatype.org/display/Repository/How+To+Generate+PGP+Signatures+With+Maven <profile> <id>release-sign-artifacts</id> <activation> <property> <name>release</name> <value>true</value> </property> </activation> </profile> </profiles> --> <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.0</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>16.0</version> </dependency> </dependencies> </project> ```
2014/07/30
[ "https://Stackoverflow.com/questions/25044403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2736496/" ]
Set your gpg.passphrase in your ~/.m2/settings.xml like so: ``` <server> <id>gpg.passphrase</id> <passphrase>clear or encrypted text</passphrase> </server> ``` Or pass it as a parameter when calling maven: ``` mvn -Dgpg.passphrase=yourpassphrase deploy ```
I uninstalled gpg4win (of which Kleopatra is part), restarted my computer, and re-installed gpg4win, and the passphrase issue went away. The dialog popped up and prompted me for my password. ``` R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava>mvn deploy [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building XBN-Java 0.1.4.1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava --- [INFO] [INFO] --- maven-gpg-plugin:1.5:sign (sign-artifacts) @ xbnjava --- You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 [INFO] [INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava --- [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.pom [INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.jar [INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-javadoc.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-javadoc.jar [INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-sources.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-sources.jar [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\xbnjava-0.1.4.1.pom.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.pom.asc [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\gpg\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1.jar.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.jar.asc [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\gpg\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-javadoc.jar.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-javadoc.jar.asc [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\gpg\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-sources.jar.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-sources.jar.asc [INFO] [INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava --- Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom (6 KB at 0.2 KB/sec) Downloading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml Downloaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (314 B at 1.2 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (314 B at 1.2 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar (630 KB at 453.2 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar (5093 KB at 605.6 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar (10728 KB at 609.6 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom.asc (499 B at 1.7 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar.asc (499 B at 1.6 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar.asc (499 B at 1.7 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar.asc (499 B at 2.0 KB/sec) [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 01:18 min [INFO] Finished at: 2014-07-30T14:30:23-04:00 [INFO] Final Memory: 5M/15M [INFO] ------------------------------------------------------------------------ 'import site' failed; use -v for traceback Traceback (most recent call last): File "C:\applications\programming\python_341\Lib\cmd.py", line 45, in ? import string, sys File "C:\applications\programming\python_341\Lib\string.py", line 73 class Template(metaclass=_TemplateMetaclass): ^ SyntaxError: invalid syntax ``` There's still the invalid syntax issue at the end of the log, which I'm about to post in a followup question. Sorry. I hope this helps someone in the future. Or in the past. Whatever.
25,044,403
I've had success with `mvn deploy` for about a week now, and suddenly it's not working. It used to prompt me for my passphrase (in a dialog window--I'm using Kleopatra on Windows 7, 32bit), but it's not any more. The only thing that's changed in the POM is the project's version number. There are two random outcomes, both bad: First, this output, which is printed *without me pressing any keys*: ``` R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava>mvn deploy [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building XBN-Java 0.1.4.1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava --- [INFO] [INFO] --- maven-gpg-plugin:1.5:sign (sign-artifacts) @ xbnjava --- You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 OK Your orders please OK OK OK OK OK D 4204 OK OK OK ``` After pressing enter, this is the response: ``` gpg: Invalid passphrase; please try again ... gpg: Invalid passphrase; please try again ... You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 OK Your orders please OK OK OK OK OK D 5220 OK gpg: AllowSetForegroundWindow(5220) failed: Access is denied. OK OK OK gpg: AllowSetForegroundWindow(5220) failed: Access is denied. ``` It freezes again here, at which point I cancel with Ctrl+C ``` Terminate batch job (Y/N)? y R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava> ``` I see the `AllowSetForegroundWindow(5220)`, and found [this about it](http://lists.wald.intevation.org/pipermail/gpg4win-users-en/2009-August/000354.html), but it doesn't say anything specific to do. I tried it again and got this: ``` R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava>mvn deploy [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building XBN-Java 0.1.4.1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava --- [INFO] [INFO] --- maven-gpg-plugin:1.5:sign (sign-artifacts) @ xbnjava --- You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 ``` I enter my passphrase here and press enter, but nothing happens. It's stuck. I cancel the process and it prints my passphrase in plain-text: ``` Terminate batch job (Y/N)? MY_PASSPHRASE_PRINTED_HERE Terminate batch job (Y/N)? y R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava> ``` I try it *again* and the original stuff happens again ("...OK Your orders please OK OK OK OK OK..."). I enter my passphrase, and it starts working (I'm not sure when it actually took, it seems now), meaning the jars are uploaded successfully, but at the end of the log, after the "BUILD SUCCESSFUL" message... ``` R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava>mvn deploy [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building XBN-Java 0.1.4.1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava --- [INFO] [INFO] --- maven-gpg-plugin:1.5:sign (sign-artifacts) @ xbnjava --- You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 [INFO] [INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava --- [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.pom [INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.jar [INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-javadoc.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-javadoc.jar [INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-sources.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-sources.jar [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\xbnjava-0.1.4.1.pom.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.pom.asc [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\gpg\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1.jar.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1.jar.asc [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\gpg\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-javadoc.jar.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-javadoc.jar.asc [INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\target\gpg\jeffy\programming\build\xbnjava-0.1.4.1\download\xbnjava-0.1.4.1-sources.jar.asc to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.4.1\xbnjava-0.1.4.1-sources.jar.asc [INFO] [INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava --- Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom (6 KB at 4.2 KB/sec) Downloading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml Downloaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (314 B at 0.9 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (314 B at 1.4 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar (630 KB at 439.6 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar (5093 KB at 572.4 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar (10728 KB at 609.9 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.pom.asc (499 B at 2.0 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1.jar.asc (499 B at 1.9 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-javadoc.jar.asc (499 B at 2.0 KB/sec) Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar.asc Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.4.1/xbnjava-0.1.4.1-sources.jar.asc (499 B at 2.2 KB/sec) [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 37.724 s [INFO] Finished at: 2014-07-30T13:58:42-04:00 [INFO] Final Memory: 6M/17M [INFO] ------------------------------------------------------------------------ ``` It ends with this: ``` 'import site' failed; use -v for traceback Traceback (most recent call last): File "C:\applications\programming\python_341\Lib\cmd.py", line 45, in ? import string, sys File "C:\applications\programming\python_341\Lib\string.py", line 73 class Template(metaclass=_TemplateMetaclass): ^ SyntaxError: invalid syntax ``` Note that, with all those ``` You need a passphrase to unlock the secret key for user: "MY NAME HERE <MY_EMAIL_HERE@yahoo.com>" 2048-bit RSA key, ID 4AB64866, created 2014-07-15 ``` I never touch the keyboard. --- Full settings.xml: ``` <?xml version="1.0" encoding="UTF-8"?> <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <servers> <server> <id>ossrh</id> <username>MY_SONATYPE_DOT_COM_USERNAME</username> <password>MY_SONATYPE_DOT_COM_PASSWORD</password> </server> </servers> <pluginGroups></pluginGroups> <proxies></proxies> <mirrors></mirrors> <profiles></profiles> </settings> ``` Full pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.aliteralmind</groupId> <artifactId>xbnjava</artifactId> <packaging>pom</packaging> <version>0.1.4.1</version> <name>XBN-Java</name> <url>https://github.com/aliteralmind/xbnjava</url> <inceptionYear>2014</inceptionYear> <organization> <name>Jeff Epstein</name> </organization> <description>XBN-Java is a collection of generically-useful backend (server side, non-GUI) programming utilities, featuring RegexReplacer and FilteredLineIterator. XBN-Java is the foundation of Codelet (http://codelet.aliteralmind.com).</description> <licenses> <license> <name>Lesser General Public License (LGPL) version 3.0</name> <url>https://www.gnu.org/licenses/lgpl-3.0.txt</url> </license> <license> <name>Apache Software License (ASL) version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> </license> </licenses> <developers> <developer> <name>Jeff Epstein</name> <email>aliteralmind-github@yahoo.com</email> <roles> <role>Lead Developer</role> </roles> </developer> </developers> <issueManagement> <system>GitHub Issue Tracker</system> <url>https://github.com/aliteralmind/xbnjava/issues</url> </issueManagement> <distributionManagement> <snapshotRepository> <id>ossrh</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> </snapshotRepository> <repository> <id>ossrh</id> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url> </repository> </distributionManagement> <scm> <connection>scm:git:git@github.com:aliteralmind/xbnjava.git</connection> <url>scm:git:git@github.com:aliteralmind/xbnjava.git</url> <developerConnection>scm:git:git@github.com:aliteralmind/xbnjava.git</developerConnection> </scm> <properties> <java.version>1.7</java.version> <jarprefix>R:\jeffy\programming\build\/${project.artifactId}-${project.version}/download/${project.artifactId}-${project.version}</jarprefix> </properties> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.8</version> <executions> <execution> <id>attach-artifacts</id> <phase>package</phase> <goals> <goal>attach-artifact</goal> </goals> <configuration> <artifacts> <artifact> <file>${jarprefix}.jar</file> <type>jar</type> </artifact> <artifact> <file>${jarprefix}-javadoc.jar</file> <type>jar</type> <classifier>javadoc</classifier> </artifact> <artifact> <file>${jarprefix}-sources.jar</file> <type>jar</type> <classifier>sources</classifier> </artifact> </artifacts> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <version>1.5</version> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <!-- <profiles> This profile will sign the JAR file, sources file, and javadocs file using the GPG key on the local machine. See: https://docs.sonatype.org/display/Repository/How+To+Generate+PGP+Signatures+With+Maven <profile> <id>release-sign-artifacts</id> <activation> <property> <name>release</name> <value>true</value> </property> </activation> </profile> </profiles> --> <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.0</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>16.0</version> </dependency> </dependencies> </project> ```
2014/07/30
[ "https://Stackoverflow.com/questions/25044403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2736496/" ]
Set your gpg.passphrase in your ~/.m2/settings.xml like so: ``` <server> <id>gpg.passphrase</id> <passphrase>clear or encrypted text</passphrase> </server> ``` Or pass it as a parameter when calling maven: ``` mvn -Dgpg.passphrase=yourpassphrase deploy ```
Definily it will work: GPG version: ------------ ``` C:\Users\joao.almeida>gpg --version gpg (GnuPG) 2.2.3 libgcrypt 1.8.1 Copyright (C) 2017 Free Software Foundation, Inc. ``` --- pom.xml ------- ```xml <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <configuration> <gpgArguments> <arg>--pinentry-mode</arg> <arg>loopback</arg> </gpgArguments> <keyname>example</keyname> <passphrase>************</passphrase> </configuration> <executions> <execution> <id>sign-artifacts</id> <phase>install</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ``` --- or moving authentication to settings.xml. settings.xml ------------ ```xml <?xml version="1.0" encoding="UTF-8"?> <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <profiles> <profile> <id>RELEASE</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <gpg.keyname>example</gpg.keyname> <gpg.passphrase>************</gpg.passphrase> </properties> </profile> </profiles> </settings> ``` pom.xml ------- ```xml <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <configuration> <gpgArguments> <arg>--pinentry-mode</arg> <arg>loopback</arg> </gpgArguments> </configuration> <executions> <execution> <id>sign-artifacts</id> <phase>install</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ``` executing mvn install: ``` mvn -f C:\.dev\.wkp\4.7\huhula\mvn.sign\pom.xml -s C:\.m2\dev\settings.xml install [INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for org.ex:mvn.sign:jar:0.0.1-SNAPSHOT [WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-gpg-plugin is missing. @ line 9, column 12 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building mvn.sign 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mvn.sign --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ mvn.sign --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ mvn.sign --- [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ mvn.sign --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mvn.sign --- [INFO] [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ mvn.sign --- [INFO] [INFO] --- maven-install-plugin:2.4:install (default-install) @ mvn.sign --- [INFO] Installing C:\.dev\.wkp\4.7\huhula\mvn.sign\target\mvn.sign-0.0.1-SNAPSHOT.jar to C:\.m2\dev\repository\org\ex\mvn.sign\0.0.1-SNAPSHOT\mvn.sign-0.0.1-SNAPSHOT.jar [INFO] Installing C:\.dev\.wkp\4.7\huhula\mvn.sign\pom.xml to C:\.m2\dev\repository\org\ex\mvn.sign\0.0.1-SNAPSHOT\mvn.sign-0.0.1-SNAPSHOT.pom [INFO] [INFO] --- maven-gpg-plugin:1.6:sign (sign-artifacts) @ mvn.sign --- [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.105 s [INFO] Finished at: 2017-11-22T13:13:37-02:00 [INFO] Final Memory: 12M/159M [INFO] ------------------------------------------------------------------------ ```
62,327,106
I am trying to make a class consisting of several methods and I want to use return values from methods as parameters for other methods within the same class. Is it possible to do so? ``` class Result_analysis(): def __init__(self, confidence_interval): self.confidence_interval = confidence_interval def read_file(self, file_number): dict_ = {1: 'Ten_Runs_avg-throughput_scalar.csv', 2: 'Thirty_Runs_avg-throughput_scalar.csv', 3: 'Hundred_Runs_avg-throughput_scalar.csv', 4: 'Thousand_Runs_avg-throughput_scalar.csv'} cols = ['run', 'ber', 'timelimit', 'repetition', 'Module', 'Avg_Throughput'] data = pd.read_csv(dict_[file_number], delimiter=',', skiprows=[0], names=cols) df = pd.DataFrame(data) return df def extract_arrays(self,df): df = Result_analysis().read_file(file_number) avgTP_10s_arr = [] avgTP_100s_arr = [] avgTP_1000s_arr = [] for i in range(len(data)): if (df['timelimit'][i] == 10): avgTP_10s_arr.append(df['Avg_Throughput'][i]) elif (df['timelimit'][i] == 100): avgTP_100s_arr.append(df['Avg_Throughput'][i]) elif (df['timelimit'][i] == 1000): avgTP_1000s_arr.append(df['Avg_Throughput'][i]) return avgTP_10s_arr, avgTP_100s_arr, avgTP_1000s_arr d = Result_analysis(0.95) d.read_file(1) d.exextract_arrays(d.read_file(1)) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-92-485309654e5c> in <module> 1 d = Result_analysis(0.95) 2 d.read_file(1) ----> 3 d.extract_arrays(d.read_file(1)) <ipython-input-91-06bc29de002c> in extract_arrays(self, file_number) 15 16 def extract_arrays(self,file_number): ---> 17 df = Result_analysis().read_file(file_number) 18 avgTP_10s_arr = [] 19 avgTP_100s_arr = [] TypeError: __init__() missing 1 required positional argument: 'confidence_interval' ``` I get the above given error.
2020/06/11
[ "https://Stackoverflow.com/questions/62327106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13628325/" ]
You didn't include all your code, and you should have updated the question with the traceback, but did you mean this: ``` n = ... # I don't know what n is. d = Result_analysis(0.95) print(d.extract_arrays(d.read_file(n)) ```
If you don't want to call the function read\_file explicitly from outside class. then you can convert the program as: ``` class Result_analysis(): def __init__(self, confidence_interval): self.confidence_interval = confidence_interval def read_file(self, file_number): dict_ = {1: 'Ten_Runs_avg-throughput_scalar.csv', 2: 'Thirty_Runs_avg-throughput_scalar.csv', 3: 'Hundred_Runs_avg-throughput_scalar.csv', 4: 'Thousand_Runs_avg-throughput_scalar.csv'} cols = ['run', 'ber', 'timelimit', 'repetition', 'Module', 'Avg_Throughput'] data = pd.read_csv(dict_[file_number], delimiter=',', skiprows=[0], names=cols) df = pd.DataFrame(data) return df def extract_arrays(self,file_number): df = Result_analysis().read_file(file_number) avgTP_10s_arr = [] avgTP_100s_arr = [] avgTP_1000s_arr = [] for i in range(len(data)): if (df['timelimit'][i] == 10): avgTP_10s_arr.append(df['Avg_Throughput'][i]) elif (df['timelimit'][i] == 100): avgTP_100s_arr.append(df['Avg_Throughput'][i]) elif (df['timelimit'][i] == 1000): avgTP_1000s_arr.append(df['Avg_Throughput'][i]) return avgTP_10s_arr, avgTP_100s_arr, avgTP_1000s_arr ``` call the function `extract_arrays`, and pass `file_number` as parameter