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
55,503,673
Let's say I have a python function whose single argument is a non-trivial type: ``` from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ``` ... and then I have a data structure that I have unpacked from a JSON source: ``` import j...
2019/04/03
[ "https://Stackoverflow.com/questions/55503673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
It's awkward that there's no built-in function for this but [`typeguard`](https://pypi.org/project/typeguard/) comes with a convenient `check_type()` function: ``` >>> from typeguard import check_type >>> from typing import List >>> check_type("foo", [1,2,"3"], List[int]) Traceback (most recent call last): ... TypeErr...
You would have to check your nested type structure manually - the type hint's are not enforced. Checking like this ist best done using **ABC (Abstract Meta Classes)** - so users can provide their derived classes that support the same accessing as default dict/lists: ``` import collections.abc def isCorrectType(dat...
55,503,673
Let's say I have a python function whose single argument is a non-trivial type: ``` from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ``` ... and then I have a data structure that I have unpacked from a JSON source: ``` import j...
2019/04/03
[ "https://Stackoverflow.com/questions/55503673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
Validating a type annotation is a non-trivial task. Python does not do it automatically, and writing your own validator is difficult because the [`typing`](https://docs.python.org/3/library/typing.html) module doesn't offer much of a useful interface. (In fact the internals of the `typing` module have changed so much s...
The common way to handle this is by making use of the fact that if whatever object you pass to `myfun` doesn't have the required functionality a corresponding exception will be raised (usually `TypeError` or `AttributeError`). So you would do the following: ``` try: myfun(data) except (TypeError, AttributeError) a...
55,503,673
Let's say I have a python function whose single argument is a non-trivial type: ``` from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ``` ... and then I have a data structure that I have unpacked from a JSON source: ``` import j...
2019/04/03
[ "https://Stackoverflow.com/questions/55503673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
Validating a type annotation is a non-trivial task. Python does not do it automatically, and writing your own validator is difficult because the [`typing`](https://docs.python.org/3/library/typing.html) module doesn't offer much of a useful interface. (In fact the internals of the `typing` module have changed so much s...
If all you want to do is json-parsing, you should just use [pydantic](https://pydantic-docs.helpmanual.io/). But, I encountered the same problem where I wanted to check the type of python objects, so I created a simpler solution than in other answers that handles at least complex types with nested lists and dictionari...
55,503,673
Let's say I have a python function whose single argument is a non-trivial type: ``` from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ``` ... and then I have a data structure that I have unpacked from a JSON source: ``` import j...
2019/04/03
[ "https://Stackoverflow.com/questions/55503673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
Validating a type annotation is a non-trivial task. Python does not do it automatically, and writing your own validator is difficult because the [`typing`](https://docs.python.org/3/library/typing.html) module doesn't offer much of a useful interface. (In fact the internals of the `typing` module have changed so much s...
You would have to check your nested type structure manually - the type hint's are not enforced. Checking like this ist best done using **ABC (Abstract Meta Classes)** - so users can provide their derived classes that support the same accessing as default dict/lists: ``` import collections.abc def isCorrectType(dat...
55,503,673
Let's say I have a python function whose single argument is a non-trivial type: ``` from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ``` ... and then I have a data structure that I have unpacked from a JSON source: ``` import j...
2019/04/03
[ "https://Stackoverflow.com/questions/55503673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
Validating a type annotation is a non-trivial task. Python does not do it automatically, and writing your own validator is difficult because the [`typing`](https://docs.python.org/3/library/typing.html) module doesn't offer much of a useful interface. (In fact the internals of the `typing` module have changed so much s...
It's awkward that there's no built-in function for this but [`typeguard`](https://pypi.org/project/typeguard/) comes with a convenient `check_type()` function: ``` >>> from typeguard import check_type >>> from typing import List >>> check_type("foo", [1,2,"3"], List[int]) Traceback (most recent call last): ... TypeErr...
55,503,673
Let's say I have a python function whose single argument is a non-trivial type: ``` from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ``` ... and then I have a data structure that I have unpacked from a JSON source: ``` import j...
2019/04/03
[ "https://Stackoverflow.com/questions/55503673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
First of all, even though I think you are aware but rather for the sake of completeness, the typing library contains types for **type hints**. These type hints are used by IDE's to check if your code is somewhat sane, and also serves as documentation what types a developer expects. To check whether a variable is a typ...
If all you want to do is json-parsing, you should just use [pydantic](https://pydantic-docs.helpmanual.io/). But, I encountered the same problem where I wanted to check the type of python objects, so I created a simpler solution than in other answers that handles at least complex types with nested lists and dictionari...
55,503,673
Let's say I have a python function whose single argument is a non-trivial type: ``` from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ``` ... and then I have a data structure that I have unpacked from a JSON source: ``` import j...
2019/04/03
[ "https://Stackoverflow.com/questions/55503673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
Validating a type annotation is a non-trivial task. Python does not do it automatically, and writing your own validator is difficult because the [`typing`](https://docs.python.org/3/library/typing.html) module doesn't offer much of a useful interface. (In fact the internals of the `typing` module have changed so much s...
First of all, even though I think you are aware but rather for the sake of completeness, the typing library contains types for **type hints**. These type hints are used by IDE's to check if your code is somewhat sane, and also serves as documentation what types a developer expects. To check whether a variable is a typ...
55,503,673
Let's say I have a python function whose single argument is a non-trivial type: ``` from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ``` ... and then I have a data structure that I have unpacked from a JSON source: ``` import j...
2019/04/03
[ "https://Stackoverflow.com/questions/55503673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
It's awkward that there's no built-in function for this but [`typeguard`](https://pypi.org/project/typeguard/) comes with a convenient `check_type()` function: ``` >>> from typeguard import check_type >>> from typing import List >>> check_type("foo", [1,2,"3"], List[int]) Traceback (most recent call last): ... TypeErr...
If all you want to do is json-parsing, you should just use [pydantic](https://pydantic-docs.helpmanual.io/). But, I encountered the same problem where I wanted to check the type of python objects, so I created a simpler solution than in other answers that handles at least complex types with nested lists and dictionari...
55,503,673
Let's say I have a python function whose single argument is a non-trivial type: ``` from typing import List, Dict ArgType = List[Dict[str, int]] # this could be any non-trivial type def myfun(a: ArgType) -> None: ... ``` ... and then I have a data structure that I have unpacked from a JSON source: ``` import j...
2019/04/03
[ "https://Stackoverflow.com/questions/55503673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
You would have to check your nested type structure manually - the type hint's are not enforced. Checking like this ist best done using **ABC (Abstract Meta Classes)** - so users can provide their derived classes that support the same accessing as default dict/lists: ``` import collections.abc def isCorrectType(dat...
If all you want to do is json-parsing, you should just use [pydantic](https://pydantic-docs.helpmanual.io/). But, I encountered the same problem where I wanted to check the type of python objects, so I created a simpler solution than in other answers that handles at least complex types with nested lists and dictionari...
72,709,963
Consider i have 5 files in 5 different location. Example = fileA in XYZ location fileB in ZXC location fileC in XBN location so on I want to check if these files are actually saved in that location if they are not re run the code above that saves the file. Ex: ``` if: fileA, fileB so on are present in their particu...
2022/06/22
[ "https://Stackoverflow.com/questions/72709963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19189066/" ]
You can store all your files with their locations in a list and then iterate all locations for existence then you can decide further what to do. A Python example: ```py from os.path import exists # all files to check in different locations locations = [ '/some/location/xyz/fileA', '/other/location/fileB', ...
I'm not a python dev, and I just wanted try to contribute to the community. The first answer is way better than mine, but I'd like to share my solution for that question. You could use `sys` to pass the files' names, inside a `try` block to handle when the files are not found. If you run the script from a location whi...
19,001,826
It starts with a url on the web (ex: <http://python.org>), fetches the web-page corresponding to that url, and parses all the links on that page into a repository of links. Next, it fetches the contents of any of the url from the repository just created, parses the links from this new content into the repository and co...
2013/09/25
[ "https://Stackoverflow.com/questions/19001826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3001533/" ]
`sfence` doesn't block StoreLoad reordering. Unless there are any NT stores in flight, it's architecturally a no-op. Stores already wait for older stores to commit before they themselves commit to L1d and become globally visible, because x86 doesn't allow StoreStore reordering. (Except for NT stores / stores to WC memo...
You don't need an `mfence`; `sfence` does indeed suffice. In fact, you never need `lfence` in x86 unless you are dealing with a device. But Intel (and I think AMD) has (or at least had) a single implementation shared with `mfence` and `sfence` (namely, flushing the store buffer), so there was no performance advantage t...
66,105,974
I am new to regex and was wondering how the following could be implemented. For example, I have a css file with `url('Inter.ttf')` and my python program would convert this url to `url('user/Inter.ttf')`. However, I run into a problem when I try to avoid double replacement. So how can I use regex to tell python the dif...
2021/02/08
[ "https://Stackoverflow.com/questions/66105974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15168919/" ]
You can use a `look-around` method to insert the `/user/` dynamically: ``` (?<=url\(')/*(?=(?:.*?Inter\.ttf)'\)) ``` And then use `re.sub` to replace with `/user/`: ``` strings = ["url('Inter.ttf')", "url('/hello/Inter.ttf')"] p = re.compile(r"(?<=url\(')/?(?=(?:.*?Inter\.ttf)'\))") for s in strings: s = re.s...
a simple way to do that is like this without regex: ``` fin = open("input.css", "rt") fout = open("out.css", "wt") for line in fin: if "'Inter.ttf'" in line: fout.write(line.replace("'Inter.ttf'", "'/user/Inter.ttf'")) elif "'/hello/Inter.ttf'" in line: fout.write(line.replace("'/hello/Inter.tt...
25,623,841
I am using Python 2.7.5. When raising an int to the power of zero you would expect to see either -1 or 1 depending on whether the numerator was positive or negative. Typing directly into the python interpreter yields the following: ``` >>> -2418**0 -1 ``` This is the correct answer. However when I type this into th...
2014/09/02
[ "https://Stackoverflow.com/questions/25623841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139011/" ]
Why would you expect it to be -1? 1 is (according to the definition I was taught) the correct answer. The first gives the incorrect answer due to operator precedence. ``` (-1)**0 = 1 -1**0 = -(1**0) = -(1) = -1 ``` See Wikipedia for the definition of the 0 exponent: <http://en.wikipedia.org/wiki/Exponentiation#Zer...
`-2418**0` is interpreted (mathematically) as `-1 * (2418**0)` so the answer is `-1 * 1 = -1`. Exponentiation happens before multiplication. In your second example you bind the variable `result` to `-1`. The next line takes the variable `result` and raises it to the power of `0` so you get `1`. In other words you're d...
25,623,841
I am using Python 2.7.5. When raising an int to the power of zero you would expect to see either -1 or 1 depending on whether the numerator was positive or negative. Typing directly into the python interpreter yields the following: ``` >>> -2418**0 -1 ``` This is the correct answer. However when I type this into th...
2014/09/02
[ "https://Stackoverflow.com/questions/25623841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139011/" ]
`-2418**0` is interpreted (mathematically) as `-1 * (2418**0)` so the answer is `-1 * 1 = -1`. Exponentiation happens before multiplication. In your second example you bind the variable `result` to `-1`. The next line takes the variable `result` and raises it to the power of `0` so you get `1`. In other words you're d...
Your maths is wrong. `(-2481)**0` should be 1. According to wikipedia, `Any nonzero number raised by the exponent 0 is 1`.
25,623,841
I am using Python 2.7.5. When raising an int to the power of zero you would expect to see either -1 or 1 depending on whether the numerator was positive or negative. Typing directly into the python interpreter yields the following: ``` >>> -2418**0 -1 ``` This is the correct answer. However when I type this into th...
2014/09/02
[ "https://Stackoverflow.com/questions/25623841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139011/" ]
Why would you expect it to be -1? 1 is (according to the definition I was taught) the correct answer. The first gives the incorrect answer due to operator precedence. ``` (-1)**0 = 1 -1**0 = -(1**0) = -(1) = -1 ``` See Wikipedia for the definition of the 0 exponent: <http://en.wikipedia.org/wiki/Exponentiation#Zer...
Your maths is wrong. `(-2481)**0` should be 1. According to wikipedia, `Any nonzero number raised by the exponent 0 is 1`.
24,648,132
so for some reason this error([Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions), keeps occurring. when i try to use registration in Django. I am using windows 7 and pycharm IDE with django 1.65. I have already tried different ports to run server (8001 & 8008) and also ad...
2014/07/09
[ "https://Stackoverflow.com/questions/24648132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3818829/" ]
The problem has to do with your email server setup. Instead of figuring out what to fix, just set your `EMAIL_BACKEND` in `settings.py` to the following: ``` if DEBUG: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ``` This way, any email sent by django will be shown in the console instead of a...
This has nothing to do with your webserver ports, this is to do with the host and port that `smtplib` is trying to open in order to send an email. These are controlled by `settings.EMAIL_HOST` and `settings.EMAIL_PORT`. There are other settings too, see the [documentation](https://docs.djangoproject.com/en/1.7/topics/...
56,553,902
I have been trying to extract stock prices using pandas\_datareader. data, but I kept receiving an error message. I have checked other threads relating to this problem and, I have tried downloading data reader using conda install DataReader and also tried pip install DataReader. ``` import pandas as pd import datet...
2019/06/12
[ "https://Stackoverflow.com/questions/56553902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11290634/" ]
`for number in d:` will iterate through the keys of the dictionary, not values. You can use ``` for number in d.values(): ``` or ``` for name, number in d.items(): ``` if you also need the names.
You need to iterate over the key-value pairs in the dict with `items()` ``` def overNum(): d = {'Tom':'93', 'Hannah':'83', 'Jack':'94'} count = 0 for name, number in d.items(): if int(number) >= 90: count += 1 print(count) ``` Also there are some issues with the `if` statement th...
56,553,902
I have been trying to extract stock prices using pandas\_datareader. data, but I kept receiving an error message. I have checked other threads relating to this problem and, I have tried downloading data reader using conda install DataReader and also tried pip install DataReader. ``` import pandas as pd import datet...
2019/06/12
[ "https://Stackoverflow.com/questions/56553902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11290634/" ]
`for number in d:` will iterate through the keys of the dictionary, not values. You can use ``` for number in d.values(): ``` or ``` for name, number in d.items(): ``` if you also need the names.
You can collect the items in a list that are greater or equal to 90 then take the [`len()`](https://docs.python.org/3/library/functions.html#len): ``` >>> d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'} >>> len([v for v in d.values() if int(v) >= 90]) 2 ``` Or using [`sum()`](https://docs.python.org/3/library/function...
56,553,902
I have been trying to extract stock prices using pandas\_datareader. data, but I kept receiving an error message. I have checked other threads relating to this problem and, I have tried downloading data reader using conda install DataReader and also tried pip install DataReader. ``` import pandas as pd import datet...
2019/06/12
[ "https://Stackoverflow.com/questions/56553902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11290634/" ]
`for number in d:` will iterate through the keys of the dictionary, not values. You can use ``` for number in d.values(): ``` or ``` for name, number in d.items(): ``` if you also need the names.
You could use `filter`: ``` len(list(filter(lambda x: int(x[1]) > 90, d.items()))) ```
56,553,902
I have been trying to extract stock prices using pandas\_datareader. data, but I kept receiving an error message. I have checked other threads relating to this problem and, I have tried downloading data reader using conda install DataReader and also tried pip install DataReader. ``` import pandas as pd import datet...
2019/06/12
[ "https://Stackoverflow.com/questions/56553902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11290634/" ]
You can collect the items in a list that are greater or equal to 90 then take the [`len()`](https://docs.python.org/3/library/functions.html#len): ``` >>> d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'} >>> len([v for v in d.values() if int(v) >= 90]) 2 ``` Or using [`sum()`](https://docs.python.org/3/library/function...
You need to iterate over the key-value pairs in the dict with `items()` ``` def overNum(): d = {'Tom':'93', 'Hannah':'83', 'Jack':'94'} count = 0 for name, number in d.items(): if int(number) >= 90: count += 1 print(count) ``` Also there are some issues with the `if` statement th...
56,553,902
I have been trying to extract stock prices using pandas\_datareader. data, but I kept receiving an error message. I have checked other threads relating to this problem and, I have tried downloading data reader using conda install DataReader and also tried pip install DataReader. ``` import pandas as pd import datet...
2019/06/12
[ "https://Stackoverflow.com/questions/56553902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11290634/" ]
You could use `filter`: ``` len(list(filter(lambda x: int(x[1]) > 90, d.items()))) ```
You need to iterate over the key-value pairs in the dict with `items()` ``` def overNum(): d = {'Tom':'93', 'Hannah':'83', 'Jack':'94'} count = 0 for name, number in d.items(): if int(number) >= 90: count += 1 print(count) ``` Also there are some issues with the `if` statement th...
56,553,902
I have been trying to extract stock prices using pandas\_datareader. data, but I kept receiving an error message. I have checked other threads relating to this problem and, I have tried downloading data reader using conda install DataReader and also tried pip install DataReader. ``` import pandas as pd import datet...
2019/06/12
[ "https://Stackoverflow.com/questions/56553902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11290634/" ]
You can collect the items in a list that are greater or equal to 90 then take the [`len()`](https://docs.python.org/3/library/functions.html#len): ``` >>> d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'} >>> len([v for v in d.values() if int(v) >= 90]) 2 ``` Or using [`sum()`](https://docs.python.org/3/library/function...
You could use `filter`: ``` len(list(filter(lambda x: int(x[1]) > 90, d.items()))) ```
20,023,709
I'm working on a laser tag game project that uses pygame and Raspberry Pi. In the game, I need a background timer in order to keep track of game time. Currently I'm using the following to do this but doesnt seem to work correctly: ``` pygame.timer.get_ticks() ``` My second problem is resetting this timer when the ga...
2013/11/16
[ "https://Stackoverflow.com/questions/20023709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1478315/" ]
You could use the `Timer` class in Android, and set a repeating timer, with a initial delay. ``` Timer timer = new Timer(); timer.schedule(TimerTask task, long delay, long period) ``` A `TimerTask` is very much like a `Runnable`. See: <http://developer.android.com/reference/java/util/Timer.html>
I've used 2 timers : ``` handler.postDelayed(runnable, 1500); // Creating a timer for 1.5 seconds ``` this created a 1.5sec timer, while inside the timer loop : ``` private Runnable runnable = new Runnable() { @Override public void run() { Foo(); handler.postDelayed(this, 1500); } }; ```...
72,393
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed: ``` result = re.match("a_regex_of_pure_awe...
2008/09/16
[ "https://Stackoverflow.com/questions/72393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string. [Python regex docs](http://docs.python.org/lib/module-re.html) [Matching vs searching](http://docs.python.org/lib/m...
Are you using the `re.match()` or `re.search()` method? My understanding is that `re.match()` assumes a "`^`" at the beginning of your expression and will only search at the beginning of the text, while `re.search()` acts more like the Perl regular expressions and will only match the beginning of the text if you includ...
72,393
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed: ``` result = re.match("a_regex_of_pure_awe...
2008/09/16
[ "https://Stackoverflow.com/questions/72393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
``` >>> import re >>> pattern = re.compile("url") >>> string = " url" >>> pattern.match(string) >>> pattern.search(string) <_sre.SRE_Match object at 0xb7f7a6e8> ```
Are you using the `re.match()` or `re.search()` method? My understanding is that `re.match()` assumes a "`^`" at the beginning of your expression and will only search at the beginning of the text, while `re.search()` acts more like the Perl regular expressions and will only match the beginning of the text if you includ...
72,393
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed: ``` result = re.match("a_regex_of_pure_awe...
2008/09/16
[ "https://Stackoverflow.com/questions/72393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(your_html) for a in soup.findAll('a', href=True): # do something with `a` w/ href attribute print a['href'] ```
Are you using the `re.match()` or `re.search()` method? My understanding is that `re.match()` assumes a "`^`" at the beginning of your expression and will only search at the beginning of the text, while `re.search()` acts more like the Perl regular expressions and will only match the beginning of the text if you includ...
72,393
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed: ``` result = re.match("a_regex_of_pure_awe...
2008/09/16
[ "https://Stackoverflow.com/questions/72393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string. [Python regex docs](http://docs.python.org/lib/module-re.html) [Matching vs searching](http://docs.python.org/lib/m...
``` >>> import re >>> pattern = re.compile("url") >>> string = " url" >>> pattern.match(string) >>> pattern.search(string) <_sre.SRE_Match object at 0xb7f7a6e8> ```
72,393
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed: ``` result = re.match("a_regex_of_pure_awe...
2008/09/16
[ "https://Stackoverflow.com/questions/72393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string. [Python regex docs](http://docs.python.org/lib/module-re.html) [Matching vs searching](http://docs.python.org/lib/m...
``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(your_html) for a in soup.findAll('a', href=True): # do something with `a` w/ href attribute print a['href'] ```
65,393,659
I built an application to suggest email addresses fixes, and I need to detect email addresses that are basically not real existing email addresses, like the following: [email protected] [email protected] 87c0d782-e09f-056f-f544-c6ec9d17943c@microso...
2020/12/21
[ "https://Stackoverflow.com/questions/65393659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4442606/" ]
This is what I come up with: ```js // gibberish detector js (function (h) { function e(c, b, a) { return c < b ? (a = b - c, Math.log(b) / Math.log(a) * 100) : c > a ? (b = c - a, Math.log(100 - a) / Math.log(b) * 100) : 0 } function k(c) { for (var b = {}, a = "", d = 0; d < c.length; ++d)c[d] in b || (b[c[d]] = ...
A thing you may consider doing is checking each time how random each string is, then sort the results according to their score and given a threshold exclude the ones with high randomness. It is inevitable that you will miss some. There are some implementations for checking the randomness of strings, for example: * <h...
6,116,527
I'm trying to get the pymysql module working with python3 on a Macintosh. Note that I am a beginning python user who decided to switch from ruby and am trying to build a simple (sigh) database project to drive my learning python. In a simple (I thought) test program, I am getting a syntax error in confiparser.py (whic...
2011/05/24
[ "https://Stackoverflow.com/questions/6116527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57246/" ]
You're most certainly running the code with a 2.x interpreter. I wonder why it even tries to import 3.x libraries, perhaps the answer lies in your installation process - but that's a different question. Anyway, this (before any other `import`s) ``` import sys print(sys.version) ``` should show which Python version i...
In Python 3.2 the configparser module does indeed look that way. Importing it works fine from Python 3.2, but *not* from Python 2. Am I right in guessing you get the error when you try to run your module with Komodo? Then you just have configured the wrong Python executable.
67,052,300
I've been trying to find the best way to convert a given GIF image to a sequence of BMP files using python. I've found some libraries like Wand and ImageMagic but still haven't found a good example to accomplish this.
2021/04/12
[ "https://Stackoverflow.com/questions/67052300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2163839/" ]
Reading an animated GIF file using Python Image Processing Library - Pillow --------------------------------------------------------------------------- ``` from PIL import Image from PIL import GifImagePlugin imageObject = Image.open("./xmas.gif") print(imageObject.is_animated) print(imageObject.n_frames) ``` Disp...
In Imagemagick, which comes with Linux and can be installed for Windows or Mac OSX, ``` convert image.gif -coalese image.bmp ``` the results will be image-0.bmp, image-1.bmp ... Use `convert` for Imagemagick 6 or replace `convert` with `magick` for Imagemagick 7.
67,052,300
I've been trying to find the best way to convert a given GIF image to a sequence of BMP files using python. I've found some libraries like Wand and ImageMagic but still haven't found a good example to accomplish this.
2021/04/12
[ "https://Stackoverflow.com/questions/67052300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2163839/" ]
```py from wand.image import Image with Image(filename="animation.gif") as img: img.coalesce() img.save(filename="frame%02d.bmp) ``` Use `Image.coalesce()` to rebuild optimized frames, and ImageMagick's "Percent Escapes" format (`%02d`) to write image frame as a separate BMP file.
In Imagemagick, which comes with Linux and can be installed for Windows or Mac OSX, ``` convert image.gif -coalese image.bmp ``` the results will be image-0.bmp, image-1.bmp ... Use `convert` for Imagemagick 6 or replace `convert` with `magick` for Imagemagick 7.
44,963,360
I am very new to python. Long time user of stackoverflow but first time posting a question. I am trying to extract data from website using beautifulsoup. [Sample Code where I want to extract is (listed in and tagged in data)](https://i.stack.imgur.com/AASRq.jpg) The was able to extract in to list but I am unable to ex...
2017/07/07
[ "https://Stackoverflow.com/questions/44963360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8268739/" ]
I don't know if there's a slicker way, but a straightforward for loop will do the trick: ``` $frequency = []; for ($i = 0; $i < sizeof($date); $i++) { $frequency[] = array($date[$i], $time_start[$i], $time_end[$i]); } print_r($frequency); // Output: // Array // ( // [0] => Array // ( // ...
You can also map them: ``` $result = array_map(function ($value1,$value2,$value3) { return [$value1,$value2,$value3]; }, $date,$time_start,$time_end); ```
44,963,360
I am very new to python. Long time user of stackoverflow but first time posting a question. I am trying to extract data from website using beautifulsoup. [Sample Code where I want to extract is (listed in and tagged in data)](https://i.stack.imgur.com/AASRq.jpg) The was able to extract in to list but I am unable to ex...
2017/07/07
[ "https://Stackoverflow.com/questions/44963360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8268739/" ]
I don't know if there's a slicker way, but a straightforward for loop will do the trick: ``` $frequency = []; for ($i = 0; $i < sizeof($date); $i++) { $frequency[] = array($date[$i], $time_start[$i], $time_end[$i]); } print_r($frequency); // Output: // Array // ( // [0] => Array // ( // ...
Or you could do: ``` $frequency=array_map(null,$date, $time_start, $time_end); ``` see here: <http://php.net/manual/de/function.array-map.php> and for a short demo, here: <http://rextester.com/VJRCA63297>
44,963,360
I am very new to python. Long time user of stackoverflow but first time posting a question. I am trying to extract data from website using beautifulsoup. [Sample Code where I want to extract is (listed in and tagged in data)](https://i.stack.imgur.com/AASRq.jpg) The was able to extract in to list but I am unable to ex...
2017/07/07
[ "https://Stackoverflow.com/questions/44963360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8268739/" ]
I don't know if there's a slicker way, but a straightforward for loop will do the trick: ``` $frequency = []; for ($i = 0; $i < sizeof($date); $i++) { $frequency[] = array($date[$i], $time_start[$i], $time_end[$i]); } print_r($frequency); // Output: // Array // ( // [0] => Array // ( // ...
You can do like below ``` <?php $complete_array = array(); $date = array('2017-06-10', '2017-06-11', '2017-06-12'); $time_start = array('02:00 PM', '03:00 PM', '04:00 PM'); $time_end = array('05:00 PM', '06:00 PM', ...
44,963,360
I am very new to python. Long time user of stackoverflow but first time posting a question. I am trying to extract data from website using beautifulsoup. [Sample Code where I want to extract is (listed in and tagged in data)](https://i.stack.imgur.com/AASRq.jpg) The was able to extract in to list but I am unable to ex...
2017/07/07
[ "https://Stackoverflow.com/questions/44963360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8268739/" ]
Or you could do: ``` $frequency=array_map(null,$date, $time_start, $time_end); ``` see here: <http://php.net/manual/de/function.array-map.php> and for a short demo, here: <http://rextester.com/VJRCA63297>
You can also map them: ``` $result = array_map(function ($value1,$value2,$value3) { return [$value1,$value2,$value3]; }, $date,$time_start,$time_end); ```
44,963,360
I am very new to python. Long time user of stackoverflow but first time posting a question. I am trying to extract data from website using beautifulsoup. [Sample Code where I want to extract is (listed in and tagged in data)](https://i.stack.imgur.com/AASRq.jpg) The was able to extract in to list but I am unable to ex...
2017/07/07
[ "https://Stackoverflow.com/questions/44963360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8268739/" ]
Or you could do: ``` $frequency=array_map(null,$date, $time_start, $time_end); ``` see here: <http://php.net/manual/de/function.array-map.php> and for a short demo, here: <http://rextester.com/VJRCA63297>
You can do like below ``` <?php $complete_array = array(); $date = array('2017-06-10', '2017-06-11', '2017-06-12'); $time_start = array('02:00 PM', '03:00 PM', '04:00 PM'); $time_end = array('05:00 PM', '06:00 PM', ...
16,326,285
I have old python. So can't use subprocess. I have two python scripts. One primary.py and another secondary.py. While running primary.py I need to run secondary.py. Format to run secondary.py is 'python secondary.py Argument' `os.system('python secondary.py Argument')...is giving error saying that can't open file 'Ar...
2013/05/01
[ "https://Stackoverflow.com/questions/16326285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2340760/" ]
Given the code you described, this error can come up for three reasons: * `python` isn't on your `PATH`, or * `secondary.py` isn't in your current working directory. * `Argument` isn't in your current working directory. From your edited question, it sounds like it's the last of the three, meaning the problem likely h...
Which python version do you have? Could you show contents of your secondary.py ? For newer version it seems to work correctly: ``` ddzialak@ubuntu:$ cat f.py import os os.system("python s.py Arg") ddzialak@ubuntu:$ cat s.py print "OK!!!" ddzialak@ubuntu:$ python f.py OK!!! ddzialak@ubuntu:$ ```
63,671,929
boto3 provides default **waiters** for some services like EC2, S3, etc. This is not provided by default for all services. Now, I've a case where an EFS volume is created and the lifecycle policy is added to the file system. The EFS creation takes some time and the lifecycle policy isn't in the required efs state. i.e.,...
2020/08/31
[ "https://Stackoverflow.com/questions/63671929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11192798/" ]
Comment out `django.middleware.csrf.CsrfViewMiddleware` in the `MIDDLEWARE` entry in `settings.py` of your django project. I tried `curl -X POST localhost:8000/` after adding a trivial post to a class-based view. It returned the famous 403 CSRF verification failed. After commenting out the above middleware the post m...
Had a simlar problem the easiest fix is to disable the firewall to get the the GET and POST working
5,483,404
I want to build a heavy ajax web2.0 app and I don't have javascript, django or ruby on rails. I have some experience with python. I am not sure which one to choose. I have a backend database and have to run few queries for each page, no big deal. So, I am looking for a choice which is quite easy to learn and maintain i...
2011/03/30
[ "https://Stackoverflow.com/questions/5483404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207335/" ]
I'm not sure if this meets the guidelines for a valid question on here. If you know any Python go with Django, if you know any Ruby go with Rails. From my understanding Rails is a bit more opinionated when it comes to JavaScript. In other words it comes bundled with a bunch of helpers to make it simpler to Ajaxify yo...
ROR has much better community activity. It's easier to learn without learning ruby (i do not recommend that way, but yes - you can write in ROR barely understanding ruby). About performance: ruby 1.8 was much slower than python. But maybe ruby 1.9 is faster. If you want to build smart ajax application and you under...
5,483,404
I want to build a heavy ajax web2.0 app and I don't have javascript, django or ruby on rails. I have some experience with python. I am not sure which one to choose. I have a backend database and have to run few queries for each page, no big deal. So, I am looking for a choice which is quite easy to learn and maintain i...
2011/03/30
[ "https://Stackoverflow.com/questions/5483404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207335/" ]
I'm not sure if this meets the guidelines for a valid question on here. If you know any Python go with Django, if you know any Ruby go with Rails. From my understanding Rails is a bit more opinionated when it comes to JavaScript. In other words it comes bundled with a bunch of helpers to make it simpler to Ajaxify yo...
We've had a blast developing with Django/Jquery, and development, in our opinion, is easier, faster. That being said, we tend to go with Django because of Python's raw power and reliability. Not to say ROR doesn't have similar strengths, but we get "stuck" more often than not when using ROR than when using Django. If...
5,483,404
I want to build a heavy ajax web2.0 app and I don't have javascript, django or ruby on rails. I have some experience with python. I am not sure which one to choose. I have a backend database and have to run few queries for each page, no big deal. So, I am looking for a choice which is quite easy to learn and maintain i...
2011/03/30
[ "https://Stackoverflow.com/questions/5483404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207335/" ]
I'm not sure if this meets the guidelines for a valid question on here. If you know any Python go with Django, if you know any Ruby go with Rails. From my understanding Rails is a bit more opinionated when it comes to JavaScript. In other words it comes bundled with a bunch of helpers to make it simpler to Ajaxify yo...
If you like Rails but want to stick with Python, you might also consider [web2py](http://www.web2py.com), which is probably the Python framework that is the most like Rails (it was inspired by Rails, as well as Django). Ajax is particularly easy in web2py -- it comes bundled with jQuery, the scaffolding application inc...
63,658,572
I am writing a program to produce an image of the Mandelbrot set. The set requires iterating through the formula: z = z\_{n-1}^2 + C. The (n-1) refers to the previous value of z in the loop. In my program I have written ``` z_new = (self.z)**2.0 + c_number self.z = z_new ``` within a loop. Is there a better way in ...
2020/08/30
[ "https://Stackoverflow.com/questions/63658572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14120667/" ]
I think you may have mis-interpreted @Lev\_Levitsky's comment. If you wanted it on one line then they suggested: ```py self.z = self.z**2 + c_number ``` is equivalent to what you've got written. You don't really need the temporary variable `z_new` since in the "one-liner" the previous value of `self.z` is used when ...
the simplified version should be: ```py self.z = (self.z)**2.0 + c_number ```
4,900,003
I'm using the @login\_required decorator in my project since day one and it's working fine, but for some reason, I'm starting to get " AttributeError: 'unicode' object has no attribute 'user' " on some specific urls (and those worked in the past). Example : I am the website, logged, and then I click on link and I'm ge...
2011/02/04
[ "https://Stackoverflow.com/questions/4900003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23051/" ]
The decorator was on a private method that doesn't have the request as a parameter. I removed that decorator (left there because of a refactoring and lack of test [bad me]). Problem solved.
This can also happen if you call a decorated method from another method without providing a request parameter.
46,000,595
I have created a pie chart in `matplotlib`. I want to achieve [**this**](http://jsfiddle.net/ztJkb/4/) result in python **i.e. whenever the mouse is hovered on any slice its color is changed**.I have searched a lot and came up with the use of `bind` method but that was not effective though and therefore was not able to...
2017/09/01
[ "https://Stackoverflow.com/questions/46000595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You would need a [matplotlib event handler](https://matplotlib.org/users/event_handling.html) for a `motion_notify_event`. This can be connected to a function which checks if the mouse is inside one of the pie chart's wedges. This is done via [`contains_point`](https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pat...
First off, what you are looking for is [the documentation on Event handling in matplotlib](https://matplotlib.org/users/event_handling.html). In particular, the `motion_notify_event` will be fired every time the mouse moves. However, I can't think of an easy way to identify which wedge the mouse is over right now. If ...
4,690,366
This is my first post and I'm still a Python and Scipy newcomer, so go easy on me! I'm trying to convert an Nx1 matrix into a python list. Say I have some 3x1 matrix `x = scipy.matrix([1,2,3]).transpose()` My aim is to create a list, y, from x so that `y = [1, 2, 3]` I've tried using the `tolist()` method, but it ...
2011/01/14
[ "https://Stackoverflow.com/questions/4690366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568864/" ]
A question for your question ---------------------------- While Sven and Navi have answered your question on how to convert ``` x = scipy.matrix([1,2,3]).transpose() ``` into a list, I'll ask a question before answering: * Why are you using an Nx1 matrix instead of an array? Using array instead of matrix -------...
How about ``` x.ravel().tolist()[0] ``` or ``` scipy.array(x).ravel().tolist() ```
4,690,366
This is my first post and I'm still a Python and Scipy newcomer, so go easy on me! I'm trying to convert an Nx1 matrix into a python list. Say I have some 3x1 matrix `x = scipy.matrix([1,2,3]).transpose()` My aim is to create a list, y, from x so that `y = [1, 2, 3]` I've tried using the `tolist()` method, but it ...
2011/01/14
[ "https://Stackoverflow.com/questions/4690366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568864/" ]
A question for your question ---------------------------- While Sven and Navi have answered your question on how to convert ``` x = scipy.matrix([1,2,3]).transpose() ``` into a list, I'll ask a question before answering: * Why are you using an Nx1 matrix instead of an array? Using array instead of matrix -------...
I think you are almost there use the flatten function <http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html>
6,876,553
I thought to try using [D](http://en.wikipedia.org/wiki/D_%28programming_language%29) for some system administration scripts which require high performance (for comparing performance with python/perl etc). I can't find an example in the tutorials I looked through so far (dsource.org etc.) on how to make a system call ...
2011/07/29
[ "https://Stackoverflow.com/questions/6876553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340811/" ]
Well, then I of course found it: <http://www.digitalmars.com/d/2.0/phobos/std_process.html#shell> (Version using the Tango library here: <http://www.dsource.org/projects/tango/wiki/TutExec>). The former version is the one that works with D 2.0 (thereby the current dmd compiler that comes with ubuntu). I got this tiny...
std.process has been updated since... the new function is spawnShell ``` import std.stdio; import std.process; void main(){ auto pid = spawnShell("ls -l"); write(pid); } ```
62,998,373
I have a graph structure like this:[![enter image description here](https://i.stack.imgur.com/SMnZU.png)](https://i.stack.imgur.com/SMnZU.png) I need to select all `ContentItem` nodes they have any connections with the other nodes. I am also passing in a list of ids for each of the nodes for filtering purposes. i.e. ...
2020/07/20
[ "https://Stackoverflow.com/questions/62998373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7412939/" ]
You can pass the \_incrementCounter method down to the other widget. File 1: ``` class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: A...
You have to pass the function instead of calling it. The code: ``` onPressed: () { _incrementCounter(); }, ``` or like this of you like shortcuts: ``` onPressed: () => _incrementCounter(), ``` Hope it helps! Happy coding:)
13,421,709
I use `vim` (installed on `cygwin`) to write `c++` programs but it does not highlight some `c++` keywords such as `new`, `delete`, `public`, `friend`, `try`, but highlight others such as `namespace`, `int`, `const`, `operator`, `true`, `class`, `include`. It also not change color of operators. I never changed its synt...
2012/11/16
[ "https://Stackoverflow.com/questions/13421709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363855/" ]
Add this to the C Highlighting paragraph: ``` call <SID>X("Statement", s:purple, "", "") ```
All the keywords you mention eventually link to the standard `Statement` syntax group. Maybe that one got cleared. Try ``` :verbose highlight Statement ``` If it shows `xxx cleared`, you're one step further and now need to investigate why your colorscheme does not define a coloring.
26,256,055
In my python program , I have my string: ``` test = {"Controller_node1_external_port": {"properties": {"fixed_ips": [{"ip_address": "12.0.0.1"}],"network_id": {"get_param": ["ex_net_map_param",{"get_param": "ex_net_param"}]}},"type": "OS::Neutron::Port"}} ``` `yaml.dump(test)` is giving me the output : ``` Control...
2014/10/08
[ "https://Stackoverflow.com/questions/26256055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3197309/" ]
I will provide a simple way to store and retrive your data inside that multidimensional array: ``` <?php //Global definition of the array $categories = array( "house" => array(), "indie" => array(), "trap" => array(), "trance" => array(), "partybangers" => array(), ); function push_to_category($ca...
I like [FoxNos's answer](https://stackoverflow.com/questions/26256032/store-value-in-multidimensional-array-if-value-is-equal-to-key#answer-26256906), but not the global, since the global might not be a global in another context (`$categories`might be defined in another function or class). So this is what I would've d...
12,326,443
I am writing a python program which validates device events. I am continuosly reading some data from serial port from a device. When I write something on serail port of device, the device writes a string on serialport which I have to read. Continously reading part from serial port is in a seperate worker thread an I r...
2012/09/07
[ "https://Stackoverflow.com/questions/12326443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348686/" ]
If you are just using threads for asynchronous IO, You may be better off not using threads and use select.select, or perhaps even asyncore if you want to make it even easier on yourself. <http://docs.python.org/library/asyncore.html>
Code Snippet is as follows: Class SerialCom: ``` __init__(self,comport): self.comport = comport self.readSerialPortThread = ReadSearialPortThread(self.comport) def writeStringToSerialPort(someString): self.comport.write(someString) def waitfordata(someString): #I have to continuously rea...
47,367,681
I am splinting a text based on ",". I need to ignore the commas in text between quotes (simple or doubled). Example of text: ``` Capacitors,3,"C2,C7-C8",100nF,, Capacitors,3,'C2,C7-C8',100nF,, ``` Have to return ``` ['Capacitors','3','C2,C7-C8','100nF','',''] ``` How to say this (ignore between quotes) in regula...
2017/11/18
[ "https://Stackoverflow.com/questions/47367681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7803545/" ]
Don't use regex for this. With a little tweaking, you can use `csv` module to parse the line perfectly (`csv` is designed to handle quoted commas). Just normalize the quotes to double quotes: ``` import csv s = """Capacitors,3,"C2,C7-C8",100nF,, Capacitors,3,'C2,C7-C8',100nF,,""" print(next(csv.reader([s.replace("'"...
I guess you changed your question. That looks like a csv-formatted file: ``` import io s = """\ Capacitors,3,"C2,C7-C8",100nF,, Capacitors,3,'C2,C7-C8',100nF,,""" [i for i in csv.reader(io.StringIO(s), delimiter=',', quotechar='"')] ``` Returns: ``` [['Capacitors', '3', 'C2,C7-C8', '100nF', '', ''], ['Capacitors...
47,367,681
I am splinting a text based on ",". I need to ignore the commas in text between quotes (simple or doubled). Example of text: ``` Capacitors,3,"C2,C7-C8",100nF,, Capacitors,3,'C2,C7-C8',100nF,, ``` Have to return ``` ['Capacitors','3','C2,C7-C8','100nF','',''] ``` How to say this (ignore between quotes) in regula...
2017/11/18
[ "https://Stackoverflow.com/questions/47367681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7803545/" ]
Don't use regex for this. With a little tweaking, you can use `csv` module to parse the line perfectly (`csv` is designed to handle quoted commas). Just normalize the quotes to double quotes: ``` import csv s = """Capacitors,3,"C2,C7-C8",100nF,, Capacitors,3,'C2,C7-C8',100nF,,""" print(next(csv.reader([s.replace("'"...
Since question is tagged under regex so here is regex version : ``` s="""Capacitors,3,"C2,C7-C8",100nF,, Capacitors,3,'C2,C7-C8',100nF,,""" import re pattern=r"(([\"'])(?:(?!\2).)*|[^,\n]+)" word_list=[] match=re.finditer(pattern,s) for find in match: word_list.append(find.group()) print(word_list) ```
14,427,281
AIM: need to find out how to parse data from api search below into a CSV file. The search returns results in the following format: ``` [(u'Bertille Maciag', 10), (u'Peter Prior', 5), (u'Chris OverPar Duguid', 4), (u 'Selby Dhliwayo', 4), (u'FakeBitch!', 4), (u'Django Unchianed UK', 4), (u'Padrai g Lynch ', 4), (u'Jes...
2013/01/20
[ "https://Stackoverflow.com/questions/14427281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1973375/" ]
It looks like you have all the hard bits working, and are just missing the 'save to csv' part. ``` import collections import twitter, json, operator #Construct Twitter API object searchApi = twitter.Twitter(domain="search.twitter.com") #Get trends query = "#snow" tweeters = collections.defaultdict(lambda: 0) for i in...
Have you looked at the [python CSV](http://docs.python.org/2/library/csv.html) module? using your output: ``` import csv, os x = [(u'Bertille Maciag', 10), (u'Peter Prior', 5), (u'Chris OverPar Duguid', 4), (u'Selby Dhliwayo', 4), (u'FakeBitch!', 4), (u'Django Unchianed UK', 4), (u'Padraig Lynch ', 4), (u'Jessica Gun...
73,988,902
I have one tensor slice with all image and one tensor with its masking image. how do i combine/join/add them and make it a single tensor dataset `tf.data.dataset` ``` # turning them into tensor data val_img_data = tf.data.Dataset.from_tensor_slices(np.array(all_val_img)) val_mask_data = tf.data.Dataset.from_tensor_sli...
2022/10/07
[ "https://Stackoverflow.com/questions/73988902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14076425/" ]
The comment of Djinn is mostly you need to follow. Here is the end to end answer. Here is how you can build data pipeline for segmentation model training, generally a training paris with both `images, masks`. First, get the sample paths. ``` images = [ 1.jpg, 2.jpg, 3.jpg, ... ] masks = [ ...
Maybe try `tf.data.Dataset.zip`: ``` val_data = tf.data.Dataset.zip((val_img_tensor, val_mask_tensor)) ```
65,846,292
My list does not appear when I'm running my program. There are no errors it just pops up with a blank screen. This is my code. Please help only new to python. ``` devices = ['iphone', 'ps5', 'pc'] devicesaccessories = ['mouse', 'keyboard', 'airpods'] joinedlist = devices + devicesaccessories ```
2021/01/22
[ "https://Stackoverflow.com/questions/65846292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15059825/" ]
You are probably not having the dependency binaries like opencv\_\*.dll in the same folder as your binary. Also InferenceEngine binaries needs to be present in the folder from where your binary is expected to run. Please use DependencyWalker to identify the load dependency and copy the needed binary.
copy "\inference\_engine\lib\intel64\Release\plugins.xml" to project dir, then replace Core core to Core core(plugins.xml)
9,331,010
This post is the same with my question in [MySQL in Python: UnicodeEncodeError: 'ascii'](https://stackoverflow.com/questions/9330046/mysql-in-python-unicodeencodeerror-ascii) this is just to clear things up. I am trying to save a string to a MySQL database but I get an error: > > File ".smart.py", line 51, in > (...
2012/02/17
[ "https://Stackoverflow.com/questions/9331010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1067791/" ]
add these parameters `MySQLdb.connect(..., use_unicode=1,charset="utf8")`. create a cursor ``` cur = db.cursor() ``` and then execute like so: ``` risk = m['Text'] sql = """INSERT INTO posts(nmbr, msg, tel, sts) \ VALUES (%s, %s, %s, %s)""" values = (number, risk, 'smart', 'u') cur.execute(sql,values) #...
It is not clear whether your `m['Text']` value is of type `StringType` or `UnicodeType`. My bet is that it is a byte-string (`StringType`). If that's true, then adding a line `m['Text'] = m['Text'].decode('UTF-8')` before your insert may work.
36,307,767
I have set the output of Azure stream analytics job to service bus queue which sends the data in JSON serialized format. When I receive the queue message in python script, along with the data in curly braces, I get @strin3http//schemas.microsoft.com/2003/10/Serialization/� appended in front. I am not able to trim it as...
2016/03/30
[ "https://Stackoverflow.com/questions/36307767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6134419/" ]
The issue was similiar with the SO thread [Interoperability Azure Service Bus Message Queue Messages](https://stackoverflow.com/questions/33542509/interoperability-azure-service-bus-message-queue-messages). Per my experience, the data from Azure Stream Analytics to Service Bus was sent via AMQP protocol, but the proto...
I ran into this issue as well. The previous answers are only workarounds and do not fix the root cause of this issue. The problem you are encountering is likely due to your Stream Analytics compatibility level. Compatibility level 1.0 uses an XML serializer producing the XML tag you are seeing. Compatibility level 1.1 ...
36,307,767
I have set the output of Azure stream analytics job to service bus queue which sends the data in JSON serialized format. When I receive the queue message in python script, along with the data in curly braces, I get @strin3http//schemas.microsoft.com/2003/10/Serialization/� appended in front. I am not able to trim it as...
2016/03/30
[ "https://Stackoverflow.com/questions/36307767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6134419/" ]
The issue was similiar with the SO thread [Interoperability Azure Service Bus Message Queue Messages](https://stackoverflow.com/questions/33542509/interoperability-azure-service-bus-message-queue-messages). Per my experience, the data from Azure Stream Analytics to Service Bus was sent via AMQP protocol, but the proto...
I had the same issue but in a .net solution. I was writing a service which sends data to a queue, and on the other hand, I was writing a service which gets that data from the queue. I've tried to send a JSON, like this: ``` var documentMessage = new DocumentMessage(); var json = JsonConvert.Ser...
36,307,767
I have set the output of Azure stream analytics job to service bus queue which sends the data in JSON serialized format. When I receive the queue message in python script, along with the data in curly braces, I get @strin3http//schemas.microsoft.com/2003/10/Serialization/� appended in front. I am not able to trim it as...
2016/03/30
[ "https://Stackoverflow.com/questions/36307767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6134419/" ]
The issue was similiar with the SO thread [Interoperability Azure Service Bus Message Queue Messages](https://stackoverflow.com/questions/33542509/interoperability-azure-service-bus-message-queue-messages). Per my experience, the data from Azure Stream Analytics to Service Bus was sent via AMQP protocol, but the proto...
When using Microsoft.ServiceBus nuget package, replace ``` message.GetBody<Stream>(); ``` with ``` message.GetBody<string>(); ```
36,307,767
I have set the output of Azure stream analytics job to service bus queue which sends the data in JSON serialized format. When I receive the queue message in python script, along with the data in curly braces, I get @strin3http//schemas.microsoft.com/2003/10/Serialization/� appended in front. I am not able to trim it as...
2016/03/30
[ "https://Stackoverflow.com/questions/36307767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6134419/" ]
[This TechNet article](https://social.technet.microsoft.com/wiki/contents/articles/34750.integrating-service-bus-stack-with-logic-apps-and-azure-functions.aspx) suggests the following code: ``` // Get indices of actual message var start = jsonString.IndexOf("{"); var end = jsonString.LastIndexOf("}") + 1; var length =...
I ran into this issue as well. The previous answers are only workarounds and do not fix the root cause of this issue. The problem you are encountering is likely due to your Stream Analytics compatibility level. Compatibility level 1.0 uses an XML serializer producing the XML tag you are seeing. Compatibility level 1.1 ...
36,307,767
I have set the output of Azure stream analytics job to service bus queue which sends the data in JSON serialized format. When I receive the queue message in python script, along with the data in curly braces, I get @strin3http//schemas.microsoft.com/2003/10/Serialization/� appended in front. I am not able to trim it as...
2016/03/30
[ "https://Stackoverflow.com/questions/36307767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6134419/" ]
[This TechNet article](https://social.technet.microsoft.com/wiki/contents/articles/34750.integrating-service-bus-stack-with-logic-apps-and-azure-functions.aspx) suggests the following code: ``` // Get indices of actual message var start = jsonString.IndexOf("{"); var end = jsonString.LastIndexOf("}") + 1; var length =...
I had the same issue but in a .net solution. I was writing a service which sends data to a queue, and on the other hand, I was writing a service which gets that data from the queue. I've tried to send a JSON, like this: ``` var documentMessage = new DocumentMessage(); var json = JsonConvert.Ser...
36,307,767
I have set the output of Azure stream analytics job to service bus queue which sends the data in JSON serialized format. When I receive the queue message in python script, along with the data in curly braces, I get @strin3http//schemas.microsoft.com/2003/10/Serialization/� appended in front. I am not able to trim it as...
2016/03/30
[ "https://Stackoverflow.com/questions/36307767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6134419/" ]
[This TechNet article](https://social.technet.microsoft.com/wiki/contents/articles/34750.integrating-service-bus-stack-with-logic-apps-and-azure-functions.aspx) suggests the following code: ``` // Get indices of actual message var start = jsonString.IndexOf("{"); var end = jsonString.LastIndexOf("}") + 1; var length =...
When using Microsoft.ServiceBus nuget package, replace ``` message.GetBody<Stream>(); ``` with ``` message.GetBody<string>(); ```
36,307,767
I have set the output of Azure stream analytics job to service bus queue which sends the data in JSON serialized format. When I receive the queue message in python script, along with the data in curly braces, I get @strin3http//schemas.microsoft.com/2003/10/Serialization/� appended in front. I am not able to trim it as...
2016/03/30
[ "https://Stackoverflow.com/questions/36307767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6134419/" ]
I ran into this issue as well. The previous answers are only workarounds and do not fix the root cause of this issue. The problem you are encountering is likely due to your Stream Analytics compatibility level. Compatibility level 1.0 uses an XML serializer producing the XML tag you are seeing. Compatibility level 1.1 ...
I had the same issue but in a .net solution. I was writing a service which sends data to a queue, and on the other hand, I was writing a service which gets that data from the queue. I've tried to send a JSON, like this: ``` var documentMessage = new DocumentMessage(); var json = JsonConvert.Ser...
36,307,767
I have set the output of Azure stream analytics job to service bus queue which sends the data in JSON serialized format. When I receive the queue message in python script, along with the data in curly braces, I get @strin3http//schemas.microsoft.com/2003/10/Serialization/� appended in front. I am not able to trim it as...
2016/03/30
[ "https://Stackoverflow.com/questions/36307767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6134419/" ]
I ran into this issue as well. The previous answers are only workarounds and do not fix the root cause of this issue. The problem you are encountering is likely due to your Stream Analytics compatibility level. Compatibility level 1.0 uses an XML serializer producing the XML tag you are seeing. Compatibility level 1.1 ...
When using Microsoft.ServiceBus nuget package, replace ``` message.GetBody<Stream>(); ``` with ``` message.GetBody<string>(); ```
37,190,989
I am using gensim word2vec package in python. I know how to get the vocabulary from the trained model. But how to get the word count for each word in vocabulary?
2016/05/12
[ "https://Stackoverflow.com/questions/37190989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5969670/" ]
Each word in the vocabulary has an associated vocabulary object, which contains an index and a count. ``` vocab_obj = w2v.vocab["word"] vocab_obj.count ``` Output for google news w2v model: 2998437 So to get the count for each word, you would iterate over all words and vocab objects in the vocabulary. ``` for word...
When you want to create a dictionary of word to count for easy retrieval later, you can do so as follows: ``` w2c = dict() for item in model.wv.vocab: w2c[item]=model.wv.vocab[item].count ``` If you want to sort it to see the most frequent words in the model, you can also do that so: ``` w2cSorted=dict(sorted(w...
37,190,989
I am using gensim word2vec package in python. I know how to get the vocabulary from the trained model. But how to get the word count for each word in vocabulary?
2016/05/12
[ "https://Stackoverflow.com/questions/37190989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5969670/" ]
Each word in the vocabulary has an associated vocabulary object, which contains an index and a count. ``` vocab_obj = w2v.vocab["word"] vocab_obj.count ``` Output for google news w2v model: 2998437 So to get the count for each word, you would iterate over all words and vocab objects in the vocabulary. ``` for word...
The vocab attribute was removed from KeyedVector in [Gensim 4.0.0](https://github.com/RaRe-Technologies/gensim/releases/tag/4.0.0beta). Instead: ``` word2vec_model.wv.get_vecattr("my-word", "count") # returns count of "my-word" len(word2vec_model.wv) # returns size of the vocabulary ``` Check out notes on [migrat...
15,169,101
I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs, > >...
2013/03/02
[ "https://Stackoverflow.com/questions/15169101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938914/" ]
[According](http://bugs.python.org/issue14243#msg164504) to Richard Oudkerk > > (...) the only reason that trying to reopen a `NamedTemporaryFile` fails on > Windows is because when we reopen we need to use `O_TEMPORARY`. > > > and he gives an example of how to do this in Python 3.3+ ``` import os, tempfile D...
I know this is a really old post, but I think it's relevant today given that the API is changing and functions like mktemp and mkstemp are being replaced by functions like TemporaryFile() and TemporaryDirectory(). I just wanted to demonstrate in the following sample how to make sure that a temp directory is still avail...
15,169,101
I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs, > >...
2013/03/02
[ "https://Stackoverflow.com/questions/15169101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938914/" ]
You can always go low-level, though am not sure if it's clean enough for you: ``` fd, filename = tempfile.mkstemp() try: os.write(fd, someStuff) os.close(fd) # ...run the subprocess and wait for it to complete... finally: os.remove(filename) ```
I know this is a really old post, but I think it's relevant today given that the API is changing and functions like mktemp and mkstemp are being replaced by functions like TemporaryFile() and TemporaryDirectory(). I just wanted to demonstrate in the following sample how to make sure that a temp directory is still avail...
15,169,101
I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs, > >...
2013/03/02
[ "https://Stackoverflow.com/questions/15169101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938914/" ]
At least if you open a temporary file using existing Python libraries, accessing it from multiple processes is not possible in case of Windows. According to [MSDN](http://msdn.microsoft.com/en-us/library/aa363858) you can specify a 3rd parameter (`dwSharedMode`) shared mode flag `FILE_SHARE_READ` to `CreateFile()` func...
Using [`mkstemp()`](https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp) instead with [`os.fdopen()`](https://docs.python.org/3/library/os.html#os.fdopen) in a `with` statement avoids having to call `close()`: ``` fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'wb') as fileTemp: fileTem...
15,169,101
I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs, > >...
2013/03/02
[ "https://Stackoverflow.com/questions/15169101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938914/" ]
Since nobody else appears to be interested in leaving this information out in the open... `tempfile` does expose a function, `mkdtemp()`, which can trivialize this problem: ``` try: temp_dir = mkdtemp() temp_file = make_a_file_in_a_dir(temp_dir) do_your_subprocess_stuff(temp_file) remove_your_temp_fil...
I know this is a really old post, but I think it's relevant today given that the API is changing and functions like mktemp and mkstemp are being replaced by functions like TemporaryFile() and TemporaryDirectory(). I just wanted to demonstrate in the following sample how to make sure that a temp directory is still avail...
15,169,101
I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs, > >...
2013/03/02
[ "https://Stackoverflow.com/questions/15169101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938914/" ]
[According](http://bugs.python.org/issue14243#msg164504) to Richard Oudkerk > > (...) the only reason that trying to reopen a `NamedTemporaryFile` fails on > Windows is because when we reopen we need to use `O_TEMPORARY`. > > > and he gives an example of how to do this in Python 3.3+ ``` import os, tempfile D...
You can always go low-level, though am not sure if it's clean enough for you: ``` fd, filename = tempfile.mkstemp() try: os.write(fd, someStuff) os.close(fd) # ...run the subprocess and wait for it to complete... finally: os.remove(filename) ```
15,169,101
I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs, > >...
2013/03/02
[ "https://Stackoverflow.com/questions/15169101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938914/" ]
At least if you open a temporary file using existing Python libraries, accessing it from multiple processes is not possible in case of Windows. According to [MSDN](http://msdn.microsoft.com/en-us/library/aa363858) you can specify a 3rd parameter (`dwSharedMode`) shared mode flag `FILE_SHARE_READ` to `CreateFile()` func...
You can always go low-level, though am not sure if it's clean enough for you: ``` fd, filename = tempfile.mkstemp() try: os.write(fd, someStuff) os.close(fd) # ...run the subprocess and wait for it to complete... finally: os.remove(filename) ```
15,169,101
I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs, > >...
2013/03/02
[ "https://Stackoverflow.com/questions/15169101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938914/" ]
Since nobody else appears to be interested in leaving this information out in the open... `tempfile` does expose a function, `mkdtemp()`, which can trivialize this problem: ``` try: temp_dir = mkdtemp() temp_file = make_a_file_in_a_dir(temp_dir) do_your_subprocess_stuff(temp_file) remove_your_temp_fil...
Using [`mkstemp()`](https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp) instead with [`os.fdopen()`](https://docs.python.org/3/library/os.html#os.fdopen) in a `with` statement avoids having to call `close()`: ``` fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'wb') as fileTemp: fileTem...
15,169,101
I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs, > >...
2013/03/02
[ "https://Stackoverflow.com/questions/15169101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938914/" ]
You can always go low-level, though am not sure if it's clean enough for you: ``` fd, filename = tempfile.mkstemp() try: os.write(fd, someStuff) os.close(fd) # ...run the subprocess and wait for it to complete... finally: os.remove(filename) ```
Using [`mkstemp()`](https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp) instead with [`os.fdopen()`](https://docs.python.org/3/library/os.html#os.fdopen) in a `with` statement avoids having to call `close()`: ``` fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'wb') as fileTemp: fileTem...
15,169,101
I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs, > >...
2013/03/02
[ "https://Stackoverflow.com/questions/15169101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938914/" ]
At least if you open a temporary file using existing Python libraries, accessing it from multiple processes is not possible in case of Windows. According to [MSDN](http://msdn.microsoft.com/en-us/library/aa363858) you can specify a 3rd parameter (`dwSharedMode`) shared mode flag `FILE_SHARE_READ` to `CreateFile()` func...
I know this is a really old post, but I think it's relevant today given that the API is changing and functions like mktemp and mkstemp are being replaced by functions like TemporaryFile() and TemporaryDirectory(). I just wanted to demonstrate in the following sample how to make sure that a temp directory is still avail...
15,169,101
I'm writing a Python script that needs to write some data to a temporary file, then create a subprocess running a C++ program that will read the temporary file. I'm trying to use [`NamedTemporaryFile`](http://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile) for this, but according to the docs, > >...
2013/03/02
[ "https://Stackoverflow.com/questions/15169101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938914/" ]
Since nobody else appears to be interested in leaving this information out in the open... `tempfile` does expose a function, `mkdtemp()`, which can trivialize this problem: ``` try: temp_dir = mkdtemp() temp_file = make_a_file_in_a_dir(temp_dir) do_your_subprocess_stuff(temp_file) remove_your_temp_fil...
You can always go low-level, though am not sure if it's clean enough for you: ``` fd, filename = tempfile.mkstemp() try: os.write(fd, someStuff) os.close(fd) # ...run the subprocess and wait for it to complete... finally: os.remove(filename) ```
61,782,776
I tried this ``` x = np.array([ [0,0], [1,0], [2.61,-1.28], [-0.59,2.1] ]) for i in X: X = np.append(X[i], X[i][0]**2, axis = 1) print(X) ``` But i am getting this ``` IndexError Traceback (most recent call last) <ipython-input-12-9bfd33261d84> in <module>() ...
2020/05/13
[ "https://Stackoverflow.com/questions/61782776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12894182/" ]
How about concatenate: ``` np.concatenate((x,x**2)) ``` Output: ``` array([[ 0. , 0. ], [ 1. , 0. ], [ 2.61 , -1.28 ], [-0.59 , 2.1 ], [ 0. , 0. ], [ 1. , 0. ], [ 6.8121, 1.6384], [ 0.3481, 4.41 ]]) ```
``` In [210]: x = np.array([ ...: [0,0], ...: [1,0], ...: [2.61,-1.28], ...: [-0.59,2.1] ...: ]) ...: In [211]: x # (4,2) array ...
37,690,440
Right now I'm writing a function that reads data from a file, with the goal being to add that data to a numpy array and return said array. I would like to return the array as a 2D array, however I'm not sure what the complete shape of the array will be (I know the amount of columns, but not rows). What I have right n...
2016/06/07
[ "https://Stackoverflow.com/questions/37690440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5379671/" ]
If your file `data.txt` is ``` 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 ``` All you need to do is ``` >>> import numpy as n >>> data_array = n.loadtxt("data.txt") >>> data_array array([[1., 2., 3., 4.], [1., 2., 3., 4.], [1., 2., 3., 4.], [1., 2., 3., 4.], [1., 2., 3., 4.], ...
If you modify @Abstracted 's solution as: ``` data_array = np.loadtxt("data.txt", dtype =int) ``` you will get the array in integer form if you want it that way.
37,690,440
Right now I'm writing a function that reads data from a file, with the goal being to add that data to a numpy array and return said array. I would like to return the array as a 2D array, however I'm not sure what the complete shape of the array will be (I know the amount of columns, but not rows). What I have right n...
2016/06/07
[ "https://Stackoverflow.com/questions/37690440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5379671/" ]
Look at the common way of constructing an array: ``` np.array([[1,2,3],[4,5,6],[7,8,9]]) np.array([[1,2,3], [4,5,6], [7,8,9]]) ``` The input is a list of lists. Your reader could imitate that Roughly: ``` data = [] for line in f.readline(): values = line.strip().split(',') values = [int...
If you modify @Abstracted 's solution as: ``` data_array = np.loadtxt("data.txt", dtype =int) ``` you will get the array in integer form if you want it that way.
32,404,818
I am using iPython in command prompt, Windows 7. I thought this would be easy to find, I searched and found directions on how to use the inspect package but it seems like the inspect package is meant to be used for functions that are created by the programmer rather than functions that are part of a package. My main ...
2015/09/04
[ "https://Stackoverflow.com/questions/32404818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4959665/" ]
There is no way to do this generically, `help(<function>)` will at a minimum return you the function signature (including the argument names), Python is dynamically typed so you don't get any types and arguments by themselves don't tell you what the valid values are. This is where a good docstring comes in. However, t...
The inspect module is extremely powerful. To get a list of classes, for example in the csv module, you could go: ``` import inspect, csv from pprint import pprint module = csv mod_string = 'csv' module_classes = inspect.getmembers(module, inspect.isclass) for i in range(len(module_classes)): myclass = module_classe...
74,074,355
My code uses matplotlib which requires numpy. I'm using pipenv as my environment. When I run the code through my terminal and pipenv shell, it executes without a problem. I've just installed Pycharm for Apple silicon (I have an M1) and set up my interpreter to use the same pipenv environment that I configured earlier. ...
2022/10/14
[ "https://Stackoverflow.com/questions/74074355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19456156/" ]
Since you are on Windows, I am pretty sure the different results are because the UCRT detects during runtime whether FMA3 (fused-multiply-add) instructions are available for the CPU and if yes, use them in transcendental functions such as cosine. This gives [slightly different results](https://stackoverflow.com/a/29086...
IEEE-745 double precision binary floating point provides no more than 15 decimal significant digits of precision. You are looking at the "noise" of different library implementations and possibly different FPU implementations. > > How to make calculations fully reproducible? > > > That is an X-Y problem. The answe...
74,074,355
My code uses matplotlib which requires numpy. I'm using pipenv as my environment. When I run the code through my terminal and pipenv shell, it executes without a problem. I've just installed Pycharm for Apple silicon (I have an M1) and set up my interpreter to use the same pipenv environment that I configured earlier. ...
2022/10/14
[ "https://Stackoverflow.com/questions/74074355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19456156/" ]
Since you are on Windows, I am pretty sure the different results are because the UCRT detects during runtime whether FMA3 (fused-multiply-add) instructions are available for the CPU and if yes, use them in transcendental functions such as cosine. This gives [slightly different results](https://stackoverflow.com/a/29086...
* First of all, `40965.8966304650828827e-01` cannot be a result from `cos()` function, as cos(x) is a function that, for real valued arguments always returns a value in the interval `[-1.0, 1.0]` so the result shown cannot be the output from it. * Second, you will have probably read somewhere that `double` values have ...
72,479,835
I'm totally new to command line and am trying to follow the instructions [here](http://rleca.pbworks.com/w/file/fetch/124098201/tuto_obitools_install_W10OS.html) to get OBITools installed. I've gotten part way through, but I am getting an error I don't understand when trying to download the OBITools install file. The c...
2022/06/02
[ "https://Stackoverflow.com/questions/72479835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15333572/" ]
You're not supposed to type those lines at the python shell (the one with >>>), you're supposed to type those into your regular bash shell (the one with $).
Type `exit()` to quit from the python shell and try again
57,077,879
I am running the function below on a very long CSV file. The function calculates the Z-score of the column MFE for every 50 lines. Some of these 50 lines contain just zeros, and therefore when calculating the Zscore the program stops because it can't divide by zero. How can I solve this problem, and instead of stopping...
2019/07/17
[ "https://Stackoverflow.com/questions/57077879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10647510/" ]
You can do either of the two following options: ``` if sum(arr) == 0: scores = [0] else: scores = stats.zscore(arr) ``` The re factored way is: ``` scores = [0] if sum(arr) == 0 else scores = stats.zscore(arr) ``` Both would work fine.
As long as that is what you want to do, you'd just check before `scores = stats.zscore(arr)` if your array is all 0s, make `scores = arr` instead.
57,077,879
I am running the function below on a very long CSV file. The function calculates the Z-score of the column MFE for every 50 lines. Some of these 50 lines contain just zeros, and therefore when calculating the Zscore the program stops because it can't divide by zero. How can I solve this problem, and instead of stopping...
2019/07/17
[ "https://Stackoverflow.com/questions/57077879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10647510/" ]
You can do either of the two following options: ``` if sum(arr) == 0: scores = [0] else: scores = stats.zscore(arr) ``` The re factored way is: ``` scores = [0] if sum(arr) == 0 else scores = stats.zscore(arr) ``` Both would work fine.
I'm guessing `scores = stats.zscore(arr)` is where the division occurs? You could add a check to see if `arr`only contains zeroes, for example by using ``` if arr.count(0) == len(arr): scores = arr else: scores = stats.zscore(arr) ```
25,193,352
How can I create a list (or a numpy array if possible) in python that takes `datetime` objects in the first column and other data types in other columns? For example, the list would be something like this: ``` list = [[<datetime object>, 0, 0.] [<datetime object>, 0, 0.] [<datetime object>, 0, 0.]] ...
2014/08/07
[ "https://Stackoverflow.com/questions/25193352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2613064/" ]
You mean something like: ``` In [17]: import numpy as np In [18]: np.array([[[datetime.now(),np.zeros(2)] for x in range(10)]]) Out[18]: array([[[datetime.datetime(2014, 8, 7, 23, 45, 12, 151489), array([ 0., 0.])], [datetime.datetime(2014, 8, 7, 23, 45, 12, 151560), array([ 0., 0.])], ...
Use `zip` ``` >>> column1 = [1, 1, 1] >>> column2 = [2, 2, 2] >>> column3 = [3, 3, 3] >>> zip(column1, column2, column3) [(1, 2, 3), (1, 2, 3), (1, 2, 3)] >>> # Or, if you'd like a list of lists: ... >>> [list(tup) for tup in zip(column1, column2, column3)] [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> ``` This would allo...
56,801,645
I tried to add python scripts to my packages reference this two tutorials. [Handling of setup.py](http://docs.ros.org/api/catkin/html/user_guide/setup_dot_py.html) [Installing Python scripts and modules](http://docs.ros.org/api/catkin/html/howto/format2/installing_python.html) So I added setup.py in root `test\src\t...
2019/06/28
[ "https://Stackoverflow.com/questions/56801645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9589731/" ]
First, while `catkin` is a generic enough tool, it's typically used for the robotics framework ROS. So by asking on ROS' question community [answers.ros.org](https://answers.ros.org/questions/) you might get more response. > > > ``` > CMake Error at C:/opt/ros/melodic/x64/share/catkin/cmake/catkin_install_python.cma...
I got the same error. I thought you copy the code to the wrong position. If you place those code in a relatively early position, you are possibly getting it wrong. Try to place the code here. ``` ## Mark executable scripts (Python etc.) for installation ## in contrast to setup.py, you can choose the destination) #catk...
56,801,645
I tried to add python scripts to my packages reference this two tutorials. [Handling of setup.py](http://docs.ros.org/api/catkin/html/user_guide/setup_dot_py.html) [Installing Python scripts and modules](http://docs.ros.org/api/catkin/html/howto/format2/installing_python.html) So I added setup.py in root `test\src\t...
2019/06/28
[ "https://Stackoverflow.com/questions/56801645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9589731/" ]
First, while `catkin` is a generic enough tool, it's typically used for the robotics framework ROS. So by asking on ROS' question community [answers.ros.org](https://answers.ros.org/questions/) you might get more response. > > > ``` > CMake Error at C:/opt/ros/melodic/x64/share/catkin/cmake/catkin_install_python.cma...
The correct order is: ``` cmake_minimum_required(VERSION 2.8.3) project(test_pkg) find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs sensor_msgs message_generation ) add_message_files( FILES Num.msg ) add_service_files( FILES AddTwoInts.srv ) generate_messages( DEPENDENCIES std_msg...
56,801,645
I tried to add python scripts to my packages reference this two tutorials. [Handling of setup.py](http://docs.ros.org/api/catkin/html/user_guide/setup_dot_py.html) [Installing Python scripts and modules](http://docs.ros.org/api/catkin/html/howto/format2/installing_python.html) So I added setup.py in root `test\src\t...
2019/06/28
[ "https://Stackoverflow.com/questions/56801645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9589731/" ]
The correct order is: ``` cmake_minimum_required(VERSION 2.8.3) project(test_pkg) find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs sensor_msgs message_generation ) add_message_files( FILES Num.msg ) add_service_files( FILES AddTwoInts.srv ) generate_messages( DEPENDENCIES std_msg...
I got the same error. I thought you copy the code to the wrong position. If you place those code in a relatively early position, you are possibly getting it wrong. Try to place the code here. ``` ## Mark executable scripts (Python etc.) for installation ## in contrast to setup.py, you can choose the destination) #catk...
17,261,801
I have a Java project where I must build an object from a JSON input, which comes in the following format: ``` { "Shell": 13401, "JavaScript": 2693931, "Ruby": 2264, "C": 111534, "C++": 940606, "Python": 39021, "R": 2216, "D": 35036, "Objective-C": 4913 } ``` Then in my code I have: ``` public voi...
2013/06/23
[ "https://Stackoverflow.com/questions/17261801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413570/" ]
You can use an **[adapter](http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapter.html)**. Say you have: ``` class Language { public String name; public Integer loc; } class Languages { public List<Language> list = new ArrayList<Language>(); } ``` The adapter: ``` c...
You can try this out `Map<String, String> map = gson.fromJson(json, new TypeToken<Map<String, String>>() {}.getType());` to get a map of language/value.
30,215,470
I found this example of code here on stackoverflow and I would like to make the first window close when a new one is opened. So what I would like is when a new window is opened, the main one should be closed automatically. ``` #!/usr/bin/env python import Tkinter as tk from Tkinter import * class windowclass(): ...
2015/05/13
[ "https://Stackoverflow.com/questions/30215470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3036295/" ]
You would withdraw the main window, but you have no way to close the program after the button click in the Toplevel, when the main window is still open but doesn't show Also pick one or the other of (but don't use both) ``` import Tkinter as tk from Tkinter import * ``` This opens a 2nd Toplevel which allows you to...
In your code: ``` self.newWindow = tk.Toplevel(self.master) ``` You are not creating a new window independent completely from your root (or `master`) but rather a child of the Toplevel (`master` in your case), of course this new `child` toplevel will act independent of the `master` until the `master` gets detroyed w...
55,036,033
Now, I have called python to C++. Using ctype to connect between both of them. And I have a problem about core dump when in running time. I have a library which is called "libfst.so" This is my code. NGramFST.h ``` #include <iostream> class NGramFST{ private: static NGramFST* m_Instace; public: NGramFST(){ ...
2019/03/07
[ "https://Stackoverflow.com/questions/55036033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5798231/" ]
`ctypes` does not understand C++ types (it's not called `c++types`). It cannot handle `std::string`. It wouldn't know that your function expects `std::string` arguments anyway. In order to work with `ctypes`, your library needs a C-compatible interface. `extern "C"` is necessary but not sufficient. The functions need ...
It work when I change python code below ``` string1 = "my string 1" string2 = "my string 2" # create byte objects from the strings b_string1 = string1.encode('utf-8') b_string2 = string2.encode('utf-8') print fst.getProbabilityOfWord(b_string1, b_string2) ``` and c++ code change type of param bellow ``` FST_getPr...
54,143,731
I am running a long computation on a Jupyter notebook and one of the threads spawn by python (a `pickle.dump` call, I suspect) took all the available RAM making the system clunky. Now, I would like to terminate the single thread. Interrupting the notebook does not work and I would like not to restart the notebook in o...
2019/01/11
[ "https://Stackoverflow.com/questions/54143731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3190076/" ]
I do not think you can kill a thread of a process outside the process itself: As reported in [this answer](https://unix.stackexchange.com/a/1071/210584) > > Threads are an integral part of the process and cannot be killed > outside it. There is the `pthread_kill` function but it only applies in > the context of th...
Of course the answer is yes, I have a demo code FYI(not secure): ``` from threading import Thread import time class MyThread(Thread): def __init__(self, stop): Thread.__init__(self) self.stop = stop def run(self): stop = False while not stop: print("I'm running") ...
10,755,833
I am attempting to deploy a [Flask](http://flask.pocoo.org/) app to [Heroku](http://www.heroku.com/). I'm using [Peewee](http://peewee.readthedocs.org/en/latest/) as an ORM for a Postgres database. When I follow the [standard Heroku steps to deploying Flask](https://devcenter.heroku.com/articles/python), the web proces...
2012/05/25
[ "https://Stackoverflow.com/questions/10755833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135156/" ]
According to the [Peewee docs](http://docs.peewee-orm.com/en/latest/peewee/database.html?highlight=postgres#dynamically-defining-a-database), you don't want to use `Proxy()` unless your local database driver is different than your remote one (i.e. locally, you're using SQLite and remotely you're using Postgres). If, ho...
Are you parsing the DATABASE\_URL environment variable? It will look something like this: ``` postgres://username:password@host:port/database_name ``` So you will want to pull that in and parse it before you open a connection to your database. Depending on how you've declared your database (in your config or next to...
10,755,833
I am attempting to deploy a [Flask](http://flask.pocoo.org/) app to [Heroku](http://www.heroku.com/). I'm using [Peewee](http://peewee.readthedocs.org/en/latest/) as an ORM for a Postgres database. When I follow the [standard Heroku steps to deploying Flask](https://devcenter.heroku.com/articles/python), the web proces...
2012/05/25
[ "https://Stackoverflow.com/questions/10755833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135156/" ]
According to the [Peewee docs](http://docs.peewee-orm.com/en/latest/peewee/database.html?highlight=postgres#dynamically-defining-a-database), you don't want to use `Proxy()` unless your local database driver is different than your remote one (i.e. locally, you're using SQLite and remotely you're using Postgres). If, ho...
heroku config:set HEROKU=1 ``` import os import urlparse import psycopg2 from flask import Flask from flask_peewee.db import Database if 'HEROKU' in os.environ: DEBUG = False urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ['DATABASE_URL']) DATABASE = { 'engine': 'pe...
10,755,833
I am attempting to deploy a [Flask](http://flask.pocoo.org/) app to [Heroku](http://www.heroku.com/). I'm using [Peewee](http://peewee.readthedocs.org/en/latest/) as an ORM for a Postgres database. When I follow the [standard Heroku steps to deploying Flask](https://devcenter.heroku.com/articles/python), the web proces...
2012/05/25
[ "https://Stackoverflow.com/questions/10755833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135156/" ]
According to the [Peewee docs](http://docs.peewee-orm.com/en/latest/peewee/database.html?highlight=postgres#dynamically-defining-a-database), you don't want to use `Proxy()` unless your local database driver is different than your remote one (i.e. locally, you're using SQLite and remotely you're using Postgres). If, ho...
I have managed to get my Flask app which uses Peewee working on Heroku using the below code: ``` # persons.py import os from peewee import * db_proxy = Proxy() # Define your models here class Person(Model): name = CharField(max_length=20, unique=True) age = IntField() class Meta: database = db...
46,125,105
I have done the following to get json file data into redis using this python script- ``` import json import redis r = redis.StrictRedis(host='127.0.0.1', port=6379, db=1) with open('products.json') as data_file: test_data = json.load(data_file) r.set('test_json', test_data) ``` When I use the **get** commmand fr...
2017/09/08
[ "https://Stackoverflow.com/questions/46125105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526217/" ]
Ways of circumventing your company's policy, from best to worse: * Load mod\_cgi anyway. * Load mod\_fcgi, and convert your CGI script into a Fast CGI daemon. It's a lot of work, but you'll can get faster code out of it! * Load your own module that does exactly the same thing as mod\_cgi. mod\_cgi is open source, so i...
[Last time you asked this question](https://stackoverflow.com/questions/45864198/cgi-scripts-to-mod-perl), you talked about using `mod_perl` instead. The standard way to run CGI program unchanged (for some value of "unchanged") under `mod_perl` is by using [ModPerl::Registry](https://metacpan.org/pod/ModPerl::Registry)...
73,416,533
I am new to python and wanted to know if there are best approaches for solving this problem. I have a string template which I want to compare with a list of strings and if any difference found, create a dictionary out of it. ``` template = "Hi {name}, how are you? Are you living in {location} currently? Can you confir...
2022/08/19
[ "https://Stackoverflow.com/questions/73416533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12722706/" ]
You can use regular-expression ``` template = "Hi {name}, how are you? Are you living in {location} currently? Can you confirm if following data is correct - {list_of_data}" list_of_strings = [ "Hi John, how are you? Are you living in California currently? Can you confirm if following data is correct - 123, 456, 3...
I guess using named regular expression groups is more elegant way to solve this problem, for example: ``` import re list_of_strings = [ "Hi John, how are you? Are you living in California currently? Can you confirm if following data is correct - 123, 456, 345", "Hi Steve, how are you? Are you living in New Y...