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
49,835,559
After installing Ubuntu as WSL(Windows Subsystem for Linux) I've run: ``` root@teclast:~# python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... ``` and try to access to this web server from my windows machine `http://0.0.0.0:8000` or `http://192.168.1.178:8000` but no success, web server available only by th...
2018/04/14
[ "https://Stackoverflow.com/questions/49835559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441863/" ]
Similar to @countach 's answer: If using Ubuntu type `ip address` in the WSL terminal. Look for the entry that says `#: eth0 ...` where `#` is some small number. There is an ip address there. Use that.
**Avoid using firewall rules used in some answers on the web, I saw some of them create some kind of allow-all firewall rule (allow any terrafic from any ip and any port), this can cause security problems** Simply use this single line from [this answer](https://stackoverflow.com/a/70566842/11190169) which worked perfe...
39,878,262
I have very large log file, which contains log of service restart messages. After I initiated service restart with external command I need to tail this log file from last occurrence of reboot message and check following messages to confirm correct restart procedure. I'm analysing messages by python, so only find last o...
2016/10/05
[ "https://Stackoverflow.com/questions/39878262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1777415/" ]
give a generous buffer value, reverse, extract, reverse ``` $ tail -1000 file | tac | awk '1,/Rebooting/' | tac ``` or, replace `awk` script with `!p; /Rebooting/{p=1}`
Perhaps something like: ``` tail -fn +$(awk '/Rebooting/ { line = NR } END { print(line) }' log) log ``` which uses `awk` to find the line number of the last occurrence of the pattern and then tails starting at that line. This still scans the entire file, though. If you're really doing it from python, you can prob...
18,520,203
I just installed the 'eve demo' I can't get it to start working. The error is: > > eve.io.base.ConnectionException: Error initializing the driver. Make sure the database serveris running. Driver exception: OperationFailure(u"command SON([('authenticate', 1), ('user', u'user'), ('nonce', u'cec66353cb35b6f5'), ('key'...
2013/08/29
[ "https://Stackoverflow.com/questions/18520203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2615737/" ]
It looks like the MongoDB user/pw combo you configured in your `settings.py` has not been set at the db level. From the mongo shell type `use <dbname>`, then `db.system.users.find()` to get a list of authorized users for `<dbname>`. It is probably empty; add the user as needed (see the [MongoDB docs](http://docs.mongod...
1. get your mongodb's dbname,username and password from setting.py,eg: ``` MONGO_USERNAME = 'username' MONGO_PASSWORD = 'password' MONGO_DBNAME = 'apitest' ``` 2. login in mongod server with mongo,and make sure your username in dbname's system.user collection.you can query authenticated users in that database with ...
74,618,712
I want to read the data on an excel file within a F drive. I am using python on Visual Studio Code to try achieve this however I am getting an error as seen in the pictures below. I installed pandas but I still get an error. How can I fix this issue? [Coding Error](https://i.stack.imgur.com/XFyH4.png) [Installed Pand...
2022/11/29
[ "https://Stackoverflow.com/questions/74618712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20636206/" ]
You should try to open terminal in VS Code, and run `pip freeze` (and `pip3 freeze`). Check if you find pandas in the results, it won't. That must be because you'd have multiple installations of Python on your system. You may do any one of the below - 1. Get rid of all but one Python installation. 2. Install pandas on...
To read an Excel file with Python, you need to install the pandas library. To install pandas, open the command line or terminal and type: pip install pandas Once pandas is installed, you can read an Excel file like this: import pandas as pd df = pd.read\_excel('file\_name.xlsx') print(df) You should also make sur...
23,516,150
I created a thread for a keylogger that logs in parallel to another thread that produces some sounds ( I want to catch reaction times). Unfortunately, the thread never finishes although i invoke killKey() and "invoked killkey()" is printed. I allways get an thread.isActive() = true from this thread. ``` class KeyHan...
2014/05/07
[ "https://Stackoverflow.com/questions/23516150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2720827/" ]
PostQuitMessage has to be posted from the same thread. To do so you need to introduce a global variable `STOP_KEY_HANDLER`. If you want to quit then just set global `STOP_KEY_HANDLER = True` from any thread you want and it will quit with the next keystroke. Your key handler has to run on the main thread. ``` STOP_KEY...
I guess pbackup's solution is fine. Just to conclude I found a solution by simply sending a key myself instead of waiting for the user to input. It's proably not the best but was the fastest an goes parallel in my timing thread with the other timing routines. ``` STOP_KEY_HANDLER = True # send key to kill han...
60,961,248
```py bigger_list_of_names = ['Jim', 'Bob', 'Fred', 'Cam', 'Reagan','Alejandro','Dee','Rana','Denisha','Nicolasa','Annett','Catrina','Louvenia','Emmanuel','Dina','Jasmine','Shirl','Jene','Leona','Lise','Dodie','Kanesha','Carmela','Yuette',] name_list = ['Jim', 'Bob', 'Fred', 'Cam'] search_people = re.compile(r'\b({})\b...
2020/03/31
[ "https://Stackoverflow.com/questions/60961248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13176034/" ]
The second argument to a compiled regular expression is the position in the string to start searching, not flags to use with the regex (the third, also optional argument, is the ending position to search). See the docs for [Regular expression objects](https://docs.python.org/3/library/re.html?highlight=re#re.Pattern.se...
What you are trying to do, does not require a regex search. You can achieve the same as follows. ```py search_result = [] targets = set(names_list) for name in set(bigger_list_of_names): if name in targets: search_result.append(name) print(f'Found name: {name}') else: print(f'Did not fi...
60,961,248
```py bigger_list_of_names = ['Jim', 'Bob', 'Fred', 'Cam', 'Reagan','Alejandro','Dee','Rana','Denisha','Nicolasa','Annett','Catrina','Louvenia','Emmanuel','Dina','Jasmine','Shirl','Jene','Leona','Lise','Dodie','Kanesha','Carmela','Yuette',] name_list = ['Jim', 'Bob', 'Fred', 'Cam'] search_people = re.compile(r'\b({})\b...
2020/03/31
[ "https://Stackoverflow.com/questions/60961248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13176034/" ]
I'm a little late but I had the same issue before. It looks like you are using pycharm, if you check the auto complete thing (if you don't have it turned off) it would say: `pattern.search(self, string, pos, endpos)` Instead of adding flags in the `.search()` part, you will need to add the flags in the `re.compile` p...
What you are trying to do, does not require a regex search. You can achieve the same as follows. ```py search_result = [] targets = set(names_list) for name in set(bigger_list_of_names): if name in targets: search_result.append(name) print(f'Found name: {name}') else: print(f'Did not fi...
41,965,187
To test my tensorflow installation I am using the mnist example provided in tensorflow repository, but when I execute the convolutional.py script I have this output: ``` I tensorflow/stream_executor/dso_loader.cc:125] successfully opened CUDA library libcublas.so.8.0 locally I tensorflow/stream_executor/dso_loader...
2017/01/31
[ "https://Stackoverflow.com/questions/41965187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3094625/" ]
The important points in the output you have shown is this: ``` I tensorflow/core/common_runtime/gpu/gpu_device.cc:885] Found device 0 with properties: name: GeForce GTX 980 Ti major: 5 minor: 2 memoryClockRate (GHz) 1.2405 pciBusID 0000:03:00.0 Total memory: 5.93GiB Free memory: 5.83GiB ``` i.e. the compute device ...
I encountered a similar error when I attempted to run the `classify_image.py` script that is part of [the image recognition tutorial](https://www.tensorflow.org/tutorials/image_recognition). Since I already had a running Python session (elpy) in which I had run some TensorFlow code, the GPUs were allocated there and th...
39,775,489
I'm trying to push a new git repo upstream using gitpython module. Below are the steps that I'm doing and get an error 128. ``` # Initialize a local git repo init_repo = Repo.init(gitlocalrepodir+"%s" %(gitinitrepo)) # Add a file to this new local git repo init_repo.index.add([filename]) # Initial commit init_repo.i...
2016/09/29
[ "https://Stackoverflow.com/questions/39775489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2170456/" ]
I tracked it down with a similar approach: ``` class ProgressPrinter(git.RemoteProgress): def line_dropped(self, line): print("line dropped : " + str(line)) ``` Which you can then call in your code: ``` init_repo.remotes.origin.push(progress=ProgressPrinter()) ```
You need to capture the output from the git command. Given this Progress class: ``` class Progress(git.RemoteProgress): def __init__( self ): super().__init__() self.__all_dropped_lines = [] def update( self, op_code, cur_count, max_count=None, message='' ): pass def line_droppe...
19,546,631
I'm trying to extract values from numerous text files in python. The numbers I require are in the scientific notation form. My result text files are as follows ``` ADDITIONAL DATA Tip Rotation (degrees) Node , UR[x] , UR[y] , UR[z] 21 , 1.0744 , 1.2389 , -4.3271 22 , -1.0744 , -1.2389 , -4.3271 53 ...
2013/10/23
[ "https://Stackoverflow.com/questions/19546631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2739143/" ]
Is this format of file standard one? If so? you can get all your float values with another technic. So, here is the code: ```py str = """ ADDITIONAL DATA Tip Rotation (degrees) Node , UR[x] , UR[y] , UR[z] 21 , 1.0744 , 1.2389 , -4.3271 22 , -1.0744 , -1.2389 , -4.3271 53 , 0.9670 , 1.0307 ,...
I don't get the need for regex, to be honest. Something like this should do what you need: ``` with open(fileName) as f: for line in f: if line.startswith('Partition line'): number=float(line.split(',')[1]) print number # or do whatever you want with it # read other file con...
58,033,457
Hey im trying to create a postgresql db container, im running it using the command: ``` docker-compose up ``` on the following compose file: ``` version: '3.1' services: db: image: postgres restart: always environment: POSTGRES_USERNAME: admin POSTGRES_PASSWORD: admin POSTGRES_DB: d...
2019/09/20
[ "https://Stackoverflow.com/questions/58033457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5273907/" ]
Using POSTGRES\_USER instead of POSTGRES\_USERNAME solved this for me.
You should use POSTGRES\_USER instead of POSTGRES\_USERNAME. Here is my postgres docker-compose configuration for your reference. ``` version: '3' services: postgres: image: 'mdillon/postgis:latest' environment: - TZ=Asia/Shanghai - POSTGRES_USER=postgres - POS...
46,708,708
I'm looking at the best way to compare strings in a python function compiled using numba jit (no python mode, python 3). The use case is the following : ``` import numba as nb @nb.jit(nopython = True, cache = True) def foo(a, t = 'default'): if t == 'awesome': return(a**2) elif t == 'default': ...
2017/10/12
[ "https://Stackoverflow.com/questions/46708708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3640767/" ]
For newer numba versions (0.41.0 and later) =========================================== Numba (since version 0.41.0) support [`str` in nopython mode](http://numba.pydata.org/numba-doc/0.42.0/reference/pysupported.html#str) and the code as written in the question will "just work". However for your example comparing the...
I'd suggest accepting @MSeifert's answer, but as a another option for these types of problems, consider using an `enum`. In python, strings are often used as a sort of enum, and you `numba` has builtin support for enums so they can be used directly. ``` import enum class FooOptions(enum.Enum): AWESOME = 1 DE...
33,009,295
Got kinda surprised with: ``` $ node -p 'process.argv' $SHELL '$SHELL' \t '\t' '\\t' [ 'node', '/bin/bash', '$SHELL', 't', '\\t', '\\\\t' ] $ python -c 'import sys; print sys.argv' $SHELL '$SHELL' \t '\t' '\\t' ['-c', '/bin/bash', '$SHELL', 't', '\\t', '\\\\t'] ``` Expected the same behavior as with: ``` $ echo $S...
2015/10/08
[ "https://Stackoverflow.com/questions/33009295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681785/" ]
Use `$'...'` form to pass escape sequences like `\t`, `\n`, `\r`, `\0` etc in BASH: ``` python -c 'import sys; print sys.argv' $SHELL '$SHELL' \t $'\t' $'\\t' ['-c', '/bin/bash', '$SHELL', 't', '\t', '\\t'] ``` As per `man bash`: > > Words of the form `$'string'` are treated specially. The word expands to string, ...
In both python and node.js, there is a difference between the way `print` works with scalar strings and the way it works with collections. Strings are printed simply as a sequence of characters. The resulting output is generally what the user expects to see, but it cannot be used as the representation of the string in...
39,237,350
How do I remove consecutive duplicates from a list like this in python? ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] ``` Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list. I want the result to be like this: ``` newlst = [1,2,4,1,3,5] ``` Wou...
2016/08/30
[ "https://Stackoverflow.com/questions/39237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5758484/" ]
[itertools.groupby()](https://docs.python.org/3/library/itertools.html#itertools.groupby) is your solution. ``` newlst = [k for k, g in itertools.groupby(lst)] ``` --- If you wish to group and limit the group size by the item's value, meaning 8 4's will be [4,4], and 9 3's will be [3,3,3] here are 2 options that do...
You'd probably want something like this. ``` lst = [1, 1, 2, 2, 2, 2, 3, 3, 4, 1, 2] prev_value = None for number in lst[:]: # the : means we're slicing it, making a copy in other words if number == prev_value: lst.remove(number) else: prev_value = number ``` So, we're going through the list,...
39,237,350
How do I remove consecutive duplicates from a list like this in python? ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] ``` Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list. I want the result to be like this: ``` newlst = [1,2,4,1,3,5] ``` Wou...
2016/08/30
[ "https://Stackoverflow.com/questions/39237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5758484/" ]
``` list1 = ['a', 'a', 'a', 'b', 'b' , 'a', 'f', 'c', 'a','a'] temp_list = [] for item in list1: if len(temp_list) == 0: temp_list.append(item) elif len(temp_list) > 0: if temp_list[-1] != item: temp_list.append(item) print(temp_list) ``` 1. Fetch each item from the main list(list1)...
You'd probably want something like this. ``` lst = [1, 1, 2, 2, 2, 2, 3, 3, 4, 1, 2] prev_value = None for number in lst[:]: # the : means we're slicing it, making a copy in other words if number == prev_value: lst.remove(number) else: prev_value = number ``` So, we're going through the list,...
39,237,350
How do I remove consecutive duplicates from a list like this in python? ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] ``` Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list. I want the result to be like this: ``` newlst = [1,2,4,1,3,5] ``` Wou...
2016/08/30
[ "https://Stackoverflow.com/questions/39237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5758484/" ]
``` list1 = ['a', 'a', 'a', 'b', 'b' , 'a', 'f', 'c', 'a','a'] temp_list = [] for item in list1: if len(temp_list) == 0: temp_list.append(item) elif len(temp_list) > 0: if temp_list[-1] != item: temp_list.append(item) print(temp_list) ``` 1. Fetch each item from the main list(list1)...
``` newlist=[] prev=lst[0] newlist.append(prev) for each in lst[:1]: #to skip 1st lst[0] if(each!=prev): newlist.append(each) prev=each ```
39,237,350
How do I remove consecutive duplicates from a list like this in python? ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] ``` Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list. I want the result to be like this: ``` newlst = [1,2,4,1,3,5] ``` Wou...
2016/08/30
[ "https://Stackoverflow.com/questions/39237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5758484/" ]
[itertools.groupby()](https://docs.python.org/3/library/itertools.html#itertools.groupby) is your solution. ``` newlst = [k for k, g in itertools.groupby(lst)] ``` --- If you wish to group and limit the group size by the item's value, meaning 8 4's will be [4,4], and 9 3's will be [3,3,3] here are 2 options that do...
``` newlist=[] prev=lst[0] newlist.append(prev) for each in lst[:1]: #to skip 1st lst[0] if(each!=prev): newlist.append(each) prev=each ```
39,237,350
How do I remove consecutive duplicates from a list like this in python? ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] ``` Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list. I want the result to be like this: ``` newlst = [1,2,4,1,3,5] ``` Wou...
2016/08/30
[ "https://Stackoverflow.com/questions/39237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5758484/" ]
``` list1 = ['a', 'a', 'a', 'b', 'b' , 'a', 'f', 'c', 'a','a'] temp_list = [] for item in list1: if len(temp_list) == 0: temp_list.append(item) elif len(temp_list) > 0: if temp_list[-1] != item: temp_list.append(item) print(temp_list) ``` 1. Fetch each item from the main list(list1)...
``` st = [''] [st.append(a) for a in [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] if a != st[-1]] print(st[1:]) ```
39,237,350
How do I remove consecutive duplicates from a list like this in python? ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] ``` Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list. I want the result to be like this: ``` newlst = [1,2,4,1,3,5] ``` Wou...
2016/08/30
[ "https://Stackoverflow.com/questions/39237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5758484/" ]
If you want to use the `itertools` method @MaxU suggested, a possible code implementation is: ``` import itertools as it lst=[1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] unique_lst = [i[0] for i in it.groupby(lst)] print(unique_lst) ```
Check if the next element always is not equal to item. If so append. ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] new_item = lst[0] new_list = [lst[0]] for l in lst: if new_item != l: new_list.append(l) new_item = l print new_list print lst ```
39,237,350
How do I remove consecutive duplicates from a list like this in python? ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] ``` Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list. I want the result to be like this: ``` newlst = [1,2,4,1,3,5] ``` Wou...
2016/08/30
[ "https://Stackoverflow.com/questions/39237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5758484/" ]
``` list1 = ['a', 'a', 'a', 'b', 'b' , 'a', 'f', 'c', 'a','a'] temp_list = [] for item in list1: if len(temp_list) == 0: temp_list.append(item) elif len(temp_list) > 0: if temp_list[-1] != item: temp_list.append(item) print(temp_list) ``` 1. Fetch each item from the main list(list1)...
Check if the next element always is not equal to item. If so append. ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] new_item = lst[0] new_list = [lst[0]] for l in lst: if new_item != l: new_list.append(l) new_item = l print new_list print lst ```
39,237,350
How do I remove consecutive duplicates from a list like this in python? ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] ``` Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list. I want the result to be like this: ``` newlst = [1,2,4,1,3,5] ``` Wou...
2016/08/30
[ "https://Stackoverflow.com/questions/39237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5758484/" ]
If you want to use the `itertools` method @MaxU suggested, a possible code implementation is: ``` import itertools as it lst=[1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] unique_lst = [i[0] for i in it.groupby(lst)] print(unique_lst) ```
You'd probably want something like this. ``` lst = [1, 1, 2, 2, 2, 2, 3, 3, 4, 1, 2] prev_value = None for number in lst[:]: # the : means we're slicing it, making a copy in other words if number == prev_value: lst.remove(number) else: prev_value = number ``` So, we're going through the list,...
39,237,350
How do I remove consecutive duplicates from a list like this in python? ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] ``` Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list. I want the result to be like this: ``` newlst = [1,2,4,1,3,5] ``` Wou...
2016/08/30
[ "https://Stackoverflow.com/questions/39237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5758484/" ]
[itertools.groupby()](https://docs.python.org/3/library/itertools.html#itertools.groupby) is your solution. ``` newlst = [k for k, g in itertools.groupby(lst)] ``` --- If you wish to group and limit the group size by the item's value, meaning 8 4's will be [4,4], and 9 3's will be [3,3,3] here are 2 options that do...
Check if the next element always is not equal to item. If so append. ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] new_item = lst[0] new_list = [lst[0]] for l in lst: if new_item != l: new_list.append(l) new_item = l print new_list print lst ```
39,237,350
How do I remove consecutive duplicates from a list like this in python? ``` lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5] ``` Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list. I want the result to be like this: ``` newlst = [1,2,4,1,3,5] ``` Wou...
2016/08/30
[ "https://Stackoverflow.com/questions/39237350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5758484/" ]
[itertools.groupby()](https://docs.python.org/3/library/itertools.html#itertools.groupby) is your solution. ``` newlst = [k for k, g in itertools.groupby(lst)] ``` --- If you wish to group and limit the group size by the item's value, meaning 8 4's will be [4,4], and 9 3's will be [3,3,3] here are 2 options that do...
``` list1 = ['a', 'a', 'a', 'b', 'b' , 'a', 'f', 'c', 'a','a'] temp_list = [] for item in list1: if len(temp_list) == 0: temp_list.append(item) elif len(temp_list) > 0: if temp_list[-1] != item: temp_list.append(item) print(temp_list) ``` 1. Fetch each item from the main list(list1)...
44,859,860
I want to implement the following function in python: [![enter image description here](https://i.stack.imgur.com/MJfQu.png)](https://i.stack.imgur.com/MJfQu.png) I will write the code using 2-loops: ``` for i in range(5): for j in range(5): sum += f(i, j) ``` But the issue is that I have 20 such si...
2017/07/01
[ "https://Stackoverflow.com/questions/44859860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7737948/" ]
You can use [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product) to get cartesian product (of indexes for your cases): ``` >>> import itertools >>> for i, j, k in itertools.product(range(1, 3), repeat=3): ... print(i, j, k) ... 1 1 1 1 1 2 1 2 1 1 2 2 2 1 1 2 1 2 2 2 1 2 2 2 ...
Create Arrays by using Numpy . ``` import numpy as np i = np.asarray([i for i in range(5)]) j = np.asarray([i for i in range(5)]) res = np.sum(f(i,j)) ``` so you can avoide all loops. Important to note is that the function f needs to be able to work with array (a so called ufunc). If your f is mor...
11,706,505
I just started learning python and I am hoping you guys can help me comprehend things a little better. If you have ever played a pokemon game for the gameboy you'll understand more as to what I am trying to do. I started off with a text adventure where you do simple stuff, but now I am at the point of pokemon battling ...
2012/07/29
[ "https://Stackoverflow.com/questions/11706505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1364915/" ]
If I was to have `fight` as a instance method (which I'm not sure I would), I would probably code it up something like this: ``` class Pokemon(object): def __init__(self,name,hp,damage): self.name = name #pokemon name self.hp = hp #hit-points of this particular pokemon self.dama...
1. You don't need the variables up the top. You just need them in the **init**() method. 2. The fight method should return a value: ``` def fight(self, target): target.nHealth -= self.nAttack return target ``` 3. You probably want to also check if someone has lost the battle: ``` def checkWin(myPoke, target...
11,706,505
I just started learning python and I am hoping you guys can help me comprehend things a little better. If you have ever played a pokemon game for the gameboy you'll understand more as to what I am trying to do. I started off with a text adventure where you do simple stuff, but now I am at the point of pokemon battling ...
2012/07/29
[ "https://Stackoverflow.com/questions/11706505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1364915/" ]
If I was to have `fight` as a instance method (which I'm not sure I would), I would probably code it up something like this: ``` class Pokemon(object): def __init__(self,name,hp,damage): self.name = name #pokemon name self.hp = hp #hit-points of this particular pokemon self.dama...
*I am only going to comment on a few obvious aspects, because a complete code review is beyond the scope of this site (try [codereview.stackexchange.com](https://codereview.stackexchange.com/))* Your `fight()` method isn't saving the results of the subtraction, so nothing is changed. You would need to do something lik...
4,414,767
I'm trying to modify an existing [Django Mezzanine](http://mezzanine.jupo.org/) setup to allow me to blog in Markdown. Mezzanine has a "Core" model that has content as an HtmlField which is defined like so: ``` from django.db.models import TextField class HtmlField(TextField): """ TextField that stores HT...
2010/12/11
[ "https://Stackoverflow.com/questions/4414767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147562/" ]
If you mean back references, then yes Java has this. You can refer to a capturing group inside a regular expression using the notation `\1` for the first group, `\2` for the second, etc. Note that inside a string literal the backslashes must be escaped.
The Java `java.util.regex.Pattern` class supports backreferences using the `\n` syntax. See [the documentation](http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html) for more details.
18,269,218
I'm trying to use django's queryset API to emulate the following query: ``` SELECT EXTRACT(year FROM chosen_date) AS year, EXTRACT(month FROM chosen_date) AS month, date_paid IS NOT NULL as is_paid FROM (SELECT (CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date,* FROM invoice_invoice) as t1...
2013/08/16
[ "https://Stackoverflow.com/questions/18269218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122757/" ]
Well here're some workarounds **1.** In your particular case you could do it with one extra: ``` if use_date_due: sum_qs = sum_qs.extra(select={ 'year': 'EXTRACT(year FROM coalesce(date_due, date))', 'month': 'EXTRACT(month FROM coalesce(date_due, date))', ...
Would this work?: ``` from django.db import connection, transaction cursor = connection.cursor() sql = """ SELECT %s AS year, %s AS month, date_paid IS NOT NULL as is_paid FROM ( SELECT (CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date, * ...
18,269,218
I'm trying to use django's queryset API to emulate the following query: ``` SELECT EXTRACT(year FROM chosen_date) AS year, EXTRACT(month FROM chosen_date) AS month, date_paid IS NOT NULL as is_paid FROM (SELECT (CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date,* FROM invoice_invoice) as t1...
2013/08/16
[ "https://Stackoverflow.com/questions/18269218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122757/" ]
Well here're some workarounds **1.** In your particular case you could do it with one extra: ``` if use_date_due: sum_qs = sum_qs.extra(select={ 'year': 'EXTRACT(year FROM coalesce(date_due, date))', 'month': 'EXTRACT(month FROM coalesce(date_due, date))', ...
You could add a property to your model definition and then do : ``` @property def chosen_date(self): return self.due_date if self.due_date else self.date ``` This assumes you can always fallback to date.If you prefer you can catch a DoesNotExist exception on due\_date and then check for the second one. You acce...
18,269,218
I'm trying to use django's queryset API to emulate the following query: ``` SELECT EXTRACT(year FROM chosen_date) AS year, EXTRACT(month FROM chosen_date) AS month, date_paid IS NOT NULL as is_paid FROM (SELECT (CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date,* FROM invoice_invoice) as t1...
2013/08/16
[ "https://Stackoverflow.com/questions/18269218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122757/" ]
Well here're some workarounds **1.** In your particular case you could do it with one extra: ``` if use_date_due: sum_qs = sum_qs.extra(select={ 'year': 'EXTRACT(year FROM coalesce(date_due, date))', 'month': 'EXTRACT(month FROM coalesce(date_due, date))', ...
Just use the raw sql. The raw() manager method can be used to perform raw SQL queries that return model instances. <https://docs.djangoproject.com/en/1.5/topics/db/sql/#performing-raw-sql-queries>
18,269,218
I'm trying to use django's queryset API to emulate the following query: ``` SELECT EXTRACT(year FROM chosen_date) AS year, EXTRACT(month FROM chosen_date) AS month, date_paid IS NOT NULL as is_paid FROM (SELECT (CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date,* FROM invoice_invoice) as t1...
2013/08/16
[ "https://Stackoverflow.com/questions/18269218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122757/" ]
**Short answer:** If you create an aliased (or computed) column using `extra(select=...)` then you cannot use the aliased column in a subsequent call to `filter()`. Also, as you've discovered, you can't use the aliased column in later calls to `extra(select=...)` or `extra(where=...)`. **An attempt to explain why:** ...
Well here're some workarounds **1.** In your particular case you could do it with one extra: ``` if use_date_due: sum_qs = sum_qs.extra(select={ 'year': 'EXTRACT(year FROM coalesce(date_due, date))', 'month': 'EXTRACT(month FROM coalesce(date_due, date))', ...
18,269,218
I'm trying to use django's queryset API to emulate the following query: ``` SELECT EXTRACT(year FROM chosen_date) AS year, EXTRACT(month FROM chosen_date) AS month, date_paid IS NOT NULL as is_paid FROM (SELECT (CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date,* FROM invoice_invoice) as t1...
2013/08/16
[ "https://Stackoverflow.com/questions/18269218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122757/" ]
**Short answer:** If you create an aliased (or computed) column using `extra(select=...)` then you cannot use the aliased column in a subsequent call to `filter()`. Also, as you've discovered, you can't use the aliased column in later calls to `extra(select=...)` or `extra(where=...)`. **An attempt to explain why:** ...
Would this work?: ``` from django.db import connection, transaction cursor = connection.cursor() sql = """ SELECT %s AS year, %s AS month, date_paid IS NOT NULL as is_paid FROM ( SELECT (CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date, * ...
18,269,218
I'm trying to use django's queryset API to emulate the following query: ``` SELECT EXTRACT(year FROM chosen_date) AS year, EXTRACT(month FROM chosen_date) AS month, date_paid IS NOT NULL as is_paid FROM (SELECT (CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date,* FROM invoice_invoice) as t1...
2013/08/16
[ "https://Stackoverflow.com/questions/18269218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122757/" ]
**Short answer:** If you create an aliased (or computed) column using `extra(select=...)` then you cannot use the aliased column in a subsequent call to `filter()`. Also, as you've discovered, you can't use the aliased column in later calls to `extra(select=...)` or `extra(where=...)`. **An attempt to explain why:** ...
You could add a property to your model definition and then do : ``` @property def chosen_date(self): return self.due_date if self.due_date else self.date ``` This assumes you can always fallback to date.If you prefer you can catch a DoesNotExist exception on due\_date and then check for the second one. You acce...
18,269,218
I'm trying to use django's queryset API to emulate the following query: ``` SELECT EXTRACT(year FROM chosen_date) AS year, EXTRACT(month FROM chosen_date) AS month, date_paid IS NOT NULL as is_paid FROM (SELECT (CASE WHEN date_due IS NULL THEN date_due ELSE date END) AS chosen_date,* FROM invoice_invoice) as t1...
2013/08/16
[ "https://Stackoverflow.com/questions/18269218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122757/" ]
**Short answer:** If you create an aliased (or computed) column using `extra(select=...)` then you cannot use the aliased column in a subsequent call to `filter()`. Also, as you've discovered, you can't use the aliased column in later calls to `extra(select=...)` or `extra(where=...)`. **An attempt to explain why:** ...
Just use the raw sql. The raw() manager method can be used to perform raw SQL queries that return model instances. <https://docs.djangoproject.com/en/1.5/topics/db/sql/#performing-raw-sql-queries>
67,800,225
I have elastic search cluster. Currently designing a python service for client for read and write query to my elastic search. The python service will not be maintained by me. Only internally python service will call our elastic search for fetching and writing Is there any way to configure the elastic search so that w...
2021/06/02
[ "https://Stackoverflow.com/questions/67800225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8989219/" ]
``` SELECT id FROM books EXCEPT ( SELECT bookid FROM books_authors WHERE authorId='A2' ) ```
``` SELECT * FROM books WHERE id NOT IN (SELECT bookid FROM books_authors WHERE authorid = 'A2') ```
67,800,225
I have elastic search cluster. Currently designing a python service for client for read and write query to my elastic search. The python service will not be maintained by me. Only internally python service will call our elastic search for fetching and writing Is there any way to configure the elastic search so that w...
2021/06/02
[ "https://Stackoverflow.com/questions/67800225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8989219/" ]
``` SELECT * FROM books WHERE id NOT IN (SELECT bookid FROM books_authors WHERE authorid = 'A2') ```
Query using JOIN: ``` SELECT DISTINCT books.* FROM books LEFT JOIN books_authors ON books_authors.bookId = books.id AND authorId <> 'A2' WHERE authorId IS NOT NULL; ``` [PostgreSQL fiddle](https://sqlize.online/?phpses=null&sqlses=5d017a400d41f0abd33c3f0e1d83e69a&php_version=null&sql_version=psql12) Result: ``` ...
67,800,225
I have elastic search cluster. Currently designing a python service for client for read and write query to my elastic search. The python service will not be maintained by me. Only internally python service will call our elastic search for fetching and writing Is there any way to configure the elastic search so that w...
2021/06/02
[ "https://Stackoverflow.com/questions/67800225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8989219/" ]
``` SELECT * FROM books WHERE id NOT IN (SELECT bookid FROM books_authors WHERE authorid = 'A2') ```
I would suggest `not exists`: ``` select b.* from books b where not exists (select 1 from book_authors ba join authors a on ba.authorid = a.id where ba.bookid = b.id and a.name = 'Dewey' ); ``` ...
67,800,225
I have elastic search cluster. Currently designing a python service for client for read and write query to my elastic search. The python service will not be maintained by me. Only internally python service will call our elastic search for fetching and writing Is there any way to configure the elastic search so that w...
2021/06/02
[ "https://Stackoverflow.com/questions/67800225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8989219/" ]
``` SELECT id FROM books EXCEPT ( SELECT bookid FROM books_authors WHERE authorId='A2' ) ```
Query using JOIN: ``` SELECT DISTINCT books.* FROM books LEFT JOIN books_authors ON books_authors.bookId = books.id AND authorId <> 'A2' WHERE authorId IS NOT NULL; ``` [PostgreSQL fiddle](https://sqlize.online/?phpses=null&sqlses=5d017a400d41f0abd33c3f0e1d83e69a&php_version=null&sql_version=psql12) Result: ``` ...
67,800,225
I have elastic search cluster. Currently designing a python service for client for read and write query to my elastic search. The python service will not be maintained by me. Only internally python service will call our elastic search for fetching and writing Is there any way to configure the elastic search so that w...
2021/06/02
[ "https://Stackoverflow.com/questions/67800225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8989219/" ]
``` SELECT id FROM books EXCEPT ( SELECT bookid FROM books_authors WHERE authorId='A2' ) ```
I would suggest `not exists`: ``` select b.* from books b where not exists (select 1 from book_authors ba join authors a on ba.authorid = a.id where ba.bookid = b.id and a.name = 'Dewey' ); ``` ...
63,483,417
Say I have a dataframe ``` id category 1 A 2 A 3 B 4 C 5 A ``` And I want to create a new column with incremental values where `category == 'A'`. So it should be something like. ``` id category value 1 A 1 2 A 2 3 B NaN 4 C NaN 5 A 3 ``` Curre...
2020/08/19
[ "https://Stackoverflow.com/questions/63483417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1676881/" ]
The following code for GNU sed: ``` sed 's/EndHere/&\n/g; s/\(StartHere\)[^\n]*\(EndHere\|$\)/\1\2/g; s/\n//g' <<EOF StartHere Word1 EndHere StartHere Word2 StartHere Word2 EndHere something else something else StartHere Word2 EndHere something else EOF ``` outputs: ``` StartHereEndHere StartHere StartHereEndHere s...
Instead of using `sed`, you could do it with Perl, which supports [negative lookahead](http://www.regular-expressions.info/lookaround.html). Using the example you gave in your comment: ``` $ echo "oooo StartHere=Yo9897 EndHereYo" \ | perl -pe 's/(StartHere) (?: .*(EndHere) | .*(?!EndHere) )/$1$2/x' ``` would outp...
42,357,563
I am thinking of different ways to take the sum of squares in python. I have found that the following works using list comprehensions: ``` def sum_of_squares(n): return sum(x ** 2 for x in range(1, n)) ``` But, when using lambda functions, the following does not compute: ``` def sum_of_squares_lambda(n): re...
2017/02/21
[ "https://Stackoverflow.com/questions/42357563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4382972/" ]
Think about what `reduce` does. It takes the output of one call and uses it as the first argument when calling the same function again. So imagine n is 4. Suppose you call your lambda `f`. Then you are doing `f(f(1, 2), 3)`. That is equivalent to: ``` (1**2 + 2**2)**2 + 3**2 ``` Because the first argument to your la...
You're only supposed to square each successive element. `x**2 + y**2` squares the running total (`x`) as well as each successive element (`y`). Change that to `x + y**2` and you'll get the correct result. Note that, as mentioned in comments, this requires a proper initial value as well, so you should pass `0` as the op...
42,357,563
I am thinking of different ways to take the sum of squares in python. I have found that the following works using list comprehensions: ``` def sum_of_squares(n): return sum(x ** 2 for x in range(1, n)) ``` But, when using lambda functions, the following does not compute: ``` def sum_of_squares_lambda(n): re...
2017/02/21
[ "https://Stackoverflow.com/questions/42357563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4382972/" ]
You're only supposed to square each successive element. `x**2 + y**2` squares the running total (`x`) as well as each successive element (`y`). Change that to `x + y**2` and you'll get the correct result. Note that, as mentioned in comments, this requires a proper initial value as well, so you should pass `0` as the op...
(for python 3 users) ``` from functools import reduce ``` To be able to use `reduce`. Second, your function `sum_of_squares_lambda` won't work the way you expect it to because `reduce` will take twice (instead of once) every argument except the first and the last one.
42,357,563
I am thinking of different ways to take the sum of squares in python. I have found that the following works using list comprehensions: ``` def sum_of_squares(n): return sum(x ** 2 for x in range(1, n)) ``` But, when using lambda functions, the following does not compute: ``` def sum_of_squares_lambda(n): re...
2017/02/21
[ "https://Stackoverflow.com/questions/42357563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4382972/" ]
You're only supposed to square each successive element. `x**2 + y**2` squares the running total (`x`) as well as each successive element (`y`). Change that to `x + y**2` and you'll get the correct result. Note that, as mentioned in comments, this requires a proper initial value as well, so you should pass `0` as the op...
Suppose you plug in 4: ``` 1^2 + 2^2 = 5 (you then take this result and put it back in the lambda) 5^2 + 3^2 = 34 (for reference the correct answer is 14) ``` It squares the "previous" sum as well in the `lambda`. (You also have an off by one issue, it should be `n+1` in your range calls.)
42,357,563
I am thinking of different ways to take the sum of squares in python. I have found that the following works using list comprehensions: ``` def sum_of_squares(n): return sum(x ** 2 for x in range(1, n)) ``` But, when using lambda functions, the following does not compute: ``` def sum_of_squares_lambda(n): re...
2017/02/21
[ "https://Stackoverflow.com/questions/42357563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4382972/" ]
Think about what `reduce` does. It takes the output of one call and uses it as the first argument when calling the same function again. So imagine n is 4. Suppose you call your lambda `f`. Then you are doing `f(f(1, 2), 3)`. That is equivalent to: ``` (1**2 + 2**2)**2 + 3**2 ``` Because the first argument to your la...
(for python 3 users) ``` from functools import reduce ``` To be able to use `reduce`. Second, your function `sum_of_squares_lambda` won't work the way you expect it to because `reduce` will take twice (instead of once) every argument except the first and the last one.
42,357,563
I am thinking of different ways to take the sum of squares in python. I have found that the following works using list comprehensions: ``` def sum_of_squares(n): return sum(x ** 2 for x in range(1, n)) ``` But, when using lambda functions, the following does not compute: ``` def sum_of_squares_lambda(n): re...
2017/02/21
[ "https://Stackoverflow.com/questions/42357563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4382972/" ]
Think about what `reduce` does. It takes the output of one call and uses it as the first argument when calling the same function again. So imagine n is 4. Suppose you call your lambda `f`. Then you are doing `f(f(1, 2), 3)`. That is equivalent to: ``` (1**2 + 2**2)**2 + 3**2 ``` Because the first argument to your la...
Suppose you plug in 4: ``` 1^2 + 2^2 = 5 (you then take this result and put it back in the lambda) 5^2 + 3^2 = 34 (for reference the correct answer is 14) ``` It squares the "previous" sum as well in the `lambda`. (You also have an off by one issue, it should be `n+1` in your range calls.)
42,357,563
I am thinking of different ways to take the sum of squares in python. I have found that the following works using list comprehensions: ``` def sum_of_squares(n): return sum(x ** 2 for x in range(1, n)) ``` But, when using lambda functions, the following does not compute: ``` def sum_of_squares_lambda(n): re...
2017/02/21
[ "https://Stackoverflow.com/questions/42357563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4382972/" ]
Suppose you plug in 4: ``` 1^2 + 2^2 = 5 (you then take this result and put it back in the lambda) 5^2 + 3^2 = 34 (for reference the correct answer is 14) ``` It squares the "previous" sum as well in the `lambda`. (You also have an off by one issue, it should be `n+1` in your range calls.)
(for python 3 users) ``` from functools import reduce ``` To be able to use `reduce`. Second, your function `sum_of_squares_lambda` won't work the way you expect it to because `reduce` will take twice (instead of once) every argument except the first and the last one.
36,663,727
I have two UI windows created with QT Designer. I have two separate python scripts for each UI. What I'm trying to do is the first script opens a window, creates a thread that looks for a certain condition, then when found, opens the second UI. Then the second UI creates a thread, and when done, opens the first UI. Th...
2016/04/16
[ "https://Stackoverflow.com/questions/36663727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5897068/" ]
Checkout the docs here: <https://code.visualstudio.com/Docs/customization/colorizer> You basically either get one from the marketplace or generate a basic editable file with yeoman. You can also add themes even from color sublime as described here: <https://code.visualstudio.com/docs/customization/themes>
Install theme from extensions from which you wish to start. Then find where the theme got installed. On Windows it would be `%USERPROFILE%\.vscode\extensions`, see details in [Installing extensions](https://code.visualstudio.com/docs/extensions/install-extension). There you'll find folder with theme, inside is `theme...
26,259,870
I am new to java (well I played with it a few times), and I am wondering: => How to do *fast* independent prototypes ? something like one file projects. The last few years, I worked with python. Each time I had to develop some new functionality or algorithm, I would make a simple python module (i.e. file) just for it...
2014/10/08
[ "https://Stackoverflow.com/questions/26259870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206998/" ]
Definitely take a look at [Spring Boot](http://docs.spring.io/spring-boot/docs/1.2.2.RELEASE/reference/htmlsingle/#getting-started-introducing-spring-boot). Relatively new project. Its aim is to remove initial configuration phase and spin up Spring apps quickly. You can think about it as convention over configuration w...
What does "develop and run independent code in this context" mean? Do you mean "small standalone example code snippets?" * Use the Maven exec plugin * Write unit/integration tests * Bring your Maven dependencies into something like a JRuby REPL
32,934,653
I am trying to load a CSV file into HDFS and read the same into Spark as RDDs. I am using Hortonworks Sandbox and trying these through the command line. I loaded the data as follows: ``` hadoop fs -put data.csv / ``` The data seems to have loaded properly as seen by the following command: ``` [root@sandbox temp]# h...
2015/10/04
[ "https://Stackoverflow.com/questions/32934653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1002903/" ]
I figured the answer out. I had to enter the complete path name of the HDFS file as follows: ``` data = sc.textFile('hdfs://sandbox.hortonworks.com:8020/data.csv') ``` The full path name is obtained from conf/core-site.xml
Error `org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/data.csv` It is reading from you local file system instead of hdfs. Try providing file path like below, ``` data = sc.textFile("hdfs://data.csv") ```
32,934,653
I am trying to load a CSV file into HDFS and read the same into Spark as RDDs. I am using Hortonworks Sandbox and trying these through the command line. I loaded the data as follows: ``` hadoop fs -put data.csv / ``` The data seems to have loaded properly as seen by the following command: ``` [root@sandbox temp]# h...
2015/10/04
[ "https://Stackoverflow.com/questions/32934653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1002903/" ]
I figured the answer out. I had to enter the complete path name of the HDFS file as follows: ``` data = sc.textFile('hdfs://sandbox.hortonworks.com:8020/data.csv') ``` The full path name is obtained from conf/core-site.xml
In case you want to create an rdd for any text or csv file available in the local system, use `rdd = sc.textFile("file://path/to/csv or text file")`
69,395,204
I have a list of dict I want to group by multiple keys. I have used sort by default in python dict ``` data = [ [], [{'value': 8, 'bot': 'DB', 'month': 9, 'year': 2020}, {'value': 79, 'bot': 'DB', 'month': 10, 'year': 2020}, {'value': 126, 'bot': 'DB', 'month':8, 'year': 2021}], [], [{'value': 222, 'bot': 'GEMBOT', '...
2021/09/30
[ "https://Stackoverflow.com/questions/69395204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9538877/" ]
Maybe try: ``` from pprint import pprint import datetime output_dict = [] for i in data: if i: for j in i: for key, val in sorted(j.items()): if key == "bot": temp["bot"] = val elif key == "value": temp["value"] = val elif key == "month": month = date...
Maybe try: ``` output = [] for i in data: if not i: pass for j in i: output.append(j) ``` And then if you want to sort it, then you can use `sorted_output = sorted(ouput, key=lambda k: k['bot'])` to sort it by `bot` for example. If you want to sort it by date, maybe create a value that calcu...
69,395,204
I have a list of dict I want to group by multiple keys. I have used sort by default in python dict ``` data = [ [], [{'value': 8, 'bot': 'DB', 'month': 9, 'year': 2020}, {'value': 79, 'bot': 'DB', 'month': 10, 'year': 2020}, {'value': 126, 'bot': 'DB', 'month':8, 'year': 2021}], [], [{'value': 222, 'bot': 'GEMBOT', '...
2021/09/30
[ "https://Stackoverflow.com/questions/69395204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9538877/" ]
Two things will make this easier to answer. The first is a list comprehension that will promote sub-items: ``` data_reshaped = [cell for row in data for cell in row] ``` this will take your original `data` and flatten it a bit to: ``` [ {'value': 8, 'bot': 'DB', 'month': 9, 'year': 2020}, {'value': 79, 'bot...
Maybe try: ``` output = [] for i in data: if not i: pass for j in i: output.append(j) ``` And then if you want to sort it, then you can use `sorted_output = sorted(ouput, key=lambda k: k['bot'])` to sort it by `bot` for example. If you want to sort it by date, maybe create a value that calcu...
69,395,204
I have a list of dict I want to group by multiple keys. I have used sort by default in python dict ``` data = [ [], [{'value': 8, 'bot': 'DB', 'month': 9, 'year': 2020}, {'value': 79, 'bot': 'DB', 'month': 10, 'year': 2020}, {'value': 126, 'bot': 'DB', 'month':8, 'year': 2021}], [], [{'value': 222, 'bot': 'GEMBOT', '...
2021/09/30
[ "https://Stackoverflow.com/questions/69395204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9538877/" ]
Two things will make this easier to answer. The first is a list comprehension that will promote sub-items: ``` data_reshaped = [cell for row in data for cell in row] ``` this will take your original `data` and flatten it a bit to: ``` [ {'value': 8, 'bot': 'DB', 'month': 9, 'year': 2020}, {'value': 79, 'bot...
Maybe try: ``` from pprint import pprint import datetime output_dict = [] for i in data: if i: for j in i: for key, val in sorted(j.items()): if key == "bot": temp["bot"] = val elif key == "value": temp["value"] = val elif key == "month": month = date...
1,586,423
I wrote a basic [Hippity Hop](http://www.facebook.com/careers/puzzles.php?puzzle_id=7) program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this: * Python: .350 seconds * C: .050 seconds * *interpreted* OCaml: .040 seco...
2009/10/19
[ "https://Stackoverflow.com/questions/1586423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Time under 0.05 can be a simple noise. Repeat the main program enough times to actually get ~1s of execution time in C. (I mean repeating it in a loop in the program itself, not by running it again) Did you compile your code with optimisations turned on? Did you try reducing the number of branches? (and comparisons) ...
I would be interested to see how much time is spent in get\_count(). I'm not sure how much it would matter, but you're reading in a long as a string, which means the string cannot be larger than 20 bytes, or 10 bytes (2^64 = some 20 character long decimal number, or 2^32 = some 10 character long decimal number), so yo...
1,586,423
I wrote a basic [Hippity Hop](http://www.facebook.com/careers/puzzles.php?puzzle_id=7) program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this: * Python: .350 seconds * C: .050 seconds * *interpreted* OCaml: .040 seco...
2009/10/19
[ "https://Stackoverflow.com/questions/1586423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Time under 0.05 can be a simple noise. Repeat the main program enough times to actually get ~1s of execution time in C. (I mean repeating it in a loop in the program itself, not by running it again) Did you compile your code with optimisations turned on? Did you try reducing the number of branches? (and comparisons) ...
Any program which mostly involves opening a file and reading it is limited by the speed of opening a file and reading it. The C computations you are doing here will take between 1 millionth and one thousandth of the time of opening the file and reading it. I thought this site was useful: <http://norvig.com/21-days.htm...
1,586,423
I wrote a basic [Hippity Hop](http://www.facebook.com/careers/puzzles.php?puzzle_id=7) program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this: * Python: .350 seconds * C: .050 seconds * *interpreted* OCaml: .040 seco...
2009/10/19
[ "https://Stackoverflow.com/questions/1586423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Your C code isn't the equivalent of the OCaml code - you used 'else if' in the OCaml to avoid having to recompute moduli quite so much. There's an awful lot of code in that 'read the long integer'. Why not just use `fscanf()`; it skips blanks and all that automatically, and avoids you doing the `malloc()` etc. I don't...
Time under 0.05 can be a simple noise. Repeat the main program enough times to actually get ~1s of execution time in C. (I mean repeating it in a loop in the program itself, not by running it again) Did you compile your code with optimisations turned on? Did you try reducing the number of branches? (and comparisons) ...
1,586,423
I wrote a basic [Hippity Hop](http://www.facebook.com/careers/puzzles.php?puzzle_id=7) program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this: * Python: .350 seconds * C: .050 seconds * *interpreted* OCaml: .040 seco...
2009/10/19
[ "https://Stackoverflow.com/questions/1586423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Time under 0.05 can be a simple noise. Repeat the main program enough times to actually get ~1s of execution time in C. (I mean repeating it in a loop in the program itself, not by running it again) Did you compile your code with optimisations turned on? Did you try reducing the number of branches? (and comparisons) ...
In a tiny program like this, it's often hard to guess why things work out the way they do. I think if I was doing it, I'd write the code like this (leaving out error checking for the moment): ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { static char buffer[20]; int limit, i;...
1,586,423
I wrote a basic [Hippity Hop](http://www.facebook.com/careers/puzzles.php?puzzle_id=7) program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this: * Python: .350 seconds * C: .050 seconds * *interpreted* OCaml: .040 seco...
2009/10/19
[ "https://Stackoverflow.com/questions/1586423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Your C code isn't the equivalent of the OCaml code - you used 'else if' in the OCaml to avoid having to recompute moduli quite so much. There's an awful lot of code in that 'read the long integer'. Why not just use `fscanf()`; it skips blanks and all that automatically, and avoids you doing the `malloc()` etc. I don't...
I would be interested to see how much time is spent in get\_count(). I'm not sure how much it would matter, but you're reading in a long as a string, which means the string cannot be larger than 20 bytes, or 10 bytes (2^64 = some 20 character long decimal number, or 2^32 = some 10 character long decimal number), so yo...
1,586,423
I wrote a basic [Hippity Hop](http://www.facebook.com/careers/puzzles.php?puzzle_id=7) program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this: * Python: .350 seconds * C: .050 seconds * *interpreted* OCaml: .040 seco...
2009/10/19
[ "https://Stackoverflow.com/questions/1586423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
In a tiny program like this, it's often hard to guess why things work out the way they do. I think if I was doing it, I'd write the code like this (leaving out error checking for the moment): ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { static char buffer[20]; int limit, i;...
I would be interested to see how much time is spent in get\_count(). I'm not sure how much it would matter, but you're reading in a long as a string, which means the string cannot be larger than 20 bytes, or 10 bytes (2^64 = some 20 character long decimal number, or 2^32 = some 10 character long decimal number), so yo...
1,586,423
I wrote a basic [Hippity Hop](http://www.facebook.com/careers/puzzles.php?puzzle_id=7) program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this: * Python: .350 seconds * C: .050 seconds * *interpreted* OCaml: .040 seco...
2009/10/19
[ "https://Stackoverflow.com/questions/1586423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Your C code isn't the equivalent of the OCaml code - you used 'else if' in the OCaml to avoid having to recompute moduli quite so much. There's an awful lot of code in that 'read the long integer'. Why not just use `fscanf()`; it skips blanks and all that automatically, and avoids you doing the `malloc()` etc. I don't...
Any program which mostly involves opening a file and reading it is limited by the speed of opening a file and reading it. The C computations you are doing here will take between 1 millionth and one thousandth of the time of opening the file and reading it. I thought this site was useful: <http://norvig.com/21-days.htm...
1,586,423
I wrote a basic [Hippity Hop](http://www.facebook.com/careers/puzzles.php?puzzle_id=7) program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this: * Python: .350 seconds * C: .050 seconds * *interpreted* OCaml: .040 seco...
2009/10/19
[ "https://Stackoverflow.com/questions/1586423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
In a tiny program like this, it's often hard to guess why things work out the way they do. I think if I was doing it, I'd write the code like this (leaving out error checking for the moment): ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { static char buffer[20]; int limit, i;...
Any program which mostly involves opening a file and reading it is limited by the speed of opening a file and reading it. The C computations you are doing here will take between 1 millionth and one thousandth of the time of opening the file and reading it. I thought this site was useful: <http://norvig.com/21-days.htm...
1,586,423
I wrote a basic [Hippity Hop](http://www.facebook.com/careers/puzzles.php?puzzle_id=7) program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this: * Python: .350 seconds * C: .050 seconds * *interpreted* OCaml: .040 seco...
2009/10/19
[ "https://Stackoverflow.com/questions/1586423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
Your C code isn't the equivalent of the OCaml code - you used 'else if' in the OCaml to avoid having to recompute moduli quite so much. There's an awful lot of code in that 'read the long integer'. Why not just use `fscanf()`; it skips blanks and all that automatically, and avoids you doing the `malloc()` etc. I don't...
In a tiny program like this, it's often hard to guess why things work out the way they do. I think if I was doing it, I'd write the code like this (leaving out error checking for the moment): ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { static char buffer[20]; int limit, i;...
47,489,567
I've been stuck on this one for hours now. I'm making a homemade smarthome terminal, and have been tinkering with kivy for about 2 weeks and it's been great so far. I'm at the point where I want to show the temperature inside a label inside a screen. I've made an actionbar with 4 buttons that slides through screens whe...
2017/11/25
[ "https://Stackoverflow.com/questions/47489567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977709/" ]
there is no id TempLabel in your menu first thing, you must add the TempLabel in your kv: ``` ... <ScreenThermo>: Label: id: TempLabel text: "stuff1" ... ``` then update the right label: ``` ... class Menu(BoxLayout): manager = ObjectProperty(None) def __init__(self,**kwargs): s...
use a StringProperty ``` <ScreenThermo>: Label: #this is where i want my label that shows the temperature my sensor reads text: root.thermo_text class ScreenThermo(BoxLayout): thermo_text = StringProperty("stuff") ... ``` then any time you want to seet the text just do ``` my_screen.ther...
47,489,567
I've been stuck on this one for hours now. I'm making a homemade smarthome terminal, and have been tinkering with kivy for about 2 weeks and it's been great so far. I'm at the point where I want to show the temperature inside a label inside a screen. I've made an actionbar with 4 buttons that slides through screens whe...
2017/11/25
[ "https://Stackoverflow.com/questions/47489567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977709/" ]
use a StringProperty ``` <ScreenThermo>: Label: #this is where i want my label that shows the temperature my sensor reads text: root.thermo_text class ScreenThermo(BoxLayout): thermo_text = StringProperty("stuff") ... ``` then any time you want to seet the text just do ``` my_screen.ther...
Using ObjectProperty ==================== In the example, I used an ObjectProperty to hook up to the label for temperature because an id is a weakref to the widget. Using an ***ObjectProperty*** creates a direct reference, provides faster access and is more explicit. main.py ------- ### 1. Import External Script ``...
47,489,567
I've been stuck on this one for hours now. I'm making a homemade smarthome terminal, and have been tinkering with kivy for about 2 weeks and it's been great so far. I'm at the point where I want to show the temperature inside a label inside a screen. I've made an actionbar with 4 buttons that slides through screens whe...
2017/11/25
[ "https://Stackoverflow.com/questions/47489567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977709/" ]
there is no id TempLabel in your menu first thing, you must add the TempLabel in your kv: ``` ... <ScreenThermo>: Label: id: TempLabel text: "stuff1" ... ``` then update the right label: ``` ... class Menu(BoxLayout): manager = ObjectProperty(None) def __init__(self,**kwargs): s...
Using ObjectProperty ==================== In the example, I used an ObjectProperty to hook up to the label for temperature because an id is a weakref to the widget. Using an ***ObjectProperty*** creates a direct reference, provides faster access and is more explicit. main.py ------- ### 1. Import External Script ``...
60,036,522
**I am learning 'Automate the Boring Stuff with Python', here is the code in the book:** ``` import csv, os os.makedirs('headerRemoved', exist_ok=True) #Loop through every file in the current working directory) for csvFilename in os.listdir('C://Users//Xinxin//Desktop//123'): if not csvFilename.endswith('.csv'...
2020/02/03
[ "https://Stackoverflow.com/questions/60036522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12831792/" ]
> > but when I move the python program out of the csv folder, and run the code, then it shows > > > 1) This is the problem. Try adding the directory of the files to your removeheader.py (first line): ``` import sys sys.path.append(r'C:/Users/Xinxin/Desktop/123') ``` 2) Store the files in the same location as th...
You can need get current directory. Then add current directory with file name. Example: ``` currentDir = os.getcwd() currentFileCSV = currentDir +"//" + csvFilename csvFileObj = open(currentFileCSV) ```
31,090,479
I think I'm not understanding something basic about python's argparse. I am trying to use the Google YouTube API for python script, but I am not understanding how to pass values to the script without using the command line. For example, [here](https://developers.google.com/youtube/v3/docs/videos/insert) is the exampl...
2015/06/27
[ "https://Stackoverflow.com/questions/31090479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3449806/" ]
Whether it is the best approach or not is really for you to figure out. But using argparse without command line is **easy**. I do it all the time because I have batches that can be run from the command line. Or can also be called by other code - which is great for unit testing, as mentioned. argparse is especially good...
Calling `parse_args` with your own list of strings is a common `argparse` testing method. If you don't give `parse_args` this list, it uses `sys.argv[1:]` - i.e. the strings that the shell gives. `sys.argv[0]` is the strip name. ``` args = argparser.parse_args(['--foo','foovalue','barvalue']) ``` It is also easy to ...
16,213,235
a methodology question: I have a "main" python script which runs on an infinite loop on my system, and I want to send information to it (a json data string for example) occasionally with some other python scripts that will be started later by myself or another program and will end just after sending the string. I can...
2013/04/25
[ "https://Stackoverflow.com/questions/16213235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112326/" ]
zeromq: <http://www.zeromq.org/> - is best solution for interprocess communications imho and have a excelent binding for python: <http://www.zeromq.org/bindings:python>
Since the "main" script looks like a service you can enhance it with a web API. [bottle](http://bottlepy.org/) is the perfect solution for this. With this additional code your python script is able to receive requests and process them: ``` import json from bottle import run, post, request, response @post('/process')...
16,213,235
a methodology question: I have a "main" python script which runs on an infinite loop on my system, and I want to send information to it (a json data string for example) occasionally with some other python scripts that will be started later by myself or another program and will end just after sending the string. I can...
2013/04/25
[ "https://Stackoverflow.com/questions/16213235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112326/" ]
zeromq: <http://www.zeromq.org/> - is best solution for interprocess communications imho and have a excelent binding for python: <http://www.zeromq.org/bindings:python>
In case you are interested in implementing the client script that Mike presented in Python 3.x, you will quickly find that there is no httplib available. Fortunately, the same thing is done with the library http.client. Otherwise it is the same: ``` import http.client c = http.client.HTTPConnection('localhost', 8080)...
34,471,188
Doing python exercises already I've a problem with string: ``` #!/usr/bin/python str = 'mandarino' indice = len(str)-1 #print ("indice is:",indice) while indice > 0: lett = str[indice] print (lett) indice = indice -1 ``` Putting off "-1" the results is: ``` IndexError: string index out of ...
2015/12/26
[ "https://Stackoverflow.com/questions/34471188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4075480/" ]
``` while indice > 0: ``` should be ``` while indice >= 0: ``` to print the first character (index `0`) at last. --- BTW, if you use [`reversed`](https://docs.python.org/3/library/functions.html#reversed), you don't need to calculate index yourself: ``` s = 'mandarino' for ch in reversed(s): print(ch) ``` ...
Though above answers are correct..this is more `pythonic` way... ``` string = 'mandarino' indice = len(string) while indice >= 0: indice -= 1 print (string[indice]), ```
34,471,188
Doing python exercises already I've a problem with string: ``` #!/usr/bin/python str = 'mandarino' indice = len(str)-1 #print ("indice is:",indice) while indice > 0: lett = str[indice] print (lett) indice = indice -1 ``` Putting off "-1" the results is: ``` IndexError: string index out of ...
2015/12/26
[ "https://Stackoverflow.com/questions/34471188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4075480/" ]
``` while indice > 0: ``` should be ``` while indice >= 0: ``` to print the first character (index `0`) at last. --- BTW, if you use [`reversed`](https://docs.python.org/3/library/functions.html#reversed), you don't need to calculate index yourself: ``` s = 'mandarino' for ch in reversed(s): print(ch) ``` ...
You can also treat strings as list of characters and using reverse indexing, this way: ``` >>> str1 = 'mandarino' >>> for ch in str1[::-1]: print ch o n i r a d n a m ```
34,471,188
Doing python exercises already I've a problem with string: ``` #!/usr/bin/python str = 'mandarino' indice = len(str)-1 #print ("indice is:",indice) while indice > 0: lett = str[indice] print (lett) indice = indice -1 ``` Putting off "-1" the results is: ``` IndexError: string index out of ...
2015/12/26
[ "https://Stackoverflow.com/questions/34471188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4075480/" ]
You can add: ``` indice = indice - 1 ``` and change: ``` while indice > 0: ``` to ``` while indice >= 0: ``` so the script will be: ``` #!/usr/bin/python str = 'mandarino' indice = len(str) indice = indice - 1 #print ("indice is:",indice) while indice >= 0: lett = str[indice] print (lett) ...
Though above answers are correct..this is more `pythonic` way... ``` string = 'mandarino' indice = len(string) while indice >= 0: indice -= 1 print (string[indice]), ```
34,471,188
Doing python exercises already I've a problem with string: ``` #!/usr/bin/python str = 'mandarino' indice = len(str)-1 #print ("indice is:",indice) while indice > 0: lett = str[indice] print (lett) indice = indice -1 ``` Putting off "-1" the results is: ``` IndexError: string index out of ...
2015/12/26
[ "https://Stackoverflow.com/questions/34471188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4075480/" ]
You can add: ``` indice = indice - 1 ``` and change: ``` while indice > 0: ``` to ``` while indice >= 0: ``` so the script will be: ``` #!/usr/bin/python str = 'mandarino' indice = len(str) indice = indice - 1 #print ("indice is:",indice) while indice >= 0: lett = str[indice] print (lett) ...
You can also treat strings as list of characters and using reverse indexing, this way: ``` >>> str1 = 'mandarino' >>> for ch in str1[::-1]: print ch o n i r a d n a m ```
43,957,412
Is it possible to extract the text information from a popup page automatically using python? I have google play store app link : <https://play.google.com/store/apps/details?id=com.facebook.katana> If you scroll down to the "ADDITIONAL INFORMATION" section, you will find "Permissions". By clicking 'View details" underne...
2017/05/13
[ "https://Stackoverflow.com/questions/43957412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5090248/" ]
You'll need to do the following: 1) Set up a webdriver to control the website. <https://sites.google.com/a/chromium.org/chromedriver/getting-started> 2) Right click "view details" and select inspect source. This will open the source code of the page. The highlighted portion corresponds to that button. You can right ...
This is going to be rather complicated: you'll have to dig through the HTML to find out what the button does (the link is actually a `button` element). The best would be to use a Google Play Store API, which doesn't exist as of right now. The easiest option would therefore be to go through a third-party API which would...
9,687,922
I recently built an application, for a client, which has several python files. I use ubuntu, and now that I am finished, I would like to give this to the client in a way that would make it easy for her to use in windows. I have looked into py2exe with wine, as well as cx\_freeze and some other stuff, but cannot find a...
2012/03/13
[ "https://Stackoverflow.com/questions/9687922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266969/" ]
[This page](http://bytes.com/topic/python/answers/26340-linux-wine-py2exe) appears to have a solution, as the asker didn't reply: 1. Install WINE. 2. Use WINE to install Python 2.3. 3. Use WINE to install py2exe. 4. Make a setup.py file for py2exe to compile your script: > > > ``` > from distutils.core import setup...
py2exe will not work on linux. Try [pyinstaller](http://www.pyinstaller.org/) it is a pure python implementation that will work on linux, mac and windows.
71,040,315
I have two builds at the same time when doing PR. [![Github Image](https://i.stack.imgur.com/QqREB.png)](https://i.stack.imgur.com/QqREB.png) According to docs, that could be turned off via [web interface](https://docs.travis-ci.com/user/web-ui/#build-pushed-branches) [![web interface](https://i.stack.imgur.com/r9zaa....
2022/02/08
[ "https://Stackoverflow.com/questions/71040315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5712858/" ]
I had to set Gpu Acceleration for the integrated terminal from default `auto` to either `off` or `canvas`. In the settings.json that is achieved with: ```json { "terminal.integrated.gpuAcceleration": "canvas", } ```
Try changing editor font size and window zoom level: ``` { "window.zoomLevel": -1, "editor.fontSize": 14, "terminal.integrated.fontSize": 12, } ```
1,643,643
I want to test againts multiple command line arguments in a loop ``` > python Read_xls_files.py group1 group2 group3 ``` No this code tests only for the first one (group1). ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) ``` How ...
2009/10/29
[ "https://Stackoverflow.com/questions/1643643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198894/" ]
[argparse](http://docs.python.org/dev/library/argparse.html) is another powerful, easy to use module that parses sys.argv for you. Very useful for creating command line scripts.
I believe this would work, and would avoid iterating over sys.argv: ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value in sys.argv[1:]: hlo.append(sh.cell(i, 8).value) ```
1,643,643
I want to test againts multiple command line arguments in a loop ``` > python Read_xls_files.py group1 group2 group3 ``` No this code tests only for the first one (group1). ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) ``` How ...
2009/10/29
[ "https://Stackoverflow.com/questions/1643643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198894/" ]
You can iterate over `sys.argv[1:]`, e.g. via something like: ``` for grp in sys.argv[1:]: for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == grp: hlo.append(sh.cell(i, 8).value) ```
I would recommend taking a look at Python's [optparse](http://docs.python.org/library/optparse.html) module. It's a nice helper to parse `sys.argv`.
1,643,643
I want to test againts multiple command line arguments in a loop ``` > python Read_xls_files.py group1 group2 group3 ``` No this code tests only for the first one (group1). ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) ``` How ...
2009/10/29
[ "https://Stackoverflow.com/questions/1643643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198894/" ]
I would recommend taking a look at Python's [optparse](http://docs.python.org/library/optparse.html) module. It's a nice helper to parse `sys.argv`.
I believe this would work, and would avoid iterating over sys.argv: ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value in sys.argv[1:]: hlo.append(sh.cell(i, 8).value) ```
1,643,643
I want to test againts multiple command line arguments in a loop ``` > python Read_xls_files.py group1 group2 group3 ``` No this code tests only for the first one (group1). ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) ``` How ...
2009/10/29
[ "https://Stackoverflow.com/questions/1643643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198894/" ]
[argparse](http://docs.python.org/dev/library/argparse.html) is another powerful, easy to use module that parses sys.argv for you. Very useful for creating command line scripts.
``` # First thing is to get a set of your query strings. queries = set(argv[1:]) # If using optparse or argparse, queries = set(something_else) hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value in queries: hlo.append(sh.cell(i, 8).value) ``` === end of answer to question === Aside: t...
1,643,643
I want to test againts multiple command line arguments in a loop ``` > python Read_xls_files.py group1 group2 group3 ``` No this code tests only for the first one (group1). ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) ``` How ...
2009/10/29
[ "https://Stackoverflow.com/questions/1643643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198894/" ]
``` outputList = [x for x in values if x in sys.argv[1:]] ``` Substitute the bits that are relevant for your (spreadsheet?) situation. This is a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions). You can also investigate the [optparse](http://docs.python.org/library/optpars...
[argparse](http://docs.python.org/dev/library/argparse.html) is another powerful, easy to use module that parses sys.argv for you. Very useful for creating command line scripts.
1,643,643
I want to test againts multiple command line arguments in a loop ``` > python Read_xls_files.py group1 group2 group3 ``` No this code tests only for the first one (group1). ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) ``` How ...
2009/10/29
[ "https://Stackoverflow.com/questions/1643643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198894/" ]
I would recommend taking a look at Python's [optparse](http://docs.python.org/library/optparse.html) module. It's a nice helper to parse `sys.argv`.
``` # First thing is to get a set of your query strings. queries = set(argv[1:]) # If using optparse or argparse, queries = set(something_else) hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value in queries: hlo.append(sh.cell(i, 8).value) ``` === end of answer to question === Aside: t...
1,643,643
I want to test againts multiple command line arguments in a loop ``` > python Read_xls_files.py group1 group2 group3 ``` No this code tests only for the first one (group1). ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) ``` How ...
2009/10/29
[ "https://Stackoverflow.com/questions/1643643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198894/" ]
You can iterate over `sys.argv[1:]`, e.g. via something like: ``` for grp in sys.argv[1:]: for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == grp: hlo.append(sh.cell(i, 8).value) ```
``` # First thing is to get a set of your query strings. queries = set(argv[1:]) # If using optparse or argparse, queries = set(something_else) hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value in queries: hlo.append(sh.cell(i, 8).value) ``` === end of answer to question === Aside: t...
1,643,643
I want to test againts multiple command line arguments in a loop ``` > python Read_xls_files.py group1 group2 group3 ``` No this code tests only for the first one (group1). ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) ``` How ...
2009/10/29
[ "https://Stackoverflow.com/questions/1643643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198894/" ]
I would recommend taking a look at Python's [optparse](http://docs.python.org/library/optparse.html) module. It's a nice helper to parse `sys.argv`.
[argparse](http://docs.python.org/dev/library/argparse.html) is another powerful, easy to use module that parses sys.argv for you. Very useful for creating command line scripts.
1,643,643
I want to test againts multiple command line arguments in a loop ``` > python Read_xls_files.py group1 group2 group3 ``` No this code tests only for the first one (group1). ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) ``` How ...
2009/10/29
[ "https://Stackoverflow.com/questions/1643643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198894/" ]
``` outputList = [x for x in values if x in sys.argv[1:]] ``` Substitute the bits that are relevant for your (spreadsheet?) situation. This is a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions). You can also investigate the [optparse](http://docs.python.org/library/optpars...
I believe this would work, and would avoid iterating over sys.argv: ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value in sys.argv[1:]: hlo.append(sh.cell(i, 8).value) ```
1,643,643
I want to test againts multiple command line arguments in a loop ``` > python Read_xls_files.py group1 group2 group3 ``` No this code tests only for the first one (group1). ``` hlo = [] for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == sys.argv[1]: hlo.append(sh.cell(i, 8).value) ``` How ...
2009/10/29
[ "https://Stackoverflow.com/questions/1643643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198894/" ]
You can iterate over `sys.argv[1:]`, e.g. via something like: ``` for grp in sys.argv[1:]: for i in range(len(sh.col_values(8))): if sh.cell(i, 1).value == grp: hlo.append(sh.cell(i, 8).value) ```
``` outputList = [x for x in values if x in sys.argv[1:]] ``` Substitute the bits that are relevant for your (spreadsheet?) situation. This is a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions). You can also investigate the [optparse](http://docs.python.org/library/optpars...
2,832,646
my dir location,i am in a.py: ``` my_Project |----blog |-----__init__.py |-----a.py |-----blog.py ``` when i 'from blog import something' in a.py , it show error: ``` from blog import BaseRequestHandler ImportError: cannot import name BaseRequestHandler ``` i think it impo...
2010/05/14
[ "https://Stackoverflow.com/questions/2832646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234322/" ]
When you are in `a.py`, `import blog` should import the local `blog.py` and nothing else. Quoting the [docs](http://docs.python.org/tutorial/modules.html#the-module-search-path): > > modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the i...
what happens when you: ``` import blog ``` Try outputting your sys.path, in order to make sure that you have the right dir to call the module from.
16,168,836
Here's a python-code-snippet: ``` import re VARS='Variables: "OUTPUTFOLDER=installers","SETUP_ORDER=Product 4,Product 4 Library","SUB_CONTENTS=Product 4 Library","SUB_CONTENT_SIZES=9364256","SUB_CONTENT_GROUPS=Product 4 Library","SUB_CONTENT_DESCRIPTIONS=","SUB_CONTENT_GROUP_DESCRIPTIONS=","SUB_DISCS=Product 4,Produ...
2013/04/23
[ "https://Stackoverflow.com/questions/16168836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446835/" ]
``` $(document).ready(function(){ $('#commentform').submit(function(){ var postname = $('h2.post-title').text(); ga('send', 'event', 'Engagement', 'Comment', postname, 5); }); }); ``` First of all. This code assigns the text of a `h2` tag with class `post-title` found in the `document`. A way more reliable way to get...
Hard to tell without looking at an actual page, but likely the browser is redirecting to the form's submission before ga's network call is made. You'd need a way to wait for ga to finish, then finish submitting the form.
71,672,487
Can't import `Quartz` package. I have installed it with this command `pip install pyobjc-framework-Quartz`. Tried reinstalling python, also tried `python -m pip install ...`. With `python2` or `sudo python3`, everything works fine but `python3` is giving me this error message every time I try importing `Quartz` Pytho...
2022/03/30
[ "https://Stackoverflow.com/questions/71672487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16965639/" ]
For investigation purposes, can you try : ``` cd /tmp python3 -m venv venv source venv/bin/activate pip install pyobjc-framework-Quartz python your-script.py ``` Can you try this to see if it works : ``` env -i /Library/Frameworks/Python.framework/Versions/3.10/bin/python3 my_script.py ``` You may have files only...
You might need to try: ```py python3 -m pip install [...] ``` Hope this will hope.
40,909,099
I'm new to image processing and I'm really having a hard time understanding stuff...so the idea is that how do you create a matrix from a binary image in python? ![](https://i.stack.imgur.com/MFBuS.jpg) to something like this: ![](https://i.stack.imgur.com/rTM6Q.jpg) It not the same image though the point is there....
2016/12/01
[ "https://Stackoverflow.com/questions/40909099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6019385/" ]
**Using cv2** -Read more [here](http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_image_display/py_image_display.html) ``` import cv2 img = cv2.imread('path/to/img.jpg') resized = cv2.resize(img, (128, 128), cv2.INTER_LINEAR) print pic ``` **Using skimage** - Read more [here](http://scikit-image.org/docs/de...
example I am currently working with. ==================================== ``` """ A set of utilities that are helpful for working with images. These are utilities needed to actually apply the seam carving algorithm to images """ from PIL import Image class Color: """ A simple class representing an RGB value....
67,740,573
I have a huge file of around 5-10 GBs which has syntax as shown below. "some text" condition1 "some text" condition2 "some text" condition3 "some text" condition1 "some text" condition4 & so on The intent is to write a fast & efficient code to create separate files to store this text info based on conditions. Al...
2021/05/28
[ "https://Stackoverflow.com/questions/67740573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4991138/" ]
The first thing that comes to mind for me would be to use the append feature on Python file handlers. You could do something like this for each line of text: ```py def writecond(text, cond): fname = cond + '.txt' with open(fname, 'a') as file: file.write(text) ``` Another thing you could do is have a...
I figured out one option of handling objects dynamically and keeping track of it. ``` file_handler = {} with open(file) as f: for line in f: if line.split()[1] not in file_handler.keys(): file_handler[line.split()[1]] = open(line.split()[1],"w") file_handler[line.split()[1]].write(...
42,349,982
I am trying to read the JSON file in python and it is successfully however some top values are skipped. I am trying to debug the reason. Here is the the code. ``` data = json.load(open('pre.txt')) for key,val in data['outputs'].items(): print key print data['outputs'][key]['feat_left'] ``` **EDIT** Here is...
2017/02/20
[ "https://Stackoverflow.com/questions/42349982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7396273/" ]
No top values are skipped. There are 45875 items in your data['output'] object. Try the following code: ``` len(data['outputs'].items()) ``` And there are exactly 45875 items in your JSON file. Just note that JSON object is an unordered collection in python, like `dict`.
If you just want to print the content of the file by using a for-loop, you can try like this: ``` data = json.load(open('pre.txt') for key,val in data['outputs'].items(): print key print val[0] #this will print the array and its values below "feat_left", if the json is consistent ``` A more robust soluti...
42,349,982
I am trying to read the JSON file in python and it is successfully however some top values are skipped. I am trying to debug the reason. Here is the the code. ``` data = json.load(open('pre.txt')) for key,val in data['outputs'].items(): print key print data['outputs'][key]['feat_left'] ``` **EDIT** Here is...
2017/02/20
[ "https://Stackoverflow.com/questions/42349982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7396273/" ]
No top values are skipped. There are 45875 items in your data['output'] object. Try the following code: ``` len(data['outputs'].items()) ``` And there are exactly 45875 items in your JSON file. Just note that JSON object is an unordered collection in python, like `dict`.
i think you want: ``` for key, val in data['outputs'].items(): if 'feat_left' in val: print key, data['outputs'][key]['feat_left'] ```
42,349,982
I am trying to read the JSON file in python and it is successfully however some top values are skipped. I am trying to debug the reason. Here is the the code. ``` data = json.load(open('pre.txt')) for key,val in data['outputs'].items(): print key print data['outputs'][key]['feat_left'] ``` **EDIT** Here is...
2017/02/20
[ "https://Stackoverflow.com/questions/42349982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7396273/" ]
No top values are skipped. There are 45875 items in your data['output'] object. Try the following code: ``` len(data['outputs'].items()) ``` And there are exactly 45875 items in your JSON file. Just note that JSON object is an unordered collection in python, like `dict`.
Try this: ``` for key, val in data['outputs'].items(): print key, val['feat_left'] #output /home/119306609.jpg [-0.7765399217605591, -1.690917730331421] ``` This get every key and element within 'feat\_left' Then you can display in the page however you like
42,349,982
I am trying to read the JSON file in python and it is successfully however some top values are skipped. I am trying to debug the reason. Here is the the code. ``` data = json.load(open('pre.txt')) for key,val in data['outputs'].items(): print key print data['outputs'][key]['feat_left'] ``` **EDIT** Here is...
2017/02/20
[ "https://Stackoverflow.com/questions/42349982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7396273/" ]
i think you want: ``` for key, val in data['outputs'].items(): if 'feat_left' in val: print key, data['outputs'][key]['feat_left'] ```
If you just want to print the content of the file by using a for-loop, you can try like this: ``` data = json.load(open('pre.txt') for key,val in data['outputs'].items(): print key print val[0] #this will print the array and its values below "feat_left", if the json is consistent ``` A more robust soluti...
42,349,982
I am trying to read the JSON file in python and it is successfully however some top values are skipped. I am trying to debug the reason. Here is the the code. ``` data = json.load(open('pre.txt')) for key,val in data['outputs'].items(): print key print data['outputs'][key]['feat_left'] ``` **EDIT** Here is...
2017/02/20
[ "https://Stackoverflow.com/questions/42349982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7396273/" ]
i think you want: ``` for key, val in data['outputs'].items(): if 'feat_left' in val: print key, data['outputs'][key]['feat_left'] ```
Try this: ``` for key, val in data['outputs'].items(): print key, val['feat_left'] #output /home/119306609.jpg [-0.7765399217605591, -1.690917730331421] ``` This get every key and element within 'feat\_left' Then you can display in the page however you like
52,318,106
HTML: I have a 'sign-up' form in a modal (index.html) JS: The form data is posted to a python flask function: /signup\_user ``` $(function () { $('#signupButton').click(function () { $.ajax({ url: '/signup_user', method: 'POST', data: $('#signupForm').serialize() }) .done(function (data) { ...
2018/09/13
[ "https://Stackoverflow.com/questions/52318106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5632508/" ]
I would do something like this: ``` student_marks.group_by { |k, v| v }.map { |k, v| [k, v.map(&:first)] }.to_h #=> { 50 => ["Alex", "Matt"], 54 => ["Beth"]} ```
Another way could be ``` student_marks.each.with_object(Hash.new([])){ |(k,v), h| h[v] += [k] } #=> {50=>["Alex", "Matt"], 54=>["Beth"]} ```
52,318,106
HTML: I have a 'sign-up' form in a modal (index.html) JS: The form data is posted to a python flask function: /signup\_user ``` $(function () { $('#signupButton').click(function () { $.ajax({ url: '/signup_user', method: 'POST', data: $('#signupForm').serialize() }) .done(function (data) { ...
2018/09/13
[ "https://Stackoverflow.com/questions/52318106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5632508/" ]
I would do something like this: ``` student_marks.group_by { |k, v| v }.map { |k, v| [k, v.map(&:first)] }.to_h #=> { 50 => ["Alex", "Matt"], 54 => ["Beth"]} ```
``` student_marks.group_by(&:last).transform_values { |v| v.map(&:first) } #=> {50=>["Alex", "Matt"], 54=>["Beth"]} ``` [Hash#transform\_values](https://ruby-doc.org/core-2.4.0/Hash.html) made its debut in Ruby MRI v2.4.0.
52,318,106
HTML: I have a 'sign-up' form in a modal (index.html) JS: The form data is posted to a python flask function: /signup\_user ``` $(function () { $('#signupButton').click(function () { $.ajax({ url: '/signup_user', method: 'POST', data: $('#signupForm').serialize() }) .done(function (data) { ...
2018/09/13
[ "https://Stackoverflow.com/questions/52318106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5632508/" ]
I would do something like this: ``` student_marks.group_by { |k, v| v }.map { |k, v| [k, v.map(&:first)] }.to_h #=> { 50 => ["Alex", "Matt"], 54 => ["Beth"]} ```
Another easy way ``` student_marks.keys.group_by{ |v| student_marks[v] } {50=>["Alex", "Matt"], 54=>["Beth"]} ```
52,318,106
HTML: I have a 'sign-up' form in a modal (index.html) JS: The form data is posted to a python flask function: /signup\_user ``` $(function () { $('#signupButton').click(function () { $.ajax({ url: '/signup_user', method: 'POST', data: $('#signupForm').serialize() }) .done(function (data) { ...
2018/09/13
[ "https://Stackoverflow.com/questions/52318106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5632508/" ]
``` student_marks.group_by(&:last).transform_values { |v| v.map(&:first) } #=> {50=>["Alex", "Matt"], 54=>["Beth"]} ``` [Hash#transform\_values](https://ruby-doc.org/core-2.4.0/Hash.html) made its debut in Ruby MRI v2.4.0.
Another way could be ``` student_marks.each.with_object(Hash.new([])){ |(k,v), h| h[v] += [k] } #=> {50=>["Alex", "Matt"], 54=>["Beth"]} ```