qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
7,549,403
How can I tell python to scan the current directory for a file called "filenames.txt" and if that file isn't there, to extract it from a zip file called "files.zip"? I know how to work zipfile, I just don't know how to scan the current directory for that file and use if/then loops with it..
2011/09/25
[ "https://Stackoverflow.com/questions/7549403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715578/" ]
``` import os, zipfile if 'filenames.txt' in os.listdir('.'): print 'file is in current dir' else: zf = zipfile.ZipFile('files.zip') zf.extract('filenames.txt') ```
From the documentation ```none $ pydoc os.path.exists Help on function exists in os.path: os.path.exists = exists(path) Test whether a path exists. Returns False for broken symbolic links ```
7,549,403
How can I tell python to scan the current directory for a file called "filenames.txt" and if that file isn't there, to extract it from a zip file called "files.zip"? I know how to work zipfile, I just don't know how to scan the current directory for that file and use if/then loops with it..
2011/09/25
[ "https://Stackoverflow.com/questions/7549403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715578/" ]
``` import os.path try: os.path.isFile(fname) # play with the file except: # unzip file ```
From the documentation ```none $ pydoc os.path.exists Help on function exists in os.path: os.path.exists = exists(path) Test whether a path exists. Returns False for broken symbolic links ```
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
You can do a waterfall in matplotlib using the [PolyCollection](https://matplotlib.org/api/collections_api.html?highlight=polycollection#matplotlib.collections.PolyCollection) class. See this specific [example](https://matplotlib.org/examples/mplot3d/polys3d_demo.html) to have more details on how to do a waterfall usin...
Have a look at [mplot3d](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots): ``` # copied from # http://matplotlib.sourceforge.net/mpl_examples/mplot3d/wire3d_demo.py from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax =...
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
Have a look at [mplot3d](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots): ``` # copied from # http://matplotlib.sourceforge.net/mpl_examples/mplot3d/wire3d_demo.py from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax =...
The Wikipedia type of [Waterfall chart](http://en.wikipedia.org/wiki/Waterfall_chart) one can obtain also like this: ``` import numpy as np import pandas as pd def waterfall(series): df = pd.DataFrame({'pos':np.maximum(series,0),'neg':np.minimum(series,0)}) blank = series.cumsum().shift(1).fillna(0) df.pl...
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
Have a look at [mplot3d](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#wireframe-plots): ``` # copied from # http://matplotlib.sourceforge.net/mpl_examples/mplot3d/wire3d_demo.py from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax =...
I have generated a function that replicates the matlab waterfall behaviour in matplotlib. That is: 1. It generates the 3D shape as many independent and parallel 2D curves 2. Its color comes from a colormap in the z values I started from two examples in matplotlib documentation: [multicolor lines](https://matplotlib....
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
You can do a waterfall in matplotlib using the [PolyCollection](https://matplotlib.org/api/collections_api.html?highlight=polycollection#matplotlib.collections.PolyCollection) class. See this specific [example](https://matplotlib.org/examples/mplot3d/polys3d_demo.html) to have more details on how to do a waterfall usin...
The Wikipedia type of [Waterfall chart](http://en.wikipedia.org/wiki/Waterfall_chart) one can obtain also like this: ``` import numpy as np import pandas as pd def waterfall(series): df = pd.DataFrame({'pos':np.maximum(series,0),'neg':np.minimum(series,0)}) blank = series.cumsum().shift(1).fillna(0) df.pl...
11,209,646
Is there a python module that will do a waterfall plot like MATLAB does? I googled 'numpy waterfall', 'scipy waterfall', and 'matplotlib waterfall', but did not find anything.
2012/06/26
[ "https://Stackoverflow.com/questions/11209646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908924/" ]
You can do a waterfall in matplotlib using the [PolyCollection](https://matplotlib.org/api/collections_api.html?highlight=polycollection#matplotlib.collections.PolyCollection) class. See this specific [example](https://matplotlib.org/examples/mplot3d/polys3d_demo.html) to have more details on how to do a waterfall usin...
I have generated a function that replicates the matlab waterfall behaviour in matplotlib. That is: 1. It generates the 3D shape as many independent and parallel 2D curves 2. Its color comes from a colormap in the z values I started from two examples in matplotlib documentation: [multicolor lines](https://matplotlib....
61,575,311
I am trying to open up data from a CSV file in my Visual Studio terminal and receive: '''' ``` Traceback (most recent call last): File "/home/jubal/ CrashCourse Python Notes/Chapter 16 CC/Downloading Date/csv format/highs_lows.py", line 7, in <module> with open(filename) as f: FileNotFoundError: [Errno 2] No s...
2020/05/03
[ "https://Stackoverflow.com/questions/61575311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10457351/" ]
So the question says that `N` can be upto 10000, but your code assumes that it is no bigger than 100.
Regarding LTE, you are almost there. Try to replace the ``` for (int j = i + 1; j <= i + (p - 1); j++) tmp += skill[i] - skill[j]; ``` loop with the constant time expression. Hint: when the most skillful player leaves the window, by how much the training time for the rest players gets decreased?
64,397,933
I have a simple webpage that uses that okta web api: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/...
2020/10/17
[ "https://Stackoverflow.com/questions/64397933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14465519/" ]
If you have created a custom mass update script you would have created parameters accessed like : ``` runtime.getCurrentScript().getParameter({name:'custscript....'}); ``` If so and you are then triggering the work flow via: ``` workflow.initiate({ recordType:'customer', ... ``` then you might do something li...
Create parameters in your script then when you are calling the custom action script in the workflow, pass the workflow field values to the script parameters.
31,361,482
I'm writing a porting a basic python script and creating a similarly basic Flask application. I have a file consisting of a bunch of functions that I'd like access to within my Flask application. Here's what I have so far for my views: ``` from flask import render_template from app import app def getRankingList(): ...
2015/07/11
[ "https://Stackoverflow.com/questions/31361482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316501/" ]
Simply have another python script file (for example `helpers.py`) in the same directory as your main flask .py file. Then at the top of your main flask file, you can do `import helpers` which will let you access any function in helpers by adding `helpers.` before it (for example `helpers.exampleFunction()`). Or you can...
Just import your file as usual and use functions from it: ``` # foo.py def bar(): return 'hey everyone!' ``` And in the main file: ``` # main.py from flask import render_template from app import app from foo import bar def getRankingList(): return 'hey everyone!' @app.route("/") @app.route("/index") def ...
33,775,658
So I have this operation in python `x = int(v,base=2)` which takes `v`as a Binary String. What would be the inverse operation to that? For example, given `1101000110111111011001100001` it would return `219936353`, so I want to get this binary string from the `219936353` number. Thanks
2015/11/18
[ "https://Stackoverflow.com/questions/33775658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3770881/" ]
Try out the bin() function. ``` bin(yourNumber)[2:] ``` will give you string containing bits for your number.
``` num = 219936353 print("{:b}".format(num)) --output:-- 1101000110111111011001100001 ``` The other solutions are all wrong: ``` num = 1 string = bin(1) result = int(string, 10) print(result) --output:-- Traceback (most recent call last): File "1.py", line 4, in <module> result = int(string, 10) ValueError:...
33,775,658
So I have this operation in python `x = int(v,base=2)` which takes `v`as a Binary String. What would be the inverse operation to that? For example, given `1101000110111111011001100001` it would return `219936353`, so I want to get this binary string from the `219936353` number. Thanks
2015/11/18
[ "https://Stackoverflow.com/questions/33775658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3770881/" ]
Try out the bin() function. ``` bin(yourNumber)[2:] ``` will give you string containing bits for your number.
``` >>> bin(219936353) '0b1101000110111111011001100001' ```
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] ```
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: ...
In Python 2.x, regular `str` values are binary-safe. You can use the [binascii](http://docs.python.org/library/binascii.html) module's `b2a_hex` and `a2b_hex` functions to convert to and from hexadecimal. You can use ordinary string methods to reverse or otherwise rearrange your bytes. However, doing any kind of arith...
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...
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
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.
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/" ]
Just split and unpack: ``` s = "x=y" key,value = s.split('=', 1) print(key, "==", value) x == y items = ["x=y","i=j","a=b"] for ele in items: key, value = ele.split('=', 1) print(key, "==", value) ```
``` 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.
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/" ]
Make it a 1-tuple - I'd also suggest using `str.partition` instead of `str.split`, eg: ``` >>> s = "x=y" >>> dict((s.partition('=')[::2],)) {'x': 'y'} ``` That way, you'll end up with `''` as the value for where no `=` is present. If there should be an `=` then `str.split` it, and let the exception propagate. If on...
``` 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.
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...
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.
A solution that worked for me was to wrap the dictionary inside a python list: ``` new_item_to_store = list(dict_to_store.items()) ```
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.
An interesting point is that the keys through the dot are not saved for insert\_one And if you save the object, and then update it via find\_one\_and\_update, the keys through the dot will not throw an error Error: ``` product = {'name': 'test_product', 'links': {'test.xyz': 'https://...'}} product_id = products_coll...
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 ...
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/" ]
Sure you can consume part of an iterator `it`, just call `next(it)` to consume a single item. Or if you need to consume several at once you can write a function to consume `n` items from the iterator. In both cases you just need to take care that the iterator has not reached an end (`StopIteration` raised): ```py def ...
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 ...
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...
Sure you can consume part of an iterator `it`, just call `next(it)` to consume a single item. Or if you need to consume several at once you can write a function to consume `n` items from the iterator. In both cases you just need to take care that the iterator has not reached an end (`StopIteration` raised): ```py def ...
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 ```
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.
try this ``` $ sudo apt-get install python-dev ```
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 was installing mysqlclient on OSX Sierra in venv w/ 2.7.7 and did the following: ``` xcode-select --install export CC=gcc export LDSHARED="gcc -Wl,-x -dynamiclib -undefined dynamic_lookup" pip install mysqlclient ``` Seemed to work - the gcc-4.2 -bundle appears to come from setuptools build\_ext somehow.
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/" ]
Same problem. Lion, latest xcode. I downloaded and installed a fresh 2.7.2 python and a single virtualenv. ``` $ which pip /opt/local/py_env/default/bin/pip (default)default $ python Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyrigh...
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 ```
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/" ]
Same problem. Lion, latest xcode. I downloaded and installed a fresh 2.7.2 python and a single virtualenv. ``` $ which pip /opt/local/py_env/default/bin/pip (default)default $ python Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyrigh...
try this ``` $ sudo apt-get install python-dev ```
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/" ]
Same problem. Lion, latest xcode. I downloaded and installed a fresh 2.7.2 python and a single virtualenv. ``` $ which pip /opt/local/py_env/default/bin/pip (default)default $ python Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyrigh...
I was installing mysqlclient on OSX Sierra in venv w/ 2.7.7 and did the following: ``` xcode-select --install export CC=gcc export LDSHARED="gcc -Wl,-x -dynamiclib -undefined dynamic_lookup" pip install mysqlclient ``` Seemed to work - the gcc-4.2 -bundle appears to come from setuptools build\_ext somehow.
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/" ]
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 ```
try this ``` $ sudo apt-get install python-dev ```
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/" ]
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 ```
I was installing mysqlclient on OSX Sierra in venv w/ 2.7.7 and did the following: ``` xcode-select --install export CC=gcc export LDSHARED="gcc -Wl,-x -dynamiclib -undefined dynamic_lookup" pip install mysqlclient ``` Seemed to work - the gcc-4.2 -bundle appears to come from setuptools build\_ext somehow.
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/" ]
I was installing mysqlclient on OSX Sierra in venv w/ 2.7.7 and did the following: ``` xcode-select --install export CC=gcc export LDSHARED="gcc -Wl,-x -dynamiclib -undefined dynamic_lookup" pip install mysqlclient ``` Seemed to work - the gcc-4.2 -bundle appears to come from setuptools build\_ext somehow.
try this ``` $ sudo apt-get install python-dev ```
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.
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...
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...
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...
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...
If you have an option between C or C#(Sharp) then go with C# and use visual studio, you can build the GUI by dragging and dropping components easy. If you want to do something in python look up **wxPython**. Java has a built in GUI builder known as swing. You'll need some tutorials, but unless this program doesn't need...
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/" ]
> > 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...
If you have an option between C or C#(Sharp) then go with C# and use visual studio, you can build the GUI by dragging and dropping components easy. If you want to do something in python look up **wxPython**. Java has a built in GUI builder known as swing. You'll need some tutorials, but unless this program doesn't need...
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...
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/" ]
In Python 3 the pattern is simply: ``` >>> import unittest.mock as um >>> with um.patch('builtins.open', um.mock_open(read_data='test')): ... with open('/dev/null') as f: ... print(f.read()) ... test >>> ``` (Yes, you can even mock /dev/null to return file contents.)
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...
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")) { ...
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...
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...
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...
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/" ]
You might have some luck with the [`h2py.py`](http://svn.python.org/projects/python/trunk/Tools/scripts/h2py.py) script found in the `Tools/scripts` directory of the Python source tarball. While it can't handle complex preprocessor macros, it might be sufficient for your needs. Here is a description of the functionali...
`#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...
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/" ]
`#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...
I had almost exactly this same problem so wrote a Python script to parse the C file. It's intended to be renamed to match your c file (but with .py instead of .h) and imported as a Python module. Code: <https://gist.github.com/camlee/3bf869a5bf39ac5954fdaabbe6a3f437> Example: configuration.h ``` #define VERBOSE 3 #...
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...
You might have some luck with the [`h2py.py`](http://svn.python.org/projects/python/trunk/Tools/scripts/h2py.py) script found in the `Tools/scripts` directory of the Python source tarball. While it can't handle complex preprocessor macros, it might be sufficient for your needs. Here is a description of the functionali...
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...
If you're writing an extension module, use <http://docs.python.org/3/c-api/module.html#PyModule_AddIntMacro>
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...
I had almost exactly this same problem so wrote a Python script to parse the C file. It's intended to be renamed to match your c file (but with .py instead of .h) and imported as a Python module. Code: <https://gist.github.com/camlee/3bf869a5bf39ac5954fdaabbe6a3f437> Example: configuration.h ``` #define VERBOSE 3 #...
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/" ]
You might have some luck with the [`h2py.py`](http://svn.python.org/projects/python/trunk/Tools/scripts/h2py.py) script found in the `Tools/scripts` directory of the Python source tarball. While it can't handle complex preprocessor macros, it might be sufficient for your needs. Here is a description of the functionali...
If you're writing an extension module, use <http://docs.python.org/3/c-api/module.html#PyModule_AddIntMacro>
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/" ]
You might have some luck with the [`h2py.py`](http://svn.python.org/projects/python/trunk/Tools/scripts/h2py.py) script found in the `Tools/scripts` directory of the Python source tarball. While it can't handle complex preprocessor macros, it might be sufficient for your needs. Here is a description of the functionali...
I had almost exactly this same problem so wrote a Python script to parse the C file. It's intended to be renamed to match your c file (but with .py instead of .h) and imported as a Python module. Code: <https://gist.github.com/camlee/3bf869a5bf39ac5954fdaabbe6a3f437> Example: configuration.h ``` #define VERBOSE 3 #...
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/" ]
If you're writing an extension module, use <http://docs.python.org/3/c-api/module.html#PyModule_AddIntMacro>
I had almost exactly this same problem so wrote a Python script to parse the C file. It's intended to be renamed to match your c file (but with .py instead of .h) and imported as a Python module. Code: <https://gist.github.com/camlee/3bf869a5bf39ac5954fdaabbe6a3f437> Example: configuration.h ``` #define VERBOSE 3 #...
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...
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/" ]
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...
just type exit(), that is what I did and it worked
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 ```
just type exit(), that is what I did and it worked
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]])) ```
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/" ]
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]])) ```
You could make use of a outer product of the b vector. The new dimesion you can obtain from the number of True values using a sum. ``` import numpy as np a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) b = np.array([False, True, False, True]) # M = np.outer(b, b) new_dim = b.sum() new_sha...
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 make use of a outer product of the b vector. The new dimesion you can obtain from the number of True values using a sum. ``` import numpy as np a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) b = np.array([False, True, False, True]) # M = np.outer(b, b) new_dim = b.sum() new_sha...
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...
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...
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...
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...
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/>
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.
Because that's **not** valid JSON. You can look at [json.org](http://json.org) for the complete spec, and also always use [JSONlint](http://jsonlint.com/) to check your JSON. JSON is made up of key/value pairs. Keys are always strings and must be double quoted. Numeric values are not quoted. ``` {"method":2, "2":3...
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.
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/" ]
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.
``` pip3 install --user <package_name> ``` No need to write your username in place of --user.
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 ```
``` pip3 install --user <package_name> ``` No need to write your username in place of --user.
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...
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/" ]
If you are using Spyder IDE easiest procedure which i found to install PIP is -: Step 1- Check if Python is installed correctly. The simplest way to test for a Python installation on your Windows server is to open a command prompt (click on the Windows icon and type cmd, then click on the command prompt icon). Once a ...
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...
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...
If you are using Spyder IDE easiest procedure which i found to install PIP is -: Step 1- Check if Python is installed correctly. The simplest way to test for a Python installation on your Windows server is to open a command prompt (click on the Windows icon and type cmd, then click on the command prompt icon). Once a ...
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...
I installed spyder without anaconda on linux, and i was missing a module, all i did was installing pip on the linux terminal `sudo apt install python3-pip` and then `pip install "the library name "` and it worked in spyder without any other modification.
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/" ]
If you are using Spyder IDE easiest procedure which i found to install PIP is -: Step 1- Check if Python is installed correctly. The simplest way to test for a Python installation on your Windows server is to open a command prompt (click on the Windows icon and type cmd, then click on the command prompt icon). Once a ...
I installed spyder without anaconda on linux, and i was missing a module, all i did was installing pip on the linux terminal `sudo apt install python3-pip` and then `pip install "the library name "` and it worked in spyder without any other modification.
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.
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.
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,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 ...
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 ...
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...
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...
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...
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.
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...
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=...
I'd suggest this approach: ``` import csv from collections import namedtuple with open("data.csv", 'r') as f: reader = csv.reader(f, delimiter=',') Row = namedtuple('Row', next(reader)) rows = [Row(*line) for line in reader] ``` If you work with Pandas, the solution becomes even more elegant...
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/" ]
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...
I'd suggest this approach: ``` import csv from collections import namedtuple with open("data.csv", 'r') as f: reader = csv.reader(f, delimiter=',') Row = namedtuple('Row', next(reader)) rows = [Row(*line) for line in reader] ``` If you work with Pandas, the solution becomes even more elegant...
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...
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)") ```
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/" ]
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)") ```
Use raw string: ``` regex= re.compile(r"\\(\d)") ```
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, ...
Use raw string: ``` regex= re.compile(r"\\(\d)") ```
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']) ```
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...
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
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...
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/" ]
you need to use load method. ``` $house = House::find($id); $house->load('trans'); ```
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...
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 ...
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) ```
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...
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...
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...