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
14,610,459
Go's time package claims giving a nanosecond precision. <http://golang.org/src/pkg/time/time.go> I'm wondering how it is implemented and if I can trust it. My doubts come from Python, which clearly documents its difficulties and limitations with time: > > *From <http://docs.python.org/2/library/time.html>* > > > T...
2013/01/30
[ "https://Stackoverflow.com/questions/14610459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/520159/" ]
Well as for the implementation, `time.Now()` falls back to a function implemented in the runtime. You can review the [C time implementation](http://code.google.com/p/go/source/browse/src/pkg/runtime/time.goc) and the implementation for [`time·now` in assembly](http://code.google.com/p/go/source/browse/src/pkg/runtime/...
If you are interested in querying the operating system to get the precision of the values returned by `clock_gettime`, you can make a syscall to [`clock_getres`](https://linux.die.net/man/2/clock_getres) using the syscall package appropriate to your operating system. For example, on Unix platforms you can do: ```golan...
14,610,459
Go's time package claims giving a nanosecond precision. <http://golang.org/src/pkg/time/time.go> I'm wondering how it is implemented and if I can trust it. My doubts come from Python, which clearly documents its difficulties and limitations with time: > > *From <http://docs.python.org/2/library/time.html>* > > > T...
2013/01/30
[ "https://Stackoverflow.com/questions/14610459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/520159/" ]
One of the problems with Python's [time.time](http://docs.python.org/2/library/time.html#time.time) function is that it returns a [float](http://docs.python.org/2/library/functions.html#float). A float is an [IEEE 754 double-precision number](http://en.wikipedia.org/wiki/Double-precision_floating-point_format) which ha...
If you are interested in querying the operating system to get the precision of the values returned by `clock_gettime`, you can make a syscall to [`clock_getres`](https://linux.die.net/man/2/clock_getres) using the syscall package appropriate to your operating system. For example, on Unix platforms you can do: ```golan...
12,172,934
(not to be confused with itertools.chain) I was reading the following: <http://en.wikipedia.org/wiki/Method_chaining> My question is: **what is the best way to implement method chaining in python?** Here is my attempt: ``` class chain(): def __init__(self, my_object): self.o = my_object def __getat...
2012/08/29
[ "https://Stackoverflow.com/questions/12172934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632088/" ]
There is a very handy [`Pipe`](https://github.com/JulienPalard/Pipe) library which may be the answer to your question. For example:: ``` seq = fib() | take_while(lambda x: x < 1000000) \ | where(lambda x: x % 2) \ | select(lambda x: x * x) \ | sum() ```
There isn't going to be any general way of allowing any method of any object to be chained, since you can't know what sort of value that method returns and why without knowing how that particular method works. Methods might return `None` for any reason; it doesn't always mean the method has modified the object. Likewis...
12,172,934
(not to be confused with itertools.chain) I was reading the following: <http://en.wikipedia.org/wiki/Method_chaining> My question is: **what is the best way to implement method chaining in python?** Here is my attempt: ``` class chain(): def __init__(self, my_object): self.o = my_object def __getat...
2012/08/29
[ "https://Stackoverflow.com/questions/12172934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632088/" ]
It's possible if you use only [pure functions](http://en.wikipedia.org/wiki/Pure_function) so that methods don't modify `self.data` directly, but instead return the modified version. You also have to return `Chainable` instances. Here's an example using [collection pipelining](http://martinfowler.com/articles/collecti...
There isn't going to be any general way of allowing any method of any object to be chained, since you can't know what sort of value that method returns and why without knowing how that particular method works. Methods might return `None` for any reason; it doesn't always mean the method has modified the object. Likewis...
12,172,934
(not to be confused with itertools.chain) I was reading the following: <http://en.wikipedia.org/wiki/Method_chaining> My question is: **what is the best way to implement method chaining in python?** Here is my attempt: ``` class chain(): def __init__(self, my_object): self.o = my_object def __getat...
2012/08/29
[ "https://Stackoverflow.com/questions/12172934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632088/" ]
**Caveat**: This only works on `class` methods() that do not intend to return any data. I was looking for something similar for chaining `Class` functions and found no good answer, so here is what I did and thought was a very simple way of chaining: Simply return the `self` object. So here is my setup: ``` class Car...
There isn't going to be any general way of allowing any method of any object to be chained, since you can't know what sort of value that method returns and why without knowing how that particular method works. Methods might return `None` for any reason; it doesn't always mean the method has modified the object. Likewis...
12,172,934
(not to be confused with itertools.chain) I was reading the following: <http://en.wikipedia.org/wiki/Method_chaining> My question is: **what is the best way to implement method chaining in python?** Here is my attempt: ``` class chain(): def __init__(self, my_object): self.o = my_object def __getat...
2012/08/29
[ "https://Stackoverflow.com/questions/12172934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632088/" ]
There is a very handy [`Pipe`](https://github.com/JulienPalard/Pipe) library which may be the answer to your question. For example:: ``` seq = fib() | take_while(lambda x: x < 1000000) \ | where(lambda x: x % 2) \ | select(lambda x: x * x) \ | sum() ```
It's possible if you use only [pure functions](http://en.wikipedia.org/wiki/Pure_function) so that methods don't modify `self.data` directly, but instead return the modified version. You also have to return `Chainable` instances. Here's an example using [collection pipelining](http://martinfowler.com/articles/collecti...
12,172,934
(not to be confused with itertools.chain) I was reading the following: <http://en.wikipedia.org/wiki/Method_chaining> My question is: **what is the best way to implement method chaining in python?** Here is my attempt: ``` class chain(): def __init__(self, my_object): self.o = my_object def __getat...
2012/08/29
[ "https://Stackoverflow.com/questions/12172934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632088/" ]
There is a very handy [`Pipe`](https://github.com/JulienPalard/Pipe) library which may be the answer to your question. For example:: ``` seq = fib() | take_while(lambda x: x < 1000000) \ | where(lambda x: x % 2) \ | select(lambda x: x * x) \ | sum() ```
What about ``` def apply(data, *fns): return data.__class__(map(fns[-1], apply(data, *fns[:-1]))) if fns else data >>> print( ... apply( ... [1,2,3], ... str, ... lambda x: {'1': 'one', '2': 'two', '3': 'three'}[x], ... str.upper)) ['ONE', 'TWO', 'THREE'] >>> ``` ? .. even keeps the type ...
12,172,934
(not to be confused with itertools.chain) I was reading the following: <http://en.wikipedia.org/wiki/Method_chaining> My question is: **what is the best way to implement method chaining in python?** Here is my attempt: ``` class chain(): def __init__(self, my_object): self.o = my_object def __getat...
2012/08/29
[ "https://Stackoverflow.com/questions/12172934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632088/" ]
**Caveat**: This only works on `class` methods() that do not intend to return any data. I was looking for something similar for chaining `Class` functions and found no good answer, so here is what I did and thought was a very simple way of chaining: Simply return the `self` object. So here is my setup: ``` class Car...
It's possible if you use only [pure functions](http://en.wikipedia.org/wiki/Pure_function) so that methods don't modify `self.data` directly, but instead return the modified version. You also have to return `Chainable` instances. Here's an example using [collection pipelining](http://martinfowler.com/articles/collecti...
12,172,934
(not to be confused with itertools.chain) I was reading the following: <http://en.wikipedia.org/wiki/Method_chaining> My question is: **what is the best way to implement method chaining in python?** Here is my attempt: ``` class chain(): def __init__(self, my_object): self.o = my_object def __getat...
2012/08/29
[ "https://Stackoverflow.com/questions/12172934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632088/" ]
It's possible if you use only [pure functions](http://en.wikipedia.org/wiki/Pure_function) so that methods don't modify `self.data` directly, but instead return the modified version. You also have to return `Chainable` instances. Here's an example using [collection pipelining](http://martinfowler.com/articles/collecti...
What about ``` def apply(data, *fns): return data.__class__(map(fns[-1], apply(data, *fns[:-1]))) if fns else data >>> print( ... apply( ... [1,2,3], ... str, ... lambda x: {'1': 'one', '2': 'two', '3': 'three'}[x], ... str.upper)) ['ONE', 'TWO', 'THREE'] >>> ``` ? .. even keeps the type ...
12,172,934
(not to be confused with itertools.chain) I was reading the following: <http://en.wikipedia.org/wiki/Method_chaining> My question is: **what is the best way to implement method chaining in python?** Here is my attempt: ``` class chain(): def __init__(self, my_object): self.o = my_object def __getat...
2012/08/29
[ "https://Stackoverflow.com/questions/12172934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632088/" ]
**Caveat**: This only works on `class` methods() that do not intend to return any data. I was looking for something similar for chaining `Class` functions and found no good answer, so here is what I did and thought was a very simple way of chaining: Simply return the `self` object. So here is my setup: ``` class Car...
What about ``` def apply(data, *fns): return data.__class__(map(fns[-1], apply(data, *fns[:-1]))) if fns else data >>> print( ... apply( ... [1,2,3], ... str, ... lambda x: {'1': 'one', '2': 'two', '3': 'three'}[x], ... str.upper)) ['ONE', 'TWO', 'THREE'] >>> ``` ? .. even keeps the type ...
61,748,604
I have two pandas series with DateTimeIndex. I'd like to join these two series such that the resulting DataFrame uses the index of the first series and "matches" the values from the second series accordingly (using a linear interpolation in the second series). First Series: ``` 2020-03-01 1 2020-03-03 2 2020-...
2020/05/12
[ "https://Stackoverflow.com/questions/61748604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5554921/" ]
Use [`concat`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html) with inner join: ``` df = pd.concat([s1, s2], axis=1, keys=('s1','s2'), join='inner') print (df) s1 s2 2020-03-01 1 20 2020-03-05 3 25 2020-03-07 4 36 ``` Solution with interpolate of `s2` Series and th...
### Construct combined dataframe ``` # there are many ways to construct a dataframe from series, this uses the constructor: df = pd.DataFrame({'s1': s1, 's2': s2}) s1 s2 2020-03-01 1.0 20.0 2020-03-02 NaN 22.0 2020-03-03 2.0 NaN 2020-03-05 3.0 25.0 2020-03-06 NaN 35.0 2020-03-07 4.0 36.0 2...
73,386,405
``` infile = open('results1', 'r') lines = infile.readlines() import re for line in lines: if re.match("track: 1,", line): print(line) ``` question solved by using python regex below
2022/08/17
[ "https://Stackoverflow.com/questions/73386405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19783767/" ]
I suggest you use Regular Expressions library (re) which gives you all you need to extract the data from text files. I ran a simple code to solve your current problem: ``` import re # Customize path as the file's address on your system text_file = open('path/sample.txt','r') # Read the file line by line using .readlin...
Given that all your target lines follow the exact same pattern, a much simpler way to extract the value between parentheses would be: ``` from ast import literal_eval as make_tuple infile = open('results1', 'r') lines = infile.readlines() import re for line in lines: if re.match("Id of the track: 1,", line): ...
5,738,339
I have a specific use. I am preparing for GRE. Everytime a new word comes, I look it up at www.mnemonicdictionary.com, for its meanings and mnemonics. I want to write a script in python preferably ( or if someone could provide me a pointer to an already existing thing as I dont know python much but I am learning now) w...
2011/04/21
[ "https://Stackoverflow.com/questions/5738339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169210/" ]
If you have Bash (version 4+) and `wget`, an example ``` #!/bin/bash template="http://www.mnemonicdictionary.com/include/ajaxSearch.php?word=%s&event=search" while read -r word do url=$(printf "$template" "$word") data=$(wget -O- -q "$url") data=${data#*&nbsp;} echo "$word: ${data%%<*}" done < file ``...
Use [curl](http://curl.haxx.se/) and sed from a Bash shell (either Linux, Mac, or Windows with Cygwin). If I get a second I will write a quick script ... gotta give the baby a bath now though.
49,766,071
I'm new to python, and I know there must be a better way to do this, especially with numpy, and without appending to arrays. Is there a more concise way to do something like this in python? ```py def create_uniform_grid(low, high, bins=(10, 10)): """Define a uniformly-spaced grid that can be used to discretize a s...
2018/04/11
[ "https://Stackoverflow.com/questions/49766071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1097028/" ]
`np.ogrid` is similar to your function. Differences: 1) It will keep the endpoints; 2) It will create a column and a row, so its output is 'broadcast ready': ``` >>> np.ogrid[-1:1:11j, -5:5:11j] [array([[-1. ], [-0.8], [-0.6], [-0.4], [-0.2], [ 0. ], [ 0.2], [ 0.4],...
Maybe the `numpy.meshgrid` is what you want. Here is an example to create the grid and do math on it: ``` #!/usr/bin/python3 # 2018.04.11 11:40:17 CST import numpy as np import matplotlib.pyplot as plt x = np.arange(-5, 5, 0.1) y = np.arange(-5, 5, 0.1) xx, yy = np.meshgrid(x, y, sparse=True) z = np.sin(xx**2 + yy*...
25,067,927
So I have a line here that is meant to dump frames from a movie via python and ffmpeg. ``` subprocess.check_output([ffmpeg, "-i", self.moviefile, "-ss 00:01:00.000 -t 00:00:05 -vf scale=" + str(resolution) + ":-1 -r", str(framerate), "-qscale:v 6", self.processpath + "/" + self.filetitles + "-output%03d.jpg"]) ``` A...
2014/07/31
[ "https://Stackoverflow.com/questions/25067927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The subprocess module does almost never allow any whitespace characters in its parameters, unless you run it in shell mode. Try this: ``` subprocess.check_output(["ffmpeg", "-i", self.moviefile, "-ss", "00:01:00.000", "-t", "00:00:05", "-vf", "scale=" + str(resolution) + ":-1", "-r", str(framerate), "-qscale:v", "6", ...
The argument array you pass to `check_call` is not correctly formatted. Every argument to `ffmpeg` needs to be a single element in the argument list, for example ``` ... "-ss 00:01:00.000 -t 00:00:05 -vf ... ``` should be ``` ... "-ss", "00:01:00.000", "-t", "00:00:05", "-vf", ... ``` The complete resulting args ...
4,002,660
In my MySQL database I have dates going back to the mid 1700s which I need to convert somehow to ints in a format similar to Unix time. The value of the int isn't important, so long as I can take a date from either my database or from user input and generate the same int. I need to use MySQL to generate the int on the ...
2010/10/23
[ "https://Stackoverflow.com/questions/4002660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64911/" ]
This is my idea, create a filter in your web application , when u receive a request like `/area.jsp?id=1` , in `doFilter` method , forward the request to `http://example.com/newyork`. In `web.xml`: ``` <filter> <filter-name>RedirectFilter</filter-name> <filter-class> com.filters.RedirectFilter </...
In your database where you store these area IDs, add a column called "slug" and populate it with the names you want to use. The "slug" for id 1 would be "newyork". Now when a request comes in for one of these URLs, look up the row by "slug" instead of by id.
4,002,660
In my MySQL database I have dates going back to the mid 1700s which I need to convert somehow to ints in a format similar to Unix time. The value of the int isn't important, so long as I can take a date from either my database or from user input and generate the same int. I need to use MySQL to generate the int on the ...
2010/10/23
[ "https://Stackoverflow.com/questions/4002660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64911/" ]
Use nginx's rewrite module to map that one URL to the area.jsp?id=1 URL <http://wiki.nginx.org/NginxHttpRewriteModule>
In your database where you store these area IDs, add a column called "slug" and populate it with the names you want to use. The "slug" for id 1 would be "newyork". Now when a request comes in for one of these URLs, look up the row by "slug" instead of by id.
4,002,660
In my MySQL database I have dates going back to the mid 1700s which I need to convert somehow to ints in a format similar to Unix time. The value of the int isn't important, so long as I can take a date from either my database or from user input and generate the same int. I need to use MySQL to generate the int on the ...
2010/10/23
[ "https://Stackoverflow.com/questions/4002660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64911/" ]
Use nginx's rewrite module to map that one URL to the area.jsp?id=1 URL <http://wiki.nginx.org/NginxHttpRewriteModule>
This is my idea, create a filter in your web application , when u receive a request like `/area.jsp?id=1` , in `doFilter` method , forward the request to `http://example.com/newyork`. In `web.xml`: ``` <filter> <filter-name>RedirectFilter</filter-name> <filter-class> com.filters.RedirectFilter </...
64,415,588
Given 2 data frames like the link example, I need to add to df1 the "index income" from df2. I need to search by the df1 combined key in df2 and if there is a match return the value into a new column in df1. There is not an equal number of instances in df1 and df2 and there are about 700 rows in df1 1000 rows in df2. ...
2020/10/18
[ "https://Stackoverflow.com/questions/64415588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14473305/" ]
This should solve your issue: ``` df1.merge(df2, how='left', on='combind_key') ``` This (`left` join) will give you all the records of `df1` and matching records from `df2`.
<https://www.geeksforgeeks.org/how-to-do-a-vlookup-in-python-using-pandas/> Here is an answer using joins. I modified my df2 to only include useful columns then used pandas left join. ``` Left_join = pd.merge(df, zip_df, on ='State County', how ='le...
66,996,373
I'm trying to install and use Pillow with Python 3.9.2 (managed with pyenv). I'm using Poetry to manage my virtual environments and dependencies, so I ran `poetry add pillow`, which successfully added `Pillow = "^8.2.0"` to my pyproject.toml. Per the Pillow docs, I added `from PIL import Image` in my script, but when I...
2021/04/08
[ "https://Stackoverflow.com/questions/66996373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4430379/" ]
I couldn't find a way to solve this either (using poetry 1.1.13). Ultimately, I resorted to a workaround of `poetry add pillow && pip install pillow` so I could move on with my life. :P `poetry add pillow` gets the dependency in to the TOML, so consumers of the package *should* be OK.
capitalizing "Pillow" solved it for me: `poetry add Pillow`
30,558,917
Using the pandas library for python I am reading a csv, then grouping the results with a sum. ``` grouped = df[['Organization Name','Views']].groupby('Organization Name').sum().sort(columns='Views',ascending=False).head(10) #Bar Chart Section print grouped.to_string() ``` Unfortunately I get the following result for...
2015/05/31
[ "https://Stackoverflow.com/questions/30558917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1760634/" ]
Because you grouped on 'Organization Name', this is being used as the name for your index, you can set this to `None` using: ``` grouped.index.name = None ``` Will then remove the line, this is just a display issue, your data is not in some funny shape Alternatively if you don't want 'Organization Name' to become t...
`grouped.reset_index()` should fix this. This happened because you have grouped the data and aggregated on a column.
67,511,611
I am new to Python socket server programming, I am following this [example](https://docs.python.org/3/library/socketserver.html#examples) to setup a server using the socketserver framework. Based on the comment, pressing Ctrl-C will stop the server but when I try to run it again, I get `OSError: [Errno 98] Address alr...
2021/05/12
[ "https://Stackoverflow.com/questions/67511611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10733376/" ]
Just split the string and add map over the `stringArray` and add `<b>` just before the `beginOffset` and `</b>` after the `endOffset`. ```js var indices = [{ beginOffset: 2, endOffset: 8, }, { beginOffset: 42, endOffset: 48, }, { beginOffset: 58, endOffset: 63, }, ]; var teststring =...
Sort the indices from highest to lowest. Then when you insert `<b>` and `</b>` it won't affect the indexes in subsequent iterations. ```js var indices = [{ beginOffset: 2, endOffset: 8 }, { beginOffset: 42, endOffset: 48 }, { beginOffset: 58, endOffset: 63 } ]; var teststring = "a lo...
67,511,611
I am new to Python socket server programming, I am following this [example](https://docs.python.org/3/library/socketserver.html#examples) to setup a server using the socketserver framework. Based on the comment, pressing Ctrl-C will stop the server but when I try to run it again, I get `OSError: [Errno 98] Address alr...
2021/05/12
[ "https://Stackoverflow.com/questions/67511611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10733376/" ]
Just split the string and add map over the `stringArray` and add `<b>` just before the `beginOffset` and `</b>` after the `endOffset`. ```js var indices = [{ beginOffset: 2, endOffset: 8, }, { beginOffset: 42, endOffset: 48, }, { beginOffset: 58, endOffset: 63, }, ]; var teststring =...
I don't know if this is good solution or not but what I shortly resolved you can use ``` let str = "a lovely day at the office to meet such a lovely woman. I loved her so much" let o = [ { beginOffset : 2, endOffset : 8 }, { beginOffset : 42, endOffset : 48 }, { b...
45,477,478
I have a group of images and some separate heatmap data which (imperfectly) explains where subject of the image is. The heatmap data is in a numpy array with shape (224,224,3). I would like to generate bounding box data from this heatmap data. The heatmaps are not always perfect, So I guess I'm wondering if anyone can...
2017/08/03
[ "https://Stackoverflow.com/questions/45477478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3539683/" ]
this is not a good piece of code. I would not know where to start on the bad practices... This function defines a function that it is not reachable from any other scope, and not reusable, just to return its call with the data argument. The outer return could be simple as ``` return self.change('groupTo', groupExp, d...
if you call `getData()` function without passing any parameter then value of the data variable in function is undefined. So at this Line ternary operator is used. ``` data = (data === undefined) ? this.defaultData() : data; ``` So it will check whether `data === undefined` condition which is true. therefore it will ...
45,477,478
I have a group of images and some separate heatmap data which (imperfectly) explains where subject of the image is. The heatmap data is in a numpy array with shape (224,224,3). I would like to generate bounding box data from this heatmap data. The heatmaps are not always perfect, So I guess I'm wondering if anyone can...
2017/08/03
[ "https://Stackoverflow.com/questions/45477478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3539683/" ]
In this pattern: ``` (function (local_arg) { doSomething(local_arg); })(arg); ``` ...the function is immediately executed, and the parameter `local_arg` will take the value of the argument that was passed, i.e. `arg`. So the above is doing the same as just: ``` doSomething(arg); ``` In some cases where `arg` i...
if you call `getData()` function without passing any parameter then value of the data variable in function is undefined. So at this Line ternary operator is used. ``` data = (data === undefined) ? this.defaultData() : data; ``` So it will check whether `data === undefined` condition which is true. therefore it will ...
34,490,117
C code: ``` #include "Python.h" #include <windows.h> __declspec(dllexport) PyObject* getTheString() { auto p = Py_BuildValue("s","hello"); char * s = PyString_AsString(p); MessageBoxA(NULL,s,"s",0); return p; } ``` Python code: ``` import ctypes import sys sys.path.append('./') dll = ctypes.CDLL('py...
2015/12/28
[ "https://Stackoverflow.com/questions/34490117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680359/" ]
> > By default functions are assumed to return the C `int` type. Other > return types can be specified by setting the `restype` attribute of the > function object. > [(ref)](https://docs.python.org/2/library/ctypes.html#return-types) > > > Define the type returned by your function like that: ``` >>> from ctype...
`int` is the default return type, to specify another type you need to set the function object's `restype` attribute. See [Return types](https://docs.python.org/2/library/ctypes.html#return-types) in the `ctype` docs for details.
61,959,745
I want to merge all files with the extension `.asc` in my current working directory to be merged into a file called `outfile.asc`. My problem is, I don't know how to exclude a specific file (`"BigTree.asc"`) and how to overwrite an existing `"outfile.asc"` if there is one in the directory. ``` if len(sys.argv) < 2: ...
2020/05/22
[ "https://Stackoverflow.com/questions/61959745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13461656/" ]
As suggested in a comment, here's my simplified (simplistic?) solution to make it such that specific flask end points in google app engine are only accessibly by application code or app engine service accounts. The answer is based on the documentation regarding [validating cron requests](https://cloud.google.com/appeng...
It still works in Python 3.x, I use the original approach in my own Flask AppEngine app running Python 3.8 Here is a simplified version of my `app.yaml` with everything you need: ``` runtime: python38 app_engine_apis: true handlers: - url: /admin/.* secure: always script: auto login: admin - url: /.* secure...
49,625,350
I have a zip file structure like - B.zip/org/note.txt I want to directly list the files inside org folder without going to other folders in B.zip I have written the following code but it is listing all the files and directories available inside the B.zip file ``` f = zipfile.ZipFile('D:\python\B.jar') for name in f....
2018/04/03
[ "https://Stackoverflow.com/questions/49625350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can filter the yields by startwith function.(Using Python 3) ``` import os import zipfile with zipfile.ZipFile('D:\python\B.jar') as z: for filename in z.namelist(): if filename.startswith("org"): print(filename) ```
How to list all files that are inside ZIP files of a certain folder ------------------------------------------------------------------- > > Everytime I came into this post making a similar question... But different at the same time. Cause of this, I think other users can have the same doubt. If you got to this post t...
53,605,066
I know there are lots of Q&As to extract datetime from string, such as [dateutil.parser](https://stackoverflow.com/questions/3276180/extracting-date-from-a-string-in-python), to extract datetime from a string ``` import dateutil.parser as dparser dparser.parse('something sep 28 2017 something',fuzzy=True).date() outp...
2018/12/04
[ "https://Stackoverflow.com/questions/53605066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1165964/" ]
Extend to the discussion with @Paul and following the solution from @alecxe, I have proposed the following solution, which works on a number of testing cases, I've made the problem slight challenger: **Step 1: get excluded tokens** ``` import dateutil.parser as dparser ostr = 'something sep 28 2017 something abcd' _...
Interesting problem! There is no direct way to get the parsed out date string out of the bigger string with `dateutil`. The problem is that `dateutil` parser does not even have this string available as an intermediate result as it really builds parts of the future `datetime` object on the fly and character by character...
16,874,010
I am trying to write out a line to a new file based on input from a csv file, with elements from different rows and different columns for example test.csv: ``` name1, value1, integer1, integer1a name2, value2, integer2, integer2a name3, value3, integer3, integer3a ``` desired output: ``` command integer1:integer1a...
2013/06/01
[ "https://Stackoverflow.com/questions/16874010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443424/" ]
For an array you can use the std::vector class. ``` std::vector<account *>MyAccounts; MyAccounts.push_back(new account()); ``` Then you can use it like an array accessing it normally. ``` MyAccounts[i]->accountFunction(); ``` **update** I don't know enough about your code, so I give just some general examples he...
You can do something like below ``` class Bank { public: int AddAccount(Account act){ m_vecAccts.push_back(act);} .... private: ... std:vector<account> m_vecAccts; } ``` Update: This is just a Bank class with vector of accounts as private member variable. AddAccount is public function which can add account to vec...
16,874,010
I am trying to write out a line to a new file based on input from a csv file, with elements from different rows and different columns for example test.csv: ``` name1, value1, integer1, integer1a name2, value2, integer2, integer2a name3, value3, integer3, integer3a ``` desired output: ``` command integer1:integer1a...
2013/06/01
[ "https://Stackoverflow.com/questions/16874010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443424/" ]
First of all, ``` //error handling else{ cout << "Error! Invalid operator." << endl; accounting(); } ``` This look ugly, you are recursively calling accounting function after every bad input. Imagine a situation where user type 1 000 000x bad inputs... you will then try to free the memory 1 000 000x...
You can do something like below ``` class Bank { public: int AddAccount(Account act){ m_vecAccts.push_back(act);} .... private: ... std:vector<account> m_vecAccts; } ``` Update: This is just a Bank class with vector of accounts as private member variable. AddAccount is public function which can add account to vec...
45,823,884
So I'm working a quiz on Python as a project for an Intro to Programming course. My quiz works as intended except in the case that the quiz variable is not being affected by the new values of the blank array. On the run\_quiz function I want to make the quiz variable update itself by changing the blanks to the correct...
2017/08/22
[ "https://Stackoverflow.com/questions/45823884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8501849/" ]
The problem is that your variable, `quiz`, is just a fixed string, and although it looks like it has something to do with `blanks`, it actually doesn't. What you want is 'string interpolation'. Python allows this with the `.format` method of `str` objects. This is really the crux of your question, and using string inte...
Only now have I read your question properly. You first make your strings quiz1, quiz2 an quiz3. You only do that once. After that you change your blanks array. But you don't reconstruct your strings. So they still have the old values. Note that a copy of elements of the blanks array is made into e.g. quiz1. That copy...
72,011,497
I am reading data remote .dat files for EDI data processing. Original Data is some string bytes: ``` b'MDA1MDtWMjAxOS44LjAuMDtWMjAxOS44LjAuMDsyMDIwMD.........' ``` Used decode as below... ``` byte_data = base64.b64decode(byte_data) ``` Gave me this below byte data. Is there a better way to process below bytes da...
2022/04/26
[ "https://Stackoverflow.com/questions/72011497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6837224/" ]
It didn't work with 'utf-8' because it's not 'utf-8', it's probably 'ISO-8859-1' (latin-1) ```py text = byte_data.decode('ISO-8859-1') ``` because `\xf6` is `ö` in 'ISO-8859-1'
Is it definitely utf-8 encoded? This might help guide to what decoder to use: ``` import chardet print(cardet.detect(byte_data)) ```
45,209,068
I'm new to python, and now I need to use it to work with some data in a txt file. Here is a sample data, where after each `'&'`, is a new index: ``` uid=aaa&sid=bbb&bid=ccc&cid=ddd&pid=eee&ver=fff... uid=aaa2&sid=bbb2&bid=ccc2&cid=ddd2&pid=eee2&ver=fff2... ... ``` The end result is to have a DataFrame (with pandas)...
2017/07/20
[ "https://Stackoverflow.com/questions/45209068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8336506/" ]
This is a URL querystring. You should use the `urllib` module in the standard library to parse it. ``` from urllib.parse import parse_qs # python3 from urlparse import parse_qs # python2 parse_qs('uid=aaa2&sid=bbb2&bid=ccc2&cid=ddd2&pid=eee2&ver=fff2') ``` Output: ``` {'bid': ['ccc2'], 'cid': ['ddd2'], 'pid': ...
You can use `regex` to create a `list` of all the columns and values and then use it to create your `dataframe`, for example: ``` import re st = 'uid=aaa&sid=bbb&bid=ccc&cid=ddd&pid=eee&ver=fffuid=aaa2&sid=bbb2&bid=ccc2&cid=ddd2&pid=eee2&ver=fff2' myData = re.findall(r'(\wid)=(\w+)', st) prit myData ``` output: ```...
45,209,068
I'm new to python, and now I need to use it to work with some data in a txt file. Here is a sample data, where after each `'&'`, is a new index: ``` uid=aaa&sid=bbb&bid=ccc&cid=ddd&pid=eee&ver=fff... uid=aaa2&sid=bbb2&bid=ccc2&cid=ddd2&pid=eee2&ver=fff2... ... ``` The end result is to have a DataFrame (with pandas)...
2017/07/20
[ "https://Stackoverflow.com/questions/45209068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8336506/" ]
This is a URL querystring. You should use the `urllib` module in the standard library to parse it. ``` from urllib.parse import parse_qs # python3 from urlparse import parse_qs # python2 parse_qs('uid=aaa2&sid=bbb2&bid=ccc2&cid=ddd2&pid=eee2&ver=fff2') ``` Output: ``` {'bid': ['ccc2'], 'cid': ['ddd2'], 'pid': ...
``` txt = open('test.txt').read() pd.DataFrame( [dict([kv.split('=') for kv in l.split('&')]) for l in txt.split('\n')] ) bid cid pid sid uid ver 0 ccc ddd eee bbb aaa fff 1 ccc2 ddd2 eee2 bbb2 aaa2 fff2 ```
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
I installed PIP with Conda `conda install pip` instead of `apt-get install python-pip python-dev`. Then installed tensorflow use [Pip Installation](https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html#test-the-tensorflow-installation): ``` # Ubuntu/Linux 64-bit, CPU only, Python 2.7 $ export TF_BINARY_...
``` pip install tensorflow ``` This worked for me in my conda virtual environment. I was trying to use `conda install tensorflow` in a conda virtual environment where jupyter notebooks was already installed, resulting in many conflicts and failure. But pip install worked fine.
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
i used these following which in virtualenv. ``` pip3 install --ignore-installed ipython pip3 install --ignore-installed jupyter ``` This re-installs both ipython and jupyter notebook in my tensorflow virtual environment. You can verify it after installation by `which ipython` and `which jupyter`. The `bin` will be ...
I have another solution that you don't need to `source activate tensorflow` before using `jupyter notebook` every time. **Partion 1** Firstly, you should ensure you have installed jupyter in your virtualenv. If you have installed, you can skip this section (Use `which jupyter` to check). If you not, you could run `so...
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
Here is what I did to enable tensorflow in Anaconda -> Jupyter. 1. Install Tensorflow using the instructions provided at 2. Go to /Users/username/anaconda/env and ensure Tensorflow is installed 3. Open the Anaconda navigator and go to "Environments" (located in the left navigation) 4. Select "All" in teh first drop d...
The accepted answer (by Zhongyu Kuang) has just helped me out. Here I've create an `environment.yml` file that enables me to make this conda / tensorflow installation process repeatable. Step 1 - create a Conda environment.yml File ============================================ `environment.yml` looks like this: ``` n...
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
**Update** [TensorFlow website](https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#virtualenv-installation) supports five installations. To my understanding, using [Pip installation](https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation) directly would be fine to impor...
Jupyter Lab: ModuleNotFound tensorflow ====================================== For a future version of me or a colleague that runs into this issue: ``` conda install -c conda-forge jupyter jupyterlab keras tensorflow ``` Turns out `jupyterlab` is a plugin for `jupyter`. So even if you are in an environment that ha...
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
I found the solution from someone else's post. It is simple and works well! <http://help.pythonanywhere.com/pages/IPythonNotebookVirtualenvs> Just install the following in the Command Prompt and change kernel to Python 3 in Jupyter Notebook. It will import tensorflow successfully. > > pip install tornado==4.5.3 > ...
Open an Anaconda Prompt screen: `(base) C:\Users\YOU>conda create -n tf tensorflow` After the environment is created type: `conda activate tf` Prompt moves to (tf) environment, that is: `(tf) C:\Users\YOU>` then install Jupyter Notebook in this (tf) environment: `conda install -c conda-forge jupyterlab - jupyter no...
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
**Update** [TensorFlow website](https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#virtualenv-installation) supports five installations. To my understanding, using [Pip installation](https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation) directly would be fine to impor...
i used these following which in virtualenv. ``` pip3 install --ignore-installed ipython pip3 install --ignore-installed jupyter ``` This re-installs both ipython and jupyter notebook in my tensorflow virtual environment. You can verify it after installation by `which ipython` and `which jupyter`. The `bin` will be ...
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
Here is what I did to enable tensorflow in Anaconda -> Jupyter. 1. Install Tensorflow using the instructions provided at 2. Go to /Users/username/anaconda/env and ensure Tensorflow is installed 3. Open the Anaconda navigator and go to "Environments" (located in the left navigation) 4. Select "All" in teh first drop d...
I think your question is very similar with the question post here. [Windows 7 jupyter notebook executing tensorflow](https://stackoverflow.com/questions/36046448/windows-7-jupyter-notebook-executing-tensorflow/37280604#37280604). As Yaroslav mentioned, you can try `conda install -c http://conda.anaconda.org/jjhelmus ...
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
I have another solution that you don't need to `source activate tensorflow` before using `jupyter notebook` every time. **Partion 1** Firstly, you should ensure you have installed jupyter in your virtualenv. If you have installed, you can skip this section (Use `which jupyter` to check). If you not, you could run `so...
I think your question is very similar with the question post here. [Windows 7 jupyter notebook executing tensorflow](https://stackoverflow.com/questions/36046448/windows-7-jupyter-notebook-executing-tensorflow/37280604#37280604). As Yaroslav mentioned, you can try `conda install -c http://conda.anaconda.org/jjhelmus ...
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
I have another solution that you don't need to `source activate tensorflow` before using `jupyter notebook` every time. **Partion 1** Firstly, you should ensure you have installed jupyter in your virtualenv. If you have installed, you can skip this section (Use `which jupyter` to check). If you not, you could run `so...
I installed PIP with Conda `conda install pip` instead of `apt-get install python-pip python-dev`. Then installed tensorflow use [Pip Installation](https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html#test-the-tensorflow-installation): ``` # Ubuntu/Linux 64-bit, CPU only, Python 2.7 $ export TF_BINARY_...
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
I have another solution that you don't need to `source activate tensorflow` before using `jupyter notebook` every time. **Partion 1** Firstly, you should ensure you have installed jupyter in your virtualenv. If you have installed, you can skip this section (Use `which jupyter` to check). If you not, you could run `so...
I wonder if it is not enough to simply launch ipython from tensorflow environnement. That is 1) first activate tensorflow virtualenv with: ``` source ~/tensorflow/bin/activate ``` 2) launch ipython under tensorflow environnement ``` (tensorflow)$ ipython notebook --ip=xxx.xxx.xxx.xxx ```
10,559,144
I am trying to use `suptitle` to print a title, and I want to occationally replace this title. Currently I am using: ``` self.ui.canvas1.figure.suptitle(title) ``` where figure is a matplotlib figure (canvas1 is an mplCanvas, but that is not relevant) and title is a python string. Currently, this works, except for...
2012/05/11
[ "https://Stackoverflow.com/questions/10559144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402632/" ]
`figure.suptitle` returns a `matplotlib.text.Text` instance. You can save it and set the new title: ``` txt = fig.suptitle('A test title') txt.set_text('A better title') plt.draw() ```
Resurrecting this old thread because I recently ran into this. There is a references to the Text object returned by the original setting of suptitle in figure.texts. You can use this to change the original until this is fixed in matplotlib.
10,559,144
I am trying to use `suptitle` to print a title, and I want to occationally replace this title. Currently I am using: ``` self.ui.canvas1.figure.suptitle(title) ``` where figure is a matplotlib figure (canvas1 is an mplCanvas, but that is not relevant) and title is a python string. Currently, this works, except for...
2012/05/11
[ "https://Stackoverflow.com/questions/10559144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402632/" ]
`figure.suptitle` returns a `matplotlib.text.Text` instance. You can save it and set the new title: ``` txt = fig.suptitle('A test title') txt.set_text('A better title') plt.draw() ```
I had similar problem. Method suptitile of figure object show title over old title (previously created). This is definately a bug in matplotlib. Especially as you can find this code in figure.py (part of matplotlib package): ``` (...) sup = self.text(x, y, t, **kwargs) if self._suptitle is not...
10,559,144
I am trying to use `suptitle` to print a title, and I want to occationally replace this title. Currently I am using: ``` self.ui.canvas1.figure.suptitle(title) ``` where figure is a matplotlib figure (canvas1 is an mplCanvas, but that is not relevant) and title is a python string. Currently, this works, except for...
2012/05/11
[ "https://Stackoverflow.com/questions/10559144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402632/" ]
Resurrecting this old thread because I recently ran into this. There is a references to the Text object returned by the original setting of suptitle in figure.texts. You can use this to change the original until this is fixed in matplotlib.
I had similar problem. Method suptitile of figure object show title over old title (previously created). This is definately a bug in matplotlib. Especially as you can find this code in figure.py (part of matplotlib package): ``` (...) sup = self.text(x, y, t, **kwargs) if self._suptitle is not...
12,451,124
So I've already graduated and received all credits for my compsci degree. But my professor from my last quarter just sent me an email saying he found something interesting in one of my homework assignments. I forget the context, but I don't think it matters. I'll post the email exchange. --- From: PROF To: ME S...
2012/09/16
[ "https://Stackoverflow.com/questions/12451124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1676273/" ]
Think about how you would call `swap` in Python, versus how you would call a swap function in C. For example, in C, ``` swap(&a, &b); ``` is valid and swaps the memory in `a` with the memory in `b` (assuming the implementation of `swap` is right). But, in Python, ``` swap(a, b) ``` ...does nothing! You'd have t...
I guess his point is that inside a function there's no need to do the swap at all - because the return values of the function aren't tied to the values passed in, so this would do as well: ``` def swap(i, j): return j, i ``` So in fact there's no point in having the function, it doesn't add anything at all. You'...
12,451,124
So I've already graduated and received all credits for my compsci degree. But my professor from my last quarter just sent me an email saying he found something interesting in one of my homework assignments. I forget the context, but I don't think it matters. I'll post the email exchange. --- From: PROF To: ME S...
2012/09/16
[ "https://Stackoverflow.com/questions/12451124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1676273/" ]
Think about how you would call `swap` in Python, versus how you would call a swap function in C. For example, in C, ``` swap(&a, &b); ``` is valid and swaps the memory in `a` with the memory in `b` (assuming the implementation of `swap` is right). But, in Python, ``` swap(a, b) ``` ...does nothing! You'd have t...
Your function seems overcomplicated, surely you could just do this def swap(i,j): return j,i This would achieve the same thing with only one line of code?
12,451,124
So I've already graduated and received all credits for my compsci degree. But my professor from my last quarter just sent me an email saying he found something interesting in one of my homework assignments. I forget the context, but I don't think it matters. I'll post the email exchange. --- From: PROF To: ME S...
2012/09/16
[ "https://Stackoverflow.com/questions/12451124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1676273/" ]
Think about how you would call `swap` in Python, versus how you would call a swap function in C. For example, in C, ``` swap(&a, &b); ``` is valid and swaps the memory in `a` with the memory in `b` (assuming the implementation of `swap` is right). But, in Python, ``` swap(a, b) ``` ...does nothing! You'd have t...
All he was expecting was the pythonic way to swap: ``` i, j = j, i ```
12,451,124
So I've already graduated and received all credits for my compsci degree. But my professor from my last quarter just sent me an email saying he found something interesting in one of my homework assignments. I forget the context, but I don't think it matters. I'll post the email exchange. --- From: PROF To: ME S...
2012/09/16
[ "https://Stackoverflow.com/questions/12451124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1676273/" ]
Your function seems overcomplicated, surely you could just do this def swap(i,j): return j,i This would achieve the same thing with only one line of code?
I guess his point is that inside a function there's no need to do the swap at all - because the return values of the function aren't tied to the values passed in, so this would do as well: ``` def swap(i, j): return j, i ``` So in fact there's no point in having the function, it doesn't add anything at all. You'...
12,451,124
So I've already graduated and received all credits for my compsci degree. But my professor from my last quarter just sent me an email saying he found something interesting in one of my homework assignments. I forget the context, but I don't think it matters. I'll post the email exchange. --- From: PROF To: ME S...
2012/09/16
[ "https://Stackoverflow.com/questions/12451124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1676273/" ]
All he was expecting was the pythonic way to swap: ``` i, j = j, i ```
I guess his point is that inside a function there's no need to do the swap at all - because the return values of the function aren't tied to the values passed in, so this would do as well: ``` def swap(i, j): return j, i ``` So in fact there's no point in having the function, it doesn't add anything at all. You'...
32,328,778
Suppose I want to match a string like this: > > 123(432)123(342)2348(34) > > > I can match digits like `123` with `[\d]*` and `(432)` with `\([\d]+\)`. How can match the whole string by repeating either of the 2 patterns? *I tried `[[\d]* | \([\d]+\)]+`, but this is incorrect.* *I am using python re module.*
2015/09/01
[ "https://Stackoverflow.com/questions/32328778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954376/" ]
I think you need this regex: ``` "^(\d+|\(\d+\))+$" ``` and to avoid catastrophic backtracking you need to change it to a regex like this: ``` "^(\d|\(\d+\))+$" ```
You can use a character class to match the whole of string : ``` [\d()]+ ``` But if you want to match the separate parts in separate groups you can use `re.findall` with a spacial regex based on your need, for example : ``` >>> import re >>> s="123(432)123(342)2348(34)" >>> re.findall(r'\d+\(\d+\)',s) ['123(432)', ...
32,328,778
Suppose I want to match a string like this: > > 123(432)123(342)2348(34) > > > I can match digits like `123` with `[\d]*` and `(432)` with `\([\d]+\)`. How can match the whole string by repeating either of the 2 patterns? *I tried `[[\d]* | \([\d]+\)]+`, but this is incorrect.* *I am using python re module.*
2015/09/01
[ "https://Stackoverflow.com/questions/32328778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954376/" ]
You can use a character class to match the whole of string : ``` [\d()]+ ``` But if you want to match the separate parts in separate groups you can use `re.findall` with a spacial regex based on your need, for example : ``` >>> import re >>> s="123(432)123(342)2348(34)" >>> re.findall(r'\d+\(\d+\)',s) ['123(432)', ...
You can achieve it with this pattern: ``` ^(?=.)\d*(?:\(\d+\)\d*)*$ ``` [demo](https://regex101.com/r/wI9jE5/1) `(?=.)` ensures there is at least one character (if you want to allow empty strings, remove it). `\d*(?:\(\d+\)\d*)*` is an unrolled sub-pattern. Explanation: With a bactracking regex engine, when you ha...
32,328,778
Suppose I want to match a string like this: > > 123(432)123(342)2348(34) > > > I can match digits like `123` with `[\d]*` and `(432)` with `\([\d]+\)`. How can match the whole string by repeating either of the 2 patterns? *I tried `[[\d]* | \([\d]+\)]+`, but this is incorrect.* *I am using python re module.*
2015/09/01
[ "https://Stackoverflow.com/questions/32328778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954376/" ]
I think you need this regex: ``` "^(\d+|\(\d+\))+$" ``` and to avoid catastrophic backtracking you need to change it to a regex like this: ``` "^(\d|\(\d+\))+$" ```
You can achieve it with this pattern: ``` ^(?=.)\d*(?:\(\d+\)\d*)*$ ``` [demo](https://regex101.com/r/wI9jE5/1) `(?=.)` ensures there is at least one character (if you want to allow empty strings, remove it). `\d*(?:\(\d+\)\d*)*` is an unrolled sub-pattern. Explanation: With a bactracking regex engine, when you ha...
32,870,262
I am trying to create a program in python in which the user enters a sentence and the reversed sentenced is printed. The code I have so far is: ``` sentence = raw_input('Enter the sentence') length = len(sentence) for i in sentence[length:0:-1]: a = i print a, ``` When the program is run it misses out the l...
2015/09/30
[ "https://Stackoverflow.com/questions/32870262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342974/" ]
You need to remove the `0` from your indices range, but instead you can use : ``` sentence[length::-1] ``` Also not that then you don't need to loop over your string and use extra assignments and even the `length` you can simply print the reversed string. So the following code will do the job for you : ``` print ...
The second argument of the slice notation means "up to, but not including", so `sentence[length:0:-1]` will loop up to 0, but not at 0. The fix is to explicitly change the 0 to -1, or leave it out (preferred). ``` for i in sentence[::-1]: ```
32,870,262
I am trying to create a program in python in which the user enters a sentence and the reversed sentenced is printed. The code I have so far is: ``` sentence = raw_input('Enter the sentence') length = len(sentence) for i in sentence[length:0:-1]: a = i print a, ``` When the program is run it misses out the l...
2015/09/30
[ "https://Stackoverflow.com/questions/32870262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342974/" ]
Try This: NO LOOPS using MAP Function ``` mySentence = "Mary had a little lamb" def reverseSentence(text): # split the text listOfWords = text.split() #reverese words order inside sentence listOfWords.reverse() #reverse each word inside the list using map function(Better than doing loops......
The second argument of the slice notation means "up to, but not including", so `sentence[length:0:-1]` will loop up to 0, but not at 0. The fix is to explicitly change the 0 to -1, or leave it out (preferred). ``` for i in sentence[::-1]: ```
32,870,262
I am trying to create a program in python in which the user enters a sentence and the reversed sentenced is printed. The code I have so far is: ``` sentence = raw_input('Enter the sentence') length = len(sentence) for i in sentence[length:0:-1]: a = i print a, ``` When the program is run it misses out the l...
2015/09/30
[ "https://Stackoverflow.com/questions/32870262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342974/" ]
You need to remove the `0` from your indices range, but instead you can use : ``` sentence[length::-1] ``` Also not that then you don't need to loop over your string and use extra assignments and even the `length` you can simply print the reversed string. So the following code will do the job for you : ``` print ...
``` print ''.join(reversed(raw_input('Enter the sentence'))) ```
32,870,262
I am trying to create a program in python in which the user enters a sentence and the reversed sentenced is printed. The code I have so far is: ``` sentence = raw_input('Enter the sentence') length = len(sentence) for i in sentence[length:0:-1]: a = i print a, ``` When the program is run it misses out the l...
2015/09/30
[ "https://Stackoverflow.com/questions/32870262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342974/" ]
You need to remove the `0` from your indices range, but instead you can use : ``` sentence[length::-1] ``` Also not that then you don't need to loop over your string and use extra assignments and even the `length` you can simply print the reversed string. So the following code will do the job for you : ``` print ...
Here you go: ``` sentence = raw_input('Enter the sentence') length = len(sentence) sentence = sentence[::-1] print(sentence) ``` Enjoy! Some explanation, the important line `sentence = sentence[::-1]` is a use of Python's slice notation. In detail [here](https://stackoverflow.com/questions/509211/explain-pythons-...
32,870,262
I am trying to create a program in python in which the user enters a sentence and the reversed sentenced is printed. The code I have so far is: ``` sentence = raw_input('Enter the sentence') length = len(sentence) for i in sentence[length:0:-1]: a = i print a, ``` When the program is run it misses out the l...
2015/09/30
[ "https://Stackoverflow.com/questions/32870262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342974/" ]
You need to remove the `0` from your indices range, but instead you can use : ``` sentence[length::-1] ``` Also not that then you don't need to loop over your string and use extra assignments and even the `length` you can simply print the reversed string. So the following code will do the job for you : ``` print ...
Try This: NO LOOPS using MAP Function ``` mySentence = "Mary had a little lamb" def reverseSentence(text): # split the text listOfWords = text.split() #reverese words order inside sentence listOfWords.reverse() #reverse each word inside the list using map function(Better than doing loops......
32,870,262
I am trying to create a program in python in which the user enters a sentence and the reversed sentenced is printed. The code I have so far is: ``` sentence = raw_input('Enter the sentence') length = len(sentence) for i in sentence[length:0:-1]: a = i print a, ``` When the program is run it misses out the l...
2015/09/30
[ "https://Stackoverflow.com/questions/32870262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342974/" ]
Try This: NO LOOPS using MAP Function ``` mySentence = "Mary had a little lamb" def reverseSentence(text): # split the text listOfWords = text.split() #reverese words order inside sentence listOfWords.reverse() #reverse each word inside the list using map function(Better than doing loops......
``` print ''.join(reversed(raw_input('Enter the sentence'))) ```
32,870,262
I am trying to create a program in python in which the user enters a sentence and the reversed sentenced is printed. The code I have so far is: ``` sentence = raw_input('Enter the sentence') length = len(sentence) for i in sentence[length:0:-1]: a = i print a, ``` When the program is run it misses out the l...
2015/09/30
[ "https://Stackoverflow.com/questions/32870262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342974/" ]
Try This: NO LOOPS using MAP Function ``` mySentence = "Mary had a little lamb" def reverseSentence(text): # split the text listOfWords = text.split() #reverese words order inside sentence listOfWords.reverse() #reverse each word inside the list using map function(Better than doing loops......
Here you go: ``` sentence = raw_input('Enter the sentence') length = len(sentence) sentence = sentence[::-1] print(sentence) ``` Enjoy! Some explanation, the important line `sentence = sentence[::-1]` is a use of Python's slice notation. In detail [here](https://stackoverflow.com/questions/509211/explain-pythons-...
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
Yes, there is: ``` return iter([]) ```
``` def do_yield(): return yield None ``` if usage of `yield` is important for you, one of the other answers otherwise.
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
Yes, there is: ``` return iter([]) ```
You can use the lambda and iter functions to create an empty iterable in Python. ``` my_iterable = lambda: iter(()) ```
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
You can use the lambda and iter functions to create an empty iterable in Python. ``` my_iterable = lambda: iter(()) ```
Another answer, as I provide a completely new solution with a different approach. In one of by libraries, I have an `EmptyIterator` such as ``` class EmptyIter(object): __name__ = 'EmptyIter' """Iterable which is False and empty""" def __len__(self): return 0 def next(self): raise StopIteration # eve...
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
How about ``` my_iterable = str ``` this passes your test. To speak seriously, `Iterable` in the [collections module](http://hg.python.org/cpython/file/2.7/Lib/_abcoll.py) provides: ``` def __iter__(self): while False: yield None ``` This can be considered "most pythonic" because this is what python...
Another answer, as I provide a completely new solution with a different approach. In one of by libraries, I have an `EmptyIterator` such as ``` class EmptyIter(object): __name__ = 'EmptyIter' """Iterable which is False and empty""" def __len__(self): return 0 def next(self): raise StopIteration # eve...
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
Yes, there is: ``` return iter([]) ```
How about ``` my_iterable = str ``` this passes your test. To speak seriously, `Iterable` in the [collections module](http://hg.python.org/cpython/file/2.7/Lib/_abcoll.py) provides: ``` def __iter__(self): while False: yield None ``` This can be considered "most pythonic" because this is what python...
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
How about ``` my_iterable = str ``` this passes your test. To speak seriously, `Iterable` in the [collections module](http://hg.python.org/cpython/file/2.7/Lib/_abcoll.py) provides: ``` def __iter__(self): while False: yield None ``` This can be considered "most pythonic" because this is what python...
``` def do_yield(): return yield None ``` if usage of `yield` is important for you, one of the other answers otherwise.
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
Another solution, in Python 3, is to use the new `yield from` syntax: ``` def empty_gen(): yield from () ``` Which is readable, and keep `empty_gen` as a generator.
Another answer, as I provide a completely new solution with a different approach. In one of by libraries, I have an `EmptyIterator` such as ``` class EmptyIter(object): __name__ = 'EmptyIter' """Iterable which is False and empty""" def __len__(self): return 0 def next(self): raise StopIteration # eve...
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
Yes, there is: ``` return iter([]) ```
Another answer, as I provide a completely new solution with a different approach. In one of by libraries, I have an `EmptyIterator` such as ``` class EmptyIter(object): __name__ = 'EmptyIter' """Iterable which is False and empty""" def __len__(self): return 0 def next(self): raise StopIteration # eve...
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
Another solution, in Python 3, is to use the new `yield from` syntax: ``` def empty_gen(): yield from () ``` Which is readable, and keep `empty_gen` as a generator.
How about ``` my_iterable = str ``` this passes your test. To speak seriously, `Iterable` in the [collections module](http://hg.python.org/cpython/file/2.7/Lib/_abcoll.py) provides: ``` def __iter__(self): while False: yield None ``` This can be considered "most pythonic" because this is what python...
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
``` def do_yield(): return yield None ``` if usage of `yield` is important for you, one of the other answers otherwise.
Another answer, as I provide a completely new solution with a different approach. In one of by libraries, I have an `EmptyIterator` such as ``` class EmptyIter(object): __name__ = 'EmptyIter' """Iterable which is False and empty""" def __len__(self): return 0 def next(self): raise StopIteration # eve...
64,523,282
I installed anaconda from the [official website](https://www.anaconda.com/) and I want to integrate it with sublime text 3. I tried to build a sublime-build json file like this: ``` { "cmd": ["C:/Users/Minh Duy/anaconda3/python.exe", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", ...
2020/10/25
[ "https://Stackoverflow.com/questions/64523282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12074366/" ]
The DLLs of the mkl-service that it's tried to load are by default located in the following directory: **C:/Users/<username>/anaconda3/Library/bin** since that path isn't in the PATH Environment Variable, it can't find them and raises the ImportError. To fix this, you can: 1. Add the mentioned path to the PATH Envir...
first configure it with python. write python in your cmd to get python path. then configure it with anaconda. ``` { "cmd": ["C:/Users/usr_name/AppData/Local/Programs/Python/Python37-32/python.exe", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python" } ```
64,708,800
I have been able to successfully detect an object(face and eye) using haar cascade classifier in python using opencv. When the object is detected, a rectangle is shown around the object. I want to get coordinates of mid point of the two eyes. and want to store them in a array. Can any one help me? how can i do this. an...
2020/11/06
[ "https://Stackoverflow.com/questions/64708800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11828549/" ]
Haskell doesn't allow this because it would be ambiguous. The value constructor `Prop` is effectively a function, which may be clearer if you ask GHCi about its type: ``` > :t Const Const :: Bool -> Prop ``` If you attempt to add one more `Const` constructor in the same module, you'd have two 'functions' called `Con...
This is somewhat horrible, but will basically let you do what you want: ```hs {-# LANGUAGE PatternSynonyms, TypeFamilies, ViewPatterns #-} data Prop = PropConst Bool | PropVar Char | PropNot Prop | PropOr Prop Prop | PropAnd Prop Prop | PropImply Prop Prop data Formu...
53,014,961
It seems like a trivial task however, I can't find a solution for doing this using python. Given the following string: ``` "Lorem/ipsum/dolor/sit amet consetetur" ``` I would like to output ``` "Lorem/ipsum/dolor/sit ametconsetetur" ``` Hence, removing the single whitespace between `amet` and `c...
2018/10/26
[ "https://Stackoverflow.com/questions/53014961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6341510/" ]
use regex and word boundary: ``` >>> s="Lorem/ipsum/dolor/sit amet consetetur" >>> import re >>> re.sub(r"\b \b","",s) 'Lorem/ipsum/dolor/sit ametconsetetur' >>> ``` This technique also handles the more general case: ``` >>> s="Lorem/ipsum/dolor/sit amet consetetur adipisci velit" >>> r...
``` s[::-1].replace(' ', '', 1)[::-1] ``` * Reverse the string * Delete the first space * Reverse the string back
53,014,961
It seems like a trivial task however, I can't find a solution for doing this using python. Given the following string: ``` "Lorem/ipsum/dolor/sit amet consetetur" ``` I would like to output ``` "Lorem/ipsum/dolor/sit ametconsetetur" ``` Hence, removing the single whitespace between `amet` and `c...
2018/10/26
[ "https://Stackoverflow.com/questions/53014961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6341510/" ]
use regex and word boundary: ``` >>> s="Lorem/ipsum/dolor/sit amet consetetur" >>> import re >>> re.sub(r"\b \b","",s) 'Lorem/ipsum/dolor/sit ametconsetetur' >>> ``` This technique also handles the more general case: ``` >>> s="Lorem/ipsum/dolor/sit amet consetetur adipisci velit" >>> r...
``` import re a="Lorem/ipsum/dolor/sit amet consetetur" print(re.sub('(\w)\s{1}(\w)',r'\1\2',a)) ```
53,014,961
It seems like a trivial task however, I can't find a solution for doing this using python. Given the following string: ``` "Lorem/ipsum/dolor/sit amet consetetur" ``` I would like to output ``` "Lorem/ipsum/dolor/sit ametconsetetur" ``` Hence, removing the single whitespace between `amet` and `c...
2018/10/26
[ "https://Stackoverflow.com/questions/53014961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6341510/" ]
``` s[::-1].replace(' ', '', 1)[::-1] ``` * Reverse the string * Delete the first space * Reverse the string back
``` import re a="Lorem/ipsum/dolor/sit amet consetetur" print(re.sub('(\w)\s{1}(\w)',r'\1\2',a)) ```
68,588,398
I would like to define python function which takes a list of dictionaries in which some keys could be lists and then returns a list of list of dictionaries in which each key is a single value, which corresponds to all the combinations of options (an option is picking a single value from each list). Consider the follow...
2021/07/30
[ "https://Stackoverflow.com/questions/68588398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13613091/" ]
If you have all vec lists in a single list of lists using, you can unpack this list when passing it to the product function: ``` list_vecs = [vec, vec2, vec3, vec4] list(product(*list_vecs, repeat=1)) ``` Concerning the \* (star-notation) see the python docs [here](https://docs.python.org/3/tutorial/controlflow.htm...
This solution is almost the same as @mcsoini, but a little more explanation: Here, ``` vec=[['A1','A2','A3'], ['B1','B2'], ['C1','C2','C3'],vec4] ``` `vec` is a list of lists. The first 3 lists are `vec1,2,3`. `vec4` can be added later on. Also, you can add more lists to `vec` using `vec.append(<list>)` Now, instea...
44,948,661
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code? Here is my code: ``` file_object=open("SupremeCourt.txt","w") from gensim.models import word2vec data = word2vec.Text8Corpus('SupremeCourt.txt') model = word2vec.Word2Vec(...
2017/07/06
[ "https://Stackoverflow.com/questions/44948661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264914/" ]
Have a look at this: <https://tweepy.readthedocs.io/en/v3.5.0/cursor_tutorial.html> And try this: ``` import tweepy auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET) api = tweepy.API(auth) for tweet in tweepy.Cursor(api.search, q='#python', rpp=100).items(): # Do something pass ``` In your case ...
Check twitter api documentation, probably it allows just 300 tweets to parse. I would recommend to forget api, make it with requests with streaming. The api is an implementation of requests with limitations.
44,948,661
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code? Here is my code: ``` file_object=open("SupremeCourt.txt","w") from gensim.models import word2vec data = word2vec.Text8Corpus('SupremeCourt.txt') model = word2vec.Word2Vec(...
2017/07/06
[ "https://Stackoverflow.com/questions/44948661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264914/" ]
Sorry, I can't answer in comment, too long. :) Sure :) Check this example: Advanced searched for #data keyword 2015 may - 2016 july Got this url: <https://twitter.com/search?l=&q=%23data%20since%3A2015-05-01%20until%3A2016-07-31&src=typd> ``` session = requests.session() keyword = 'data' date1 = '2015-05-01' date2 = ...
Check twitter api documentation, probably it allows just 300 tweets to parse. I would recommend to forget api, make it with requests with streaming. The api is an implementation of requests with limitations.
44,948,661
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code? Here is my code: ``` file_object=open("SupremeCourt.txt","w") from gensim.models import word2vec data = word2vec.Text8Corpus('SupremeCourt.txt') model = word2vec.Word2Vec(...
2017/07/06
[ "https://Stackoverflow.com/questions/44948661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264914/" ]
This code worked for me. ``` import tweepy import pandas as pd import os #Twitter Access auth = tweepy.OAuthHandler( 'xxx','xxx') auth.set_access_token('xxx-xxx','xxx') api = tweepy.API(auth,wait_on_rate_limit = True) df = pd.DataFrame(columns=['text', 'source', 'url']) msgs = [] msg =[] for tweet in tweepy.Cursor...
Check twitter api documentation, probably it allows just 300 tweets to parse. I would recommend to forget api, make it with requests with streaming. The api is an implementation of requests with limitations.
44,948,661
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code? Here is my code: ``` file_object=open("SupremeCourt.txt","w") from gensim.models import word2vec data = word2vec.Text8Corpus('SupremeCourt.txt') model = word2vec.Word2Vec(...
2017/07/06
[ "https://Stackoverflow.com/questions/44948661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264914/" ]
Have a look at this: <https://tweepy.readthedocs.io/en/v3.5.0/cursor_tutorial.html> And try this: ``` import tweepy auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET) api = tweepy.API(auth) for tweet in tweepy.Cursor(api.search, q='#python', rpp=100).items(): # Do something pass ``` In your case ...
Sorry, I can't answer in comment, too long. :) Sure :) Check this example: Advanced searched for #data keyword 2015 may - 2016 july Got this url: <https://twitter.com/search?l=&q=%23data%20since%3A2015-05-01%20until%3A2016-07-31&src=typd> ``` session = requests.session() keyword = 'data' date1 = '2015-05-01' date2 = ...
44,948,661
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code? Here is my code: ``` file_object=open("SupremeCourt.txt","w") from gensim.models import word2vec data = word2vec.Text8Corpus('SupremeCourt.txt') model = word2vec.Word2Vec(...
2017/07/06
[ "https://Stackoverflow.com/questions/44948661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264914/" ]
Have a look at this: <https://tweepy.readthedocs.io/en/v3.5.0/cursor_tutorial.html> And try this: ``` import tweepy auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET) api = tweepy.API(auth) for tweet in tweepy.Cursor(api.search, q='#python', rpp=100).items(): # Do something pass ``` In your case ...
This code worked for me. ``` import tweepy import pandas as pd import os #Twitter Access auth = tweepy.OAuthHandler( 'xxx','xxx') auth.set_access_token('xxx-xxx','xxx') api = tweepy.API(auth,wait_on_rate_limit = True) df = pd.DataFrame(columns=['text', 'source', 'url']) msgs = [] msg =[] for tweet in tweepy.Cursor...
44,948,661
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code? Here is my code: ``` file_object=open("SupremeCourt.txt","w") from gensim.models import word2vec data = word2vec.Text8Corpus('SupremeCourt.txt') model = word2vec.Word2Vec(...
2017/07/06
[ "https://Stackoverflow.com/questions/44948661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264914/" ]
Sorry, I can't answer in comment, too long. :) Sure :) Check this example: Advanced searched for #data keyword 2015 may - 2016 july Got this url: <https://twitter.com/search?l=&q=%23data%20since%3A2015-05-01%20until%3A2016-07-31&src=typd> ``` session = requests.session() keyword = 'data' date1 = '2015-05-01' date2 = ...
This code worked for me. ``` import tweepy import pandas as pd import os #Twitter Access auth = tweepy.OAuthHandler( 'xxx','xxx') auth.set_access_token('xxx-xxx','xxx') api = tweepy.API(auth,wait_on_rate_limit = True) df = pd.DataFrame(columns=['text', 'source', 'url']) msgs = [] msg =[] for tweet in tweepy.Cursor...
55,013,809
OK I was afraid to use the terminal, so I installed the python-3.7.2-macosx10.9 package downloaded from python.org Ran the certificate and shell profile scripts, everything seems fine. Now the "which python3" has changed the path from 3.6 to the new 3.7.2 So everything seems fine, correct? My question (of 2) is what'...
2019/03/06
[ "https://Stackoverflow.com/questions/55013809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9291766/" ]
Yes, you can install Python 3.7 or Python 3.8 using installer that you can download from [python.org](https://www.python.org/downloads/). It doesn't automatically delete the older version that you can keep using the older version. For example, if you have `python3.7` and `python3.8`, you can run either one on your te...
Each version of the Python installation is independent of each other. So its safe to delete the version you don't want, but be cautious of this because it can lead to broken dependencies :-). You can run any version by adding the specific version i.e $python3.6 or $python3.7 The best approach is to use virtual enviro...
32,736,350
I did found quite a lot about this error, but somehow none of the suggested solutions resolved the problem. I am trying to use JNA bindings for libgphoto2 under Ubuntu in Eclipse (moderate experience with Java on Eclipse, none whatsoever on Ubuntu, I'm afraid). The bindings in question I want to use are here: <http://...
2015/09/23
[ "https://Stackoverflow.com/questions/32736350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4428658/" ]
In addition to what @Paul Whelan has said. You might have better luck by just get the missing jar directly. Get the missing library [here](https://github.com/java-native-access/jna), set the classpath and then re-run the application again and see whether it will run fine or not.
What version of java are you using com/sun/jna/Structure may only work with certain JVMs. In general, packages such as sun.*, that are outside of the Java platform, can be different across OS platforms (Solaris, Windows, Linux, Macintosh, etc.) and can change at any time without notice with SDK versions (1.2, 1.2.1, 1...
32,736,350
I did found quite a lot about this error, but somehow none of the suggested solutions resolved the problem. I am trying to use JNA bindings for libgphoto2 under Ubuntu in Eclipse (moderate experience with Java on Eclipse, none whatsoever on Ubuntu, I'm afraid). The bindings in question I want to use are here: <http://...
2015/09/23
[ "https://Stackoverflow.com/questions/32736350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4428658/" ]
In addition to what @Paul Whelan has said. You might have better luck by just get the missing jar directly. Get the missing library [here](https://github.com/java-native-access/jna), set the classpath and then re-run the application again and see whether it will run fine or not.
Your jar needs a MANIFEST.MF which tells your application where the library is found. Create the file in you project root-directory in eclipse and add the following lines: ``` Manifest-Version: 1.0 Class-Path: <PATH_TO_LIB__CAN_BE_RELATIVE>.jar // e.g Class-Path: ../test.jar <empty line> ``` Right-click your p...
45,384,065
I am looking for a way to run a method every second, regardless of how long it takes to run. In looking for help with that, I ran across [Run certain code every n seconds](https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds) and in trying it, found that it doesn't work correctly. It appears t...
2017/07/29
[ "https://Stackoverflow.com/questions/45384065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8217211/" ]
1. Don't use a `threading.Timer` if you don't actually need a new thread each time; to run a function periodically `sleep` in a loop will do (possibly in a single separate thread). 2. Whatever method you use to schedule the next execution, don't wait for the exact amount of time you use as interval - execution of the o...
I'm pretty sure the problem with that code is that it takes Python some time (apparently around .3s) to execute the call to your function `woof`, instantiate a new `threading.Timer` object, and print the current time. So basically, after your first call to the function, and the creation of a `threading.Timer`, Python w...
6,686,576
What i'm trying to achieve is playing a guitar chord from my python application. I know (or can calculate) the frequencies in the chord if needed. I'm thinking that even if I do the low level leg work of producing multiple sine waves at the right frequencies it wont sound right due to the envelope needing to be correc...
2011/07/13
[ "https://Stackoverflow.com/questions/6686576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384388/" ]
a) The hackish way is to spawn a background subprocess to run each `play` command. Since a background subprocess doesn't make the shell wait for it to finish, you can have multiple `play`s running at once. Something like this would work: ``` for p in "C3" "E3" "G3"; do ( play -n synth 3 pluck $p & ); done ``` I see ...
*a) is it possible to shoehorn the play command to do a whole chord... ?* If your sound architecture supports it, you can run multiple commands that output audio at the same time. If you're using ALSA, you need dmix or other variants in your `~/.asoundrc`. Use `subprocess.Popen` to spawn many child processes. If this ...
6,686,576
What i'm trying to achieve is playing a guitar chord from my python application. I know (or can calculate) the frequencies in the chord if needed. I'm thinking that even if I do the low level leg work of producing multiple sine waves at the right frequencies it wont sound right due to the envelope needing to be correc...
2011/07/13
[ "https://Stackoverflow.com/questions/6686576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384388/" ]
The manual gives this example: ``` play -n synth pl G2 pl B2 pl D3 pl G3 pl D4 pl G4 \ delay 0 .05 .1 .15 .2 .25 remix - fade 0 4 .1 norm -1 ``` This creates 6 simultaneous instances of synth (as separate audio channels), delays 5 of the channels by slightly increasing times, then mixes them down to a...
*a) is it possible to shoehorn the play command to do a whole chord... ?* If your sound architecture supports it, you can run multiple commands that output audio at the same time. If you're using ALSA, you need dmix or other variants in your `~/.asoundrc`. Use `subprocess.Popen` to spawn many child processes. If this ...
6,686,576
What i'm trying to achieve is playing a guitar chord from my python application. I know (or can calculate) the frequencies in the chord if needed. I'm thinking that even if I do the low level leg work of producing multiple sine waves at the right frequencies it wont sound right due to the envelope needing to be correc...
2011/07/13
[ "https://Stackoverflow.com/questions/6686576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384388/" ]
The manual gives this example: ``` play -n synth pl G2 pl B2 pl D3 pl G3 pl D4 pl G4 \ delay 0 .05 .1 .15 .2 .25 remix - fade 0 4 .1 norm -1 ``` This creates 6 simultaneous instances of synth (as separate audio channels), delays 5 of the channels by slightly increasing times, then mixes them down to a...
a) The hackish way is to spawn a background subprocess to run each `play` command. Since a background subprocess doesn't make the shell wait for it to finish, you can have multiple `play`s running at once. Something like this would work: ``` for p in "C3" "E3" "G3"; do ( play -n synth 3 pluck $p & ); done ``` I see ...
27,643,383
I am trying to install the elastic beanstalk CLI on an EC2 instance (running AMI) using these instructions: <http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-getting-started.html> I have python 2.7.9 installed, pip and eb. However, when I try to run eb I get the error below. It looks like it is still usi...
2014/12/25
[ "https://Stackoverflow.com/questions/27643383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536188/" ]
Pip is probably set up with Python 2.6 instead of python 2.7. ``` pip --version ``` You can reinstall pip with Python 2.7, then reinstall 2.6 ``` pip uninstall awsebcli wget https://bootstrap.pypa.io/get-pip.py python get-pip.py pip install awsebcli ```
The "smartest" solution for me was to install python-dev tools sudo apt install python-dev found here: <http://ericbenson.azurewebsites.net/deployment-on-aws-elastic-beanstalk-for-ubuntu/>
27,643,383
I am trying to install the elastic beanstalk CLI on an EC2 instance (running AMI) using these instructions: <http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-getting-started.html> I have python 2.7.9 installed, pip and eb. However, when I try to run eb I get the error below. It looks like it is still usi...
2014/12/25
[ "https://Stackoverflow.com/questions/27643383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536188/" ]
Pip is probably set up with Python 2.6 instead of python 2.7. ``` pip --version ``` You can reinstall pip with Python 2.7, then reinstall 2.6 ``` pip uninstall awsebcli wget https://bootstrap.pypa.io/get-pip.py python get-pip.py pip install awsebcli ```
I had the same problem, the fix for me was actually to upgrade to latest Beanstalk stack ( `eb upgrade` ). **Note there are downtime** etc. So investigate if you can run the latest stack before upgrading.
27,643,383
I am trying to install the elastic beanstalk CLI on an EC2 instance (running AMI) using these instructions: <http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-getting-started.html> I have python 2.7.9 installed, pip and eb. However, when I try to run eb I get the error below. It looks like it is still usi...
2014/12/25
[ "https://Stackoverflow.com/questions/27643383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536188/" ]
I had the same problem, the fix for me was actually to upgrade to latest Beanstalk stack ( `eb upgrade` ). **Note there are downtime** etc. So investigate if you can run the latest stack before upgrading.
The "smartest" solution for me was to install python-dev tools sudo apt install python-dev found here: <http://ericbenson.azurewebsites.net/deployment-on-aws-elastic-beanstalk-for-ubuntu/>
69,437,836
I was trying to make a program that can make classification between runway and taxiway using mask rcnn. after importing custom dataset in json format I am getting key error ``` class CustomDataset(utils.Dataset): def load_custom(self, dataset_dir, subset): """Load a subset of the Horse-Man dataset. ...
2021/10/04
[ "https://Stackoverflow.com/questions/69437836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16702137/" ]
I think it should be `name`, not `names`, based on the file format in the comment: ``` { 'filename': '28503151_5b5b7ec140_b.jpg', 'regions': { '0': { 'region_attributes': {}, 'shape_attributes': { 'all_points_x': [...], 'all_points_y': [...], ...
i resolved this error by rechecking my annotations in VGG tool and found that i double labeled (wrongly labeled) two file. so my suggestion is to recheck all files in VGG Annotation Tool and check for missing or multiple times labelled files. Thanks
13,352,296
The following works and returns a list of all users ``` ldapsearch -x -b "ou=lunchbox,dc=office,dc=lbox,dc=com" -D "OFFICE\Administrator" -h ad.office.lbox.com -p 389 -W "(&(objectcategory=person)(objectclass=user))" ``` I'm trying to do the same in Python and I'm getting `Invalid credentials` ``` #!/usr/bin/env py...
2012/11/12
[ "https://Stackoverflow.com/questions/13352296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039166/" ]
You're using different credentials for the bind from the command line and the python script. The command line is using the bind dn of `OFFICE\Administrator` while the script is using the bind dn of `cn=Administrator,dc=office,dc=lbox,dc=com` On Active Directory, the built-in account `Administrator` doesn't reside at ...
The python-ldap library does not parse the user name, neither does ldapsearch. In you code, simply use the same username `OFFICE\Administrator` and let Active Directory handle it. Also it is not uncommon for ActiveDirectory to refuse simple bind over ldap. You must use LDAPS. Add this line to bypass certificat checkin...
53,157,921
Please excuse my silly question as I am really new to python. I have 20 different .txt files (eg `"myfile_%s"` with `s` having been attributed to an integer in range=1,21). So I load them as follows: ``` runs=range(1,21) for i in runs: Myfile=np.loadtxt("myfile_%s.txt" %i, delimiter=',', unpack=True) ``` Hen...
2018/11/05
[ "https://Stackoverflow.com/questions/53157921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10042405/" ]
You can split using your delimiter and load into a native python list: ``` my_files = [] for i in range(1,21): with open("my_file_{0}.txt".format(i), 'r') as f: my_files.append(f.read().split(',')) ``` Now you have a list of lists. You can get the max overall, or get the max of each list, like so: ``` ...
Are your lists of equal length? If yes, you can do everything in one numpy array: ``` a = np.zeros((100,20)) for i in range(1,21): a[i-1,:]=np.loadtxt("myfile_%s.txt" %i, delimiter=',', unpack=True) ``` Now you can do all `numpy` functions on the resulting array such as ``` b = np.sum(a,axis=0) ```
56,066,816
I have several data frames (with equal # columns but different names). I'm trying to create one data frame with rows stacked below each other. I don't care now about the column names (I can always rename them later). I saw different SO links but they don't address this problem completely. Note I've 21 data frames and...
2019/05/09
[ "https://Stackoverflow.com/questions/56066816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9473446/" ]
Assuming your DataFrames are stored in some list `df_l`: Rename the columns and concat: ``` df_l = [df1, df2, df3] for df in df_l: df.columns = df_l[0].columns # Just chose any DataFrame pd.concat(df_l) # Columns named with above DataFrame # Index is preserved ``` Or construct a new DataFram...
Once you put all the data frames into a list, try this code. ``` import pandas as pd df = [df1, df2, df3] result = pd.DataFrame(columns=df1.columns) for df in df: result = pd.concat([result,df.rename(columns=df1.columns)], ignore_index=True) ```
56,066,816
I have several data frames (with equal # columns but different names). I'm trying to create one data frame with rows stacked below each other. I don't care now about the column names (I can always rename them later). I saw different SO links but they don't address this problem completely. Note I've 21 data frames and...
2019/05/09
[ "https://Stackoverflow.com/questions/56066816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9473446/" ]
Assuming your DataFrames are stored in some list `df_l`: Rename the columns and concat: ``` df_l = [df1, df2, df3] for df in df_l: df.columns = df_l[0].columns # Just chose any DataFrame pd.concat(df_l) # Columns named with above DataFrame # Index is preserved ``` Or construct a new DataFram...
I will do it at the beginning adding `skiprows=1` ``` names=[0,1,2,3,4]# what every you want to call them .. pd.concat([pd.read_csv(f, usecols = [0,1,2,3,4],skiprows=1,names=[0,1,2,3,4]) for f in files]) ```