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
309,135
I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit. I need Pros and Cons for Python development between this two editors...
2008/11/21
[ "https://Stackoverflow.com/questions/309135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35425/" ]
A downside I found of Notepad++ for Python is that it tends (for me) to silently mix tabs and spaces. I know this is configurable, but it caught me out, especially when trying to work with other people using different editors / IDE's, so take care.
If I had to choose between Notepad++ and Komodo i would choose PyScripter ;.) Seriously I consider PyScripter as a great alternative...
5,495,143
``` var data; $(document).ready(function(){ var rows = document.getElementById("orderlist_1").rows; var cell = rows[rows.length - 1].cells[3]; data = "id="+cell.innerHTML checkAndNotify(); }) function checkAndNotify() { alert("oo"); $("#shownoti").load("/mostrecenttransaction","id=2008010661301520679"); ...
2011/03/31
[ "https://Stackoverflow.com/questions/5495143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/167814/" ]
``` jQuery.ajax({ url: "mostRecentTransaction", type: "GET", data: { id : 2008010661301520679 }, success: function(data) { alert(data); jQuery('#shownoti').html(data).hide().fadeIn(1500); } }); ```
Try using setInterval instead of setTimeout
48,819,547
I want take logarithm multiple times. We know this ``` import numpy as np np.log(x) ``` now the second logarithm would be ``` np.log(np.log(x)) ``` what if one wants to take n number of logs? surely it would not be pythonic to repeat n times as above.
2018/02/16
[ "https://Stackoverflow.com/questions/48819547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As per @eugenhu's suggestion, one way is to use a generic function which loops iteratively: ``` import numpy as np def repeater(f, n): def fn(i): result = i for _ in range(n): result = f(result) return result return fn repeater(np.log, 5)(x) ```
You could use the following little trick: ``` >>> from functools import reduce >>> >>> k = 4 >>> x = 1e12 >>> >>> y = np.array(x) >>> reduce(np.log, (k+1) * (y,))[()] 0.1820258315495139 ``` and back: ``` >>> reduce(np.exp, (k+1) * (y,))[()] 999999999999.9813 ``` On my machine this is slightly faster than @jp\_d...
48,819,547
I want take logarithm multiple times. We know this ``` import numpy as np np.log(x) ``` now the second logarithm would be ``` np.log(np.log(x)) ``` what if one wants to take n number of logs? surely it would not be pythonic to repeat n times as above.
2018/02/16
[ "https://Stackoverflow.com/questions/48819547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As per @eugenhu's suggestion, one way is to use a generic function which loops iteratively: ``` import numpy as np def repeater(f, n): def fn(i): result = i for _ in range(n): result = f(result) return result return fn repeater(np.log, 5)(x) ```
From this [post](https://stackoverflow.com/questions/35398472/sequential-function-mapping-in-python), you can compose functions: **Code** ``` import itertools as it import functools as ft import numpy as np def compose(f, g): return lambda x: f(g(x)) identity = lambda x: x ``` **Demo** ``` ft.reduce(compos...
48,819,547
I want take logarithm multiple times. We know this ``` import numpy as np np.log(x) ``` now the second logarithm would be ``` np.log(np.log(x)) ``` what if one wants to take n number of logs? surely it would not be pythonic to repeat n times as above.
2018/02/16
[ "https://Stackoverflow.com/questions/48819547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could use the following little trick: ``` >>> from functools import reduce >>> >>> k = 4 >>> x = 1e12 >>> >>> y = np.array(x) >>> reduce(np.log, (k+1) * (y,))[()] 0.1820258315495139 ``` and back: ``` >>> reduce(np.exp, (k+1) * (y,))[()] 999999999999.9813 ``` On my machine this is slightly faster than @jp\_d...
From this [post](https://stackoverflow.com/questions/35398472/sequential-function-mapping-in-python), you can compose functions: **Code** ``` import itertools as it import functools as ft import numpy as np def compose(f, g): return lambda x: f(g(x)) identity = lambda x: x ``` **Demo** ``` ft.reduce(compos...
994,460
I have a Pylons app and am using FormEncode and HtmlFill to handle my forms. I have an array of text fields in my template (Mako) ``` <tr> <td>Yardage</td> <td>${h.text('yardage[]', maxlength=3, size=3)}</td> <td>${h.text('yardage[]', maxlength=3, size=3)}</td> <td>${h.text('yardage[]', maxlength=3,...
2009/06/15
[ "https://Stackoverflow.com/questions/994460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10738/" ]
Turns out what I wanted to do wasn't quite right. **Template**: ``` <tr> <td>Yardage</td> % for hole in range(9): <td>${h.text('hole-%s.yardage'%(hole), maxlength=3, size=3)}</td> % endfor </tr> ``` (Should have made it in a loop to begin with.) You'll notice that the name of the first element will become ...
``` c.form_result = schema.to_python(request.params) - (without dict) ``` It seems to works fine.
38,608,781
Python has filter method which filters the desired output on some criteria as like in the following example. ``` >>> s = "some\x00string. with\x15 funny characters" >>> import string >>> printable = set(string.printable) >>> filter(lambda x: x in printable, s) 'somestring. with funny characters' ``` The example is ...
2016/07/27
[ "https://Stackoverflow.com/questions/38608781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5453723/" ]
As others said it is undefined behaviour. Why it is working though? It is probably because the function call is linked statically, during compile-time (it's not virtual function). The function `B::hi()` exists so it is called. Try to add variable to `class B` and use it in function `hi()`. Then you will see problem (t...
> > Now, why is this happening ? > > > Because it can happen. Anything can happen. The behaviour is *undefined*. The fact that something unexpected happened demonstrates well why UB is so dangerous. If it always caused a crash, then it would be far easier to deal with. > > What object was used to call such a me...
38,608,781
Python has filter method which filters the desired output on some criteria as like in the following example. ``` >>> s = "some\x00string. with\x15 funny characters" >>> import string >>> printable = set(string.printable) >>> filter(lambda x: x in printable, s) 'somestring. with funny characters' ``` The example is ...
2016/07/27
[ "https://Stackoverflow.com/questions/38608781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5453723/" ]
As others said it is undefined behaviour. Why it is working though? It is probably because the function call is linked statically, during compile-time (it's not virtual function). The function `B::hi()` exists so it is called. Try to add variable to `class B` and use it in function `hi()`. Then you will see problem (t...
This only works because of the implementation of the `hi()` method itself, and the peculiar part of the C++ spec called *undefined behaviour*. Casting using a C-style cast to an incompatible pointer type is undefined behaviour - literally anything at all could happen. In this case, the compiler has obviously decided ...
42,875,890
I do install odoo version 8 in ubuntu version 16 , then I doing like this link <https://www.getopenerp.com/easy-odoo8-installation/> . In step 3 , it is wrong it say "E:Package 'python-pybabel' has no installation candidate". what happens?
2017/03/18
[ "https://Stackoverflow.com/questions/42875890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7626653/" ]
python-pybabel was replace by python-babel package from what I see on the web search. After I face also this problem I use python-babel and all work correctly. best regards, CiprianR
Hello this is a command for dependencies, you need to run it : ``` sudo apt-get install python-psutil python-pybabel ```
42,875,890
I do install odoo version 8 in ubuntu version 16 , then I doing like this link <https://www.getopenerp.com/easy-odoo8-installation/> . In step 3 , it is wrong it say "E:Package 'python-pybabel' has no installation candidate". what happens?
2017/03/18
[ "https://Stackoverflow.com/questions/42875890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7626653/" ]
This python-pybabel has been replaced by another package called python-babel. So try: ``` $ sudo apt-get install python-babel ``` This should work
Hello this is a command for dependencies, you need to run it : ``` sudo apt-get install python-psutil python-pybabel ```
42,875,890
I do install odoo version 8 in ubuntu version 16 , then I doing like this link <https://www.getopenerp.com/easy-odoo8-installation/> . In step 3 , it is wrong it say "E:Package 'python-pybabel' has no installation candidate". what happens?
2017/03/18
[ "https://Stackoverflow.com/questions/42875890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7626653/" ]
python-pybabel was replace by python-babel package from what I see on the web search. After I face also this problem I use python-babel and all work correctly. best regards, CiprianR
This python-pybabel has been replaced by another package called python-babel. So try: ``` $ sudo apt-get install python-babel ``` This should work
62,045,094
I'm trying to create an s3 bucket in every region in AWS with boto3 in python but I'm failing to create a bucket in 4 regions (af-south-1, eu-south-1, ap-east-1 & me-south-1) My python code: ``` def create_bucket(name, region): s3 = boto3.client('s3') s3.create_bucket(Bucket=name, CreateBucketConfiguration={'...
2020/05/27
[ "https://Stackoverflow.com/questions/62045094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4213730/" ]
The regions your code fails in are relativly new regions, where you need to opt-in first to use them, see here [Managing AWS Regions](https://docs.aws.amazon.com/general/latest/gr/rande-manage.html)
Newer AWS regions only support regional endpoints. Thus, if creating buckets in one of those regions, a regional endpoint needs to be created. Since I was creating buckets in multiple regions, I set the endpoint by creating a new instance of the client for each region. (This was in Node.js, but should still work with ...
30,518,714
After running a python program, I obtain a list of numeric data. How can I format the data in CSV? Goal: I hope to format it so that I can reuse the CSV-formatted data in Mathematica.
2015/05/28
[ "https://Stackoverflow.com/questions/30518714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4143312/" ]
Let's assume your list of numeric data is stored in a variable - `numericList` ``` import csv myFile = open(csvFile, 'wb') writer = csv.writer(myFile, quoting = csv.QUOTE_ALL) writer.writerow(numericList) ``` *wb* indicates that the file is opened for **w**riting in **b**inary mode. The `csvFile` should contain you...
for a simple case you can just as easily write it directly.. ``` f=open('test.csv','w') for p in data : f.write('%g,%g\n'%tuple(p)) f.close() ``` where data here is an `nx2` array.
52,161,349
I have successfully install pattern3 for python 3.6 in my Linux system. But after writing this code I got an error. ``` from pattern3.en import referenced print(referenced('university')) print(referenced('hour')) ``` > > IndentationError::expected an indented block > > >
2018/09/04
[ "https://Stackoverflow.com/questions/52161349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6051513/" ]
I solved this by entering to the problematic file, which should be `(C:\Python27\Lib\site-packages\pattern3\text\tree.py)` and fixing the problem myself: ```py from itertools import chain # 34 try: # 35 None # ===> THIS IS THE LINE I ADDED! <=== except: ...
Python will give you an error `expected an indented block` if you skip the indentation: Example of this: ``` if 5 > 2: print("Five is greater than two!") ``` run it,and it will give an error ``` if 5 > 2: print("Five is greater than two!") ``` run it,it will not give any error.
25,538,584
I have 2 date columns (begin and end) in a data frame where the dates are in the following string format '%Y-%m-%d %H:%M:%S.%f'. How can I change these into date format in python? I also want to create a new column that shows the difference in days between the end and begin dates. Thanks in advance!
2014/08/27
[ "https://Stackoverflow.com/questions/25538584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313307/" ]
If you're using a recent version of pandas you can pass a format argument to `to_datetime`: ``` In [11]: dates = ["2014-08-27 19:53:06.000", "2014-08-27 19:53:15.002"] In [12]: pd.to_datetime(dates, format='%Y-%m-%d %H:%M:%S.%f') Out[12]: <class 'pandas.tseries.index.DatetimeIndex'> [2014-08-27 19:53:06, 2014-08-27 1...
The `datetime` module has everything you need to play around with dates. Note that in the format you describe `%Y-%m-%d %H:%M:%S.%f` the `%f` does not appear in the [known directives](https://docs.python.org/3/library/time.html#time.strftime) and is not included in my answer ``` from datetime import datetime dates = [...
19,845,259
I am getting below errors while configuring Grinder on JIRA instances, followed all instruction as per <https://confluence.atlassian.com/display/ATLAS/JIRA+Performance+Testing+with+Grinder#JIRAPerformanceTestingwithGrinder-Prerequisites> Errors : $ cat project\_manager\_8/error\_xxxx004.fm.XXXXX.com-0.log ``` 11/7/1...
2013/11/07
[ "https://Stackoverflow.com/questions/19845259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2608551/" ]
It's taken me 2 weeks to find out how to REALLY fix this issue. I had put a new class file under the **App\_Code** folder (I haven't used that folder for ages). For some reason I had set the "Build Action" to "*Compile*". Well, I guess anything under the **App\_Code** folder is already compiled by default, so when the ...
It appears that something was wrong with either one of the web.config's. Simply took the web.config's from a blank MVC4 project and replaced. Incidentally, having the namespace in both the config and layout does not throw an error.
48,189,688
Im trying to find if a .xlsx file contains a @. I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns? the code: ``` df = pandas.read_excel(open(path,'rb'), sheetname=0) out = 'False' for col in df.co...
2018/01/10
[ "https://Stackoverflow.com/questions/48189688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1495850/" ]
Take a look at the [json module](https://docs.python.org/3/library/json.html). More specifically the 'Decoding JSON:' section. ``` import json import requests response = requests.get() # api call users = json.loads(response.text) for user in users: print(user['id']) ```
It seems what you are looking for is the [json](https://docs.python.org/2/library/json.html) module. with it you can use this to parse a string into json format: ``` import json output=json.loads(myJsonString) ```
48,189,688
Im trying to find if a .xlsx file contains a @. I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns? the code: ``` df = pandas.read_excel(open(path,'rb'), sheetname=0) out = 'False' for col in df.co...
2018/01/10
[ "https://Stackoverflow.com/questions/48189688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1495850/" ]
Take a look at the [json module](https://docs.python.org/3/library/json.html). More specifically the 'Decoding JSON:' section. ``` import json import requests response = requests.get() # api call users = json.loads(response.text) for user in users: print(user['id']) ```
use python 3 and import urlib ``` import urllib.request import json url = link of the server #Taking response and request from url r = urllib.request.urlopen(url) #reading and decoding the data data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8')) for json_inner_array in data: for j...
48,189,688
Im trying to find if a .xlsx file contains a @. I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns? the code: ``` df = pandas.read_excel(open(path,'rb'), sheetname=0) out = 'False' for col in df.co...
2018/01/10
[ "https://Stackoverflow.com/questions/48189688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1495850/" ]
Take a look at the [json module](https://docs.python.org/3/library/json.html). More specifically the 'Decoding JSON:' section. ``` import json import requests response = requests.get() # api call users = json.loads(response.text) for user in users: print(user['id']) ```
You can try like below to get the values from json response: ``` import json content=[{ "username": "admin", "first_name": "", "last_name": "", "roles": "system_admin system_user", "locale": "en", "delete_at": 0, "update_at": 1511335509393, "create_at": 1511335500662, "auth_service...
48,189,688
Im trying to find if a .xlsx file contains a @. I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns? the code: ``` df = pandas.read_excel(open(path,'rb'), sheetname=0) out = 'False' for col in df.co...
2018/01/10
[ "https://Stackoverflow.com/questions/48189688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1495850/" ]
You can try like below to get the values from json response: ``` import json content=[{ "username": "admin", "first_name": "", "last_name": "", "roles": "system_admin system_user", "locale": "en", "delete_at": 0, "update_at": 1511335509393, "create_at": 1511335500662, "auth_service...
It seems what you are looking for is the [json](https://docs.python.org/2/library/json.html) module. with it you can use this to parse a string into json format: ``` import json output=json.loads(myJsonString) ```
48,189,688
Im trying to find if a .xlsx file contains a @. I have used pandas, which work great, unless if the excel sheet have the first column empty, then it fails.. any ideas how to rewrite the code to handle/skip empty columns? the code: ``` df = pandas.read_excel(open(path,'rb'), sheetname=0) out = 'False' for col in df.co...
2018/01/10
[ "https://Stackoverflow.com/questions/48189688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1495850/" ]
You can try like below to get the values from json response: ``` import json content=[{ "username": "admin", "first_name": "", "last_name": "", "roles": "system_admin system_user", "locale": "en", "delete_at": 0, "update_at": 1511335509393, "create_at": 1511335500662, "auth_service...
use python 3 and import urlib ``` import urllib.request import json url = link of the server #Taking response and request from url r = urllib.request.urlopen(url) #reading and decoding the data data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8')) for json_inner_array in data: for j...
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
You can use `collections.dequeue`, which has a `rotate` method. However, if you want to make it on your own you can do it like this: ``` >>> a = ['a','b','c','d'] >>> counter = 0 >>> start_index=2 >>> while counter < len(a): ... print(a[start_index]) ... start_index+=1 ... counter += 1 ... if start_ind...
Use the following function: ``` def cycle_list(l, i): for element in l[i:]: yield element for element in l[:i]: yield element ```
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
You could pop the start item off and add it to the end. ``` days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for _ in range(7): print("----") print("\n".join(days)) days.append(days.pop(0)) ```
Use the following function: ``` def cycle_list(l, i): for element in l[i:]: yield element for element in l[:i]: yield element ```
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
You can use `collections.dequeue`, which has a `rotate` method. However, if you want to make it on your own you can do it like this: ``` >>> a = ['a','b','c','d'] >>> counter = 0 >>> start_index=2 >>> while counter < len(a): ... print(a[start_index]) ... start_index+=1 ... counter += 1 ... if start_ind...
If you don't want to import any libraries. ``` DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for i in range(7): print("----") for j in range(len(DAYS)): print(DAYS[(j+i) % len(DAYS)]) ```
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
One approach would be using [`collections.deque`](https://docs.python.org/2/library/collections.html#collections.deque): ``` from collections import deque from itertools import repeat d = deque(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']) n = 7 for i in repeat(d, n): print(*i, ...
If you don't want to import any libraries. ``` DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for i in range(7): print("----") for j in range(len(DAYS)): print(DAYS[(j+i) % len(DAYS)]) ```
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
You could pop the start item off and add it to the end. ``` days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for _ in range(7): print("----") print("\n".join(days)) days.append(days.pop(0)) ```
If you don't want to import any libraries. ``` DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for i in range(7): print("----") for j in range(len(DAYS)): print(DAYS[(j+i) % len(DAYS)]) ```
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
You could pop the start item off and add it to the end. ``` days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for _ in range(7): print("----") print("\n".join(days)) days.append(days.pop(0)) ```
It can be done by: ```py a[i:]+a[:i] ```
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
One approach would be using [`collections.deque`](https://docs.python.org/2/library/collections.html#collections.deque): ``` from collections import deque from itertools import repeat d = deque(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']) n = 7 for i in repeat(d, n): print(*i, ...
You can use `collections.dequeue`, which has a `rotate` method. However, if you want to make it on your own you can do it like this: ``` >>> a = ['a','b','c','d'] >>> counter = 0 >>> start_index=2 >>> while counter < len(a): ... print(a[start_index]) ... start_index+=1 ... counter += 1 ... if start_ind...
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
You can use `collections.dequeue`, which has a `rotate` method. However, if you want to make it on your own you can do it like this: ``` >>> a = ['a','b','c','d'] >>> counter = 0 >>> start_index=2 >>> while counter < len(a): ... print(a[start_index]) ... start_index+=1 ... counter += 1 ... if start_ind...
It can be done by: ```py a[i:]+a[:i] ```
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
You can use `collections.dequeue`, which has a `rotate` method. However, if you want to make it on your own you can do it like this: ``` >>> a = ['a','b','c','d'] >>> counter = 0 >>> start_index=2 >>> while counter < len(a): ... print(a[start_index]) ... start_index+=1 ... counter += 1 ... if start_ind...
you can [chain](https://docs.python.org/3.7/library/itertools.html#itertools.chain) the elements starting from your current index (in your case the current index is `i`) with the elements before current index using generators, in this way you will not create new lists, will be memory-efficient: ``` a = ['Sunday', 'Mon...
57,919,803
Similar question asked here ([Start index for iterating Python list](https://stackoverflow.com/questions/6148619/start-index-for-iterating-python-list)), but I need one more thing. Assume I have a list [Sunday, Monday, ...Saturday], and I want to iterate the list starting from different position, wrap around and compl...
2019/09/13
[ "https://Stackoverflow.com/questions/57919803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12062120/" ]
One approach would be using [`collections.deque`](https://docs.python.org/2/library/collections.html#collections.deque): ``` from collections import deque from itertools import repeat d = deque(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']) n = 7 for i in repeat(d, n): print(*i, ...
you can [chain](https://docs.python.org/3.7/library/itertools.html#itertools.chain) the elements starting from your current index (in your case the current index is `i`) with the elements before current index using generators, in this way you will not create new lists, will be memory-efficient: ``` a = ['Sunday', 'Mon...
13,610,654
I understand [from this question](https://stackoverflow.com/questions/2227169/are-python-built-in-containers-thread-safe) that if I want to have a `set` which is thread-safe I have to implement the thread-safety part on my own. Therefore I could come up with: ``` from threading import Lock class LockedSet(set): ...
2012/11/28
[ "https://Stackoverflow.com/questions/13610654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15931/" ]
[Indeed, see the comments, it is not true] If you are running CPython you can see from the set source code that it doesn't release the GIL (http://hg.python.org/cpython/file/db20367b20de/Objects/setobject.c) so all its operations should be atomic. If it is all what you need and you are sure to run your code on CPytho...
You can implement your own context manager: ``` class LockableSet: def __enter__(self): self.lock() return self def __exit__(self, exc_type, exc_value, traceback): #Do what you want with the error self.unlock() with LockableSet() as s: s.whatever() raise Exception() `...
13,610,654
I understand [from this question](https://stackoverflow.com/questions/2227169/are-python-built-in-containers-thread-safe) that if I want to have a `set` which is thread-safe I have to implement the thread-safety part on my own. Therefore I could come up with: ``` from threading import Lock class LockedSet(set): ...
2012/11/28
[ "https://Stackoverflow.com/questions/13610654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15931/" ]
This is my first attempt to play with decorators (although my code doesn't actually use the @decorate syntax), and I don't have much experience with multi-threading/multiprocessing. With that disclaimer, though, here's an attempt I made: ``` from multiprocessing import Lock def decorate_all(obj): lock = Lock() ...
You can implement your own context manager: ``` class LockableSet: def __enter__(self): self.lock() return self def __exit__(self, exc_type, exc_value, traceback): #Do what you want with the error self.unlock() with LockableSet() as s: s.whatever() raise Exception() `...
13,610,654
I understand [from this question](https://stackoverflow.com/questions/2227169/are-python-built-in-containers-thread-safe) that if I want to have a `set` which is thread-safe I have to implement the thread-safety part on my own. Therefore I could come up with: ``` from threading import Lock class LockedSet(set): ...
2012/11/28
[ "https://Stackoverflow.com/questions/13610654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15931/" ]
You can use Python's metaprogramming facilities to accomplish this. (Note: written quickly and not thoroughly tested.) I prefer to use a class decorator. I also think you *may* need to lock more than `add` and `remove` to make a set thread-safe, but I'm not sure. I'll ignore that problem and just concentrate on your q...
You can implement your own context manager: ``` class LockableSet: def __enter__(self): self.lock() return self def __exit__(self, exc_type, exc_value, traceback): #Do what you want with the error self.unlock() with LockableSet() as s: s.whatever() raise Exception() `...
13,610,654
I understand [from this question](https://stackoverflow.com/questions/2227169/are-python-built-in-containers-thread-safe) that if I want to have a `set` which is thread-safe I have to implement the thread-safety part on my own. Therefore I could come up with: ``` from threading import Lock class LockedSet(set): ...
2012/11/28
[ "https://Stackoverflow.com/questions/13610654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15931/" ]
You can use Python's metaprogramming facilities to accomplish this. (Note: written quickly and not thoroughly tested.) I prefer to use a class decorator. I also think you *may* need to lock more than `add` and `remove` to make a set thread-safe, but I'm not sure. I'll ignore that problem and just concentrate on your q...
[Indeed, see the comments, it is not true] If you are running CPython you can see from the set source code that it doesn't release the GIL (http://hg.python.org/cpython/file/db20367b20de/Objects/setobject.c) so all its operations should be atomic. If it is all what you need and you are sure to run your code on CPytho...
13,610,654
I understand [from this question](https://stackoverflow.com/questions/2227169/are-python-built-in-containers-thread-safe) that if I want to have a `set` which is thread-safe I have to implement the thread-safety part on my own. Therefore I could come up with: ``` from threading import Lock class LockedSet(set): ...
2012/11/28
[ "https://Stackoverflow.com/questions/13610654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15931/" ]
You can use Python's metaprogramming facilities to accomplish this. (Note: written quickly and not thoroughly tested.) I prefer to use a class decorator. I also think you *may* need to lock more than `add` and `remove` to make a set thread-safe, but I'm not sure. I'll ignore that problem and just concentrate on your q...
This is my first attempt to play with decorators (although my code doesn't actually use the @decorate syntax), and I don't have much experience with multi-threading/multiprocessing. With that disclaimer, though, here's an attempt I made: ``` from multiprocessing import Lock def decorate_all(obj): lock = Lock() ...
11,965,655
I have created a utility software for operating file copy process in python.Every thing is working nice but when i start copying any files larger than 2 Gb the the whole system hangs. It seems to me that it might be a memory leak issue. I have tried: * Copying it using Shutil Module * Using Lazy operation by copying ...
2012/08/15
[ "https://Stackoverflow.com/questions/11965655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599825/" ]
Since you only have 2 GB of memory when you copy a file that's larger than your memory, it causes issues. Don't load the entire file into memory. Instead, I would do something like: ``` with open(myLargeFile) as f: with open(myOtherLargeFile, "w") as fo: for line in f: fo.write(line) ``` Sinc...
The good approach for this problem is: * use multiprocessing or multithreading * split file into chunks * use python dbm for storing which chunk belongs to which filename, filepath and chunk offset( for file.seek function) * create queue for read and write chunks
48,441,737
I have a raspberry pi and I have installed dockers in it. I have made a python script to read gpio status in it. So when I run the below command ``` sudo docker run -it --device /dev/gpiomem app-image ``` It runs perfectly and shows the gpio status. Now I have created a `docker-compose.yml` file as I want to deploy ...
2018/01/25
[ "https://Stackoverflow.com/questions/48441737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9267000/" ]
Adding devices, capabilities, and using privileged mode are not supported in swarm mode. Those options in the yml file exist for using `docker-compose` instead of `docker stack deploy`. You can track the progress on getting these features added to swarm mode in [github issue #24862](https://github.com/moby/moby/issues/...
As stated in [docker-compose devices](https://docs.docker.com/compose/compose-file/#devices) > > Note: This option is ignored when deploying a stack in swarm mode with > a (version 3) Compose file. > > > The devices option is ignored in swarm. You can use `privileged: true` which will give access to all devices.
19,331,093
I am trying to create a legend for a plot with variable sets of data. There are at least 2, and at most 5. The first two will always be there, but the other three are optional, so how can I create a legend for only the existing number of data sets? I've tried if-statements to tell python what to do if that variable do...
2013/10/12
[ "https://Stackoverflow.com/questions/19331093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873277/" ]
Because selectedFiles is a tuple, and the logic of processing each item inside it is same. you can iterate it with a for loop. ``` lines = [os.path.basename(str(os.path.splitext(filename)[0])) for filename in selectedFiles] #extend lines' length to 5 and fill the space with None lines = lines + [None] * (5-len(lines)...
I have no idea what your data structures look like, but it looks like you just want ``` lines = (os.path.basename(str(os.path.splitext(x)[0])) for x in selectedFiles) legend(lines, loc='upper left') ```
19,331,093
I am trying to create a legend for a plot with variable sets of data. There are at least 2, and at most 5. The first two will always be there, but the other three are optional, so how can I create a legend for only the existing number of data sets? I've tried if-statements to tell python what to do if that variable do...
2013/10/12
[ "https://Stackoverflow.com/questions/19331093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873277/" ]
I have no idea what your data structures look like, but it looks like you just want ``` lines = (os.path.basename(str(os.path.splitext(x)[0])) for x in selectedFiles) legend(lines, loc='upper left') ```
I would prefer this way. ``` line = [] for i in range(5): if i < len(selectedFiles): line.append(os.path.basename(str(os.path.splitext(selectedFiles[i])[0]))) else: line.append(None) legend(tuple(line), loc='upper left') ``` or you can always use `except IndexError:`.
19,331,093
I am trying to create a legend for a plot with variable sets of data. There are at least 2, and at most 5. The first two will always be there, but the other three are optional, so how can I create a legend for only the existing number of data sets? I've tried if-statements to tell python what to do if that variable do...
2013/10/12
[ "https://Stackoverflow.com/questions/19331093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873277/" ]
Because selectedFiles is a tuple, and the logic of processing each item inside it is same. you can iterate it with a for loop. ``` lines = [os.path.basename(str(os.path.splitext(filename)[0])) for filename in selectedFiles] #extend lines' length to 5 and fill the space with None lines = lines + [None] * (5-len(lines)...
I would prefer this way. ``` line = [] for i in range(5): if i < len(selectedFiles): line.append(os.path.basename(str(os.path.splitext(selectedFiles[i])[0]))) else: line.append(None) legend(tuple(line), loc='upper left') ``` or you can always use `except IndexError:`.
56,106,783
I am building a dockerfile with the `docker build .` command. While building, I am experiencing the following error: ``` Downloading/unpacking requests Cannot fetch index base URL http://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement requests No distributions at all found fo...
2019/05/13
[ "https://Stackoverflow.com/questions/56106783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11439964/" ]
You have a pip problem, not a docker problem, you need to add `pip install --index-url https://pypi.python.org/simple/ --upgrade pip` to your docker file: ``` FROM jonasbonno/rpi-grovepi RUN pip install --index-url https://pypi.python.org/simple/ --upgrade pip RUN hash -r RUN pip install requests RUN git clone https:/...
#### Legacy problem In Python 2.7, a pip installer of *Pylons* threw the same error. I then read somewhere that upgrading *pip* could help, and doing so in the bash of the container, you get the same error again, now for *pip* itself: ```bash Cannot fetch index base URL https://pypi.python.org/simple/ Could not find ...
19,312,270
Is there any way to break string based on punctuation-word ``` #!/usr/bin/python #Asking user to Enter a line in specified format myString=raw_input('Enter your String:\nFor Example:I am doctor break I stays in CA break you can contact me on +000000\n') # 'break' is punctuation word <my code which breaks the user ...
2013/10/11
[ "https://Stackoverflow.com/questions/19312270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1699472/" ]
If you have written you `java-script` code then make sure that you `return false` from the js code if it is not valid and in aspx file you need to use return as follows ``` <asp:Button runat="server" id="btnLogin" Text="Login" OnClientClick="return Validate()"/> ``` Edit -1 ------- There is a chance that your...
You need add a add an attribute to button(btnLogin) `OnClientClick="Validate()"`. Like: ``` <asp:Button runat="server" id="btnLogin" Text="Login" OnClientClick="Validate()"/> ``` Define javascript function `Validate()` and return false if your form value is not valid.
19,312,270
Is there any way to break string based on punctuation-word ``` #!/usr/bin/python #Asking user to Enter a line in specified format myString=raw_input('Enter your String:\nFor Example:I am doctor break I stays in CA break you can contact me on +000000\n') # 'break' is punctuation word <my code which breaks the user ...
2013/10/11
[ "https://Stackoverflow.com/questions/19312270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1699472/" ]
you want to validate the value of textbox when user clicks enter and focus is in textbox then use the below code: ``` <table> <tr> <td> Username:> </td> <td> <asp:TextBox CssClass="save" runat="server" ID="txtUsername" /> </td> ...
You need add a add an attribute to button(btnLogin) `OnClientClick="Validate()"`. Like: ``` <asp:Button runat="server" id="btnLogin" Text="Login" OnClientClick="Validate()"/> ``` Define javascript function `Validate()` and return false if your form value is not valid.
19,312,270
Is there any way to break string based on punctuation-word ``` #!/usr/bin/python #Asking user to Enter a line in specified format myString=raw_input('Enter your String:\nFor Example:I am doctor break I stays in CA break you can contact me on +000000\n') # 'break' is punctuation word <my code which breaks the user ...
2013/10/11
[ "https://Stackoverflow.com/questions/19312270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1699472/" ]
If you have written you `java-script` code then make sure that you `return false` from the js code if it is not valid and in aspx file you need to use return as follows ``` <asp:Button runat="server" id="btnLogin" Text="Login" OnClientClick="return Validate()"/> ``` Edit -1 ------- There is a chance that your...
I would do that in Jquery. ``` //set this so that Jquery selector can get your button <asp:Button runat="server" id="btnLogin" Text="Login" ClientIDMode="Static" /> ``` jquery ``` $(function) () { $('#btnLogin').click(e) { Your javascript code here //put those if you don't want your page reloading e.preventD...
19,312,270
Is there any way to break string based on punctuation-word ``` #!/usr/bin/python #Asking user to Enter a line in specified format myString=raw_input('Enter your String:\nFor Example:I am doctor break I stays in CA break you can contact me on +000000\n') # 'break' is punctuation word <my code which breaks the user ...
2013/10/11
[ "https://Stackoverflow.com/questions/19312270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1699472/" ]
you want to validate the value of textbox when user clicks enter and focus is in textbox then use the below code: ``` <table> <tr> <td> Username:> </td> <td> <asp:TextBox CssClass="save" runat="server" ID="txtUsername" /> </td> ...
I would do that in Jquery. ``` //set this so that Jquery selector can get your button <asp:Button runat="server" id="btnLogin" Text="Login" ClientIDMode="Static" /> ``` jquery ``` $(function) () { $('#btnLogin').click(e) { Your javascript code here //put those if you don't want your page reloading e.preventD...
52,175,927
I am coming from a C# background and Python's Asyncio library is confusing me. I have read the following [1](https://stackoverflow.com/questions/37278647/fire-and-forget-python-async-await/37345564#37345564) [2](https://stackoverflow.com/questions/33357233/when-to-use-and-when-not-to-use-python-3-5-await/33399896#3339...
2018/09/05
[ "https://Stackoverflow.com/questions/52175927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8714371/" ]
As the **requests** library is not asynchronous, you can use [run\_in\_executor](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor) method, so it won't block the running thread. As the result, you can define `requestPage` as a regular function and call it in the `main` function like ...
Ok, I think I found a basic solution. ``` async def requestPage(url): request = requests.get(url, headers=headers) soup = BeautifulSoup(request.content, 'html.parser') return soup async def getValueAsync(func, param): # Create new task task = asyncio.ensure_future(func(param)) # Execute task. ...
57,417,108
I have to parse the following file in python: ``` 20100322;232400;1.355800;1.355900;1.355800;1.355900;0 20100322;232500;1.355800;1.355900;1.355800;1.355900;0 20100322;232600;1.355800;1.355800;1.355800;1.355800;0 ``` I need to end upwith the following variables (first line is parsed as example): ``` year = 2010 mont...
2019/08/08
[ "https://Stackoverflow.com/questions/57417108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5328289/" ]
``` from decimal import Decimal from datetime import datetime line = "20100322;232400;1.355800;1.355900;1.355800;1.355900;0" tokens = line.split(";") dt = datetime.strptime(tokens[0] + tokens[1], "%Y%m%d%H%M%S") decimals = [Decimal(string) for string in tokens[2:6]] # datetime objects also have some useful attribut...
You could use regex: ``` import re to_parse = """ 20100322;232400;1.355800;1.355900;1.355800;1.355900;0 20100322;232500;1.355800;1.355900;1.355800;1.355900;0 20100322;232600;1.355800;1.355800;1.355800;1.355800;0 """ stx = re.compile( r'(?P<date>(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2}));' r'(?P<time>(?P<...
10,904,629
noob programmer here, I'm trying to get the SQLite3 on my Python installation up-to-date (I currently have version 3.6.11, whereas I need at least version 3.6.19, as that is the first version that supports foreign keys). Here's my problem, though: I have no idea how to do this. I know next to nothing about the command ...
2012/06/05
[ "https://Stackoverflow.com/questions/10904629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430987/" ]
I suggest using the 'pip' command on the command line. ``` pip search sqlite pip install pysqlite ```
<https://pip.pypa.io/en/latest/installing.html> python get-pip.py python [complete path] python c:\folder\get-pip.py
10,904,629
noob programmer here, I'm trying to get the SQLite3 on my Python installation up-to-date (I currently have version 3.6.11, whereas I need at least version 3.6.19, as that is the first version that supports foreign keys). Here's my problem, though: I have no idea how to do this. I know next to nothing about the command ...
2012/06/05
[ "https://Stackoverflow.com/questions/10904629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430987/" ]
I suggest using the 'pip' command on the command line. ``` pip search sqlite pip install pysqlite ```
> > Disclaimer: I'm not a Mac User, but by common knowledge i give you > this info. > > > You could follow the next instructions: Use Homebrew ------------ As this [page](http://mislav.uniqpath.com/rails/install-sqlite3/) mention: If you need to upgrade sqlite, you could use [Homebrew](http://brew.sh/). Homebr...
10,904,629
noob programmer here, I'm trying to get the SQLite3 on my Python installation up-to-date (I currently have version 3.6.11, whereas I need at least version 3.6.19, as that is the first version that supports foreign keys). Here's my problem, though: I have no idea how to do this. I know next to nothing about the command ...
2012/06/05
[ "https://Stackoverflow.com/questions/10904629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430987/" ]
> > Disclaimer: I'm not a Mac User, but by common knowledge i give you > this info. > > > You could follow the next instructions: Use Homebrew ------------ As this [page](http://mislav.uniqpath.com/rails/install-sqlite3/) mention: If you need to upgrade sqlite, you could use [Homebrew](http://brew.sh/). Homebr...
<https://pip.pypa.io/en/latest/installing.html> python get-pip.py python [complete path] python c:\folder\get-pip.py
10,904,629
noob programmer here, I'm trying to get the SQLite3 on my Python installation up-to-date (I currently have version 3.6.11, whereas I need at least version 3.6.19, as that is the first version that supports foreign keys). Here's my problem, though: I have no idea how to do this. I know next to nothing about the command ...
2012/06/05
[ "https://Stackoverflow.com/questions/10904629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430987/" ]
I just came fresh from installing this both in Mavericks and Mountain Lion. This [SO article](https://stackoverflow.com/questions/1545479/force-python-to-forego-native-sqlite3-and-use-the-installed-latest-sqlite3-ver/1546162#1546162) mentions using the build\_static method, which they say retrieves that latest version...
<https://pip.pypa.io/en/latest/installing.html> python get-pip.py python [complete path] python c:\folder\get-pip.py
10,904,629
noob programmer here, I'm trying to get the SQLite3 on my Python installation up-to-date (I currently have version 3.6.11, whereas I need at least version 3.6.19, as that is the first version that supports foreign keys). Here's my problem, though: I have no idea how to do this. I know next to nothing about the command ...
2012/06/05
[ "https://Stackoverflow.com/questions/10904629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430987/" ]
I recently installed python from source and used the following commands to install both SQLite from source and Python 2.7.13 from source. for SQLite3 you can use the following commands $SQLITE\_INSTALL\_LOCATION ``` $ curl -O http://www.sqlite.org/sqlite-autoconf-3070603.tar.gz $ tar xvfz sqlite-autoconf-3070603.tar...
<https://pip.pypa.io/en/latest/installing.html> python get-pip.py python [complete path] python c:\folder\get-pip.py
10,904,629
noob programmer here, I'm trying to get the SQLite3 on my Python installation up-to-date (I currently have version 3.6.11, whereas I need at least version 3.6.19, as that is the first version that supports foreign keys). Here's my problem, though: I have no idea how to do this. I know next to nothing about the command ...
2012/06/05
[ "https://Stackoverflow.com/questions/10904629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430987/" ]
I just came fresh from installing this both in Mavericks and Mountain Lion. This [SO article](https://stackoverflow.com/questions/1545479/force-python-to-forego-native-sqlite3-and-use-the-installed-latest-sqlite3-ver/1546162#1546162) mentions using the build\_static method, which they say retrieves that latest version...
> > Disclaimer: I'm not a Mac User, but by common knowledge i give you > this info. > > > You could follow the next instructions: Use Homebrew ------------ As this [page](http://mislav.uniqpath.com/rails/install-sqlite3/) mention: If you need to upgrade sqlite, you could use [Homebrew](http://brew.sh/). Homebr...
10,904,629
noob programmer here, I'm trying to get the SQLite3 on my Python installation up-to-date (I currently have version 3.6.11, whereas I need at least version 3.6.19, as that is the first version that supports foreign keys). Here's my problem, though: I have no idea how to do this. I know next to nothing about the command ...
2012/06/05
[ "https://Stackoverflow.com/questions/10904629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430987/" ]
I recently installed python from source and used the following commands to install both SQLite from source and Python 2.7.13 from source. for SQLite3 you can use the following commands $SQLITE\_INSTALL\_LOCATION ``` $ curl -O http://www.sqlite.org/sqlite-autoconf-3070603.tar.gz $ tar xvfz sqlite-autoconf-3070603.tar...
> > Disclaimer: I'm not a Mac User, but by common knowledge i give you > this info. > > > You could follow the next instructions: Use Homebrew ------------ As this [page](http://mislav.uniqpath.com/rails/install-sqlite3/) mention: If you need to upgrade sqlite, you could use [Homebrew](http://brew.sh/). Homebr...
33,978,739
First post to the forum here. I searched for an answer, but wasnt exactly sure how to phrase the search. I am currently working through "learn python the hard way" and one of the drills he uses this coding: ``` target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.wri...
2015/11/29
[ "https://Stackoverflow.com/questions/33978739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5616687/" ]
Using a comma sends each object as a separate argument. Concatenate them with `+` instead, or `join()` them: ``` target.write(line1 + "\n" + line2 + "\n" + line3) ``` Or: ``` target.write('\n'.join((line1, line2, line3))) ```
You can use Python's `str` `format`: ``` target.write('{}\n{}\n{}'.format(line1, line2, line3)) ```
33,580,308
Hello I am new to python, I was trying to find the distance from different points. Example: The distance between each door is about 2.5 feet. So the distance between door 1 and door 2 is 2.5 feet. How would i go about looking for two different distanced in the door dictionary. or should i use something else. ``` d =...
2015/11/07
[ "https://Stackoverflow.com/questions/33580308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5533124/" ]
try this ``` final ListPopupWindow listPopupWindow = new ListPopupWindow( context); listPopupWindow.setAdapter(new ArrayAdapter( context, R.layout.list_row_layout, arrayOfValues)); listPopupWindow.setAnchorView(your_view); ...
Exmaple : ``` findViewById(R.id.btn).setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //use MotionEvent event : getX() and getY() will return your pressing location in the button. } }); ```
72,363,146
I am working on a project where I have to send arguments by a command line to a python file (using system exec) and then visualize the results saved in a folder after the python file finishes executing. I need to have this by only clicking on one button, so my question is, if there is any way to realize this scenario o...
2022/05/24
[ "https://Stackoverflow.com/questions/72363146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18449615/" ]
The way you phrased your question makes me think that you want to wait until the command you call via system exec finished and then run some code. You could simply use a sequence structure for this. However, if you need to do this *asynchronously*, i.e. launch the command and get an event when the command finished so ...
Use "wait until completion?" input of System Exec function to make sure the script finished execution, then proceed with the results visualization part.
69,856,536
**Goal:** Using python, I want to create a service account in a project on the Google Cloud Platform and grant that service account one role. **Problem:** The docs explain [here](https://cloud.google.com/iam/docs/granting-changing-revoking-access#grant-single-role) how to grant a single role to the service acc...
2021/11/05
[ "https://Stackoverflow.com/questions/69856536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13439686/" ]
Creating a service account, creating a service account key, downloading a service account JSON key file, and granting a role are separate steps. There is no single API to create a service account and grant a role at the same time. Anytime you update a project's IAM bindings is a risk. Google prevents multiple applicat...
As mentioned in John’s answer, you should be very careful when manipulating the IAM module, if something goes wrong it could end in services completely inoperable. Here is a Google’s document which [manipulates the IAM resources using the REST API](https://cloud.google.com/resource-manager/reference/rest/v1/projects/se...
63,695,246
Is there a fast possibility to reverse a binary number in python? Example: I have the number 11 in binary 0000000000001011 with 16 Bits. Now I'm searching for a **fast** function f, which returns 1101000000000000 (decimal 53248). Lookup tables are no solutions since i want it to scale to 32Bit numbers. Thank you for y...
2020/09/01
[ "https://Stackoverflow.com/questions/63695246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8080648/" ]
This might be faster using small 8-bit lookup table: ``` num = 11 # One time creation of 8bit lookup rev = [int(format(b, '08b')[::-1], base=2) for b in range(256)] # Run for each number to be flipped. lower_rev = rev[num & 0xFF] << 8 upper_rev = rev[(num & 0xFF00) >> 8] flipped = lower_rev + upper_rev ```
My current approach is to access the bits via bit shifting and mask and to shift them in the mirror number until they reach their destination. Still I have the feeling that there is room for improvement. ``` num = 11 print(format(num, '016b')) right = num left = 0 for i in range(16): tmp = right & 1 left = (left ...
63,695,246
Is there a fast possibility to reverse a binary number in python? Example: I have the number 11 in binary 0000000000001011 with 16 Bits. Now I'm searching for a **fast** function f, which returns 1101000000000000 (decimal 53248). Lookup tables are no solutions since i want it to scale to 32Bit numbers. Thank you for y...
2020/09/01
[ "https://Stackoverflow.com/questions/63695246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8080648/" ]
This might be faster using small 8-bit lookup table: ``` num = 11 # One time creation of 8bit lookup rev = [int(format(b, '08b')[::-1], base=2) for b in range(256)] # Run for each number to be flipped. lower_rev = rev[num & 0xFF] << 8 upper_rev = rev[(num & 0xFF00) >> 8] flipped = lower_rev + upper_rev ```
I think you can just use slicing to get what you are looking for: ``` b=bytes('0000000000001011'.encode('utf-8')) >>> b b'0000000000001011' >>> b[::-1] b'1101000000000000' ```
63,695,246
Is there a fast possibility to reverse a binary number in python? Example: I have the number 11 in binary 0000000000001011 with 16 Bits. Now I'm searching for a **fast** function f, which returns 1101000000000000 (decimal 53248). Lookup tables are no solutions since i want it to scale to 32Bit numbers. Thank you for y...
2020/09/01
[ "https://Stackoverflow.com/questions/63695246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8080648/" ]
This might be faster using small 8-bit lookup table: ``` num = 11 # One time creation of 8bit lookup rev = [int(format(b, '08b')[::-1], base=2) for b in range(256)] # Run for each number to be flipped. lower_rev = rev[num & 0xFF] << 8 upper_rev = rev[(num & 0xFF00) >> 8] flipped = lower_rev + upper_rev ```
There's this, but in Python it seems slower than Matthias' proposed `int`->`str`->`int` solution. ``` x = ((x & 0x5555) << 1) | ((x & 0xAAAA) >> 1) x = ((x & 0x3333) << 2) | ((x & 0xCCCC) >> 2) x = ((x & 0x0F0F) << 4) | ((x & 0xF0F0) >> 4) x = ((x & 0x00FF) << 8) | (x >> 8) ```
52,553,757
I am a newcomer to python. I want to implement a "For" loop on the elements of a dataframe, with an embedded "if" statement. Code: ``` import numpy as np import pandas as pd #Dataframes x = pd.DataFrame([1,-2,3]) y = pd.DataFrame() for i in x.iterrows(): for j in x.iteritems(): if x>0: y = x...
2018/09/28
[ "https://Stackoverflow.com/questions/52553757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1978243/" ]
In pandas is best avoid loops if exist vectorized solution: ``` x = pd.DataFrame([1,-2,3], columns=['a']) y = pd.DataFrame(np.where(x['a'] > 0, x['a'] * 2, 0), columns=['b']) print (y) b 0 2 1 0 2 6 ``` **Explanation**: First compare column by value for boolean mask: ``` print (x['a'] > 0) 0 True 1 F...
You can try this: ``` y = (x[(x > 0)]*2).fillna(0) ```
20,629,561
#### With many started postgresql services, psql chooses the lowest postgresql version I have installed two versions of postgresql, `12` and `13` (in an earlier version of this question, these were `9.1` and `9.2`, I change this to be in line with the added output details from the higher versions). ``` sudo service p...
2013/12/17
[ "https://Stackoverflow.com/questions/20629561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813589/" ]
This situation with two clusters in Ubuntu may happen when upgrading to a newer release providing an newer postgresql version. The automatic upgrade does not remove the old cluster, presumably for fear of erasing valuable data (which is wise because some postgres upgrades may require human work to be complete). If yo...
`psql` fails because none of your postgres is running. First, you should understand **why** there are 2 different servers, then delete one of them (through `apt-get`, I think), and if necessary reconfigure the other (if you type `sudo service portgresql start`, both of the servers will start, and to connect to 9.2 y...
47,684,408
new to web development and i need some help to figure out the basics.I have a website right now,which is working fine,on a VPS with Ubuntu 16.04 and Apache.Say i would like a converter in my site or in a mobile application and have a python script in my server doing all the work.How can i send the python program the re...
2017/12/06
[ "https://Stackoverflow.com/questions/47684408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5540416/" ]
There are a few things you need to take into consideration. **Centralising this element** To address your issue of centralising this element with a couple of methods: **Option 1.** You can make the entire `span` width 100% and center the text within it by adding this to `#header-content`: ``` width: 100%; display:...
First you need to make the image `max-width:100%` to avoid overflow, then simply adjust left/right/bottom values since your element is absolute position and add `text-align:center` : ```css .elixir { position: absolute; top: 5px; left: 15px; color: white; font-weight: bold; font-size: 50px; } .lev...
47,684,408
new to web development and i need some help to figure out the basics.I have a website right now,which is working fine,on a VPS with Ubuntu 16.04 and Apache.Say i would like a converter in my site or in a mobile application and have a python script in my server doing all the work.How can i send the python program the re...
2017/12/06
[ "https://Stackoverflow.com/questions/47684408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5540416/" ]
There are a few things you need to take into consideration. **Centralising this element** To address your issue of centralising this element with a couple of methods: **Option 1.** You can make the entire `span` width 100% and center the text within it by adding this to `#header-content`: ``` width: 100%; display:...
By using `left:0; right:0;` and appropirate margin value, you should be able to center it. You could also set the width of the `#header-content` and set `margin:0 auto;`, it would achieve the same effect. I also fit the image inside parent and added a curve to the label, you can see everything commented in css. Workin...
47,684,408
new to web development and i need some help to figure out the basics.I have a website right now,which is working fine,on a VPS with Ubuntu 16.04 and Apache.Say i would like a converter in my site or in a mobile application and have a python script in my server doing all the work.How can i send the python program the re...
2017/12/06
[ "https://Stackoverflow.com/questions/47684408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5540416/" ]
There are a few things you need to take into consideration. **Centralising this element** To address your issue of centralising this element with a couple of methods: **Option 1.** You can make the entire `span` width 100% and center the text within it by adding this to `#header-content`: ``` width: 100%; display:...
Not too sure, but looks like you are just missing coordonates and text-align. update example for `#header-content`: ``` bottom: 30px; left:24px; right:24px; text-align:center; ``` and eventually ``` border-radius:0 0 10px 10px; text-shadow:1px 1px white; ``` --- Demo below: ```css .elixir { pos...
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
I think the solutions using split are good. I tried to solve it without `split` and here's what I came up with. ``` sOdd = "The cat jumped over the moon very quickly." sEven = "The cat jumped over the moon very quickly now." def split_on_delim_mid(s, delim=" "): delim_indexes = [ x[0] for x in enumerate(s) if...
Solutions with `split()` and `join()` are fine if you want to get half the words, not half the string (counting the characters and not the words). I think the latter is impossibile without a `for` loop or a list comprehension (or an expensive workaround such a recursion to find the indexes of the spaces maybe). But if...
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
I think the solutions using split are good. I tried to solve it without `split` and here's what I came up with. ``` sOdd = "The cat jumped over the moon very quickly." sEven = "The cat jumped over the moon very quickly now." def split_on_delim_mid(s, delim=" "): delim_indexes = [ x[0] for x in enumerate(s) if...
As Valentino says, the answer depends on whether you want to split the number of characters as evenly as possible or the number of words as evenly as possible: `split()`-based methods will do the latter. Here's a way to do the former without looping or list comprehension. `delim` can be any single character. This meth...
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
This should work: ``` def split_text(text): middle = len(text)//2 under = text.rfind(" ", 0, middle) over = text.find(" ", middle) if over > under and under != -1: return (text[:,middle - under], text[middle - under,:]) else: if over is -1: raise ValueError("No separat...
You can use `min` to find the closest space to the middle and then slice the string. ``` s = "The cat jumped over the moon very quickly." mid = min((i for i, c in enumerate(s) if c == ' '), key=lambda i: abs(i - len(s) // 2)) fst, snd = s[:mid], s[mid+1:] print(fst) print(snd) ``` ### Output ``` The cat jumped o...
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
how about something like this: ``` s = "The cat jumped over the moon very quickly" l = s.split() s1 = ' '.join(l[:len(l)//2]) s2 = ' '.join(l[len(l)//2 :]) print(s1) print(s2) ```
As Valentino says, the answer depends on whether you want to split the number of characters as evenly as possible or the number of words as evenly as possible: `split()`-based methods will do the latter. Here's a way to do the former without looping or list comprehension. `delim` can be any single character. This meth...
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
This should work: ``` def split_text(text): middle = len(text)//2 under = text.rfind(" ", 0, middle) over = text.find(" ", middle) if over > under and under != -1: return (text[:,middle - under], text[middle - under,:]) else: if over is -1: raise ValueError("No separat...
how about something like this: ``` s = "The cat jumped over the moon very quickly" l = s.split() s1 = ' '.join(l[:len(l)//2]) s2 = ' '.join(l[len(l)//2 :]) print(s1) print(s2) ```
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
This should work: ``` def split_text(text): middle = len(text)//2 under = text.rfind(" ", 0, middle) over = text.find(" ", middle) if over > under and under != -1: return (text[:,middle - under], text[middle - under,:]) else: if over is -1: raise ValueError("No separat...
As Valentino says, the answer depends on whether you want to split the number of characters as evenly as possible or the number of words as evenly as possible: `split()`-based methods will do the latter. Here's a way to do the former without looping or list comprehension. `delim` can be any single character. This meth...
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
This should work: ``` def split_text(text): middle = len(text)//2 under = text.rfind(" ", 0, middle) over = text.find(" ", middle) if over > under and under != -1: return (text[:,middle - under], text[middle - under,:]) else: if over is -1: raise ValueError("No separat...
Solutions with `split()` and `join()` are fine if you want to get half the words, not half the string (counting the characters and not the words). I think the latter is impossibile without a `for` loop or a list comprehension (or an expensive workaround such a recursion to find the indexes of the spaces maybe). But if...
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
I'd just split then rejoin: ``` text = "The cat jumped over the moon very quickly" words = text.split() first_half = " ".join(words[:len(words)//2]) ```
As Valentino says, the answer depends on whether you want to split the number of characters as evenly as possible or the number of words as evenly as possible: `split()`-based methods will do the latter. Here's a way to do the former without looping or list comprehension. `delim` can be any single character. This meth...
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
This should work: ``` def split_text(text): middle = len(text)//2 under = text.rfind(" ", 0, middle) over = text.find(" ", middle) if over > under and under != -1: return (text[:,middle - under], text[middle - under,:]) else: if over is -1: raise ValueError("No separat...
I think the solutions using split are good. I tried to solve it without `split` and here's what I came up with. ``` sOdd = "The cat jumped over the moon very quickly." sEven = "The cat jumped over the moon very quickly now." def split_on_delim_mid(s, delim=" "): delim_indexes = [ x[0] for x in enumerate(s) if...
54,298,939
Is there a way to split a python string without using a for loop that basically splits a string in the middle to the closest delimiter. Like: ``` The cat jumped over the moon very quickly. ``` The delimiter would be the space and the resulting strings would be: ``` The cat jumped over the moon very quickly. ``` ...
2019/01/21
[ "https://Stackoverflow.com/questions/54298939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327258/" ]
Solutions with `split()` and `join()` are fine if you want to get half the words, not half the string (counting the characters and not the words). I think the latter is impossibile without a `for` loop or a list comprehension (or an expensive workaround such a recursion to find the indexes of the spaces maybe). But if...
As Valentino says, the answer depends on whether you want to split the number of characters as evenly as possible or the number of words as evenly as possible: `split()`-based methods will do the latter. Here's a way to do the former without looping or list comprehension. `delim` can be any single character. This meth...
4,184,841
I need to color the white part surrounded by black edges! ``` from PIL import Image import sys image=Image.open("G:/ghgh.bmp") data=image.load() image_width,image_height=image.size sys.setrecursionlimit(10115) def f(x,y): if(x<image_width and y<image_height and x>0 and y>0): if (data[x,y]==255): ...
2010/11/15
[ "https://Stackoverflow.com/questions/4184841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/508292/" ]
Some warnings provide a description, others may not. Maybe the documentation is just incomplete or the authors figure some warnings don't need additional clarification?
If stylecop check is been run during a build (MSBuild/VS build) the show help option wont appear, however if you right click on the solution and run stylecop check, it will have the show help option. Hope that helps
29,775,006
I've been writing automated tests with Selenium Webdriver 2.45 in python. To get through some of the things I need to test I must retrieve the various `JSESSION` cookies that are generate from the site. When I use webdrivers `get_cookies()` function with Firefox or Chrome all of the needed cookies return to me. When I ...
2015/04/21
[ "https://Stackoverflow.com/questions/29775006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3249517/" ]
What you describe sounds like an issue I ran into a few months ago. My tests ran fine with Chrome and Firefox but not in IE, and the problem was cookies. Upon investigation what I found is that my web site had set its session cookies to be [HTTP-only](https://en.wikipedia.org/wiki/HTTP_cookie#Secure_and_HttpOnly). When...
There is an open issue with IE and Safari. Those driver will not return correct cookies information. At least not the domain. See [this](https://code.google.com/p/selenium/issues/detail?id=8509)
60,992,133
I am trying to get my PTZ camera to stream using python 3 and openCV. The URL i use in the code works with VLC stream but not with the code. ``` import cv2 import numpy as np cap = cv2.VideoCapture(src="rtsp://USER:PASS@XX.XXX.XXX.XXX:XXX/Streaming/Channels/101/") FRAME_WIDTH = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) ...
2020/04/02
[ "https://Stackoverflow.com/questions/60992133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13198103/" ]
one small change, remove **src=** from the cv2.VideoCapture() method. It should look like, ``` cap = cv2.VideoCapture("rtsp://USER:PASS@XX.XXX.XXX.XXX:XXX/Streaming/Channels/101/") ```
This is working for me in Hikvision camera. Avoid using special letter in the password. ``` import cv2 cap = cv2.VideoCapture('rtsp://username:password@10.199.27.123:554') while True: ret, img = cap.read() cv2.imshow('video output', img) k = cv2.waitKey(10)& 0xff if k == 27: break cap.release()...
67,740,665
The Script, running on a Linux host, should call some Windows hosts holding Oracle Databases. Each Oracle Database is in DNS with its name "db-[ORACLE\_SID]". Lets say you have a database with ORACLE SID `TEST02`, it can be resolved as `db-TEST02`. The complete script is doing some more stuff, but this example is suffi...
2021/05/28
[ "https://Stackoverflow.com/questions/67740665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15623827/" ]
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(...
74,195,370
Hello so im new on python, i want to know how to do multiple string input on list. I already try to append the input to the list, but it doesn't give me expected output. Here is the source code: ``` test=[] input1=input("Enter multiple strings: ") splitinput1=input1.split() for x in range(len(splitinput1)): test.a...
2022/10/25
[ "https://Stackoverflow.com/questions/74195370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19363291/" ]
> > reducing vertex data down to 32bits per vertex is as far as the GPU will allow > > > You seem to think that vertex buffer sizes are what's holding you back. Make no mistake here, they are not. You have many gigs of VRAM to work with, use them if it will make your code faster. Specifically, anything you're unpa...
I think your code is CPU bound. While your approach has very small vertices, you have non-trivial API overhead. A better approach is rendering all quads with a single draw call. I would probably use instancing for that. Assuming you want arbitrary per-quad size, position, and orientation in 3D space, here’s one possi...
48,702,330
Code: ``` a={'day': [{'average_price': 9.3, 'buy_m2m': 9.3, 'buy_price': 9.3, 'buy_quantity': 1, 'buy_value': 9.3, 'close_price': 0, 'exchange': 'NSE', 'instrument_token': 2867969, 'last_price': 9.3, 'm2m': 0.0, 'multiplier': 1, 'net_buy_amount_m2m': 9.3, 'net_sell_amount_m2m': 0, ...
2018/02/09
[ "https://Stackoverflow.com/questions/48702330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9337404/" ]
`Footer` is not inside a section element, so your selector won't work. ```css .mypage :not(footer) p{ color:red } ``` ```html <body class="mypage"> <section> <p>Hello world</p> </section> <footer> <p>footer content</p> </footer> </body> ```
Why not target the footer again ? ``` .mypage section p{color: red} .mypage footer p{color: blue} <body class="mypage"> <section> <p>Hello world</p> </section> <footer> <p>footer content</p> </footer> </body> ```
37,297,276
I have a data frame ``` df=data.frame(f=c('a','ab','abc'),v=1:3) ``` and make a new column with: ``` df$c=paste(df$v,df$f,sep='') ``` the result is ``` > df f v c 1 a 1 1a 2 ab 2 2ab 3 abc 3 3abc ``` I would like column c to be in this format: ``` > df f v c 1 a 1 1 a 2 ab 2 2 ab 3 abc...
2016/05/18
[ "https://Stackoverflow.com/questions/37297276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2123706/" ]
You can use the `format()` function to pretty print the values of your column. For example: ``` > format(df$f, width = 3, justify = "right") [1] " a" " ab" "abc" ``` So your code should be: ``` df <- within(df, { c <- paste0(v, format(f, width = 3, justify = "right")) }) df ``` The result: ``` > df f v ...
You can use the `formatC`function as follow ``` df$c <- paste(df$v, formatC(as.character(df$f), width = 3, flag = " "), sep = "") df f v c 1 a 1 1 a 2 ab 2 2 ab 3 abc 3 3abc ``` **DATA** ``` df <- data.frame(f = c('a','ab','abc'), v=1:3) ```
40,397,657
So, Im a complete newb when it comes to programming. I have been watching tutorials and I am reading a book on how to program python. So, I want to create a number generator guesser on my own and I have watched some tutorials on it but I do not want to recreate the code. basically, I want to make my own guesser with th...
2016/11/03
[ "https://Stackoverflow.com/questions/40397657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7096598/" ]
**Updated Answer** For ASP Core 1.1.0 generic model binding is now done using `Get`: ``` var config = Configuration.GetSection("configuredClients").Get<ClientConfiguration>(); ``` --- **Original Answer** How about this: ``` var config = Configuration.GetSection("configuredClients").Bind<ClientConfiguration>(...
You don't read the configuration manually generally in ASP.NET Core yourself, instead you create an object that matches your definition. You can read more on that in the official documentation [here](https://docs.asp.net/en/latest/fundamentals/configuration.html). E.g. ``` public class MyOptions { public string O...
40,397,657
So, Im a complete newb when it comes to programming. I have been watching tutorials and I am reading a book on how to program python. So, I want to create a number generator guesser on my own and I have watched some tutorials on it but I do not want to recreate the code. basically, I want to make my own guesser with th...
2016/11/03
[ "https://Stackoverflow.com/questions/40397657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7096598/" ]
**Updated Answer** For ASP Core 1.1.0 generic model binding is now done using `Get`: ``` var config = Configuration.GetSection("configuredClients").Get<ClientConfiguration>(); ``` --- **Original Answer** How about this: ``` var config = Configuration.GetSection("configuredClients").Bind<ClientConfiguration>(...
If you want to get first "clientName"(expected "Client1"), just write: ``` Configuration.GetSection("configuredClients")["clients:0:clientName"]; ``` **Update for comment** Install .NET Core 1.0.1 and go with @TomMakin's way.
40,397,657
So, Im a complete newb when it comes to programming. I have been watching tutorials and I am reading a book on how to program python. So, I want to create a number generator guesser on my own and I have watched some tutorials on it but I do not want to recreate the code. basically, I want to make my own guesser with th...
2016/11/03
[ "https://Stackoverflow.com/questions/40397657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7096598/" ]
**Updated Answer** For ASP Core 1.1.0 generic model binding is now done using `Get`: ``` var config = Configuration.GetSection("configuredClients").Get<ClientConfiguration>(); ``` --- **Original Answer** How about this: ``` var config = Configuration.GetSection("configuredClients").Bind<ClientConfiguration>(...
With **ASP.NET Core 2.0** (basically Core 1.1+), the `IConfiguration` is injected to `Startup`, and that can be used within `ConfigureServices()` and `Configure()` methods. As shown in the accepted answer, the configuration can be bound to an object. But if just one value is required, the key based approach works well...
40,397,657
So, Im a complete newb when it comes to programming. I have been watching tutorials and I am reading a book on how to program python. So, I want to create a number generator guesser on my own and I have watched some tutorials on it but I do not want to recreate the code. basically, I want to make my own guesser with th...
2016/11/03
[ "https://Stackoverflow.com/questions/40397657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7096598/" ]
You don't read the configuration manually generally in ASP.NET Core yourself, instead you create an object that matches your definition. You can read more on that in the official documentation [here](https://docs.asp.net/en/latest/fundamentals/configuration.html). E.g. ``` public class MyOptions { public string O...
If you want to get first "clientName"(expected "Client1"), just write: ``` Configuration.GetSection("configuredClients")["clients:0:clientName"]; ``` **Update for comment** Install .NET Core 1.0.1 and go with @TomMakin's way.
40,397,657
So, Im a complete newb when it comes to programming. I have been watching tutorials and I am reading a book on how to program python. So, I want to create a number generator guesser on my own and I have watched some tutorials on it but I do not want to recreate the code. basically, I want to make my own guesser with th...
2016/11/03
[ "https://Stackoverflow.com/questions/40397657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7096598/" ]
With **ASP.NET Core 2.0** (basically Core 1.1+), the `IConfiguration` is injected to `Startup`, and that can be used within `ConfigureServices()` and `Configure()` methods. As shown in the accepted answer, the configuration can be bound to an object. But if just one value is required, the key based approach works well...
You don't read the configuration manually generally in ASP.NET Core yourself, instead you create an object that matches your definition. You can read more on that in the official documentation [here](https://docs.asp.net/en/latest/fundamentals/configuration.html). E.g. ``` public class MyOptions { public string O...
40,397,657
So, Im a complete newb when it comes to programming. I have been watching tutorials and I am reading a book on how to program python. So, I want to create a number generator guesser on my own and I have watched some tutorials on it but I do not want to recreate the code. basically, I want to make my own guesser with th...
2016/11/03
[ "https://Stackoverflow.com/questions/40397657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7096598/" ]
With **ASP.NET Core 2.0** (basically Core 1.1+), the `IConfiguration` is injected to `Startup`, and that can be used within `ConfigureServices()` and `Configure()` methods. As shown in the accepted answer, the configuration can be bound to an object. But if just one value is required, the key based approach works well...
If you want to get first "clientName"(expected "Client1"), just write: ``` Configuration.GetSection("configuredClients")["clients:0:clientName"]; ``` **Update for comment** Install .NET Core 1.0.1 and go with @TomMakin's way.
70,736,110
I have a pandas dataframe like this: ``` df = pd.DataFrame([ {'A': 'aaa', 'B': 0.01, 'C': 0.00001, 'D': 0.00999999999476131, 'E': 0.00023191546403037534}, {'A': 'bbb', 'B': 0.01, 'C': 0.0001, 'D': 0.010000000000218279, 'E': 0.002981781316158273}, {'A': 'ccc', 'B': 0.1, 'C': 0...
2022/01/17
[ "https://Stackoverflow.com/questions/70736110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14382768/" ]
You can use a `-log10` operation to obtain the number of decimals before a digit (credit goes to @Willem van Onsem's answer [here](https://stackoverflow.com/questions/57663565/pandas-column-with-count-of-decimal-places)). Then you can incorporate this into a lambda function that you `apply` rowwise: ``` import numpy ...
I use part of the solution above of Derek and make my solution: ``` df['b_decimals'] = -np.floor(np.log10(df['B'])) df['c_decimals'] = -np.floor(np.log10(df['C'])) df['D'] = [np.around(x, y) for x, y in zip(df['D'], df['b_decimals'].astype(int))] df['E'] = [np.around(x, y) for x, y in zip(df['E'], df['c_decimals'].as...
62,446,911
I have this dataset ``` age 24 32 29 23 23 31 25 26 34 ``` I want to categorize using python and save the result to a new column "agegroup" such that age between; 23 to 26 to return 1 in the agegroup column, 27-30 to return value 2 in the agegroup column and 31-34 to return 3 in the agegroup column
2020/06/18
[ "https://Stackoverflow.com/questions/62446911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12360445/" ]
You can use [`pandas.cut`](https://pandas.pydata.org/docs/reference/api/pandas.cut.html). Given: ``` >>> df age 0 24 1 32 2 29 3 23 4 23 5 31 6 25 7 26 8 34 ``` Solution: ``` >>> df.assign(agegroup=pd.cut(df['age'], bins=[23, 27, 31, 35], right=False, labels=[1, 2, 3])) age agegroup 0 24 ...
You can use dictionaries to do this as well. Key-value pairs. The keys would be the different age ranges and the value for a particular key would be the count for that particular age group. groupDict={'23-26':0,'27-30':0,'31-34':0} ``` for i in ages: if i>=23 and i<=26: groupDict['23-26']+=1 elif i>=27 and i<=30...
40,744,392
I use Anonymous Python Functions in BitBake recipes to set variables during parsing. Now I wonder if I can check if a specific variable is set or not. If not, then I want to generate a BitBake Error, which stops the build process. Pseudo code, that I want to create: ``` python __anonymous () { if d.getVar('MY_VAR...
2016/11/22
[ "https://Stackoverflow.com/questions/40744392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5316879/" ]
You can call `bb.fatal("MY_VARIABLE not set")` which will print that error and abort the build by throwing an exception. Beware that d.getVar() returns `None` when the variable is unset. You only get the empty string if that's your default value.
Outputs are possible on different loglevels and with python as well as shell script code For usage in python there are: * **bb.fatal** * bb.error * bb.warn * bb.note * bb.plain * bb.debug For usage in shell script there are: * **bbfatal** * bberror * bbwarn * bbnote * bbplain * bbdebug for example if you want to th...
37,228,607
In C, as well as in C++, one can in a for-loop change the index (for example `i`). This can be useful to, for example, compare a current element and based on that comparison compare the next element: ``` for(int i = 0; i < end; i++) if(array[i] == ':') if(array[++i] == ')') smileyDetected = true; ``` Now...
2016/05/14
[ "https://Stackoverflow.com/questions/37228607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762311/" ]
Perhaps: ``` smileyDetected = ':)' in "".join(array) ``` or per @jonrsharpe: ``` from itertools import tee # pairwise() from "Itertools Recipes" def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) for a, b in pairwise(array): if a...
In this special case, you could do: ``` for i, char in enumerate(array[:-1]): if char == ":" and array[i+1] == ")": smiley_detected = True ``` However, in the more general case, if you need to skip elements, you could modify the raw iterator: ``` iterator = iter(array) for char in iterator: if char ...
37,228,607
In C, as well as in C++, one can in a for-loop change the index (for example `i`). This can be useful to, for example, compare a current element and based on that comparison compare the next element: ``` for(int i = 0; i < end; i++) if(array[i] == ':') if(array[++i] == ')') smileyDetected = true; ``` Now...
2016/05/14
[ "https://Stackoverflow.com/questions/37228607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762311/" ]
Perhaps: ``` smileyDetected = ':)' in "".join(array) ``` or per @jonrsharpe: ``` from itertools import tee # pairwise() from "Itertools Recipes" def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) for a, b in pairwise(array): if a...
If `array` is a string, the shortest pythonic version would obviously be: ```py smileyDetected = ':)' in array ``` A more generic / non-string-specific way of doing this would be using iterators: ```py smileyDetected = (':', ')') in zip(array, array[1:]) ```
37,228,607
In C, as well as in C++, one can in a for-loop change the index (for example `i`). This can be useful to, for example, compare a current element and based on that comparison compare the next element: ``` for(int i = 0; i < end; i++) if(array[i] == ':') if(array[++i] == ')') smileyDetected = true; ``` Now...
2016/05/14
[ "https://Stackoverflow.com/questions/37228607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762311/" ]
If `array` is a string, the shortest pythonic version would obviously be: ```py smileyDetected = ':)' in array ``` A more generic / non-string-specific way of doing this would be using iterators: ```py smileyDetected = (':', ')') in zip(array, array[1:]) ```
In this special case, you could do: ``` for i, char in enumerate(array[:-1]): if char == ":" and array[i+1] == ")": smiley_detected = True ``` However, in the more general case, if you need to skip elements, you could modify the raw iterator: ``` iterator = iter(array) for char in iterator: if char ...
68,026,549
I'm using TFX to build an AI Pipeline on Vertex AI. I've followed [this tutorial](https://www.tensorflow.org/tfx/tutorials/tfx/gcp/vertex_pipelines_simple) to get started, then I adapted the pipeline to my own data which has over 100M rows of time series data. A couple of my components get killed midway because of memo...
2021/06/17
[ "https://Stackoverflow.com/questions/68026549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2005440/" ]
Turns out you can't at the moment but according to this [issue](https://github.com/tensorflow/tfx/issues/3194#issuecomment-802598448), this feature is coming. An alternative solution is to convert your TFX pipeline to a Kubeflow pipeline. Vertex AI pipelines support kubeflow and with these you can set memory and cpu c...
An alternate option to this solution would be using the dataflow beam runner which allows components to be run dataflow cluster via Vertex. I am still to find a way for specifying machine types for custom components Sample beam input: ``` BIG_QUERY_WITH_DIRECT_RUNNER_BEAM_PIPELINE_ARGS = [ --project= GOOGLE_CLOUD_PR...
24,862,912
**Solution:** My fault: The file where adding the icon to the button is used via the "placeholder" function from QtDesigner. The Main-programm located in a different folder searches in its own folder for the icon, not in the folder from the "imported" file. So you just have to add the path to the icon: ``` dirpath ...
2014/07/21
[ "https://Stackoverflow.com/questions/24862912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3027322/" ]
This works for me and is auto generated by pyqt when you convert a .ui file to .py with the [pyuic4](http://pyqt.sourceforge.net/Docs/PyQt4/designer.html#the-uic-module) tool. ``` Icon = QtGui.QIcon() Icon.addPixmap(QtGui.QPixmap(_fromUtf8("SOME FILE")), QtGui.QIcon.Normal, QtGui.QIcon.Off) button.setIcon(...
Do you have text rendered on that button? Try playing with the icon size setIconSize(), to begin with you can try setting it to the rect of the pixmap.
24,862,912
**Solution:** My fault: The file where adding the icon to the button is used via the "placeholder" function from QtDesigner. The Main-programm located in a different folder searches in its own folder for the icon, not in the folder from the "imported" file. So you just have to add the path to the icon: ``` dirpath ...
2014/07/21
[ "https://Stackoverflow.com/questions/24862912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3027322/" ]
I was able to create the `QPushButton` with Icon without any problem using the code you have provided.The following is the code I used. ``` from PyQt4 import QtGui,QtCore import sys class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) butto...
Do you have text rendered on that button? Try playing with the icon size setIconSize(), to begin with you can try setting it to the rect of the pixmap.
24,862,912
**Solution:** My fault: The file where adding the icon to the button is used via the "placeholder" function from QtDesigner. The Main-programm located in a different folder searches in its own folder for the icon, not in the folder from the "imported" file. So you just have to add the path to the icon: ``` dirpath ...
2014/07/21
[ "https://Stackoverflow.com/questions/24862912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3027322/" ]
I was able to create the `QPushButton` with Icon without any problem using the code you have provided.The following is the code I used. ``` from PyQt4 import QtGui,QtCore import sys class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) butto...
This works for me and is auto generated by pyqt when you convert a .ui file to .py with the [pyuic4](http://pyqt.sourceforge.net/Docs/PyQt4/designer.html#the-uic-module) tool. ``` Icon = QtGui.QIcon() Icon.addPixmap(QtGui.QPixmap(_fromUtf8("SOME FILE")), QtGui.QIcon.Normal, QtGui.QIcon.Off) button.setIcon(...