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
29,692,140
If we make a pathological potato like this: ``` >>> class Potato: ... def __eq__(self, other): ... return False ... def __hash__(self): ... return random.randint(1, 10000) ... >>> p = Potato() >>> p == p False ``` We can break sets and dicts this way (*note:* it's the same even if `__eq__` r...
2015/04/17
[ "https://Stackoverflow.com/questions/29692140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
`list`, `tuple`, etc., does indeed do an identity check before an equality check, and this behavior is motivated by [these invariants](http://bugs.python.org/issue4296#msg75735): ``` assert a in [a] assert a in (a,) assert [a].count(a) == 1 for a in container: assert a in container # this should ALWAYS be true ...
In general, breaking the assumption that identity implies equality can break a variety of things in Python. It is true that NaN breaks this assumption, and thus NaN breaks some things in Python. Discussion can be found in [this Python bug](http://bugs.python.org/issue4296). In a pre-release version of Python 3.0, relia...
65,869,272
I've created a TensorFlow model that uses RaggedTensors. Model works fine and when calling `model.predict` and I get the expected results. ``` input = tf.ragged.constant([[[-0.9984272718429565, -0.9422321319580078, -0.27657580375671387, -3.185823678970337, -0.6360141634941101, -1.6579184532165527, -1.9000954627990723,...
2021/01/24
[ "https://Stackoverflow.com/questions/65869272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1115237/" ]
<https://www.tensorflow.org/tfx/serving/api_rest#predict_api> I think that you need to use a columnar format as recommended in the REST API instead of the row format because the dimensions of your 0th input do not match. This means that instead of instances you will have to use inputs. Since you also have multiple inp...
Others may benefit from this, as it took me a while to stitch together: 1. Training a toy LSTM model on ragged tensors. 2. Loading it into TensorFlow Serving. 3. Making a prediction request with a serielized ragged tensor. If anyone knows how to rename "args\_0" and "args\_0\_1", please add. Relevant Git Issue: <http...
69,929,986
I tried many ways but neither worked. I have to convert string like `assdggg` to `a2sd3g` in python. If letters are next to each other we leave only one letter and before it we write how mamy of them were next to eachother. Any idea how can it be done?
2021/11/11
[ "https://Stackoverflow.com/questions/69929986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14868201/" ]
I'd suggest `itertools.groupby` then format as you need ``` from itertools import groupby # groupby("assdggg") # {'a': ['a'], 's': ['s', 's'], 'd': ['d'], 'g': ['g', 'g', 'g']} result = "" for k, v in groupby("assdggg"): count = len(list(v)) result += (str(count) if count > 1 else "") + k print(result) # a...
Try using `.groupby()`: ``` from itertools import groupby txt = "assdggg" print(''.join(str(l) + k if (l := len(list(g))) != 1 else k for k, g in groupby(txt))) ``` output : ``` a2sd3g ```
69,929,986
I tried many ways but neither worked. I have to convert string like `assdggg` to `a2sd3g` in python. If letters are next to each other we leave only one letter and before it we write how mamy of them were next to eachother. Any idea how can it be done?
2021/11/11
[ "https://Stackoverflow.com/questions/69929986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14868201/" ]
I'd suggest `itertools.groupby` then format as you need ``` from itertools import groupby # groupby("assdggg") # {'a': ['a'], 's': ['s', 's'], 'd': ['d'], 'g': ['g', 'g', 'g']} result = "" for k, v in groupby("assdggg"): count = len(list(v)) result += (str(count) if count > 1 else "") + k print(result) # a...
You can try this : ``` string = 'assdggg' compression = '' for char in string : if char not in compression : if string.count(char) != 1 : compression += str(string.count(char)) compression += char print(compression) #'a2sd3g' ```
69,929,986
I tried many ways but neither worked. I have to convert string like `assdggg` to `a2sd3g` in python. If letters are next to each other we leave only one letter and before it we write how mamy of them were next to eachother. Any idea how can it be done?
2021/11/11
[ "https://Stackoverflow.com/questions/69929986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14868201/" ]
Try using `.groupby()`: ``` from itertools import groupby txt = "assdggg" print(''.join(str(l) + k if (l := len(list(g))) != 1 else k for k, g in groupby(txt))) ``` output : ``` a2sd3g ```
You can try this : ``` string = 'assdggg' compression = '' for char in string : if char not in compression : if string.count(char) != 1 : compression += str(string.count(char)) compression += char print(compression) #'a2sd3g' ```
16,704,588
I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1]. [This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've...
2013/05/23
[ "https://Stackoverflow.com/questions/16704588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730674/" ]
This might not be the right things to do , but ``` $ open -a Google\ Chrome http://localhost:8888 $ open -a Firefox http://localhost:8888 ``` Works from me (only on mac) to open any url in one of the 2 browser. Use the `--no-browser` option and make an bash function that does that. Or even have a bookmark in Chrome...
For future reference, this works looks the most elegant way to edit `jupyter_notebook_config.py` for me on macOS: ``` c.NotebookApp.browser = u'open -a "Google Chrome" %s' ``` > > You can obviously replace `"Google Chrome"` with any other browser. > > > Full procedure: 1. `jupyter notebook --generate-config` 2...
16,704,588
I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1]. [This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've...
2013/05/23
[ "https://Stackoverflow.com/questions/16704588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730674/" ]
Based on [this answer](https://stackoverflow.com/a/6042407/1225068), (running Python 2.7.3 and IPython-0.13.1 on Linux), all I had to set in my `ipython_notebook_config.py` was ``` c.NotebookApp.browser = u'/usr/bin/google-chrome %s' ``` I'm guessing, setting `c.NotebookApp.browser` to `/Applications/Browsers/Chrom...
This might not be the right things to do , but ``` $ open -a Google\ Chrome http://localhost:8888 $ open -a Firefox http://localhost:8888 ``` Works from me (only on mac) to open any url in one of the 2 browser. Use the `--no-browser` option and make an bash function that does that. Or even have a bookmark in Chrome...
16,704,588
I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1]. [This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've...
2013/05/23
[ "https://Stackoverflow.com/questions/16704588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730674/" ]
For people who want to make firefox their default for ipython notebooks (where it is not necessarily the system default), adding the following line to `ipython_notebook_config.py` should be sufficient: `c.NotebookApp.browser = 'Firefox'` For me, this was better than linking to the application file directly because it...
For Mac users, the best way is to change the default browser from the system preferences/General, and enjoy your new browser for jupyter notebook.
16,704,588
I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1]. [This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've...
2013/05/23
[ "https://Stackoverflow.com/questions/16704588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730674/" ]
Since the great switch to Jupyter, and with recent versions of OS X (e.g., Yosemite), Jupyter/iPython (e.g., 4.0.1), and Chrome (e.g., 47), things have changed a bit. Jupyter/iPython no longer puts the notebook config file in `~/.ipython`; it's now in `~/.jupyter`, and the default file is generated with ``` jupyter n...
For future reference, this works looks the most elegant way to edit `jupyter_notebook_config.py` for me on macOS: ``` c.NotebookApp.browser = u'open -a "Google Chrome" %s' ``` > > You can obviously replace `"Google Chrome"` with any other browser. > > > Full procedure: 1. `jupyter notebook --generate-config` 2...
16,704,588
I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1]. [This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've...
2013/05/23
[ "https://Stackoverflow.com/questions/16704588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730674/" ]
Since the great switch to Jupyter, and with recent versions of OS X (e.g., Yosemite), Jupyter/iPython (e.g., 4.0.1), and Chrome (e.g., 47), things have changed a bit. Jupyter/iPython no longer puts the notebook config file in `~/.ipython`; it's now in `~/.jupyter`, and the default file is generated with ``` jupyter n...
For people who want to make firefox their default for ipython notebooks (where it is not necessarily the system default), adding the following line to `ipython_notebook_config.py` should be sufficient: `c.NotebookApp.browser = 'Firefox'` For me, this was better than linking to the application file directly because it...
16,704,588
I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1]. [This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've...
2013/05/23
[ "https://Stackoverflow.com/questions/16704588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730674/" ]
For people who want to make firefox their default for ipython notebooks (where it is not necessarily the system default), adding the following line to `ipython_notebook_config.py` should be sufficient: `c.NotebookApp.browser = 'Firefox'` For me, this was better than linking to the application file directly because it...
If you don't want to open the browser at all, you can add `ipython notebook --no-browser`.
16,704,588
I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1]. [This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've...
2013/05/23
[ "https://Stackoverflow.com/questions/16704588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730674/" ]
On OS X, you can put the following in ipython\_notebook\_config.py to open Chrome: ``` c.NotebookApp.browser = u'/usr/bin/open -a Google\\ Chrome %s' ``` The executable in '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' fails for me with 'unable to obtain profile lock', so going through 'open' is the ...
This worked for me on OSX Mavericks: ``` c.NotebookApp.browser = u'/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome %s' ```
16,704,588
I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1]. [This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've...
2013/05/23
[ "https://Stackoverflow.com/questions/16704588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730674/" ]
On OS X, you can put the following in ipython\_notebook\_config.py to open Chrome: ``` c.NotebookApp.browser = u'/usr/bin/open -a Google\\ Chrome %s' ``` The executable in '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' fails for me with 'unable to obtain profile lock', so going through 'open' is the ...
For people who want to make firefox their default for ipython notebooks (where it is not necessarily the system default), adding the following line to `ipython_notebook_config.py` should be sufficient: `c.NotebookApp.browser = 'Firefox'` For me, this was better than linking to the application file directly because it...
16,704,588
I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1]. [This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've...
2013/05/23
[ "https://Stackoverflow.com/questions/16704588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730674/" ]
If you don't want to open the browser at all, you can add `ipython notebook --no-browser`.
For Mac users, the best way is to change the default browser from the system preferences/General, and enjoy your new browser for jupyter notebook.
16,704,588
I would like to keep firefox as my system default browser on my Mac, but launch IPython Notebook in Chrome[1]. [This answer](https://stackoverflow.com/a/15748692/1730674) led me to my `ipython_notebook_config.py` file but I can't get an instance of Chrome running. After `c = get_config()` and `import webbrowser`, I've...
2013/05/23
[ "https://Stackoverflow.com/questions/16704588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730674/" ]
Based on [this answer](https://stackoverflow.com/a/6042407/1225068), (running Python 2.7.3 and IPython-0.13.1 on Linux), all I had to set in my `ipython_notebook_config.py` was ``` c.NotebookApp.browser = u'/usr/bin/google-chrome %s' ``` I'm guessing, setting `c.NotebookApp.browser` to `/Applications/Browsers/Chrom...
For people who want to make firefox their default for ipython notebooks (where it is not necessarily the system default), adding the following line to `ipython_notebook_config.py` should be sufficient: `c.NotebookApp.browser = 'Firefox'` For me, this was better than linking to the application file directly because it...
7,022,148
In the below python the message RSU is not supported on single node machine\*\* is not getting printed. can anyone help please?? ``` #! /usr/bin/env python import sys class SWMException(Exception): def __init__(self, arg): print "inside exception" Exception.__init__(self, arg) class RSUNotSuppor...
2011/08/11
[ "https://Stackoverflow.com/questions/7022148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889384/" ]
It is not printed, because you're even not trying to print it :) Here: ``` try: isPrepActionNeeded() except RSUNotSupported as e: print str(e) sys.exit(1) ```
Because you handle the exception with your try/except clause.
7,022,148
In the below python the message RSU is not supported on single node machine\*\* is not getting printed. can anyone help please?? ``` #! /usr/bin/env python import sys class SWMException(Exception): def __init__(self, arg): print "inside exception" Exception.__init__(self, arg) class RSUNotSuppor...
2011/08/11
[ "https://Stackoverflow.com/questions/7022148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889384/" ]
It is not printed, because you're even not trying to print it :) Here: ``` try: isPrepActionNeeded() except RSUNotSupported as e: print str(e) sys.exit(1) ```
Change the last two lines to: ``` except Exception as e: print e sys.exit(1) ``` I use just `Exception` here to keep this the equivalent of a bare `except:`. You really should use `RSUNotSupported` so you don't hide other types of errors.
68,435,024
My code: ```py import pyttsx3 #sapi5 is default windows voice api engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') print(voices[1].id) engine.setProperty('voice', voices[0].id) def speak(audio): pass ``` On running the code instead of getting that voice ID printed I am getting this error: ...
2021/07/19
[ "https://Stackoverflow.com/questions/68435024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15030983/" ]
No, they don't conflict with Windows 11! For me they still are running efficiently! Try to uninstall Python and pip including all modules as well and then download them. If that doesn't work you, you could try switching to older versions of Python that support these quiet efficiently or you can download these librarie...
Ok, I have tried the code and works fine for me now as per me there is no problem in your code and its probably the windows 11 or the installation has a defect / glitch cause windows 11 is not yet the smoothest and it may be causing your code to not run properly i would also like to ask you to see if the permissions a...
16,627,533
I'm very new to python. How can I convert a unit in python? I mean not using a conversion function to do this. Just as a built-in syntax in python, like the complex numbers works. E.g., when I typed 1mm in python command line, and expect the result is 0.001 ``` >>> 1mm 0.001 #Just like the built-in complex numbers or ...
2013/05/18
[ "https://Stackoverflow.com/questions/16627533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2397416/" ]
how bout ``` mm = 0.001 1*mm ``` not sure if that is what you are asking for ... if you have ever messed with report lab they do simillar stuff. (although they use it to convert pixels to actual border sizes and what not) eg: ``` inch = DPI*some_thing margin = 2*inch ```
If you are doing scientific work with physical units, it is a good idea to use a units library (not built-in) like [quantities](http://pythonhosted.org/quantities/user/tutorial.html) which also supports scientific packages like numpy. For example: ``` >>> from quantities import meter >>> q = 1 * meter >>> q.units = 'f...
16,627,533
I'm very new to python. How can I convert a unit in python? I mean not using a conversion function to do this. Just as a built-in syntax in python, like the complex numbers works. E.g., when I typed 1mm in python command line, and expect the result is 0.001 ``` >>> 1mm 0.001 #Just like the built-in complex numbers or ...
2013/05/18
[ "https://Stackoverflow.com/questions/16627533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2397416/" ]
how bout ``` mm = 0.001 1*mm ``` not sure if that is what you are asking for ... if you have ever messed with report lab they do simillar stuff. (although they use it to convert pixels to actual border sizes and what not) eg: ``` inch = DPI*some_thing margin = 2*inch ```
Python doens't have built-in units, so you'll need to install a package specifically for that. [Axiompy](https://github.com/ArztKlein/Axiompy) is a package that can do this. Install with `pip install axiompy` If you want to convert from millimetres to metres, like in the question, you'd use: ```py from axiompy impo...
43,897,628
I updated to pandas 0.20.1 recently and I tried to use the new feature of to\_json(orient='table') ``` import pandas as pd pd.__version__ # '0.20.1' a = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]}) a.to_json('a.json', orient='table') ``` But how can I read this JSON file to DataFrame? I tried `pd.read_json('a.json', o...
2017/05/10
[ "https://Stackoverflow.com/questions/43897628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4956987/" ]
Apparently the new method outputs some metadata with the dataset into json such as the pandas version. Hence, consider using the built-in `json` module to read in this nested object to extract the value at *data* key: ``` import json ... with open('a.json', 'r') as f: json_obj = json.loads(f.read()) df = pd...
Here is a function I have developed from Parfait answer: ``` def table_to_df(table): df = pd.DataFrame(table['data'], columns=[t['name'] for t in table['schema']['fields']]) for t in table['schema']['fields']: if t['type'] == "datetime": df[t['name']] = pd.to_datetime(...
66,129,496
I am using Featuretools library to try to generate custom features involving customer transactions. I tested the function and it returns the answer so I am not sure why I am getting this error. I tried using the following link: <https://featuretools.alteryx.com/en/stable/getting_started/primitives.html> Thank you! `...
2021/02/10
[ "https://Stackoverflow.com/questions/66129496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15179950/" ]
Default CSS should be overridden by your CSS. SO your need to use `!important` in your CSS. Here is the css : ``` <style> .toasting { color: yellow !important; background-color: pink !important; } </style> ``` Working [demo](https://codesandbox.io/s/vue-toasted-example-forked-hd4n3?file=/App.vue)
If someone is facing the same issue, the solution above works but keep in mind it's only **without** style scoping!
15,777,992
First, note that I understand that `==` is used for comparing two expressions, while `=` is used for assigning a value to a variable. However, python is such a clean language with minimal syntax requirements, that this seems like an easy operator to axe. Also I am not trying to start a debate or discussion, but rather ...
2013/04/03
[ "https://Stackoverflow.com/questions/15777992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2218093/" ]
One very simple reason is that python allows boolean expressions: ``` a = b == c ``` and also multiple assignment: ``` a = b = c ``` In the first case, `a` gets assigned a boolean value\* (`True` or `False`) depending on whether `b` and `c` are equal. In the second case, `a` and `b` end up referencing the same ob...
The two operators can overlap. For instance, consider ``` a = b = c ``` which sets `a` and `b` both to `c`, and ``` a = b == c ``` which sets `a` to either `True` or `False` based on whether `b` and `c` are equal. --- More generally, Python attempts to avoid syntax that is even possibly ambiguous to allow the p...
72,089,771
I have a working python package that's a CLI tool and I wanted to convert it into a single `.exe` file to upload it to other package managers so I used Pyinstaller. After building the `.exe` file with this command: ``` pyinstaller -c --log-level=DEBUG main.py 2> build.txt --onefile --exclude-module=pytest --add-data "...
2022/05/02
[ "https://Stackoverflow.com/questions/72089771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15747757/" ]
It means that the parameter is optional and has a dynamic default value. Usually, optional parameters have default values that are static, like this: ``` foo (string $bar = null): bool ``` Or this: ``` foo (string $bar = 0): bool ``` But in some cases, the default value changes depending on environment. These are...
The `$description` argument is optional, but its default value is not a constant. The manual explains: > > From PHP 7, if no description is provided, a default description equal to the source code for the invocation of `assert()` is provided. > > > This can't be easily expressed in the syntax summary, so they use...
72,089,771
I have a working python package that's a CLI tool and I wanted to convert it into a single `.exe` file to upload it to other package managers so I used Pyinstaller. After building the `.exe` file with this command: ``` pyinstaller -c --log-level=DEBUG main.py 2> build.txt --onefile --exclude-module=pytest --add-data "...
2022/05/02
[ "https://Stackoverflow.com/questions/72089771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15747757/" ]
The `$description` argument is optional, but its default value is not a constant. The manual explains: > > From PHP 7, if no description is provided, a default description equal to the source code for the invocation of `assert()` is provided. > > > This can't be easily expressed in the syntax summary, so they use...
According to the documentation <https://www.php.net/manual/en/function.assert.php> > > assert() is a language construct in PHP 7 > > > So it's not a function syntax. You can't use such a syntax in your own function. Other answers are right about meaning of the question mark in the description of assert(). But th...
72,089,771
I have a working python package that's a CLI tool and I wanted to convert it into a single `.exe` file to upload it to other package managers so I used Pyinstaller. After building the `.exe` file with this command: ``` pyinstaller -c --log-level=DEBUG main.py 2> build.txt --onefile --exclude-module=pytest --add-data "...
2022/05/02
[ "https://Stackoverflow.com/questions/72089771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15747757/" ]
It means that the parameter is optional and has a dynamic default value. Usually, optional parameters have default values that are static, like this: ``` foo (string $bar = null): bool ``` Or this: ``` foo (string $bar = 0): bool ``` But in some cases, the default value changes depending on environment. These are...
According to the documentation <https://www.php.net/manual/en/function.assert.php> > > assert() is a language construct in PHP 7 > > > So it's not a function syntax. You can't use such a syntax in your own function. Other answers are right about meaning of the question mark in the description of assert(). But th...
41,982,238
Is there a way to add a header row to a CSV without loading the CSV into memory in python? I have an 18GB CSV I want to add a header to, and all the methods I've seen require loading the CSV into memory, which is obviously unfeasible.
2017/02/01
[ "https://Stackoverflow.com/questions/41982238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6637269/" ]
You will need to rewrite the whole file. Simplest is not to use python ``` echo 'col1, col2, col2,... ' > out.csv cat in.csv >> out.csv ``` Python based solutions will work at much higher levels and will be a lot slower. 18GB is a lot of data after all. Better to work with operating system functionality, which will ...
Here is a comparison of the three suggested solutions for a ~200 MB CSV file with 10^6 rows and 10 columns (n=50). The ratio stays approximately the same for larger and smaller files (10 MB to 8 GB). > > cp:shutil:csv\_reader 1:10:55 > > > i.e. using the builtin `cp` function is approximately 55 times faster than...
41,982,238
Is there a way to add a header row to a CSV without loading the CSV into memory in python? I have an 18GB CSV I want to add a header to, and all the methods I've seen require loading the CSV into memory, which is obviously unfeasible.
2017/02/01
[ "https://Stackoverflow.com/questions/41982238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6637269/" ]
Just use the fact that `csv` module iterates on the rows, so it never loads the whole file in memory ``` import csv with open("huge_csv.csv") as fr, open("huge_output.csv","w",newline='') as fw: cr = csv.reader(fr) cw = csv.writer(fw) cw.writerow(["title1","title2","title3"]) cw.writerows(cr) ``` us...
Here is a comparison of the three suggested solutions for a ~200 MB CSV file with 10^6 rows and 10 columns (n=50). The ratio stays approximately the same for larger and smaller files (10 MB to 8 GB). > > cp:shutil:csv\_reader 1:10:55 > > > i.e. using the builtin `cp` function is approximately 55 times faster than...
54,195,111
I have a JSON data set that looks like this: ``` {"sequence":109428985,"bids":[["0.1243","53",5],["0.12429","24",2],["0.12428","6",1],["0.12427","6",2],["0.12426","6",1],["0.12425","6",1],["0.12424","6",1],["0.12423","6",1],["0.12422","6",1],["0.12421","6",1],["0.124206","6496",2],["0.124205","36032",1],["0.124201","...
2019/01/15
[ "https://Stackoverflow.com/questions/54195111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10915583/" ]
What I've done: I've recalculated the `viewBox` of your svg element, then I calculated the center of your svg. I've added a blue circle with the center in the center of the svg element. To get the size of your svg I deleted first the transform and used the `getBBox()` method. I've used the properties of the bounding bo...
Just to expand on enxanetas answer to orient the arrow correctly, here is the code, with all transforms reduced and your viewbox/sizes intact (plus I tidied up the circles): ```html <?xml version="1.0" encoding="utf-8"?> <svg version="1.0" width="160pt" height="157pt" viewBox="0 0 160 157" preserveAspectRatio="xMidYM...
54,195,111
I have a JSON data set that looks like this: ``` {"sequence":109428985,"bids":[["0.1243","53",5],["0.12429","24",2],["0.12428","6",1],["0.12427","6",2],["0.12426","6",1],["0.12425","6",1],["0.12424","6",1],["0.12423","6",1],["0.12422","6",1],["0.12421","6",1],["0.124206","6496",2],["0.124205","36032",1],["0.124201","...
2019/01/15
[ "https://Stackoverflow.com/questions/54195111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10915583/" ]
You can simplify it massively by using simpler shapes. The following needs a little tweaking but is a good starting point: ```html <svg width="160" height="160" viewBox="0 0 160 160"> <circle cx="80" cy="80" r="65" fill="skyblue" stroke="red" stroke-width="15" /> <path stroke="red" stroke-width="12" fill="none" ...
Just to expand on enxanetas answer to orient the arrow correctly, here is the code, with all transforms reduced and your viewbox/sizes intact (plus I tidied up the circles): ```html <?xml version="1.0" encoding="utf-8"?> <svg version="1.0" width="160pt" height="157pt" viewBox="0 0 160 157" preserveAspectRatio="xMidYM...
57,823,327
I'm new to python and I'm trying to make user registration that is extend from user creation model, I created profile model with the fields I want and saved the profile object with signal when user is saved, the profile is created successfully and linked with the user but profile data is not saved (in this example: job...
2019/09/06
[ "https://Stackoverflow.com/questions/57823327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2930966/" ]
Remove the second `@receiver(post_save, sender=User)`, it's useless (it's always done in the #1 profile). When you do `user = form.save()`, the signal is raised, creating an *empty* `profile`. So, just after `user = form.save()`, get the profile that has been created through the signal, like: ``` profile = Profile.o...
You need to also import signals in app to let django know about your implementation. You can implement it in following manner: ``` from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals ```
38,134,900
I'm following the `rangeslider` example on the Plotly website: <https://plot.ly/python/range-slider/> Is there a way to automatically (or even manually) rescale the y axis as the x range changes? For example, if the date range in the example above is set between Nov 2008 - April 2009, how can we automatically rescale ...
2016/06/30
[ "https://Stackoverflow.com/questions/38134900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4830338/" ]
There is no need to use triple pointer `***`. Passing two-dimensional array will work as is. Here is the code: ``` #include <stdio.h> #include <stdlib.h> // create zero initialized matrix int** callocMatrix(int rmax, int colmax) { int **mat = calloc(rmax, sizeof(int*)); for(int i = 0; i < rmax; i++) mat[i] = ...
Should be: ``` scanf("%d", &(*mat)[i][j]); ``` You're passing a pointer to you matrix object, so you need to dereference it (with `*`) just as you do with `printf`. `scanf` then needs the address of the element to write into, so you need the `&`
34,989,032
``` #code like this import dns import dns.resolver import dns.name import dns.message import dns.query request = dns.message.make_query("google.com",dns.rdatatype.NS) response = dns.query.udp(request,"216.239.32.10") print response.authority ``` but it's null ============= and then when use " nslookup google.com 21...
2016/01/25
[ "https://Stackoverflow.com/questions/34989032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5836175/" ]
Are you sure? ``` c:\srv>nslookup google.com 216.239.32.10 Server: ns1.google.com Address: 216.239.32.10 Name: google.com Addresses: 2a00:1450:400f:805::200e 178.74.30.16 178.74.30.49 178.74.30.37 178.74.30.24 178.74.30.26 178.74.30.59 178.74...
I also encountered the same problem. It turned out to be that some DNS resolvers do not reply with authority or additional sections (Check the packets using Wireshark). Change the IP address to `127.0.1.1` in your python code and make sure that you have configured your DNS resolver is not pointing to your original res...
57,438,262
I have a python function that reads random snippets from a large file and does some processing on it. I want the processing to happen in multiple processes and so make use of multiprocessing. I open the file (in binary mode) in the parent process and pass the file descriptor to each child process then use a multiproces...
2019/08/09
[ "https://Stackoverflow.com/questions/57438262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/601004/" ]
This seems to be caused by buffering: using `open(args.file, 'rb', buffering=0)` I can't reproduce anymore. <https://docs.python.org/3/library/functions.html#open> > > buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off [...] When no buffering argument is given, the defa...
I've checked, only using multiprocessing.Lock (without buffering = 0), still met the `bad data`. with both `multiprocessing.Lock` and `buffering=0`, all things goes well
11,836,748
I am using ``` httplib.HTTPConnection ("http://ipaddr:port") conn.request("GET", "", params, headers) ``` I am able to do PUT/GET using ipaddr:port using my firefox client!!. But I am seeing this error on execution of the script: ``` File "post_python.py", line 5, in <module> conn.request("GET", "", params...
2012/08/06
[ "https://Stackoverflow.com/questions/11836748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1524625/" ]
Try this instead (without "http://" before the IP address): ``` conn = httplib.HTTPConnection("x.x.x.x", port) conn.request("GET", "", params, headers) ```
You might have a proxy in between that the browser already knows about. If you're under linux try setting `http_proxy` environment variable.
11,836,748
I am using ``` httplib.HTTPConnection ("http://ipaddr:port") conn.request("GET", "", params, headers) ``` I am able to do PUT/GET using ipaddr:port using my firefox client!!. But I am seeing this error on execution of the script: ``` File "post_python.py", line 5, in <module> conn.request("GET", "", params...
2012/08/06
[ "https://Stackoverflow.com/questions/11836748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1524625/" ]
You might have a proxy in between that the browser already knows about. If you're under linux try setting `http_proxy` environment variable.
If it's an IPv6 address, you need to surround it with brackets as per [RFC 2732](http://www.ietf.org/rfc/rfc2732.txt). If I recall correctly, that's the error message you get if you don't use brackets. ``` httplib.HTTPConnection ("http://[::1]:8080") conn.request("GET", "", params, headers) ```
11,836,748
I am using ``` httplib.HTTPConnection ("http://ipaddr:port") conn.request("GET", "", params, headers) ``` I am able to do PUT/GET using ipaddr:port using my firefox client!!. But I am seeing this error on execution of the script: ``` File "post_python.py", line 5, in <module> conn.request("GET", "", params...
2012/08/06
[ "https://Stackoverflow.com/questions/11836748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1524625/" ]
Try this instead (without "http://" before the IP address): ``` conn = httplib.HTTPConnection("x.x.x.x", port) conn.request("GET", "", params, headers) ```
If it's an IPv6 address, you need to surround it with brackets as per [RFC 2732](http://www.ietf.org/rfc/rfc2732.txt). If I recall correctly, that's the error message you get if you don't use brackets. ``` httplib.HTTPConnection ("http://[::1]:8080") conn.request("GET", "", params, headers) ```
54,496,251
I'm trying to create a PDF file using Python and FPDF. I've read the project's page about unicode and I've tryed to follow their instructions, but everytime I run my program, I receave the error: > > File "eventsmanager.py", line 8 SyntaxError: Non-ASCII character > '\xc3' in file eventsmanager.py on line 8, but no ...
2019/02/02
[ "https://Stackoverflow.com/questions/54496251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10735382/" ]
You need to declare that the file encoding is UTF8 as Python 2 defaults to Latin-1. UTF8 became default in Python 3. The linked PEP contain the required line that you have to add at the beginning of the file: ``` # coding: utf8 ``` This must be the first line after the `#!` line EMACS and VIM formats are also suppo...
If you are using Python 3.x you have to use: ``` pdf.output(dest='S').encode('latin-1','ignore') ``` or ``` text=text.encode('latin-1', 'ignore').decode('latin-1') ``` in order to get the output.
52,641,587
I made a class in python and when I tried to call it into another python file (after importing it) it doesn't recognizes it as a class but as an object and then it tells me that my class is not callable here is my class: ``` class Cell: def __init__(self,value=9,isVissible=False): self.value=value ...
2018/10/04
[ "https://Stackoverflow.com/questions/52641587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10455256/" ]
The `Cell` has been used for both your imported module and your class. According to the error, python has mapped it to the module name. So, when you are writing `Cell()`, it tries to use the module name as a function, instead of calling the class constructor. If the class `Cell` is inside the `Cell` module, use `Cell....
Your import statement is wrong, you're importing a module called Cell instead of your Cell class. You should use lower case for your filenames and import it like so: ``` from cell import Cell test = Cell() ```
26,979,711
I am limited to python2.5, and I thought that threading.Thread was asynchronous. I run: python t.py and the script does not return to the shell until 3 seconds have gone by, which means its blocking. Why is it blocking? My Code: ``` #!/usr/bin/python import threading,time def doit(): time.sleep(3) print "DONE" ...
2014/11/17
[ "https://Stackoverflow.com/questions/26979711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420259/" ]
By default, threads in Python are non-daemonic. A Python application [will not exit](https://docs.python.org/2.7/library/threading.html#thread-objects) until the all non-daemon threads have completed, so in your case it won't exit until `doit` has finished. If you want to script to exit immediately upon reaching the en...
Threading in Python is "kind-of" asynchronous. What does this mean? * Only one thread can be running Python code at one time * threads that are Python code and CPU intensive will not benefit Your issue seems to be that you think a Python thread should keep running after Python itself quits -- that's not how it works....
45,248,279
I tried to run a script using turtle module on pythonanywere.com, however, got stuck at an error that cannot find the module named "**tkinter**" and I need to install python3-tk package. I followed this tutorial [installing new modules on pythonanywhere](https://help.pythonanywhere.com/pages/InstallingNewModules/) in a...
2017/07/21
[ "https://Stackoverflow.com/questions/45248279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5186966/" ]
You can't use the tkinter module from a server such as pythonanywhere. It needs to have a connection to a display and not just a browser window. <https://www.pythonanywhere.com/forums/topic/360/>
Just learnt the lesson of finding answer by asking question in different way. My purpose is to use turtle module on pythonanywere, which is not possible as explained in the answer above. However, I just found out that pythonanywhere has an affiliate website that is free and supports turtle ([www.trinker.io](http://www....
49,631,966
I want to access a list which is field from different python function. Please refer below code for more details ``` abc = [] name = "apple,orange" def foo(name): abc = name.split(',') print abc foo(name) print abc print name ``` The output is as below. > > ['apple', 'orange'] > > > [] > > > apple,orang...
2018/04/03
[ "https://Stackoverflow.com/questions/49631966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5993900/" ]
``` abc = [] name = "apple,orange" def foo(name): global abc # do this abc = name.split(',') print abc foo(name) print abc print name ```
abc from function is not the same as abc from first line, because abc in def foo is a local variable, if you want to refer to abc declared above you have to use global abc.
49,631,966
I want to access a list which is field from different python function. Please refer below code for more details ``` abc = [] name = "apple,orange" def foo(name): abc = name.split(',') print abc foo(name) print abc print name ``` The output is as below. > > ['apple', 'orange'] > > > [] > > > apple,orang...
2018/04/03
[ "https://Stackoverflow.com/questions/49631966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5993900/" ]
While other answers suggest to use `global abc`, it is considered (in general) to be bad practice to use global variables. See [why are global variables evil?](https://stackoverflow.com/questions/19158339/why-are-global-variables-evil) A better way would be to `return` the variable: ``` name = "apple,orange" def foo(...
abc from function is not the same as abc from first line, because abc in def foo is a local variable, if you want to refer to abc declared above you have to use global abc.
22,796,547
I have an issue where I am trying to log some additional attributes (the user ID and connecting host IP) on a Python CGI script. This is running under python 2.6.8 on a RHEL 5 system. I am following the documentation for extending the attributes in the basic logging dictionary as follows: ``` from __future__ import pr...
2014/04/01
[ "https://Stackoverflow.com/questions/22796547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1980968/" ]
I figured out what was happening here: I am also importing Google's oauth2client.client module which is using the logging module as well. Since the oauth2cleint.client module is considered a "child" of my page, logging was being passed up to my logging object and since the Google module is not including the extra logg...
Faced a similar problem. I guess the error occurs when there are loggers used which do not have filters added (to add the extra attributes on instantiating the loggers) but still passing the records to the formatters using formats corresponding to these attributes. [Link to documentation example using filters](https:/...
22,796,547
I have an issue where I am trying to log some additional attributes (the user ID and connecting host IP) on a Python CGI script. This is running under python 2.6.8 on a RHEL 5 system. I am following the documentation for extending the attributes in the basic logging dictionary as follows: ``` from __future__ import pr...
2014/04/01
[ "https://Stackoverflow.com/questions/22796547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1980968/" ]
I figured out what was happening here: I am also importing Google's oauth2client.client module which is using the logging module as well. Since the oauth2cleint.client module is considered a "child" of my page, logging was being passed up to my logging object and since the Google module is not including the extra logg...
by call `logging.basicConfig`, you actually change the `formatter` of `RootLogger`, which is the ancestor of all `Logger`. Then it will affect other `loggers`. You can get more detail from this [github issue](https://github.com/urllib3/urllib3/issues/1417).
50,760,826
I have the date in the following format: ``` data = """*Date:* May 31, 2018 at 1:49:05 PM EDT""" ``` I need to extract the date and month in 2 different variables: ``` date = 31 month = "May" ``` How can i do that using regex in python 3??. I tried using the below regex to get the date and month: ``` month , dat...
2018/06/08
[ "https://Stackoverflow.com/questions/50760826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9422965/" ]
**Update**: [@Markonius' answer](https://stackoverflow.com/a/54548429/288201) is the proper way to do it. Here is a script that does this based on experimenting with an LFS repository. I didn't look at the LFS protocol in details, so there might be quirks unaccounted for, but it worked for my simple case. [git-lfs-ca...
When last I was working with LFS, there were conversations on the project page about better integration - such as by writing diff and/or merge tools that could be plugged in via `.gitattributes`. These didn't seem to be considered high priority, since the main intended use case of LFS is to protect large *binary* files...
50,760,826
I have the date in the following format: ``` data = """*Date:* May 31, 2018 at 1:49:05 PM EDT""" ``` I need to extract the date and month in 2 different variables: ``` date = 31 month = "May" ``` How can i do that using regex in python 3??. I tried using the below regex to get the date and month: ``` month , dat...
2018/06/08
[ "https://Stackoverflow.com/questions/50760826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9422965/" ]
Piping an lfs pointer into `git lfs smudge` will yield you what you want. For example: ``` git cat-file blob <blob-sha> | git lfs smudge ``` Or if you have a commit-ish (a commit hash, branch name, just `HEAD`, etc.) and a file name: ``` git cat-file blob <commit-ish>:path/to/my-large-file.name | git lfs smudge ``...
When last I was working with LFS, there were conversations on the project page about better integration - such as by writing diff and/or merge tools that could be plugged in via `.gitattributes`. These didn't seem to be considered high priority, since the main intended use case of LFS is to protect large *binary* files...
50,760,826
I have the date in the following format: ``` data = """*Date:* May 31, 2018 at 1:49:05 PM EDT""" ``` I need to extract the date and month in 2 different variables: ``` date = 31 month = "May" ``` How can i do that using regex in python 3??. I tried using the below regex to get the date and month: ``` month , dat...
2018/06/08
[ "https://Stackoverflow.com/questions/50760826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9422965/" ]
Piping an lfs pointer into `git lfs smudge` will yield you what you want. For example: ``` git cat-file blob <blob-sha> | git lfs smudge ``` Or if you have a commit-ish (a commit hash, branch name, just `HEAD`, etc.) and a file name: ``` git cat-file blob <commit-ish>:path/to/my-large-file.name | git lfs smudge ``...
**Update**: [@Markonius' answer](https://stackoverflow.com/a/54548429/288201) is the proper way to do it. Here is a script that does this based on experimenting with an LFS repository. I didn't look at the LFS protocol in details, so there might be quirks unaccounted for, but it worked for my simple case. [git-lfs-ca...
45,225,741
I'm learning how to use the python `xarray` package, however, I'm having troubles with multi-dimensional data. Specifically, how to add and use additional coordinates? Here's an example. ``` import xarray as xr import pandas as pd import numpy as np site_id = ['brw','sum','mlo'] dss = [] for site in site_id: df...
2017/07/20
[ "https://Stackoverflow.com/questions/45225741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4603445/" ]
Thanks for the easy-to-reproduce example! You can only use `.sel(x=y)` with `=`, because of the limitations of python. An example using `.isel` with latitude (`sel` is harder because it's a float type): ``` In [7]: ds.isel(latitude=0) Out[7]: <xarray.Dataset> Dimensions: (index: 20, longitude: 3, site: 3) Coordina...
Another solution for selecting data through "sel" method would be using the "slice" object of Python. So, in order to select data from a Xarray object whose latitude is greater than a given value (i.e. 50 degrees north), one could write the following: ``` ds.sel(dict(latitude=slice(50,None))) ``` I hope it helps...
62,113,084
I googled it and tried lots of solutions, but this problem still happened. This is my yum.conf: ``` [root@localhost etc]# cat yum.conf [main] gpgcheck=1 installonly_limit=3 clean_requirements_on_remove=True best=True ``` I tried to re-install epel-release: ``` [root@localhost ~]# dnf update Last metadata expirati...
2020/05/31
[ "https://Stackoverflow.com/questions/62113084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13651016/" ]
You can find the below information useful to install the Nginx web server. But, Nginx is not available in CentOS 8 default repository. So, follow the below steps. And please let me know if it works for you or not. **Step 1: Installation of EPEL repository** You have to install the `EPEL` (Extra Package for Enterprise...
I hope it helps you. I am trying to install Nginx using Yum. Instructions for installing Nginx can be found in the Download section of the NGINX official website. ``` sudo vi /etc/yum.repos.d/nginx.repo [nginx] name=nginx repo baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/ gpgcheck=0 enabled=1 ``` In t...
57,927,442
On the following linke: <https://classicdb.ch/?quest=788> here at `//*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td` it contains a text > > Mottled Boar slain (10) > > > ``` //*[@id="main-contents"]/div[1]/table[1]/tbody/tr/td/a ``` contains only: > > Mottled Boar > > > And I only need the second p...
2019/09/13
[ "https://Stackoverflow.com/questions/57927442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6854832/" ]
Try this xpath. ``` //table[@class='iconlist']//tr//td[contains(.,'slain')]//a[contains(.,'Mottled Boar')] ``` **Edit** ``` //table[@class='iconlist']//tr//td//a ``` Use **javaScript** executor. where `firstChild` will return the `Mottled Boar` and `lastChild` will return `slain (10)` ``` driver.get("https://cl...
You xpath is correct. you can try this approach to get the text directly from that node. you will need lxml import. ``` from lxml import html tree = html.fromstring(driver.page_source) myText = tree.xpath("//*[@id='main-contents']/div[1]/table[1]/tbody/tr/td/a/following-sibling::text()") print(str(myText).replace('\...
48,583,455
I'm using the Python C API to call a method. At present I am using [`PyObject_CallMethodObjArgs`](https://docs.python.org/3/c-api/object.html#c.PyObject_CallMethodObjArgs) to do this. This is a variadic function: ``` PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL) ``` This is absolutely ...
2018/02/02
[ "https://Stackoverflow.com/questions/48583455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/505088/" ]
I am not sure if I am completey wrong, but AFAICT it should be possible to * create a tuple with the required number of arguments * pass this tuple to <https://docs.python.org/3/c-api/object.html#c.PyObject_CallObject> or <https://docs.python.org/3/c-api/object.html#c.PyObject_Call> (this decision depending on the nee...
A possible way might be to use [libffi](https://sourceware.org/libffi/), perhaps thru the [ctypes](https://docs.python.org/3/library/ctypes.html) Python library. It knows your [ABI](https://en.wikipedia.org/wiki/Application_binary_interface) and [calling conventions](https://en.wikipedia.org/wiki/Calling_convention) (s...
42,794,384
[python update](https://i.stack.imgur.com/gyHJ2.png) I have Python 3.5 installed on my (LinuxMint) computer by: ``` sudo apt-get install python3.5 ``` However, when I run python -V, it shows that Python 2.7 is being used. How do I tell the system to use the updated version of Python?
2017/03/14
[ "https://Stackoverflow.com/questions/42794384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You have python2.7 installed and you already have a link to the `python2.7` executable so that when you simply run `python`, it actually runs `python2.7`. When you install python3.5, that link still exists. You should either run `python3` (or `python3.5`) or you should replace the link with a new link like so (assumin...
More dynamically, ``` ln -sf $(which python3) $(which python) ``` which forces the creation of symbolic link from python3 to python.
50,619,846
I'm trying to create a series of subplots: ``` count=0 fig1, axes1 = plt.subplots(nrows=2, ncols=1, figsize=(10,80)) for x in b: """code gets data here as a dataframe""" axes1[count]=q1.plot() count=count+1 ``` However this creates two plots rather than 2 subplots in one figure. I am using python 3.5 in Pyc...
2018/05/31
[ "https://Stackoverflow.com/questions/50619846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9874771/" ]
`DataReceived` event returns on another/secondary thread, which means you will have to marshal back to the UI thread to update your `TextBox` [SerialPort.DataReceived Event](https://msdn.microsoft.com/fi-fi/library/system.io.ports.serialport.datareceived(v=vs.110).aspx) > > The DataReceived event is raised on a sec...
I got now the problem that when i send my command using **SerialPort.Write(string cmd)**, I can't read back the answer...
57,551,049
I am new to web scraping. I am trying to extract data using python from <https://www.clinicaltrialsregister.eu> using keywords "acute myeloid leukemia", "chronic myeloid leukemia", "acute lymphoblastic leukemia" to extract following information-EudraCT Number, Trial Status, Full title of the trial, Name of Sponsor, Cou...
2019/08/19
[ "https://Stackoverflow.com/questions/57551049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11266219/" ]
As i said, you can achieve this by concatenating the required part of url to every result. Try this code: ``` import requests from bs4 import BeautifulSoup page = requests.get('https://www.clinicaltrialsregister.eu/ctr-search/search?query=acute+myeloid+leukemia&page=1') soup = BeautifulSoup(page.text, 'html.parser')...
This script will traverse all pages of the search results and try to find relevant information. It's necessary to add full url, not just `https://www.clinicaltrialsregister.eu`. ``` import requests from bs4 import BeautifulSoup base_url = 'https://www.clinicaltrialsregister.eu/ctr-search/search?query=acute+myeloid+l...
11,300,737
I cant import rdflib in python. error detailed: ``` Python 2.7.3 (default, Jun 27 2012, 23:48:21) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import rdflib Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/sit...
2012/07/02
[ "https://Stackoverflow.com/questions/11300737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1497041/" ]
If you actually install rdflib via `pip`, then its dependencies will come along with it (isodate included): ``` pip install -U rdflib ``` or ``` easy_install -U rdflib ``` Chances are you might have installed it directly from source, meaning you would have to take care of the deps yourself. Information on instal...
It seems there is a dependency to [isodate](http://pypi.python.org/pypi/isodate/), so try installing that via your favorite PyPI-Installer (*pip* oder \*easy\_install\*).
5,646,322
I've written a python cgi script to generate random numbers and add them together than ask the user to give the answer. But even user answer was correct, it gives him wrong. The answer will not be correct. The problem is in the flow : ``` #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout input_fie...
2011/04/13
[ "https://Stackoverflow.com/questions/5646322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` javascript: var all_product_ids = #{raw existing_ids.to_json}; var products_json = #{raw @filter.data.to_json}; ```
I had a similar problem with this. Using the code that others have provided didn't work for me because slim was html escaping my variable. I ended up using [Gon](https://github.com/gazay/gon-sinatra). This one is for Sinatra, but they have a gem for Rails as well. Hope it helps others having similar problems.
5,646,322
I've written a python cgi script to generate random numbers and add them together than ask the user to give the answer. But even user answer was correct, it gives him wrong. The answer will not be correct. The problem is in the flow : ``` #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout input_fie...
2011/04/13
[ "https://Stackoverflow.com/questions/5646322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From <https://github.com/slim-template/slim> Text Interpolation paragraph SLIM escapes HTML by default. To avoid the same use **#{{content}}** for **#{content}**
create a `_your_erb_file_contain_javascript_code.erb` first And then in your slim file `javascript:` part: ``` #{ conditions ? (render 'your_erb_file_contain_javascript_code') : nil} ```
5,646,322
I've written a python cgi script to generate random numbers and add them together than ask the user to give the answer. But even user answer was correct, it gives him wrong. The answer will not be correct. The problem is in the flow : ``` #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout input_fie...
2011/04/13
[ "https://Stackoverflow.com/questions/5646322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In Slim ``` javascript: var all_product_ids = "#{existing_ids.to_json}"; var products_json = "#{@filter.data.to_json}"; ```
what i prefer to do, is to keep all the javascript in a separate file. for example, i would do it as follows(jquery): in your layout: ... ``` <body data-product-ids="<%= existing_ids.to_json %>" data-products-json="<%= @filter.data.to_json %>"> ``` .. in js: ``` // create your application namespace $.my...
5,646,322
I've written a python cgi script to generate random numbers and add them together than ask the user to give the answer. But even user answer was correct, it gives him wrong. The answer will not be correct. The problem is in the flow : ``` #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout input_fie...
2011/04/13
[ "https://Stackoverflow.com/questions/5646322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In Slim ``` javascript: var all_product_ids = "#{existing_ids.to_json}"; var products_json = "#{@filter.data.to_json}"; ```
create a `_your_erb_file_contain_javascript_code.erb` first And then in your slim file `javascript:` part: ``` #{ conditions ? (render 'your_erb_file_contain_javascript_code') : nil} ```
5,646,322
I've written a python cgi script to generate random numbers and add them together than ask the user to give the answer. But even user answer was correct, it gives him wrong. The answer will not be correct. The problem is in the flow : ``` #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout input_fie...
2011/04/13
[ "https://Stackoverflow.com/questions/5646322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` javascript: var all_product_ids = #{raw existing_ids.to_json}; var products_json = #{raw @filter.data.to_json}; ```
``` javascript: var isAdmin = "#{current_user.admin? ? 1 : 0}"; ```
5,646,322
I've written a python cgi script to generate random numbers and add them together than ask the user to give the answer. But even user answer was correct, it gives him wrong. The answer will not be correct. The problem is in the flow : ``` #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout input_fie...
2011/04/13
[ "https://Stackoverflow.com/questions/5646322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
what i prefer to do, is to keep all the javascript in a separate file. for example, i would do it as follows(jquery): in your layout: ... ``` <body data-product-ids="<%= existing_ids.to_json %>" data-products-json="<%= @filter.data.to_json %>"> ``` .. in js: ``` // create your application namespace $.my...
create a `_your_erb_file_contain_javascript_code.erb` first And then in your slim file `javascript:` part: ``` #{ conditions ? (render 'your_erb_file_contain_javascript_code') : nil} ```
5,646,322
I've written a python cgi script to generate random numbers and add them together than ask the user to give the answer. But even user answer was correct, it gives him wrong. The answer will not be correct. The problem is in the flow : ``` #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout input_fie...
2011/04/13
[ "https://Stackoverflow.com/questions/5646322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
what i prefer to do, is to keep all the javascript in a separate file. for example, i would do it as follows(jquery): in your layout: ... ``` <body data-product-ids="<%= existing_ids.to_json %>" data-products-json="<%= @filter.data.to_json %>"> ``` .. in js: ``` // create your application namespace $.my...
I had a similar problem with this. Using the code that others have provided didn't work for me because slim was html escaping my variable. I ended up using [Gon](https://github.com/gazay/gon-sinatra). This one is for Sinatra, but they have a gem for Rails as well. Hope it helps others having similar problems.
5,646,322
I've written a python cgi script to generate random numbers and add them together than ask the user to give the answer. But even user answer was correct, it gives him wrong. The answer will not be correct. The problem is in the flow : ``` #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout input_fie...
2011/04/13
[ "https://Stackoverflow.com/questions/5646322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From <https://github.com/slim-template/slim> Text Interpolation paragraph SLIM escapes HTML by default. To avoid the same use **#{{content}}** for **#{content}**
I had a similar problem with this. Using the code that others have provided didn't work for me because slim was html escaping my variable. I ended up using [Gon](https://github.com/gazay/gon-sinatra). This one is for Sinatra, but they have a gem for Rails as well. Hope it helps others having similar problems.
5,646,322
I've written a python cgi script to generate random numbers and add them together than ask the user to give the answer. But even user answer was correct, it gives him wrong. The answer will not be correct. The problem is in the flow : ``` #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout input_fie...
2011/04/13
[ "https://Stackoverflow.com/questions/5646322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In Slim ``` javascript: var all_product_ids = "#{existing_ids.to_json}"; var products_json = "#{@filter.data.to_json}"; ```
``` javascript: var isAdmin = "#{current_user.admin? ? 1 : 0}"; ```
5,646,322
I've written a python cgi script to generate random numbers and add them together than ask the user to give the answer. But even user answer was correct, it gives him wrong. The answer will not be correct. The problem is in the flow : ``` #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout input_fie...
2011/04/13
[ "https://Stackoverflow.com/questions/5646322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` javascript: var all_product_ids = #{raw existing_ids.to_json}; var products_json = #{raw @filter.data.to_json}; ```
create a `_your_erb_file_contain_javascript_code.erb` first And then in your slim file `javascript:` part: ``` #{ conditions ? (render 'your_erb_file_contain_javascript_code') : nil} ```
58,917,280
I am trying to base64 encode using a custom character set in python3. Most of the examples I have seen in SO are related to Python 2, so I had to make some minor adjustments to the code. The issue that I am facing is that I am replacing the character `/` with `_`, but it is still printing with `/`. My code is: This is ...
2019/11/18
[ "https://Stackoverflow.com/questions/58917280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7402287/" ]
If the only characters you want to switch are `+` and `\`, you can use [base64.urlsafe\_b64encode](https://docs.python.org/2/library/base64.html#base64.urlsafe_b64encode) to replace with `-` and `_` respectively. ``` >>> base64.urlsafe_b64encode(data.encode()) b'c29tZSByYW5kb20_IGRhdGE=' ``` Alternatively, you can r...
Shouldn't this work: ``` import base64 data = 'some random? data' custom = b"-_" rslt = base64.b64encode(data) print(rslt) rslt = base64.b64encode(data, altchars=custom) print(rslt) ``` I get following output: ``` c29tZSByYW5kb20/IGRhdGE= c29tZSByYW5kb20_IGRhdGE= ``` or if you insist, that custom contains: `...
65,335,763
Good day I am using FastAPI and I want to render the database contents on index.html - however I get the following error: ``` INFO: 127.0.0.1:55139 - "GET /?skip=0&limit=100 HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "/Users/barnaby/.local/...
2020/12/17
[ "https://Stackoverflow.com/questions/65335763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14372626/" ]
BMC does not use OS services. BMC is completely OS independent and it may monitor and control hardware even when no OS is running or installed. BMC power line is independent on the host power and BMC is powered even when the host is powered off. It is ensured by power source design. BMC can control the host power suppl...
A general design is: BMC connects to a CPLD, which controls the power sequence. When power off is needed, BMC will trigger the CPLD so that it is the same as if someone pushes the front panel power button.
59,087,639
I have the following code: ``` for i in range (0,20,1): df = pd.read_excel(url, sheet_name=i,sep='\s*,\s*') print('sample:',i+1) df1 = df.loc[0:50] #initial push ma=df1['Latest: Potential (V)'].values.tolist() max_force_initial_push=max(ma) ``` And when I run it, I get the...
2019/11/28
[ "https://Stackoverflow.com/questions/59087639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12007010/" ]
This happens because the Promise object holds its state internally . So when you call `.then` on a Promise object it will either : * Await for resolution, and then fire the callback * If the promise is already resolved, the callback will execute immediately
> > So does it mean that the compiler does sth to assist here? for example, the compiler merge the then clause right after the promise1 statement just like example 1? > > > No, there is much less magic happening than you think. `new Promise` returns a promise object. A promise object has a `.then` method. You use ...
69,614,180
Hi I have a set of data which I extracted from an api and I am trying to split the data in the set down into separate sets since currently they are all nested in the larger set. My current set: ``` api = { "9/30/2018": { "Capital Expenditure": "-13313000", "End Cash Position": "25913000", "Financing C...
2021/10/18
[ "https://Stackoverflow.com/questions/69614180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13970042/" ]
Given this structure: ``` api = { "9/30/2018": { "Capital Expenditure": "-13313000", "End Cash Position": "25913000", }, "9/30/2019": { .... ``` to get a list of key,values for the first entry can run: ``` for key,value in api["9/30/2018"]: l = [key, value] print(f" {key}, {value}") # prin...
Your dictionary keys are string so use quotes when you access them like ``` s_19_30_2018 = api["9/30/2018"] ``` also I don't see any key such as "19\_30\_2018" in your dictionary.
69,614,180
Hi I have a set of data which I extracted from an api and I am trying to split the data in the set down into separate sets since currently they are all nested in the larger set. My current set: ``` api = { "9/30/2018": { "Capital Expenditure": "-13313000", "End Cash Position": "25913000", "Financing C...
2021/10/18
[ "https://Stackoverflow.com/questions/69614180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13970042/" ]
Your dictionary keys are string so use quotes when you access them like ``` s_19_30_2018 = api["9/30/2018"] ``` also I don't see any key such as "19\_30\_2018" in your dictionary.
``` ks = api.keys() for k in ks: for key, value, in api[k]: print(f" {key}, {value}") ``` By using code you can solve your problem.
69,614,180
Hi I have a set of data which I extracted from an api and I am trying to split the data in the set down into separate sets since currently they are all nested in the larger set. My current set: ``` api = { "9/30/2018": { "Capital Expenditure": "-13313000", "End Cash Position": "25913000", "Financing C...
2021/10/18
[ "https://Stackoverflow.com/questions/69614180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13970042/" ]
Your dictionary keys are string so use quotes when you access them like ``` s_19_30_2018 = api["9/30/2018"] ``` also I don't see any key such as "19\_30\_2018" in your dictionary.
by using the following code .....you can solve your problem ``` ks = api.keys() for k in ks: for key, value, in api[k]: print(f" {key}, {value}") ```
69,614,180
Hi I have a set of data which I extracted from an api and I am trying to split the data in the set down into separate sets since currently they are all nested in the larger set. My current set: ``` api = { "9/30/2018": { "Capital Expenditure": "-13313000", "End Cash Position": "25913000", "Financing C...
2021/10/18
[ "https://Stackoverflow.com/questions/69614180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13970042/" ]
Given this structure: ``` api = { "9/30/2018": { "Capital Expenditure": "-13313000", "End Cash Position": "25913000", }, "9/30/2019": { .... ``` to get a list of key,values for the first entry can run: ``` for key,value in api["9/30/2018"]: l = [key, value] print(f" {key}, {value}") # prin...
``` ks = api.keys() for k in ks: for key, value, in api[k]: print(f" {key}, {value}") ``` By using code you can solve your problem.
69,614,180
Hi I have a set of data which I extracted from an api and I am trying to split the data in the set down into separate sets since currently they are all nested in the larger set. My current set: ``` api = { "9/30/2018": { "Capital Expenditure": "-13313000", "End Cash Position": "25913000", "Financing C...
2021/10/18
[ "https://Stackoverflow.com/questions/69614180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13970042/" ]
Given this structure: ``` api = { "9/30/2018": { "Capital Expenditure": "-13313000", "End Cash Position": "25913000", }, "9/30/2019": { .... ``` to get a list of key,values for the first entry can run: ``` for key,value in api["9/30/2018"]: l = [key, value] print(f" {key}, {value}") # prin...
by using the following code .....you can solve your problem ``` ks = api.keys() for k in ks: for key, value, in api[k]: print(f" {key}, {value}") ```
66,670,681
I am working on a desktop application that I made by using the python language and some open-source library. When I convert that .py file to a .exe file using Pyinstaller it runs on window 10 but shows an error on window 7. Is there any way to make one .exe for all window versions 7/8/10? * List item
2021/03/17
[ "https://Stackoverflow.com/questions/66670681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10975941/" ]
You do not need to "import" the functions, you would need just to create a `class` that keeps all your needed functions, and import that class. I am supposing you use an IDE, you could go to your IDE and create a simple `class`. e.g: ```java public class Utils { public static int doSmth(/* Your parameters here */...
You can add at the beginning: import like- ```java import utils; ``` Assuming it is in the same package as the current class Else it should be: ```java import <package name>.<class name> ```
66,670,681
I am working on a desktop application that I made by using the python language and some open-source library. When I convert that .py file to a .exe file using Pyinstaller it runs on window 10 but shows an error on window 7. Is there any way to make one .exe for all window versions 7/8/10? * List item
2021/03/17
[ "https://Stackoverflow.com/questions/66670681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10975941/" ]
You do not need to "import" the functions, you would need just to create a `class` that keeps all your needed functions, and import that class. I am supposing you use an IDE, you could go to your IDE and create a simple `class`. e.g: ```java public class Utils { public static int doSmth(/* Your parameters here */...
Yes, you can import methods but there are caveats. The methods are defined on a class. The methods are defined as static. The import employs the keyword static. Keep in mind that importing methods directly can create confusion and complicate debugging. Consider importing the class and invoke the method from the class. ...
19,162,812
I have a python data structure like this ``` dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']}, {'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']}, {'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']}, {'plat': 'centOs', 'val':['', '', ''...
2013/10/03
[ "https://Stackoverflow.com/questions/19162812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2843234/" ]
``` dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']}, {'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']}, {'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']}, {'plat': 'centOs', 'val':['', '', '', '', '', '202', '', '']}, {'plat': 'ubu...
``` from itertools import izip from operator import itemgetter # create an iterator over columns columns = izip(*(d['val'] for d in dl)) # make function keeps non-empty columns keepfunc = itemgetter(*(i for i, c in enumerate(columns) if any(c))) # apply function to each list for d in dl: d['val'] = list(keepfunc...
19,162,812
I have a python data structure like this ``` dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']}, {'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']}, {'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']}, {'plat': 'centOs', 'val':['', '', ''...
2013/10/03
[ "https://Stackoverflow.com/questions/19162812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2843234/" ]
Let's do this in two steps. First, find indices to remove: ``` lists = [e['val'] for e in dl] idx_to_remove = [i for i, elem in enumerate(map(any, zip(*lists))) if not elem] ``` Second, let's filter original lists: ``` for l in lists: l[:] = [elem for i, elem in enumerate(l) if i not in idx_to_remove] ``` Res...
``` from itertools import izip from operator import itemgetter # create an iterator over columns columns = izip(*(d['val'] for d in dl)) # make function keeps non-empty columns keepfunc = itemgetter(*(i for i, c in enumerate(columns) if any(c))) # apply function to each list for d in dl: d['val'] = list(keepfunc...
19,162,812
I have a python data structure like this ``` dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']}, {'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']}, {'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']}, {'plat': 'centOs', 'val':['', '', ''...
2013/10/03
[ "https://Stackoverflow.com/questions/19162812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2843234/" ]
Let's do this in two steps. First, find indices to remove: ``` lists = [e['val'] for e in dl] idx_to_remove = [i for i, elem in enumerate(map(any, zip(*lists))) if not elem] ``` Second, let's filter original lists: ``` for l in lists: l[:] = [elem for i, elem in enumerate(l) if i not in idx_to_remove] ``` Res...
``` dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']}, {'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']}, {'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']}, {'plat': 'centOs', 'val':['', '', '', '', '', '202', '', '']}, {'plat': 'ubu...
19,162,812
I have a python data structure like this ``` dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']}, {'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']}, {'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']}, {'plat': 'centOs', 'val':['', '', ''...
2013/10/03
[ "https://Stackoverflow.com/questions/19162812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2843234/" ]
``` dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']}, {'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']}, {'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']}, {'plat': 'centOs', 'val':['', '', '', '', '', '202', '', '']}, {'plat': 'ubu...
Yet another possible solution (not really efficient but well...). `zip()` is really underrated... ``` # extract the values as a list of list vals = [item["val"] for item in dl] # transpose lines to columns cols = map(list, zip(*lines)) # filter out empty columns cols = [c for c in cols if filter(None, c)] # retranspos...
19,162,812
I have a python data structure like this ``` dl= [{'plat': 'unix', 'val':['', '', '1ju', '', '', '202', '', '']}, {'plat': 'Ios', 'val':['', '', '', '', 'Ty', '', 'Jk', '']}, {'plat': 'NT', 'val':['', '', 1, '', '' , '202', '', '']}, {'plat': 'centOs', 'val':['', '', ''...
2013/10/03
[ "https://Stackoverflow.com/questions/19162812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2843234/" ]
Let's do this in two steps. First, find indices to remove: ``` lists = [e['val'] for e in dl] idx_to_remove = [i for i, elem in enumerate(map(any, zip(*lists))) if not elem] ``` Second, let's filter original lists: ``` for l in lists: l[:] = [elem for i, elem in enumerate(l) if i not in idx_to_remove] ``` Res...
Yet another possible solution (not really efficient but well...). `zip()` is really underrated... ``` # extract the values as a list of list vals = [item["val"] for item in dl] # transpose lines to columns cols = map(list, zip(*lines)) # filter out empty columns cols = [c for c in cols if filter(None, c)] # retranspos...
40,701,398
I am trying to figure out how to take the following for loop that splits an array based on the index of the lowest value in the row and use vectorization. I've looked at this [link](https://www.safaribooksonline.com/library/view/python-for-data/9781449323592/ch04.html) and have been trying to use the numpy.where functi...
2016/11/20
[ "https://Stackoverflow.com/questions/40701398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5025845/" ]
First, use `argsort` to see where the lowest value in each row is: ``` >>> a.argsort(axis=1) array([[0, 1, 2], [0, 1, 2], [0, 1, 2], [1, 0, 2], [1, 0, 2], [1, 0, 2], [2, 1, 0], [2, 1, 0], [2, 1, 0]]) ``` Note that wherever a row has `0`, that is the smallest c...
This is not the best solution since it relies on simple python loops and is not very efficient when you start dealing with large data sets but it should get you started. The point is to create an array of "buckets" which store the data based on the depth of the lengthiest element. Then enumerate each element in `val...
40,701,398
I am trying to figure out how to take the following for loop that splits an array based on the index of the lowest value in the row and use vectorization. I've looked at this [link](https://www.safaribooksonline.com/library/view/python-for-data/9781449323592/ch04.html) and have been trying to use the numpy.where functi...
2016/11/20
[ "https://Stackoverflow.com/questions/40701398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5025845/" ]
First, use `argsort` to see where the lowest value in each row is: ``` >>> a.argsort(axis=1) array([[0, 1, 2], [0, 1, 2], [0, 1, 2], [1, 0, 2], [1, 0, 2], [1, 0, 2], [2, 1, 0], [2, 1, 0], [2, 1, 0]]) ``` Note that wherever a row has `0`, that is the smallest c...
I found a much easier way to do this. I hope that I am interpreting the OP correctly. My sense is that the OP wants to create a slice of the larger array based upon some set of conditions. Note that the code above to create the array does not seem to work--at least in python 3.5. I generated the array as follow. `...
66,776,644
My freelance client is giving FTP access to the shared hosting, I am new to web development and can't figure out how to deploy the flask app to cgi-bin folder, please help me understand how this works? ``` .htaccess file RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f # Don't interfere with static files RewriteR...
2021/03/24
[ "https://Stackoverflow.com/questions/66776644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13993581/" ]
First create a python script which will contain: ```py import sys import subprocess # implement pip as a subprocess: subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'flask']) ``` And then follow the instructions given by **Hostgator**. Please mark it as an answer if it is helpful! [![Rajdeep, a Ful...
Sorry but the Flask hosting can't be done within Shared-Hosting. You need **DigitalOcean** or **Heroku** or **PythonAnywhere**(easiest) Hosting to deploy a **Flask**/**Django** Website.
48,044,680
I have a problem with python that is I want to generate a multidict like the one below, using a for loop. Numbers are generated randomly and if the two elements are the same, the value if 0. ``` arcs, capacity = multidict({ (0, 0): 0, (0, 1): 80, (0, 2): 11, (1, 0): 15, (1, 1): 0, (1, 2): 120 (2, 0...
2017/12/31
[ "https://Stackoverflow.com/questions/48044680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Unit tests call functions that they test. You want to know if a function F called by a unit test can eventually invoke malloc (or new or ...). Seems like what you really want to do is build a call graph for your entire system, and then ask for the critical functions F whether F can reach malloc etc. in the call graph. ...
If you're using libraries which invoke malloc, then you might want to take a look at the [Joint Strike Fighter C++ Coding Standards](http://www.stroustrup.com/JSF-AV-rules.pdf). It's a coding style aimed towards mission critical software. One suggestion would be to write your own allocator(s). Another suggestion is to ...
48,044,680
I have a problem with python that is I want to generate a multidict like the one below, using a for loop. Numbers are generated randomly and if the two elements are the same, the value if 0. ``` arcs, capacity = multidict({ (0, 0): 0, (0, 1): 80, (0, 2): 11, (1, 0): 15, (1, 1): 0, (1, 2): 120 (2, 0...
2017/12/31
[ "https://Stackoverflow.com/questions/48044680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Unit tests call functions that they test. You want to know if a function F called by a unit test can eventually invoke malloc (or new or ...). Seems like what you really want to do is build a call graph for your entire system, and then ask for the critical functions F whether F can reach malloc etc. in the call graph. ...
This is not a full answer but you can try to use Valgrind to count allocs and frees. The default Valgrind tool memcheck by default counts the number of allocs and frees and prints resulting report in `HEAP SUMMARY`, here is a sample output: ``` $ valgrind ./a.out ==2653== Memcheck, a memory error detector ==2653== Cop...
48,044,680
I have a problem with python that is I want to generate a multidict like the one below, using a for loop. Numbers are generated randomly and if the two elements are the same, the value if 0. ``` arcs, capacity = multidict({ (0, 0): 0, (0, 1): 80, (0, 2): 11, (1, 0): 15, (1, 1): 0, (1, 2): 120 (2, 0...
2017/12/31
[ "https://Stackoverflow.com/questions/48044680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Unit tests call functions that they test. You want to know if a function F called by a unit test can eventually invoke malloc (or new or ...). Seems like what you really want to do is build a call graph for your entire system, and then ask for the critical functions F whether F can reach malloc etc. in the call graph. ...
In case you are using the GNU C library, you can use the `_malloc_hook ()` and alike functions to have a user-defined function called whenever one of the functions of the `malloc` family is used. Such a hooked function could analyse the call trace (using `backtrace()`) in order to find whether `malloc` was allowed in ...
7,076,254
I have a program which deals with nested data structures where the underlying type usually ends up being a decimal. e.g. ``` x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...} ``` Is there a simple pythonic way to print such a variable but rounding all floats to (say) 3dp and not assuming a par...
2011/08/16
[ "https://Stackoverflow.com/questions/7076254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/768552/" ]
This will recursively descend dicts, tuples, lists, etc. formatting numbers and leaving other stuff alone. ``` import collections import numbers def pformat(thing, formatfunc): if isinstance(thing, dict): return type(thing)((key, pformat(value, formatfunc)) for key, value in thing.iteritems()) if isins...
``` >>> b = [] >>> x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]]} >>> for i in x.get('a'): if type(i) == type([]): for y in i: print("%0.3f"%(float(y))) else: print("%0.3f"%(float(i))) 1.056 2.346 1.111 10.000 ``` The proble...
7,076,254
I have a program which deals with nested data structures where the underlying type usually ends up being a decimal. e.g. ``` x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...} ``` Is there a simple pythonic way to print such a variable but rounding all floats to (say) 3dp and not assuming a par...
2011/08/16
[ "https://Stackoverflow.com/questions/7076254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/768552/" ]
A simple approach assuming you have lists of floats: ``` >>> round = lambda l: [float('%.3g' % e) if type(e) != list else round(e) for e in l] >>> print {k:round(v) for k,v in x.iteritems()} {'a': [1.06, 2.35, [1.11, 10.0]]} ```
``` >>> b = [] >>> x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]]} >>> for i in x.get('a'): if type(i) == type([]): for y in i: print("%0.3f"%(float(y))) else: print("%0.3f"%(float(i))) 1.056 2.346 1.111 10.000 ``` The proble...
7,076,254
I have a program which deals with nested data structures where the underlying type usually ends up being a decimal. e.g. ``` x={'a':[1.05600000001,2.34581736481,[1.1111111112,9.999990111111]],...} ``` Is there a simple pythonic way to print such a variable but rounding all floats to (say) 3dp and not assuming a par...
2011/08/16
[ "https://Stackoverflow.com/questions/7076254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/768552/" ]
This will recursively descend dicts, tuples, lists, etc. formatting numbers and leaving other stuff alone. ``` import collections import numbers def pformat(thing, formatfunc): if isinstance(thing, dict): return type(thing)((key, pformat(value, formatfunc)) for key, value in thing.iteritems()) if isins...
A simple approach assuming you have lists of floats: ``` >>> round = lambda l: [float('%.3g' % e) if type(e) != list else round(e) for e in l] >>> print {k:round(v) for k,v in x.iteritems()} {'a': [1.06, 2.35, [1.11, 10.0]]} ```
49,883,687
How to close a file if it is already open? ``` import xlwings as xw wb = xw.Book(folderpath + 'Metrics - auto.xlsx') ``` Using try:except: but need a way to close the file so it can be opened, or find the file and work with it? I get this error if it's already open: ``` wb = xw.Book(folderpath + 'Metrics - auto....
2018/04/17
[ "https://Stackoverflow.com/questions/49883687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3664733/" ]
You can check the workbook collection with ``` import xlwings as xw xw.books ``` and check if your fullname is already open using something like: ``` if myworkbook in [i.fullname for i in xw.books]: ... ```
I have no experience with the xlwings package, but looking at the [source code](https://github.com/ZoomerAnalytics/xlwings/blob/master/xlwings/main.py) for `Book.__init__`, it looks like it automatically looks for any instances of the work book that are already open. If there is only one, then it returns it. If there i...
35,692,537
I want to scan some websites and would like to get all the java script files names and content.I tried python requests with BeautifulSoup but wasn't able to get the scripts details and contents.am I missing something ? I have been trying lot of methods to find but I felt like stumbling in the dark. This is the code I ...
2016/02/29
[ "https://Stackoverflow.com/questions/35692537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5478079/" ]
You can get all the linked JavaScript code use the below code: ``` l = [i.get('src') for i in soup.find_all('script') if i.get('src')] ``` * `soup.find_all('script')` returns a list of all the `<script>` tags in the page. * A [*list comprehension*](https://stackoverflow.com/questions/34835951/) is used here to loop...
You can use a select with `script[src]` which will only find script tags with a src, you don't need to call .get multiple times: ``` import requests from bs4 import BeautifulSoup r = requests.get("http://www.marunadanmalayali.com/") soup = BeautifulSoup(r.content) src = [sc["src"] for sc in soup.select("script[src]"...
71,443,087
i'm struggling to debug my python code with regex in PyCharm. The idea: I want to find any case of 'here we are', which can go with or without 'attention', and the word 'attention' can be separated by whitespace, dot, comma, exclamation mark. I expect this expression should do the job ``` r'(attention.{0,2})?here we...
2022/03/11
[ "https://Stackoverflow.com/questions/71443087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15769721/" ]
I would assume that you're using class components, so the solution I would provide is for that. First step is to import ConnectedProps: ``` import { connect, ConnectedProps } from 'react-redux' ``` Next step is to define the objects that your state/reducer, so in a file that we can name `TsConnector.ts`, add someth...
Have you tried `useDispatch` and `useSelector` in ts file to get redux state ``` import { useSelector as useReduxSelector, TypedUseSelectorHook, } from 'react-redux' export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector ```
3,878,195
The Python [logging module](http://docs.python.org/library/logging.html) is cumbersome to use. Is there a more elegant alternative? Integration with desktop notifications would be a plus.
2010/10/07
[ "https://Stackoverflow.com/questions/3878195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105066/" ]
You can look into [Twiggy](https://github.com/wearpants/twiggy), it's an early stage attempt to build a more pythonic alternative to the logging module.
``` #!/usr/bin/env python # -*- coding: utf-8 -*- import logging import logging.handlers from logging.config import dictConfig logger = logging.getLogger(__name__) DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, } def configure_logging(logfile_path): """ Initialize logging defaul...
3,878,195
The Python [logging module](http://docs.python.org/library/logging.html) is cumbersome to use. Is there a more elegant alternative? Integration with desktop notifications would be a plus.
2010/10/07
[ "https://Stackoverflow.com/questions/3878195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105066/" ]
You can look into [Twiggy](https://github.com/wearpants/twiggy), it's an early stage attempt to build a more pythonic alternative to the logging module.
You might want to have a look at [pysimplelog](http://bachiraoun.github.io/pysimplelog/). It's pure python, very simple to use, pip installable and provides what you need ``` from pysimplelog import Logger L=Logger() print L >>> Logger (Version 0.2.1) >>> log type |log name |level |std flag |file flag | >>> ---...
3,878,195
The Python [logging module](http://docs.python.org/library/logging.html) is cumbersome to use. Is there a more elegant alternative? Integration with desktop notifications would be a plus.
2010/10/07
[ "https://Stackoverflow.com/questions/3878195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105066/" ]
You can look into [Twiggy](https://github.com/wearpants/twiggy), it's an early stage attempt to build a more pythonic alternative to the logging module.
Checkout [logbook](https://github.com/getlogbook/logbook), it is much nicer to work with. Logbook was mentioned in a comment but it deserves its own answer.
3,878,195
The Python [logging module](http://docs.python.org/library/logging.html) is cumbersome to use. Is there a more elegant alternative? Integration with desktop notifications would be a plus.
2010/10/07
[ "https://Stackoverflow.com/questions/3878195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105066/" ]
You might want to have a look at [pysimplelog](http://bachiraoun.github.io/pysimplelog/). It's pure python, very simple to use, pip installable and provides what you need ``` from pysimplelog import Logger L=Logger() print L >>> Logger (Version 0.2.1) >>> log type |log name |level |std flag |file flag | >>> ---...
``` #!/usr/bin/env python # -*- coding: utf-8 -*- import logging import logging.handlers from logging.config import dictConfig logger = logging.getLogger(__name__) DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, } def configure_logging(logfile_path): """ Initialize logging defaul...
3,878,195
The Python [logging module](http://docs.python.org/library/logging.html) is cumbersome to use. Is there a more elegant alternative? Integration with desktop notifications would be a plus.
2010/10/07
[ "https://Stackoverflow.com/questions/3878195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105066/" ]
Checkout [logbook](https://github.com/getlogbook/logbook), it is much nicer to work with. Logbook was mentioned in a comment but it deserves its own answer.
``` #!/usr/bin/env python # -*- coding: utf-8 -*- import logging import logging.handlers from logging.config import dictConfig logger = logging.getLogger(__name__) DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, } def configure_logging(logfile_path): """ Initialize logging defaul...
3,878,195
The Python [logging module](http://docs.python.org/library/logging.html) is cumbersome to use. Is there a more elegant alternative? Integration with desktop notifications would be a plus.
2010/10/07
[ "https://Stackoverflow.com/questions/3878195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105066/" ]
Checkout [logbook](https://github.com/getlogbook/logbook), it is much nicer to work with. Logbook was mentioned in a comment but it deserves its own answer.
You might want to have a look at [pysimplelog](http://bachiraoun.github.io/pysimplelog/). It's pure python, very simple to use, pip installable and provides what you need ``` from pysimplelog import Logger L=Logger() print L >>> Logger (Version 0.2.1) >>> log type |log name |level |std flag |file flag | >>> ---...
64,913,140
As per the [documentation](https://docs.python.org/3/reference/datamodel.html#object.__bool__), every class has a default `__bool__` that returns `true`. Is there a way to "remove" this default behaviour so that it raises an error when used as bool (for instance in a expression like `if obj`? And especially, is there...
2020/11/19
[ "https://Stackoverflow.com/questions/64913140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4444546/" ]
you can use Array map function on **option.selectedOption** too just like: ``` {restaurant.map((option, marker) => ( <p key={marker.id}> {option.selectedOption.map((optn, index) => ( <strong key={index}> {optn.label + ', '} ...
You should do that instead: ``` {restaurant.map((option, marker) => ( <p key={marker.id}> <strong> {option.selectedOption.reduce(labels, label, index => labels += `${index > 0 ? ', ' : ''}${label}`, '')} </strong> </p> ))} ``` The array function `reduce()` allow you to (as the na...