qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
5,918,353
I'm quite new to python and trying to port a simple exploit I've written for a stack overflow (just a nop sled, shell code and return address). This isn't for nefarious purposes but rather for a security lecture at a university. Given a hex string (deadbeef), what are the best ways to: * represent it as a series of b...
2011/05/07
[ "https://Stackoverflow.com/questions/5918353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742620/" ]
In Python 2.6 and above, you can use the built-in [`bytearray`](http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange) class. To create your `bytearray` object: ``` b = bytearray.fromhex('deadbeef') ``` To alter a byte, you can reference it using array notation: ...
Not sure if this is the best way... ``` hex_str = "deadbeef" bytes = "".join(chr(int(hex_str[i:i+2],16)) for i in xrange(0,len(hex_str),2)) rev_bytes = bytes[::-1] ``` Or might be simpler: ``` bytes = "\xde\xad\xbe\xef" rev_bytes = bytes[::-1] ```
4,712
28,771,226
I have a python list question: Input: ``` l=[2, 5, 6, 7, 10, 11, 12, 19, 20, 26, 28, 33, 34, 45, 46, 47, 50, 57, 59, 64, 67, 77, 79, 87, 93, 97, 106, 110, 111, 113, 115, 120, 125, 126, 133, 135, 142, 148, 160, 166, 169, 176, 202, 228, 234, 253, 274, 365, 433, 435, 436, 468, 476, 529, 570, 575, 577, 581, 614, 766, 81...
2015/02/27
[ "https://Stackoverflow.com/questions/28771226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556250/" ]
As you loop through the original array, check whether the current element is the next one in the sequence. If not, use another loop to generate the missing elements: ``` var dataParsed = []; var lastTime = data[0][0]; var timeStep = 60000; for (var i = 0; i < data.length; i++) { var curTime = data[i][0]; if (c...
You can have a loop which counts from first timestamp to the last, incremented by 60 seconds. Then populate a new array with current values + missing values like below. ``` var dataParsed = []; for(var i=data[0][0], j=0; i<=data[data.length-1][0]; i+=60000) { if(i == data[j][0]) { dataParsed.push(data[j]); j...
4,714
63,922,241
I am trying to use python Ctypes to interface to a C++ class I have been provided. I've gotten most everything working in terms of reading/writing member data and calling methods. But The class Im trying to exercise (call it ClassA) relies on an external Class (call it classB). see: ``` //main.cc This is existing ca...
2020/09/16
[ "https://Stackoverflow.com/questions/63922241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2312509/" ]
Given that you didnt show any code its hard to tell what your really trying to do. However assuming your mean nodes like in a tree then below simple example shows how you could recursivly work back up the tree to show the relationships. this of course is not a complete example but should give you an idea. ```py class ...
I don't quite understand what you are talking about but from what I DO understand there is no such thing as a parent object only parent classes so a node parent would not be possible
4,715
28,915,587
How can i split a **single** key-value pair into dictionary in python? ``` s = "x=y" sp = s.split('=', 1) for key,value in sp: print(key, "==", value) ``` I did not find anything helpful, except using nested `for` and `dict()` which is really unclear.
2015/03/07
[ "https://Stackoverflow.com/questions/28915587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3367446/" ]
``` >>> s = "x=y" >>> dict([s.split('=', 1)]) {'x': 'y'} ```
``` In [1]: s = "x=y" In [2]: sp = s.split('=', 1) In [3]: i=iter(sp) In [4]: new_dict=dict(zip(i,i)) In [5]: new_dict Out[5]: {'x': 'y'} ``` **dict-** It is used for creating a new dictionary. **zip-** It is used for iterating over two lists in parallel. **iter-** Returns a iterator.
4,716
21,201,661
I am trying to get the output of serverStatus command via pymongo and then insert it into a mongodb collection. Here is the dictionary `{u'metrics': {u'getLastError': {u'wtime': {u'num': 0, u'totalMillis': 0}, u'wtimeouts': 0L}, u'queryExecutor': {u'scanned': 0L}, u'record': {u'moves': 0L}, u'repl': {u'buffer': {u'cou...
2014/01/18
[ "https://Stackoverflow.com/questions/21201661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/649746/" ]
In the 14th line: ``` u'.': {u'timeAcquiringMicros': {u'R': 218733L, u'W': 30803L}, u'timeLockedMicros': {u'R': 311478L, u'W': 145679L}}} ``` For future safety, iterate through the keys, replace '.'s with '\_' or something, and then perform a write.
Here is a function which will remove '.' from your keys: ``` def fix_dict(data, ignore_duplicate_key=True): """ Removes dots "." from keys, as mongo doesn't like that. If the key is already there without the dot, the dot-value get's lost. This modifies the existing dict! :param ignore_duplicate_ke...
4,719
53,755,983
There is a related question [here](https://stackoverflow.com/questions/7001917/pause-python-generator). I am attempting to do [this](https://www.hackerrank.com/contests/projecteuler/challenges/euler024/copy-from/1311767864) project Euler challenge on HackerRank. What it requires is that you are able to derive the *n*th...
2018/12/13
[ "https://Stackoverflow.com/questions/53755983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4476908/" ]
Pausing is built-in functionality for generators. It's half the point of generators. However, `range` is **not a generator**. It's a lazy sequence type. If you want an object where iterating over it again will resume where you last stopped, you want an iterator over the range object: ``` idsx_iter = iter(range(1, mat...
The answer to the question in the title is "yes", you can pause and restart. How? Unexpectedly (to me), apparently `zip()` restarts the zipped generators despite them being previously defined (maybe someone can tell me why that happens?). So, I added `main_gen = zip(idxs_gen, perms_gen)` and changed to `for num, stry ...
4,722
7,949,024
I am trying to install psycopg2 in virtualenv enviroment and am having a heck of a time. I think I may have screwed something up because I installed virtualenv and then upgraded to Xcode 4. ``` (my_enviroment)my_users-macbook-2:my_enviroment my_user$ pip install psycopg2 ``` Produces this message: ``` Downloading/...
2011/10/31
[ "https://Stackoverflow.com/questions/7949024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/913018/" ]
Your error is this: ``` unable to execute gcc-4.2: No such file or directory ``` Which means that `gcc-4.2` is not installed. Either downgrade (or upgrade) your GCC version, or modify the package to build with just the `gcc` command. A bit more hacky would be to `ln` `gcc-4.2` to the `gcc` command.
I've found the easiest way to install PIL on 10.7 is to create a symlink from gcc-4.2 to gcc. ``` sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2 easy_install pil ```
4,725
64,882,718
I'm using Rpy2 within python to call R but for some reason I am not able to load a a specific package, 'rmgarch'. I have installed it separately in R and it works when I import it in RStudio, but for whatever reason, it just doesn't wanna work in rpy2, even though rpy2 is perfectly happy importing other packages such a...
2020/11/17
[ "https://Stackoverflow.com/questions/64882718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14290433/" ]
You can integrate with something like this: ```js class BoxCast extends React.Component { componentDidMount() { const {broadcastChannelId, broadcastId} = this.props; this.$el = $(this.el); this.context = boxcast(this.$el); this.context.loadChannel(broadcastChannelId, { autoplay: true, sho...
This does not looks like its being React compatible. If you insist to use it from React, you'll need to [integrate it](https://reactjs.org/docs/integrating-with-other-libraries.html). It might be a tedious job and I discourage you from doing that. Look for another provider claiming to be React compatible.
4,734
54,896,846
What should I do if I want to get the sum of every 3 elements? ``` test_arr = [1,2,3,4,5,6,7,8] ``` It sounds like a map function ``` map_fn(arr, parallel_iterations = True, lambda a,b,c : a+b+c) ``` and the result of `map_fn(test_arr)` should be ``` [6,9,12,15,18,21] ``` which equals to ``` [(1+2+3),(2+3+...
2019/02/27
[ "https://Stackoverflow.com/questions/54896846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5958473/" ]
It's even easier: use a list comprehension. Slice the list into 3-element segments and take the sum of each. Wrap those in a list. ``` [sum(test_arr[i-2:i+1]) for i in range(2, len(test_arr))] ```
Simply loop through your array until you are 3 from the end. ``` # Takes a collection as argument def map_function(array): # Initialise results and i results = [] int i = 0 # While i is less than 3 positions away from the end of the array while(i <= (len(array) - 3)): # Add the sum of the...
4,735
50,490,556
wx [event handlers](https://wxpython.org/Phoenix/docs/html/events_overview.html) attached with `.Bind(...)` receive as a parameter an event object with a `.Skip()` method. Calling `.Skip()` allows the event's default behaviour to happen; attaching a handler that does not call `.Skip()` suppresses the default behaviour....
2018/05/23
[ "https://Stackoverflow.com/questions/50490556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709587/" ]
Not calling `wxEvent::Skip()` does 2 related but different things: it prevents the default event handler inside the underlying UI toolkit from from processing it and it also prevents any other handlers of the same event in your own code from processing it. The first aspect is indeed not important for command events, w...
Generally speaking calling Skip() inside the event handler only make sense for non-wxCommandEvent handlers. You can just let the handler finish and you program will do next event iteration. Since wxEVT\_TEXT is wxCommandEvent event calling Skip() does not make much sense. However not calling Skip() on non-wxCommandEv...
4,736
13,173,029
My friend has an application written in `C` that comes with a GUI made using `GTK` under Linux. Now we want to rewrite the GUI in python (`wxpython` or `PyQT`). I don't have experience with Python and don't know how to make Python communicate with C. I'd like to know if this is possible and if yes, how should I go abo...
2012/11/01
[ "https://Stackoverflow.com/questions/13173029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1703502/" ]
Yes its possible to call 'C' functions from Python. Please look into SWIG(deprecated) also Python provides its own Extensibility API. You might want to look into that. Also google CTypes. LINKS: [Python Extension](http://docs.python.org/2/extending/extending.html) A simple example: I used Cygwin on Windows for thi...
> > Sorry but i don't have python experience so don't know how to make Python communicate with C program. > > > Yes, that's exactly how you do it. Turn your C code into a Python module, and then you can write the entire GUI in Python. See [Extending and Embedding the Python Interpreter](http://docs.python.org/2/ex...
4,737
8,746,586
I'm using [python-mock](http://www.voidspace.org.uk/python/mock/) to mock out a file open call. I would like to be able to pass in fake data this way, so I can verify that `read()` is being called as well as using test data without hitting the filesystem on tests. Here's what I've got so far: ``` file_mock = MagicMoc...
2012/01/05
[ "https://Stackoverflow.com/questions/8746586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112785/" ]
This sounds like a good use-case for a `StringIO` object that already implements the file interface. Maybe you can make a `file_mock = MagicMock(spec=file, wraps=StringIO('test'))`. Or you could just have your function accept a file-like object and pass it a `StringIO` instead of a real file, avoiding the need for ugly...
building on @tbc0 answer, to support Python 2 and 3 (multi-version tests are helpful to port 2 to 3): ``` import sys module_ = "builtins" module_ = module_ if module_ in sys.modules else '__builtin__' try: import unittest.mock as mock except (ImportError,) as e: import mock with mock.patch('%s.open' % modul...
4,740
63,307,054
I am learning how to code a game in python(version 3.6), and I have come across an error that has me lost. I tried to run my code and this error message that traced back to sprite.py(A file that I imported from python's library). This is the error message popped up: > > File "C:\Users\aveil\AppData\Roaming\Python\Pyt...
2020/08/07
[ "https://Stackoverflow.com/questions/63307054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
you may find useful the function "replace", also this will allow to do a backup for the file (if you want) ``` string backup = destination + ".bak"; File.Delete(backup); File.Replace(source, destination, backup, true); ``` You can play a little with that. More info: <https://learn.microsoft.com/en-us/dotnet/api/sys...
If the new image has the same name, you can check the existence of the file and delete it before creating the new file. Note: Make sure the file path is correct (filename along with extension should also be included). ``` if (File.Exists("smb://serverUsername:ServerPassword@serverIP/sharefile/fileToDelete.jpg")) { ...
4,742
29,925,783
I am pretty new to programming with python. So apologies in advance: I have two python scripts which should share variables. Furthermore the first script (first.py) should call second script (second.py) first.py: ``` import commands x=5 print x cmd = "path-to-second/second.py" ou = commands.getoutput(cmd) print x ``...
2015/04/28
[ "https://Stackoverflow.com/questions/29925783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4723963/" ]
C++ does not provide some magical handling for your abstract logic, it cannot just work out that `File1=File2+File3` means you want to merge two files together. Firstly, those variables would have to be some form of 'type', and to have the logic you want, a type of your own devising. It would be constructed from a `st...
Unfortunately you cannot add two files together like that Instead you have to use `ifstream` and `ofstream` from the `fstream` library Here is an example that you can use ``` std::ifstream file1( "Data1.txt" ) ; std::ifstream file2( "Data2.txt" ) ; std::ofstream combined_file( "dataOut.txt" ) ; combined_file << file...
4,743
52,781,297
I setup Ubuntu server 18.04 LTS, LAMP, and mod\_mono (which appears to be working fine alongside PHP now by the way.) Got python working too; at first it gave an HTTP "Internal Server Error" message. `sudo chmod +x myfile.py` fixed this error and the code python generates is displayed fine. But any time the execute per...
2018/10/12
[ "https://Stackoverflow.com/questions/52781297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4626146/" ]
I really struggled with this and finally managed to clear it with the following approach: ``` require './aws/aws-autoloader.php'; use Aws\Credentials\Credentials; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; use Aws\Signature\SignatureV4; use Aws\Credentials\CredentialProvider; $url = '<your URL>'; $region = ...
You can install AWS php sdk via composer `composer require aws/aws-sdk-php` and here is the github <https://github.com/aws/aws-sdk-php> . In case you want to do something simple or they don't have what you are looking for you can use `curl` in php to post data. ``` $ch = curl_init(); $data = http_build_query([ "e...
4,744
12,147,394
I have a C file that has a bunch of #defines for bits that I'd like to reference from python. There's enough of them that I'd rather not copy them into my python code, instead is there an accepted method to reference them directly from python? Note: I know I can just open the header file and parse it, that would be si...
2012/08/27
[ "https://Stackoverflow.com/questions/12147394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354209/" ]
Running under the assumption that the C .h file contains only #defines (and therefore has nothing external to link against), then the following would work with swig 2.0 (http://www.swig.org/) and python 2.7 (tested). Suppose the file containing just defines is named just\_defines.h as above: ``` #define FOO_A 0x3 #def...
`#define`s are macros, that have no meaning whatsoever outside of your C compiler's preprocessor. As such, they are the bane of multi-language programmers everywhere. (For example, see this Ada question: [Setting the license for modules in the linux kernel](https://stackoverflow.com/questions/11927590/setting-the-licen...
4,745
32,367,279
I start Django server with `python manage.py runserver` and then quit with CONTROL-C, but I can still access urls in `ROOT_URLCONF`, why?
2015/09/03
[ "https://Stackoverflow.com/questions/32367279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456105/" ]
Probably you left another process running somewhere else. Here is how you can list all processes whose command contains `manage.py`: ``` ps ax | grep manage.py ``` Here is how you can kill them: ``` pkill -f manage.py ```
Without seeing your script, I would have to say that you have blocking calls, such as socket.recv() or os.system(executable) running at the time of the CTRL+C. Your script is stuck after the CTRL+C because python executes the `KeyboardInterrupt` AFTER the the current command is completed, but before the next one. If t...
4,754
71,484,131
I am trying to extract a sub-array using logical indexes as, ``` a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) a Out[45]: array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) b = np.array([False, True, False, True]) a[b, b] Out[49]: array...
2022/03/15
[ "https://Stackoverflow.com/questions/71484131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10976198/" ]
Numpy supports logical indexing, though it is a little different than what you are familiar in MATLAB. To get the results you want you can do the following: ``` a[b][:,b] # first brackets isolates the rows, second brackets isolate the columns Out[27]: array([[ 6, 8], [14, 16]]) ``` The more "numpy" method ...
You could use [`np.ix_`](https://numpy.org/doc/stable/reference/generated/numpy.ix_.html) here. ``` a[np.ix_(b, b)] # array([[ 6, 8], # [14, 16]]) ``` --- Output returned by `np.ix_` ``` >>> np.ix_(b, b) (array([[1], [3]]), array([[1, 3]])) ```
4,757
60,393,214
In django, I have attempted to switch from using an sqlite3 database to postgresql. `settings.py` has been switched to connect to postgres. Both `python manage.py makemigrations` and `python manage.py migrate` run without errors. `makemigrations` says that it creates the models for the database, however when running `m...
2020/02/25
[ "https://Stackoverflow.com/questions/60393214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12959523/" ]
The datapoints on the old domain, i.e. ``` import numpy as np from scipy import interpolate from scipy import misc import matplotlib.pyplot as plt arr = misc.face(gray=True) x = np.linspace(0, 1, arr.shape[0]) y = np.linspace(0, 1, arr.shape[1]) f = interpolate.interp2d(y, x, arr, kind='cubic') x2 = np.linspace(0, ...
[skimage.transform.resize](https://scikit-image.org/docs/stable/api/skimage.transform.html#skimage.transform.resize) is a very convenient way to do this: ``` import numpy as np from skimage.transform import resize import matplotlib.pyplot as plt from scipy import misc arr = misc.face(gray=True) dim1, dim2 = 1000, 16...
4,760
26,093,807
I have installed thrift 0.8.0 in Ubuntu 12.04 I followed the all commands correctly with out any error but after installation it's working perfect **Now i want to use PHP by using thrift but in below code it only Shows YES for C++ and Python i need java and PHP but that two languages shows NO How can i use PHP and ...
2014/09/29
[ "https://Stackoverflow.com/questions/26093807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3967915/" ]
First, download the source version of Thrift. I would strongly recommend using a newer version if possible. There are several ways to include the Thrift Java library (may have to change slightly for your Thrift version): If you are using maven, you can add the maven coordinates to your pom.xml: ``` <dependency> <...
* for Java: you can download .jar library, javadoc here <http://repo1.maven.org/maven2/org/apache/thrift/libthrift/0.9.1/> * for PHP: copy [thrift-source]/lib/php/lib to your project and use it. This is a example to use: <https://thrift.apache.org/tutorial/php> P/s: i want to use .dll PHP extension rather than PHP sou...
4,761
43,383,686
In one of my shell script I am using eval command like below to evaluate the environment path - ``` CONFIGFILE='config.txt' ###Read File Contents to Variables while IFS=\| read TEMP_DIR_NAME EXT do eval DIR_NAME=$TEMP_DIR_NAME echo $DIR_NAME done < "$CONFIGFILE" ``` Output: ``` /path/to/...
2017/04/13
[ "https://Stackoverflow.com/questions/43383686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2350145/" ]
You can do it a couple of ways depending on where you want to set MY\_PATH. `os.path.expandvars()` expands shell-like templates using the current environment. So if MY\_PATH is set before calling, you do ``` td@mintyfresh ~/tmp $ export MY_PATH=/path/to/certain/location td@mintyfresh ~/tmp $ python3 Python 3.5.2 (defa...
You could use os.path.expandvars() (from [Expanding Environment variable in string using python](https://stackoverflow.com/questions/5258647/expanding-environment-variable-in-string-using-python)): ``` import os config_file = 'config.txt' with open(config_file) as f: for line in f: temp_dir_name, ext = lin...
4,762
69,442,782
At first I thought it was an error connecting with GitHub but this seems to not be the script since the first part of the script fires up normally Full output for context ``` ┌──(kali㉿kali)-[~/bhptrojan] └─$ python3 git_trojan.py ...
2021/10/04
[ "https://Stackoverflow.com/questions/69442782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16464360/" ]
Here is a possible method of doing this, which should be slightly faster than excessive use of loops. Method: 1. Split each review into its individual words. 2. Create a dictionary with the key being the review word and the value being the frequency. 3. Loop through every topic, then loop through every keyword in tha...
I think your `countOccurance(topics:reviews:)` function is violating the single responsibility principle (it's not really counting occurrences, it's also filtering words). As a result, it's very specialized to your one use-case, and you won't find any built-in facilities to help you. On the other hand, if you broke do...
4,763
21,559,433
I have the following code in my client: ``` data = {"method": 2,"read": 3} s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(server_address) req = json.dumps(data) s.send(req) ``` and I am trying the following in my server: ``` # Threat the socket as a f...
2014/02/04
[ "https://Stackoverflow.com/questions/21559433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2277094/" ]
I'm assuming you're using python 3, judging by the errors. You'll need to encode your data into bytes. Sockets cannot directly send python3 strings.
Your JSON isn't valid. Put it through JSON lint to find the error. <http://jsonlint.com/>
4,764
27,849,412
This is the error when I try to get anything with pip3 I'm not sure what to do ``` Exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 283, ...
2015/01/08
[ "https://Stackoverflow.com/questions/27849412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358680/" ]
just install them using --user option which install the package only for the current user and not for all ``` pip install xxxxxx --user ```
You need to use `sudo` to install globally or have permissions to write to the folder. Or as @Alasdair commented using a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/) is a better option.
4,766
50,963,625
I'm using Python 3.6 through Spyder in Anaconda3. I have both the Anaconda installation and a "clean" python installation. Before I installed the "clean" python, when I ran the `Python -V` command in cmd I got the following version description `Python 3.6.5 :: Anaconda, Inc.` Now when I run the command it just says `...
2018/06/21
[ "https://Stackoverflow.com/questions/50963625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114229/" ]
I know it's a very late answer, but it may help other people. When you are working with anaconda you can use the basic environement or create a new one (it may be what's you call a "clean" python installation). To do that just do the following : * Open you anaconda navigator * Go to "Environments" * Click on the butto...
There is a pip.exe included in the anaconda/Spyder package which can cleanly add mopdules to Spyder. It's not installed in the windows path by default, probably so it' won't interfere with the "normal" pip in my "normal" python package. Check "/c/Users/myname/Anaconda3/Scripts/pip.exe". It seems to depend on local DLL...
4,769
30,856,274
I am new to python development using virtualenv. I have installed python 2.7, pip, virtualenv, virtualenvwrapper in windows and I am using windows PS. I have referred lots of tutorials for setting this up. Most of them contained the same steps and almost all of them stopped short of explaining what to do *after* the vi...
2015/06/15
[ "https://Stackoverflow.com/questions/30856274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4051896/" ]
> > How do I actually work in a virtualenv? suppose I want to create a new flask application after installing that package in my new env virtualenv (eg; testenv). > > > You open up Command Prompt and activate the virtualenv: ``` > \path\to\env\Scripts\activate ``` When you run `python` and `pip`, they run in th...
1. testenv/bin/pip and testenv/bin/python 2. I'd check it in a local repository and check it out in the virtualenv. 3. No, you have not.
4,774
34,093,247
On Windows 8, I've created a sample project in Django (1.6.5) and I'm getting errors when I run a custom command I wrote (runtcpserver). This is how my project structure looks like: c:/django/entitetracker: ``` manage.py tcpserver/ forms.py views.py models.py urls.py management __init__.p...
2015/12/04
[ "https://Stackoverflow.com/questions/34093247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563130/" ]
Your `PYTHONPATH` is `C:\django\entitetracker`. You can load `entitetracker.settings`. In finish, Python try to find `C:\django\entitetracker\entitetracker\settings` package. Use ``` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") ```
My God, I'm so stupid. The error was I was missing the two dashes before settings=settings.local! Thanks for your help Tomasz.
4,775
48,506,093
I have a REST API backend with python/flask and want to stream the response in an event stream. Everything is running inside a docker container with nginx/uwsgi (<https://hub.docker.com/r/tiangolo/uwsgi-nginx-flask/>). The API works fine until it comes to the event-stream. It seems like something (probably nginx) is b...
2018/01/29
[ "https://Stackoverflow.com/questions/48506093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5623899/" ]
I ran into the same problem. Try changing ``` return Response(calcResult(), content_type="text/event-stream") ``` to ``` return Response(calcResult(), content_type="text/event-stream", headers={'X-Accel-Buffering': 'no'}) ```
Following [the answer from @u-rizwan here](https://stackoverflow.com/a/48746083/236195), I added this to the `/etc/nginx/conf.d/mysite.conf` and it resolved the problem: ``` add_header X-Accel-Buffering no; ``` I have added it under `location /`, but it is probably a good idea to put it under the specific location...
4,776
4,982,138
I am on exercise 43 doing some self-directed work in [Learn Python The Hard Way](http://learnpythonthehardway.org/). And I have designed the framework of a game spread out over two python files. The point of the exercise is that each "room" in the game has a different class. I have tried a number of things, but I canno...
2011/02/13
[ "https://Stackoverflow.com/questions/4982138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614742/" ]
Instead of returning a string try returning an object, ie ``` if choice == "car": return CarRoom() ```
1. It might be a good idea to make a Room class, and derive your other rooms from it. 2. The Room base class can then have a class variable which automatically keeps track of all instantiated rooms. I haven't thoroughly tested the following, but hopefully it will give you some ideas: ``` # getters.py try: getStr ...
4,777
13,822,823
Currently, it is possible to **mark** tests and then run them (or not run them) using `-m` argument. However, all tests are still collected first and only then are **deselected** In the below example all 8 are still collected, and then 4 are run and 4 are deselected. ``` ============================= test session sta...
2012/12/11
[ "https://Stackoverflow.com/questions/13822823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1167879/" ]
The problem is not `py.test`, but the fact that the class code is executed when the file is imported, so you get the error **before** the decorator is even called. The only way(without modifying the logic of the code) to avoid this is to completely ignore the whole file. Anyway, I do not understand why you set the `d...
Deselecting tests only after collection is complete happens for two reasons: * to always get a correct number of overall tests * collection hooks might dynamically add or remove marks Regarding auto-completion, i believe putting heavy setup into fixtures is more important. I am not sure if Pydev could learn to still ...
4,778
60,932,166
I'm setting up a image data pipeline on Tensorflow 2.1. I'm using a dataset with RGB images of variable shapes (h, w, 3) and I can't find a way to make it work. I get the following error when I call `tf.data.Dataset.batch()` : `tensorflow.python.framework.errors_impl.InvalidArgumentError: Cannot batch tensors with dif...
2020/03/30
[ "https://Stackoverflow.com/questions/60932166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9727793/" ]
I just hit the same problem. The solution turned out to be loading the data as 2 datasets and then using dataet.zip() to merge them. ``` images = dataset.map(parse_images, num_parallel_calls=tf.data.experimental.AUTOTUNE) images = dataset_images.apply( tf.data.experimental.dense_to_ragged_batch(batch_size=batch_si...
If you do not want to resize your images, you can only use a batch size of `1` and not bigger than that. Thus you can train your model one image at at time. The error you reported clearly says that you are using a batch size bigger than 1 and trying to put two images of different shape/size in a batch. You could either...
4,779
23,526,592
I am trying to extract the stem of the words `taller` and `shorter` from a string in python. I did the following: ``` >>> from nltk.stem.porter import * >>> print(stemmer.stem('shorter')) shorter >>> print(stemmer.stem('taller')) taller ``` And for some reason, I don't get the words `tall` and `short`. Anyone knows...
2014/05/07
[ "https://Stackoverflow.com/questions/23526592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2816349/" ]
There are a few stemmers. Here's one: ``` >>> from nltk.stem.lancaster import LancasterStemmer >>> stemmer = LancasterStemmer() >>> stemmer.stem('shorter') 'short' ```
``` >>> from nltk import stem >>> s = 'short'; t = 'tall' >>> porter = stem.porter.PorterStemmer() >>> lancaster = stem.lancaster.LancasterStemmer() >>> snowball = stem.snowball.EnglishStemmer() >>> porter.stem(s) u'short' >>> porter.stem(t) u'tall' >>> lancaster.stem(s) 'short' >>> lancaster.stem(t) 'tal' >>> snowball...
4,780
69,103,209
I have a [dataset](https://drive.google.com/file/d/1EariymtHoBJEflDPkJTg-jKxMfVhll59/view?usp=sharing) containing nested json object. I wish to extract information from this nested json and put it in a DataFrame in python. I have used json\_normalize method but i am unable to parse after a certain level. Kindly help. T...
2021/09/08
[ "https://Stackoverflow.com/questions/69103209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7054640/" ]
Have been working on a function that will expand all embedded lists and dictionaries. ``` from pathlib import Path with open(Path.home().joinpath("Downloads").joinpath("Sample Json.txt")) as f: js = f.read() def normalize(js, expand_all=False): df = pd.json_normalize(json.loads(js) if type(js) == str else js) ...
To "flat" a nested json file, you can use the following function: ``` def flatten_json(nested_json): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x...
4,781
17,369,212
I would like to know if there's a function similar to `map` but working for methods of an instance. To make it clear, I know that `map` works as: ``` map( function_name , elements ) # is the same thing as: [ function_name( element ) for element in elements ] ``` and now I'm looking for some kind of `map2` that does:...
2013/06/28
[ "https://Stackoverflow.com/questions/17369212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2014276/" ]
[`operator.methodcaller()`](http://docs.python.org/2/library/operator.html#operator.methodcaller) will give you a function that you can use for this. ``` map(operator.methodcaller('method_name'), sequence) ```
You can use `lambda` expression. For example ``` a = ["Abc", "ddEEf", "gHI"] print map(lambda x:x.lower(), a) ``` You will find that all elements of `a` have been turned into lower case.
4,782
9,007,174
What is the best way to take a data file that contains a header row and read this row into a named tuple so that the data rows can be accessed by header name? I was attempting something like this: ``` import csv from collections import namedtuple with open('data_file.txt', mode="r") as infile: reader = csv.reade...
2012/01/25
[ "https://Stackoverflow.com/questions/9007174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636493/" ]
Use: ``` Data = namedtuple("Data", next(reader)) ``` and omit the line: ``` next(reader) ``` Combining this with an iterative version based on martineau's comment below, the example becomes for Python 2 ``` import csv from collections import namedtuple from itertools import imap with open("data_file.txt", mode=...
Please have a look at [`csv.DictReader`](http://docs.python.org/library/csv.html#csv.DictReader). Basically, it provides the ability to get the column names from the first row as you're looking for and, after that, lets you access to each column in a row by name using a dictionary. If for some reason you still need to...
4,783
31,813,457
I am trying to run a blat search from within my python code. Right now it's written as... ``` os.system('blat database.fa fastafile pslfile') ``` When I run the code, I specify file names for "fastafile" and "pslfile"... ``` python my_code.py -f new.fasta -p test.psl ``` This doesn't work as "fastafile" and "pslf...
2015/08/04
[ "https://Stackoverflow.com/questions/31813457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5025033/" ]
As it applies to agent-based releases: *Tools* are intended to provide a custom resource (executable, PowerShell script, batch file, and so on) with a command line to execute said custom resource, and a default set of command line parameters. Using an example from the built-in resources: IIS Manager. The IIS Manager i...
I'm not sure that there is a universal definition that doesn't have exceptions, but I see it as: **Actions** - functionality that doesn't interact with a build eg starting or stopping a service (except for the Deploy using Chef or PS/DSC actions). Only used in Agent-based templates. **Tools** - functionality that int...
4,786
28,314,742
Using the regex in python, I want to compile a string that gets the pattern "\1" up to "\9". I've tried ``` regex= re.compile("\\(\d)") #sre_constants.error: unbalanced parenthesis regex= re.compile("\\\(\d)") #gets \\4 but not \4 ``` but to no avail.. Any thoughts?
2015/02/04
[ "https://Stackoverflow.com/questions/28314742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4383952/" ]
One more: `re.compile("\\\\(\\d)")`. Or, a better option, a raw string: `re.compile(r"\\(\d)")`. The reason is the fact that backslash has meaning in both a string and in a regexp. For example, in regexp, `\d` is "a digit"; so you can't just use `\` for a backslash, and backslash is thus `\\`. But in a normal string, ...
You should use a [raw-string](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals) (which does not process escape sequences): ``` regex= re.compile(r"\\(\d)") ```
4,787
70,854,703
I have a bunch of .json files that I am trying to access. I need to calculate the growing season of a particular crop based on the planting and harvest dates. Problem: With the following code, I get this error: AttributeError: Can only use .dt accessor with datetimelike values Code: ``` import os import copy import ...
2022/01/25
[ "https://Stackoverflow.com/questions/70854703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10609402/" ]
``` >>> df plant_date 0 NaN 1 2021-11-12 >>> df.loc[1, 'plant_date'] = pd.to_datetime(df.loc[1, 'plant_date'], errors='coerce', format='%Y-%m-%d') >>> df plant_date 0 NaN 1 2021-11-12 00:00:00 ``` Due to how you're creating your dataframe - it being prepopulated with `np.nan`...
I was able to make it work. Here is the updated code. Right after pd.concat, the following code helped: ``` obs_df['plant_date'] = pd.to_datetime(obs_df['plant_date']) obs_df['harvest_date'] = pd.to_datetime(obs_df['harvest_date']) ```
4,790
33,579,522
I am a new python user and I am quite interesting on understanding in depth how works the NumPy module. I am writing on a function able to use both masked and unmasked arrays as data input. I have noticed that there are several [numpy masked operations](http://docs.scipy.org/doc/numpy/reference/routines.ma.html) that ...
2015/11/07
[ "https://Stackoverflow.com/questions/33579522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5373784/" ]
`np.ma.zeros` creates a masked array rather than a normal array which could be useful if some later operation on this array creates invalid values. An example from the manual: > > Arrays sometimes contain invalid or missing data. When doing > operations on such arrays, we wish to suppress invalid values, which > is...
As a beginner don't get too bogged down with masked arrays. It's a subclass of `np.ndarray`, that is useful when dealing with data that has some bad values that you'd like to ignored when calculating things like the mean. But otherwise you should focus on creation and indexing (and calculations) with the base numpy cla...
4,791
17,497,860
I am trying to download an entire play list for Android development tutorial from Youtube. So I used [savefrom](http://en.savefrom.net/) for generating playlist for download. But the problem is that I have so many videos in that playlist. So, I decided to write a python script for making this work simpler. But the prob...
2013/07/05
[ "https://Stackoverflow.com/questions/17497860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1464519/" ]
Error occured on following line. ``` return browser.page_source() ``` I think brackets did not need. ``` return browser.page_source ```
I think not ! ``` pcode = wdriver.page_source() ``` is absoluteley right call. By auto-complete in python ide. I have the same problem. Looks like we need to encode page-sourse text variable in somethind like classic ANSI
4,792
73,099,677
Could you help me? I'm trying to close my main window and then create a new window. I'm using withdraw() instead of destroy() since I'm planning to use that widget later. Here is my code, but I just get: `tkinter.TclError: image "pyimage10" doesn't exist` I separated the codes of the main window and a new window into...
2022/07/24
[ "https://Stackoverflow.com/questions/73099677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14257622/" ]
::with('trans') returns completely new query and forgets everything about your ::find($id)
What happens is, `House::find($id)` is a method that returns the element by its primary key. Then, the `::with('trans')` gets the result, sees the House class and starts creating a new query builder for the Model. Finally, the `->get()` runs this new query and the end result is what is return for the `$house` value. Y...
4,793
67,353,503
i'm new to python and i'm trying to parse a list in `["+",1,3,3]` and then identify it's string operator `"+" "-" "x" "/"` and convert it into a question `{"qns": "1 + 3 + 3", "ans": 7}` and answer into a dictionary with just two key "qns and "ans" So the question is there is a nested list as an input to the function....
2021/05/02
[ "https://Stackoverflow.com/questions/67353503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12929490/" ]
A variable of type `dynamic` would be similar to javascript where it can change type during runtime. For example store an integer then change to a string. `var` is not the same as dynamic. `var` is an easy way to initialise variables as you don't have to explicitly state the type. Dart just infers the type to make it ...
the reason I think var is better is that it is slightly more convenience, for example ```dart var n = 1; int m = 1; ``` both `n` and `m` are integer if some day you changed your mind and want to reinitialize them with new decimal number instead ```dart var n = 9.9; double m = 9.9; ``` in this case, var requires ...
4,795
57,948,794
I have made a Python application which uses GTK. I want to send the user a dialog asking for confirmation for an action, however after creating the dialog based on [this](https://python-gtk-3-tutorial.readthedocs.io/en/latest/dialogs.html) tutorial, I noticed that there is no apparent way to center-align the 'Cancel' a...
2019/09/15
[ "https://Stackoverflow.com/questions/57948794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11116713/" ]
> > **Question**: Aligning dialog buttons to center > > > --- * [Gtk.Dialog.get\_action\_area](http://lazka.github.io/pgi-docs/#Gtk-3.0/classes/Dialog.html#Gtk.Dialog.get_action_area) * [Gtk.Widget.props.parent](http://lazka.github.io/pgi-docs/#Gtk-3.0/classes/Widget.html#Gtk.Widget.props.parent) * [Gtk.Box.set\_...
I don't know if this is a cheaty way of doing it but it seems to work. ``` action_area= self.get_action_area() action_area.set_halign(3) ```
4,796
25,849,850
In python 3.4.0, using `json.dumps()` throws me a TypeError in one case but works like a charm in other case (which I think is equivalent to the first one). I have a dict where keys are strings and values are numbers and other dicts (i.e. something like `{'x': 1.234, 'y': -5.678, 'z': {'a': 4, 'b': 0, 'c': -6}}`). Th...
2014/09/15
[ "https://Stackoverflow.com/questions/25849850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/461202/" ]
The cause was that the numbers inside the `dict` were not ordinary python `int`s but `numpy.in64`s which are apparently not supported by the json encoder.
As you have seen, numpy int64 data types are not serializable into json directly: ``` >>> import numpy as np >>> import json >>> a=np.zeros(3, dtype=np.int64) >>> a[0]=-9223372036854775808 >>> a[2]=9223372036854775807 >>> jstr=json.dumps(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> Fil...
4,797
24,690,298
Python matplotlib gives very nice figures. How to call python matplotlib in Qt C++ project? I'd like to put those figures in Qt dialogs and data are transferred via memory.
2014/07/11
[ "https://Stackoverflow.com/questions/24690298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1899020/" ]
You can create a python script with function calls to matplotlib and add them as callback functions in your C++ code. [This tutorial](http://www.codeproject.com/Articles/11805/Embedding-Python-in-C-C-Part-I) explains how this can be done. I also recommend reading the documentation on [Python.h](https://docs.python....
I would try using [matplotlib-cpp](https://github.com/lava/matplotlib-cpp). It is built to resemble the plotting API used by Matlab and matplotlib. Basically it is a C++ wrapper around matplotlib and it's header only. Keep in mind though that it does not provide all the matplotlib features from python. Here is the in...
4,798
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...
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...
4,799
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...
4,809
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...
4,810
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...
4,811
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...
4,812
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/...
4,815
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...
4,816
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); } }; ```...
4,822
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...
4,823
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: 14370afcdc17429f9e418d5ffbd0334a@magic.com ce06e817-2149-6cfd-dd24-51b31e93ea1a@stackoverflow.org.il 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...
4,828
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.
4,829
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.
4,830
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); ```
4,832
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:$ ```
4,837
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
4,838
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...
4,839
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,842
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.
4,843
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,844
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,845
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); } ```
4,847
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:)
4,848
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.
4,849
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...
4,850
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...
4,851
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...
4,852
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...
4,854
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)) ```
4,855
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)
4,856
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.
4,857
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 ...
4,858
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...
4,866
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...
4,868
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 ...
4,878
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.
4,879
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...
4,881
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...
4,882
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
4,884
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.
4,885
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...
4,887
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...
4,888
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.
4,891
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...
4,892
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...
4,893
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") ...
4,894
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...
4,895
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)...
4,898
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...
4,899
16,375,781
I am trying a simple nested for loop in python to scan a threshold-ed image to detect the white pixels and store their location. The problem is that although the array it is reading from is only 160\*120 (19200) it still takes about 6s to execute, my code is as follows and any help or guidance would be greatly apprecia...
2013/05/04
[ "https://Stackoverflow.com/questions/16375781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274632/" ]
First, it shouldn't take 6 seconds. Trying your code on a 160x120 image takes ~0.2 s for me. That said, for good `numpy` performance, you generally want to avoid loops. Sometimes it's simpler to vectorize along all except the smallest axis and loop along that, but when possible you should try to do everything at once....
e you're on python 2.x (2.6 or 2.7). In python 2, every time you call `range` you're creating a list with that many elements. (In this case, you're creating 1 list of `width - 1` length, and then `width - 1` lists of `height - 1` length. One way to speed this up is to make one list of each ahead of time and use that li...
4,900
11,705,114
I am reading a bunch of strings from mysql database using python, and after some processing, writing them to a CSV file. However I see some totally junk characters appearing in the csv file. For example when I open the csv using gvim, I see characters like `<92>`,`<89>`, `<94>` etc. Any thoughts? I tried doing string...
2012/07/28
[ "https://Stackoverflow.com/questions/11705114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1546936/" ]
I would try a character class regex similar to ``` "[.!?\\-]" ``` Add whatever characters you wish to match inside the `[]`s. Be careful to escape any characters that might have a special meaning to the regex parser. You then have to iterate through the matches by using `Matcher.find()` until it returns false.
I would try > > `\W` > > > it matches any non-word character. This includes spaces and punctuation, but not underscores. It’s equivalent to [^A-Za-z0-9\_]
4,901
49,557,625
For my exercice I must with selenium and Chrome webdriver with python 2.7 click on the link : > > <https://test.com/console/remote.pl> > > > Below structure of the html file : ``` <div class="leftside" > <span class="spacer spacer-20"></span> <a href="https://test.com" title="Retour à l'accueil"><img cl...
2018/03/29
[ "https://Stackoverflow.com/questions/49557625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4200256/" ]
I think you were pretty close. But as it is a `<div>` tag with *class* attribute set as **leftside** you have to be specific. But again the `<a[3]>` tag won't be the immediate child of `driver.find_element_by_xpath("//div[@class='leftside']` node but a decendent, so instead of `/` you have to induce `//` as follows : ...
The issue is that you need to have a tag name also. So you should either use ``` driver.find_element_by_xpath('//*[@id="leftside"]/a[3]').click() ``` When you don't care about which tag it is. Or you should use the actual tag if you care ``` driver.find_element_by_xpath('//div[@id="leftside"]/a[3]').click() ``` I...
4,906
49,544,207
I am using python 2.7. I am looking to calculate compounding returns from daily returns and my current code is pretty slow at calculating returns, so I was looking for areas where I could gain efficiency. What I want to do is pass two dates and a security into a price table and calulate the compounding returns betwee...
2018/03/28
[ "https://Stackoverflow.com/questions/49544207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5293603/" ]
Here is a solution (100x times faster on my computer with some dummy data). ``` import numpy as np price_df = price_df.set_index('asof') def calc_comp_returns_fast(price_df, start_date, end_date, security): rows = price_df[price_df.security_id == security].loc[start_date:end_date] changes = rows.px_last.pct_...
I'm not very familiar with pandas, but I'll give this a shot. Problem with your solution ========================== Your solution currently does a huge amount of unnecessary calculation. This is mostly due to the line: ``` df['return'] = df.px_last.pct_change() ``` This line is actually calcuating the percent ...
4,908
51,454,694
Azure Cognitive Services OCR has a demo on the site <https://azure.microsoft.com/en-us/services/cognitive-services/computer-vision/#text> On the website, I get pretty accurate results. However, when I try to call the same using the code mentioned in their documentation, I get different and poor results. <https://learn...
2018/07/21
[ "https://Stackoverflow.com/questions/51454694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10093162/" ]
There is now an official Microsoft package for that: * <https://pypi.org/project/azure-cognitiveservices-vision-computervision/> With samples: * <https://github.com/Azure-Samples/cognitive-services-python-sdk-samples/blob/master/samples/vision/computer_vision_samples.py> Create issue on Github if you have troubles ...
There are two different APIs for recognizing text. The demo page is using the new way, but has the caveat that it only works for English as of this writing. The example code you should be looking at is [here](https://learn.microsoft.com/en-us/azure/cognitive-services/Computer-vision/quickstarts/python-hand-text). If y...
4,910
45,836,036
Comparing two python lists upto n-2 elements: ```py list1 = [1,2,3,'a','b'] list2 = [1,2,3,'c','d'] list1 == list2 => True ``` Excluding the last 2 elements of the 2 lists they are the same. I am able to do it by comparing each and every element of the 2 lists. But is there any other efficient way to do this?
2017/08/23
[ "https://Stackoverflow.com/questions/45836036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7016928/" ]
return false after the first pair (a,b) where a != b ``` def compare(list1,list2): for a,b in zip(list1[:-2],list2[:-2]): if a != b : return False return True ```
This way: ``` list1 = [1,2,3,'a','b'] list2 = [1,2,3,'c','d'] list1[:-2] == list2[:-2] => True ```
4,911
746,873
I am a C/C++ programmer with more than 10 years of experience. I also know python and perl, but I've never used this languages for a web development. Now for some reasons I want to move into the web development realm and as part of that transition I have to learn css, javascript, (x)html etc. So I need an advice for...
2009/04/14
[ "https://Stackoverflow.com/questions/746873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90593/" ]
For CSS, how about CSS in a Nutshell, by O'Reilly? Nice and thin.
[W3Schools](http://www.w3schools.com/) is a good place to start. However, you might also benefit by poking around the [Mozilla Developer Centre](https://developer.mozilla.org/En) (MDC), which has lots of information about HTML, CSS, and JavaScript. I now almost exclusively use the MDC for looking things up—it has lots...
4,917