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
18,314,228
I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list e.g: ``` List = [a, bb, aa, ccc, dddd] Sublist1 = [a] Sublist2= [bb, aa] Sublist3= [ccc] Sublist2= [dddd] ``` How can i achieve this in python ? Thank you
2013/08/19
[ "https://Stackoverflow.com/questions/18314228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413734/" ]
by using `itertools.groupby`: ``` values = ['a', 'bb', 'aa', 'ccc', 'dddd', 'eee'] from itertools import groupby output = [list(group) for key,group in groupby(sorted(values, key=len), key=len)] ``` The result is: ``` [['a'], ['bb', 'aa'], ['ccc', 'eee'], ['dddd']] ``` If your list is already sorted by string ...
Assuming you're happy with a list of lists, indexed by length, how about something like ``` by_length = [] for word in List: wl = len(word) while len(by_length) < wl: by_length.append([]) by_length[wl].append(word) print "The words of length 3 are %s" % by_length[3] ```
18,314,228
I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list e.g: ``` List = [a, bb, aa, ccc, dddd] Sublist1 = [a] Sublist2= [bb, aa] Sublist3= [ccc] Sublist2= [dddd] ``` How can i achieve this in python ? Thank you
2013/08/19
[ "https://Stackoverflow.com/questions/18314228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413734/" ]
``` >>> from collections import defaultdict >>> l = ["a", "bb", "aa", "ccc", "dddd"] >>> d = defaultdict(list) >>> for elem in l: ... d[len(elem)].append(elem) ... >>> sublists = list(d.values()) >>> print(sublists) [['a'], ['bb', 'aa'], ['ccc'], ['dddd']] ```
Assuming you're happy with a list of lists, indexed by length, how about something like ``` by_length = [] for word in List: wl = len(word) while len(by_length) < wl: by_length.append([]) by_length[wl].append(word) print "The words of length 3 are %s" % by_length[3] ```
18,314,228
I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list e.g: ``` List = [a, bb, aa, ccc, dddd] Sublist1 = [a] Sublist2= [bb, aa] Sublist3= [ccc] Sublist2= [dddd] ``` How can i achieve this in python ? Thank you
2013/08/19
[ "https://Stackoverflow.com/questions/18314228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413734/" ]
by using `itertools.groupby`: ``` values = ['a', 'bb', 'aa', 'ccc', 'dddd', 'eee'] from itertools import groupby output = [list(group) for key,group in groupby(sorted(values, key=len), key=len)] ``` The result is: ``` [['a'], ['bb', 'aa'], ['ccc', 'eee'], ['dddd']] ``` If your list is already sorted by string ...
``` >>> from collections import defaultdict >>> l = ["a", "bb", "aa", "ccc", "dddd"] >>> d = defaultdict(list) >>> for elem in l: ... d[len(elem)].append(elem) ... >>> sublists = list(d.values()) >>> print(sublists) [['a'], ['bb', 'aa'], ['ccc'], ['dddd']] ```
29,997,120
I have a problem with a little server-client assignment in python 2.7. The client can send 5 types of requests to the server: 1. get the server's IP 2. get contents of a directory on the server 3. run cmd command on the server and get the output 4. open a calculator on the server 5. disconnect This is the error I ge...
2015/05/02
[ "https://Stackoverflow.com/questions/29997120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3554255/" ]
In code shown in your question: ``` HashTable::HashTable(int buckets) { this->buckets = buckets; vector<Entry>* table = new vector<Entry>[buckets]; } ``` you create a local variable `table` which is a pointer to `vector<Entry>` and then leak that memory. Then in `HashTable::insert` you try to access member v...
``` HashTable::HashTable(int buckets) { this->buckets = buckets; vector<Entry>* table = new vector<Entry>[buckets]; // this table is local to this function, also a memory leek. } ``` As I can see in your `HashTable` constructor, you are initializing a local `vector<Entry>* table` to your const...
54,233,559
I am generating a doc using python docx module. I want to bold the specific cell of a row in python docx here is the code ``` book_title = '\n-:\n {}\n\n'.format(book_title) book_desc = '-: {}\n\n:\n{}\n\n :\n{}'.format(book.author,book_description,sales_point) row1.cells[1].text = (book_title + book_desc) ``` I ...
2019/01/17
[ "https://Stackoverflow.com/questions/54233559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6892109/" ]
Here is how I understand it: Paragraph is holding the run objects and styles (bold, italic) are methods of run. So following this logic here is what might solve your question: ``` row1_cells[0].paragraphs[0].add_run(book_title + book_desc).bold=True ``` This is just an example for the first cell of the table. Please...
Since you are using the docx module, you can style your text/paragraph by explicitly defining the style. In order to apply a style, use the following code snippet referenced from docx documentation [here](https://python-docx.readthedocs.io/en/latest/user/styles-using.html#apply-a-style). ``` >>> from docx import Docu...
54,233,559
I am generating a doc using python docx module. I want to bold the specific cell of a row in python docx here is the code ``` book_title = '\n-:\n {}\n\n'.format(book_title) book_desc = '-: {}\n\n:\n{}\n\n :\n{}'.format(book.author,book_description,sales_point) row1.cells[1].text = (book_title + book_desc) ``` I ...
2019/01/17
[ "https://Stackoverflow.com/questions/54233559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6892109/" ]
A cell does not have a character style; character style can only be applied to text, and in particular to a *run* of text. This is in fact the defining characteristic of a run, being a sequence of characters that share the same character formatting, also known as *font* in `python-docx`. To get the book title with a d...
Since you are using the docx module, you can style your text/paragraph by explicitly defining the style. In order to apply a style, use the following code snippet referenced from docx documentation [here](https://python-docx.readthedocs.io/en/latest/user/styles-using.html#apply-a-style). ``` >>> from docx import Docu...
54,233,559
I am generating a doc using python docx module. I want to bold the specific cell of a row in python docx here is the code ``` book_title = '\n-:\n {}\n\n'.format(book_title) book_desc = '-: {}\n\n:\n{}\n\n :\n{}'.format(book.author,book_description,sales_point) row1.cells[1].text = (book_title + book_desc) ``` I ...
2019/01/17
[ "https://Stackoverflow.com/questions/54233559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6892109/" ]
Here is how I understand it: Paragraph is holding the run objects and styles (bold, italic) are methods of run. So following this logic here is what might solve your question: ``` row1_cells[0].paragraphs[0].add_run(book_title + book_desc).bold=True ``` This is just an example for the first cell of the table. Please...
In python-docx, the styling of any character in a docx template document can be overridden by the use of [Rich Text](https://docxtpl.readthedocs.io/en/latest/#richtext) styling. You should provide a context variable for the particular character/string that needs styling in your template, at the position of the characte...
54,233,559
I am generating a doc using python docx module. I want to bold the specific cell of a row in python docx here is the code ``` book_title = '\n-:\n {}\n\n'.format(book_title) book_desc = '-: {}\n\n:\n{}\n\n :\n{}'.format(book.author,book_description,sales_point) row1.cells[1].text = (book_title + book_desc) ``` I ...
2019/01/17
[ "https://Stackoverflow.com/questions/54233559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6892109/" ]
A cell does not have a character style; character style can only be applied to text, and in particular to a *run* of text. This is in fact the defining characteristic of a run, being a sequence of characters that share the same character formatting, also known as *font* in `python-docx`. To get the book title with a d...
In python-docx, the styling of any character in a docx template document can be overridden by the use of [Rich Text](https://docxtpl.readthedocs.io/en/latest/#richtext) styling. You should provide a context variable for the particular character/string that needs styling in your template, at the position of the characte...
10,216,019
So I was developing an app in Django and needed a function from the 1.4 version so I decided to update. But then a weird error appeared when I wanted to do `syncdb` I am using the new `manage.py` and as You can see it makes some of the tables but then fails : ``` ./manage.py syncdb Creating tables ... Creating ...
2012/04/18
[ "https://Stackoverflow.com/questions/10216019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1092459/" ]
I had the same issue, the definition for my custom field was missing the connection parameter. ``` from django.db import models class BigIntegerField(models.IntegerField): def db_type(self, connection): return "bigint" ```
Although already old, answered and accepted question but I am adding my understanding I have added it because I am not using customized type and it is a Django Evolution error (but not syncdb)`evolve --hint --execute`. I think it may be helpful for someone in future. . I am average in Python and new to Django. I als...
35,689,139
I am writing a simple web application where I want to use a print out a few korean characters. Although I changed the encoding in the header, the web application, when opened in chrome, prints out gibberish instead of regular Korean characters. I also changed my chrome language settings to display korean as well. Here'...
2016/02/28
[ "https://Stackoverflow.com/questions/35689139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4590749/" ]
Change your encoding/charset to a charset that supports all the characters. For example by replacing both occurrences of `iso-8859-1` to `utf-8`. [UTF-8](https://en.wikipedia.org/wiki/UTF-8) can support Korean characters and basically any writing systems that exist.
You can use the [korean package](https://pypi.python.org/pypi/korean) : Example : ``` from korean import Noun fmt = u'{subj:์€} {obj:์„} ๋จน์—ˆ๋‹ค.' print fmt.format(subj=Noun(u'๋‚˜'), obj=Noun(u'๋ฐฅ')) print fmt.format(subj=Noun(u'ํ•™์ƒ'), obj=Noun(u'๋ˆ๊นŒ์Šค')) ``` Output : ``` ๋‚˜์€ ๋ฐฅ์„ ๋จน์—ˆ๋‹ค. ํ•™์ƒ์€ ๋ˆ๊นŒ์Šค์„ ๋จน์—ˆ๋‹ค. ```
67,663,059
I m testing my incomplete kivy app to grap a suitable apk of that. using buildozer and ubuntu i generate the apk, but it crashes right after starting it on android device. Is buildozer spec file the root cause should change something inside that? , or its incompatible version issue. please share kivy, kivymd, python an...
2021/05/23
[ "https://Stackoverflow.com/questions/67663059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13331490/" ]
Try using `kivy 2.0.0rc4`. Install it in plugins trough settings in pycharm. And your `buildozer.spec` should be like this: ``` requirements = python3,kivy==2.0.0rc4 ```
Refer to the requirements specidied in buildozer.spec file for the KivyMD-kitchen\_sink app in the repo. This is the link -> [Kitchen\_Sink\_Repo](https://github.com/kivymd/KivyMD/blob/master/demos/kitchen_sink/buildozer.spec) **Tip** If, after changing the `requirements` you still see your app crashing, run the fol...
60,389,566
I am new to multi-processing and python, from the documentation, <https://docs.python.org/3/library/multiprocessing.html> I was able to run the below code. ``` from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': with Pool(5) as p: print(p.map(f, [1, 2, 3])) ``` But if...
2020/02/25
[ "https://Stackoverflow.com/questions/60389566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9066431/" ]
Maybe you are looking for [`starmap`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.starmap)? > > `starmap(func, iterable[, chunksize])` > > > Like map() except that the elements of the iterable are expected to be iterables that are unpacked as arguments. > > > Hence an iterable...
Use [`p.starmap()`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.starmap), it's meant for exactly this case.
70,074,369
I have a list of words like this: ``` word_list=[{"word": "python", "repeted": 4}, {"word": "awsome", "repeted": 3}, {"word": "frameworks", "repeted": 2}, {"word": "programing", "repeted": 2}, {"word": "stackoverflow", "repeted": 2}, {"word": "work", "repeted": 1}, {"wo...
2021/11/23
[ "https://Stackoverflow.com/questions/70074369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17483739/" ]
numpy broadcasting is so useful here: ```py bm = df_other.values[:, 0] == df.values ``` Output: ```py >>> bm array([[ True, True, False, False, False], [False, False, True, False, False], [False, False, False, True, False]]) ``` If you need it as ints: ```py >>> bm.astype(int) array([[1, 1, 0, 0...
Another way to do this using pandas methods are as follows: ``` pd.crosstab(df_other['a'], df_other['c']).reindex(df['a']).to_numpy(dtype=int) ``` Output: ``` array([[1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0]]) ```
63,759,451
I'm trying to check the validity of comma-separated strings in python. That is, it's possible that the strings contain mistakes whereby there are more than one comma used. Here is a valid string: ``` foo = "a, b, c, d, e" ``` This is a valid string as it is comma-delimited; only one comma, not several or spaces onl...
2020/09/05
[ "https://Stackoverflow.com/questions/63759451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5269850/" ]
It appears the best way to accomplish this is with regex: Here is a valid string: ``` valid = "a, b, c, foo, bar, dog, cat" ``` Here are various invalid strings: ``` ## invalid1 is invalid as it contains multiple , i.e. `,,` and : invalid1 = "a,, b, c,,,,d, e,,; f, g" ## invalid2 is invalid as it contains `, ,` ...
Here you have some way to check if it's valid: ``` def is_valid(comma_sep_str): if ';' in comma_sep_str or ',,' in comma_sep_str: return 'Not valid' else: return 'Valid' myString1 = "a,, b, c,,,,d, e,,; f, g" myString2 = "a, b, c, d, e" print(is_valid(myString1)) print(is_valid(myString2)) ``` PS: Mayb...
62,882,592
I have a `df` named `data` as follows: ``` id upper_ci lower_ci max_power_contractual 0 12858 60.19878860406808 49.827481214215204 0 1 12858 60.61189293066522 49.298784196530896 0 2 12858 60.34397624424309 49.718421137642885 70 3 12858 59.87472261936114 49.464255779713476 10 4 12858 60.2735279...
2020/07/13
[ "https://Stackoverflow.com/questions/62882592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11853632/" ]
You can use `np.where` to add the new column: ``` df['up_threshold'] = np.where(df['max_power_contractual'].fillna(0) == 0, df['upper_ci'], np.where(df['max_power_contractual'] > df['upper_ci'], df['upper_ci'], df['max_power_contractual']) ) print(df) ``` Prints: ``` id upper_ci lower_ci max_power_c...
Not the efficient way but easier to understand ``` In [17]: def process(data): ...: result = None ...: if (data['max_power_contractual'] in (0, np.nan)) or (data['max_power_contractual'] > data['upper_ci']): ...: result = data['upper_ci'] ...: elif (data['upper_ci'] > data['max_power...
62,882,592
I have a `df` named `data` as follows: ``` id upper_ci lower_ci max_power_contractual 0 12858 60.19878860406808 49.827481214215204 0 1 12858 60.61189293066522 49.298784196530896 0 2 12858 60.34397624424309 49.718421137642885 70 3 12858 59.87472261936114 49.464255779713476 10 4 12858 60.2735279...
2020/07/13
[ "https://Stackoverflow.com/questions/62882592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11853632/" ]
Use `np.select` ```py import numpy as np m1 = df.max_power_contractual.isin([np.NaN, 0]) m2 = df.max_power_contractual > df.upper_ci df['up_threshold'] = np.select([m1, m2], [df.upper_ci, df.upper_ci], default=df.max_power_contractual) print(df) ``` Output ``` id upper_ci lower_ci max_power_contractual...
Not the efficient way but easier to understand ``` In [17]: def process(data): ...: result = None ...: if (data['max_power_contractual'] in (0, np.nan)) or (data['max_power_contractual'] > data['upper_ci']): ...: result = data['upper_ci'] ...: elif (data['upper_ci'] > data['max_power...
39,666,183
Im trying to extract all the images from a page. I have used Mechanize Urllib and selenium to extract the Html but the part i want to extract is never there. Also when i view the page source im not able to view the part i want to extract. Instead of the Description i want to extract there is this: ``` <div class="lo...
2016/09/23
[ "https://Stackoverflow.com/questions/39666183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6736217/" ]
Possibly you're trying to get elements that are created with a client sided script. I don't think javascript elements run when you just send a GET/POST request (which is what I'm assuming you mean by "view source").
At the time I was not aware how much content is loaded in through js after the page is loaded. Mechanize does not have a JavaScript interpreter. The way I ended up solving this is extracting the links from the \*.js file and redoing the get commend with urllib and getting the required content that way.
32,302,725
Hi there am new to OOP and python, I am currently trying to increment a User Id variable from a child Class, when I create an instance of the parent class using inheritance it doesn't seem to recognise the Id Variable from its parent class. Example here ``` class User: _ID = 0 def __init__(self, name): ...
2015/08/31
[ "https://Stackoverflow.com/questions/32302725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2374021/" ]
First, the way to get hold of the ListView itself is relatively easy. In an Activity subclass, you would do this: ``` ListView itemList = (ListView) findViewById(R.id.ItemList); ``` In your example above, the ArrayAdapter needs a layout id in it's constructor. This layout should contain a single TextView element (or...
Writing apps for Android is much more complicated than writing apps for Windows in vb6. You should really study basics and do some tutorials. Start [here!](http://developer.android.com/training/index.html) But for your question, to get access to xml control in your code, first you have to make object of that control, ...
32,302,725
Hi there am new to OOP and python, I am currently trying to increment a User Id variable from a child Class, when I create an instance of the parent class using inheritance it doesn't seem to recognise the Id Variable from its parent class. Example here ``` class User: _ID = 0 def __init__(self, name): ...
2015/08/31
[ "https://Stackoverflow.com/questions/32302725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2374021/" ]
You would have to use the findViewById() method which is inherited from the AppCompatActivity class. Then call the list views setAdapter method. ``` ListView listView = (ListView) findViewById(R.id.'the id-name of your list view'); listView.setAdapater(myAdapter); ``` The ArrayAdapter takes 3 parameters in to it...
Writing apps for Android is much more complicated than writing apps for Windows in vb6. You should really study basics and do some tutorials. Start [here!](http://developer.android.com/training/index.html) But for your question, to get access to xml control in your code, first you have to make object of that control, ...
32,302,725
Hi there am new to OOP and python, I am currently trying to increment a User Id variable from a child Class, when I create an instance of the parent class using inheritance it doesn't seem to recognise the Id Variable from its parent class. Example here ``` class User: _ID = 0 def __init__(self, name): ...
2015/08/31
[ "https://Stackoverflow.com/questions/32302725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2374021/" ]
First, the way to get hold of the ListView itself is relatively easy. In an Activity subclass, you would do this: ``` ListView itemList = (ListView) findViewById(R.id.ItemList); ``` In your example above, the ArrayAdapter needs a layout id in it's constructor. This layout should contain a single TextView element (or...
There is no syntactical similarities with VB6, In Android what happens is UI elements are created as object hierarchy in the memory. To get a particular object, we use findViewById method with id of that particular element as argument. You can get the List View. ``` ListView itemList = (ListView) findViewById(R.id.I...
32,302,725
Hi there am new to OOP and python, I am currently trying to increment a User Id variable from a child Class, when I create an instance of the parent class using inheritance it doesn't seem to recognise the Id Variable from its parent class. Example here ``` class User: _ID = 0 def __init__(self, name): ...
2015/08/31
[ "https://Stackoverflow.com/questions/32302725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2374021/" ]
You would have to use the findViewById() method which is inherited from the AppCompatActivity class. Then call the list views setAdapter method. ``` ListView listView = (ListView) findViewById(R.id.'the id-name of your list view'); listView.setAdapater(myAdapter); ``` The ArrayAdapter takes 3 parameters in to it...
There is no syntactical similarities with VB6, In Android what happens is UI elements are created as object hierarchy in the memory. To get a particular object, we use findViewById method with id of that particular element as argument. You can get the List View. ``` ListView itemList = (ListView) findViewById(R.id.I...
51,420,803
I have been trying to install `python-poppler-qt4` but it shows the error that `ModuleNotFoundError: No module name sipdistutils`. When I tried installing the `sipdistutils`, it again showed the error. **Error Message** [![enter image description here](https://i.stack.imgur.com/m6Pdk.png)](https://i.stack.imgur.com/...
2018/07/19
[ "https://Stackoverflow.com/questions/51420803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10104837/" ]
I have found a simillar issue here: <https://github.com/wbsoft/python-poppler-qt5/issues/14> I think that `sipdistutils` should be part of `sip` package. Please verify if you have it installed: ``` $ pip freeze | grep sip sip==4.19.1 ``` If there's no output install it with `pip install sip`. If this won't work so...
It is true that using `sipdistutils` for building python extensions is no longer the way to do things. So, the absolute fix is to modify the build procedure for the package but since I am not in control of that (though I may try to find time to contribute to the project) I did find a work-around. In our case, on Ubunt...
52,750,669
I want to create a new list (V) from other lists (a, b, c) and using a function, but I would like to take advantage of python and apply the function to the three lists and not element by element. For example, I have the lists a, b and c; and the result after apply the function should be V. Thanks. ``` def mag(a, b, ...
2018/10/11
[ "https://Stackoverflow.com/questions/52750669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8766822/" ]
You want to first zip the arguments, then map the function on the unpacked tuples: ``` from itertools import starmap starmap(mag, zip(a,b,c)) ``` See [here](https://ideone.com/uTNa5L) for an example.
What about using only built-in functions? Like [zip](https://docs.python.org/3.3/library/functions.html#zip) ``` >>> [mag(a_, b_, c_) for a_,b_,c_ in zip(a, b, c)] [10, 78, 30] ``` Plus another python buit-in function, [map](https://docs.python.org/3.3/library/functions.html#map) which returns an iterator and thus m...
52,750,669
I want to create a new list (V) from other lists (a, b, c) and using a function, but I would like to take advantage of python and apply the function to the three lists and not element by element. For example, I have the lists a, b and c; and the result after apply the function should be V. Thanks. ``` def mag(a, b, ...
2018/10/11
[ "https://Stackoverflow.com/questions/52750669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8766822/" ]
You can easily do this with the `map` function: ``` V = list(map(mag, a, b, c)) ```
What about using only built-in functions? Like [zip](https://docs.python.org/3.3/library/functions.html#zip) ``` >>> [mag(a_, b_, c_) for a_,b_,c_ in zip(a, b, c)] [10, 78, 30] ``` Plus another python buit-in function, [map](https://docs.python.org/3.3/library/functions.html#map) which returns an iterator and thus m...
52,750,669
I want to create a new list (V) from other lists (a, b, c) and using a function, but I would like to take advantage of python and apply the function to the three lists and not element by element. For example, I have the lists a, b and c; and the result after apply the function should be V. Thanks. ``` def mag(a, b, ...
2018/10/11
[ "https://Stackoverflow.com/questions/52750669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8766822/" ]
You can easily do this with the `map` function: ``` V = list(map(mag, a, b, c)) ```
You want to first zip the arguments, then map the function on the unpacked tuples: ``` from itertools import starmap starmap(mag, zip(a,b,c)) ``` See [here](https://ideone.com/uTNa5L) for an example.
52,750,669
I want to create a new list (V) from other lists (a, b, c) and using a function, but I would like to take advantage of python and apply the function to the three lists and not element by element. For example, I have the lists a, b and c; and the result after apply the function should be V. Thanks. ``` def mag(a, b, ...
2018/10/11
[ "https://Stackoverflow.com/questions/52750669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8766822/" ]
You want to first zip the arguments, then map the function on the unpacked tuples: ``` from itertools import starmap starmap(mag, zip(a,b,c)) ``` See [here](https://ideone.com/uTNa5L) for an example.
An alternate solution is to use `map` and `lambda` ``` In [16]: list(map(lambda p: mag(*p), zip(a, b, c))) Out[16]: [10, 78, 30] ```
52,750,669
I want to create a new list (V) from other lists (a, b, c) and using a function, but I would like to take advantage of python and apply the function to the three lists and not element by element. For example, I have the lists a, b and c; and the result after apply the function should be V. Thanks. ``` def mag(a, b, ...
2018/10/11
[ "https://Stackoverflow.com/questions/52750669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8766822/" ]
You can easily do this with the `map` function: ``` V = list(map(mag, a, b, c)) ```
An alternate solution is to use `map` and `lambda` ``` In [16]: list(map(lambda p: mag(*p), zip(a, b, c))) Out[16]: [10, 78, 30] ```
12,246,908
What is my requirement ? --> I need Exception notifier which will email to some specific configured user, about any sort of exception occurring in plain python app and web.py. I want something similar to this <http://matharvard.ca/posts/2011/jul/31/exception-notification-for-rails-3/> Is there anything same sort pre...
2012/09/03
[ "https://Stackoverflow.com/questions/12246908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486565/" ]
You can get what you want by: * Wrapping your code in `try..except` clause. * Using `logging` module to log the exceptions with a certain level of severity e.g `ERROR`. * Setting an `SMTPHandler` for exceptions of and above certain level. This way is quite flexible. Your messages can be send to several places (like l...
You can overwrite the `excepthook` function from the [`sys`](http://docs.python.org/library/sys.html#sys.excepthook) module, and handle any uncought exceptions there.
12,246,908
What is my requirement ? --> I need Exception notifier which will email to some specific configured user, about any sort of exception occurring in plain python app and web.py. I want something similar to this <http://matharvard.ca/posts/2011/jul/31/exception-notification-for-rails-3/> Is there anything same sort pre...
2012/09/03
[ "https://Stackoverflow.com/questions/12246908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486565/" ]
If you are not using any python heavy weight framework, try: <https://github.com/fossilet/exception-notifier> , it seems to be similar to the Rails' Exception notification, but quite simple. If you are using django, seems you can use its built-in feature:<https://docs.djangoproject.com/en/dev/howto/error-reporting/> ...
You can overwrite the `excepthook` function from the [`sys`](http://docs.python.org/library/sys.html#sys.excepthook) module, and handle any uncought exceptions there.
12,246,908
What is my requirement ? --> I need Exception notifier which will email to some specific configured user, about any sort of exception occurring in plain python app and web.py. I want something similar to this <http://matharvard.ca/posts/2011/jul/31/exception-notification-for-rails-3/> Is there anything same sort pre...
2012/09/03
[ "https://Stackoverflow.com/questions/12246908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486565/" ]
You can get what you want by: * Wrapping your code in `try..except` clause. * Using `logging` module to log the exceptions with a certain level of severity e.g `ERROR`. * Setting an `SMTPHandler` for exceptions of and above certain level. This way is quite flexible. Your messages can be send to several places (like l...
I have the same requirement with you. I write [a simple module](https://github.com/fossilet/exception-notifier) to mail uncaught exceptions to the developers, as well as to record them to log files. It is used in our teams' cron scripts written in Python. Hope it can be useful for you too.
12,246,908
What is my requirement ? --> I need Exception notifier which will email to some specific configured user, about any sort of exception occurring in plain python app and web.py. I want something similar to this <http://matharvard.ca/posts/2011/jul/31/exception-notification-for-rails-3/> Is there anything same sort pre...
2012/09/03
[ "https://Stackoverflow.com/questions/12246908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486565/" ]
If you are not using any python heavy weight framework, try: <https://github.com/fossilet/exception-notifier> , it seems to be similar to the Rails' Exception notification, but quite simple. If you are using django, seems you can use its built-in feature:<https://docs.djangoproject.com/en/dev/howto/error-reporting/> ...
I have the same requirement with you. I write [a simple module](https://github.com/fossilet/exception-notifier) to mail uncaught exceptions to the developers, as well as to record them to log files. It is used in our teams' cron scripts written in Python. Hope it can be useful for you too.
3,027,394
what does the '~' mean in python? i found this BF interpreter in python a while ago. ``` import sys #c,i,r,p=0,0,[0]*255,raw_input() c=0 i=0 p=raw_input() r=[0]*255 while c<len(p): m,n,u=p[c],0,r[i] if m==">":i+=1 if m=="<":i-=1 if m=="+":r[i]+=1 if m=="-":r[i]-=1 if m==".":sys.stdo...
2010/06/12
[ "https://Stackoverflow.com/questions/3027394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365060/" ]
Bitwise NOT, just like in C. In two's complement representation, `~n` is equivalent to `-n - 1`.
`~` is bitwise-not. I can't really think of a good way to illustrate it (unless you know that `-1` is the bitwise negation of `0`), but [the wikipedia entry](http://en.wikipedia.org/wiki/Bitwise_NOT#NOT) is pretty good.
3,027,394
what does the '~' mean in python? i found this BF interpreter in python a while ago. ``` import sys #c,i,r,p=0,0,[0]*255,raw_input() c=0 i=0 p=raw_input() r=[0]*255 while c<len(p): m,n,u=p[c],0,r[i] if m==">":i+=1 if m=="<":i-=1 if m=="+":r[i]+=1 if m=="-":r[i]-=1 if m==".":sys.stdo...
2010/06/12
[ "https://Stackoverflow.com/questions/3027394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365060/" ]
In this particular context, just replace '~' with 'not'. PS. ok i guess i will have to explain - started getting slapped with -1's, probably on the premise i don't know the difference between logical and bitwise negation. The thing is, the code in the question is **broken**. There is a bug in it. If you check how B...
`~` is bitwise-not. I can't really think of a good way to illustrate it (unless you know that `-1` is the bitwise negation of `0`), but [the wikipedia entry](http://en.wikipedia.org/wiki/Bitwise_NOT#NOT) is pretty good.
3,027,394
what does the '~' mean in python? i found this BF interpreter in python a while ago. ``` import sys #c,i,r,p=0,0,[0]*255,raw_input() c=0 i=0 p=raw_input() r=[0]*255 while c<len(p): m,n,u=p[c],0,r[i] if m==">":i+=1 if m=="<":i-=1 if m=="+":r[i]+=1 if m=="-":r[i]-=1 if m==".":sys.stdo...
2010/06/12
[ "https://Stackoverflow.com/questions/3027394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365060/" ]
Bitwise NOT, just like in C. In two's complement representation, `~n` is equivalent to `-n - 1`.
And to bring up one thing none of the other answers mentioned: the behavior of `~` for user-defined classes can be changed by overriding the `__invert__` method (or the `nb_invert` slot if you're using the Python/C API).
3,027,394
what does the '~' mean in python? i found this BF interpreter in python a while ago. ``` import sys #c,i,r,p=0,0,[0]*255,raw_input() c=0 i=0 p=raw_input() r=[0]*255 while c<len(p): m,n,u=p[c],0,r[i] if m==">":i+=1 if m=="<":i-=1 if m=="+":r[i]+=1 if m=="-":r[i]-=1 if m==".":sys.stdo...
2010/06/12
[ "https://Stackoverflow.com/questions/3027394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365060/" ]
In this particular context, just replace '~' with 'not'. PS. ok i guess i will have to explain - started getting slapped with -1's, probably on the premise i don't know the difference between logical and bitwise negation. The thing is, the code in the question is **broken**. There is a bug in it. If you check how B...
And to bring up one thing none of the other answers mentioned: the behavior of `~` for user-defined classes can be changed by overriding the `__invert__` method (or the `nb_invert` slot if you're using the Python/C API).
67,183,501
``` import os import numpy as np from scipy.signal import * import csv import matplotlib.pyplot as plt from scipy import signal from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds from brainflow.data_filter import DataFilter, FilterTypes, AggOperations, WindowFunctions, DetrendOperati...
2021/04/20
[ "https://Stackoverflow.com/questions/67183501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15708550/" ]
Here's a simple case that produces your error message: ``` In [19]: np.asarray([[1,2,3],[4,5]],float) Traceback (most recent call last): File "<ipython-input-19-72fd80bc7856>", line 1, in <module> np.asarray([[1,2,3],[4,5]],float) File "/usr/local/lib/python3.8/dist-packages/numpy/core/_asarray.py", line 102, ...
I was getting the same error. I was opening a txt file that contains a table of values, and saving it into a NumPy array defining the dtype as float since otherwise, the numbers would be strings. ``` with open(dirfile) as fh: next(fh) header = next(fh)[2:] next(fh) data = np.array([line.strip().split()...
67,183,501
``` import os import numpy as np from scipy.signal import * import csv import matplotlib.pyplot as plt from scipy import signal from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds from brainflow.data_filter import DataFilter, FilterTypes, AggOperations, WindowFunctions, DetrendOperati...
2021/04/20
[ "https://Stackoverflow.com/questions/67183501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15708550/" ]
Here's a simple case that produces your error message: ``` In [19]: np.asarray([[1,2,3],[4,5]],float) Traceback (most recent call last): File "<ipython-input-19-72fd80bc7856>", line 1, in <module> np.asarray([[1,2,3],[4,5]],float) File "/usr/local/lib/python3.8/dist-packages/numpy/core/_asarray.py", line 102, ...
[1, np.array[0,1,2], 3, np.array[8,9,10]] you might have an issue like this. simple thing you can do is: Put the break point where the error is arising -- > run the IDE in debug mode --> print the particular variable or line --> avoid this array within array scenario and it will work ! (It worked for me, hope it works...
67,183,501
``` import os import numpy as np from scipy.signal import * import csv import matplotlib.pyplot as plt from scipy import signal from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds from brainflow.data_filter import DataFilter, FilterTypes, AggOperations, WindowFunctions, DetrendOperati...
2021/04/20
[ "https://Stackoverflow.com/questions/67183501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15708550/" ]
I was getting the same error. I was opening a txt file that contains a table of values, and saving it into a NumPy array defining the dtype as float since otherwise, the numbers would be strings. ``` with open(dirfile) as fh: next(fh) header = next(fh)[2:] next(fh) data = np.array([line.strip().split()...
[1, np.array[0,1,2], 3, np.array[8,9,10]] you might have an issue like this. simple thing you can do is: Put the break point where the error is arising -- > run the IDE in debug mode --> print the particular variable or line --> avoid this array within array scenario and it will work ! (It worked for me, hope it works...
68,654,663
I'm trying to aggregate my data by getting the sum every 30 seconds. I would like to know if the result of this aggregation is zero, this will happen if there are no rows in that 30s region. Here's a minimal working example illustrating the result I would like with pandas, and where it falls short with pyspark. Input...
2021/08/04
[ "https://Stackoverflow.com/questions/68654663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2550114/" ]
The HTML5 specification now has a whole section on [Button Layout](https://html.spec.whatwg.org/multipage/rendering.html#button-layout) Sometimes it's treated like a replaced element, and sometimes like an inline-block element. But it's never treated as a non-replaced inline element. In detail, it says that: > > Bu...
If you want more clarification...it seems that the **button element is a replaced element** in most modern browsers today and in the past, which means no matter how you style it, even after changing the default UA browser styles, it still retains width and height characteristics regardless of display properties. It the...
43,934,830
According to [PythonCentral](http://pythoncentral.io/pyside-pyqt-tutorial-qwebview/) : > > QWebView ... allows you to display web pages from URLs, arbitrary HTML, *XML with XSLT stylesheets*, web pages constructed as QWebPages, and other data whose MIME types it knows how to interpret > > > However, the xml conte...
2017/05/12
[ "https://Stackoverflow.com/questions/43934830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/508402/" ]
Try converting to NSData then storing to nsuserdefaults like below ``` func saveListIdArray(_ params: NSMutableArray = []) { let data = NSKeyedArchiver.archivedData(withRootObject: params) UserDefaults.standard.set(data, forKey: "test") UserDefaults.standard.synchronize() } ``` For retrieving the data use ``` if ...
You are force unwrapping the NSMutableArray for a key. Don't force unwrap when you try to get the value from a dictionary or UserDefault for a key because there may be a chance that the value does not exist for that key and force unwrapping will crash your app. Do this as: ``` //to get array from user default if ...
43,934,830
According to [PythonCentral](http://pythoncentral.io/pyside-pyqt-tutorial-qwebview/) : > > QWebView ... allows you to display web pages from URLs, arbitrary HTML, *XML with XSLT stylesheets*, web pages constructed as QWebPages, and other data whose MIME types it knows how to interpret > > > However, the xml conte...
2017/05/12
[ "https://Stackoverflow.com/questions/43934830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/508402/" ]
Try converting to NSData then storing to nsuserdefaults like below ``` func saveListIdArray(_ params: NSMutableArray = []) { let data = NSKeyedArchiver.archivedData(withRootObject: params) UserDefaults.standard.set(data, forKey: "test") UserDefaults.standard.synchronize() } ``` For retrieving the data use ``` if ...
I have 2 possible reasons for this: 1. You need to be 100% sure that you are retrieving array with the same key as you save it with. In your code you are saving the array with "ArrayKey" but retrieving it with NSUserDefaultsKey.LIST\_ID\_ARRAY, are you sure this is the same string? 2. What datatype is self.listId? If ...
39,010,366
While executing the code below, I'm getting `AttributeError: attribute '__doc__' of 'type' objects is not writable`. ``` from functools import wraps def memoize(f): """ Memoization decorator for functions taking one or more arguments. Saves repeated api calls for a given value, by caching it. """ ...
2016/08/18
[ "https://Stackoverflow.com/questions/39010366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2264738/" ]
`@wraps(f)` is primarily designed to be used as a *function* decorator, rather than as a class decorator, so using it as the latter may lead to the occasional odd quirk. The specific error message you're receiving relates to a limitation of builtin types on Python 2: ``` >>> class C(object): pass ... >>> C.__doc__ =...
The `wraps` decorator you're trying to apply to your class doesn't work because you can't modify the docstring of a class after it has been created. You can recreate the error with this code: ``` class Foo(object): """inital docstring""" Foo.__doc__ = """new docstring""" # raises an exception in Python 2 ``` Th...
39,010,366
While executing the code below, I'm getting `AttributeError: attribute '__doc__' of 'type' objects is not writable`. ``` from functools import wraps def memoize(f): """ Memoization decorator for functions taking one or more arguments. Saves repeated api calls for a given value, by caching it. """ ...
2016/08/18
[ "https://Stackoverflow.com/questions/39010366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2264738/" ]
`functools.wraps()` was designed to wrap function, not class objects. One of the things it does is attempt to assign the `__doc__` string of the wrapped (original) function to the wrapper function, which, as you've discovered, isn't allowed in Python 2. It also does the same for the `__name__` and `__module__` attribut...
The `wraps` decorator you're trying to apply to your class doesn't work because you can't modify the docstring of a class after it has been created. You can recreate the error with this code: ``` class Foo(object): """inital docstring""" Foo.__doc__ = """new docstring""" # raises an exception in Python 2 ``` Th...
65,460,702
I am having an issue with my personal project, my python skills are pretty basic but any help would be greatly appreciated Question: TASK 1 To simulate the monitoring required, write a routine that allows entry of the babyโ€™s temperature in degrees Celsius. The routine should check whether the temperature is within the...
2020/12/26
[ "https://Stackoverflow.com/questions/65460702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14861692/" ]
According to the discord.py docs [bot.run()](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.run) is "A blocking call that abstracts away the event loop initialisation from you." and further they said if we want more control over the loop we could use start() coroutine instead of run(). So now we sho...
You are not returning anything from your `send_message` function. Something like this should do good. ```py @app.post("/items/") async def create_item(item: Item): msg = await send_message() return msg async def send_message(): user = await bot.fetch_user(USER_ID) return await user.send('') ```
65,460,702
I am having an issue with my personal project, my python skills are pretty basic but any help would be greatly appreciated Question: TASK 1 To simulate the monitoring required, write a routine that allows entry of the babyโ€™s temperature in degrees Celsius. The routine should check whether the temperature is within the...
2020/12/26
[ "https://Stackoverflow.com/questions/65460702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14861692/" ]
According to the discord.py docs [bot.run()](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.run) is "A blocking call that abstracts away the event loop initialisation from you." and further they said if we want more control over the loop we could use start() coroutine instead of run(). So now we sho...
Code `bot.run(...)` runs all time and it blocks next line which starts API. You would have to run one of them in separated thread or process. I tried to run `bot` in `thread` ``` if __name__ == "__main__": import threading print('Starting bot') t = threading.Thread(target=bot.start, args=(TOKEN,)) t...
57,445,907
I want to detect malicious sites using python. Now, I've tried using `requests` module to get the contents of a website, then would search for `malicious words` in it. But, I didn't get it to work. [![here example images of red page](https://i.stack.imgur.com/f3vOj.png)](https://i.stack.imgur.com/f3vOj.png) this my ...
2019/08/10
[ "https://Stackoverflow.com/questions/57445907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675882/" ]
It doesn't work because you're using the `requests` library wrong. In your code, you essentially only get the HTML of the virus site (line of code: `req_check = requests.get(url, verify=False)` and `if 'example for detect ' in req_check.content:`{source: <https://pastebin.com/6x24SN6v>}) In Chrome, the browser runs ...
Tell the user to enter a website, then use selenium or something to upload the url to virustotal.com
57,445,907
I want to detect malicious sites using python. Now, I've tried using `requests` module to get the contents of a website, then would search for `malicious words` in it. But, I didn't get it to work. [![here example images of red page](https://i.stack.imgur.com/f3vOj.png)](https://i.stack.imgur.com/f3vOj.png) this my ...
2019/08/10
[ "https://Stackoverflow.com/questions/57445907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675882/" ]
It doesn't work because you're using the `requests` library wrong. In your code, you essentially only get the HTML of the virus site (line of code: `req_check = requests.get(url, verify=False)` and `if 'example for detect ' in req_check.content:`{source: <https://pastebin.com/6x24SN6v>}) In Chrome, the browser runs ...
I would comment that your indentation might be messed where there is other code. Otherwise, it should work flawlessly. Edit 2 ------ It appeared that OP was after a way to detect malicious sites in python. This is a documentation from [totalvirus](https://developers.virustotal.com/reference#url-scan) explaining how t...
54,806,005
I have a list of dictionaries that looks something like this-> ``` list = [{"id":1,"path":"a/b", ........}, {"id":2,"path":"a/b/c", ........}, {"id":3,"path":"a/b/c/d", ........}] ``` Now I want to create a dict of path to id mapping. That should look something like this-> ``` d=dict() ...
2019/02/21
[ "https://Stackoverflow.com/questions/54806005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9593015/" ]
Make outer div `fixed` then inner 4 div element will show next to each other. ```css .groups { display: flex; display: -webkit-flex; position: fixed; margin: 0 auto; left: 0; right: 0; justify-content: space-around; max-width: 500px; } .g{ height: 70px; ...
Otherwise you can do it with flex: ```css .g{ height: 70px; width: 70px; background-color: black; margin: 5px; } .groups { display: flex; justify-content: space-between; width: 400px } ``` ```html <div class="groups"> <div class="g g1"></div> <div class="g g2"></div> <div class="g g3"...
54,806,005
I have a list of dictionaries that looks something like this-> ``` list = [{"id":1,"path":"a/b", ........}, {"id":2,"path":"a/b/c", ........}, {"id":3,"path":"a/b/c/d", ........}] ``` Now I want to create a dict of path to id mapping. That should look something like this-> ``` d=dict() ...
2019/02/21
[ "https://Stackoverflow.com/questions/54806005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9593015/" ]
Make outer div `fixed` then inner 4 div element will show next to each other. ```css .groups { display: flex; display: -webkit-flex; position: fixed; margin: 0 auto; left: 0; right: 0; justify-content: space-around; max-width: 500px; } .g{ height: 70px; ...
Try this fiddle [Fiddle here](https://jsfiddle.net/c1kjmsxv/) ``` .groups{ position: fixed; bottom: 15%; display:flex; justify-content:center; width:100%; } .g{ height: 70px; width: 70px; background-color: black; margin: 5px; } ```
54,806,005
I have a list of dictionaries that looks something like this-> ``` list = [{"id":1,"path":"a/b", ........}, {"id":2,"path":"a/b/c", ........}, {"id":3,"path":"a/b/c/d", ........}] ``` Now I want to create a dict of path to id mapping. That should look something like this-> ``` d=dict() ...
2019/02/21
[ "https://Stackoverflow.com/questions/54806005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9593015/" ]
Make outer div `fixed` then inner 4 div element will show next to each other. ```css .groups { display: flex; display: -webkit-flex; position: fixed; margin: 0 auto; left: 0; right: 0; justify-content: space-around; max-width: 500px; } .g{ height: 70px; ...
Just add `float:left;` to the css class .g Of course you MUST remove `position: fixed;` You can also use `position: fixed;` but you must provide different values for position for each div. ``` <div class="groups"> <div class="g g1"></div> <div class="g g2"></div> <div class="g g3"></div> <div class="g g4"></di...
54,806,005
I have a list of dictionaries that looks something like this-> ``` list = [{"id":1,"path":"a/b", ........}, {"id":2,"path":"a/b/c", ........}, {"id":3,"path":"a/b/c/d", ........}] ``` Now I want to create a dict of path to id mapping. That should look something like this-> ``` d=dict() ...
2019/02/21
[ "https://Stackoverflow.com/questions/54806005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9593015/" ]
Make outer div `fixed` then inner 4 div element will show next to each other. ```css .groups { display: flex; display: -webkit-flex; position: fixed; margin: 0 auto; left: 0; right: 0; justify-content: space-around; max-width: 500px; } .g{ height: 70px; ...
As position is fixed, you may need to sepcify the positions of class g1, g2 and g3 like below. ``` .g1{ left: 0px; } .g2{ left: 100px; } .g3{ left: 200px; } ```
29,704,139
I am trying to apply `_pickle` to save data onto disk. But when calling `_pickle.dump`, I got an error ``` OverflowError: cannot serialize a bytes object larger than 4 GiB ``` Is this a hard limitation to use `_pickle`? (`cPickle` for python2)
2015/04/17
[ "https://Stackoverflow.com/questions/29704139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2880978/" ]
Not anymore in Python 3.4 which has PEP 3154 and Pickle 4.0 <https://www.python.org/dev/peps/pep-3154/> But you need to say you want to use version 4 of the protocol: <https://docs.python.org/3/library/pickle.html> ``` pickle.dump(d, open("file", 'w'), protocol=4) ```
Yes, this is a hard-coded limit; from [`save_bytes` function](https://hg.python.org/cpython/file/2d8e4047c270/Modules/_pickle.c#l1958): ```c else if (size <= 0xffffffffL) { // ... } else { PyErr_SetString(PyExc_OverflowError, "cannot serialize a bytes object larger than 4 GiB"); return ...
29,704,139
I am trying to apply `_pickle` to save data onto disk. But when calling `_pickle.dump`, I got an error ``` OverflowError: cannot serialize a bytes object larger than 4 GiB ``` Is this a hard limitation to use `_pickle`? (`cPickle` for python2)
2015/04/17
[ "https://Stackoverflow.com/questions/29704139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2880978/" ]
Yes, this is a hard-coded limit; from [`save_bytes` function](https://hg.python.org/cpython/file/2d8e4047c270/Modules/_pickle.c#l1958): ```c else if (size <= 0xffffffffL) { // ... } else { PyErr_SetString(PyExc_OverflowError, "cannot serialize a bytes object larger than 4 GiB"); return ...
There is a great answers above for why pickle doesn't work. But it still doesn't work for Python 2.7, which is a problem if you are are still at Python 2.7 and want to support large files, especially NumPy (NumPy arrays over 4G fail). You can use OC serialization, which has been updated to work for data over 4Gig. The...
29,704,139
I am trying to apply `_pickle` to save data onto disk. But when calling `_pickle.dump`, I got an error ``` OverflowError: cannot serialize a bytes object larger than 4 GiB ``` Is this a hard limitation to use `_pickle`? (`cPickle` for python2)
2015/04/17
[ "https://Stackoverflow.com/questions/29704139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2880978/" ]
Not anymore in Python 3.4 which has PEP 3154 and Pickle 4.0 <https://www.python.org/dev/peps/pep-3154/> But you need to say you want to use version 4 of the protocol: <https://docs.python.org/3/library/pickle.html> ``` pickle.dump(d, open("file", 'w'), protocol=4) ```
There is a great answers above for why pickle doesn't work. But it still doesn't work for Python 2.7, which is a problem if you are are still at Python 2.7 and want to support large files, especially NumPy (NumPy arrays over 4G fail). You can use OC serialization, which has been updated to work for data over 4Gig. The...
53,012,388
When I do `python -mzeep https://testingapi.ercot.com/2007-08/Nodal/eEDS/EWS/?WSDL` the operations are blank. When I pull that up in a browser I can find many things under an `<operation>` tag. What am I missing? I'm not sure if this is relevant but I hate to exclude this info if it is. The site has a zip file of XS...
2018/10/26
[ "https://Stackoverflow.com/questions/53012388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1818713/" ]
> > I actually don't need those serialized into the JSON file > > > In JSON.NET there is a `[JsonIgnore]` attribute that you can decorate properties with. Related: [Newtonsoft ignore attributes?](https://stackoverflow.com/questions/6309725/newtonsoft-ignore-attributes)
To serialize and write it to a file, just do this: ``` string json = JsonConvert.SerializeObject(theme); System.IO.File.WriteAllText("yourfile.json", json); ```
53,356,449
I'm having trouble carrying out what I think should be a pretty straightforward task on a NIDAQ usb6002: I have a low frequency sine wave that I'm measuring at an analog input channel, and when it crosses zero I would like to light an LED for 1 second. I'm trying to use the nidaqmx Python API, but haven't been able to ...
2018/11/17
[ "https://Stackoverflow.com/questions/53356449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10397841/" ]
In short: Web worksers do not ignore messages even if the web worker thread is blocked. All browsers events, including web worker `postMessage()`/`onmessage()` events are queued. This is the fundamental philosophy of JavaScript (`onmessage()` is done in JS even if you use WebAssembly). Have a look at ["Concurrency mod...
Considering you are targeting recent browsers (WebAssembly), you can most likely rely on SharedArrayBuffer and Atomics. Have a look at these solutions [Is it possible to pause/resume a web worker externally?](https://stackoverflow.com/questions/57701464/is-it-possible-to-pause-resume-a-web-worker-externally/71888014#71...
30,019,283
I was wondering how to parse the CURL JSON output from the server into variables. Currently, I have - ``` curl -X POST -H "Content: agent-type: application/x-www-form-urlencoded" https://www.toontownrewritten.com/api/login?format=json -d username="$USERNAME" -d password="$PASSWORD" | python -m json.tool ``` But it ...
2015/05/03
[ "https://Stackoverflow.com/questions/30019283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3152204/" ]
Find and install `jq` (<https://stedolan.github.io/jq/>). `jq` is a JSON parser. JSON is not reliably parsed by line-oriented tools like `sed` because, like XML, JSON is not a line-oriented data format. In terms of your question: ``` source <( curl -X POST -H "$content_type" "$url" -d username="$USERNAME" -d pass...
Here's an example of [Extract a JSON value from a BASH script](https://gist.github.com/cjus/1047794) ``` #!/bin/bash function jsonval { temp=`echo $json | sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's...
30,019,283
I was wondering how to parse the CURL JSON output from the server into variables. Currently, I have - ``` curl -X POST -H "Content: agent-type: application/x-www-form-urlencoded" https://www.toontownrewritten.com/api/login?format=json -d username="$USERNAME" -d password="$PASSWORD" | python -m json.tool ``` But it ...
2015/05/03
[ "https://Stackoverflow.com/questions/30019283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3152204/" ]
Find and install `jq` (<https://stedolan.github.io/jq/>). `jq` is a JSON parser. JSON is not reliably parsed by line-oriented tools like `sed` because, like XML, JSON is not a line-oriented data format. In terms of your question: ``` source <( curl -X POST -H "$content_type" "$url" -d username="$USERNAME" -d pass...
You could use perl module on command line: 1st, ensure they is installed, under debian based, you could ``` sudo apt-get install libjson-xs-perl ``` But for other OS, you could install perl modules via [CPAN (the *Comprehensive Perl Archive Network*)](http://www.cpan.org/modules/INSTALL.html): ``` cpan App::cpanmi...
13,774,443
I'm making a request in python to a web service which returns AMF. I don't know if it's AMF0 or AMF3 yet. ``` r = requests.post(url, data=data) >>> r.text u'\x00\x03...' ``` ([Full data here](http://pastebin.com/sdZnU8Ds)) How can I take `r.text` and convert it to a python object or similar? I found [amfast](http:/...
2012/12/08
[ "https://Stackoverflow.com/questions/13774443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246265/" ]
**EDIT:** I had calculated some of my probabilities wrongly. Also I've now mentioned that we need to randomly pick 2 distinct inputs for the function f in order to guarantee that, if f is balanced, then we know the probabilities of seeing the various possible outcomes. The fact that the prior probability of the functi...
Look at the probabilities for the different types of functions to return different results for two given values: ``` constant 0,0 50% constant 1,1 50% balanced 0,0 4/8 * 3/7 = 21,4% balanced 0,1 4/8 * 4/7 = 28.6% balanced 1,0 4/8 * 4/7 = 28.6% balanced 1,1 4/8 * 3/7 = 21.4% ``` If the results are 0,0 or ...
17,081,363
I'm trying to convert C++ code to python but I'm stuck original C++ code ``` int main(void) { int levels = 40; int xp_for_first_level = 1000; int xp_for_last_level = 1000000; double B = log((double)xp_for_last_level / xp_for_first_level) / (levels - 1); double A = (double)xp_for_first_level / (ex...
2013/06/13
[ "https://Stackoverflow.com/questions/17081363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1934748/" ]
Change the `print` line to: ``` print("%i %i" % (i, new_xp - old_xp)) ``` Refer to this [list of allowed type conversion specifiers](http://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting) for more informations. Or use the new [format](http://docs.python.org/3/library/functions.html#format) m...
Depending on the version of python you are using, the cast to double in the C++ code ``` (double)xp_for_last_level / xp_for_first_level ``` might need to be taken into account in the python code. In python 3 you will get a float, in older python you can do ``` from __future__ import division ``` then `xp_for_last...
17,081,363
I'm trying to convert C++ code to python but I'm stuck original C++ code ``` int main(void) { int levels = 40; int xp_for_first_level = 1000; int xp_for_last_level = 1000000; double B = log((double)xp_for_last_level / xp_for_first_level) / (levels - 1); double A = (double)xp_for_first_level / (ex...
2013/06/13
[ "https://Stackoverflow.com/questions/17081363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1934748/" ]
For the last line, you can simply use: ``` print(i, new_xp - old_xp) ``` As @pfnuesel commented, you will need to adjust the range of your for loop slightly. Finally, you don't need `import math`. You can replace the first 3 lines with: ``` from math import log, exp ```
Depending on the version of python you are using, the cast to double in the C++ code ``` (double)xp_for_last_level / xp_for_first_level ``` might need to be taken into account in the python code. In python 3 you will get a float, in older python you can do ``` from __future__ import division ``` then `xp_for_last...
57,169,697
When I use the PIL.ImageTk library to load a png to my GUI and use logging to log some events, it creates some unwanted logs in DEBUG mode. I have tried changing the `level` of `logging` to `INFO` or `WARNING` (or higher). But that does not help: ``` logging.basicConfig(filename='mylog.log', filemode='a', format='%(a...
2019/07/23
[ "https://Stackoverflow.com/questions/57169697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2365866/" ]
Problem is because module already created root logger and now `basicConfig` uses this logger but it can't change level for existing logger. Doc: [basicConfig](https://docs.python.org/3/library/logging.html#logging.basicConfig) > > This function does nothing if the root logger already has handlers configured for it. ...
Instead Of Using: ``` ... level=logging.DEBUG ... ``` Use: ``` ... level=logging.INFO ... ``` And Your File Will Be: > > DD/MM/YYYY HH:MM:SS PM INFO: This is a test log... > > >
57,169,697
When I use the PIL.ImageTk library to load a png to my GUI and use logging to log some events, it creates some unwanted logs in DEBUG mode. I have tried changing the `level` of `logging` to `INFO` or `WARNING` (or higher). But that does not help: ``` logging.basicConfig(filename='mylog.log', filemode='a', format='%(a...
2019/07/23
[ "https://Stackoverflow.com/questions/57169697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2365866/" ]
Add: ``` pil_logger = logging.getLogger('PIL') pil_logger.setLevel(logging.INFO) ``` (source: <https://github.com/camptocamp/pytest-odoo/issues/15#issuecomment-559203242>)
Problem is because module already created root logger and now `basicConfig` uses this logger but it can't change level for existing logger. Doc: [basicConfig](https://docs.python.org/3/library/logging.html#logging.basicConfig) > > This function does nothing if the root logger already has handlers configured for it. ...
57,169,697
When I use the PIL.ImageTk library to load a png to my GUI and use logging to log some events, it creates some unwanted logs in DEBUG mode. I have tried changing the `level` of `logging` to `INFO` or `WARNING` (or higher). But that does not help: ``` logging.basicConfig(filename='mylog.log', filemode='a', format='%(a...
2019/07/23
[ "https://Stackoverflow.com/questions/57169697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2365866/" ]
Add: ``` pil_logger = logging.getLogger('PIL') pil_logger.setLevel(logging.INFO) ``` (source: <https://github.com/camptocamp/pytest-odoo/issues/15#issuecomment-559203242>)
Instead Of Using: ``` ... level=logging.DEBUG ... ``` Use: ``` ... level=logging.INFO ... ``` And Your File Will Be: > > DD/MM/YYYY HH:MM:SS PM INFO: This is a test log... > > >
60,414,356
I have a GUI application made using PySide2 and it some major modules it uses are OpenVino(2019), dlib, OpenCV-contrib(4.2.x) and Postgres(psycopg2) and I am trying to freeze the application using PyInstaller (--debug is True). The program gets frozen without errors but during execution, I get the following error: ``...
2020/02/26
[ "https://Stackoverflow.com/questions/60414356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8243797/" ]
You changed the python version. So, you have to give a new path according to the Python version. Just remove all older version and the current one and reinstall new Python v.3.8.1
You need to include base\_library.zip in your application folder
41,923,890
I'm attempting to create a simple selection sort program in python without using any built in functions. My problem right now is my code is only sorting the first digit of the list. What's wrong? Here's my sort ``` def selectionsort(list1): for x in range(len(list1)): tiniest = minimum(list1) swap(t...
2017/01/29
[ "https://Stackoverflow.com/questions/41923890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6843896/" ]
Some simplification will make it more readable/comprehensible: ``` def swap(lst, i1, i2): lst[i1], lst[i2] = lst[i2], lst[i1] # easy-swapping by multi assignment def minimum(lst, s): # s: start index min_val, min_index = lst[s], s for i in range(s+1, len(lst)): if lst[i] < min_val: min_val, min_ind...
It seems `minimum` returns the value of the smallest element in `list1`, but your `swap` expects an index instead. Try making `minimum` return the index instead of the value of the smallest element.
74,101,582
I am calculating concentrations from a file that has separate Date and Time columns. I set the date and time columns as indexes as they are not suppose to change. However when I print the new dataframe it only prints the "date" one time like this: ``` 55... Date Time ...
2022/10/17
[ "https://Stackoverflow.com/questions/74101582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19096358/" ]
From the Pandas [to\_string() docs](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_string.html#pandas-dataframe-to-string). > > sparsify : bool, optional, default True > > Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row. > > > --- ``` print(co...
remove `inplace=True` and replace it with `reset_index()` at the end here is the code (first two lines) ``` df = pd.read_csv('csv2.txt',delimiter=r'\s+',engine = 'python') df.set_index(['Date', 'Time'] ).reset_index() # cannot do calculation step, as sample column is not present in the sample data ``` ``` Date ...
65,463,877
I've installed Spark and components locally and I'm able to execute PySpark code in Jupyter, iPython and via spark-submit - however receiving the following WARNING's: ``` WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/Users/ayu...
2020/12/27
[ "https://Stackoverflow.com/questions/65463877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9372996/" ]
Install Java 8 instead of Java 11, which is known to give this sort of warnings with Spark.
If you run your PySpark code often and you are tired (like me) of looking through all these warnings again and again before you see **your** output, bash/zsh process substitution comes to the rescue: ``` $ spark-3.0.1-bin-hadoop3.2/bin/spark-submit test.py 2> >(tail -n +8 >&2) | cat ``` Here we redirect STDERR of ou...
65,463,877
I've installed Spark and components locally and I'm able to execute PySpark code in Jupyter, iPython and via spark-submit - however receiving the following WARNING's: ``` WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/Users/ayu...
2020/12/27
[ "https://Stackoverflow.com/questions/65463877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9372996/" ]
Install Java 8 instead of Java 11, which is known to give this sort of warnings with Spark.
If you upgrade to the lastest JDBC driver, you won't see this warning with Java 11. I upgraded to org.postgresql:postgresql:42.3.3.
65,463,877
I've installed Spark and components locally and I'm able to execute PySpark code in Jupyter, iPython and via spark-submit - however receiving the following WARNING's: ``` WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/Users/ayu...
2020/12/27
[ "https://Stackoverflow.com/questions/65463877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9372996/" ]
If you run your PySpark code often and you are tired (like me) of looking through all these warnings again and again before you see **your** output, bash/zsh process substitution comes to the rescue: ``` $ spark-3.0.1-bin-hadoop3.2/bin/spark-submit test.py 2> >(tail -n +8 >&2) | cat ``` Here we redirect STDERR of ou...
If you upgrade to the lastest JDBC driver, you won't see this warning with Java 11. I upgraded to org.postgresql:postgresql:42.3.3.
68,959,506
Lets say I have a CSV file that looks like this: ``` name,country,email john,US,[email protected] brad,UK,[email protected] James,US,[email protected] ``` I want to search for any county that equals US and if its exists, then print their email address. How would I do this in python without using pandas?
2021/08/27
[ "https://Stackoverflow.com/questions/68959506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12260632/" ]
You can do something like: ``` with open('file.csv', 'r') as f: f.readline() for line in f: data = line.strip().split(',') ``` Then you can access the stuff inside of `data` to get what you need.
So to read an CSV as dataframe you need: ``` import pandas as pd df = pd.read_csv("filename.csv") ``` Next, I will generate a dummy df and show you how to get the US users and then print their emails in a list: ``` df= pd.DataFrame({"Name":['jhon','brad','james'], "Country":['US','UK','US'], "email":['[email protected]...
64,167,192
I am a begginer programer in python and when i run this code ``` from PIL import Image im = Image.open(r'C:\\images\\imagetest.png') width, height = im.size print(width, height) im.show() ``` I get this error: ``` im = Image.open(r'C:\\images\\imagetest.png') File "C:\Users\danie\AppData\Local\Programs\Pytho...
2020/10/02
[ "https://Stackoverflow.com/questions/64167192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14378032/" ]
r strings don't need their backslashes escaped Remove the r before the string declaration or remove the double backslashes
The path of the image is not correct. You have to write it like that: im = Image.open(r'C:\images\imagetest.png')
64,167,192
I am a begginer programer in python and when i run this code ``` from PIL import Image im = Image.open(r'C:\\images\\imagetest.png') width, height = im.size print(width, height) im.show() ``` I get this error: ``` im = Image.open(r'C:\\images\\imagetest.png') File "C:\Users\danie\AppData\Local\Programs\Pytho...
2020/10/02
[ "https://Stackoverflow.com/questions/64167192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14378032/" ]
r strings don't need their backslashes escaped Remove the r before the string declaration or remove the double backslashes
As the error said, the path you gave is incorrect. this ``` im = Image.open(r'C:\\images\\imagetest.png') ``` have issues such as double "\" which is not the proper format. Sometimes you also have the give it the full path: Example of a path: ``` C:\Users\Hamza\Downloads\me.jpg ``` If you're not sure about the pa...
44,517,641
I want to connect to my database from Python shell ``` import MySQLdb db = MySQLdb.connect(host="localhost",user="milenko",passwd="********",db="classicmodels") ``` But ``` File "/home/milenko/anaconda3/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(...
2017/06/13
[ "https://Stackoverflow.com/questions/44517641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8006605/" ]
this generally means you do not have permissions to access the server from that particular machine. to fix it, either create user 'milenko'@'localhost' or 'milenko'@'%' using your root server user OR grant your user privileges on that particular db
Make sure your local server (e.g WampServer) is turned on.
56,576,470
I am confused about the runtime of the binary operator of the set in Python. e.g. - `set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa. I went through some websites but I am not able to find any clea...
2019/06/13
[ "https://Stackoverflow.com/questions/56576470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072927/" ]
I had the same problem. Following command worked for me: After the `./gradlew bundleRelease` command we get a *.aab* version of our app. To get APK, you should run the app with release version on any device with the below command. * Make sure you have connected an android device * For the production ready app, firstl...
step - 1) ./gradlew bundleRelease step - 2) react-native run-android --variant=release Make sure you have connected an android device For the production-ready app, firstly you have to remove the previous app from the device
56,576,470
I am confused about the runtime of the binary operator of the set in Python. e.g. - `set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa. I went through some websites but I am not able to find any clea...
2019/06/13
[ "https://Stackoverflow.com/questions/56576470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072927/" ]
I had the same problem. Following command worked for me: After the `./gradlew bundleRelease` command we get a *.aab* version of our app. To get APK, you should run the app with release version on any device with the below command. * Make sure you have connected an android device * For the production ready app, firstl...
Use `gradlew bundleRelease` to generate an app bundle (.aab file) and `gradlew assembleRelease` to generate an apk (.apk file). To install a release on your emulator, use `react-native run-android --variant=release`. I hope this helps
56,576,470
I am confused about the runtime of the binary operator of the set in Python. e.g. - `set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa. I went through some websites but I am not able to find any clea...
2019/06/13
[ "https://Stackoverflow.com/questions/56576470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072927/" ]
I made a file that called `build.sh`. When i want to release a new version of android in ReactNative, just type and press `sh ./build.sh` in terminal. My shell script in `build.sh` file: ``` npx jetify && cd android && ./gradlew clean && ./gradlew assembleRelease && ./gradlew bundleRelease && cd .. ```
The following should solve your issue: Open Android Studio and select "build bundle(s)" from Build/Build Bundle(s)/Apk(s) ![Refer this image](https://i.stack.imgur.com/7BO2U.png) Then, open your console and run ``` cd android && ./gradlew bundleRelease ``` from your project's root. You may encounter an error su...
56,576,470
I am confused about the runtime of the binary operator of the set in Python. e.g. - `set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa. I went through some websites but I am not able to find any clea...
2019/06/13
[ "https://Stackoverflow.com/questions/56576470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072927/" ]
I had the same problem. Following command worked for me: After the `./gradlew bundleRelease` command we get a *.aab* version of our app. To get APK, you should run the app with release version on any device with the below command. * Make sure you have connected an android device * For the production ready app, firstl...
I made a file that called `build.sh`. When i want to release a new version of android in ReactNative, just type and press `sh ./build.sh` in terminal. My shell script in `build.sh` file: ``` npx jetify && cd android && ./gradlew clean && ./gradlew assembleRelease && ./gradlew bundleRelease && cd .. ```
56,576,470
I am confused about the runtime of the binary operator of the set in Python. e.g. - `set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa. I went through some websites but I am not able to find any clea...
2019/06/13
[ "https://Stackoverflow.com/questions/56576470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072927/" ]
You can simply open the **Build Variants** window on the bottom left hand corner of Android Studio and choose *release* as the current variant: [![enter image description here](https://i.stack.imgur.com/fs3ln.png)](https://i.stack.imgur.com/fs3ln.png)
step - 1) ./gradlew bundleRelease step - 2) react-native run-android --variant=release Make sure you have connected an android device For the production-ready app, firstly you have to remove the previous app from the device
56,576,470
I am confused about the runtime of the binary operator of the set in Python. e.g. - `set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa. I went through some websites but I am not able to find any clea...
2019/06/13
[ "https://Stackoverflow.com/questions/56576470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072927/" ]
I made a file that called `build.sh`. When i want to release a new version of android in ReactNative, just type and press `sh ./build.sh` in terminal. My shell script in `build.sh` file: ``` npx jetify && cd android && ./gradlew clean && ./gradlew assembleRelease && ./gradlew bundleRelease && cd .. ```
You can simply open the **Build Variants** window on the bottom left hand corner of Android Studio and choose *release* as the current variant: [![enter image description here](https://i.stack.imgur.com/fs3ln.png)](https://i.stack.imgur.com/fs3ln.png)
56,576,470
I am confused about the runtime of the binary operator of the set in Python. e.g. - `set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa. I went through some websites but I am not able to find any clea...
2019/06/13
[ "https://Stackoverflow.com/questions/56576470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072927/" ]
Use `gradlew bundleRelease` to generate an app bundle (.aab file) and `gradlew assembleRelease` to generate an apk (.apk file). To install a release on your emulator, use `react-native run-android --variant=release`. I hope this helps
step - 1) ./gradlew bundleRelease step - 2) react-native run-android --variant=release Make sure you have connected an android device For the production-ready app, firstly you have to remove the previous app from the device
56,576,470
I am confused about the runtime of the binary operator of the set in Python. e.g. - `set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa. I went through some websites but I am not able to find any clea...
2019/06/13
[ "https://Stackoverflow.com/questions/56576470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072927/" ]
the short answer uses `gradlew assembleRelease` instead. not short answer :) The command you are using `gradlew bundleRelease` builds an android App bundle. read this: [Difference between apk (.apk) and app bundle (.aab)](https://stackoverflow.com/questions/52059339/difference-between-apk-apk-and-app-bundle-aab) and t...
Use `gradlew bundleRelease` to generate an app bundle (.aab file) and `gradlew assembleRelease` to generate an apk (.apk file). To install a release on your emulator, use `react-native run-android --variant=release`. I hope this helps
56,576,470
I am confused about the runtime of the binary operator of the set in Python. e.g. - `set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa. I went through some websites but I am not able to find any clea...
2019/06/13
[ "https://Stackoverflow.com/questions/56576470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072927/" ]
the short answer uses `gradlew assembleRelease` instead. not short answer :) The command you are using `gradlew bundleRelease` builds an android App bundle. read this: [Difference between apk (.apk) and app bundle (.aab)](https://stackoverflow.com/questions/52059339/difference-between-apk-apk-and-app-bundle-aab) and t...
I made a file that called `build.sh`. When i want to release a new version of android in ReactNative, just type and press `sh ./build.sh` in terminal. My shell script in `build.sh` file: ``` npx jetify && cd android && ./gradlew clean && ./gradlew assembleRelease && ./gradlew bundleRelease && cd .. ```
56,576,470
I am confused about the runtime of the binary operator of the set in Python. e.g. - `set1 | set2` Does it take the linear time as `set1 - set2` or it takes quadratic time as each element in set1 has to do bitwise or with each number of set2 or vice-versa. I went through some websites but I am not able to find any clea...
2019/06/13
[ "https://Stackoverflow.com/questions/56576470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9072927/" ]
Use `gradlew bundleRelease` to generate an app bundle (.aab file) and `gradlew assembleRelease` to generate an apk (.apk file). To install a release on your emulator, use `react-native run-android --variant=release`. I hope this helps
Cutting the long story short the command `gradlew bundleRelease` is used to generate an .aab file where as the command `gradlew assembleRelease` is used to generate .apk file so use the command accordingly
31,977,245
Let's say I have a web bot written in python that sends data via POST request to a web site. The data is pulled from a text file line by line and passed into an array. Currently, I'm testing each element in the array through a simple for-loop. How can I effectively implement multi-threading to iterate through the data ...
2015/08/12
[ "https://Stackoverflow.com/questions/31977245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313602/" ]
This sounds like a recipe for `multiprocessing.Pool` See here: <https://docs.python.org/2/library/multiprocessing.html#introduction> ``` from multiprocessing import Pool def test(num): if num%2 == 0: return True else: return False if __name__ == "__main__": list_of_datas_to_test = [0, 1,...
Threads are slow in python because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock). You should consider using multiple processes with the Python `multiprocessing` module instead of threads. Using multiple processes can increase the "ramp up" time of your code, as spawning a real pro...
31,458,813
I get a TemplateNotFound after I installed django-postman and django-messages. I obviously installed them separately - first django-postman, and then django-messages. This is so simple and yet I've spent hours trying to resolve this. I'm using Django 1.8, a fresh base install using pip. I then installed the two above ...
2015/07/16
[ "https://Stackoverflow.com/questions/31458813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4431105/" ]
The issue is because it extends from the site's base.html. It is also mentioned in postman documentation :- <https://django-postman.readthedocs.org/en/latest/quickstart.html#templates> ``` The postman/base.html template extends a base.html site template, in which some blocks are expected: title: in <html><head><t...
The problem was resolved for django-messages after reviewing a called template and changing the extends/inheritance parameter. The file that was being called, inbox.html, inherited "django\_messages/base.html" ... which worked fine. "base.html" then inherited from "base.html," so there appeared to be some circular log...
44,112,399
I run a Python Discord bot. I import some modules and have some events. Now and then, it seems like the script gets killed for some unknown reason. Maybe because of an error/exception or some connection issue maybe? I'm no Python expert but I managed to get my bot working pretty well, I just don't exactly understand ho...
2017/05/22
[ "https://Stackoverflow.com/questions/44112399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1689179/" ]
You can write another `python code (B)` to call your original `python code (A)` using `Popen` from `subprocess`. In `python code (B)`, ask the program to `wait` for your `python code (A)`. If `'A'` exits with an `error code`, `recall` it from `B`. I provide an example for python\_code\_B.py ``` import subprocess fi...
for problem you stated i prefer to use python [subprocess](https://docs.python.org/3.4/library/subprocess.html) call to rerun python script or use [try blocks](https://docs.python.org/3.4/tutorial/errors.html). This might be helpful to you. check this sample try block code: ``` try: import xyz # consider it is not e...
55,290,527
How do I write python scrip to solve this? ``` l=[1,2,3] Length A X=[one,two,three,.... ] length A ``` how do print/write to file output should be ``` 1=one 2=two 3=three .... ``` Trying to use something like but since the Length A is variable this won't work ``` logfile.write('%d=%s %d=%s %d=%s %d=%s \n' % (...
2019/03/21
[ "https://Stackoverflow.com/questions/55290527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7038853/" ]
Use `zip`: ``` l = [1, 2, 3] X = ['one', 'two', 'three'] ' '.join('{}={}'.format(first, second) for first, second in zip(l, X)) ``` Output: ``` '1=one 2=two 3=three' ```
You could also use an fString to make this more concise: ``` numbers = [1, 2, 3] strings = ['one', 'two', 'three'] print(' '.join(f'{n}={s}' for n,s in zip(numbers,strings))) ```
55,290,527
How do I write python scrip to solve this? ``` l=[1,2,3] Length A X=[one,two,three,.... ] length A ``` how do print/write to file output should be ``` 1=one 2=two 3=three .... ``` Trying to use something like but since the Length A is variable this won't work ``` logfile.write('%d=%s %d=%s %d=%s %d=%s \n' % (...
2019/03/21
[ "https://Stackoverflow.com/questions/55290527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7038853/" ]
Use `zip`: ``` l = [1, 2, 3] X = ['one', 'two', 'three'] ' '.join('{}={}'.format(first, second) for first, second in zip(l, X)) ``` Output: ``` '1=one 2=two 3=three' ```
* zip(a, b) would return pairs from both lists until shorter list is over * map(f, a) would apply function f to every element in list a. * join is a python way to concatenate strings All combined: ``` print(''.join(map('{}={}'.format, zip(l, X)))) print(''.join(map('='.join, zip(map(str,l), X)))) ``` since join wor...
3,929,096
A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ...
2010/10/14
[ "https://Stackoverflow.com/questions/3929096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227567/" ]
Your operating system is almost certainly buffering/caching disk writes already. It's not surprising the RAM disk is so close in performance. Without knowing exactly what you're writing or how, we can only offer general suggestions. Some ideas: * If you have 2 GB RAM you probably have a decent processor, so you could...
I know that Windows is very aggressive about caching disk data in RAM, and 100K would fit easily. The writes are going directly to cache and then perhaps being written to disk via a non-blocking write, which allows the program to continue. The RAM disk probably wouldn't support non-blocking operations because it expect...
3,929,096
A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ...
2010/10/14
[ "https://Stackoverflow.com/questions/3929096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227567/" ]
Your operating system is almost certainly buffering/caching disk writes already. It's not surprising the RAM disk is so close in performance. Without knowing exactly what you're writing or how, we can only offer general suggestions. Some ideas: * If you have 2 GB RAM you probably have a decent processor, so you could...
I had the same mind boggling experience, and after many tries I figured it out. When ramdisk is formatted as FAT32, then even though benchmarks shows high values, real world use is actually slower than NTFS formatted SSD. But NTFS formatted ramdisk is faster in real life than SSD.
3,929,096
A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ...
2010/10/14
[ "https://Stackoverflow.com/questions/3929096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227567/" ]
I know that Windows is very aggressive about caching disk data in RAM, and 100K would fit easily. The writes are going directly to cache and then perhaps being written to disk via a non-blocking write, which allows the program to continue. The RAM disk probably wouldn't support non-blocking operations because it expect...
In my tests I've found that not only batch size affects overall performance, but also the nature of data itself. I've managed to get 5 times better write times compared to SSD in only one scenario: writing a 100MB chunk of pre-cooked random byte array to RAM drive. Writing more "predictable" data like letters "aaa" or ...
3,929,096
A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ...
2010/10/14
[ "https://Stackoverflow.com/questions/3929096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227567/" ]
Can you write the data out in batches rather than one item at a time? Are you caching resources like open file handles etc or cleaning those up? Are your disk writes blocking, can you use background threads to saturate IO while not affecting compute performance. I would look at optimising the disk writes first, and th...
I join the people having problems with RAM disk speeds (only on Windows). The SSD i have can write 30 GiB (in one big block, dump a 30GiB RAM ARRAY) with a speed of 550 MiB/s (arround 56 seconds to write 30 GiB) ... this is if the write is asked in one source code sentence. The RAM Disk (imDisk) i have can write 30 G...
3,929,096
A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ...
2010/10/14
[ "https://Stackoverflow.com/questions/3929096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227567/" ]
Your operating system is almost certainly buffering/caching disk writes already. It's not surprising the RAM disk is so close in performance. Without knowing exactly what you're writing or how, we can only offer general suggestions. Some ideas: * If you have 2 GB RAM you probably have a decent processor, so you could...
Can you write the data out in batches rather than one item at a time? Are you caching resources like open file handles etc or cleaning those up? Are your disk writes blocking, can you use background threads to saturate IO while not affecting compute performance. I would look at optimising the disk writes first, and th...
3,929,096
A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ...
2010/10/14
[ "https://Stackoverflow.com/questions/3929096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227567/" ]
In my tests I've found that not only batch size affects overall performance, but also the nature of data itself. I've managed to get 5 times better write times compared to SSD in only one scenario: writing a 100MB chunk of pre-cooked random byte array to RAM drive. Writing more "predictable" data like letters "aaa" or ...
I had the same mind boggling experience, and after many tries I figured it out. When ramdisk is formatted as FAT32, then even though benchmarks shows high values, real world use is actually slower than NTFS formatted SSD. But NTFS formatted ramdisk is faster in real life than SSD.
3,929,096
A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ...
2010/10/14
[ "https://Stackoverflow.com/questions/3929096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227567/" ]
In my tests I've found that not only batch size affects overall performance, but also the nature of data itself. I've managed to get 5 times better write times compared to SSD in only one scenario: writing a 100MB chunk of pre-cooked random byte array to RAM drive. Writing more "predictable" data like letters "aaa" or ...
I join the people having problems with RAM disk speeds (only on Windows). The SSD i have can write 30 GiB (in one big block, dump a 30GiB RAM ARRAY) with a speed of 550 MiB/s (arround 56 seconds to write 30 GiB) ... this is if the write is asked in one source code sentence. The RAM Disk (imDisk) i have can write 30 G...
3,929,096
A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ...
2010/10/14
[ "https://Stackoverflow.com/questions/3929096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227567/" ]
I know that Windows is very aggressive about caching disk data in RAM, and 100K would fit easily. The writes are going directly to cache and then perhaps being written to disk via a non-blocking write, which allows the program to continue. The RAM disk probably wouldn't support non-blocking operations because it expect...
I had the same mind boggling experience, and after many tries I figured it out. When ramdisk is formatted as FAT32, then even though benchmarks shows high values, real world use is actually slower than NTFS formatted SSD. But NTFS formatted ramdisk is faster in real life than SSD.
3,929,096
A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ...
2010/10/14
[ "https://Stackoverflow.com/questions/3929096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227567/" ]
Can you write the data out in batches rather than one item at a time? Are you caching resources like open file handles etc or cleaning those up? Are your disk writes blocking, can you use background threads to saturate IO while not affecting compute performance. I would look at optimising the disk writes first, and th...
In my tests I've found that not only batch size affects overall performance, but also the nature of data itself. I've managed to get 5 times better write times compared to SSD in only one scenario: writing a 100MB chunk of pre-cooked random byte array to RAM drive. Writing more "predictable" data like letters "aaa" or ...
3,929,096
A python program I created is IO bounded. The majority of the time (over 90%) is spent in a single loop which repeats ~10,000 times. In this loop, ~100KB data is generated and written to a temporary file; it is then read back out by another program and statistics about that data collected. This is the only way to pass ...
2010/10/14
[ "https://Stackoverflow.com/questions/3929096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227567/" ]
Your operating system is almost certainly buffering/caching disk writes already. It's not surprising the RAM disk is so close in performance. Without knowing exactly what you're writing or how, we can only offer general suggestions. Some ideas: * If you have 2 GB RAM you probably have a decent processor, so you could...
I join the people having problems with RAM disk speeds (only on Windows). The SSD i have can write 30 GiB (in one big block, dump a 30GiB RAM ARRAY) with a speed of 550 MiB/s (arround 56 seconds to write 30 GiB) ... this is if the write is asked in one source code sentence. The RAM Disk (imDisk) i have can write 30 G...
4,149,274
Okay, I'm having one of those moments that makes me question my ability to use a computer. This is not the sort of question I imagined asking as my first SO post, but here goes. Started on Zed's new "Learn Python the Hard Way" since I've been looking to get back into programming after a 10 year hiatus and python was a...
2010/11/10
[ "https://Stackoverflow.com/questions/4149274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/502486/" ]
When you type the name of a file at the windows command prompt, cmd can check the windows registry for the default file association, and use that program to open it. So if the Inkscape installer associated .py files with its own version of python, cmd might preferentially run that and ignore the PATH entirely. See [thi...
Based on your second edit, you may have more than one copy of pydoc.py in your path, with the 'wrong' one first such that when it starts up it doesn't have the correct environment in which to execute.