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
24,044,734
I'm looking for a way to use pandas and python to combine several columns in an excel sheet with known column names into a new, single one, keeping all the important information as in the example below: input: ``` ID,tp_c,tp_b,tp_p 0,transportation - cars,transportation - boats,transportation - planes 1,checked,-,...
2014/06/04
[ "https://Stackoverflow.com/questions/24044734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3700450/" ]
OK a more dynamic method: ``` In [63]: # get a list of the columns col_list = list(df.columns) # remove 'ID' column col_list.remove('ID') # create a dict as a lookup col_dict = dict(zip(col_list, [df.iloc[0][col].split(' - ')[1] for col in col_list])) col_dict Out[63]: {'tp_b': 'boats', 'tp_c': 'cars', 'tp_p': 'planes...
Here is one way: ``` newCol = pandas.Series('',index=d.index) for col in d.ix[:, 1:]: name = '+' + col.split('-')[1].strip() newCol[d[col]=='checked'] += name newCol = newCol.str.strip('+') ``` Then: ``` >>> newCol 0 cars 1 boats 2 cars+boats 3 boats+planes 4...
24,044,734
I'm looking for a way to use pandas and python to combine several columns in an excel sheet with known column names into a new, single one, keeping all the important information as in the example below: input: ``` ID,tp_c,tp_b,tp_p 0,transportation - cars,transportation - boats,transportation - planes 1,checked,-,...
2014/06/04
[ "https://Stackoverflow.com/questions/24044734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3700450/" ]
This is quite interesting as it's a reverse `get_dummies`... I think I would manually munge the column names so that you have a boolean DataFrame: ``` In [11]: df1 # df == 'checked' Out[11]: cars boats planes 0 1 True False False 2 False True False 3 True True False 4 False True True 5 True ...
Here is one way: ``` newCol = pandas.Series('',index=d.index) for col in d.ix[:, 1:]: name = '+' + col.split('-')[1].strip() newCol[d[col]=='checked'] += name newCol = newCol.str.strip('+') ``` Then: ``` >>> newCol 0 cars 1 boats 2 cars+boats 3 boats+planes 4...
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
Firstly, you are using **imgpt1** in every case which should not be the scenario. Rather use ``` v.getTag.equals("xxx") ``` After resolving that try to use the best android practice for comparison of strings. Best practice while checking the strings in android(Java) first check the null and empty string using ```...
You should check the tag of the `view` not the static item as they will be always true! look at your first condition. `imgpt1` tag is "`frontbumpers`" thus that condition is always true! hence it shows the same message every time. ``` @Override public void onClick(View v) { String message=""; //for y...
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
Try this If You have to check Strings use **.equals()** ,in case of int use **==** ``` if(imgpt1.getTag().equals("frontbumpers")) { message="This is Bumper"; } else if(imgpt1.getTag().equals("frontfenders")) { message="This is Fenders"; } else if(imgpt1.getTag().equals("frontheadlight")) { message="Th...
Use `imgpt1.getTag().equals("string")` instead of `imgpt1.getTag()=="string"` **Try this:** ``` @Override public void onClick(View v) { String message=""; if(imgpt1.getTag().equals("frontbumpers")) { message="This is Bumper"; } else if(imgpt1.getTag().equals("frontfenders")) { ...
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
Firstly, you are using **imgpt1** in every case which should not be the scenario. Rather use ``` v.getTag.equals("xxx") ``` After resolving that try to use the best android practice for comparison of strings. Best practice while checking the strings in android(Java) first check the null and empty string using ```...
Use `imgpt1.getTag().equals("string")` instead of `imgpt1.getTag()=="string"` **Try this:** ``` @Override public void onClick(View v) { String message=""; if(imgpt1.getTag().equals("frontbumpers")) { message="This is Bumper"; } else if(imgpt1.getTag().equals("frontfenders")) { ...
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
In `onClick` use `imgpt1.getTag().equals("frontgrilles")` **instead of** ``` imgpt1.getTag()=="frontgrilles" ```
Use `imgpt1.getTag().equals("string")` instead of `imgpt1.getTag()=="string"` **Try this:** ``` @Override public void onClick(View v) { String message=""; if(imgpt1.getTag().equals("frontbumpers")) { message="This is Bumper"; } else if(imgpt1.getTag().equals("frontfenders")) { ...
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
In `onClick` use `imgpt1.getTag().equals("frontgrilles")` **instead of** ``` imgpt1.getTag()=="frontgrilles" ```
You should check the tag of the `view` not the static item as they will be always true! look at your first condition. `imgpt1` tag is "`frontbumpers`" thus that condition is always true! hence it shows the same message every time. ``` @Override public void onClick(View v) { String message=""; //for y...
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
Firstly, you are using **imgpt1** in every case which should not be the scenario. Rather use ``` v.getTag.equals("xxx") ``` After resolving that try to use the best android practice for comparison of strings. Best practice while checking the strings in android(Java) first check the null and empty string using ```...
In `onClick` use `imgpt1.getTag().equals("frontgrilles")` **instead of** ``` imgpt1.getTag()=="frontgrilles" ```
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
Firstly, you are using **imgpt1** in every case which should not be the scenario. Rather use ``` v.getTag.equals("xxx") ``` After resolving that try to use the best android practice for comparison of strings. Best practice while checking the strings in android(Java) first check the null and empty string using ```...
Try this If You have to check Strings use **.equals()** ,in case of int use **==** ``` if(imgpt1.getTag().equals("frontbumpers")) { message="This is Bumper"; } else if(imgpt1.getTag().equals("frontfenders")) { message="This is Fenders"; } else if(imgpt1.getTag().equals("frontheadlight")) { message="Th...
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
You should check the tag of the `view` not the static item as they will be always true! look at your first condition. `imgpt1` tag is "`frontbumpers`" thus that condition is always true! hence it shows the same message every time. ``` @Override public void onClick(View v) { String message=""; //for y...
Use `imgpt1.getTag().equals("string")` instead of `imgpt1.getTag()=="string"` **Try this:** ``` @Override public void onClick(View v) { String message=""; if(imgpt1.getTag().equals("frontbumpers")) { message="This is Bumper"; } else if(imgpt1.getTag().equals("frontfenders")) { ...
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
In onClick method, you used first image for all if else conditions, that is why, no matter which image you click, it'll show first image message. ``` String message=""; if(**imgpt1.getTag()**=="frontbumpers") { message="This is Bumper"; } else if(**imgpt1.getTag()**=="frontfenders") { ...
Use `imgpt1.getTag().equals("string")` instead of `imgpt1.getTag()=="string"` **Try this:** ``` @Override public void onClick(View v) { String message=""; if(imgpt1.getTag().equals("frontbumpers")) { message="This is Bumper"; } else if(imgpt1.getTag().equals("frontfenders")) { ...
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
Try this If You have to check Strings use **.equals()** ,in case of int use **==** ``` if(imgpt1.getTag().equals("frontbumpers")) { message="This is Bumper"; } else if(imgpt1.getTag().equals("frontfenders")) { message="This is Fenders"; } else if(imgpt1.getTag().equals("frontheadlight")) { message="Th...
In onClick method, you used first image for all if else conditions, that is why, no matter which image you click, it'll show first image message. ``` String message=""; if(**imgpt1.getTag()**=="frontbumpers") { message="This is Bumper"; } else if(**imgpt1.getTag()**=="frontfenders") { ...
17,659,010
I'm trying to use the ctypes module to call, from within a python program, a (fortran) library of linear algebra routines that I have written. I have successfully imported the library and can call my *subroutines* and functions that return a single value. My problem is calling functions that return an array of doubles....
2013/07/15
[ "https://Stackoverflow.com/questions/17659010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1733205/" ]
The compiler may return a pointer to the array, or the array descriptor... So, when mixing languages, you should always use `bind(C)` except when the wrapper specifically supports Fortran. And (not surprisingly) `bind(C)` functions cannot return arrays. You could theoretically allocate the array and return `type(c_ptr)...
With gfortran the function call has a hidden argument: ``` >>> from ctypes import * >>> testlib = CDLL('./libutils.so') >>> cross = testlib.cross_product_ >>> a = (c_double * 3)(*[0.0, 1.0, 2.0]) >>> b = (c_double * 3)(*[1.0, 3.0, 2.0]) >>> c = (c_double * 3)() >>> pc = pointer(c) >>> cross(byref(pc), a, b) 3 >>> c[...
5,762,766
I've created a little helper application using Python and GTK. I've never used GTK before. As per the comment on <http://www.pygtk.org/> I used the PyGObject interface. Now I would like to add spell checking to my Gtk.TextBuffer. I found a library called GtkSpell and an associated python-gtkspell in the package manag...
2011/04/23
[ "https://Stackoverflow.com/questions/5762766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471/" ]
I wrote one, yesterday because I had the same problem, so it's a bit alpha but it works fine. You could get the source from: <https://github.com/koehlma/pygtkspellcheck>. It requires [pyenchant](http://packages.python.org/pyenchant/) and I only test it with Python 3 on Archlinux. If something doesn't work feel free to ...
I'm afraid that the PyGObject interface is new enough that GtkSpell hasn't been updated to use it yet. As far as I know there is no other premade GTK spell checker.
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
Maybe your code is outdated. For anyone who aims to use `fetch_mldata` in digit handwritten project, you should `fetch_openml` instead. ([link](https://stackoverflow.com/questions/47324921/cant-load-mnist-original-dataset-using-sklearn/52297457)) In old version of sklearn: ``` from sklearn.externals import joblib mni...
When getting error: **from sklearn.externals import joblib** it deprecated older version. For new version follow: 1. conda install -c anaconda scikit-learn (install using "Anaconda Promt") 2. import joblib (Jupyter Notebook)
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
It looks like your existing pickle save file (`model_d2v_version_002`) encodes a reference module in a non-standard location – a `joblib` that's in `sklearn.externals.joblib` rather than at top-level. The current `scikit-learn` documentation only talks about a top-level `joblib` – eg in [3.4.1 Persistence example](ht...
for this error, I had to directly use the following and it worked like a charm: ``` import joblib ``` Simple
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
You should directly use ``` import joblib ``` instead of ``` from sklearn.externals import joblib ```
I had the same problem What I did not realize was that joblib *was already installed!* so what you have to do is replace ``` from sklearn.externals import joblib ``` with ``` import joblib ``` and that is it
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
It looks like your existing pickle save file (`model_d2v_version_002`) encodes a reference module in a non-standard location – a `joblib` that's in `sklearn.externals.joblib` rather than at top-level. The current `scikit-learn` documentation only talks about a top-level `joblib` – eg in [3.4.1 Persistence example](ht...
Maybe your code is outdated. For anyone who aims to use `fetch_mldata` in digit handwritten project, you should `fetch_openml` instead. ([link](https://stackoverflow.com/questions/47324921/cant-load-mnist-original-dataset-using-sklearn/52297457)) In old version of sklearn: ``` from sklearn.externals import joblib mni...
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
When getting error: **from sklearn.externals import joblib** it deprecated older version. For new version follow: 1. conda install -c anaconda scikit-learn (install using "Anaconda Promt") 2. import joblib (Jupyter Notebook)
After a long investigation, given my computer setup, I've found that was because an SSL certificate was required to download the dataset.
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
none of the answers below works for me, with a little changes this modification was ok for me ``` import sklearn.externals as extjoblib import joblib ```
After a long investigation, given my computer setup, I've found that was because an SSL certificate was required to download the dataset.
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
You should directly use ``` import joblib ``` instead of ``` from sklearn.externals import joblib ```
none of the answers below works for me, with a little changes this modification was ok for me ``` import sklearn.externals as extjoblib import joblib ```
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
You can import `joblib` directly by installing it as a dependency and using `import joblib`, [Documentation](https://joblib.readthedocs.io/en/latest/).
I had the same problem What I did not realize was that joblib *was already installed!* so what you have to do is replace ``` from sklearn.externals import joblib ``` with ``` import joblib ``` and that is it
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
It looks like your existing pickle save file (`model_d2v_version_002`) encodes a reference module in a non-standard location – a `joblib` that's in `sklearn.externals.joblib` rather than at top-level. The current `scikit-learn` documentation only talks about a top-level `joblib` – eg in [3.4.1 Persistence example](ht...
You can import `joblib` directly by installing it as a dependency and using `import joblib`, [Documentation](https://joblib.readthedocs.io/en/latest/).
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
You can import `joblib` directly by installing it as a dependency and using `import joblib`, [Documentation](https://joblib.readthedocs.io/en/latest/).
none of the answers below works for me, with a little changes this modification was ok for me ``` import sklearn.externals as extjoblib import joblib ```
65,590,149
I am trying to make a python script that will make payment automatically on [this](https://www.audiobooks.com/signup) site. I am able to get credit-card-number input but i can't access expirty month or CVV. **Code I tried** I used this to get credit card number field below ``` WebDriverWait(browser, 20).until(EC....
2021/01/06
[ "https://Stackoverflow.com/questions/65590149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10830982/" ]
if you switch to one iframe you have to swithc to default content before you can interact with another iframe outside the current iframe in which the code focus is use ``` WebDriverWait(browser, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='braintree-hosted-field-number']"))) WebDriverWa...
[![Try switch first, then catch the xpath](https://i.stack.imgur.com/Pp7gY.png)](https://i.stack.imgur.com/Pp7gY.png) Try to switch to the iframe first, then you can identify the column with xpath
65,590,149
I am trying to make a python script that will make payment automatically on [this](https://www.audiobooks.com/signup) site. I am able to get credit-card-number input but i can't access expirty month or CVV. **Code I tried** I used this to get credit card number field below ``` WebDriverWait(browser, 20).until(EC....
2021/01/06
[ "https://Stackoverflow.com/questions/65590149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10830982/" ]
Frame id was off and the xpath was also off cause no expirationMonth. Also switch to default content. ``` browser.get("https://www.audiobooks.com/signup") wait = WebDriverWait(browser, 10) wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID,"braintree-hosted-field-number"))) wait.until(EC.element_to_be_clickab...
[![Try switch first, then catch the xpath](https://i.stack.imgur.com/Pp7gY.png)](https://i.stack.imgur.com/Pp7gY.png) Try to switch to the iframe first, then you can identify the column with xpath
54,058,184
I'm new to GCS and Cloud Functions and would like to understand how I can do an lightweight ETL using these two technologies combined with Python (3.7). I have a GCS bucket called 'Test\_1233' containing 3 files (all structurally identical). When a new file is added to this gcs bucket, I would like the following pyth...
2019/01/06
[ "https://Stackoverflow.com/questions/54058184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7638546/" ]
``` document.getElementById("loginField").getAttribute("name") ```
You can easily get it by attr method: ``` var name = $("#id").attr("name"); ```
23,653,147
I need to run a command as a different user in the %post section of an RPM. At the moment I am using a bit of a hack via python but it can't be the best way (it does feel a little dirty) ... ``` %post -p /usr/bin/python import os, pwd, subprocess os.setuid(pwd.getpwnam('apache')[2]) subprocess.call(['/usr/bin/somethi...
2014/05/14
[ "https://Stackoverflow.com/questions/23653147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2245703/" ]
If `/usr/bin/something` is something you are installing as part of the package, install it with something like ``` attr(4755, apache, apache) /usr/bin/something ``` When installed like this, `/usr/bin/something` will *always* run as user `apache`, regardless of what user actually runs it.
The accepted answer here is wrong IMO. It is not often at all you want to set attributes to allow *anyone* execute something as the owner. If you want to run something as a specific user, and that user doesn't have a shell set, you can use `su -s` to set the shell to use. For example: `su -s /bin/bash apache -c "/usr...
7,988,772
I have already created a 64-bit program for windows using cx freeze on a 64-bit machine. I am using Windows 7 64-bit Home premium. py2exe is not working because as i understand it does not work with python 3.2.2 yet. Is there an option i have to specify in cx freeze to compile in 32-bit instead of 64-bit. Thanks!
2011/11/02
[ "https://Stackoverflow.com/questions/7988772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1026738/" ]
To produce 32 bit executables you need to install 32-bit versions of Python and cx\_freeze.
All the "produce an executable from Python code" methods I know of basically create a file that bundles up the Python interpreter with the Python code you want to execute inside a single file. It is nothing at all like compiling C code to an executable; Python is just about impossible to compile to machine code in any ...
7,988,772
I have already created a 64-bit program for windows using cx freeze on a 64-bit machine. I am using Windows 7 64-bit Home premium. py2exe is not working because as i understand it does not work with python 3.2.2 yet. Is there an option i have to specify in cx freeze to compile in 32-bit instead of 64-bit. Thanks!
2011/11/02
[ "https://Stackoverflow.com/questions/7988772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1026738/" ]
To produce 32 bit executables you need to install 32-bit versions of Python and cx\_freeze.
In addition to the answers already given: 1. To compile/freeze python code for different architectures (x86/x64), **install** both, **x86 and x64 versions of python**, to your system and corresponding variations of **all required modules and libraries** to your python installations so both installations have the same ...
7,988,772
I have already created a 64-bit program for windows using cx freeze on a 64-bit machine. I am using Windows 7 64-bit Home premium. py2exe is not working because as i understand it does not work with python 3.2.2 yet. Is there an option i have to specify in cx freeze to compile in 32-bit instead of 64-bit. Thanks!
2011/11/02
[ "https://Stackoverflow.com/questions/7988772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1026738/" ]
In addition to the answers already given: 1. To compile/freeze python code for different architectures (x86/x64), **install** both, **x86 and x64 versions of python**, to your system and corresponding variations of **all required modules and libraries** to your python installations so both installations have the same ...
All the "produce an executable from Python code" methods I know of basically create a file that bundles up the Python interpreter with the Python code you want to execute inside a single file. It is nothing at all like compiling C code to an executable; Python is just about impossible to compile to machine code in any ...
41,448,447
I am trying to run a **list of tasks** (*here running airflow but it could be anything really*) that require to be executed in a existing Conda environment. I would like to do these tasks: ``` - name: activate conda environment # does not work, just for the sake of understanding command: source activate my_conda_e...
2017/01/03
[ "https://Stackoverflow.com/questions/41448447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7370442/" ]
Each of your commands will be executed in a different process. `source` command, on the other hand, is used for reading the environment variables into the current process only (and its children), so it will apply only to the `activate conda environment` task. What you can try to do is: ``` - name: initialize the dat...
Was looking out for something similar. Found a neater solution than having multiple actions: ``` - name: Run commands in conda environment shell: source activate my_conda_env && airflow {{ item }} with_items: - initdb - webserver -p {{ airflow_webserver_port }} - scheduler ```
51,273,827
I thought I read somewhere that python (3.x at least) is smart enough to handle this: ``` x = 1.01 if 1 < x < 0: print('out of range!') ``` However it is not working for me. I know I can use this instead: ``` if ((x > 1) | (x < 0)): print('out of range!') ``` ... but is it possible to fix the version ab...
2018/07/10
[ "https://Stackoverflow.com/questions/51273827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3126298/" ]
It works well, it is your expression that is always False; try this one instead: ``` x = .99 if 1 > x > 0: print('out of range!') ```
You can do it in one *compound* expression, as you've already noted, and others have commented. You cannot do it in an expression with an implied conjunction (and / or), as you're trying to do with `1 < x < 0`. Your expression requires an `or` conjunction, but Python's implied operation in this case is `and`. Therefor...
51,273,827
I thought I read somewhere that python (3.x at least) is smart enough to handle this: ``` x = 1.01 if 1 < x < 0: print('out of range!') ``` However it is not working for me. I know I can use this instead: ``` if ((x > 1) | (x < 0)): print('out of range!') ``` ... but is it possible to fix the version ab...
2018/07/10
[ "https://Stackoverflow.com/questions/51273827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3126298/" ]
Python chained comparisons work like mathematical notation. In math, "0 < x < 1" means that x is greater than 0 **and** less than one, and "1 < x < 0" means that x is greater than 1 **and** less than 0. **And.** Not or. Both conditions need to hold. If you want an "or" , you can write one yourself. It's `or` in Pytho...
It works well, it is your expression that is always False; try this one instead: ``` x = .99 if 1 > x > 0: print('out of range!') ```
51,273,827
I thought I read somewhere that python (3.x at least) is smart enough to handle this: ``` x = 1.01 if 1 < x < 0: print('out of range!') ``` However it is not working for me. I know I can use this instead: ``` if ((x > 1) | (x < 0)): print('out of range!') ``` ... but is it possible to fix the version ab...
2018/07/10
[ "https://Stackoverflow.com/questions/51273827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3126298/" ]
Python chained comparisons work like mathematical notation. In math, "0 < x < 1" means that x is greater than 0 **and** less than one, and "1 < x < 0" means that x is greater than 1 **and** less than 0. **And.** Not or. Both conditions need to hold. If you want an "or" , you can write one yourself. It's `or` in Pytho...
You can do it in one *compound* expression, as you've already noted, and others have commented. You cannot do it in an expression with an implied conjunction (and / or), as you're trying to do with `1 < x < 0`. Your expression requires an `or` conjunction, but Python's implied operation in this case is `and`. Therefor...
63,739,587
I've been following along to [Corey Schafer's awesome youtube tutorial](https://www.youtube.com/watch?v=MwZwr5Tvyxo&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH) on the basic flaskblog. In addition to Corey's code, I`d like to add a logic, where users have to verify their email-address before being able to login. I've figur...
2020/09/04
[ "https://Stackoverflow.com/questions/63739587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13828684/" ]
The key to your question is this: > > My question is: how do I best identify the user (for whom to alter the email\_confirmed Column) when he clicks on his custom url? > > > The answer can be seen [in the example on URL safe serialisation using itsdangerous](https://itsdangerous.palletsprojects.com/en/1.1.x/url_s...
Thanks to @exhuma. Here is how I eventually got it to work - also in addition I'm posting the previously missing part of email-sending. **User Class in my models.py** ``` class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=Fal...
17,457,608
I'm trying to time several things in python, including upload time to Amazon's S3 Cloud Storage, and am having a little trouble. I can time my hash, and a few other things, but not the upload. I thought [this](https://stackoverflow.com/questions/7523767/how-to-use-python-timeit-when-passing-variables-to-functions) post...
2013/07/03
[ "https://Stackoverflow.com/questions/17457608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2407064/" ]
I know this is heresy in the Python community, but I actually recommend *not* to use `timeit`, especially for something like this. For your purposes, I believe it will be good enough (and possibly even better than `timeit`!) if you simply use `time.time()` to time things. In other words, do something like ``` from tim...
You can use the command line interface to `timeit`. Just save your code as a module without the timing stuff. For example: ``` # file: test.py data = range(5) def foo(l): return sum(l) ``` Then you can run the timing code from the command line, like this: ``` $ python -mtimeit -s 'import test;' 'test.foo(test....
48,344,035
**Scenario:** I am trying to work out a way to send a quick test message in skype with a python code. From the documentations (<https://pypi.python.org/pypi/SkPy/0.1>) I got a snippet that should allow me to do that. **Problem:** I refilled the information as expected, but I am getting an error when trying to create t...
2018/01/19
[ "https://Stackoverflow.com/questions/48344035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7321700/" ]
It might look like you have been blocked from your server's IP if you logged in elsewhere recently. This works for me. ``` from skpy import Skype loggedInUser = Skype("userName", "password") print(loggedInUser.users) // loggedIn user info print(loggedInUser.contacts) // loggedIn user contacts ...
try this: ``` def connect_skype(user, pwd, token): s = Skype(connect=False) s.conn.setTokenFile(token) try: s.conn.readToken() except SkypeAuthException: s.conn.setUserPwd(user, pwd) s.conn.getSkypeToken() s.conn.writeToken() finally: sk = Skype(user, pwd, to...
34,004,510
I'm a beginner in the Python language. Is there a "try and except" function in python to check if the input is a LETTER or multiple LETTERS. If it isn't, ask for an input again? (I made one in which you have to enter an integer number) ``` def validation(i): try: result = int(i) return(result) except ValueErro...
2015/11/30
[ "https://Stackoverflow.com/questions/34004510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5622261/" ]
You can just call the same function again, in the try/except clause - to do that, you'll have to adjust your logic a bit: ``` def validate_integer(): x = input('Please enter a number: ') try: int(x) except ValueError: print('Sorry, {} is not a valid number'.format(x)) return validate_integer...
Don't use recursion in Python when simple iteration will do. ``` def validate(i): try: result = int(i) return result except ValueError: pass def start(): z = None while z is None: x = input("Please enter a number: ") z = validate(x) print("Success") start(...
4,393,830
In the process of trying to write a Python script that uses PIL today, I discovered I don't seem have it on my local machine (OS X 10.5.8, default 2.5 Python install). So I run: ``` easy_install --prefix=/usr/local/python/ pil ``` and it complains a little about /usr/local/python/lib/python2.5/site-packages not yet...
2010/12/09
[ "https://Stackoverflow.com/questions/4393830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87170/" ]
You are using the Apple-supplied Python 2.5 in OS X; it's a framework build and, by default, uses `/Library/Python/2.5/site-packages` as the location for installed packages, not `/usr/local`. Normally you shouldn't need to specify `--prefix` with an OS X framework build. Also beware that the `setuptools` (`easy_install...
Why did you specify `--prefix` in your `easy_install` invocation? Did you try just: ``` sudo easy_install pil ``` If you're only trying to install PIL to the default location, I would think `easy_install` could work out the correct path. (Clearly, `/usr/local/python` isn't it...) **EDIT**: Someone down-voted this a...
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
The error means that you're navigating to a view whose model is declared as typeof `Foo` (by using `@model Foo`), but you actually passed it a model which is typeof `Bar` (note the term *dictionary* is used because a model is passed to the view via a `ViewDataDictionary`). The error can be caused by **Passing the wro...
**Passing the model value that is populated from a controller method to a view** ``` public async Task<IActionResult> Index() { //Getting Data from Database var model= await _context.GetData(); //Selecting Populated Data from the Model and passing to view return View(model.Value); } ```
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
The error means that you're navigating to a view whose model is declared as typeof `Foo` (by using `@model Foo`), but you actually passed it a model which is typeof `Bar` (note the term *dictionary* is used because a model is passed to the view via a `ViewDataDictionary`). The error can be caused by **Passing the wro...
one more thing. if your view is a partial/sub page and the model for that partial view is null for some reason (e.g no data) you will get this error. Just need to handle the null partial view model
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
This question already has a great answer, but I ran into the same error, in a different scenario: displaying a **`List`** in an *EditorTemplate*. I have a model like this: ``` public class Foo { public string FooName { get; set; } public List<Bar> Bars { get; set; } } public class Bar { public string Bar...
**Passing the model value that is populated from a controller method to a view** ``` public async Task<IActionResult> Index() { //Getting Data from Database var model= await _context.GetData(); //Selecting Populated Data from the Model and passing to view return View(model.Value); } ```
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
This question already has a great answer, but I ran into the same error, in a different scenario: displaying a **`List`** in an *EditorTemplate*. I have a model like this: ``` public class Foo { public string FooName { get; set; } public List<Bar> Bars { get; set; } } public class Bar { public string Bar...
Consider the partial `map.cshtml` at `Partials/Map.cshtml`. This can be called from the Page where the partial is to be rendered, simply by using the `<partial>` tag: `<partial name="Partials/Map" model="new Pages.Partials.MapModel()" />` This is one of the easiest methods I encountered (although I am using razor pag...
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
This question already has a great answer, but I ran into the same error, in a different scenario: displaying a **`List`** in an *EditorTemplate*. I have a model like this: ``` public class Foo { public string FooName { get; set; } public List<Bar> Bars { get; set; } } public class Bar { public string Bar...
First you need to return an IEnumerable version of your model to the list view. ``` @model IEnumerable<IdentityManager.Models.MerchantDetail> ``` Second, you need to return a list from the database. I am doing it via SQL Server, so this is code I got working. ``` public IActionResult Merchant_Boarding_List() ...
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
Observe if the view has the model required: **View** ``` @model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel> <div class="row"> <table class="table table-striped table-hover table-width-custom"> <thead> <tr> .... ``` **Controller** ``` [HttpGet] public ActionResult ListItems() { ...
**Passing the model value that is populated from a controller method to a view** ``` public async Task<IActionResult> Index() { //Getting Data from Database var model= await _context.GetData(); //Selecting Populated Data from the Model and passing to view return View(model.Value); } ```
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
The error means that you're navigating to a view whose model is declared as typeof `Foo` (by using `@model Foo`), but you actually passed it a model which is typeof `Bar` (note the term *dictionary* is used because a model is passed to the view via a `ViewDataDictionary`). The error can be caused by **Passing the wro...
This question already has a great answer, but I ran into the same error, in a different scenario: displaying a **`List`** in an *EditorTemplate*. I have a model like this: ``` public class Foo { public string FooName { get; set; } public List<Bar> Bars { get; set; } } public class Bar { public string Bar...
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
The error means that you're navigating to a view whose model is declared as typeof `Foo` (by using `@model Foo`), but you actually passed it a model which is typeof `Bar` (note the term *dictionary* is used because a model is passed to the view via a `ViewDataDictionary`). The error can be caused by **Passing the wro...
Observe if the view has the model required: **View** ``` @model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel> <div class="row"> <table class="table table-striped table-hover table-width-custom"> <thead> <tr> .... ``` **Controller** ``` [HttpGet] public ActionResult ListItems() { ...
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
Consider the partial `map.cshtml` at `Partials/Map.cshtml`. This can be called from the Page where the partial is to be rendered, simply by using the `<partial>` tag: `<partial name="Partials/Map" model="new Pages.Partials.MapModel()" />` This is one of the easiest methods I encountered (although I am using razor pag...
**Passing the model value that is populated from a controller method to a view** ``` public async Task<IActionResult> Index() { //Getting Data from Database var model= await _context.GetData(); //Selecting Populated Data from the Model and passing to view return View(model.Value); } ```
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
Consider the partial `map.cshtml` at `Partials/Map.cshtml`. This can be called from the Page where the partial is to be rendered, simply by using the `<partial>` tag: `<partial name="Partials/Map" model="new Pages.Partials.MapModel()" />` This is one of the easiest methods I encountered (although I am using razor pag...
one more thing. if your view is a partial/sub page and the model for that partial view is null for some reason (e.g no data) you will get this error. Just need to handle the null partial view model
54,706,513
According to the xgboost documentation (<https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.training>) the xgboost returns feature importances: > > **feature\_importances\_** > > > Feature importances property > > > **Note** > > > Feature importance is defined only for tree boosters....
2019/02/15
[ "https://Stackoverflow.com/questions/54706513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8270077/" ]
If you set: ``` "moment": "^2.22.2" ``` the user will download almost the `v2.22.2`. In this case you will download the `v2.24.0` If you set: ``` "moment": "2.22.2" ``` the user will download exactly that version If you set: ``` "moment": "~2.22.1" ``` the user will download almost the `v2.22.1`. In this cas...
> > can we use any of version 2.x.x functionality( i.e. we can use the new functions provided by 2.9.9 in our app, though we installed 2.22.2 on our computer) > > > Just to avoid confusion. You will not install version 2.22.2 on your computer. By saying ^2.22.2, npm will look what is the highest version of 2.x.x a...
50,750,688
In python I can do: ``` >>> 5 in [2,4,6] False >>> 5 in [4,5,6] True ``` to determine if the give value `5` exists in the list. I want to do the same concept in `jq`. But, there is no `in`. Here is an example with a more realistic data set, and how I can check for 2 values. In my real need I have to check for a few ...
2018/06/07
[ "https://Stackoverflow.com/questions/50750688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117471/" ]
using `,` --------- I don't know where in <https://stedolan.github.io/jq/manual/v1.5/> this is documented. But the answer is in that `jq` does implicit one-to-many and many-to-one munging. ``` jq '.[] | select(.PrivateIpAddress == ("172.31.6.209", "172.31.6.229")) | .Pri...
> > But, there is no `in`. > > > You could use `index/1`, as documented in the manual. Even better would be to use `IN`, which however was only introduced after the release of jq 1.5. If your jq does not have it, you can use this definition for `IN/1`: ``` # return true or false as . is in the stream s def IN(s)...
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
Take a look here: [Asynchronous Programming in Python](http://xph.us/2009/12/10/asynchronous-programming-in-python.html) [An Introduction to Asynchronous Programming and Twisted](http://krondo.com/blog/?p=1247) Worth checking out: [asyncio (previously Tulip) has been checked into the Python default branch](https://...
The other respondents are pointing you to Twisted, which is a great and very comprehensive framework but in my opinion it has a very un-pythonic design. Also, AFAICT, you have to use the Twisted main loop, which may be a problem for you if you're already using something else that provides its own loop. Here is a contr...
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
What you describe (the main program flow resuming immediately while another function executes) is not what's normally called "asynchronous" (AKA "event-driven") programming, but rather "multitasking" (AKA "multithreading" or "multiprocessing"). You can get what you described with the standard library modules `threading...
The other respondents are pointing you to Twisted, which is a great and very comprehensive framework but in my opinion it has a very un-pythonic design. Also, AFAICT, you have to use the Twisted main loop, which may be a problem for you if you're already using something else that provides its own loop. Here is a contr...
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
Take a look here: [Asynchronous Programming in Python](http://xph.us/2009/12/10/asynchronous-programming-in-python.html) [An Introduction to Asynchronous Programming and Twisted](http://krondo.com/blog/?p=1247) Worth checking out: [asyncio (previously Tulip) has been checked into the Python default branch](https://...
You may see my Python Asynchronous Programming tool: <http://www.ideawu.com/blog/2010/08/delegate-in-pythonpython-asynchronous-programming.html> ``` import time, random, sys from delegate import * def proc(a): time.sleep(random.random()) return str(a) def proc_callback(handle, args=None): ret = d.end(ha...
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
You may well want to checkout the Twisted library for Python. They provide many useful tools. 1. [A little primer](http://jessenoller.com/2009/02/11/twisted-hello-asynchronous-programming/1.) 2. [Defer and Related stuff](http://twistedmatrix.com/documents/current/core/howto/defer.html)
You may see my Python Asynchronous Programming tool: <http://www.ideawu.com/blog/2010/08/delegate-in-pythonpython-asynchronous-programming.html> ``` import time, random, sys from delegate import * def proc(a): time.sleep(random.random()) return str(a) def proc_callback(handle, args=None): ret = d.end(ha...
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
The other respondents are pointing you to Twisted, which is a great and very comprehensive framework but in my opinion it has a very un-pythonic design. Also, AFAICT, you have to use the Twisted main loop, which may be a problem for you if you're already using something else that provides its own loop. Here is a contr...
You may see my Python Asynchronous Programming tool: <http://www.ideawu.com/blog/2010/08/delegate-in-pythonpython-asynchronous-programming.html> ``` import time, random, sys from delegate import * def proc(a): time.sleep(random.random()) return str(a) def proc_callback(handle, args=None): ret = d.end(ha...
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
What you describe (the main program flow resuming immediately while another function executes) is not what's normally called "asynchronous" (AKA "event-driven") programming, but rather "multitasking" (AKA "multithreading" or "multiprocessing"). You can get what you described with the standard library modules `threading...
You may well want to checkout the Twisted library for Python. They provide many useful tools. 1. [A little primer](http://jessenoller.com/2009/02/11/twisted-hello-asynchronous-programming/1.) 2. [Defer and Related stuff](http://twistedmatrix.com/documents/current/core/howto/defer.html)
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
Take a look here: [Asynchronous Programming in Python](http://xph.us/2009/12/10/asynchronous-programming-in-python.html) [An Introduction to Asynchronous Programming and Twisted](http://krondo.com/blog/?p=1247) Worth checking out: [asyncio (previously Tulip) has been checked into the Python default branch](https://...
Good news everyone! **Python 3.4 would include brand new ambitious asynchronous programming [implementation](http://www.slideshare.net/megafeihong/tulip-24190096)!** It is currently called [tulip](https://code.google.com/p/tulip/source/list) and already has an [active following](https://groups.google.com/forum/?fromg...
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
The other respondents are pointing you to Twisted, which is a great and very comprehensive framework but in my opinion it has a very un-pythonic design. Also, AFAICT, you have to use the Twisted main loop, which may be a problem for you if you're already using something else that provides its own loop. Here is a contr...
You may well want to checkout the Twisted library for Python. They provide many useful tools. 1. [A little primer](http://jessenoller.com/2009/02/11/twisted-hello-asynchronous-programming/1.) 2. [Defer and Related stuff](http://twistedmatrix.com/documents/current/core/howto/defer.html)
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
Good news everyone! **Python 3.4 would include brand new ambitious asynchronous programming [implementation](http://www.slideshare.net/megafeihong/tulip-24190096)!** It is currently called [tulip](https://code.google.com/p/tulip/source/list) and already has an [active following](https://groups.google.com/forum/?fromg...
You may see my Python Asynchronous Programming tool: <http://www.ideawu.com/blog/2010/08/delegate-in-pythonpython-asynchronous-programming.html> ``` import time, random, sys from delegate import * def proc(a): time.sleep(random.random()) return str(a) def proc_callback(handle, args=None): ret = d.end(ha...
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
What you describe (the main program flow resuming immediately while another function executes) is not what's normally called "asynchronous" (AKA "event-driven") programming, but rather "multitasking" (AKA "multithreading" or "multiprocessing"). You can get what you described with the standard library modules `threading...
Good news everyone! **Python 3.4 would include brand new ambitious asynchronous programming [implementation](http://www.slideshare.net/megafeihong/tulip-24190096)!** It is currently called [tulip](https://code.google.com/p/tulip/source/list) and already has an [active following](https://groups.google.com/forum/?fromg...
59,860,579
I used postman to get urls from an api so I can look at certain titles. The response was saved as a .json file. A snippet of my response.json file looks like this: ``` { "apiUrl":"https://api.ft.com/example/83example74-3c9b-11ea-a01a-example547046735", "title": { "title": "Example title example title...
2020/01/22
[ "https://Stackoverflow.com/questions/59860579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11197012/" ]
If you are using materialize CSS framework make sure you initialize the select again, after appending new options. This worked for me ``` $.each(jsonArray , (key , value)=>{ var option = new Option(value.name , value.id) $('#subcategory').append(option) }) $('select').formSelect(); ```
Try This : ``` function PopulateDropDown(jsonArray) { if (jsonArray != null && jsonArray.length > 0) { $("#subcategory").removeAttr("disabled"); $.each(jsonArray, function () { $("#subcategory").append($("<option></option>").val(this['id']).html(this['name'])); }); } } ```
49,091,870
I want a model with 5 choices, but I cannot enforce them and display the display value in template. I am using CharField(choice=..) instead of ChoiceField or TypeChoiceField as in the [docs](https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display). I tried the solutions [here]...
2018/03/04
[ "https://Stackoverflow.com/questions/49091870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3592827/" ]
Well this is the common issue even when I started with django. So first let's look at django's feature that you can do it like below (Note: your choice case's value are going to be store as integer so you should use `models.IntegerField` instead of `models.CharField`): * [get\_FOO\_display()](https://docs.djangoprojec...
You can also use `models.CharField` but you have to set field option `choices` to your tuples. For exapmle: ``` FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' LEVELS = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) level = models.CharField(...
53,520,300
Using the python bindings for libVLC in a urwid music player I am building. libVLC keeps outputting some errors about converting time and such when pausing and resuming a mp3 file. As far as I can gather from various posts on the vlc mailing list and forums, these errors appear in mp3 files all the time and as long as ...
2018/11/28
[ "https://Stackoverflow.com/questions/53520300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150033/" ]
This is just a macro `Privileged_Data` doing nothing. The compiler will not even see it after the preprocessor pass. It's probably a readability or company standards decision to tag some variables like this.
A preprocessor macro can be defined without an associated value. When that is the case, the macro is substituted with nothing after preprocessing. So given this: ``` #define Privileged_Data ``` Then this: ``` Privileged_Data static int dVariable ``` Becomes this after preprocessing: ``` static int dVariable ``...
43,714,967
I found (lambda \*\*x: x) is very useful for defining a dict in a succinct way, e.g. ``` xxx = (lambda **x: x)(a=1, b=2, c=3) ``` Is there any pre-defined python function does that?
2017/05/01
[ "https://Stackoverflow.com/questions/43714967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4927088/" ]
The `dict` function/constructor can be used in the same manner. ``` >>> (lambda **x: x)(a=1, b=2, c=3) == dict(a=1, b=2, c=3) True ``` See `help(dict)` for more ways to instantiate `dict`s. You are not limited to just defining them with `{'a': 1, 'b': 2, 'c': 3}`.
Try the `{}` literal dictionary syntax. It is quite succinct. See [5.5. *Dictionaries*](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) in the **Data Structures tutorial**. ``` >>> xxx = {'a': 1, 'b': 2, 'c': 3} >>> xxx {'a': 1, 'b': 2, 'c': 3} ```
48,103,343
I was a little surprised to find that: ``` # fast_ops_c.pyx cimport cython cimport numpy as np @cython.boundscheck(False) # turn off bounds-checking for entire function @cython.wraparound(False) # turn off negative index wrapping for entire function @cython.nonecheck(False) def c_iseq_f1(np.ndarray[np.double_t, ndi...
2018/01/04
[ "https://Stackoverflow.com/questions/48103343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48956/" ]
Current versions of Cython (at least >=0.29.20) produce similar performant C-code for both variants. The answer bellow holds for older Cython-versions. --- The reason for this surprise is that `x[i]` is more subtle as it looks. Let's take a look at the following cython function: ``` %%cython def cy_sum(x): cdef ...
Cython can translate `range(len(x))` loops into nearly onLy C Code: ``` for i in range(len(x)): ``` Generated code: ``` __pyx_t_6 = PyObject_Length(((PyObject *)__pyx_v_x)); if (unlikely(__pyx_t_6 == -1)) __PYX_ERR(0, 17, __pyx_L1_error) for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { __pyx_v_i =...
51,584,994
In python if my list is ``` TheTextImage = [["111000"],["222999"]] ``` How would one loop through this list creating a new one of ``` NewTextImage = [["000111"],["999222"]] ``` Can use `[:]` but not `[::-1]`, and cannot use `reverse()`
2018/07/29
[ "https://Stackoverflow.com/questions/51584994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10092065/" ]
You may not use `[::-1]` but you can multiply each range index by -1. ``` t = [["111000"],["222999"]] def rev(x): return "".join(x[(i+1)*-1] for i in range(len(x))) >>> [[rev(x) for x in z] for z in t] [['000111'], ['999222']] ``` --- If you may use the `step` arg in `range`, can do AChampions suggestion: ``...
If you can't use any standard functionality such as `reversed` or `[::-1]`, you can use `collections.deque` and `deque.appendleft` in a loop. Then use a list comprehension to apply the logic to multiple items. ``` from collections import deque L = [["111000"], ["222999"]] def reverser(x): out = deque() for i...
51,584,994
In python if my list is ``` TheTextImage = [["111000"],["222999"]] ``` How would one loop through this list creating a new one of ``` NewTextImage = [["000111"],["999222"]] ``` Can use `[:]` but not `[::-1]`, and cannot use `reverse()`
2018/07/29
[ "https://Stackoverflow.com/questions/51584994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10092065/" ]
You know how to copy a sequence to another sequence one by one, right? ``` new_string = '' for ch in old_string: new_string = new_string + ch ``` If you want to copy the sequence in reverse, just add the new values onto the left instead of onto the right: ``` new_string = '' for ch in old_string: new_string...
If you can't use any standard functionality such as `reversed` or `[::-1]`, you can use `collections.deque` and `deque.appendleft` in a loop. Then use a list comprehension to apply the logic to multiple items. ``` from collections import deque L = [["111000"], ["222999"]] def reverser(x): out = deque() for i...
51,584,994
In python if my list is ``` TheTextImage = [["111000"],["222999"]] ``` How would one loop through this list creating a new one of ``` NewTextImage = [["000111"],["999222"]] ``` Can use `[:]` but not `[::-1]`, and cannot use `reverse()`
2018/07/29
[ "https://Stackoverflow.com/questions/51584994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10092065/" ]
You may not use `[::-1]` but you can multiply each range index by -1. ``` t = [["111000"],["222999"]] def rev(x): return "".join(x[(i+1)*-1] for i in range(len(x))) >>> [[rev(x) for x in z] for z in t] [['000111'], ['999222']] ``` --- If you may use the `step` arg in `range`, can do AChampions suggestion: ``...
You can use `reduce(lambda x,y: y+x, string)` to reverse a string ``` >>> from functools import reduce >>> TheTextImage = [["111000"],["222999"]] >>> [[reduce(lambda x,y: y+x, b) for b in a] for a in TheTextImage] [['000111'], ['999222']] ```
51,584,994
In python if my list is ``` TheTextImage = [["111000"],["222999"]] ``` How would one loop through this list creating a new one of ``` NewTextImage = [["000111"],["999222"]] ``` Can use `[:]` but not `[::-1]`, and cannot use `reverse()`
2018/07/29
[ "https://Stackoverflow.com/questions/51584994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10092065/" ]
You know how to copy a sequence to another sequence one by one, right? ``` new_string = '' for ch in old_string: new_string = new_string + ch ``` If you want to copy the sequence in reverse, just add the new values onto the left instead of onto the right: ``` new_string = '' for ch in old_string: new_string...
You can use `reduce(lambda x,y: y+x, string)` to reverse a string ``` >>> from functools import reduce >>> TheTextImage = [["111000"],["222999"]] >>> [[reduce(lambda x,y: y+x, b) for b in a] for a in TheTextImage] [['000111'], ['999222']] ```
8,377,157
I want to find the fastest way to do the job of `switch` in C. I'm writing some Python code to replace C code, and it's all working fine except for a bottleneck. This code is used in a tight loop, so it really is quite crucial that I get the best performance. **Optimsation Attempt 1:** First attempt, as per previous q...
2011/12/04
[ "https://Stackoverflow.com/questions/8377157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148423/" ]
I think others are right to suggest numpy or pure c; but for pure python, here are some timings, for what they're worth. Based on these, I'm a bit surprised that `array.array` performed so much better than a `dict`. Are you creating these tables on the fly inside the loop? Or have I misunderstood something else about y...
Branch logic in general can be painfully slow in python when used in this type of application and you basically struck on one of the better ways of doing this for a tight inner loop where you are converting between integers. A few more things to experiment with: You might try would be working with [np.array](http://do...
19,174,634
**I found a better error message (see below).** I have a model called App in core/models.py. The error occurs when trying to access a specific app object in django admin. Even on an empty database (after syncdb) with a single app object. Seems core\_app\_history is something django generated. Any help is appreciated....
2013/10/04
[ "https://Stackoverflow.com/questions/19174634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252307/" ]
i Think this is not valid JSON JSON should be like ``` [ { "id": 1, "src": "src1", "name": "name1" }, { "id": 2, "src": "src2", "name": "name2" }, { "id": 3, "src": "src3", "name": "name3" }, { "id": 4, ...
Your outer object in json does not have a key where the internal list is stored in. Also, your strings in json should be quoted. `src1`, `name1` are unquoted.
54,761,993
Passing the file as an argument and storing to an object reference seems very straightforward and easy to understand for the open() function, however the read () function does not take the argument in, and is using the format file.read() instead. Why does the read function not take in the file as arguments, such as rea...
2019/02/19
[ "https://Stackoverflow.com/questions/54761993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11000101/" ]
It's not included there because it's not a *function*, it's a *method* of the object that's exposing a file-oriented API, which is, in this case, `in_file`.
Because you have file reference by `in_file = open(from_file)` so when you do `in_file.read()` you are calling the read on the reference itself which is equivalent of `self` it means the object in this case file object
49,314,270
stuck with create dbf file in python3 with dbf lib. im tried this - ``` import dbf Tbl = dbf.Table( 'sample.dbf', 'ID N(6,0); FCODE C(10)') Tbl.open('read-write') Tbl.append() with Tbl.last_record as rec: rec.ID = 5 rec.FCODE = 'GA24850000' ``` and have next error: ``` Traceback (most recent call ...
2018/03/16
[ "https://Stackoverflow.com/questions/49314270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9394255/" ]
I had the same error. In the older versions of the dbf module, I was able to write dbf files by opening them just with `Tbl.open()` However, with the new version (dbf.0.97), I have to open the files with `Tbl.open(mode=dbf.READ_WRITE)` in order to be able to write them.
here's an append example: ``` table = dbf.Table('sample.dbf', 'cod N(1,0); name C(30)') table.open(mode=dbf.READ_WRITE) row_tuple = (1, 'Name') table.append(row_tuple) ```
14,633,952
I'm new to Elastic Search and to the non-SQL paradigm. I've been following ES tutorial, but there is one thing I couldn't put to work. In the following code (I'me using [PyES](http://packages.python.org/pyes/) to interact with ES) I create a single document, with a nested field (subjects), that contains another nested...
2013/01/31
[ "https://Stackoverflow.com/questions/14633952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/759733/" ]
Ok, after trying a tone of combinations, I finally got it using the following query: ``` query3 = { "nested": { "path": "subjects", "score_mode": "avg", "query": { "bool": { "must": [ { "text": {"subjects.concepts.name"...
Shot in the dark since I haven't tried this personally, but have you tried the fully qualified path to Concepts? ``` query2 = { "nested": { "path": "subjects.concepts", "score_mode": "avg", "query": { "bool": { "must": [ ...
14,633,952
I'm new to Elastic Search and to the non-SQL paradigm. I've been following ES tutorial, but there is one thing I couldn't put to work. In the following code (I'me using [PyES](http://packages.python.org/pyes/) to interact with ES) I create a single document, with a nested field (subjects), that contains another nested...
2013/01/31
[ "https://Stackoverflow.com/questions/14633952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/759733/" ]
Shot in the dark since I haven't tried this personally, but have you tried the fully qualified path to Concepts? ``` query2 = { "nested": { "path": "subjects.concepts", "score_mode": "avg", "query": { "bool": { "must": [ ...
I have some question for JCJS's answer. why your mapping shouldn't like this? ``` mapping = { "subjects": { "type": "nested", "properties": { "concepts": { "type": "nested" } } } } ``` I try to define two type-mapping maybe doesn't work, but be ...
14,633,952
I'm new to Elastic Search and to the non-SQL paradigm. I've been following ES tutorial, but there is one thing I couldn't put to work. In the following code (I'me using [PyES](http://packages.python.org/pyes/) to interact with ES) I create a single document, with a nested field (subjects), that contains another nested...
2013/01/31
[ "https://Stackoverflow.com/questions/14633952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/759733/" ]
Ok, after trying a tone of combinations, I finally got it using the following query: ``` query3 = { "nested": { "path": "subjects", "score_mode": "avg", "query": { "bool": { "must": [ { "text": {"subjects.concepts.name"...
I have some question for JCJS's answer. why your mapping shouldn't like this? ``` mapping = { "subjects": { "type": "nested", "properties": { "concepts": { "type": "nested" } } } } ``` I try to define two type-mapping maybe doesn't work, but be ...
22,444,378
I am looking for a simple solution to display thumbnails using wxPython. This is not about creating the thumbnails. I have a directory of thumbnails and want to display them on the screen. I am purposely not using terms like (Panel, Frame, Window, ScrolledWindow) because I am open to various solutions. Also note I hav...
2014/03/16
[ "https://Stackoverflow.com/questions/22444378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381864/" ]
I would recommend using the ThumbNailCtrl widget: <http://wxpython.org/Phoenix/docs/html/lib.agw.thumbnailctrl.html>. There is a good example in the wxPython demo. Or you could use this one from the documentation. Note that the ThumbNailCtrl requires the Python Imaging Library to be installed. ``` import os import wx...
I would just display them as wx.Image inside a frame. <http://www.wxpython.org/docs/api/wx.Image-class.html> From the class: "A platform-independent image class. An image can be created from data, or using wx.Bitmap.ConvertToImage, or loaded from a file in a variety of formats. Functions are available to set and get ...
22,444,378
I am looking for a simple solution to display thumbnails using wxPython. This is not about creating the thumbnails. I have a directory of thumbnails and want to display them on the screen. I am purposely not using terms like (Panel, Frame, Window, ScrolledWindow) because I am open to various solutions. Also note I hav...
2014/03/16
[ "https://Stackoverflow.com/questions/22444378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381864/" ]
Not sure if I am supposed to answer my own question but I did find a solution to my problem and I wanted to share. I was using wx version 2.8. I found that in 2.9 and 3.0 there was a widget added called WrapSizer. Once I updated my version of wx to 3.0 that made the solution beyond simple. Here are the code snippets th...
I would just display them as wx.Image inside a frame. <http://www.wxpython.org/docs/api/wx.Image-class.html> From the class: "A platform-independent image class. An image can be created from data, or using wx.Bitmap.ConvertToImage, or loaded from a file in a variety of formats. Functions are available to set and get ...
22,444,378
I am looking for a simple solution to display thumbnails using wxPython. This is not about creating the thumbnails. I have a directory of thumbnails and want to display them on the screen. I am purposely not using terms like (Panel, Frame, Window, ScrolledWindow) because I am open to various solutions. Also note I hav...
2014/03/16
[ "https://Stackoverflow.com/questions/22444378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381864/" ]
Not sure if I am supposed to answer my own question but I did find a solution to my problem and I wanted to share. I was using wx version 2.8. I found that in 2.9 and 3.0 there was a widget added called WrapSizer. Once I updated my version of wx to 3.0 that made the solution beyond simple. Here are the code snippets th...
I would recommend using the ThumbNailCtrl widget: <http://wxpython.org/Phoenix/docs/html/lib.agw.thumbnailctrl.html>. There is a good example in the wxPython demo. Or you could use this one from the documentation. Note that the ThumbNailCtrl requires the Python Imaging Library to be installed. ``` import os import wx...
39,053,393
I'm using the formula "product of two number is equal to the product of their GCD and LCM". Here's my code : ``` # Uses python3 import sys def hcf(x, y): while(y): x, y = y, x % y return x a,b = map(int,sys.stdin.readline().split()) res=int(((a*b)/hcf(a,b))) print(res) ``` It works great for s...
2016/08/20
[ "https://Stackoverflow.com/questions/39053393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6032875/" ]
Elaborating on the comments. In Python 3, true division, `/`, converts its arguments to floats. In your example, the true answer of `lcm(226553150, 1023473145)` is `46374212988031350`. By looking at `bin(46374212988031350)` you can verify that this is a 56 bit number. When you compute `226553150*1023473145/5` (5 is the...
You should use a different method to find the **GCD** that will be the issue: Use: ``` def hcfnaive(a, b): if(b == 0): return abs(a) else: return hcfnaive(b, a % b) ``` You can try one more method: ``` import math a = 13 b = 5 print((a*b)/math.gcd(a,b)) ```
46,996,102
python is new to me and I'm facing this little, probably for most of you really easy to solve, problem. I am trying for the first time to use a class so I dont have to make so many functions and just pick one out of the class!! so here is what I have writen so far: ``` from tkinter import * import webbrowser cla...
2017/10/29
[ "https://Stackoverflow.com/questions/46996102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8839994/" ]
You need to initiate a class first variable = web\_open3(). The **init** is a magic function that is ran when you create an instance of the class. This is to show how to begin writing a class in python. ``` from tkinter import * import webbrowser class web_open3: def __init__(self): self.A = "http://www.googl...
In programming, a class is an object. What is an object? It's an instance. In order to use your object, you first have to create it. You do that by instantiating it, `web = web_open3()`. Then, you can use the `open()` function. Now, objects may also be static. A static object, is an object that you don't instantiate....
57,270,642
I have a program that uploads videos to via the vimeo api. But everytime I click run, the program that runs is not the current one, its an old program, which I have now deleted and even deleted from recycle bin, yet everytime I run my vimeo code it runs a completely different program that shouldnt even exist its drivin...
2019/07/30
[ "https://Stackoverflow.com/questions/57270642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8066094/" ]
I suspect you have a script cached somewhere. To troubleshoot please do the following: * Restart VScode * Restart PC (if on windows 10 use `shutdown/r /f /t 000` in cmd to force a full restart and avoid windows fast-boot saving anything.) * check what happens if you run the script manually via `python *your script*` a...
If you are importing any module like "import some\_module" you could change it to "from some\_module import \*", or the specific function you want.
10,076,075
I have a data structure like this: ``` { 'key1':[ [1,1,'Some text'], [2,0,''], ... ], ... 'key99':[ [1,1,'Some text'], [2,1,'More text'], ... ], } ``` The size of this will be only like 100 keys and 100 lists in each key. I like to store it and re...
2012/04/09
[ "https://Stackoverflow.com/questions/10076075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126463/" ]
You should use a [`ObservableCollection<SomeType>`](http://msdn.microsoft.com/en-us/library/ms668604.aspx) for this instead. `ObservableCollection<T>` provides the `CollectionChanged` event which you can subscribe to - the [`CollectionChanged`](http://msdn.microsoft.com/en-us/library/ms653375.aspx) event fires when an...
`List` does not expose any events for that. You should consider using [`ObservableCollection`](http://msdn.microsoft.com/en-us/library/ms653375.aspx) instead. It has `CollectionChanged` event which occurs when an item is added, removed, changed, moved, or the entire list is refreshed.
10,076,075
I have a data structure like this: ``` { 'key1':[ [1,1,'Some text'], [2,0,''], ... ], ... 'key99':[ [1,1,'Some text'], [2,1,'More text'], ... ], } ``` The size of this will be only like 100 keys and 100 lists in each key. I like to store it and re...
2012/04/09
[ "https://Stackoverflow.com/questions/10076075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126463/" ]
You should use a [`ObservableCollection<SomeType>`](http://msdn.microsoft.com/en-us/library/ms668604.aspx) for this instead. `ObservableCollection<T>` provides the `CollectionChanged` event which you can subscribe to - the [`CollectionChanged`](http://msdn.microsoft.com/en-us/library/ms653375.aspx) event fires when an...
Maybe you should be using `ObservableCollection<T>`. It fires events when items are added or removed, or several other events. Here is the doc: <http://msdn.microsoft.com/en-us/library/ms668604.aspx>
10,076,075
I have a data structure like this: ``` { 'key1':[ [1,1,'Some text'], [2,0,''], ... ], ... 'key99':[ [1,1,'Some text'], [2,1,'More text'], ... ], } ``` The size of this will be only like 100 keys and 100 lists in each key. I like to store it and re...
2012/04/09
[ "https://Stackoverflow.com/questions/10076075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126463/" ]
You should use a [`ObservableCollection<SomeType>`](http://msdn.microsoft.com/en-us/library/ms668604.aspx) for this instead. `ObservableCollection<T>` provides the `CollectionChanged` event which you can subscribe to - the [`CollectionChanged`](http://msdn.microsoft.com/en-us/library/ms653375.aspx) event fires when an...
you can do something like ``` private List<SomeType> _list; public void AddToList(SomeType item) { _list.Add(item); SomeOtherMethod(); } public ReadOnlyCollection<SomeType> MyList { get { return _list.AsReadOnly(); } } ``` but ObservableCollection would be b...
10,076,075
I have a data structure like this: ``` { 'key1':[ [1,1,'Some text'], [2,0,''], ... ], ... 'key99':[ [1,1,'Some text'], [2,1,'More text'], ... ], } ``` The size of this will be only like 100 keys and 100 lists in each key. I like to store it and re...
2012/04/09
[ "https://Stackoverflow.com/questions/10076075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126463/" ]
You should use a [`ObservableCollection<SomeType>`](http://msdn.microsoft.com/en-us/library/ms668604.aspx) for this instead. `ObservableCollection<T>` provides the `CollectionChanged` event which you can subscribe to - the [`CollectionChanged`](http://msdn.microsoft.com/en-us/library/ms653375.aspx) event fires when an...
If you create your own implementation of IList you can call methods when an item is added to the list (or do anything else you want). Create a class that inherits from IList and have as a private member a list of type T. Implement each of the Interface methods using your private member and modify the Add(T item) call t...
10,076,075
I have a data structure like this: ``` { 'key1':[ [1,1,'Some text'], [2,0,''], ... ], ... 'key99':[ [1,1,'Some text'], [2,1,'More text'], ... ], } ``` The size of this will be only like 100 keys and 100 lists in each key. I like to store it and re...
2012/04/09
[ "https://Stackoverflow.com/questions/10076075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126463/" ]
`List` does not expose any events for that. You should consider using [`ObservableCollection`](http://msdn.microsoft.com/en-us/library/ms653375.aspx) instead. It has `CollectionChanged` event which occurs when an item is added, removed, changed, moved, or the entire list is refreshed.
you can do something like ``` private List<SomeType> _list; public void AddToList(SomeType item) { _list.Add(item); SomeOtherMethod(); } public ReadOnlyCollection<SomeType> MyList { get { return _list.AsReadOnly(); } } ``` but ObservableCollection would be b...
10,076,075
I have a data structure like this: ``` { 'key1':[ [1,1,'Some text'], [2,0,''], ... ], ... 'key99':[ [1,1,'Some text'], [2,1,'More text'], ... ], } ``` The size of this will be only like 100 keys and 100 lists in each key. I like to store it and re...
2012/04/09
[ "https://Stackoverflow.com/questions/10076075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126463/" ]
`List` does not expose any events for that. You should consider using [`ObservableCollection`](http://msdn.microsoft.com/en-us/library/ms653375.aspx) instead. It has `CollectionChanged` event which occurs when an item is added, removed, changed, moved, or the entire list is refreshed.
If you create your own implementation of IList you can call methods when an item is added to the list (or do anything else you want). Create a class that inherits from IList and have as a private member a list of type T. Implement each of the Interface methods using your private member and modify the Add(T item) call t...
10,076,075
I have a data structure like this: ``` { 'key1':[ [1,1,'Some text'], [2,0,''], ... ], ... 'key99':[ [1,1,'Some text'], [2,1,'More text'], ... ], } ``` The size of this will be only like 100 keys and 100 lists in each key. I like to store it and re...
2012/04/09
[ "https://Stackoverflow.com/questions/10076075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126463/" ]
Maybe you should be using `ObservableCollection<T>`. It fires events when items are added or removed, or several other events. Here is the doc: <http://msdn.microsoft.com/en-us/library/ms668604.aspx>
you can do something like ``` private List<SomeType> _list; public void AddToList(SomeType item) { _list.Add(item); SomeOtherMethod(); } public ReadOnlyCollection<SomeType> MyList { get { return _list.AsReadOnly(); } } ``` but ObservableCollection would be b...
10,076,075
I have a data structure like this: ``` { 'key1':[ [1,1,'Some text'], [2,0,''], ... ], ... 'key99':[ [1,1,'Some text'], [2,1,'More text'], ... ], } ``` The size of this will be only like 100 keys and 100 lists in each key. I like to store it and re...
2012/04/09
[ "https://Stackoverflow.com/questions/10076075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126463/" ]
Maybe you should be using `ObservableCollection<T>`. It fires events when items are added or removed, or several other events. Here is the doc: <http://msdn.microsoft.com/en-us/library/ms668604.aspx>
If you create your own implementation of IList you can call methods when an item is added to the list (or do anything else you want). Create a class that inherits from IList and have as a private member a list of type T. Implement each of the Interface methods using your private member and modify the Add(T item) call t...
10,076,075
I have a data structure like this: ``` { 'key1':[ [1,1,'Some text'], [2,0,''], ... ], ... 'key99':[ [1,1,'Some text'], [2,1,'More text'], ... ], } ``` The size of this will be only like 100 keys and 100 lists in each key. I like to store it and re...
2012/04/09
[ "https://Stackoverflow.com/questions/10076075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126463/" ]
you can do something like ``` private List<SomeType> _list; public void AddToList(SomeType item) { _list.Add(item); SomeOtherMethod(); } public ReadOnlyCollection<SomeType> MyList { get { return _list.AsReadOnly(); } } ``` but ObservableCollection would be b...
If you create your own implementation of IList you can call methods when an item is added to the list (or do anything else you want). Create a class that inherits from IList and have as a private member a list of type T. Implement each of the Interface methods using your private member and modify the Add(T item) call t...
70,234,520
I am new at python, im trying to write a code to print several lines after an if statement. for example, I have a file "test.txt" with this style: ``` Hello how are you? fine thanks how old are you? 24 good how old are you? i am 26 ok bye. Hello how are you? fine how old are you? 13 good how old are you? i am 34 ok b...
2021/12/05
[ "https://Stackoverflow.com/questions/70234520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17594775/" ]
You can use `readlines()` function that returnes lines of a file as a list and use `enumerate()` function to loop through list elements: ``` lines = open('test.txt').readlines() for i,line in enumerate(lines): if line.startswith('how old are you?'): print(lines[i+1], line[i+2]) ```
You could convert the file to a list and use a variable which increases by 1 for each line: ```py fhandle = list(open('test.txt')) i = 1 for line in fhandle: if line.startswith('how old are you?') print(fhandle[i]) i += 1 ```
70,234,520
I am new at python, im trying to write a code to print several lines after an if statement. for example, I have a file "test.txt" with this style: ``` Hello how are you? fine thanks how old are you? 24 good how old are you? i am 26 ok bye. Hello how are you? fine how old are you? 13 good how old are you? i am 34 ok b...
2021/12/05
[ "https://Stackoverflow.com/questions/70234520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17594775/" ]
You can use `readlines()` function that returnes lines of a file as a list and use `enumerate()` function to loop through list elements: ``` lines = open('test.txt').readlines() for i,line in enumerate(lines): if line.startswith('how old are you?'): print(lines[i+1], line[i+2]) ```
Assuming there are always two more lines after each "how old are you", you could just skip to the next iteration by using `next(fhandle)` like this: ``` fhandle = open('test.txt') for line in fhandle: if line.startswith('how old are you?'): print(line) print(next(fhandle)) print(next(fhandl...
70,234,520
I am new at python, im trying to write a code to print several lines after an if statement. for example, I have a file "test.txt" with this style: ``` Hello how are you? fine thanks how old are you? 24 good how old are you? i am 26 ok bye. Hello how are you? fine how old are you? 13 good how old are you? i am 34 ok b...
2021/12/05
[ "https://Stackoverflow.com/questions/70234520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17594775/" ]
You can use `readlines()` function that returnes lines of a file as a list and use `enumerate()` function to loop through list elements: ``` lines = open('test.txt').readlines() for i,line in enumerate(lines): if line.startswith('how old are you?'): print(lines[i+1], line[i+2]) ```
So as you want to print next line (or two lines) I suggest to use list index. to do that use `readlines()` to convert the file to a `list`: ```py fhandle = open('test.txt').readlines() ``` After you did this you can use `len` to calculate list length and index it in a for loop and print next two lines. ```py for li...
2,009,379
``` import re from decimal import * import numpy from scipy.signal import cspline1d, cspline1d_eval import scipy.interpolate import scipy import math import numpy from scipy import interpolate Y1 =[0.48960000000000004, 0.52736099999999997, 0.56413900000000006, 0.60200199999999993, 0.640...
2010/01/05
[ "https://Stackoverflow.com/questions/2009379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240524/" ]
I believe it's due to the X1 values not being ordered from smallest to largest plus also you have one duplicate x point, i.e, you need to sort the values for X1 and Y1 before you can use the splrep and remove duplicates. splrep from the docs seem to be low level access to FITPACK libraries which expects a sorted, non-...
The X value 0.029999999999999999 occurs twice, with two different Y coordinates. It wouldn't surprise me if that caused a problem trying to fit a polynomial spline segment....
70,639,556
Recently I have started to use [hydra](https://hydra.cc/docs/intro/) to manage the configs in my application. I use [Structured Configs](https://hydra.cc/docs/tutorials/structured_config/intro/) to create schema for .yaml config files. Structured Configs in Hyda uses [dataclasses](https://docs.python.org/3/library/data...
2022/01/09
[ "https://Stackoverflow.com/questions/70639556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10943470/" ]
For those of you wondering how this works exactly, here is an example of it: ```py import hydra from hydra.core.config_store import ConfigStore from omegaconf import OmegaConf from pydantic.dataclasses import dataclass from pydantic import validator @dataclass class MyConfigSchema: some_var: float @validator...
See [pydantic.dataclasses.dataclass](https://pydantic-docs.helpmanual.io/usage/dataclasses/), which are a drop-in replacement for the standard-library dataclasses with some extra type-checking.
31,460,152
I am writing a python code that will work as a dameon in a Raspberry pi. However, the person I am writing this for want to see the raw output it gets while it is running, not just my log files. My first idea to do this was to use a bash script using the Screen program, but that has some features in it that I CANNOT ha...
2015/07/16
[ "https://Stackoverflow.com/questions/31460152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3346931/" ]
In the latest seaborn, you can use the `countplot` function: ``` seaborn.countplot(x='reputation', data=df) ``` To do it with `barplot` you'd need something like this: ``` seaborn.barplot(x=df.reputation.value_counts().index, y=df.reputation.value_counts()) ``` You can't pass `'reputation'` as a column name to `x...
Using just `countplot` you can get the bars in the same order as `.value_counts()` output too: ``` seaborn.countplot(data=df, x='reputation', order=df.reputation.value_counts().index) ```
35,230,093
When a terminal is opened, the environmental shell is set. If I then type "csh" it starts running a c shell as a program within the bash terminal. My question is, from a python script, how can I check to determine if csh has been executed prior to starting the python script. THanks
2016/02/05
[ "https://Stackoverflow.com/questions/35230093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5889345/" ]
You can check the shell environment by using ``` import os shell = os.environ['SHELL'] ``` Then you can make sure `shell` is set to `/bin/csh`
You can use `os.getppid()` to find the [parent PID](https://unix.stackexchange.com/q/18166/3330), and `ps` to find the name of the command: ``` import subprocess import os ppid = os.getppid() out = subprocess.check_output(['ps', '--format', '%c', '--pid', str(ppid)]) print(out.splitlines()[-1]) ``` --- ``` % csh % ...