qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
53,581,563
Currently, I'm trying to make a game and in the game I would like it so if the character is on top of an object, it picks it up. This is what I have so far: ``` import turtle import time default = turtle.clone() scar = turtle.clone() def pickupScar(): if default.distance(-7,48) > 5.0: default.changeshape...
2018/12/02
[ "https://Stackoverflow.com/questions/53581563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10735185/" ]
Since I don't have your images, nor recognize what your game is about, below is an example of the functionality you describe. On the screen is a black circle and pink square. You can drag the circle and if you drag it onto the square, it will sprout a head and legs becoming a turtle. Dragging off the square, it reverts...
I dont know the `turtle-graphics`, but in real world to determine the distance between two points (for 2D surfaces) we use **Pythagorean theorem**. If some object is at `(x1, y1)` and another at `(x2, y2)`, the distance is ``` dist=sqrt((x1-x2)^2 + (y1-y2)^2) ``` So, if `dist <= R`, turtle (or whatever) is `in R r...
3,742
29,871,209
I have compressed a file using python-snappy and put it in my hdfs store. I am now trying to read it in like so but I get the following traceback. I can't find an example of how to read the file in so I can process it. I can read the text file (uncompressed) version fine. Should I be using sc.sequenceFile ? Thanks! ``...
2015/04/25
[ "https://Stackoverflow.com/questions/29871209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4833015/" ]
The issue here is that python-snappy is not compatible with Hadoop's snappy codec, which is what Spark will use to read the data when it sees a ".snappy" suffix. They are based on the same underlying algorithm but they aren't compatible in that you can compress with one and decompress with another. You can make this w...
Alright I found a solution! Build this... <https://github.com/liancheng/snappy-utils> On ubuntu 14.10 I had to install gcc-4.4 to get it to build commented on my error I was seeing here <https://code.google.com/p/hadoop-snappy/issues/detail?id=9> I can now compress the text files using snappy at the command line lik...
3,743
56,436,777
Referencing this question: [What's the canonical way to check for type in Python?](https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python) It is said that the best way to check for inputs is to not check them - that is to let try/except blocks take care of bad inputs. My quest...
2019/06/04
[ "https://Stackoverflow.com/questions/56436777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4992644/" ]
there you go ``` For Each row As DataGridViewRow In DataGridView1.Rows For Each nextrow As DataGridViewRow In DataGridView1.Rows If row.Index <> nextrow.Index Then If row.Cells(0).Value = nextrow.Cells(0).Value Then MsgBox("Duplicate on col 0, index = " & row.In...
``` For Each row As DataGridViewRow In dtg3.Rows For Each nextrow As DataGridViewRow In dtg3.Rows If row.Index <> nextrow.Index Then If row.Cells(0).Value = nextrow.Cells(0).Value AndAlso row.Cells(2).Value = nextrow.Cells(2).Value AndAlso row.Cells(3).Value = nextrow.C...
3,749
9,014,991
So let's say i have this python code: ``` def loopForEachFileInDirectory(self, conn): for filename in os.listdir(uploadedFilesDirectory): try: self.insertNewEntryForStagingFile(conn, filename) self.copyFilesToStagingDirectory(filename) except: ??? def copyFilesToStagingDire...
2012/01/26
[ "https://Stackoverflow.com/questions/9014991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061426/" ]
> > what is the rule for bubbling up a generic exception? Do i just raise on its own? > > > Yes. The short answer is to just use `raise`. > > And if so, how do i generically throw an exception... > > > The above answer the other submitter posted is correct, but it doesn't provide much in the way of context. ...
``` #!/usr/bin/python try: print 'Youll see me first.' try: 1[90] except Exception,e: print "************ UTOH!",str(e) raise e except Exception,e: print ">>>>>>>>>>>> I concur, THE JIG IS UP!",str(e) raise e ```
3,750
21,819,649
What's the difference between a namespace Python package (no `__init__.py`) and a regular Python package (has an `__init__.py`), especially when `__init__.py` is empty for a regular package? I am curious because recently I've been forgetting to make `__init__.py` in packages I make, and I never noticed any problems. I...
2014/02/17
[ "https://Stackoverflow.com/questions/21819649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/469721/" ]
Namespace packages ------------------ As of [Python 3.3](https://docs.python.org/3/whatsnew/3.3.html#pep-420-implicit-namespace-packages), we get namespace packages. These are a special kind of package that allows you to unify two packages with the same name at different points on your Python-path. For example, consid...
1. Having `__init__.py` makes it so you can import that package elsewhere. 2. Also, the `__init__.py` file can contain code you want executed each time the module is loaded.
3,753
21,272,497
I'm trying to see if this is the most efficient way to sort a bubble list in python or if there are better ways some people tell me to use two loops, what are the benefits of doing like that vs the below ``` def sort_bubble(blist): n = 0 while n < len(blist) - 1: if blist[n] > blist[n + 1]: ...
2014/01/22
[ "https://Stackoverflow.com/questions/21272497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3221614/" ]
Your algorithm is technically a bubble sort in that it does exactly the swaps that it should. However, it's a *very inefficient* bubble sort, in that it does a *lot* more compares than are necessary. How can you *know* that? It's pretty easy to instrument your code to count the number of compares and swaps. And meanwh...
This is how I would do it if I was forced to use bubble sort, you should probably always just use the default sort() function in python, it's very fast. ``` def BubbleSort(A): end = len(A)-1 swapped = True while swapped: swapped = False for i in range(0, end): if A[i] > A[i+1]: ...
3,756
48,689,158
I want to send commands to run a python script to the Linux terminal. I have a list of python files which I want to run and I want to run them one after the other as we read the list sequentially. Once the first file is finished, it should send the second one to run and so on.
2018/02/08
[ "https://Stackoverflow.com/questions/48689158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4782295/" ]
I would suggest gsl-like syntactic sugar to mark that it is not the pointer you manage. Something like: ``` template<class T> using observer = T; observer<library_managed_object *> foo = nullptr; ``` You can also use, as sugested elsewhere the `observer_ptr`. And one final word - in world of C++11 and so forth - u...
You can try [gsl::owner](https://github.com/Microsoft/GSL/blob/master/include/gsl/pointers) defined in the GSL project. Its not a type but more of a tag to define ownership. The [CPP core guidelines](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-raw) define the use case of `gsl::owner...
3,759
39,185,797
In Node.js when I want to quickly check the value of something rather than busting out the debugger and stepping through, I quickly add a console.log(foo) and get a beautiful: ``` { lemmons: "pie", number: 9, fetch: function(){..} elements: { fire: 99.9 } } ``` Very clear! In Python I get this: ...
2016/08/27
[ "https://Stackoverflow.com/questions/39185797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5947872/" ]
Actually, there is a way to stop Java GC. Just use the Epsilon GC algorithm that was introduced as an experimental feature in Java 11. Just add the following two arguments to your JVM's startup script: ``` -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC ``` All or Nothing -------------- Now just keep in mind tha...
By default the JVM runs the JVM only needed. This means you can't turn off the GC or your program will fail. The simplest way to avoid stopping the JVM is; * use a very small eden size so when it stops it will be less than some acceptable time. * or make the eden size very large and delay the GC until it hardly matte...
3,760
14,817,210
I have quite a simple question here. In Tkinter (python), I was wondering who to use a button to go to different pages of my application, e.g a register page, and a login page. I am aware that GUI does not have 'pages' like websites do, I've seen a few different ways, but what is the best way to make links to different...
2013/02/11
[ "https://Stackoverflow.com/questions/14817210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2061989/" ]
Make each page a frame. Then, all your buttons need to do is hide whatever is visible, then make the desired frame visible. A simple method to do this is to stack the frames on top of each other (this is one time when `place` makes sense) and then ,`lift()` the frame you want to be visible. This technique works best w...
Could you do something like this? ``` import tkinter def page1(): page2text.pack_forget() page1text.pack() def page2(): page1text.pack_forget() page2text.pack() window = tkinter.Tk() page1btn = tkinter.Button(window, text="Page 1", command=page1) page2btn = tkinter.Button(window, text="Page 2", com...
3,761
56,642,128
I have a data set with columns titled as product name, brand,rating(1:5),review text, review-helpfulness. What I need is to propose a recommendation algorithm using reviews. I have to use python for coding here. data set is in .csv format. To identify the nature of the data set I need to use kmeans on the data set. H...
2019/06/18
[ "https://Stackoverflow.com/questions/56642128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9725182/" ]
You did not plot anything. So nothing shows up.
Unless you are more specific about what you are trying to achieve we won't be able to help. Figure out what exactly you want to predict. Do you just want to cluster products according to their sentiment score which isn't especially promising or do you want to predict actual product preferences on a new dataset? If you...
3,764
69,557,664
I have a custom python logger ``` # logger.py import logging #logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) c_handler = logging.StreamHandler() c_handler.setLevel(logging.DEBUG) c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s') c_handler.setFormatter(c_format) ...
2021/10/13
[ "https://Stackoverflow.com/questions/69557664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3070181/" ]
TL;DR Use `logger.setLevel(logging.DEBUG)` --- According to [Python documentation](https://docs.python.org/3/library/logging.html#logging.Logger.setLevel), a handler processes messages with a level equal to or higher than the handler is set to (via `.setLevel()`). But also note, emphasis mine: > > When a logger is...
Having read the [docs](https://docs.python.org/3/library/logging.html#logging.Logger.setLevel) again I realise that *propagate* is the attribute that I need to use to turn off the ancestor *logging* output. So my logger becomes ``` # logger.py import logging logging.basicConfig(level=logging.DEBUG) logger.propagate =...
3,765
65,343,093
I am working on a pipeline where the majority of code is within a python script that I call in the pipeline. In the script I would like to use the predefined variable System.AccessToken to make a call to the DevOps API that sets the status of a pull request. However, when I try to get the token using `os.environ['Syst...
2020/12/17
[ "https://Stackoverflow.com/questions/65343093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11090784/" ]
After reviewing the page that Mani posted I found the answer. For most variables, something like System.AccessToken would have a corresponding SYSTEM\_ACCESSTOKEN. However, with a secret variable this is not the case. I was able to make it accessible to my python script by adding: ``` env: SYSTEM_ACCESSTOKEN: $(S...
with this documentation it can work: <https://learn.microsoft.com/de-de/azure/developer/python/azure-sdk-authenticate?tabs=cmd> Just change the language to "read in english" There must be a vault and a present Secret aka SAS Token. And I have to say your code above is curl not python. --- ``` import os from azure.i...
3,766
6,600,039
I'm trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object?
2011/07/06
[ "https://Stackoverflow.com/questions/6600039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234723/" ]
If you're using Django 1.3, take a look at the included [RequestFactory](https://docs.djangoproject.com/en/1.3/topics/testing/#the-request-factory).
Sounds like you want the django test client <https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client>
3,768
19,130,113
I've got a database full of BlobKeys that were previously uploaded through the standard Google App Engine [create\_upload\_url()](https://developers.google.com/appengine/docs/python/blobstore/functions#create_upload_url) process, and each of the uploads went to the same Google Cloud Storage bucket by setting the `gs_bu...
2013/10/02
[ "https://Stackoverflow.com/questions/19130113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361897/" ]
You can get the cloudstorage filename only in the upload handler (fileInfo.gs\_object\_name) and store it in your database. After that it is lost and it seems not to be preserved in BlobInfo or other metadata structures. > > Google says: Unlike BlobInfo metadata FileInfo metadata is not > persisted to datastore. (Th...
From the statement in the docs, it looks like the generated GCS filenames are lost. You'll have to use gsutil to manually browse your bucket. <https://developers.google.com/storage/docs/gsutil/commands/ls>
3,774
66,921,090
I am trying to create SparkContext in jupyter notebook but I am getting following Error: **Py4JError: org.apache.spark.api.python.PythonUtils.getPythonAuthSocketTimeout does not exist in the JVM** Here is my code ``` from pyspark import SparkContext, SparkConf conf = SparkConf().setMaster("local").setAppName("Grocer...
2021/04/02
[ "https://Stackoverflow.com/questions/66921090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7527164/" ]
Python's pyspark and spark cluster versions are inconsistent and this error is reported. Uninstall the version that is consistent with the current pyspark, then install the same version as the spark cluster. My spark version is 3.0.2 and run the following code: ``` pip3 uninstall pyspark pip3 install pyspark==3.0.2 `...
I have had the same error today and resolved it with the below code: Execute this in a separate cell before you have your spark session builder ``` from pyspark import SparkContext,SQLContext,SparkConf,StorageLevel from pyspark.sql import SparkSession from pyspark.conf import SparkConf SparkSession.bu...
3,777
4,787,291
I'm writing an application. No fancy GUI:s or anything, just a plain old console application. This application, lets call it App, needs to be able to load plugins on startup. So, naturally, i created a class for the plugins to inherit from: ``` class PluginBase(object): def on_load(self): pass def on_u...
2011/01/24
[ "https://Stackoverflow.com/questions/4787291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/350784/" ]
You would make this a lot easier if you forced some constraints on the plugin writer, for example that all plugins must be packages that contain a `load_plugin( app, config)` function that returns a Plugin instance. Then all you have to do is try to import these packages and run the function.
Could you use execfile() instead of import with a specified namespace dict, then iterate over that namespace with issubclass, etc?
3,780
29,463,921
A frog wants to cross a river. There are 3 stones in the river she can jump to. She wants to choose among all possible paths the one that leads to the smallest longest jump. Ie. each of the possible paths will have one jump that is the longest. She needs to find the path where this longest jump is smallest. The 2...
2015/04/06
[ "https://Stackoverflow.com/questions/29463921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4542063/" ]
I would use `Array()` to normalize the input and then there is only on case left: ``` work.map! do |w| element = Array(w).first console.button_map[element] || element end ```
I settled on this, not sure if it can be cleaner: ``` work.map! do |w| if w.is_a? Array w.tap{|x| x[0] = console.button_map[x[0]] || x[0] } else console.button_map[w] || w ...
3,785
49,582,981
I have a flask app in a docker container that writes to a local copy of SQLite db. what I want to do is move the db out of the container and have it reside on my host. how do I setup docker to run the python code from the container and read and write to the sql lite db on the host.
2018/03/31
[ "https://Stackoverflow.com/questions/49582981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9577029/" ]
Use bind-mount to share host file to container. If you have the SQLite DB file as `app.db`, you can run your container with the `-v` flag (or the `--mount` flag): ``` docker run -v /absolute/path/to/app.db:/flask/app/app.db <IMAGE> ``` Docs: <https://docs.docker.com/storage/bind-mounts/>
You have either * setup ownership privileges of your host directory to match `uid`:`gid` of the user in the container or * change `uid`:`gid` of the user in the container to match numerically `uid`:`gid` of your host user who owns directory with sqlite db file Great answers for both approaches are described [here]...
3,788
52,710,878
I created conda environment and install pytorch and fastai (Mac OS Mojave) as below: ``` conda create -n fai_course python=3.7 source activate fai_course conda install -c pytorch pytorch-nightly-cpu conda install -c fastai torchvision-nightly-cpu jupyter notebook ``` When I import a package from jupyter notebook, I...
2018/10/08
[ "https://Stackoverflow.com/questions/52710878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3899975/" ]
The comments say you "should" do a print, but nothing says you cannot print anything else after the print. Nothing even *forces* you to do a print, otherwise it would be a *shall*. --- To be honest, reading questions about homework like this one makes me unhappy. To me, the whole thing is useless, ugly, and does not...
The method stringLengt() should return "7" when you pass it the string "request", a different value when you pass it an empty string and another different value, when you pass null. Maybe you should take a look on control structures, especially selections. Also your stringLength method needs to return values of type St...
3,789
32,042,679
I saw a [twitter post](https://twitter.com/kssreeram/status/627477751797121024) pointing out that -12/10 = -2 in Python. What causes this? I thought the answer should (mathematically) be one. Why does python "literally" round down like this? ``` >>> -12/10 -2 >>> 12/10 1 >>> -1*12/10 -2 >>> 12/10 * -1 -1 ```
2015/08/17
[ "https://Stackoverflow.com/questions/32042679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3474956/" ]
This is due to [int](https://docs.python.org/2/library/functions.html#int) rounding down divisions. (aka [Floor division](http://python-history.blogspot.com.br/2010/08/why-pythons-integer-division-floors.html)) ``` >>> -12/10 -2 >>> -12.0/10 -1.2 >>> 12/10 1 >>> 12.0/10 1.2 ```
This is known as floor division (aka int division). In Python 2, this is the default behavior for `-12/10`. In Python 3, the default behavior is to use floating point division. To enable this behavior in Python 2, use the following import statement: ``` from __future__ import division ``` To use floor division in Py...
3,790
27,102,518
I need to optimize this regular expression. ``` ^(.+?)\|[\w\d]+?\s+?(\d\d\/\d\d\/\d\d\d\d\s+?\d\d:\d\d:\d\d\.\d\d\d)[\s\d]+?\s+?(\d+?)\s+?\d+?\s+?(\d+?)$ ``` The input is something like this: ``` -tpf0q16|856B 11/20/2014 00:00:00.015 0 0 0 0 0 689 ...
2014/11/24
[ "https://Stackoverflow.com/questions/27102518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42371/" ]
The first step is to get rid of the unneeded reluctant (a.k.a. "lazy") quantifiers. According to RegexBuddy, your regex: ``` ^(.+?)\|[\w\d]+?\s+?(\d\d\/\d\d\/\d\d\d\d\s+?\d\d:\d\d:\d\d\.\d\d\d)[\s\d]+?\s+?(\d+?)\s+?\d+?\s+?(\d+?)$ ``` ...takes 6425 steps to match your sample string. This one: ``` ^(.+?)\|[\w\d]+\s+...
A bit more optimized. ``` >>> import re >>> s = "-tpf0q16|856B 11/20/2014 00:00:00.015 0 0 0 0 0 689 14 689 703 702 701 700" >>> re.findall(r'(?m)^([^|]+)\|[\w\d]+?\s+?(\d{2}\/\d{2}\/\d{4}\s+\d{2}:\d{2}:\d{2}\...
3,791
24,995,438
I can run iPython, but when I try to initiate a notebook I get the following error: ``` ~ ipython notebook Traceback (most recent call last): File "/usr/local/bin/ipython", line 8, in <module> load_entry_point('ipython==2.1.0', 'console_scripts', 'ipython')() File "/Library/Python/2.7/site-...
2014/07/28
[ "https://Stackoverflow.com/questions/24995438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54564/" ]
Arg. The *ipython* install is a little idiosyncratic. Here's what I had to do to resolve this: ``` $ pip uninstall ipython $ pip install "ipython[all]" ``` The issue is that notebooks have their own set of dependencies, which aren't installed with `pip install ipython`. However, having installed *ipython*, pip doesn...
For me (Ubuntu 14.04.2) worked installation by synaptic package manager: the package is called python3-zmq, with this package will be installed libzmq3. After that check if pyzmq is correctly installed: ``` pip list ``` Then I installed ipython: ``` pip install "ipython[all]" ```
3,792
48,452,294
I have a python script that accepts a `-f` flag, and appends multiple uses of the flag. For example, if I run `python myscript -f file1.txt -f file2.txt`, I would have a list of files, `files=['file1.txt', 'files2.txt']`. This works great, but am wondering how I can automatically use the results of a find command to a...
2018/01/25
[ "https://Stackoverflow.com/questions/48452294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4509191/" ]
With the caveat that this will fail if there are more files than will fit on a single command line (whereas `xargs` would run `myscript.py` multiple times, each with a subset of the full list of arguments): ``` #!/usr/bin/env bash args=( ) while IFS= read -r -d '' name; do args+=( -f "$name" ) done < <(find . -inam...
Your title seems to imply that you can modify the script. In that case, use the `nargs` (number of args) option to allow more arguments for the `-f` flag: ``` parser = argparse.ArgumentParser() parser.add_argument('--files', '-f', nargs='+') args = parser.parse_args() print(args.files) ``` Then you can use your find...
3,794
22,597,089
There are a lot of questions about installing matplotlib on mac, but as far as I can tell I've installed it correctly using pip and it's just not working. When I try and run a script with matplotlib.pyplot.plot(x, y) nothing happens. No error, no nothing. ``` import matplotlib.pyplot x = [1,2,3,4] y = [4,3,2,1] mat...
2014/03/23
[ "https://Stackoverflow.com/questions/22597089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2930596/" ]
You need to call the `show` function. ``` import matplotlib.pyplot as plt x = [1,2,3,4] y = [4,3,2,1] plt.plot(x, y) plt.show() ```
It's likely that the plot is hidden behind the editor window or the spyder window on the screen. Instead of changing matplotlib settings, just learn the trackpack gestures of the mac, "app exposé" is the one you need to make your plots visible (see system preferences, trackpack). Then click on the figure to raise it to...
3,795
14,938,541
I use matplotlib to plot a scatter chart: ![enter image description here](https://i.stack.imgur.com/Nllqp.png) And label the bubble using a transparent box according to the tip at [How to annotate point on a scatter automatically placed arrow](https://stackoverflow.com/q/9074996/7758804) Here is the code: ``` if sh...
2013/02/18
[ "https://Stackoverflow.com/questions/14938541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1072888/" ]
It is a little rough around the edges (I can't quite figure out how to scale the relative strengths of the spring network vs the repulsive force, and the bounding box is a bit screwed up), but this is a decent start: ``` import networkx as nx N = 15 scatter_data = rand(3, N) G=nx.Graph() data_nodes = [] init_pos = {...
We can use plotly for this. But we can't help placing overlap correctly if there is lot of data. Instead we can zoom in and zoom out. ``` import plotly.express as px df = px.data.tips() df = px.data.gapminder().query("year==2007 and continent=='Americas'") fig = px.scatter(df, x="gdpPercap", y="lifeExp", text="count...
3,796
34,314,022
The documentation linked below seems to say that top level classes can be pickled, as well as their instances. But based on the answers to my previous [question](https://stackoverflow.com/q/34261379/3904031) it seem not to be correct. In the script I posted the pickle accepts the class object and writes a file, but thi...
2015/12/16
[ "https://Stackoverflow.com/questions/34314022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3904031/" ]
Make a class that is *defined at the top level of a module*: **foo.py**: ``` class Foo(object): pass ``` Then running a separate script, **script.py**: ``` import pickle import foo with open('/tmp/out.pkl', 'w') as f: pickle.dump(foo.Foo, f) del foo with open('/tmp/out.pkl', 'r') as f: cls = pickle.loa...
It's totally possible to pickle a class instance in python… while also saving the code to reconstruct the class and the instance's state. If you want to hack together a solution on top of `pickle`, or use a "trojan horse" `exec` based method here's how to do it: [How to unpickle an object whose class exists in a diffe...
3,802
22,734,148
I'm trying to check if a number is a perfect square. However, i am dealing with extraordinarily large numbers so python thinks its infinity for some reason. it gets up to 1.1 X 10^154 before the code returns "Inf". Is there anyway to get around this? Here is the code, the lst variable just holds a bunch of really reall...
2014/03/29
[ "https://Stackoverflow.com/questions/22734148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3476226/" ]
I think that you need to take a look at the [BigFloat](https://pythonhosted.org/bigfloat/) module, e.g.: ``` import bigfloat as bf b = bf.BigFloat('1e1000', bf.precision(21)) print bf.sqrt(b) ``` Prints `BigFloat.exact('9.9999993810013282e+499', precision=53)`
math.sqrt() converts the argument to a Python float which has a maximum value around 10^308. You should probably look at using the [gmpy2](https://code.google.com/p/gmpy/) library. gmpy2 provide very fast multiple precision arithmetic. If you want to check for arbitrary powers, the function `gmpy2.is_power()` will re...
3,803
30,326,654
I'm following this for django manage.py module <http://docs.ansible.com/django_manage_module.html> for e.g. one of my tasks looks like - ``` - name: Django migrate django_manage: command=migrate app_path={{app_path}} settings={{django_settings}} tags: - django ``` this wor...
2015/05/19
[ "https://Stackoverflow.com/questions/30326654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4414786/" ]
From Ansible website <http://docs.ansible.com/intro_installation.html> > > Python 3 is a slightly different language than Python 2 and most Python programs (including Ansible) are not switching over yet. However, some Linux distributions (Gentoo, Arch) may not have a Python 2.X interpreter installed by default. On th...
Ansible is using `python` to run the django command: <https://github.com/ansible/ansible-modules-core/blob/devel/web_infrastructure/django_manage.py#L237> Your only solution is thus to override the executable that will be run, for instance by changing your PATH: ``` - file: src=/usr/bin/python3 dest=/home/user/.local...
3,808
25,863,769
I have a set (or a list) of numbers {1, 2.25, 5.63, 2.12, 7.98, 4.77} and i want to find the best combination of numbers from this set/list which when added are closest to 10. How do i accomplish that in python using an element from collection ?
2014/09/16
[ "https://Stackoverflow.com/questions/25863769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1578720/" ]
If the problem size permits, you can use some friends in `itertools` to quickly brute force through it: ``` s = {1, 2.25, 5.63, 2.12, 7.98, 4.77} from itertools import combinations, chain res = min(((comb, abs(sum(comb)-10)) for comb in chain(*[combinations(s, k) for k in range(1, len(s)+1)])), key=lambda x: x[1])[0] ...
It's an NP-Hard problem. If your data are not too big, you can just test every single solution with a code like : ``` def combination(itemList): """ Returns all the combinations of items in the list """ def wrapped(current_pack, itemList): if itemList == []: return [current_pack] el...
3,810
62,787,056
I created virtual environment and installed both tensorflow and tensorflow-gpu. After that I installed keras. And then I checked in my conda terminal by importing keras and I was able to import keras in it. However, using jupyter notebook if I try to import keras then it gives me below error. ``` import keras ImportEr...
2020/07/08
[ "https://Stackoverflow.com/questions/62787056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13605650/" ]
Did you installed the dependencies with conda? Like this: ``` $ conda install -c conda-forge keras $ conda install -c conda-forge tensorflow $ conda install -c anaconda tensorflow-gpu ``` If you installed with `pip` they will not work inside your virtual env. Look at your conda dependencies list, to see if the ...
Doing below solved my issue. So I removed all the packages that were installed via pip and intstalled packages through conda. I had environment issue and created another environment from the scratch and ran below commands. Create virtual environment: ``` conda create -n <env_name> ``` Install tensorflow-gpu via con...
3,811
24,112,445
I am using Python 3.4.0 and I have Mac OSX 10.9.2. I have the following code saved as sublimePygame in Sublime Text. ``` import pygame, sys from pygame.locals import * pygame.init() #set up the window DISPLAYSURF = pygame.display.set_mode((400, 300)) pygame.display.set_caption('Drawing') # set up the colors B...
2014/06/09
[ "https://Stackoverflow.com/questions/24112445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3720830/" ]
Hope this link helps for part 1. Should be able to commit and push your changes using git push heroku master. <https://devcenter.heroku.com/articles/git#tracking-your-app-in-git> For part 2: will scaling your dynos back to 0 work for your case? [How to stop an app on Heroku?](https://stackoverflow.com/questions/2811...
1. When you make a change, just push the git repository to heroku again with`git push heroku master`. The server will automatically restart with the changed system. 2. You seem to have a misconception. You can always run your local development server regardless of what Heroku is doing (unless some other service your ap...
3,812
53,147,752
I am saving a user's database connection. On the first time they enter in their credentials, I do something like the following: ``` self.conn = MySQLdb.connect ( host = 'aaa', user = 'bbb', passwd = 'ccc', db = 'ddd', charset='utf8' ) cursor = self.conn.cursor() cursor.execute("SET NAMES utf8") cur...
2018/11/05
[ "https://Stackoverflow.com/questions/53147752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/651174/" ]
I actually shared my solution to this exact issue. What I did here was create a pool of connections that you can specify the max with, and then queued query requests async through this channel. This way you can leave a certain amount of connections open, but it will queue and pool async and keep the speed you are used ...
I'm no expert in this field, but I believe that [PgBouncer](https://pgbouncer.github.io/features.html) would do the job for you, assuming you're able to use a PostgreSQL back-end (that's one detail you didn't make clear). PgBouncer is a *connection pooler*, which allows you re-use connections avoiding the overhead of c...
3,815
54,494,842
I am totally new to python and basically new to programming in general. I have a college assignment that involves scanning through a CSV file and storing each row as a list. My file is a list of football data for the premier league season so the CSV file is structured as follows: ``` date; home; away; homegoals; awayg...
2019/02/02
[ "https://Stackoverflow.com/questions/54494842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11005752/" ]
One option would be to loop through the `list` ('list1'), `filter` the 'names' column based on the 'names' vector, convert it to a single dataset while creating an identification column with `.id`, `spread` from 'long' to 'wide' and remove the 'grp' column ``` library(tidyverse) map_df(list1, ~ .x %>% ...
A mix of base R and `dplyr`. For every list element we create a dataframe with 1 row. Using `dplyr`'s `rbind_list` row bind them together and then subset only those columns which we need using `names`. ``` library(dplyr) rbind_list(lapply(list1, function(x) setNames(data.frame(t(x$values)), x$names)))[names]...
3,825
70,075,290
I am try update a lambda by zappa, I created virtualenv and active virtualenv and install libraries, but in the moment run zappa update enviroment, I have this problem: How can i fix this :( ``` zappa update qa (pip 18.1 (/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages), Requirement.pars...
2021/11/23
[ "https://Stackoverflow.com/questions/70075290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16488584/" ]
You should wait for function code update to complete before proceeding with update of function configuration. Inserting the following shell script between the steps can keep the process waiting: ``` STATE=$(aws lambda get-function --function-name "$FN_NAME" --query 'Configuration.LastUpdateStatus' --output text) while...
Add to your zappa\_settings.json: ``` "lambda_description": "aws:states:opt-out" ``` [Zappa issue about it](https://github.com/zappa/Zappa/issues/1041)
3,832
20,858,336
I'm using IPython Qt Console and when I copy code FROM Ipython it comes out like that: ``` class notathing(object): ...: ...: def __init__(self): ...: pass ...: ``` Is there any way to copy them without those leading triple dots and doublecolon? P.S. I tried both `Cop...
2013/12/31
[ "https://Stackoverflow.com/questions/20858336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2022518/" ]
This may be too roundabout for you, but you could use the %save magic function to save the lines in question and then copy them from the save file.
I tend to keep an open gvim window for this kind of things. Paste your class definition as is and then do something like: ``` :%s/^.*\.:// ```
3,835
14,198,382
I have some Entrys in a python list.Each Entry has a creation date and creation time.The values are stored as python datetime.date and datetime.time (as two separate fields).I need to get the list of Entrys sorted sothat previously created Entry comes before the others. I know there is a list.sort() function that acce...
2013/01/07
[ "https://Stackoverflow.com/questions/14198382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291096/" ]
You probably want something like: ``` my_entries_list.sort(key=lambda v: datetime.datetime.combine(v.created_date, v.created_time)) ``` Passing `datetime.datetime.combine(created_date, created_time)` tries to call `combine` immediately and breaks since `created_date` and `created_time` are...
Use `lambda`: ``` sorted(my_entries_list, key=lambda e: datetime.combine(e.created_date, e.created_time)) ```
3,844
17,601,602
First, I'm extremely new to coding and self-taught, so models / views / DOM fall on deaf ears (but willing to learn!) So I saved images into a database as blobs (BlobProperty), now trying to serve them. **Relevant Code:** (I took out a ton for ease of reading) ``` class Mentors(db.Model): id = db.StringProperty...
2013/07/11
[ "https://Stackoverflow.com/questions/17601602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/646491/" ]
In the handler, you're getting the ID from `self.request.get('mentor_id')`. However, in the template you've set the image URL to `imageit?key=whatever` - so the parameter is "key" not "mentor\_id". Choose one or the other.
Finally figured it out. I'm using a subdomain, and wasn't setting up *that* route, only /img coming off of the www root. I also wasn't using the URL correctly and the 15th pass of <https://developers.google.com/appengine/articles/python/serving_dynamic_images> finally answered my problem.
3,850
47,528,696
I am new about docker, so ,if any wrong thoughts come from me ,please point out it.Thanks~ I aim at running a web server that was developed by me ,or a team I belong to,in the docker. So, I thought out three steps: Have a image ,copy the web files into it,and run the container.so,I do the step below: 1- get a docke...
2017/11/28
[ "https://Stackoverflow.com/questions/47528696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8948738/" ]
You have docker images and docker container. That is different. You pull or build images. When you launch an image, it becomes a running container. An image is not a running container, and so, you will not be able to copy a file inside an image. I do not know if this what you want to do, but you may 1) launch an ...
I aimed at deploying a python web project by docker,and the first method I thought about is :copy server files to a container and run it with `python ***.py`. But I did not get the difference between images and container. Also,I got some other methods: 1- build a Dcokerfile. By this way,we can run a image with out o...
3,851
35,887,597
I am new in Odoo development. I want to add product brand and country for the products. I just created the form view and menu for the brand under product menu in warehouse. Now I want to add a field for the brand in product view. I am trying to extend the product.product model for it but the model not found error occur...
2016/03/09
[ "https://Stackoverflow.com/questions/35887597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5123488/" ]
This is the jsFiddle with your expectations: [jsFiddle](https://jsfiddle.net/y277r5zL/) as you wanted the yellow border be around the whole content so it was better to extend your wrapper height. ```css #wrapper{ border: 1px solid #F68004; height: 150px; } #content{ background-color: #0075CF; height: ...
try this **CSS** ``` #wrapper{ border: 1px solid #F68004; } #content{ background-color: #0075CF; height: 100px; margin-bottom: 50px; } ```
3,852
54,262,301
I downloaded openCV and YOLO weights, in order to implement object detection for a certain project using Python 3.5 version. when I run this code: ```python from yolo_utils import read_classes, read_anchors, generate_colors, preprocess_image, draw_boxes, scale_boxes from yad2k.models.keras_yolo import yolo_head, yol...
2019/01/18
[ "https://Stackoverflow.com/questions/54262301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10935479/" ]
Actually You are Importing user built module. As Yolo\_utils is created by a Coursera coordinators to make things easy, this module is available in only their machines and You are trying to import this in your machine. Here is github link of module : <https://github.com/JudasDie/deeplearning.ai/blob/master/Convolutiona...
Copy the source code of [yolo\_utils](https://github.com/iArunava/YOLOv3-Object-Detection-with-OpenCV/blob/master/yolo_utils.py) . Paste it in your source code before importing yolo\_utils. It worked for me. Hope this will help..
3,862
10,135,656
I had an existing Django project that I've just added South to. * I ran syncdb locally. * I ran `manage.py schemamigration app_name` locally * I ran `manage.py migrate app_name --fake` locally * I commit and pushed to heroku master * I ran syncdb on heroku * I ran `manage.py schemamigration app_name` on heroku * I ran...
2012/04/13
[ "https://Stackoverflow.com/questions/10135656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722427/" ]
You must fake the migrations that create the tables, then run the other migrations as usual. ``` manage.py migrate app_name 000X --fake manage.py migrate app_name ``` With 000X being the number of the migration in which you create the table.
First of all, from the looks of 0003\_initial and 0005\_initial, you've done multiple `schemamigration myapp --initial` commands which add create\_table statements. Having two sets of these will definitely cause problems as one will create tables, then the next one will attempt creating existing tables. Your `migratio...
3,863
64,160,347
I am trying to replicate a Case Statement within my python script (involving pandas) that is applied to a dataframe and fills a new column based on how each row is processed, but it seems like every row is falling into the else condition due to every value in the new column being `Other`. My first thought is that it is...
2020/10/01
[ "https://Stackoverflow.com/questions/64160347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061892/" ]
I figured out a better approach to the problem. Rather than using contains methods, I decided to run a regex search to see if the combined list values are found within the column row and if they are present, then apply that value. Found below are my updates: **Lists:** ``` fb_landing_page_crit = [ 'utm_source=fac...
Right now, the problem is not the `any` but the `x in df['source_name']` part (I took `source_name` as it is simpler to explain there). You check if any row of the dataframe is *equal* to (e.g.) `'Google'`, not if it contains the word. To achieve the latter, you could nest the `for` statements: ``` ... if any((x in y ...
3,864
58,971,323
I have an assignment in my class to implement something in Java and Python. I need to implement an IntegerStack with both languages. All the values are supposed to be held in an array and there are some meta data values like head() index. When I implement this is Java I just create an Array with max size (that I choos...
2019/11/21
[ "https://Stackoverflow.com/questions/58971323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10137268/" ]
In python, if you declare an array like: ``` myarray = [] ``` You are declaring an empty array with head -1, and you can append values to it with the .append() function and access them the same way you would in java. For all intents and purposes, they are the same thing
It's easer to use collections.deque for stacks in python. ``` from collections import deque stack = deque() stack.append(1) # push stack.append(2) # push stack.append(3) # push stack.append(4) # push t = stack[-1] # your 'head()' tt = stack.pop() # pop if not len(stack): # empty() print("It's empty") ```
3,865
5,325,858
I need to perform http PUT operations from python Which libraries have been proven to support this? More specifically I need to perform PUT on keypairs, not file upload. I have been trying to work with the restful\_lib.py, but I get invalid results from the API that I am testing. (I know the results are invalid becaus...
2011/03/16
[ "https://Stackoverflow.com/questions/5325858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/662525/" ]
httplib should manage. <http://docs.python.org/library/httplib.html> There's an example on this page <http://effbot.org/librarybook/httplib.htm>
[urllib](http://docs.python.org/library/urllib.html) and [urllib2](http://docs.python.org/library/urllib2.html) are also suggested.
3,874
26,699,356
i am using Spyder 2.3.1 under Windows 7 and have a running iPython 2.3 Kernel on a Rasperry Pi RASPBIAN Linux OS. I can connect to an external kernel, using a .json file and this tutorial: [Remote ipython console](https://pythonhosted.org/spyder/ipythonconsole.html) But what now? If I "run" a script (F5), then the ke...
2014/11/02
[ "https://Stackoverflow.com/questions/26699356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4153871/" ]
The tutorial that you mention is a little bit our of date as Spyder now has the ability to connect to remote kernels. The "This is a remote kernel" checkbox, when checked, enables the portion of the dialog where you can enter your ssh connection credentials. (You should need this unless you have manually opened the r...
Another option is to use Spyder cells to send the whole contents of your file to the IPython console. I think this is easier than mounting your remote filesystem with Samba or sshfs (in case that's not possible or hard to do). Cells are defined by adding lines of the form `# %%` to your file. For example, let's say yo...
3,877
74,180,540
i'm trying execute project python in terminal but appear this error: ``` (base) hopu@docker-manager1:~/bentoml-airquality$ python src/main.py Traceback (most recent call last): File "src/main.py", line 7, in <module> from src import VERSION, SERVICE, DOCKER_IMAGE_NAME ModuleNotFoundError: No module named 'src' ...
2022/10/24
[ "https://Stackoverflow.com/questions/74180540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15767572/" ]
Your PYTHONPATH is determined by the directory your python executable is located, not from where you're executing it. For this reason, you should be able to import the files directly, and not from source. You're trying to import from `/src`, but your path is already in there. Maybe something like this might work: ```p...
The interpretor is right. For `from src import VERSION, SERVICE, DOCKER_IMAGE_NAME` to be valid, `src` has to be a module or package accessible from the Python path. The problem is that the `python` program looks in the current directory to search for the modules or packages to run, but the current directory is not add...
3,880
68,555,515
I am pretty new to python and webscraping, but I have managed to get a well working table to print, I am just curious how I would get this table into a CSV file in the exact same format as the print statement. Any logic explanations would be greatly appreciated and very helpful! My code is below... ``` from bs4 import...
2021/07/28
[ "https://Stackoverflow.com/questions/68555515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16523958/" ]
The charges API allows specifying a description. The description can be anything you want. It's your own tidbit of info you can have added to each transaction. When you export transactions on the Stripe site to a CSV, the description can be exported too. I assume it can be extracted with their APIs as well. Would th...
There isn't really a way to do this on the Stripe dashboard, but you can certainly build something like this yourself. You'd start by [retrieving](https://stripe.com/docs/api/checkout/sessions/list) all the Checkout Sessions, then loop over the list and add up the [totals](https://stripe.com/docs/api/checkout/sessions...
3,881
71,213,873
I've been trying to run through this tutorial (<https://bedapub.github.io/besca/tutorials/scRNAseq_tutorial.html>) for the past day and constantly get an error after running this portion: `bc.pl.kp_genes(adata, min_genes=min_genes, ax = ax1)` The error is the following: ``` Traceback (most recent call last): File...
2022/02/21
[ "https://Stackoverflow.com/questions/71213873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18272784/" ]
It seems that `ax.set_yscale("log", basey=10)` does not recognise keyword argument `basey`. This keyword was replaced in the most recent matplotlib releases if you would install an older version it should work: `pip install matplotlib==3.3.4` So why is this happening in the first place? The package you are using does...
I looked for posts with a similar issue ("wrong" keyword calls on **init**) in Github and SO and it seems like you might need to update your matplotlib: ``` sudo pip install --upgrade matplotlib # for Linux sudo pip install matplotlib --upgrade # for Windows ```
3,882
65,383,598
I have read some posts but I have not been able to get what I want. I have a dataframe with ~4k rows and a few columns which I exported from Infoblox (DNS server). One of them is dhcp attributes and I would like to expand it to have separated values. This is my df (I attach a screenshot from excel): [excel screenshot](...
2020/12/20
[ "https://Stackoverflow.com/questions/65383598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13546976/" ]
You seem to be a little confused about [variable scope](https://www.php.net/manual/en/language.variables.scope.php). There's also an errant `$` in `$this->$cards`. While this [is valid syntax](https://www.php.net/manual/en/language.variables.variable.php), it's not doing what you expect. Consider the following to get ...
In this case you don't need a 'global' keyword. Just access your class attributes using $this keyword. ``` class GamesManager extends Main { protected $DB; public $cards = array(); public function __construct() { $this->cards = array('2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8...
3,888
46,234,207
I have a multi-line string: ``` inputString = "Line 1\nLine 2\nLine 3" ``` I want to have an array, each element will have maximum 2 lines it it as below: ``` outputStringList = ["Line 1\nLine2", "Line3"] ``` Can i convert inputString to outputStringList in python. Any help will be appreciated.
2017/09/15
[ "https://Stackoverflow.com/questions/46234207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8595590/" ]
you could try to find 2 lines (with lookahead inside it to avoid capturing the linefeed) or only one (to process the last, odd line). I expanded your example to show that it works for more than 3 lines (with a little "cheat": adding a newline in the end to handle all cases: ``` import re s = "Line 1\nLine 2\nLine 3\n...
I wanted to post the grouper recipe from the itertools docs as well, but [PyToolz' `partition_all`](https://toolz.readthedocs.io/en/latest/api.html#toolz.itertoolz.partition_all) is actually a bit nicer. ``` from toolz import partition_all s = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5" result = ['\n'.join(tup) for tup ...
3,889
47,659,731
My code is running fine for first iteration but after that it outputs the following error: ``` ValueError: matrix must be 2-dimensional ``` To the best of my knowledge (which is not much in python), my code is correct. but I don't know, why it is not running correctly for all given iterations. Could anyone help me i...
2017/12/05
[ "https://Stackoverflow.com/questions/47659731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5507715/" ]
In a comment, you said, > > Yes that is the structure however const items, references, and class items can't be initialized in the body of constructors or in a non-constructor method. > > > A [delegating constructor](http://www.stroustrup.com/C++11FAQ.html#delegating-ctor) can be used to initialize reference memb...
So this is a restriction that you can't initialize const variables other than in the constructor so there is one approach in my mind. You can have one overloaded constructor with all the possible variable types as arguments and the last argument being the integer that represent which argument to take care off assuming ...
3,899
26,978,891
Using Maven I want to create 1) a JAR file for my current project with the current version included in the file name, myproject-version.jar, and 2) an overall artifact in tar.gzip format containing the project's JAR file and all dependency JARs in a lib directory and various driver scripts in a bin directory, but witho...
2014/11/17
[ "https://Stackoverflow.com/questions/26978891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85248/" ]
Just use `${project.artifactId}` as the value for your `finalName` in your assembly configuration. Example derived from your config (note the `finalName` element inside configuration): ``` <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.4.1</version> <con...
I think you are looking for this: <http://maven.apache.org/plugins/maven-assembly-plugin/single-mojo.html#finalName> just put it in the configuration of the plugin. however, i think you shouldn't remove the version if you planning to upload it to some repository.
3,901
612,253
I'm using parallel linq, and I'm trying to download many urls concurrently using essentily code like this: ``` int threads = 10; Dictionary<string, string> results = urls.AsParallel( threads ).ToDictionary( url => url, url => GetPage( url ); ``` Since downloading web pages is Network bound rather than CPU bound, usi...
2009/03/04
[ "https://Stackoverflow.com/questions/612253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30529/" ]
Do the URLs refer to the same server? If so, it could be that you are hitting the HTTP connection limit instead of the threading limit. There's an easy way to tell - change your code to: ``` int threads = 10; Dictionary<string, string> results = urls.AsParallel(threads) .ToDictionary(url => url, ...
Monitor your network traffic. If the URLs are from the same domain it may be limiting the bandwidth. More connections might not actually provide any speed-up.
3,902
20,424,426
I have recently moved from Ubuntu to Mac osx. And my first thing is to bring my vim with me. I downloaded source from vim.org and compiled with gcc.( I'll put the version output at the bottom of my post) I added pathogen.vim to ~/.vim/autoload directory. But when I add the code in ~/.vim/vimrc: ``` execute pathogen#...
2013/12/06
[ "https://Stackoverflow.com/questions/20424426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1914683/" ]
I found the problem. system vimrc file: "$VIM/vimrc" user vimrc file: "$HOME/.vimrc" 2nd user vimrc file: "~/.vim/vimrc" user exrc file: "$HOME/.exrc" I set $VIM to ~/.vim, which is the same as the 2nd user vimrc file. So the vimrc file load twice. After I change $VIM to /etc/vim, everything turns out be good.
I had a similar problem and found that I had not created the ~/.vim directory correctly. I created it in the root by changing directory there and typing mkdir /.vim but for some reason it was not working. Then I deleted this folder and did mkdir ~/.vim and was ably to install and use pathogen.
3,908
33,512,243
I am trying to understand what is a better design choice in the case when we have functions in a Class which does a bunch of things and should either return a string or raise a custom exception when a particular check fails. Example : Suppose I have a class like :- ``` #Division only for +ve numbers class DivisionEr...
2015/11/04
[ "https://Stackoverflow.com/questions/33512243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1982483/" ]
Your problem was due to your adding the JScrollPane and the JTextArea both to the `thePanel` JPanel, and so you see both: a JTextArea **without** JScrollPanes and an empty JScrollPane. * Don't add add the textArea itself to the JScrollPane and also to a JPanel, since you can only add a component to **one** container....
> > Try this : > > > ``` textArea1 = new JTextArea(); textArea1.setColumns(20); textArea1.setRows(5); scroller.setViewportView(textArea1); ```
3,909
67,503,532
When I try to run my localhost server I get the following error: `FileNotFoundError: [Errno 2] No such file or directory: '/static/CSV/ExtractedTweets.csv'` This error is due to the line the line `with open(staticfiles_storage.url('/CSV/ExtractedTweets.csv'), 'r', newline='', encoding="utf8") as csvfile:` This line...
2021/05/12
[ "https://Stackoverflow.com/questions/67503532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403355/" ]
I never found a solution to getting the staticfile path however the find() function seems to be an alternative solution. custommodule.py `from django.contrib.staticfiles.finders import find` `with open(find('CSV/ExtractedTweets.csv'), 'r', newline='', encoding="utf8") as csvfile:`
if you are not looking to deploy this project you can add : ``` from django.conf import settings urlpatterns = [ path(....), path(....), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ``` or you can try to add : ``` STATICFILES_DIRS = [ BASE_DIR / "static", ] ``` to...
3,910
64,483,271
I'm trying install packages through pip, but every package I try to install, it fails with ``` ERROR: Could not find a version that satisfies the requirement numpy (from versions: none) ERROR: No matching distribution found for numpy ``` When running the same command with `-vvv` like `pip install numpy -vvv` it give...
2020/10/22
[ "https://Stackoverflow.com/questions/64483271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4601149/" ]
The main issue is the `alpha` argument together with `geom_line`. If you want the keys to show up as lines you set alpha to 1 in the legend via `guides(color = guide_legend(override.aes = list(alpha = c(1, 1, 1, 1))))`. If you want colored rectangles for the keys this could be achieved by adding `key_glyph = "rect"` to...
The `values` argument from `scale_color_manual` should have color names instead of the line names, which you don't need to pass. Example: ``` scale_color_manual(name="Educational Attainment", values = c("red","yellow","white",...)) ```
3,911
32,400,048
I am trying to edit a .reg file in python to replace strings in a file. I can do this for any other file type such as .txt. Here is the python code: ``` with open ("C:/Users/UKa51070/Desktop/regFile.reg", "r") as myfile: data=myfile.read() print data ``` It returns an empty string
2015/09/04
[ "https://Stackoverflow.com/questions/32400048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3473280/" ]
I am not sure why you are not seeing any output, perhaps you could try: `print len(data)` Depending on your version of Windows, your `REG` file will be saved using UTF-16 encoding, unless you specifically export it using the `Win9x/NT4` format. You could try using the following script: ``` import codecs with codec...
It's probably not a good idea to edit `.reg` files manually. My suggestion is to search for a Python package that handles it for you. I think the [\_winreg](https://docs.python.org/2/library/_winreg.html) Python built-in library is what you are looking for.
3,913
64,256,474
I have to deploy a python project on AWS Lambda function. When I create its zip package it occupies a memory of around 80 MB (Lambda allows upto 50 MB). Also I cannot upload it to s3 because the memory size of the uncompressed package is around 284 MB (S3 allows upto 250 MB). Any idea how to tackle this problem or Is t...
2020/10/08
[ "https://Stackoverflow.com/questions/64256474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9920934/" ]
To work just include this jQuery, Popper.js, and bootstrap js CDN and it will work. Note that jQuery must come first, then Popper.js, and then our JavaScript plugins. for more info click [here](https://getbootstrap.com/docs/4.5/getting-started/download/) ``` <script src="https://code.jquery.com/jquery-3.5.1.slim.min...
You forgot to add the CDN Bootstrap or link your bootstrap javascript at the bottom of the body. Here: ``` <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.clo...
3,914
60,197,890
I'm new to python and running the command: > > pip install pysam > > > Which results in: ``` Collecting pysam Using cached https://files.pythonhosted.org/packages/25/7e/098753acbdac54ace0c6dc1f8a74b54c8028ab73fb027f6a4215487d1fea/pysam-0.15.4.tar.gz ERROR: Command errored out with exit status 1: comma...
2020/02/12
[ "https://Stackoverflow.com/questions/60197890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308743/" ]
There are many binary wheels [at PyPI](https://pypi.org/project/pysam/#files) but only for Linux and MacOS X. [The package at bioconda](https://anaconda.org/bioconda/pysam) is also compiled only for Linux and OS X. When you try to install pysam at Windows `pip` downloads the source distribution `pysam-0.15.4.tar.gz`, ...
if you have anaconda, try this: `conda install -c bioconda pysam`
3,915
57,921,006
I have flask application via python. In my page, there is three images but flask only shows one of them. I could not figure out where is the problem. Here is my code. HTML ==== ``` <div class="col-xs-4"> <img style="width:40%;padding:5px" src="static/tomato.png"/> <br> <button class="btn btn-warning"><a style="colo...
2019/09/13
[ "https://Stackoverflow.com/questions/57921006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11697825/" ]
You can change the route main to mainPage. Try below code ``` @app.route("/mainPage") def index(): return render_template('gui2.html') ```
The error message 404 clear tells that the resource you are looking for was not found in the given location. Make sure that the file exists on the path you give. Simply, as tomato.png file is displayed correctly, just make sure that other files are also in the same location as tomato.png Try opening in Incognito or pr...
3,916
32,075,662
I'm facing a nearly-textbook diamond inheritance problem. The (rather artificial!) example below captures all its essential features: ``` # CAVEAT: error-checking omitted for simplicity class top(object): def __init__(self, matrix): self.matrix = matrix # matrix must be non-empty and rectangular! de...
2015/08/18
[ "https://Stackoverflow.com/questions/32075662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/559827/" ]
`bottom` simply inherits from both; there is nothing specific about your classes that would make this case special: ``` class bottom(middle_0, middle_1): pass ``` Demo: ``` >>> class bottom(middle_0, middle_1): ... pass ... >>> bottom(3, 3).foo() 15 ``` This works as expected because Python arranges both...
I think the > > a class bottom that "gets"1 foo from middle\_0 and \_\_init\_\_ from middle\_1. > > > would be simply done by ``` class bottom(middle_0, middle_1): pass ```
3,917
33,771,929
**Definition**: > > [Bag or Multiset](https://xlinux.nist.gov/dads/HTML/bag.html) is a set data structure which allows duplicate elements, provided the order of retrieval is not significant. > > > Now as I read python documentation it is told that a [Counter](https://docs.python.org/2/library/collections.html#col...
2015/11/18
[ "https://Stackoverflow.com/questions/33771929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/867461/" ]
> > Can we use List or Tuple as a Bag data structure? > > > Yes. It would require some code to get the structure correct, and you'd likely want a list as they are mutable. But you can add duplicates to a list, count them and remove them.
No. * The elements of a bag are unordered and non-unique. * The elements of a Counter are unordered and non-unique. * The elements of a set are unordered and unique. * The elements of a list (and tuple) are ordered and non-unique. A Counter behaves like a bag of m&m's. A list behaves like a pez dispenser - the order ...
3,918
54,483,013
I am using a ScanSnap scanner which generates PDF-1.3 where it will auto-correct the orientation (rotate 0 or 180 degrees) of scanned documents when the PDF is viewed within Adobe Reader. OCR is done by the scanning software and I am assuming the orientation is determined then and encoded into the PDF. Note that I kno...
2019/02/01
[ "https://Stackoverflow.com/questions/54483013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/297500/" ]
The image **Im0** in the resources of the page in "internetfile-180.pdf" is not rotated: [![internetfile-180.pdf image](https://i.stack.imgur.com/DS43A.jpg?s=256)](https://i.stack.imgur.com/DS43A.jpg) But the image **Im0** in the resources of the page in "internetfile.pdf" is rotated: [![enter image description here...
**mkl** answered the question correctly doing all the hard work decoding the PDF for me. I thought I would add in my python (PyPDF2) code to search for the found rotation condition in case it helps someone else. ```py input1 = PyPDF2.PdfFileReader(open(filepath, "rb")) totalPages = input1.getNumPages() for pgNum in r...
3,919
54,044,022
I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is `','`, for the numeric part `';'`. I want to construct a dataframe only out of the numeric part as efficiently as possible. I have made 5 attempts: among them, utilising the `converters` argument of `pd.read_csv`, using...
2019/01/04
[ "https://Stackoverflow.com/questions/54044022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9209546/" ]
### Use a command-line tool By far the most efficient solution I've found is to use a specialist command-line tool to replace `";"` with `","` and *then* read into Pandas. Pandas or pure Python solutions do not come close in terms of efficiency. Essentially, using CPython or a tool written in C / C++ is likely to out...
If this is an option, substituting the character `;` with `,` in the string is faster. I have written the string `x` to a file `test.dat`. ``` def csv_reader_4(x): with open(x, 'r') as f: a = f.read() return pd.read_csv(StringIO(unicode(a.replace(';', ','))), usecols=[3, 4, 5]) ``` The `unicode()` fu...
3,920
21,616,994
I apologize if this question has been answered elsewhere. I havn't been able to find an answer yet through the search here or in the Pandas documentation (quite possible I've just missed it though). I'm trying to import a html file into python through pandas and am unsure how to obtain the data I need from the result....
2014/02/07
[ "https://Stackoverflow.com/questions/21616994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3264279/" ]
`History[0]` will give you the first element. FYI, generally uppercase names are used for classes; variable names are `like_this` These are just conventions; History is a legal identifier.
For each dataframe column you wish to convert to a list, you can transpose the values, and then convert it to a list as follows. Here is an arbitrary DataFrame with one column (if there is more than one column, then slice into columns, and do this for each column): ``` s=DataFrame({'column 1':random.sample(range(10),...
3,929
56,867,659
While debugging `cmd is not recognized` is displayed and program is not debugged. What can be the problem? I have already checked the `path` and `pythonpath` variables and those seem to be just fine ``` bash C:\Users\rahul\Desktop\vscode\.vscode>cd c:\Users\rahul\Desktop\vscode\.vscode && cmd /C "set "PYTHONIOEN...
2019/07/03
[ "https://Stackoverflow.com/questions/56867659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8306141/" ]
> > TL;DR: `cmd` is not in your Windows Environment Path. > [![enter image description here](https://i.stack.imgur.com/9hZxD.png)](https://i.stack.imgur.com/9hZxD.png) > add `%SystemRoot%\system32` to your *System Variables* and restart VSCode. > > > --- Visual Studio Code has actually brought native support fo...
It means that `cmd` is not in your path. Either: * Add the path to the system or user variables in the control panel * Use the full path to `cmd` instead (typically `C:\Windows\System32\cmd.exe`), meaning something like: `cd c:\Users\rahul\Desktop\vscode\.vscode && C:\Windows\System32\cmd.exe /C "set "PYTHONIOENCODIN...
3,930
14,506,717
I need to print some information directly (without user confirmation) and I'm using Python and the `win32print` module. I've already read the whole [Tim Golden win32print page](http://timgolden.me.uk/python/win32_how_do_i/print.html) (even read the [win32print doc](http://timgolden.me.uk/pywin32-docs/win32print.html)...
2013/01/24
[ "https://Stackoverflow.com/questions/14506717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1814970/" ]
I'm still looking for the best way to do this, but I found an answer that satisfy myself for the problem that I have. In Tim Golden's site (linked in question) you can find this example: ``` import win32ui import win32print import win32con INCH = 1440 hDC = win32ui.CreateDC () hDC.CreatePrinterDC (win32print.GetDefa...
``` # U must install pywin32 and import modules: import win32print, win32ui, win32con # X from the left margin, Y from top margin # both in pixels X=50; Y=50 # Separate lines from Your string # for example:input_string and create # new string for example: multi_line_string multi_line_string = input_string.splitli...
3,932
56,612,386
I am trying to use the pre-made estimator `tf.estimator.DNNClassifier` to use on the MNIST dataset. I load the dataset from `tensorflow_dataset`. I pursue the following four steps: first building the dataset pipeline and defining the input function: ```py ## Step 1 mnist, info = tfds.load('mnist', with_info=True) ds...
2019/06/15
[ "https://Stackoverflow.com/questions/56612386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2191236/" ]
I think the graph construction gets weird if you load a tensorflow\_datasets dataset outside the `input_fn`. I followed the TF2.0 migration guide example and this does not give errors. Please note that I have not tested for model correctness and you will have to modify `input_fn` logic a bit to get the function for eva...
Answer by @dgumo is correct. I just wanted to add a basic example. All tensors returned by the input function must be created within the input function. ```py #Raw data can be outside data_x = [0.0, 1.0, 2.0, 3.0, 4.0] data_y = [3.0, 4.9, 7.3, 8.65, 10.75] def supply_input(): #Tensors must be created inside the fu...
3,935
17,363,611
My code works perfectly, but I want it to write the values to a text file. When I try to do it, I get 'invalid syntax'. When I use a python shell, it works. So I don't understand why it isn't working in my script. I bet it's something silly, but why wont it output the data to a text file?? ``` #!/usr/bin/env python ...
2013/06/28
[ "https://Stackoverflow.com/questions/17363611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519572/" ]
`lis` is an empty list, *any* index will raise an exception. If you wanted to add elements to that list, use `lis.append()` instead. Note that you can loop over sequences *directly*, there is no need to keep your own counter: ``` def front_x(words): lis = [] words.sort() for word in words: if wo...
> > i need to sort the list but the words starting with x should be the first ones. > > > Complementary to the custom search key in @Martijn's extended answer, you could also try this, which is closer to your original approach and might be easier to understand: ``` def front_x(words): has_x, hasnt = [], [] ...
3,936
9,570,637
Working on getting Celery setup (following the basic tutorial) with a mongodb broker as backend. Following the configuration guidelines set out in the official docs, my `celeryconfig.py` is setup as follows: ``` CELERY_RESULT_BACKEND = "mongodb" BROKER_BACKEND = "mongodb" BROKER_URL = "mongodb://user:pass@subdomain.m...
2012/03/05
[ "https://Stackoverflow.com/questions/9570637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/215608/" ]
I think it's a bug. Celery passed hostname instead of server\_uri to kombu, thus cause this problem. After tracing the code, I found the following conf to bypass the bug before they fixed it. ``` CELERY_RESULT_BACKEND = 'mongodb' BROKER_HOST = "subdomain.mongolab.com" BROKER_PORT = 123456 BROKER_TRANSPORT = 'mongodb' ...
Would it help if you remove "user", "pass", "port", and "database" from the CELERY\_MONGODB\_BACKEND\_SETTINGS dict, and do: ``` BROKER_URL = "mongodb://user:pass@subdomain.mongolab.com:123456/testdb" CELERY_MONGODB_BACKEND_SETTINGS = { "host":BROKER_URL, "taskmeta_collection":"taskmeta", } ```
3,937
23,320,954
how to replace '1c' to '\x1c' in python. I have a list with elements like '12','13' etc and want to replace with '\x12', '\x13' etc. here is what i tried and failed ``` letters=[] for i in range(10,128,1): a=(str(hex(i))).replace('0x','\x') letters.append(a) print letters ``` **I need is '31' t...
2014/04/27
[ "https://Stackoverflow.com/questions/23320954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3559830/" ]
You need to use the built-in function [`chr`](https://docs.python.org/2/library/functions.html#chr) to return the correct ascii code (which is the string you are after): ``` >>> [chr(i) for i in range(10,20,1)] ['\n', '\x0b', '\x0c', '\r', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13'] ```
Your code is fine, you just need to escape the `\` with a `\`. ``` letters=[] for i in range(10,128,1): a=(str(hex(i))).replace('0x','\\x') #you have to escape the \ letters.append(a) print letters ``` [DEMO ----](http://repl.it/Rvl/1)
3,938
4,740,473
After studying this page: <http://docs.python.org/distutils/builtdist.html> I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file). Could the s.o. community point me towards some good examples?
2011/01/19
[ "https://Stackoverflow.com/questions/4740473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62255/" ]
**Minimal example** ``` from setuptools import setup, find_packages setup( name="foo", version="1.0", packages=find_packages(), ) ``` More info in [docs](https://packaging.python.org/tutorials/packaging-projects/)
Here you will find the simplest possible example of using distutils and setup.py: <https://docs.python.org/2/distutils/introduction.html#distutils-simple-example> This assumes that all your code is in a single file and tells how to package a project containing a single module.
3,940
46,229,543
I have written a fraction adder in Python for my computer science class. However, I am running into problems with the final answer reduction procedure. The procedure uses the "not equal" comparison operator **!=** at the start of a **for** loop to test whether, when dividing the numerator and denominator, there will b...
2017/09/14
[ "https://Stackoverflow.com/questions/46229543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8580749/" ]
The error you see is derived by the wrong usage of `for` where `while` is the right type of loop (`for` is for iteration, `while` for condition). Nevertheless, your logic at deciding the common denominators is flawed, and leads to an infinite loop. Please read about [least common multiple](https://en.wikipedia.org/wik...
You are trying to write a greatest-common-denominator finder, and your terminating condition is wrong. [Euclid's Algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) repeatedly takes takes the modulo difference of the two numbers until the result is 0; then the next-to-last result is the GCD. The standard pyth...
3,950
16,514,570
I can get matplotlib to work in pylab (ipython --pylab), but when I execute the same command in a python script a plot does not appear. My workspace focus changes from a fullscreened terminal to a Desktop when I run my script, which suggests that it is trying to plot something but failing. The following code works in ...
2013/05/13
[ "https://Stackoverflow.com/questions/16514570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3749393/" ]
I believe you need `plt.show()` .
You need to add `plt.show()` after `plt.plot(...)`. `plt.plot()` just makes the plot, `plt.show()` takes the plot you made and displays it on the screen.
3,951
44,057,032
my python program isn't working properly and it's something with the submit button and it gives me an error saying: ``` TypeError: 'str' object is not callable ``` help please. Here is the part of the code that doesn't work: ``` def submit(): g_name = ent0.get() g_surname = ent1.get() g_dob = ent2.get()...
2017/05/18
[ "https://Stackoverflow.com/questions/44057032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8033270/" ]
`childByAutoId()` is for the iOS SDK. For `admin.Database()`, use [push()](https://firebase.google.com/docs/reference/admin/node/admin.database.Reference#push). ``` var reference = admin.database().ref(path).push(); ```
It should work like this: ``` exports.addPersonalRecordHistory = functions.database.ref('/personalRecords/{userId}/current/{exerciseId}').onWrite(event => { var path = 'personalRecords/' + event.params.userId + '/history/' + event.params.exerciseId; return admin.database().ref(path).set({ username: "asd", ...
3,952
14,626,189
> > **Possible Duplicate:** > > [python looping seems to not follow sequence?](https://stackoverflow.com/questions/4123266/python-looping-seems-to-not-follow-sequence) > > [In what order does python display dictionary keys?](https://stackoverflow.com/questions/4458169/in-what-order-does-python-display-dictionary...
2013/01/31
[ "https://Stackoverflow.com/questions/14626189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1990185/" ]
A dictionary is a mapping of keys to values; it does not have an order. You want a `collections.OrderedDict`: ``` collections.OrderedDict([('x', 9), ('y', 10), ('z', 20)]) Out[175]: OrderedDict([('x', 9), ('y', 10), ('z', 20)]) for key in Out[175]: print Out[175][key] ``` Note, however, that dictionary orderin...
A dictionary is a collection that is not ordered. So in theory the order of the elements may change on each operation you perform on it. If you want the keys to be printed in order, you will have to sort them before printing(i.e. collect the keys and then sort them).
3,953
70,023,042
I was wondering if anyone can help. I'm trying to take a CSV from a GCP bucket, run it into a dataframe, and then output the file to another bucket in the project, however using this method my dag is running but i dont im not getting any outputs into my designated bucket? My dag just takes ages to run. Any insight on t...
2021/11/18
[ "https://Stackoverflow.com/questions/70023042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12176250/" ]
With broadcasting ``` res = np.where(arr0[...,None] == entries, arr1[...,None], 0).max(axis=(0, 1)) ``` The result of `np.where(...)` is a (3, 3, 4) array, where slicing `[...,0]` would give you the same 3x3 array you get by manually doing the `np.where` with just `entries[0]`, etc. Then taking the max of each 3x3 s...
It's more convenient to work in 1D case. You need to sort your `arr0` then find starting indices for every group and use `np.maximum.reduceat`. ``` arr0_1D = np.array([[0,3,0],[1,3,2],[1,2,0]]).ravel() arr1_1D = np.array([[4,5,6],[6,2,4],[3,7,9]]).ravel() arg_idx = np.argsort(arr0_1D) >>> arr0_1D[arg_idx] array([0, 0,...
3,954
35,346,971
I'm having some problems with inheritance. I need to import simplejson or install if it can't be found and import. I'm doing this in a another class and sending it via inheritance where needed. The way I'm doing it here works in python 2.6+ but not in 2.4. ``` # This class will hold all things needed over in all class...
2016/02/11
[ "https://Stackoverflow.com/questions/35346971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4840281/" ]
I know this is not the question, but you should not be using subprocess.popen for this. Use pip. It's great. ``` try: import simplejson as json except ImportError: import pip try: import os isAdmin = os.getuid() == 0 except AttributeError: import ctypes isAdmin = ctypes....
`apt-get install` won't guarantee that you are installing `simplejson` for all versions of python. It will only work for the *system installed* version of Python which may or may not be 2.4. That's going to depend highly on what underlying version of Linux or Ubuntu or Debian you are using. If you want to be portable a...
3,955
1,900,956
Let's say I have the following dictionary in a small application. ``` dict = {'one': 1, 'two': 2} ``` What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ...
2009/12/14
[ "https://Stackoverflow.com/questions/1900956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55366/" ]
the `repr` function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name. ``` >>> dict = {'one': 1, 'two': 2} >>> repr(dict) "{'two': 2, 'on...
You could do: ``` import inspect mydict = {'one': 1, 'two': 2} source = inspect.getsourcelines(inspect.getmodule(inspect.stack()[0][0]))[0] print([x for x in source if x.startswith("mydict = ")]) ``` Also: make sure not to shadow the dict builtin!
3,958
62,933,026
I am new to python and I am trying to loop through the list of urls in a `csv` file and grab the website `title`using `BeautifulSoup`, which I would like then to save to a file `Headlines.csv`. But I am unable to grab the webpage `title`. If I use a variable with single url as follows: ``` url = 'https://www.space.com...
2020/07/16
[ "https://Stackoverflow.com/questions/62933026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13122812/" ]
As the previous answer has already mentioned about the "\ufeff", you would need to change the encoding. The second issue is that when you read a CSV file, you will get a list containing all the columns for each row. The keyword here is list. You are passing the request a list instead of a string. Based on the example...
You have a byte order mark `\\ufeff` on the URL you parse from your file. It looks like your file is a signature file and has encoding like utf-8-sig. You need to read with the file with `encoding='utf-8-sig'` Read more [here](https://stackoverflow.com/a/49150749/7502914).
3,968
31,039,972
I am trying to run a Python script from another Python script, and getting its `pid` so I can kill it later. I tried `subprocess.Popen()` with argument `shell=True', but the`pid`attribute returns the`pid` of the parent script, so when I try to kill the subprocess, it kills the parent. Here is my code: ```py proc = s...
2015/06/25
[ "https://Stackoverflow.com/questions/31039972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4759209/" ]
`shell=True` starts a new shell process. `proc.pid` is the pid of that shell process. `kill -9` kills the shell process making the grandchild python process into an orphan. If the grandchild python script can spawn its own child processes and you want to kill the whole process tree then see [How to terminate a python ...
So run it directly without a shell: ``` proc = subprocess.Popen(['python', './script.py']) ``` By the way, you may want to consider changing the hardcoded `'python'` to [`sys.executable`](https://docs.python.org/3.5/library/sys.html#sys.executable). Also, you can use [`proc.kill()`](https://docs.python.org/3.5/libra...
3,969
47,403,218
-I am successfully logged into my Virtual Machine and I have uploaded my files to the AWS as well (Amazon EC2). What I wish to do is execute my python code on the server but it says that the dependencies are not installed. When I run a pip install command, it returns the following error: PermissionError: [Errno 13] Pe...
2017/11/21
[ "https://Stackoverflow.com/questions/47403218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8888799/" ]
Assuming you have the number 3 in cell A1 on Sheet2, the following will display the value of column A in the row that has rank 3 in Sheet1 This can be copied down in Sheet2 if you have other numbers in the rows below ``` =INDEX(Sheet1!A:AH,MATCH($A1,Sheet1!$AH:$AH,0),1) ```
Sounds like you need `INDEX/MATCH` like this `=INDEX(Sheet1!A:A,MATCH(3,Sheet1!AH:AH,0))` The `MATCH` function finds the position of 3 in column `AH` and then the `INDEX` function returns the value from column `A` in the same row. Is that what you need?
3,970
45,046,601
I have this weird problem that can be reproduced with the [simple tutorial](https://docs.docker.com/compose/django/) from Docker. If I follow the tutorial exactly, everything would work fine, i.e. after `docker-compose up` command, the web container would run and connect nicely to the db container. However, if I ch...
2017/07/12
[ "https://Stackoverflow.com/questions/45046601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3814824/" ]
Use [wait-for-it.sh](https://github.com/vishnubob/wait-for-it) to wait for Postgres to be ready: Download this well known script: <https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh> ``` version: '3' services: db: image: postgres web: build: . command: /wait-for-it.sh db:54...
You can use [healthcheck](https://docs.docker.com/compose/compose-file/#healthcheck). example from: [peter-evans/docker-compose-healthcheck: How to wait for container X before starting Y using docker-compose healthcheck](https://github.com/peter-evans/docker-compose-healthcheck#waiting-for-postgresql-to-be-healthy) `...
3,971
40,062,854
i want to see some info and get info about my os with python as in my tutorial but actually can't run this code: ``` import os F = os.popen('dir') ``` and this : ``` F.readline() ' Volume in drive C has no label.\n' F = os.popen('dir') # Read by sized blocks F.read(50) ' Volume in drive C has no labe...
2016/10/15
[ "https://Stackoverflow.com/questions/40062854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4716040/" ]
The problem is you can't save your custom array in NSUserDefaults. To do that you should change them to NSData then save it in NSUserDefaults Here is the code I used in my project it's in swift 2 syntax and I don't think it's going be hard to convert it to swift 3 ``` let data = NSKeyedArchiver.archivedDataWithRootObj...
The closest type to a Swift struct that UserDefaults supports might be an NSDictionary. You could copy the struct elements into an Objective C NSDictionary object before saving the data.
3,973
65,849,470
I am writing a unit test in python for a function that takes an object from an S3 bucket as the input parameter. The input parameter is of type `boto3.resources.factory.s3.ObjectSummary`. I don't want my unit test to access S3. I am writing a test that reads a .csv file into an object of type `pandas.core.frame.Dat...
2021/01/22
[ "https://Stackoverflow.com/questions/65849470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15061060/" ]
The answer is you shouldn't have a `loadingData()` Redux action in the first place. Loading or not is, as you correctly pointed out, every component's "local" state, so you should store it appropriately - inside each component's "normal" state. Redux store is designed for storing the data that is mutual to several com...
There is good practice that you have `loading` for each `subject` you're calling a backend `api`, for example a `loading` for calling `books` api, a `loading` for calling `movies` api and so on. I recommend you create a `loadings` object in your state and fill it with different loadings that you need like this: ``` l...
3,977
10,572,671
I'm new to c/c++ and I've been working with python for a long time, I didn't take any tutorials, but I got this error when I tried to declare an array of strings. code: ``` QString months[12]={'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'}; ``` error: invalid conversion from 'int' to ...
2012/05/13
[ "https://Stackoverflow.com/questions/10572671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164958/" ]
Use double quotes for strings (`"`). `'` is for character literals.
In the Python is not difference between `'` and `"`(are strings) , but in the C++ They are different: ``` char c = 'c'; string str = "string"; ``` Don't forget the C++ has not `'''`, while it was as string in Python. Your code: ``` ... "Oct", "Nov", "Dec"}; ```
3,980
63,381,325
i am using a python script with regex module trying to process 2 files and create a final output as required but getting some errors. cat links.txt ``` https://videos-a.jwpsrv.com/content/conversions/7kHOkkQa/videos/XXXXJD8C-32313922.mp4.m3u8?hdnts=exp=1596554537~acl=*/bGxpJD8C-32313922.mp4.m3u8~hmac=2ac95222f1693d11...
2020/08/12
[ "https://Stackoverflow.com/questions/63381325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13516930/" ]
If you are using regular expressions anyway, why not use them to pull out this information, too? ```py import re base = 'https://cdn.jwplayer.com/videos/' kek = re.compile(r'(?<=\/)[\w\-\.]+(?=.m3u8)') nre = re.compile(r'(.*)\s+Lecture (\d+)(.*)') with open('name.txt') as b: lecture = [] for line in b: parse...
The issue is with the last line of cat names.txt. ``` >>> line = "Labour Costing Lecture 352 (Classroom Lecture)" >>> [c for c in line.rpartition(' ')[2]] ['L', 'e', 'c', 't', 'u', 'r', 'e', ')'] ``` Clearly not what you are intending to extract. Since none of these is a number, it returns an empty string which cann...
3,981
45,026,566
i was try to use python API but its not working if i try to use multiple parameter **Not working** ``` from flask import Flask, request @app.route('/test', methods=['GET', 'POST']) def test(): req_json = request.get_json(force=True) UserName = req_json['username'] UserPassword = req...
2017/07/11
[ "https://Stackoverflow.com/questions/45026566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6472692/" ]
as you can see in the logs ,the app crashed due to indentation error. please check indentation of account\_sid variable in your code.
The hint is in your logs. ``` 2017-07-11T06:44:16.078195+00:00 app[web.1]: File "server.py", line 29 2017-07-11T06:44:16.078211+00:00 app[web.1]: account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID) 2017-07-11T06:44:16.078211+00:00 app[web.1]: ^ 2017-07-11T06:44:16.078213+00:00 app[web.1]: IndentationErr...
3,982
28,619,302
I'M using pycharm (python) (and mapnik)on windows 7, I just wanted to test if everything is in place after installation. I used an example from the net here is it , and I have a frame error. Could it be an installation problem ? compiler ?? I'M very new to python. thanks in advance for your time. ``` """ This is a sim...
2015/02/19
[ "https://Stackoverflow.com/questions/28619302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4586167/" ]
A little insight on your code first: `all` will fetch ALL records from the database and pass it to your ruby code, this is resource and time consuming. Then the `shuffle`, `sort_by` and `reverse` are all executed by ruby. You will quickly hit performance issues as your database grow. Your solution is to let your datab...
Hmm, here's a fun hack that *should* work: ``` @articles = Article. all. sort_by{|t| (t.date_published.beginning_of_day.to_i * 1000) + rand(100)} ``` This works by forcing all the dates to be the beginning of the day (so that everything published on '2015-02-19' for example will have the same `to_i` value. Then ...
3,985
12,121,260
I've run into a specific problem and thought of an solution. But since the solution is pretty involved, I was wondering if others have encountered something similar and could comment on best practises or propose alternatives. The problem is as follows: I have a webapp written in Django which has some screen in which d...
2012/08/25
[ "https://Stackoverflow.com/questions/12121260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227852/" ]
I tried something similar and you might be interested in the solution. Here is my question: [python Socket.IO client for sending broadcast messages to TornadIO2 server](https://stackoverflow.com/questions/10950365/python-socket-io-client-for-sending-broadcast-messages-to-tornadio2-server) And this is the answer: <ht...
The scheme Google implemented for the now abandoned Wave product's concurrent editing features is documented, <http://www.waveprotocol.org/whitepapers/operational-transform>. This aspect of Wave seemed like a success, even though Wave itself was quickly abandoned. As far as the questions you asked about implementing y...
3,986
40,499,702
I‘m studying the tensoflow, and want to test the example of slim. When I command ./scripts/train\_lenet\_on\_mnist.sh, The program run to eval\_image\_classifier give a Type Error, The Error information as follows: ``` I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcublas.so.8.0 lo...
2016/11/09
[ "https://Stackoverflow.com/questions/40499702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7134638/" ]
The problem is the compatible of `python2` and `python3`. As I used `python3` for interpretation, but the the Keys From a Dictionary is different from p`ython2` and `python3`. In `Python2`, simply calling `keys()` on a dictionary object will return what you expect, however, in `Python3`, `keys()` no longer returns a ...
The other python3 change for eval\_image\_classifier.py is ``` for name, value in names_to_values.iteritems(): to for name, value in names_to_values.items(): ```
3,987
56,689,803
I'm trying to remove some part of text in the given string. So the problem is as follows. I have a string. Say HTML code like this. ``` <!DOCTYPE html> <html> <head> <style> body {background-color: powderblue;} h1 {color: blue;} p {color: red;} </style> </head> <body> <h1>This is a ...
2019/06/20
[ "https://Stackoverflow.com/questions/56689803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7928692/" ]
You put the `$` which means end of string. try this: ``` x = re.sub('<style>.*?</style>', '', text, flags=re.DOTALL) print(x) ``` You can check out [this website](https://regex101.com/r/Fti1aD/1), has a nice regex demo. **A little note**: I am not extremely familiar with CSS so if there are nested `<style>` tags it...
Note particularly the `?` character in the `<style>(.*?)</style>` portion of the RegExp expression so as not to be "too greedy". Otherwise, in the example below, it would also remove the `<title>` HTML tag. ``` import re text = """ <!DOCTYPE html> <html> <head> <style> body {background-color: powderblue;} ...
3,988
33,984,889
I want to use an array and its first derivative (diff) as features for training. Since the diff array is of an smaller size I would like to fill it up so that I don't have problems with sizes when I stack them and use both as features. If I fill the diff(array) with a 0, How should I align them? Do I put the 0 at the...
2015/11/29
[ "https://Stackoverflow.com/questions/33984889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1978146/" ]
Instead of left- or right-sided finite differences, you could use a centered finite difference (which is equivalent to taking the average of the left- and right-sided differences), and then pad both ends with appropriate approximations of the derivatives there. This will keep the estimation of the derivative aligned wi...
According to the [documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html), diff is simply doing `out[n] = a[n+1] - a[n]`. This means that it is not a derivative approximated by finite difference, but the discrete difference. To calculate the finite difference, you need to divide by the step ...
3,989
38,596,674
I bet I am doing something very simple wrong. I want to start with an empty 2D numpy array and append arrays to it (with dimensions 1 row by 4 columns). ``` open_cost_mat_train = np.matrix([]) for i in xrange(10): open_cost_mat = np.array([i,0,0,0]) open_cost_mat_train = np.vstack([open_cost_mat_train,open_co...
2016/07/26
[ "https://Stackoverflow.com/questions/38596674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3948664/" ]
If `open_cost_mat_train` is large I would encourage you to replace the for loop by a **vectorized algorithm**. I will use the following funtions to show how efficiency is improved by vectorizing loops: ``` def fvstack(): import numpy as np np.random.seed(100) ocmt = np.matrix([]).reshape((0, 4)) for i ...
You need to reshape your original matrix so that the number of columns match the appended arrays: ``` open_cost_mat_train = np.matrix([]).reshape((0,4)) ``` After which, it gives: ``` open_cost_mat_train # matrix([[ 0., 0., 0., 0.], # [ 1., 0., 0., 0.], # [ 2., 0., 0., 0.], # [ 3.,...
3,990
23,280,253
I have the following code - ``` from sys import version class ExampleClass(object): def get_sys_version(self): return version x = ExampleClass() print x.get_sys_version() ``` and it gets parsed by this code - ``` import ast source = open("input.py") code = source.read() node = ast.parse(...
2014/04/24
[ "https://Stackoverflow.com/questions/23280253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/827401/" ]
This is because you're using `mode='eval'`, which only works for single expressions. Your code has multiple statements, so use `mode='exec'` instead. (It's the default) See the [documentation for `compile()`](https://docs.python.org/2/library/functions.html#compile) for explanation of the `mode` argument, since that's...
It's not related to `ast`. You get same error, when try: ``` In [1]: eval('from sys import version') File "<string>", line 1 from sys import version ^ SyntaxError: invalid syntax ``` Try `exec` mode: ``` In [1]: exec('from sys import version') In [2]: ```
3,991
48,821,856
I would like to clean a list from leading occurrences of `'a'`. That is, `['a', 'a', 'b', 'b']` should become `['b', 'b']` and at the same time `['b', 'a', 'a', 'b']` should be kept unchanged. ``` def remove_leading_items(l): if len(l) == 1 or l[0] != 'a': return l else: return remove_leading_i...
2018/02/16
[ "https://Stackoverflow.com/questions/48821856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/671013/" ]
Yes. Immediately, you should be using a for loop. Recursion is generally not Pythonic. Second, use built in tools: ``` from itertools import dropwhile def remove_leading_items(l, item): return list(dropwhile (lambda x: x == item, l)) ``` Or ``` return list(dropwhile(item.__eq__, l)) ``` ### Edit Out of curi...
### Code: ``` def remove_leading(a_list, to_remove): i = 0 while i < len(a_list) and a_list[i] == to_remove: i += 1 return a_list[i:] ``` ### Test Code: ``` print(remove_leading(list('aabb'), 'a')) print(remove_leading(list('baab'), 'a')) print(remove_leading([], 'a')) ``` ### Results: ``` [...
3,992
50,534,429
I made a FC neural network with numpy based on the video's of welch's lab but when I try to train it I seem to have exploding gradients at launch, which is weird, I will put down the whole code which is testable in python 3+. only costfunctionprime seem to break the gradient descent stuff going but I have no idea what ...
2018/05/25
[ "https://Stackoverflow.com/questions/50534429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7974205/" ]
This conversion works. ``` #string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray(); String[] path = {"1","2","3"}; int[] numb = Array.ConvertAll(path,int.Parse); for (int i = 0; i < path.Length; i++) { Console.WriteLine(path[i]); } for (int i = 0; i < numb.Length; i++) { Console.WriteLine(num...
I can't imagine this wouldn't work: ``` string[] path = File.ReadAllLines("C:\\Users\\M\\numb.txt"); int[] numb = new int[path.Length]; for (int i = 0; i < path.Length; i++) { numb[i] = int.Parse(path[i]); } ``` I think your issue is that you are using `File.ReadLines`, which reads each line into a single strin...
3,995
45,916,726
here is my output.txt file ``` 4f337d5000000001 4f337d5000000001 0082004600010000 0082004600010000 334f464600010000 334f464600010000 [... many values omitted ...] 334f464600010000 334f464600010000 4f33464601000100 4f33464601000100 ``` how i can change these values into decimal with the help of python and save into a...
2017/08/28
[ "https://Stackoverflow.com/questions/45916726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8523601/" ]
Since the values are 16 hex digits long I assume these are 64-bit integers you want to play with. If the file is reasonably small then you can use `read` to bring in the whole string and `split` to break it into individual values: ``` with open("newfile.txt", 'w') as out_file, open("outfile,txt") as in_file: for h...
You can do this: ``` with open('output.txt') as f: new_file = open("new_file.txt", "w") for item in f.readlines(): new_file.write(str(int(item, 16)) + "\n") new_file.close() ```
3,997
29,692,140
If we make a pathological potato like this: ``` >>> class Potato: ... def __eq__(self, other): ... return False ... def __hash__(self): ... return random.randint(1, 10000) ... >>> p = Potato() >>> p == p False ``` We can break sets and dicts this way (*note:* it's the same even if `__eq__` r...
2015/04/17
[ "https://Stackoverflow.com/questions/29692140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
`list`, `tuple`, etc., does indeed do an identity check before an equality check, and this behavior is motivated by [these invariants](http://bugs.python.org/issue4296#msg75735): ``` assert a in [a] assert a in (a,) assert [a].count(a) == 1 for a in container: assert a in container # this should ALWAYS be true ...
In general, breaking the assumption that identity implies equality can break a variety of things in Python. It is true that NaN breaks this assumption, and thus NaN breaks some things in Python. Discussion can be found in [this Python bug](http://bugs.python.org/issue4296). In a pre-release version of Python 3.0, relia...
4,000