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
63,708,795
I'm receiving a string like this sentence **"Mr,Pavol,Bujna,has arrived"** from a server. To my Raspberry Pi with Python sockets... It's working well, but need to split the sentence to separate variables. What I have now: `message2 = 'Mr,Pavol,Bujna,has arrived'` What I need: ``` firstname = 'Pavol' surname = 'Buj...
2020/09/02
[ "https://Stackoverflow.com/questions/63708795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13082942/" ]
message2 = 'Mr,Pavol,Bujna,has arrived' ``` words=message2.split(',') firstname=words[1] lastname=words[2] arravingLeaving=words[3] ``` or u could use tuple unpacking as well
Thanks, I figured it out myself meanwhile. Splitting message2 string to multiple variables ``` title, firstName, lastName, arravingLeaving = message2.split(",") print(title) print(firstName) print(lastName) print(arravingLeaving) ``` Whole code: ``` #!/usr/bin/python # -*- coding:utf-8 -*- impo...
13,256,735
In my application, I have one single thread that is performing very fast processing on log lines to produce a float value. There is usually only a single other thread performing slow reads on the values at intervals. Every so often, other threads can come and go and also perform once-off reads on those values. My ques...
2012/11/06
[ "https://Stackoverflow.com/questions/13256735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496445/" ]
Try this macro: ``` Sub ConsolidateRows() 'takes rows and consolidate one or many cells, based on one or many cells matching with above or below rows. Dim lastRow As Long, i As Long, j As Long Dim colMatch As Variant, colConcat As Variant '**********PARAMETERS TO UPDATE**************** Const strMatch As String = "A"...
The following VBA code should work for what you are trying to do. It assumes that your email addresses are in the range A2:A50000, so you can change this to fit your needs. If you are not too familiar with VBA, under the Developer Tab in Excel 2011 Mac, there should be an icon called Visual Basic Editor. Open VB and CM...
53,910,919
I want get the name (first line only) from the below raw content. Can you please help me? I want to get just `RAM KUMAR` only from the raw text using python. Raw Content: ``` "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\[email protected], [email protected]\n\nLinkedin.com/in/...
2018/12/24
[ "https://Stackoverflow.com/questions/53910919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3239174/" ]
No need to use regex, just simply do: ``` print(yourstring.split('\n')[0]) ``` Output: ``` RAM KUMAR ``` **Edit:** ``` with open(filename,'r') as f: print(f.read().split('\n')[0]) ```
Use [`split`](https://www.geeksforgeeks.org/python-string-split/) to do something like this perhaps: ``` txt_content = "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\[email protected], [email protected]\n\nLinkedin.com/in/ramkumar \t\t\t\t ...
53,910,919
I want get the name (first line only) from the below raw content. Can you please help me? I want to get just `RAM KUMAR` only from the raw text using python. Raw Content: ``` "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\[email protected], [email protected]\n\nLinkedin.com/in/...
2018/12/24
[ "https://Stackoverflow.com/questions/53910919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3239174/" ]
No need to use regex, just simply do: ``` print(yourstring.split('\n')[0]) ``` Output: ``` RAM KUMAR ``` **Edit:** ``` with open(filename,'r') as f: print(f.read().split('\n')[0]) ```
Since the question is tagged [regex](/questions/tagged/regex "show questions tagged 'regex'"), I am offering a regex-based solution for the same. Use the following expression: `^[^\n]+` [Demo](https://regex101.com/r/h40abu/1) All I am doing is matching everything except the `'\n'` charatcer from the beginning of th...
53,910,919
I want get the name (first line only) from the below raw content. Can you please help me? I want to get just `RAM KUMAR` only from the raw text using python. Raw Content: ``` "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\[email protected], [email protected]\n\nLinkedin.com/in/...
2018/12/24
[ "https://Stackoverflow.com/questions/53910919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3239174/" ]
Use [`split`](https://www.geeksforgeeks.org/python-string-split/) to do something like this perhaps: ``` txt_content = "RAM KUMAR\n\nMarketing and Sales Professional\n\n+91.0000000000\n\[email protected], [email protected]\n\nLinkedin.com/in/ramkumar \t\t\t\t ...
Since the question is tagged [regex](/questions/tagged/regex "show questions tagged 'regex'"), I am offering a regex-based solution for the same. Use the following expression: `^[^\n]+` [Demo](https://regex101.com/r/h40abu/1) All I am doing is matching everything except the `'\n'` charatcer from the beginning of th...
28,465,477
I'm looking into how to compute as efficient as possible in python3 a dot product inside a double sum of the form: ``` import cmath for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * sum(a*b for a,b in zip(x, [l - m for l, m in zip(r_p[j], r_p[k])]))) ``` where r\_np is a array of several...
2015/02/11
[ "https://Stackoverflow.com/questions/28465477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519380/" ]
I used this to generate test data: ``` x = (1, 2, 3) r_p = [(i, j, k) for i in range(10) for j in range(10) for k in range(10)] ``` On my machine, this took `2.7` seconds with your algorithm. Then I got rid of the `zip`s and `sum`: ``` for j in range(0,N): for k in range(0,N): s = 0 for t in ra...
That double loop is a time killer in `numpy`. If you use vectorized array operations, the evaluation is cut to under a second. ``` In [1764]: sum_np=0 In [1765]: for j in range(0,N): for k in range(0,N): sum_np += np.exp(-1j * np.inner(x_np,(r_np[j] - r_np[k]))) In [1766]: sum_np Out[1766]: (2116.33165264...
28,465,477
I'm looking into how to compute as efficient as possible in python3 a dot product inside a double sum of the form: ``` import cmath for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * sum(a*b for a,b in zip(x, [l - m for l, m in zip(r_p[j], r_p[k])]))) ``` where r\_np is a array of several...
2015/02/11
[ "https://Stackoverflow.com/questions/28465477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519380/" ]
I used this to generate test data: ``` x = (1, 2, 3) r_p = [(i, j, k) for i in range(10) for j in range(10) for k in range(10)] ``` On my machine, this took `2.7` seconds with your algorithm. Then I got rid of the `zip`s and `sum`: ``` for j in range(0,N): for k in range(0,N): s = 0 for t in ra...
Ok guys, thanks a lot for the help. IVlads last code that uses the identity `sum_j sum_k a[j]*a[k] = sum_j a[j] * sum_k a[k]` makes the biggest difference. This now scales also with less then O(N^2). Precalculating the dot product before the sum makes hpaulj's numpy suggestion exactly the same fast: ``` sum_np = 0 dot...
28,465,477
I'm looking into how to compute as efficient as possible in python3 a dot product inside a double sum of the form: ``` import cmath for j in range(0,N): for k in range(0,N): sum_p += cmath.exp(-1j * sum(a*b for a,b in zip(x, [l - m for l, m in zip(r_p[j], r_p[k])]))) ``` where r\_np is a array of several...
2015/02/11
[ "https://Stackoverflow.com/questions/28465477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519380/" ]
That double loop is a time killer in `numpy`. If you use vectorized array operations, the evaluation is cut to under a second. ``` In [1764]: sum_np=0 In [1765]: for j in range(0,N): for k in range(0,N): sum_np += np.exp(-1j * np.inner(x_np,(r_np[j] - r_np[k]))) In [1766]: sum_np Out[1766]: (2116.33165264...
Ok guys, thanks a lot for the help. IVlads last code that uses the identity `sum_j sum_k a[j]*a[k] = sum_j a[j] * sum_k a[k]` makes the biggest difference. This now scales also with less then O(N^2). Precalculating the dot product before the sum makes hpaulj's numpy suggestion exactly the same fast: ``` sum_np = 0 dot...
61,354,963
``` >>> 1/3 0.3333333333333333 >>> 1/3+1/3+1/3 1.0 ``` I can't understand why this is 1.0. Shouldn't it be `0.9999999999999999`? So I kind of came up with the solution that python has an automatic rounding for it's answer, but if than, the following results can't be explained... ``` >>> 1/3+1/3+1/3+1/3+1/3+1/3 1.9...
2020/04/21
[ "https://Stackoverflow.com/questions/61354963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376385/" ]
This is one of the subtle points of IEEE-754 arithmetic. When you write: ```py >>> 1/3 0.3333333333333333 ``` the number you see printed is a "rounded" version of the number that is internally stored as the result of `1/3`. It's just what the Double -> String conversion in the printing process decided to show you. B...
This question may provide some answers to the floating point error [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) With the brackets, the compiler is breaking down the addition into smaller pieces, reducing the possibility of a floating point which is not supp...
61,354,963
``` >>> 1/3 0.3333333333333333 >>> 1/3+1/3+1/3 1.0 ``` I can't understand why this is 1.0. Shouldn't it be `0.9999999999999999`? So I kind of came up with the solution that python has an automatic rounding for it's answer, but if than, the following results can't be explained... ``` >>> 1/3+1/3+1/3+1/3+1/3+1/3 1.9...
2020/04/21
[ "https://Stackoverflow.com/questions/61354963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376385/" ]
Most Python implementations use a binary floating-point format, most commonly the IEEE-754 binary64 format. This format has **no** decimal digits. It has 53 binary digits. When this format is used with round-to-nearest-ties-to-even, computing 1/3 yields 0.333333333333333314829616256247390992939472198486328125. Your Py...
This question may provide some answers to the floating point error [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) With the brackets, the compiler is breaking down the addition into smaller pieces, reducing the possibility of a floating point which is not supp...
61,354,963
``` >>> 1/3 0.3333333333333333 >>> 1/3+1/3+1/3 1.0 ``` I can't understand why this is 1.0. Shouldn't it be `0.9999999999999999`? So I kind of came up with the solution that python has an automatic rounding for it's answer, but if than, the following results can't be explained... ``` >>> 1/3+1/3+1/3+1/3+1/3+1/3 1.9...
2020/04/21
[ "https://Stackoverflow.com/questions/61354963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13376385/" ]
Most Python implementations use a binary floating-point format, most commonly the IEEE-754 binary64 format. This format has **no** decimal digits. It has 53 binary digits. When this format is used with round-to-nearest-ties-to-even, computing 1/3 yields 0.333333333333333314829616256247390992939472198486328125. Your Py...
This is one of the subtle points of IEEE-754 arithmetic. When you write: ```py >>> 1/3 0.3333333333333333 ``` the number you see printed is a "rounded" version of the number that is internally stored as the result of `1/3`. It's just what the Double -> String conversion in the printing process decided to show you. B...
50,120,062
I have a 1D `numpy` array. The difference between two succeeding values in this array is either one or larger than one. I want to cut the array into parts for every occurrence that the difference is larger than one. Hence: ``` arr = numpy.array([77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104]) ``` should become...
2018/05/01
[ "https://Stackoverflow.com/questions/50120062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2776885/" ]
One Pythonic way would be - ``` np.split(arr, np.flatnonzero(np.diff(arr)>1)+1) ``` Sample run - ``` In [10]: arr Out[10]: array([ 77, 78, 79, 80, 90, 91, 92, 100, 101, 102, 103, 104]) In [11]: np.split(arr, np.flatnonzero(np.diff(arr)>1)+1) Out[11]: [array([77, 78, 79, 80]), array([90, 91, 92]), array([1...
Another way with slicing, getting the appropriate indices using `np.diff`: ``` import numpy as np def split(arr): idx = np.pad(np.where(np.diff(arr) > 1)[0]+1, (1,1), 'constant', constant_values = (0, len(arr))) return [arr[idx[i]: idx[i+1]] for i in range(len(idx)-1)] ``` Result: ``` arr = np....
63,709,660
I'm trying to connect to an SFTP server using Python and Paramiko, but I'm getting this error (the same error occurs when I use pysftp): ```none starting thread (client mode): 0x17ccde50L Local version/idstring: SSH-2.0-paramiko_2.7.2 Remote version/idstring: SSH-2.0-OpenSSH_7.2 Connected (version 2.0, client OpenSSH_...
2020/09/02
[ "https://Stackoverflow.com/questions/63709660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5754267/" ]
This topic suggests that you may have obsolete dependencies: <https://github.com/paramiko/paramiko/issues/1027> [The solution by @bieli](https://github.com/paramiko/paramiko/issues/1027#issuecomment-374145838) seems to help many of those who face the problem: ``` sudo pip uninstall cryptography -y && sudo apt-get ...
In the sample below, you may see absolute paths to a few of the dependencies because I'm running the Python script on a remote server without internet. Therefore, .whl files had to be copied from my PC to the remote server. Of these dependencies, "**cffi**" was upgraded to version 1.11.2 and eventually resolved the iss...
56,904,802
I want functions in a class to store their returned values in some data structure. For this purpose I want to use a decorator: ```py results = [] instances = [] class A: def __init__(self, data): self.data = data @decorator def f1(self, a, b): return self.data + a + b @decorator ...
2019/07/05
[ "https://Stackoverflow.com/questions/56904802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2015614/" ]
You will need to use `CodeIdTokenToken` response type, according to the [documentation](https://openid.net/specs/openid-connect-core-1_0.html#HybridAuthRequest) `options.ResponseType = OpenIdConnectResponseType.CodeIdTokenToken;`
I managed to fix this. To anyone that would encounter this issue, set the response type to **Code** to get both the id\_token and the access\_token. This will instruct Open ID Connect to use the authorization code flow. ``` options.ResponseType = OpenIdConnectResponseType.Code ```
61,039,847
I am making Exam app with kivy(python) and I have problem with getting correct answer. I have dictonary of translates from latin words to slovenian words exemple(Keys are latin words, values are slovenian words): ``` Dic = {"Aegrotus": "bolnik", "Aether": "eter"} ``` So the problem is when 2 or 3 latin words mean sa...
2020/04/05
[ "https://Stackoverflow.com/questions/61039847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11590506/" ]
Firstly, you have to be able to get the text output from the app shown in the picture, then you use your dictionary to check it. And the way to design the dictionary makes it difficult to check. You should design it that way: key is only one string, and values is a list. For example: ``` Dic = {"A": ["od"], "ab": ["o...
Do you only need to translate from latin -> slovenian and not the other way around? If so, just make every key a single word. It's OK for multiple keys to have the same value: ```py Dic = { "Aegrotus": "bolnik", "Aether": "eter", "A": "od", "ab": "od", "Acutus": ("Akuten", "Akutna", "Akutno"), "Aromaticus": ("...
61,039,847
I am making Exam app with kivy(python) and I have problem with getting correct answer. I have dictonary of translates from latin words to slovenian words exemple(Keys are latin words, values are slovenian words): ``` Dic = {"Aegrotus": "bolnik", "Aether": "eter"} ``` So the problem is when 2 or 3 latin words mean sa...
2020/04/05
[ "https://Stackoverflow.com/questions/61039847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11590506/" ]
Firstly, you have to be able to get the text output from the app shown in the picture, then you use your dictionary to check it. And the way to design the dictionary makes it difficult to check. You should design it that way: key is only one string, and values is a list. For example: ``` Dic = {"A": ["od"], "ab": ["o...
you could use `dict.items()` (`dict.iteritems()` for python2, but why am I even mentioning that ?) so try something like ```py for latin_words, slovenian_words in dic.items(): if isinstance(latin_words, tuple): # this is the check # if there are multiple values # this will run ... ...
61,039,847
I am making Exam app with kivy(python) and I have problem with getting correct answer. I have dictonary of translates from latin words to slovenian words exemple(Keys are latin words, values are slovenian words): ``` Dic = {"Aegrotus": "bolnik", "Aether": "eter"} ``` So the problem is when 2 or 3 latin words mean sa...
2020/04/05
[ "https://Stackoverflow.com/questions/61039847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11590506/" ]
Firstly, you have to be able to get the text output from the app shown in the picture, then you use your dictionary to check it. And the way to design the dictionary makes it difficult to check. You should design it that way: key is only one string, and values is a list. For example: ``` Dic = {"A": ["od"], "ab": ["o...
If you want to search both ways, at the trade off of memory usage vs speed of searching, you could consider building a second reversed dictionary. I changed your example to have unique Latin keys in the first dictionary, and then create a second dictionary which has a slightly different structure (can't add to tuples, ...
51,187,904
Trying to read a `Parquet` file in PySpark but getting `Py4JJavaError`. I even tried reading it from the `spark-shell` and was able to do so. I cannot understand what I am doing wrong here in terms of the Python APIs that it is working in Scala and not in PySpark; ``` spark = SparkSession.builder.master("local").appNa...
2018/07/05
[ "https://Stackoverflow.com/questions/51187904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5129047/" ]
I figured out what was going wrong exactly. The `spark-shell` was using `Java 1.8`, but `PySpark` was using `Java 10.1`. There is some issue with Java 1.9/10 and Spark. Changed the default Java version to 1.8.
Spark runs on Java 8/11. For switching between Java versions, you can add this to your .bashrc/.zshrc file: ```sh alias j='f(){ export JAVA_HOME=$(/usr/libexec/java_home -v $1) };f' ``` Then in your terminal: ```sh source .zshrc ``` ```sh j 1.8 ``` ```sh java -version ``` This will change the version system-...
51,187,904
Trying to read a `Parquet` file in PySpark but getting `Py4JJavaError`. I even tried reading it from the `spark-shell` and was able to do so. I cannot understand what I am doing wrong here in terms of the Python APIs that it is working in Scala and not in PySpark; ``` spark = SparkSession.builder.master("local").appNa...
2018/07/05
[ "https://Stackoverflow.com/questions/51187904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5129047/" ]
I figured out what was going wrong exactly. The `spark-shell` was using `Java 1.8`, but `PySpark` was using `Java 10.1`. There is some issue with Java 1.9/10 and Spark. Changed the default Java version to 1.8.
Java Version: openjdk version "1.8.0\_275" OpenJDK Runtime Environment (build 1.8.0\_275-b01) OpenJDK 64-Bit Server VM (build 25.275-b01, mixed mode) Python Version: Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more i...
51,187,904
Trying to read a `Parquet` file in PySpark but getting `Py4JJavaError`. I even tried reading it from the `spark-shell` and was able to do so. I cannot understand what I am doing wrong here in terms of the Python APIs that it is working in Scala and not in PySpark; ``` spark = SparkSession.builder.master("local").appNa...
2018/07/05
[ "https://Stackoverflow.com/questions/51187904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5129047/" ]
Spark runs on Java 8/11. For switching between Java versions, you can add this to your .bashrc/.zshrc file: ```sh alias j='f(){ export JAVA_HOME=$(/usr/libexec/java_home -v $1) };f' ``` Then in your terminal: ```sh source .zshrc ``` ```sh j 1.8 ``` ```sh java -version ``` This will change the version system-...
Java Version: openjdk version "1.8.0\_275" OpenJDK Runtime Environment (build 1.8.0\_275-b01) OpenJDK 64-Bit Server VM (build 25.275-b01, mixed mode) Python Version: Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more i...
5,838,307
I'd like to create a drop-in replacement for python's `list`, that will allow me to know when an item is added or removed. A subclass of list, or something that implements the list interface will do equally well. I'd prefer a solution where I don't have to reimplement all of list's functionality though. Is there a easy...
2011/04/29
[ "https://Stackoverflow.com/questions/5838307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143091/" ]
To see what functions are defined in list, you can do ``` >>> dir(list) ``` Then you will see what you can override, try for instance this: ``` class MyList(list): def __iadd__(self, *arg, **kwargs): print "Adding" return list.__iadd__(self, *arg, **kwargs) ``` You probably need to do a few mo...
The [documentation for userlist](http://docs.python.org/release/2.5.2/lib/module-UserList.html) tells you to subclass `list` if you don't require your code to work with Python <2.2. You probably don't get around overriding at least the methods which allow to add/remove elements. Beware, this includes the slicing operat...
18,619,205
To start I will mention that I am new to the Python Language and come from a networking background. If you are wondering why I am using Python 2.5 it is due to some device constraints. What I am trying to do is count the number of lines that are in a string of data as seen below. (not in a file) ``` data = ['This','...
2013/09/04
[ "https://Stackoverflow.com/questions/18619205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2240963/" ]
`list.count` is used to get the count of an item in list, but you need to do a substring search in each item to get the count as 4. ``` >>> data = ['This','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\n'] ``` Total number of items...
Your first code does not work because you only have one `'\n'` in your actual list of strings. When you compare `'\n'` to something like `'nThis'`, then it will say that `\n` is not equal to that string and not include it in the count. What you can do is join the list into a string like so: ``` x = ''.join(num) ``` ...
54,997,210
Im currently writing a program in python where I have to figure out smileys like these `:)`, `:(`, `:-)`, `:-(` should be replace if it is followed by special characters and punctuation should be replaced in this pattern : ex : `Hi, this is good :)#` should be replaced to `Hi, this is good :)`. I have created regex pa...
2019/03/05
[ "https://Stackoverflow.com/questions/54997210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4045224/" ]
One approach is to use the following pattern: ``` (:\)|:\(|:-\)|:-\()[^A-Za-z0-9]+ ``` This matches *and* captures a smiley face, then matches any number of non alphanumeric characters immediately afterwards. The replacement is just the captured smiley face, thereby removing the non alpha characters. ``` input = "H...
you can escape special characters with `\` try: ``` re.sub("[^a-zA-Z0-9:):D:\-))]+", " " , words) ```
54,997,210
Im currently writing a program in python where I have to figure out smileys like these `:)`, `:(`, `:-)`, `:-(` should be replace if it is followed by special characters and punctuation should be replaced in this pattern : ex : `Hi, this is good :)#` should be replaced to `Hi, this is good :)`. I have created regex pa...
2019/03/05
[ "https://Stackoverflow.com/questions/54997210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4045224/" ]
The `[^a-zA-Z0-9:):D)]` pattern is erronrous since it is a character class meant to match sequences of chars. You need to add an alternative to this regex that will match char sequences. To remove any punctuation other than a certain list of smileys you may use ``` re.sub(r"(:-?[()D])|[^A-Za-z0-9\s]", r"\1" , s) ```...
you can escape special characters with `\` try: ``` re.sub("[^a-zA-Z0-9:):D:\-))]+", " " , words) ```
37,451,031
I have some python code to unzip a file and then remove it (the original file), but my code catches an exception: it cannot remove the file, because it is in use. I think the problem is that when the removal code runs, the unzip action has not finished, so the exception is thrown. So, how can I check the run state of ...
2016/05/26
[ "https://Stackoverflow.com/questions/37451031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213922/" ]
The documentation for ZipFile says: > > ZipFile is also a context manager and therefore supports the [with](https://docs.python.org/2/reference/compound_stmts.html#with) statement. > > > So, I'd recommend doing the following: ``` with zipfile.ZipFile(lfilename) as file: file.extract(filename, dir) remove(lfi...
Try closing the file before removing it. ``` file = zipfile.ZipFile(lfilename) for filename in file.namelist(): file.extract(filename,dir) file.close() remove(lfilename) ```
37,451,031
I have some python code to unzip a file and then remove it (the original file), but my code catches an exception: it cannot remove the file, because it is in use. I think the problem is that when the removal code runs, the unzip action has not finished, so the exception is thrown. So, how can I check the run state of ...
2016/05/26
[ "https://Stackoverflow.com/questions/37451031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213922/" ]
Try closing the file before removing it. ``` file = zipfile.ZipFile(lfilename) for filename in file.namelist(): file.extract(filename,dir) file.close() remove(lfilename) ```
You must first close the file. ``` file.close() remove(lfilename) ``` Alternatively you could do the following: ``` with ZipFile('lfilename') as file: for filename in file.namelist(): file.extract(filename,dir) remove(lfilename) ```
37,451,031
I have some python code to unzip a file and then remove it (the original file), but my code catches an exception: it cannot remove the file, because it is in use. I think the problem is that when the removal code runs, the unzip action has not finished, so the exception is thrown. So, how can I check the run state of ...
2016/05/26
[ "https://Stackoverflow.com/questions/37451031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2213922/" ]
The documentation for ZipFile says: > > ZipFile is also a context manager and therefore supports the [with](https://docs.python.org/2/reference/compound_stmts.html#with) statement. > > > So, I'd recommend doing the following: ``` with zipfile.ZipFile(lfilename) as file: file.extract(filename, dir) remove(lfi...
You must first close the file. ``` file.close() remove(lfilename) ``` Alternatively you could do the following: ``` with ZipFile('lfilename') as file: for filename in file.namelist(): file.extract(filename,dir) remove(lfilename) ```
33,687,594
I have been trying to debug this issue, but can't seem to figure it out. When debugging I can see that all the variables are where they should be, but I can't seem to get them out. When running I get the error message `'dict' object is not callable` This is the full error message from Django ``` Environment: Req...
2015/11/13
[ "https://Stackoverflow.com/questions/33687594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5039579/" ]
Dictionaries need square brackets ``` form_counter_currency = form.cleaned_data['form_counter_currency'] ``` although you may want to use `get` so you can provide a default ``` form_counter_currency = form.cleaned_data.get('form_counter_currency', None) ```
import this ``` from rest_framework.response import Response ``` Then after write this in **views.py** file ``` class userlist(APIView): def get(self,request): user1=webdata.objects.all() serializer=webdataserializers(user1,many=True) return Response(serializer.data) def post(self): pass ```
7,748,563
*Disclaimer: complete rewrite for clarity as of 10/14/2011* **Given** the `number` primitive in JavaScript is an [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754-2008) 64-bit floating point (*known in other languages as a double*), and [using floats to model currencies is a **bad idea**](https://stackoverflow.com/ques...
2011/10/13
[ "https://Stackoverflow.com/questions/7748563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902839/" ]
Both [bigdecimal.js](https://github.com/jhs/bigdecimal.js/) and [node-bigint](https://github.com/substack/node-bigint) have arbitrary precision. I'd go with bigint. bigdecimal is a GWT version of of Java's BigDecimal, clocking in at 113kb, so the code is not what one would call *readable*. **update:** [money.js](http...
There is a GREAT $.money class the does almost everything you could ever want from money in the ku4js-kernel library. You can find the documentation [here](http://kodmunki.github.io/ku4js-kernel/#money). Have fun! :{)}
7,748,563
*Disclaimer: complete rewrite for clarity as of 10/14/2011* **Given** the `number` primitive in JavaScript is an [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754-2008) 64-bit floating point (*known in other languages as a double*), and [using floats to model currencies is a **bad idea**](https://stackoverflow.com/ques...
2011/10/13
[ "https://Stackoverflow.com/questions/7748563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902839/" ]
Both [bigdecimal.js](https://github.com/jhs/bigdecimal.js/) and [node-bigint](https://github.com/substack/node-bigint) have arbitrary precision. I'd go with bigint. bigdecimal is a GWT version of of Java's BigDecimal, clocking in at 113kb, so the code is not what one would call *readable*. **update:** [money.js](http...
Was looking for something to handle money in node.js and came across this question, and then found esmoney which is a straightforward money calculator. <https://www.npmjs.com/package/es-money>
67,579,796
I am trying to change the JSON format using python. The received message has some key-value pairs and needs to change certain key names before forwarding the message. for normal key-value pairs, I have used "data. pop" method, data["newkey"]=data.pop("oldkey") . But it got complicated with nested key-values. This is ju...
2021/05/18
[ "https://Stackoverflow.com/questions/67579796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15715705/" ]
If the keys gonna be in the same format you can do something like this. ``` d = { "ev": "contact_form_submitted", "et": "form_submit", "id": "cl_app_id_001", "uid": "cl_app_id_001-uid-001", "mid": "cl_app_id_001-uid-001", "t": "Vegefoods - Free Bootstrap 4 Template by Colorlib", "p": "http...
Use the following code it will successfully convert it. ``` json1={ "atrk1": "form_varient", "atrv1": "red_top", "atrt1": "string", "atrk2": "ref", "atrv2": "XPOWJRICW993LKJD", "atrt2": "string" } json2={} keys=[] values=[] types=[] for i in json1: if i[:4]=='atrk': keys.append(json1[...
58,740,865
I'm trying to scrape this page/iframe with selenium/python but I can't insert any text in this selected form. [link](https://ibb.co/cF8ZRZP) ```py from selenium import webdriver from time import sleep driver = webdriver.Firefox() url = 'http://web.transparencia.pe.gov.br/despesas/despesa-geral/' driver.get(url) slee...
2019/11/07
[ "https://Stackoverflow.com/questions/58740865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7651009/" ]
In such kind of situation, the right tool is to use [std::integer\_sequence](https://en.cppreference.com/w/cpp/utility/integer_sequence) ``` #include <iostream> #include <utility> template <size_t N> void make() { std::cout << N << std::endl; } template <size_t... I> void do_make_helper(std::index_sequence<I...>) ...
As a start point with handcrafted index list: ``` template <size_t N> int make(); template<> int make<1>() { std::cout<< "First" << std::endl; return 100; } template<> int make<2>() { std::cout << "Second" << std::endl; return 200; } template<> int make<3>() { std::cout << "Third" << std::endl; return 100; } struct ...
58,740,865
I'm trying to scrape this page/iframe with selenium/python but I can't insert any text in this selected form. [link](https://ibb.co/cF8ZRZP) ```py from selenium import webdriver from time import sleep driver = webdriver.Firefox() url = 'http://web.transparencia.pe.gov.br/despesas/despesa-geral/' driver.get(url) slee...
2019/11/07
[ "https://Stackoverflow.com/questions/58740865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7651009/" ]
As a start point with handcrafted index list: ``` template <size_t N> int make(); template<> int make<1>() { std::cout<< "First" << std::endl; return 100; } template<> int make<2>() { std::cout << "Second" << std::endl; return 200; } template<> int make<3>() { std::cout << "Third" << std::endl; return 100; } struct ...
You can try this: ``` #include <utility> #include <cassert> struct Foo { Foo() {} Foo(std::size_t i) : i(i) {} std::size_t i; }; template <std::size_t... Is> void setFoo(std::size_t i, Foo& foo, std::index_sequence<Is...>) { ((i == Is && (foo = Foo{Is}, false)), ...); } int main() { for (std::s...
58,740,865
I'm trying to scrape this page/iframe with selenium/python but I can't insert any text in this selected form. [link](https://ibb.co/cF8ZRZP) ```py from selenium import webdriver from time import sleep driver = webdriver.Firefox() url = 'http://web.transparencia.pe.gov.br/despesas/despesa-geral/' driver.get(url) slee...
2019/11/07
[ "https://Stackoverflow.com/questions/58740865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7651009/" ]
In such kind of situation, the right tool is to use [std::integer\_sequence](https://en.cppreference.com/w/cpp/utility/integer_sequence) ``` #include <iostream> #include <utility> template <size_t N> void make() { std::cout << N << std::endl; } template <size_t... I> void do_make_helper(std::index_sequence<I...>) ...
You can try this: ``` #include <utility> #include <cassert> struct Foo { Foo() {} Foo(std::size_t i) : i(i) {} std::size_t i; }; template <std::size_t... Is> void setFoo(std::size_t i, Foo& foo, std::index_sequence<Is...>) { ((i == Is && (foo = Foo{Is}, false)), ...); } int main() { for (std::s...
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.co...
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here it is. By the way, if you need this operation often, you may create a function for `color_ins` creation, based on `pixel_ins`. Or even for any subnamedtuple! ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._...
`Point._fields + Color._fields` is simply a tuple. So given this: ``` from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) f = Point._fields + Color._fields ``` `type(f)` is just `tuple`. T...
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.co...
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
`Point._fields + Color._fields` is simply a tuple. So given this: ``` from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) f = Point._fields + Color._fields ``` `type(f)` is just `tuple`. T...
Another way you could do this is to make the arguments for "Pixel" align with what you actually want instead of flattening all of the arguments for its constituent parts. Instead of combining `Point._fields + Color._fields` to get the fields for Pixel, I think you should just have two parameters: `location` and `color...
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.co...
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
`Point._fields + Color._fields` is simply a tuple. So given this: ``` from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) f = Point._fields + Color._fields ``` `type(f)` is just `tuple`. T...
**Background** Originally I've asked this question because I had to support some spaghetti codebase that used tuples a lot but not giving any explanation about the values inside them. After some refactoring, I noticed that I need to extract some typed information from other tuples and was looking for some boilerplate ...
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.co...
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here it is. By the way, if you need this operation often, you may create a function for `color_ins` creation, based on `pixel_ins`. Or even for any subnamedtuple! ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._...
Here's an alternative implementation of Nikolay Prokopyev's `extract_sub_namedtuple` that uses a dictionary instead of `getattr`. ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) def extr...
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.co...
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here it is. By the way, if you need this operation often, you may create a function for `color_ins` creation, based on `pixel_ins`. Or even for any subnamedtuple! ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._...
Another way you could do this is to make the arguments for "Pixel" align with what you actually want instead of flattening all of the arguments for its constituent parts. Instead of combining `Point._fields + Color._fields` to get the fields for Pixel, I think you should just have two parameters: `location` and `color...
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.co...
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here it is. By the way, if you need this operation often, you may create a function for `color_ins` creation, based on `pixel_ins`. Or even for any subnamedtuple! ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._...
**Background** Originally I've asked this question because I had to support some spaghetti codebase that used tuples a lot but not giving any explanation about the values inside them. After some refactoring, I noticed that I need to extract some typed information from other tuples and was looking for some boilerplate ...
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.co...
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here's an alternative implementation of Nikolay Prokopyev's `extract_sub_namedtuple` that uses a dictionary instead of `getattr`. ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) def extr...
Another way you could do this is to make the arguments for "Pixel" align with what you actually want instead of flattening all of the arguments for its constituent parts. Instead of combining `Point._fields + Color._fields` to get the fields for Pixel, I think you should just have two parameters: `location` and `color...
42,369,259
**Preface** I was wondering how to conceptualize data classes in a *pythonic* way. Specifically I’m talking about DTO ([Data Transfer Object](https://martinfowler.com/eaaCatalog/dataTransferObject.html).) I found a good answer in @jeff-oneill question “[Using Python class as a data container](https://stackoverflow.co...
2017/02/21
[ "https://Stackoverflow.com/questions/42369259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598113/" ]
Here's an alternative implementation of Nikolay Prokopyev's `extract_sub_namedtuple` that uses a dictionary instead of `getattr`. ``` from collections import namedtuple Point = namedtuple('Point', 'x y') Color = namedtuple('Color', 'red green blue') Pixel = namedtuple('Pixel', Point._fields + Color._fields) def extr...
**Background** Originally I've asked this question because I had to support some spaghetti codebase that used tuples a lot but not giving any explanation about the values inside them. After some refactoring, I noticed that I need to extract some typed information from other tuples and was looking for some boilerplate ...
44,535,068
I want to cover a image with a transparent solid color overlay in the shape of a black-white mask Currently I'm using the following java code to implement this. ``` redImg = new Mat(image.size(), image.type(), new Scalar(255, 0, 0)); redImg.copyTo(image, mask); ``` I'm not familiar with the python api. So I want ...
2017/06/14
[ "https://Stackoverflow.com/questions/44535068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2640554/" ]
Now after I deal with all this Python, OpenCV, Numpy thing for a while, I find out it's quite simple to implement this with code: ``` image[mask] = (0, 0, 255) ``` -------------- the original answer -------------- I solved this by the following code: ``` redImg = np.zeros(image.shape, image.dtype) redImg[:,:] = (0...
The idea is to convert the mask to a binary format where pixels are either `0` (black) or `255` (white). White pixels represent sections that are kept while black sections are thrown away. Then set all white pixels on the mask to your desired `BGR` color. **Input image and mask** ![](https://i.stack.imgur.com/OfGZF.p...
44,535,068
I want to cover a image with a transparent solid color overlay in the shape of a black-white mask Currently I'm using the following java code to implement this. ``` redImg = new Mat(image.size(), image.type(), new Scalar(255, 0, 0)); redImg.copyTo(image, mask); ``` I'm not familiar with the python api. So I want ...
2017/06/14
[ "https://Stackoverflow.com/questions/44535068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2640554/" ]
Now after I deal with all this Python, OpenCV, Numpy thing for a while, I find out it's quite simple to implement this with code: ``` image[mask] = (0, 0, 255) ``` -------------- the original answer -------------- I solved this by the following code: ``` redImg = np.zeros(image.shape, image.dtype) redImg[:,:] = (0...
this is what worked for me: ``` red = np.ones(mask.shape) red = red*255 img[:,:,0][mask>0] = red[mask>0] ``` so I made a 2d array with solid 255 values and replaced it with my image's red band in pixels where the mask is not zero. [redmask](https://i.stack.imgur.com/kYbMV.png)
44,535,068
I want to cover a image with a transparent solid color overlay in the shape of a black-white mask Currently I'm using the following java code to implement this. ``` redImg = new Mat(image.size(), image.type(), new Scalar(255, 0, 0)); redImg.copyTo(image, mask); ``` I'm not familiar with the python api. So I want ...
2017/06/14
[ "https://Stackoverflow.com/questions/44535068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2640554/" ]
The idea is to convert the mask to a binary format where pixels are either `0` (black) or `255` (white). White pixels represent sections that are kept while black sections are thrown away. Then set all white pixels on the mask to your desired `BGR` color. **Input image and mask** ![](https://i.stack.imgur.com/OfGZF.p...
this is what worked for me: ``` red = np.ones(mask.shape) red = red*255 img[:,:,0][mask>0] = red[mask>0] ``` so I made a 2d array with solid 255 values and replaced it with my image's red band in pixels where the mask is not zero. [redmask](https://i.stack.imgur.com/kYbMV.png)
57,251,368
Kindly need some help please :) I have two date-time's i am using the date-time.combine to concatenate one is datetime.date (pretty much todays date) - the other is datetime.time (which is a manually defined time) keep getting stuck with the below error; ``` Traceback (most recent call last): File "sunsetTimer.py"...
2019/07/29
[ "https://Stackoverflow.com/questions/57251368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11847814/" ]
Look at how you have defined `currentTime`: ``` currentTime = localtimesTZ() ``` Your `localtimesTZ()` actually returns a tuple `currentTime, tday, todayDate`, which is what is assigned to `currentTime`. Not sure why you are doing that; returning just the `currentTime` should be sufficient, since it is a `datetime....
It sounds like you are just trying to do a simple comparison of a manually set date and check if that day is today. If that is the case it would be simpler to use the same class datetime. Below is a simple example checking if today (manually defined) is today (defined by python) from datetime import datetime ``` toda...
57,251,368
Kindly need some help please :) I have two date-time's i am using the date-time.combine to concatenate one is datetime.date (pretty much todays date) - the other is datetime.time (which is a manually defined time) keep getting stuck with the below error; ``` Traceback (most recent call last): File "sunsetTimer.py"...
2019/07/29
[ "https://Stackoverflow.com/questions/57251368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11847814/" ]
Look at how you have defined `currentTime`: ``` currentTime = localtimesTZ() ``` Your `localtimesTZ()` actually returns a tuple `currentTime, tday, todayDate`, which is what is assigned to `currentTime`. Not sure why you are doing that; returning just the `currentTime` should be sufficient, since it is a `datetime....
i think you are trying to compare a datetime with a tuple. This is the line that adds `currentTime` to a tuple: ``` currentTime, tday, todayDate = localtimesTZ() ``` You therefore need the index of `currentTime` from the tuple for comparison i.e ``` if currentTime[0] >= lightOffDT ``` Index is 0 because curr...
6,265,517
Can anyone name a language with all the following properties: 1. Has algebraic data types 2. Has good support for linear algebra 3. Is fast(-er than python, at least) 4. Has at least some functional programming ability (I don't need monads) 5. Has been heard of, is not dead, and can interface on a C calling level
2011/06/07
[ "https://Stackoverflow.com/questions/6265517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787480/" ]
Scala ===== According to [Wikipedia](http://en.wikipedia.org/wiki/Algebraic_data_type) it has algebraic datatypes. And it is [fast](http://www.scribd.com/doc/57021877/Loop-Recognition-in-C-Java-Go-Scala). Scala is both functional and object oriented. And it's a young language with a growing userbase but still to some ...
I'd say C and C++. And they work well with: * [Matlab](http://www.mathworks.com/products/matlab/) * [Maple](http://www.maplesoft.com/products/Maple/)
6,265,517
Can anyone name a language with all the following properties: 1. Has algebraic data types 2. Has good support for linear algebra 3. Is fast(-er than python, at least) 4. Has at least some functional programming ability (I don't need monads) 5. Has been heard of, is not dead, and can interface on a C calling level
2011/06/07
[ "https://Stackoverflow.com/questions/6265517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787480/" ]
I have my own favorite pet languages, and this isn't one of them, but it sounds to me like [R](http://www.r-project.org/) is probably what you are looking for. It seems to be *the* hot new language these days for people doing heavy math. As for the "faster than Python" part, that's tough to say. In general, languages...
I'd say C and C++. And they work well with: * [Matlab](http://www.mathworks.com/products/matlab/) * [Maple](http://www.maplesoft.com/products/Maple/)
6,265,517
Can anyone name a language with all the following properties: 1. Has algebraic data types 2. Has good support for linear algebra 3. Is fast(-er than python, at least) 4. Has at least some functional programming ability (I don't need monads) 5. Has been heard of, is not dead, and can interface on a C calling level
2011/06/07
[ "https://Stackoverflow.com/questions/6265517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/787480/" ]
Scala ===== According to [Wikipedia](http://en.wikipedia.org/wiki/Algebraic_data_type) it has algebraic datatypes. And it is [fast](http://www.scribd.com/doc/57021877/Loop-Recognition-in-C-Java-Go-Scala). Scala is both functional and object oriented. And it's a young language with a growing userbase but still to some ...
I have my own favorite pet languages, and this isn't one of them, but it sounds to me like [R](http://www.r-project.org/) is probably what you are looking for. It seems to be *the* hot new language these days for people doing heavy math. As for the "faster than Python" part, that's tough to say. In general, languages...
54,722,389
First off, let me say that yes I have researched this extensively for a few days now with no luck. I have looked at numerous examples and similar situations such as [this one](https://stackoverflow.com/questions/35149265/python-super-method-class-name-not-defined), but so far nothing has been able to resolve me issue. ...
2019/02/16
[ "https://Stackoverflow.com/questions/54722389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348576/" ]
[Here](https://stackoverflow.com/questions/38778158/how-to-do-nested-class-and-inherit-inside-the-class?rq=1) they do it like this ``` super(MainClass.InnerSubClass, self).__init__(thing, otherThing) ``` So that you can test it here is the full working example ``` class SomeClass(object): def __init__(self)...
If you have reasons for not using `MainClass.InnerSubClass`, you can also use `type(self)` or `self.__class__` ([OK, but which one](https://stackoverflow.com/questions/1060499/difference-between-typeobj-and-obj-class)) inside `__init__` to get the containing class. This works well lots of layers deep (which shouldn't h...
54,722,389
First off, let me say that yes I have researched this extensively for a few days now with no luck. I have looked at numerous examples and similar situations such as [this one](https://stackoverflow.com/questions/35149265/python-super-method-class-name-not-defined), but so far nothing has been able to resolve me issue. ...
2019/02/16
[ "https://Stackoverflow.com/questions/54722389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1348576/" ]
### There is no "class scope" in lookup order When creating a new class, the code in the body is executed and the resulting names are passed to `type` for creation. Python lookups go from inner to outer, but you don't have a "class level", only the names you define to become attributes/methods of your new class. In fa...
If you have reasons for not using `MainClass.InnerSubClass`, you can also use `type(self)` or `self.__class__` ([OK, but which one](https://stackoverflow.com/questions/1060499/difference-between-typeobj-and-obj-class)) inside `__init__` to get the containing class. This works well lots of layers deep (which shouldn't h...
17,903,820
code below creates a layout and displays some text in the layout. Next the layout is displayed on the console screen using raw display module from urwid library. (More info on my complete project can be gleaned from questions at [widget advice for a console project](https://stackoverflow.com/questions/17846930/required...
2013/07/28
[ "https://Stackoverflow.com/questions/17903820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2534758/" ]
It means that self.\_started has been evaluated to False. ``` assert <Some boolean expression>, "Message if exp is False" ``` If the expression is evaluated to True, nothing special will happen, but if the expression is evaluated to False an AssertionError exception will be thrown. You can try/except the line if yo...
You call `formLayout` before you `start` the screen. `formLayout` calls `ui.draw_screen`, which requires that the screen has been started.
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Thanks for all the answers and comments ! Thought for a while and got another answer in my previous way I have written the code. So, I am posting it. ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] e = d[:] # just a bit of trick/spice >>> for i in d: ... if d.count(i) == 1: ... e.remov...
You can also do like this : ``` data=[1,2,3,4,1,2,3,1,2,1,5,6] first_list=[] second_list=[] for i in data: if data.count(i)==1: first_list.append(i) else: second_list.append(i) print (second_list) ``` Result ====== [1, 2, 3, 1, 2, 3, 1, 2, 1]
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
I just thought I would add my method with set comprehension if anyone was interested. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> d = list({x for x in d if d.count(x) > 1}) >>> print d ['a', 1, 2, 'b', 4] ``` Python 2.7 and up I believe for the set comprehension functionality.
In python3 , use `dict.items()` instead of `dict.iteritems()` `iteritems()` was removed in python3, so you can't use this method anymore. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).items() if v > 1] ['a', 1, 2, ...
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Thanks for all the answers and comments ! Thought for a while and got another answer in my previous way I have written the code. So, I am posting it. ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] e = d[:] # just a bit of trick/spice >>> for i in d: ... if d.count(i) == 1: ... e.remov...
In python3 , use `dict.items()` instead of `dict.iteritems()` `iteritems()` was removed in python3, so you can't use this method anymore. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).items() if v > 1] ['a', 1, 2, ...
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Removing elements of a list while iterating over it is never a good idea. The appropriate way to do this would be to use a [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) with a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)...
In python3 , use `dict.items()` instead of `dict.iteritems()` `iteritems()` was removed in python3, so you can't use this method anymore. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).items() if v > 1] ['a', 1, 2, ...
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Thanks for all the answers and comments ! Thought for a while and got another answer in my previous way I have written the code. So, I am posting it. ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] e = d[:] # just a bit of trick/spice >>> for i in d: ... if d.count(i) == 1: ... e.remov...
For ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] ``` Using conversion to a set yields the unique items: ``` >>> d_unique = list(set(d)) ``` Non-unique items can be found using a list comprehension ``` >>> [item for item in d_unique if d.count(item) >1] [1, 2, 4, 'a', 'b'] ```
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Removing elements of a list while iterating over it is never a good idea. The appropriate way to do this would be to use a [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) with a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)...
I just thought I would add my method with set comprehension if anyone was interested. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> d = list({x for x in d if d.count(x) > 1}) >>> print d ['a', 1, 2, 'b', 4] ``` Python 2.7 and up I believe for the set comprehension functionality.
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Better use [collections.Counter()](http://docs.python.org/2/library/collections.html#counter-objects): ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).iteritems() if v > 1] ['a', 1, 2, 'b', 4] ``` Also see relevant thread: * [How ...
For ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] ``` Using conversion to a set yields the unique items: ``` >>> d_unique = list(set(d)) ``` Non-unique items can be found using a list comprehension ``` >>> [item for item in d_unique if d.count(item) >1] [1, 2, 4, 'a', 'b'] ```
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Removing elements of a list while iterating over it is never a good idea. The appropriate way to do this would be to use a [`collections.Counter`](http://docs.python.org/2/library/collections.html#collections.Counter) with a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)...
Thanks for all the answers and comments ! Thought for a while and got another answer in my previous way I have written the code. So, I am posting it. ``` d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] e = d[:] # just a bit of trick/spice >>> for i in d: ... if d.count(i) == 1: ... e.remov...
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
You can also do like this : ``` data=[1,2,3,4,1,2,3,1,2,1,5,6] first_list=[] second_list=[] for i in data: if data.count(i)==1: first_list.append(i) else: second_list.append(i) print (second_list) ``` Result ====== [1, 2, 3, 1, 2, 3, 1, 2, 1]
In python3 , use `dict.items()` instead of `dict.iteritems()` `iteritems()` was removed in python3, so you can't use this method anymore. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).items() if v > 1] ['a', 1, 2, ...
19,006,095
I wanted to find the non-unique elements in the list, but I am not able to figure out why this is not happening in the below code section. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> for i in d: ... if d.count(i) == 1: ... d.remove(i) ... >>> d [1, 2, 1, 2, 4, 4, 'a', 'b', ...
2013/09/25
[ "https://Stackoverflow.com/questions/19006095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969731/" ]
Better use [collections.Counter()](http://docs.python.org/2/library/collections.html#counter-objects): ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).iteritems() if v > 1] ['a', 1, 2, 'b', 4] ``` Also see relevant thread: * [How ...
In python3 , use `dict.items()` instead of `dict.iteritems()` `iteritems()` was removed in python3, so you can't use this method anymore. ``` >>> d = [1, 2, 1, 2, 4, 4, 5, 'a', 'b', 'a', 'b', 'c', 6,'f',3] >>> from collections import Counter >>> [k for k, v in Counter(d).items() if v > 1] ['a', 1, 2, ...
15,000,311
I am having trouble to start a python script and get the parameters I send to the script. ![enter image description here](https://i.stack.imgur.com/z2Pnj.jpg) As you can see if I start the following test script with python comand, it works, if not, well, no arguments are passed to the script :/ ``` import optparse i...
2013/02/21
[ "https://Stackoverflow.com/questions/15000311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095037/" ]
Check out [ImageResizer](http://imageresizing.net) - it's a suite of NuGet packages designed for this exact purpose. It runs eBay in Denmark, MSN Olympics, and a few other big sites. Dynamic image processing can be done safely and efficiently, but not in a sane amount of code. It's [trickier than it appears](http://...
I wouldn't recommend this but you can do next thing: ``` using (Image img = Image.FromStream(originalImage)) { using (Bitmap bitmap = new Bitmap(img, width, height)) { bitmap.Save(outputStream, ImageFormat.Jpeg); } } ``` Be aware that this could cause OutOfMemoryException.
14,486,802
What are common uses for Python's built-in `coerce` function? I can see applying it if I do not know the `type` of a numeric value [as per the documentation](http://docs.python.org/2/library/functions.html#coerce), but do other common usages exist? I would guess that `coerce()` is also called when performing arithmetic...
2013/01/23
[ "https://Stackoverflow.com/questions/14486802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/839375/" ]
Its a left over from [early python](http://docs.python.org/release/1.5.2/ref/numeric-types.html), it basically makes a tuple of numbers to be the same underlying number type e.g. ``` >>> type(10) <type 'int'> >>> type(10.0101010) <type 'float'> >>> nums = coerce(10, 10.001010) >>> type(nums[0]) <type 'float'> >>> type...
Python core programing says: > > Function coerce () provides the programmer do not rely on the Python interpreter, but custom two numerical type conversion." > > > e.g. ``` >>> coerce(1, 2) (1, 2) >>> >>> coerce(1.3, 134L) (1.3, 134.0) >>> >>> coerce(1, 134L) (1L, 134L) >>> >>> coerce(1j, 134L) (1j, (134+0j)) >>...
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $...
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
Put a dash in front of the process, this should kill the process group. ``` kill -s SIGINT -4189 ```
`kill -9 4189` Have a try, it should work!
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $...
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
`kill -9 4189` Have a try, it should work!
I had similar problem but accepted answer didn't work on my CentOS: ``` $ ps fx | grep [p]ython 30864 pts/0 S 0:00 python manage.py runserver 0.0.0.0:80 30866 pts/0 Sl 0:00 \_ /var/webapp/venv/bin/python manage.py runserver 0.0.0.0:80 $ kill -s SIGINT -30864 -bash: kill: 30864: invalid signal specifica...
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $...
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
`kill -9 4189` Have a try, it should work!
Try using `pkill`: ``` $ pkill -f "python3 manage.py runserver" ```
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $...
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
Put a dash in front of the process, this should kill the process group. ``` kill -s SIGINT -4189 ```
I had similar problem but accepted answer didn't work on my CentOS: ``` $ ps fx | grep [p]ython 30864 pts/0 S 0:00 python manage.py runserver 0.0.0.0:80 30866 pts/0 Sl 0:00 \_ /var/webapp/venv/bin/python manage.py runserver 0.0.0.0:80 $ kill -s SIGINT -30864 -bash: kill: 30864: invalid signal specifica...
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $...
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
Put a dash in front of the process, this should kill the process group. ``` kill -s SIGINT -4189 ```
Try using `pkill`: ``` $ pkill -f "python3 manage.py runserver" ```
14,411,394
I'm trying to send a signal to the django development server to kill the parent and child processes. ``` $ python manage.py runserver Validating models... 0 errors found Django version 1.4.1, using settings 'myproject.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. $...
2013/01/19
[ "https://Stackoverflow.com/questions/14411394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246871/" ]
I had similar problem but accepted answer didn't work on my CentOS: ``` $ ps fx | grep [p]ython 30864 pts/0 S 0:00 python manage.py runserver 0.0.0.0:80 30866 pts/0 Sl 0:00 \_ /var/webapp/venv/bin/python manage.py runserver 0.0.0.0:80 $ kill -s SIGINT -30864 -bash: kill: 30864: invalid signal specifica...
Try using `pkill`: ``` $ pkill -f "python3 manage.py runserver" ```
11,941,027
Python beginner here. I have two text files with the same format of tab-delimited information. They contain rows with 3 columns (identifier, chromosome and position) eg: File 1: ``` 2323 2 125 2324 3 754 ``` ... etc File 2: ``` 2323 2 150 2324 3 12000 ``` ... etc I want to create a list or matrix (not sure ex...
2012/08/13
[ "https://Stackoverflow.com/questions/11941027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/964689/" ]
There can be several answers to your question: 1. If you plan to use extensive computations with matrices, I advice you to look at [numpy](http://numpy.scipy.org/) library that is very efficient. You can see how to create matrices with numpy [here](http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html)...
You could use a dictionary having the identifier as the key and a list of the positions as the value. Then you can calculate the difference between the positions and have it as the 3rd element of the list. You can then iterate through the dictionary finding the largest value in position [2] of the dictionary's values. ...
11,941,027
Python beginner here. I have two text files with the same format of tab-delimited information. They contain rows with 3 columns (identifier, chromosome and position) eg: File 1: ``` 2323 2 125 2324 3 754 ``` ... etc File 2: ``` 2323 2 150 2324 3 12000 ``` ... etc I want to create a list or matrix (not sure ex...
2012/08/13
[ "https://Stackoverflow.com/questions/11941027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/964689/" ]
``` import collections d=collections.defaultdict(list) for f in ('file1','file2'): with open(f) as f1: for line in f1: ident, chrom, pos = line.split() d[ident].append(int( pos )) #big differences at end of list items = sorted(d.items(), key = lambda item: abs(item[1][1] - item[1][0...
You could use a dictionary having the identifier as the key and a list of the positions as the value. Then you can calculate the difference between the positions and have it as the 3rd element of the list. You can then iterate through the dictionary finding the largest value in position [2] of the dictionary's values. ...
61,232,982
This is my code: ``` users.age.mean().astype(int64) ``` (where users is the name of dataframe and age is a column in it) This is the error I am getting: ``` AttributeError Traceback (most recent call last) <ipython-input-29-10b672e7f7ae> in <module> ----> 1 users.age.mean().astype(int64...
2020/04/15
[ "https://Stackoverflow.com/questions/61232982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13322571/" ]
`users.age.mean()` returns a float not a series. Floats don't have `astype`, only pandas series. Try: `x = numpy.int64(users.age.mean())` Or: `x = int(users.age.mean())`
Try `int` before your function example: ``` X = int(users.age.mean()) ``` Hope it helps!
997,419
Is there any lib available to connect to yahoo messenger using either the standard protocol or the http way from python?
2009/06/15
[ "https://Stackoverflow.com/questions/997419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9789/" ]
Google is your friend. The [Python Package Index](http://pypi.python.org/pypi) has [several](http://pypi.python.org/pypi?%3Aaction=search&term=yahoo&submit=search) modules to do with Yahoo, including this [one](http://pypi.python.org/pypi/pyahoolib/0.2) which matches your requirements.
There is also the [Yahoo IM SDK](http://developer.yahoo.com/messenger/guide/index.html) that might help.
5,342,359
is it possible to Insert a python tuple in a postgresql database
2011/03/17
[ "https://Stackoverflow.com/questions/5342359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654796/" ]
Yes it is, PostgreSQL supports array as column type. ``` CREATE TABLE tuples_table ( tuple_of_strings text[], tuple_of_ints integer[] ); ``` Then inserting is done like this: ``` INSERT INTO tuples_table VALUES ( ('{"a","b","c"}', '{1,2}'), ('{"e",'f... etc"}', '{3,4,5}') ); ```
Really we need more information. What data is **inside** the tuple? Is it just integers? Just strings? Is it megabytes of images? If you had a Python tuple like `(4,6,2,"Hello",7)` you could insert **the string** `'(4,6,2,"Hello",7)'` into a Postgres database, but that's probably not the answer you're looking for. Yo...
5,342,359
is it possible to Insert a python tuple in a postgresql database
2011/03/17
[ "https://Stackoverflow.com/questions/5342359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654796/" ]
Yes, it is. Probably the easiest way is to serialise it using e.g. [marshal](http://docs.python.org/library/marshal.html), [pickle](http://docs.python.org/library/pickle.html) or [json](http://docs.python.org/library/json.html) and store it in a `text` field. Another approach is to use Postgres' multitude of [data typ...
Really we need more information. What data is **inside** the tuple? Is it just integers? Just strings? Is it megabytes of images? If you had a Python tuple like `(4,6,2,"Hello",7)` you could insert **the string** `'(4,6,2,"Hello",7)'` into a Postgres database, but that's probably not the answer you're looking for. Yo...
5,342,359
is it possible to Insert a python tuple in a postgresql database
2011/03/17
[ "https://Stackoverflow.com/questions/5342359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654796/" ]
Yes it is, PostgreSQL supports array as column type. ``` CREATE TABLE tuples_table ( tuple_of_strings text[], tuple_of_ints integer[] ); ``` Then inserting is done like this: ``` INSERT INTO tuples_table VALUES ( ('{"a","b","c"}', '{1,2}'), ('{"e",'f... etc"}', '{3,4,5}') ); ```
This question does not make any sense. You can insert using SQL whatever is supported by your database model. If you need a fancy mapper: look at an ORM like SQLAlchemy.
5,342,359
is it possible to Insert a python tuple in a postgresql database
2011/03/17
[ "https://Stackoverflow.com/questions/5342359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654796/" ]
Yes, it is. Probably the easiest way is to serialise it using e.g. [marshal](http://docs.python.org/library/marshal.html), [pickle](http://docs.python.org/library/pickle.html) or [json](http://docs.python.org/library/json.html) and store it in a `text` field. Another approach is to use Postgres' multitude of [data typ...
This question does not make any sense. You can insert using SQL whatever is supported by your database model. If you need a fancy mapper: look at an ORM like SQLAlchemy.
65,764,302
I am working through some exercises on python and my task is to create a program that can take a number, divide it by 2 if it is an even number. Or it will take the number, multiply it by 3, then add 1. It should ask for an input and afterwards it should wait for another input. My code looks like this, mind you I am n...
2021/01/17
[ "https://Stackoverflow.com/questions/65764302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15025453/" ]
So my understanding is you want the function to run indefinitely. this is my approach, through the use of a while loop ``` print("Enter a number") while True: c = int(input("")) numberCheck(c) ```
You could use a `while` loop with `True`: ```py while True: c = int(input()) numberCheck(c) ```
65,764,302
I am working through some exercises on python and my task is to create a program that can take a number, divide it by 2 if it is an even number. Or it will take the number, multiply it by 3, then add 1. It should ask for an input and afterwards it should wait for another input. My code looks like this, mind you I am n...
2021/01/17
[ "https://Stackoverflow.com/questions/65764302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15025453/" ]
If you want to run an infinite loop, that can be done with a while loop. ``` print('Please enter a number:') def numberCheck(c): if c % 2 == 0: print(c // 2) elif c % 2 == 1: print(3 * c + 1) while True: c = int(input()) numberCheck(c) ```
So my understanding is you want the function to run indefinitely. this is my approach, through the use of a while loop ``` print("Enter a number") while True: c = int(input("")) numberCheck(c) ```
65,764,302
I am working through some exercises on python and my task is to create a program that can take a number, divide it by 2 if it is an even number. Or it will take the number, multiply it by 3, then add 1. It should ask for an input and afterwards it should wait for another input. My code looks like this, mind you I am n...
2021/01/17
[ "https://Stackoverflow.com/questions/65764302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15025453/" ]
If you want to run an infinite loop, that can be done with a while loop. ``` print('Please enter a number:') def numberCheck(c): if c % 2 == 0: print(c // 2) elif c % 2 == 1: print(3 * c + 1) while True: c = int(input()) numberCheck(c) ```
You could use a `while` loop with `True`: ```py while True: c = int(input()) numberCheck(c) ```
2,341,972
I'm writing a basic html-proxy in python (3), and up to now I'm not using prebuild classes like http.server. I'm just starting a socket which accepts connection: ``` self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listen_socket.bind((socket.gethostname(), 4321)) self.listen_socket.listen(5...
2010/02/26
[ "https://Stackoverflow.com/questions/2341972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258267/" ]
You need to include an encoding when converting to a string, for example use: ``` >>> str(b'GET http://...', 'UTF-8') 'GET http://...' ``` If you don't use an encoding then as you've discovered you get something a little less helpful: ``` >>> str(b'GET http://...') "b'GET http://...'" ```
Also, you might want to check the `*HTTPServer` classes. They provide a wrapper around being HTTP servers and will also parse headers for you. If you can't, well, at the very least they will provide source code examples on how to do it!
2,341,972
I'm writing a basic html-proxy in python (3), and up to now I'm not using prebuild classes like http.server. I'm just starting a socket which accepts connection: ``` self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listen_socket.bind((socket.gethostname(), 4321)) self.listen_socket.listen(5...
2010/02/26
[ "https://Stackoverflow.com/questions/2341972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258267/" ]
You need to include an encoding when converting to a string, for example use: ``` >>> str(b'GET http://...', 'UTF-8') 'GET http://...' ``` If you don't use an encoding then as you've discovered you get something a little less helpful: ``` >>> str(b'GET http://...') "b'GET http://...'" ```
Methods are provided to convert between bytes and strings try str.encode() and bytes.decode() <http://python.about.com/od/python30/ss/30_strings_3.htm>
2,341,972
I'm writing a basic html-proxy in python (3), and up to now I'm not using prebuild classes like http.server. I'm just starting a socket which accepts connection: ``` self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listen_socket.bind((socket.gethostname(), 4321)) self.listen_socket.listen(5...
2010/02/26
[ "https://Stackoverflow.com/questions/2341972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258267/" ]
Also, you might want to check the `*HTTPServer` classes. They provide a wrapper around being HTTP servers and will also parse headers for you. If you can't, well, at the very least they will provide source code examples on how to do it!
Methods are provided to convert between bytes and strings try str.encode() and bytes.decode() <http://python.about.com/od/python30/ss/30_strings_3.htm>
19,806,494
I'm attempting to write a cython interface to the complex version of the MUMPS solver (zmumps). I'm running into some problems as I have no previous experience with either C or cython. Following the example of the [pymumps package](https://github.com/bfroehle/pymumps) I was able to get the real version of the code (dmu...
2013/11/06
[ "https://Stackoverflow.com/questions/19806494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2661958/" ]
Form a user standpoint hovering 1 cm over the screens highly inconvenient compared to placing a finger over the screen. Swipes seen by a front facing camera with a small aperture will be contaminated with the motion blur for a reasonable speed of swipe. A few years back I solved this problem by considering how motion...
You can't detect the motion vector with the proximity sensor. But there usually is a much smarter sensor that allows for much more precision: the front camera. It is more complex to read gestures with a camera, but you can definitely do that with OpenCV, for example.
50,242,147
It's easy in python to calculate simple permutations using [itertools.permutations()](https://docs.python.org/3/library/itertools.html#itertools.permutations). You can even find some [possible permutations of multiple lists](https://stackoverflow.com/q/2853212). ``` import itertools s=[ [ 'a', 'b', 'c'], ['d'], ['e',...
2018/05/08
[ "https://Stackoverflow.com/questions/50242147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99923/" ]
Like you suggested, do: ``` s = [x for y in s for x in y] ``` and then use your solution for finding permutations of different lengths: ``` for L in range(0, len(s)+1): for subset in itertools.combinations(s, L): print(subset) ``` would find: ``` () ('a',) ('b',) ('c',) ('d',) ('e',) ('f',) ('a', 'b'...
Here's a simple one liner (You can replace `feature_cols` instead of `s`) **Combinations:** ```py [combo for i in range(1, len(feature_cols) + 1) for combo in itertools.combinations(feature_cols, i) ] ``` **Permutations:** ```py [combo for i in range(1, len(feature_cols) + 1) for combo in itertools.permutations(fe...
63,096,451
I am pretty good at python and couldn't figure out how to use the Mojang API with python. I want to d something like `GET https://api.mojang.com/users/profiles/minecraft/<username>?at=<timestamp>`(from the API) but I can't figure out how to do it! Does anyone know how to do this? I'm in python 3.8. <https://wiki.vg/M...
2020/07/26
[ "https://Stackoverflow.com/questions/63096451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13996262/" ]
It's pretty straightforward, just replace `<username>` with the person's username, and the response will give your their `uuid`. Here is an example using **[`requests`](https://2.python-requests.org/en/master/)**: ``` import requests username = 'KrisJelbring' url = f'https://api.mojang.com/users/profiles/minecraft/{u...
The documentation is relatively straightforward. You want to send a `GET` request with their username: ```py import requests username = "Bob" resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{username}") uuid = resp.json()["id"] print(f"Bob's current UUID is {uuid}") ``` Optionally, you can ...
63,096,451
I am pretty good at python and couldn't figure out how to use the Mojang API with python. I want to d something like `GET https://api.mojang.com/users/profiles/minecraft/<username>?at=<timestamp>`(from the API) but I can't figure out how to do it! Does anyone know how to do this? I'm in python 3.8. <https://wiki.vg/M...
2020/07/26
[ "https://Stackoverflow.com/questions/63096451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13996262/" ]
You can find all the documentation [here](https://wiki.vg/Mojang_API) If you read the first few lines you will notice that there is a rate limit of 600 requests per 10 minutes. After that rate limit is reached you will raise a `KeyError`. To fix this we will use a try exception. Don't forget to install the `requests` ...
The documentation is relatively straightforward. You want to send a `GET` request with their username: ```py import requests username = "Bob" resp = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{username}") uuid = resp.json()["id"] print(f"Bob's current UUID is {uuid}") ``` Optionally, you can ...
65,073,434
I'm using the Mask\_RCNN package from this repo: `https://github.com/matterport/Mask_RCNN`. I tried to train my own dataset using this package but it gives me an error at the beginning. ``` 2020-11-30 12:13:16.577252: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library ...
2020/11/30
[ "https://Stackoverflow.com/questions/65073434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11919189/" ]
Go to mrcnn/model.py and add: ``` class AnchorsLayer(KL.Layer): def __init__(self, anchors, name="anchors", **kwargs): super(AnchorsLayer, self).__init__(name=name, **kwargs) self.anchors = tf.Variable(anchors) def call(self, dummy): return self.anchors def get_config(self): ...
ROOT CAUSE: The bahavior of Lambda layer of Keras in Tensorflow 2.X was changed from Tensorflow 1.X. In Keras in Tensorflow 1.X, all tf.Variable and tf.get\_variable are automatically tracked into the layer.weights via variable creator context so they receive gradient and trainable automatically. Such approach has prob...
37,848,815
I develop a web-app using Flask under Python3. I have a problem with postgresql enum type on db migrate/upgrade. I added a column "status" to model: ``` class Banner(db.Model): ... status = db.Column(db.Enum('active', 'inactive', 'archive', name='banner_status')) ... ``` Generated migration by `python m...
2016/06/16
[ "https://Stackoverflow.com/questions/37848815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2111562/" ]
I decided on this problem using that. I changed the code of migration, and migration looks like this: ``` from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): banner_status = postgresql.ENUM('active', 'inactive', 'archive', name='banner_status') banner_stat...
I think this way is more simple: ``` from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): # others_column = ... banner_status = postgresql.ENUM('active', 'inactive', 'archive', name='banner_status', create_type=False), nullable=False) ``` Also added the `...
12,576,734
I have a list which needs to be alphabetized(ignoring lower and uppercase) and printed with spaces and "+" seperating each element in the list. Here's my code: ``` #!/usr/bin/python3.2 fruit = ['A', 'banana', 'Watermelon', 'mango'] #list containing fruits name for diet in sorted(fruit): print(diet) ``` This pr...
2012/09/25
[ "https://Stackoverflow.com/questions/12576734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1687755/" ]
``` In [10]: fruit = ['A', 'banana', 'Watermelon', 'mango'] In [11]: ' + '.join(sorted(fruit, key=str.lower)) Out[11]: 'A + banana + mango + Watermelon' ``` for more detials visit : <http://docs.python.org/library/stdtypes.html#str.join> <http://wiki.python.org/moin/HowTo/Sorting/>
``` print(" + ".join(sorted(fruit, key=str.lower))) ```
39,505,630
This is my first question on stack overflow so bear with me, please. I am trying to download automatically (i.e. scrape) the text of some Italian laws from the website: [http://www.normattiva.it/](http://www.normattiva.it) I am using this code below (and similar permutations): ``` import requests, sys debug = {'ve...
2016/09/15
[ "https://Stackoverflow.com/questions/39505630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6696413/" ]
Once you click any link on the page with dev tools open, under the doc tab under Network: [![enter image description here](https://i.stack.imgur.com/orZHr.png)](https://i.stack.imgur.com/orZHr.png) You can see three links, the first is what we click on, the second returns the html that allows you to jump to a specifi...
wonderful, wonderful, wonderful Padraic. It works. Just had to edits slightly to clear imports but it's works wonderfully. Thanks very much. I am just discovering python's potential and you have made my journey much easier with this specific task. I would have not solved it alone. ``` import requests, sys import os f...
61,209,143
Python : 3.7.6 rpy2: 3.2.7 R: 3.3.3 I’m using GCE at AI Platform to perform some clustering. I’ve installed the r-base, updated properly, installed the python-rpy2 and I’m getting this error. ```py import rpy2.robjects as robjects error: symbol 'R_tryCatchError' not found in library '/usr/lib/R/lib/libR.so': /usr/...
2020/04/14
[ "https://Stackoverflow.com/questions/61209143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13214910/" ]
Here's a one-liner to update it without mutating the original array: ```js const updatedPersons = persons.map(p => p.id === id ? {...p, lastname} : p); ```
``` persons.forEach(person => { if(this.id === person.id) person.lastname = this.lastname }) ```
61,209,143
Python : 3.7.6 rpy2: 3.2.7 R: 3.3.3 I’m using GCE at AI Platform to perform some clustering. I’ve installed the r-base, updated properly, installed the python-rpy2 and I’m getting this error. ```py import rpy2.robjects as robjects error: symbol 'R_tryCatchError' not found in library '/usr/lib/R/lib/libR.so': /usr/...
2020/04/14
[ "https://Stackoverflow.com/questions/61209143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13214910/" ]
Here's a one-liner to update it without mutating the original array: ```js const updatedPersons = persons.map(p => p.id === id ? {...p, lastname} : p); ```
You need to loop over the array and add a condition to check if id matches `person.id` then add `lastname` to that person object. If you don't want to change the original array go for `.map()` else `.forEach()` With `.forEach()`: ``` persons.forEach(person => { if (person.id === id) { person.lastname = lastname ...
14,693,256
I've just finished up installing mod\_wsgi but I'm having problems starting my Pyramid application. I'm using python 2.7, Apache 2.2.3, mod\_wsgi 3.4 on CentOS 5.8 Here is my httpd.config file ``` WSGISocketPrefix run/wsgi <VirtualHost *:80> ServerName myapp.domain.com ServerAlias myapp WSGIApplicationGroup %{G...
2013/02/04
[ "https://Stackoverflow.com/questions/14693256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1210711/" ]
Often when you get syntax errors the preceding line is the culprit. Looking at [the Pyramid source](https://github.com/Pylons/pyramid/blob/master/pyramid/request.py) we see that the preceding line is: ``` @implementer(IRequest) ``` This is a class-decorator. Class-decorators were added to Python in version 2.6. The ...
I see two different wsgi files mentioned in the error /var/wsgi\_sites/project\_name\_api/apache.wsgi and /var/wsgi\_sites/myapp/apache.wsgi I cannot see any project\_name path reference in the httpd.conf that you pasted. You might want to start by reviewing that. If the problem persists then please post additiona...
47,747,532
I'm confronted with a problem as below and hoping some body could give some advice. I need to convert a lot of excel tables in different shapes into constructed data, the excel tables are as below. ``` |--------------------|----|----| |user:Sam | | | |--------------------|----|----| |mail:sam@ex...
2017/12/11
[ "https://Stackoverflow.com/questions/47747532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8226471/" ]
Looking at the patterns you have provided in your question we see that the data is sometimes in a separate cell, other times encoded in the text with a ':' separator. I'd flatten it out and parse the assembled text for a linear pattern. I suggest you read the excel file using something like [xlrd](https://pypi.python....
You have 4 types of files. If that is all you can write 1 function with 4 if statements. ``` def table_sort(file): If file == condition: extract_data_this_way elif file == other_condition: extract_data_this_way elif file == other_condition: extract_data_this_way else: ...
18,314,228
I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list e.g: ``` List = [a, bb, aa, ccc, dddd] Sublist1 = [a] Sublist2= [bb, aa] Sublist3= [ccc] Sublist2= [dddd] ``` How can i achieve this in python ? Thank you
2013/08/19
[ "https://Stackoverflow.com/questions/18314228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413734/" ]
I think you should use dictionaries ``` >>> dict_sublist = {} >>> for el in List: ... dict_sublist.setdefault(len(el), []).append(el) ... >>> dict_sublist {1: ['a'], 2: ['bb', 'aa'], 3: ['ccc'], 4: ['dddd']} ```
Assuming you're happy with a list of lists, indexed by length, how about something like ``` by_length = [] for word in List: wl = len(word) while len(by_length) < wl: by_length.append([]) by_length[wl].append(word) print "The words of length 3 are %s" % by_length[3] ```
18,314,228
I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list e.g: ``` List = [a, bb, aa, ccc, dddd] Sublist1 = [a] Sublist2= [bb, aa] Sublist3= [ccc] Sublist2= [dddd] ``` How can i achieve this in python ? Thank you
2013/08/19
[ "https://Stackoverflow.com/questions/18314228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413734/" ]
by using `itertools.groupby`: ``` values = ['a', 'bb', 'aa', 'ccc', 'dddd', 'eee'] from itertools import groupby output = [list(group) for key,group in groupby(sorted(values, key=len), key=len)] ``` The result is: ``` [['a'], ['bb', 'aa'], ['ccc', 'eee'], ['dddd']] ``` If your list is already sorted by string ...
I think you should use dictionaries ``` >>> dict_sublist = {} >>> for el in List: ... dict_sublist.setdefault(len(el), []).append(el) ... >>> dict_sublist {1: ['a'], 2: ['bb', 'aa'], 3: ['ccc'], 4: ['dddd']} ```
18,314,228
I have a list of strings and I like to split that list in different "sublists" based on the character length of the words in th list e.g: ``` List = [a, bb, aa, ccc, dddd] Sublist1 = [a] Sublist2= [bb, aa] Sublist3= [ccc] Sublist2= [dddd] ``` How can i achieve this in python ? Thank you
2013/08/19
[ "https://Stackoverflow.com/questions/18314228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413734/" ]
I think you should use dictionaries ``` >>> dict_sublist = {} >>> for el in List: ... dict_sublist.setdefault(len(el), []).append(el) ... >>> dict_sublist {1: ['a'], 2: ['bb', 'aa'], 3: ['ccc'], 4: ['dddd']} ```
``` >>> from collections import defaultdict >>> l = ["a", "bb", "aa", "ccc", "dddd"] >>> d = defaultdict(list) >>> for elem in l: ... d[len(elem)].append(elem) ... >>> sublists = list(d.values()) >>> print(sublists) [['a'], ['bb', 'aa'], ['ccc'], ['dddd']] ```