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
62,745,685
I am a beginner in Python. Here's what I am trying to do : ```python import numpy as np r10 = np.array([[i for i in range(0,10)],[i*10 for i in range(0,10)]]).T r6 = np.array([[i for i in range(0,6)],[i*10 for i in range(0,6)]]).T r_comb = np.array([[r10],[r6]]).T np.savetxt('out.txt',r_comb) ``` Using np.savetxt g...
2020/07/05
[ "https://Stackoverflow.com/questions/62745685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13872751/" ]
How about using a ref as the gatekeepr ``` function useEffectIfReady(fn, deps = [], isReady = true) { const readyWasToggled = useRef(isReady); /* There are 2 states: 0 - initial 1 - ready was toggled */ const getDep = () => { if (readyWasToggled.current) { return 1; } if (isReady...
Try splitting the useEffect in this case for each state, just an idea based on your codes ``` useEffect(() => { // your codes here if (!isTrue) { return; } }, [isTrue]); useEffect(() => { // your another set of codes here someFunction(dep); }, [dep]) ```
1,707
66,015,125
I am running python3.9 on ubuntu 18.04. I already went ahead and rand the command `sudo apt-get install python-scipy` and got the message: ``` Reading package lists... Done Building dependency tree Reading state information... Done python-scipy is already the newest version (0.19.1-2ubuntu1). The following pack...
2021/02/02
[ "https://Stackoverflow.com/questions/66015125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13972346/" ]
Maybe try ```sh python3.9 -m pip install scipy --user ``` which would use pip of python3.9 to install the package to a place without sudo privilege
Try `pip3 install scipy`, if that returns an `ERRNO 13: access denied` then try `pip3 install scipy --user`
1,712
31,568,936
I am using Selenium webdriver with firefox. I am wondering if there is a setting i can change such that it to only requesting resources from certain domains. (Specifically i want it only to request content which is on the same domain as the webpage itself). My current set up, written in Python, is: ```python from se...
2015/07/22
[ "https://Stackoverflow.com/questions/31568936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2801069/" ]
With thanks to Vicky, (who's approach of using Proxy settings i followed - although directly from Selenium), the code below will change the proxy settings in firefox such that it will not connect to a domain except that on the white-list. I suspect several setting changes are unnecessary and can be omitted for most pu...
I think it is still impossible in selenium.But you can still achieve this by using proxies like browsermob. Webdriver integrates well with [browsermob](https://github.com/lightbody/browsermob-proxy) proxy. **Sample pseudeocode in java** ```java //LittleProxy-powered 2.1.0 release LegacyProxyServer server = n...
1,715
61,424,762
I am a beginner in python. I am currently building an online video study website like Udemy and Treehouse using Flask. The little issue is that, the videos on the site can be downloaded by viewing or inspecting the source code. Browsers with video download extension (firefox, Chrome etc) can easily download videos when...
2020/04/25
[ "https://Stackoverflow.com/questions/61424762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12172995/" ]
I don't think the problem comes from the flask side, but from the frontend side. So you might check if this is possible through javascript. I quickly looked into it and saw the question below: I think you are facing a problem related to that mentioned in - [Prevent HTML5 video from being downloaded (right-click saved)...
You have a couple of options here to make it more difficult, in order of difficulty: 1. You absolutely can use .htaccess (it is a web server feature--nothing to do with PHP) to require the referrer to be your site. Don't allow access to the video file if the referrer doesn't contain your site. ([See here for how to do...
1,716
58,487,038
I have a `while` loop that exits when an `if(condition){break;}` is met, after an unknown number of iterations. Inside the `while` loop, a function is called, that will return an array of variable size at every iteration. I know in `python` I could just append the arrays one to each other, and in the end I would have a...
2019/10/21
[ "https://Stackoverflow.com/questions/58487038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9104884/" ]
You need to store store the zeros in `foo` independently from the values returned by `find_zeros`, as you would in Python, where you'd have separate variables `zeros_list` and `zeros`. Python's `list.append` method is realized in two steps: first the array is reallocated to new capacity with `realloc` (you already hav...
regarding your question: *// append the zeros somewhere (how?!)* the easiest way is a call to `memcpy()` similar to: ``` memcpy( &zeros[ last used offset ], newXeros, sizeof( newzeros ) ); ```
1,717
35,241,760
I'm running this every minute to debug and it keeps returning with `com.apple.xpc.launchd[1] (com.me.DesktopChanger[16390]): Service exited with abnormal code: 2` ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist ver...
2016/02/06
[ "https://Stackoverflow.com/questions/35241760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3042759/" ]
You can use the `reduce` method. ``` let placeNames = results.reduce("") { (placeNames, place) -> String in return placeNames + place.name + " " } ``` Now you have a single `String` with the concatenation of all the place names. Short notation -------------- You can also write it as follow ``` let placeNames ...
You can do it without a loop: (the '$0' is the argument in the closure) ``` results.forEach{ print($0, terminator:" ") } ```
1,718
18,782,620
(disclaimer: this is my first stackoverflow question so forgive me in advance if I'm not too clear) **Expected results:** My task is to find company legal identifiers in a string representing a company name, then separate them from it and save them in a separate string. The company names have already been cleaned so...
2013/09/13
[ "https://Stackoverflow.com/questions/18782620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2775630/" ]
Non-Regex solution would be easier here, and this is how, I would do it ``` legal_ids = """gmbh gesmbh""" def foo(name, legal_ids): #Remove all spaces from the string name_stream = name.replace(' ','') #Now iterate through the legal_ids for id in legal_ids: #Remove the legal ID's from the s...
Here's the code I came up with: ``` company_1 = 'uber wien abcd gmbh' company_2 = 'uber wien abcd g m b h' company_3 = 'uber wien abcd ges mbh' legalids = ["gmbh", "gesmbh"] def info(company, legalids): for legalid in legalids: found = [] last_pos = len(company)-1 pos = len(legalid)-1 ...
1,723
51,030,872
Using Tensorflow 1.8.0, we are running into an issue whenever we attempt to build a categorical column. Here is a full example demonstrating the problem. It runs as-is (using only numeric columns). Uncommenting the indicator column definition and data generates a stack trace ending in `tensorflow.python.framework.error...
2018/06/25
[ "https://Stackoverflow.com/questions/51030872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3955068/" ]
The issue here is related to the ragged shape of the "indicator" input array (some elements are of length 1, one is length 2, one is length 3). If you pad your input lists with some non-vocabulary string (I used "Z" for example since your vocabulary is "A", "B", "C"), you'll get the expected results: ``` inputs = { ...
From what I can tell, the difficulty is that you are trying to make an indicator column from an array of arrays. I collapsed your indicator array to ``` "indicator": np.array([ "A", "B", "C", "AA", "ABC", ]) ``` ... and the thing ran. More, I can't find any example where the vocabulary array is anythin...
1,725
28,654,247
I want to remove the heteroatoms (HETATM)s from PDB text files that I have locally. I found a perl script that apparently needs a quick tweak to make it do what I want but I'm unsure of what that tweak is. ``` !#/usr/bin/env perl open(FILE,"file.pdb"); @file=<FILE>; foreach (@file){ if (/^HETATM/){ print $_,"\n"; }}...
2015/02/22
[ "https://Stackoverflow.com/questions/28654247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4589414/" ]
In R you can use the [Bio3D package](http://thegrantlab.org/bio3d/): ``` library(bio3d) # read pdb pdb <- read.pdb("1hel") # make a subset based on TYPE new <- trim.pdb(pdb, type="ATOM") # write new pdb to disk write.pdb(new, file="1hel_ATOM.pdb") ``` This can also be combined with various other selection criteri...
In PERL Try this ``` use warnings; use strict; my $filename = "4BI7.pdb"; die "Error opening file" unless (open my $handler , '<' , "$filename"); open my $newfile, '>', "filename.pdb" or die "New file not create"; while($_ = <$handler>){ print $newfile "$_" unless /^HETATM.*/; } ```
1,726
57,771,019
I want to write something like this when expressed in python. ``` a = int(input()) for i in range(a): b = input() print(b) ``` And this is what I actually wrote. ``` (let [a][(read-line)] (for[i (range [a])] (defn b[string] (= (read-line) b) (println [b]))))...
2019/09/03
[ "https://Stackoverflow.com/questions/57771019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5237648/" ]
Similar to the Python flow. ``` (doseq [_ (range (Integer. (read-line))) :let [b (read-line)]] (println b)) ``` Even closer to Python code: ``` (let [a (Integer. (read-line))] (doseq [i (range a) :let [b (read-line)]] (println b))) ``` More functional Code ``` (mapv println (repeatedly ...
Off the top of my head, you could do something like: `(map (fn [_] (println (read-line))) (range (Integer/parseInt (read-line))))` There may be something more appropriate than a map here, read the clojure documentation. The clojure standard library has a lot of cool stuff :) Edit: @SeanCorfield brought up a good po...
1,727
36,267,936
Given a 2-dimensional array in python, I would like to normalize each row with the following norms: * Norm 1: **L\_1** * Norm 2: **L\_2** * Norm Inf: **L\_Inf** I have started this code: ``` from numpy import linalg as LA X = np.array([[1, 2, 3, 6], [4, 5, 6, 5], [1, 2, 5, 5], ...
2016/03/28
[ "https://Stackoverflow.com/questions/36267936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4208169/" ]
This is the L₁ norm: ``` >>> np.abs(X).sum(axis=1) array([12, 20, 13, 44, 42]) ``` This is the L₂ norm: ``` >>> np.sqrt((X * X).sum(axis=1)) array([ 7.07106781, 10.09950494, 7.41619849, 27.67670501, 27.45906044]) ``` This is the L∞ norm: ``` >>> np.abs(X).max(axis=1) array([ 6, 6, 5, 25, 25]) ``` To no...
You can pass `axis=1` parameter: ``` In [58]: LA.norm(X, axis=1, ord=1) Out[58]: array([12, 20, 13, 44, 42]) In [59]: LA.norm(X, axis=1, ord=2) Out[59]: array([ 7.07106781, 10.09950494, 7.41619849, 27.67670501, 27.45906044]) ```
1,729
28,975,468
When I run ipython notebook; I get "ImportError: IPython.html requires pyzmq >= 13" error message in console. I already run " pip install "ipython[notebook]" " but I can not run the notebook. Could you pls assist how to solve this issue. ``` C:\Python27\Scripts>ipython notebook Traceback (most recent call last): File ...
2015/03/10
[ "https://Stackoverflow.com/questions/28975468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2993130/" ]
Looks like you need the pyzmq package (version >= 13). You can try installing it (or upgrading if need be) with : `pip install --upgrade pyzmq`
These works for me ( win8 + anaconda 2.7.10 ) * Uninstall zmq 4.0.4. * Install zmq 3.2.4. * pip uninstall ipython * pip install "ipython[all]" * pip uninstall pyzmq * pip install pyzmq
1,730
37,888,923
I have a datafile like this: ``` # coating file for detector A/R # column 1 is the angle of incidence (degrees) # column 2 is the wavelength (microns) # column 3 is the transmission probability # column 4 is the reflection probability 14.2000 0.531000 0.0618000 0.938200 14.2000 0.532000 0...
2016/06/17
[ "https://Stackoverflow.com/questions/37888923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5200329/" ]
`inline-block` by default is `vertical-aligne`d `baseline`, and you are setting it to `middle` the first but you need to set it to `top` ```css .logo-letter-text { width: 1em; text-align: center; font-family: "Bebas Kai"; font-weight: 400; color: rgba(246, 244, 229, 1.0); } .nav-menu { position: re...
Instead of using `.nav-menu ul li {display: inline-block}` Use `.nav-menu ul li {float: left;}` See fiddle <https://jsfiddle.net/4uggcyro/4/> Or another solution would be to use `display: flex;` ``` .nav-menu ul { display: flex; flex-direction: row; } ``` See fiddle <https://jsfiddle.net/4uggcyro/6/>
1,731
12,405,322
I have written a code for parallel programming in python.I am using pp module for this. job\_server = pp.Server(ncpus, ppservers=ppservers) where ncpus=8 which is no. of core in my system. python version:2.6.5. pp version:1.6.2. But I am facing an error as follows, ``` Traceback (most recent call last): File "/ho...
2012/09/13
[ "https://Stackoverflow.com/questions/12405322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1372331/" ]
The theme is not used as part of the FPC uri and therefore there is only one cache per package. I wrote a little extension to fix the issue and you can grab it on Github. <https://github.com/benjy14/MobileFpcFix>
I have a feeling that the design exceptions support in Enterprise/PageCache work at the *package* level and not the *theme* level. Take a look at the code referencing design exceptions in app/code/core/Enterprise/PageCache/Model/Observer.php. My first suggestion would be to contact EE support, perhaps they can provide ...
1,732
66,209,089
The problem: ------------ I have a column with a list of redundant values, which I need to be converted into a dictionary-like format in a new column of a PySpark dataframe. The scenario: Here's my PySpark dataframe: | A | C | all\_classes | | --- | --- | --- | | 10 | RDK | [1, 1, 1, 2, 2] | | 10 | USW | [1, 2, 2, ...
2021/02/15
[ "https://Stackoverflow.com/questions/66209089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8046443/" ]
Just introduce extra variables: ``` int main() { int a, b; std::cin >> a >> b; const int sum = a + b; const int diff = a - b; std::cout << sum << std::endl; std::cout << diff; } ``` or use computation when needed: ``` int main() { int a, b; std::cin >> a >> b; std::cout << a + b...
If you want to have: ``` a = a + b b = a - b ``` in the end and not to use any other variable you can also do it like: ``` #include<iostream> using namespace std; int main() { int a,b; cin>>a>>b; a = a + b; b = a - ( 2 * b); cout<<a<<endl; cout<<b; } ``` but please note that it is not a good practice to use `usi...
1,734
70,134,739
I'm new to python and would appreciate any help i can I'm looking at this code : ``` if left[0] < right[0]: result.append(left[0]) left = left[1:] elif left[0] > right[0]: result.append(right[0]) right = right[1:] max_iter -= 1 ``` it doesn't make se...
2021/11/27
[ "https://Stackoverflow.com/questions/70134739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17303354/" ]
The `%y` code matches a two-digit year - for a four-digit year, you should use `%Y` instead. ``` date = datetime.strptime('2021-11-27 00:00', '%Y-%m-%d %H:%M') ```
as per the [documentation](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior), `%y` is > > Year without century as a zero-padded decimal number. > > > and `%Y` is > > Year with century as a decimal number. > > > so ``` from datetime import datetime date = datetime.strptime('2021-11...
1,737
60,610,009
I tried to do a choice menu, each menu make different things, for example if you choice the number 1, will work good, but if you try to choose 2 or other number, first will try to run 1, and I don't want this. Is there a way to become "independent" for each option? Example (this will work): ``` choice = input (""" ...
2020/03/10
[ "https://Stackoverflow.com/questions/60610009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13025132/" ]
Python lacks a switch/case statement (like C/C++) in which you CAN have it perform multiple (adjacent) case conditions, and then have it `break` before processing further cases. In Python you'll need to simulate using if-elif-else statements, perhaps utilizing comparison operators (like `==`, `<`) and/or boolean operat...
Good news for you, if you are still interested in using the switch case in Python. you can now use `match` with Python 3.10 like this: ```py match n: case 0: print("You typed zero.\n") case "1": print("thing 1") case "2": print("thing 2") case "3...
1,739
40,332,032
I'm thinking about writing a desktop application that the GUI is made with either HTML or PHP, but the functions are run by a separate Java or python code, is there any heads up that I can look into?
2016/10/30
[ "https://Stackoverflow.com/questions/40332032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5517067/" ]
There are a couple of possible options: 1. Run your backend code as an embedded HTTP-server (like Jetty\* for Java or Tornado\* for Python). If the user starts the application, the backend runs the server and automatically starts the web browser with the URL of your server. This, however, may cause problems with the o...
You could expose data from Java or Python as JSON via GET request and use PHP to access it. There are multiple libraries for each of these languages both for writing and reading JSON. GET request can take parameters if needed.
1,740
12,311,348
I am trying to implement a class in which an attempt to access any attributes that do not exist in the current class or any of its ancestors will attempt to access those attributes from a member. Below is a trivial version of what I am trying to do. ``` class Foo: def __init__(self, value): self._value = v...
2012/09/07
[ "https://Stackoverflow.com/questions/12311348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/652722/" ]
If I understand you correctly, what you are doing is correct, but it still won't work for what you're trying to use it for. The reason is that implicit magic-method lookup does not use `__getattr__` (or `__getattribute__` or any other such thing). The methods have to actually explicitly be there with their magic names....
`__*__` methods will not work unless they actually exist - so neither `__getattr__` nor `__getattribute__` will allow you to proxy those calls. You must create every single methods manually. Yes, this does involve quite a bit of copy&paste. And yes, it's perfectly fine in this case. You might be able to use the [werk...
1,741
3,905,179
I'm struggling with setting my scons environment variables for visual studio 2008. Normally I do following: ``` %VS90COMNTOOLS%vsvars32.bat or call %VS90COMNTOOLS%vsvars32.bat ``` And this works in my shell. I try to do that in python using subprocess ``` subprocess.call([os.environ['VS90COMNTOOLS']+r"\vsvar...
2010/10/11
[ "https://Stackoverflow.com/questions/3905179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112496/" ]
Write a batch file that runs `vsvars32.bat` and then outputs the values in the form `VARNAME=value`, then have your Python script parse the values and inject them into `os.environ`. This is done in python's own distutils module, [see the source here](http://hg.python.org/distutils2/file/0291648eb2b2/distutils2/compile...
In addition to the previous answer. An excerpt of my SConstruct: ``` for key in ['INCLUDE','LIB']: if os.environ.has_key(key): env.Prepend(ENV = {key.upper():os.environ[key]}) ``` Please take care that variable names in Python are case-sensitive. Ensure that your `env['ENV']` dict has no duplicate variab...
1,742
24,024,920
I have a python script which runs a fabfile. My issue is that I am asked for a password whenever I run the fabfile from my script. However, the login works fine with the specified key when I run the fabfile manually from the command line even though I am using the same fab parameters. Here is the contents of my fabfile...
2014/06/03
[ "https://Stackoverflow.com/questions/24024920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3507094/" ]
You can use [ssh-agent](http://www.openbsd.org/cgi-bin/man.cgi?query=ssh-agent&sektion=1): ``` $ eval `ssh-agent -s` $ ssh-add /home/myhome/scripts/bakery/id_rsa $ fab -H 10.10.15.185 deploy ```
I was being asked for a password even though I had specified a key because there was an extra space between the "u" and "ec2-user". Here is the snippet before: ``` '-u ec2-user' ``` And here it is after: ``` '-uec2-user' ``` The extra space meant that fab was trying to authenticate with " ec2-user" instead of "ec...
1,744
70,386,636
I'm trying to load a large CSV file into Pandas, which I'm new to. The input file should have 13 columns. Howeever, Pandas is reading all of the column headings as one heading, and then just collecting the first few columns of data. The code I am using is;- leases=pd.read\_csv("/content/LEASES\_FULL\_2021\_12.csv", ...
2021/12/16
[ "https://Stackoverflow.com/questions/70386636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16950273/" ]
The problem is that through type erasure, the compiler will produce the method below for your generic method. ``` public static JsonNode of(String key, Object value) { ObjectMapper objectMapper = new ObjectMapper(); ObjectNode root = objectMapper.createObjectNode(); root.put(key, value); //...
There is another approach that works for any json object: ``` Map<String, Object> map = new ObjectMapper().readValue(json, new TypeReference<HashMap<String,Object>>() {}); ``` The object in the value can be any value object (`String`, `Integer`, etc), another `Map<String, Object>` as a nested object or a `List<Objec...
1,745
6,866,802
Im fairly proficient in php and am also learning python. I have been wanting to create a basic game for some time now and would like to create it in python. But in order to have a fancy smooth interface I need to use javascript (i dont much care for the flash/silverlight route). So I decided to start looking up game de...
2011/07/28
[ "https://Stackoverflow.com/questions/6866802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/519990/" ]
I found that splitting the collection view item view into its own XIB and then rewiring the connections so that the collection view item prototype loads the new XIB will allow for you to create the bindings in interface builder without it crashing. I followed these steps... 1. Delete the collection view item view from...
Yup, I can confirm this bug too, even on Interface Builder 3. The only workaround is to do the binding programmatically: ``` [textField bind:@"value" toObject:collectionViewItem withKeyPath:@"representedObject.foo" options:nil]; ```
1,748
63,345,527
I am trying to build a Docker application that uses Python's gensim library, version 3.8.3, which is being installed via pip from a requirements.txt file. However, Docker seems to have trouble while trying to do RUN pip install -r requirements.txt My Requirement.txt for reference - ``` boto==2.49.0 boto3==1.14.33 bo...
2020/08/10
[ "https://Stackoverflow.com/questions/63345527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12138506/" ]
in the post you mension, thye install `libc-dev` to compile packs ... you dont. ``` RUN apt-get -y install libc-dev RUN apt-get -y install build-essential ``` I have problems trying to use "alpine" with Python... so we choose ["slim-buster"](https://hub.docker.com/_/python) as docker image for Python. so if you ...
To install `numpy` on an alpine image, you typically need a few more dependencies: ``` RUN apk update && apk add gfortran build-base openblas-dev libffi-dev ``` Namely the openblas-dev, which you are missing. That will at least get `numpy` to install
1,751
54,299,203
I've looked around and haven't found anything just yet. I'm going through emails in an inbox and checking for a specific word set. It works on most emails but some of them don't parse. I checked the broken emails using. ``` print (msg.Body.encode('utf8')) ``` and my problem messages all start with **b'**. like thi...
2019/01/21
[ "https://Stackoverflow.com/questions/54299203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6054714/" ]
Is the dropdown populated on the server or after an ajax call? It might be that you've tried to select a value before any are available as it's still waiting on for a response to provide data. You could wait until that response is received and then select the first option from that data set. You could reference thi...
if you used jquery ajax you should do this ```js $(document).on("click", 'button', function() { $(".modal-body").load(YOURURL, function() { $("#MyDropDown").prop('selectedIndex', 1); }); $("#myModal").modal(); }); ```
1,752
15,995,987
In python, I have this list containing ``` ['HELLO', 'WORLD'] ``` how do I turn that list into ``` ['OLLEH', 'DLROW'] ```
2013/04/14
[ "https://Stackoverflow.com/questions/15995987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2278906/" ]
``` >>> words = ['HELLO', 'WORLD'] >>> [word[::-1] for word in words] ['OLLEH', 'DLROW'] ```
Using a list comprehension: ``` reversed_list = [x[::-1] for x in old_list] ```
1,753
16,560,497
I am new at Python so this may seem to be very easy. I am trying to remove all **#**, numbers and if the same letter is repeated more then two times in a row, I need to change it to only two letters. This work perfectly but not with ØÆÅ. *Any ideas how this can be done with ØÆÅ letters?* ``` #!/usr/bin/python # -*- ...
2013/05/15
[ "https://Stackoverflow.com/questions/16560497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/871742/" ]
You need to work with Unicode values, not with byte strings. UTF-8 encoded `å` is *two* bytes, and a regular expression matching `\w` *only* matches ascii letters, digits and underscores when operating in the default non-Unicode-aware mode. From the [`re` module documentation](http://docs.python.org/2/library/re.html)...
Change: ``` text = u"ån9d ånd åååååååånd d9d flllllløde... :)asd " ``` and ``` text = re.sub(r'(\w)\1+', r'\1\1', text) ``` **COMPELTE SOLUTION** ``` import math, re, sys, os, codecs reload(sys) sys.setdefaultencoding('utf-8') text = u"ån9d ånd åååååååånd d9d flllllløde... :)asd " # Remove anything other than ...
1,759
40,664,786
I'm a beginner using python, and am writing a "guess my number game". So far I have everything working fine. The computer picks a random number between 1 and 3 and asks the player to guess the number. If the guess is higher than the random number, the program prints "Lower", and vice versa. The player only has 5 tries,...
2016/11/17
[ "https://Stackoverflow.com/questions/40664786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6912990/" ]
To answer your original question about the lack of congratulatory message for correct number, end the code with input(), to ensure it does not terminate before displaying the last message. Order of calculation: 1. give input guess 2. reduce guesses (starting at 5), increase tries (starting at 1) 3. immediate break if...
Assuming everything else works, un-indent the final check. You can't check `guess == the_number` while it isn't equal ``` #guessing loop while guess != the_number: # do logic # outside guessing loop if guesses > 0: print("You guessed it! The number was", the_number) print("And it only took you", tries, "t...
1,760
11,055,921
I am using mongoexport to export mongodb data which also has Image data in Binary format. Export is done in csv format. I tried to read image data from csv file into python and tried to store as in Image File in .jpg format on disk. But it seems that, data is corrupt and image is not getting stored. Has anybody com...
2012/06/15
[ "https://Stackoverflow.com/questions/11055921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1459413/" ]
One thing to watch out for is an arbitrary 2MB BSON Object size limit in several of 10gen's implementations. You might have to denormalize your image data and store it across multiple objects.
Depending how you stored the data, it may be prefixed with 4 bytes of size. Are the corrupt exports 4 bytes/GridFS chunk longer than you'd expect?
1,762
58,851,954
Im trying to do the obeythetestinggoat tutorial and cant set my geckodriver, Im working in Win10 64bits my pip freeze shows: Django==1.7,selenium==3.141.0,urllib3==1.25.7 i download the geckodriver (geckodriver-v0.26.0-win64) when i try to get the geckodriver version (via `$geckodriver --version`) stops and show me...
2019/11/14
[ "https://Stackoverflow.com/questions/58851954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663963/" ]
Vim 8 ( and a number of Vim emulations ) I'd start with ``` <h1>This is h0</h1> <h2>This is h0</h2> <h3>This is h0</h3> <h4>This is h0</h4> <h5>This is h0</h5> <h6>This is h0</h6> ``` then on the top 0 of h0. I'd block highlight with `CTRL-V` go down to the bottom 0 of the h6 tag with `5j` then type `g` and then ...
With my [UnconditionalPaste plugin](http://www.vim.org/scripts/script.php?script_id=3355), you just need to yank the first `<h1>This is h1</h1>` line, and then paste 5 times with `5gPp`, which pastes with all decimal numbers incremented by 1. This also is repeatable via `.`, so you could have also pasted just once and ...
1,763
82,607
I get DNS records from a Python program, using [DNS Python](http://www.dnspython.org/) I can get various DNSSEC-related records: ``` >>> import dns.resolver >>> myresolver = dns.resolver.Resolver() >>> myresolver.use_edns(1, 0, 1400) >>> print myresolver.query('sources.org', 'DNSKEY') <dns.resolver.Answer object at 0...
2008/09/17
[ "https://Stackoverflow.com/questions/82607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
You probably mean RRSIG ANY (otherwise, the order is wrong, the class needs to be after the type) ``` >>> print myresolver.query('sources.org', 'RRSIG', 'ANY') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/site-packages/dns/resolver.py", line 664, in query answ...
If you try this, what happens? ``` print myresolver.query('sources.org', 'ANY', 'RRSIG') ```
1,772
45,368,847
Very related to this post but I don't have the priviledge to comment there so I had to make a new post. [Deploy a simple VS2017 Django app to Azure - server error](https://stackoverflow.com/questions/43506691/deploy-a-simple-vs2017-django-app-to-azure-server-error) I followed Silencer's tutorial there and I am getting...
2017/07/28
[ "https://Stackoverflow.com/questions/45368847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335827/" ]
I had the same problem and finally it was fixed by changing this line in app config: ``` <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_virtualenv_handler()" /> ``` to this: ``` <add key="WSGI_HANDLER" value="myProject.wsgi.application" /> ``` myProject is the name of my django project so you should put...
I get the same errors in python 3.4. For python 2.7 there is an activate\_this.py script, which can help in some way. Just put the activate\_this.py from a python 2.7 virtual environment in the .\env\Scripts folder and changed the path in web.config to point to activate\_this.py. It seems to work. I am just not sure ...
1,779
31,096,631
I am currently writing a script that installs my software-under-test then automatically runs my smoke tests using py.test. If a failure occurs during any of these tests, I would like to tell my software to not publish the software to the build servers. This is basically how it goes in pseudo-code: ``` def install_buil...
2015/06/28
[ "https://Stackoverflow.com/questions/31096631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4621806/" ]
Approach #1 =========== This is I think the road you were heading down. Basically, just treat test.py as a black box process and use the exit code to determine if there were any test failures (e.g. if there is a non-zero exit code) ``` exit_code = subprocess.Popen(["py.test", "smoke_test_suite.py"]).wait() test_failu...
py.test must return a non-zero exit code if the tests fail. The simplest way to handle that would be using [`subprocess.check_call()`](https://docs.python.org/2/library/subprocess.html#subprocess.check_call): ``` try: subprocess.check_call(["py.test", "smoke_test_suite.py"]) except subprocess.CalledProcessError: ...
1,781
41,724,259
Happy new year 2017! Hello everybody! I have some issues when I try to deploy my docker image in a BlueMix container (where `cf ic run = docker run`) I can't access the container from web even if the image is running well inside. I pinged the binded adress: ``` ping 169.46.18.91 PING 169.46.18.91 (169.46.18.91):...
2017/01/18
[ "https://Stackoverflow.com/questions/41724259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7365430/" ]
Hmm - I see that you published port 3000 (the -p 3000 parameter in the run command), but the default port would be 5000. In the dockerfile, you switched that to 12345, so that's presumably what you're actually listening on there. Guessing that's the reason you want to open all ports? Docker only exposes the ports that...
Looks like Bluemix single container service is a bit touchy, it was hard to reach from web until I added a "scalable" container which asks for the required HTTP port. I think the problem was this http port wasn't exposed, but now problem is solved the way I said above.
1,782
28,478,279
Hi I have this sample path "\10.81.67.162" which is a remote server (windows OS) I want to be able to transfer files (local) to the remote server using paramiko in python. I can make it work if the server is in linux. This is my sample code ``` import paramiko import base64 username = 'username' password = 'pass...
2015/02/12
[ "https://Stackoverflow.com/questions/28478279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3728094/" ]
If you are asking about method argument and method internal variables the answer is no. These variables are allocated on stack and are different for each thread. EDIT: Issues may happen when passing shared (among several threads) not thread safe objects. For example your method `foo()` accepts parameter of type `MyC...
There shouldn't be any problems with your code since you don't manipulate the `parameters` (e.g. `adding/removing` stuff from the maps ). of course there is this assumption that those maps are not related (e.g `sharing same resources`) **AND** no where else in you program you will manipulate those objects at the same ...
1,783
54,675,259
I am answering the Euler project questions in python and I don't know how to multiply a list by itself I can get a list within the range though
2019/02/13
[ "https://Stackoverflow.com/questions/54675259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11051957/" ]
Seems like this should do it: ``` SET Row1 = CASE WHEN Row1 = 'From1' THEN 'To1' WHEN Row1 = 'From2' THEN 'To2' etc END ```
Are you simply looking for a `case` expression? ``` UPDATE TOP (@batchsize) Table1 SET Row1 = (CASE table1.Row1 WHEN 'From1' THEN 'To1' WHEN 'From2' THEN 'To2' WHEN 'From3' THEN 'To3' WHEN 'From4' THEN 'To4' ...
1,784
69,067,530
I installed several files based upon `https://pbpython.com/pdf-reports.htm to create reports. However the following error messages ``` Traceback (most recent call last): File "C:\histdata\test02.py", line 10, in <module> from weasyprint import HTML File "C:\Users\AquaTrader\AppData\Local\Programs\Python\Python...
2021/09/05
[ "https://Stackoverflow.com/questions/69067530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6090578/" ]
The error means that the `gobject-2.0.0` library, which is part of GTK3+, cannot be found. Did you follow the installation instructions (<https://doc.courtbouillon.org/weasyprint/stable/first_steps.html>), which include installation of GTK3+? If no, do that. If yes, then the problem is, that the GTK3+ DLLs are not wher...
As @mad said, you need the GTK3 library to have the `libobject-2.0.0` DLL. In Github Actions for example, you might be interested to use the [tschoonj/GTK-for-Windows](https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer) repository : ```sh # Download GTK3 resources git clone -b 2022-01-04 https:/...
1,785
16,819,938
I have a class which would be a container for a number of variables of different types. The collection is finite and not very large so I didn't use a dictionary. Is there a way to automate, or shorten the creation of variables based on whether or not they are requested (specified as True/False) in the constructor? Her...
2013/05/29
[ "https://Stackoverflow.com/questions/16819938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2433420/" ]
Maybe something like: ``` def __init__(self,*args,**kwargs): default_values = {a:{},b:34,c:"generic string"} for k,v in kwargs.iteritems(): try: if not v is False: setattr(self,k,default_values[k]) except Exception, e: print "Argument has no default valu...
You can subclass `dict` (if you aren't using positional arguments): ``` class Test(dict): def your_method(self): return self['foo'] * 4 ``` You can also override `__getattr__` and `__setattr__` if the `self['foo']` syntax bothers you: ``` class Test(dict): def __getattr__(self, key): return ...
1,786
50,271,354
Consider the following python snippet (I am running Python 3) ``` name = "Sammy" def greet(): name = 'johny' def hello(): print('hello ' + name) # gets 'name' from the enclosing 'greet' hello() greet() ``` This produces the output `hello johny` as expected However, ``` x = 50 def func1(): ...
2018/05/10
[ "https://Stackoverflow.com/questions/50271354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5157905/" ]
The error is actually caused (indirectly) by the following line, i.e. `x = 2`. Try commenting out that line and you'll see that the function works. The fact that there is an assignment to a variable named `x` makes `x` local to the function at *compile time*, however, at *execution time* the first reference to `x` fai...
In a given scope, *you can only reference a variable's name from one given scope*. Your variable cannot be global at some point and local later on or vice versa. For that reason, if `x` is ever to be declared in a scope, Python will assume that you are refering to the local variable everywhere in that scope, unless yo...
1,787
55,717,203
I wrote this small function: ``` def sets(): set1 = random.sample(range(1, 50), 10) set2 = random.sample(range(1, 50), 10) return(set1,set2) sets() ``` The output of this function looks like this: ``` ([24, 29, 43, 42, 45, 28, 26, 3, 8, 21], [22, 37, 38, 44, 25, 42, 29, 7, 35, 9]) ``` I want to plot...
2019/04/16
[ "https://Stackoverflow.com/questions/55717203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8407951/" ]
A possible solution is to output the labels instead of the set size. With the [matplotlib\_venn](https://pypi.org/project/matplotlib-venn/) package, you can do something like this: ``` import matplotlib.pyplot as plt from matplotlib_venn import venn2 import random set1 = set(random.sample(range(1, 50), 10)) set2 = se...
The default behaviour of the venn2 package is to print the size of the overlap of the two sets. Here's the line of the source code where those sizes are added to the Venn diagram plot: <https://github.com/konstantint/matplotlib-venn/blob/master/matplotlib_venn/_venn2.py#L247> To make this print the overlapping numbers...
1,788
63,416,534
I've recently tried to create a simple bot in discord with Python Code. I'm testing just the first features to DM a user when he joins the server Here is my code: ``` import os import discord from dotenv import load_dotenv load_dotenv() #load .env files TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('D...
2020/08/14
[ "https://Stackoverflow.com/questions/63416534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13461081/" ]
So You Need To Edit Your Code Sligitly Store Orginal Image To a temp for a while ``` originalBlue = image[i][j].rgbtBlue; originalRed = image[i][j].rgbtRed; originalGreen = image[i][j].rgbtGreen; ``` the result of each of these formulas may not be an integer so use float and rou...
You need to use "saturation math". For near white colors, your intermediate values (e.g. `sepiared`) can exceed 255. 255 (0xFF) is the maximum value that can fit in an `unsigned char` For example, if `sepiared` were 256 (0x100), when it gets put into `rgbtRed`, only the rightmost 8 bits will be retained and the valu...
1,789
18,296,394
I've got a list of instances of a particular class Foo, that has a field bar: ``` foo[1..n].bar ``` I'd like to "convert" this to just a list of bar items, so that I have `bar[1..n]` Sorry for the 1..n notation - I'm just trying to indicate I have an arbitrarily long list. Be gentle - I'm new to python.
2013/08/18
[ "https://Stackoverflow.com/questions/18296394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8478/" ]
Use a list comprehension ``` bar = [ i.bar for i in foo ] ``` Also, list indices in python start from 0, so a list of N elements would have items from `0` to `n - 1`.
> > Be gentle - I'm new to python. > > > Okay. > > I've got a list of items: > > > > ``` > foo[1..n].bar > > ``` > > How in the heck is that a list? A list looks like this: ``` [1, 2, 3] ``` How does `foo[1..n].bar` fit that format? Like this? ``` foo[1, 2, 3].bar ``` That's nonsensical. > > I'd l...
1,794
41,778,173
I have been using turtle package in python idle. Now I have switched to using Jupyter notebook. How can I make turtle inline instead of opening a separate graphic screen. I am totally clueless about. Any pointers and advice will be highly appreciated.
2017/01/21
[ "https://Stackoverflow.com/questions/41778173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3668042/" ]
I found the following library that has a Turtle implementation working in Jupyter notebooks: <https://github.com/takluyver/mobilechelonian>
It seems you can get turtle module to work, if you run the Jupyter Notebook cell containing the code twice. Not sure why it works, but it does!
1,795
1,584,864
Say that we have a multilayered iterable with some strings at the "final" level, yes strings are iterable, but I think that you get my meaning: ``` ['something', ('Diff', ('diff', 'udiff'), ('*.diff', '*.patch'), ('text/x-diff', 'text/x-patch')), ('Delphi', ('delphi', 'pas', 'pascal', 'objectpascal'), ('*.pas',), ('...
2009/10/18
[ "https://Stackoverflow.com/questions/1584864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177293/" ]
Here is a grep that uses recursion to search the data structure. Note that good data structures lead the way to elegant solutions. Bad data structures make you bend over backwards to accomodate. This feels to me like one of those cases where a bad data structure is obstructing rather than helping you. Having a si...
To get the position use `enumerate()` ``` >>> data = [('foo', 'bar', 'frrr', 'baz'), ('foo/bar', 'baz/foo')] >>> >>> for l1, v1 in enumerate(data): ... for l2, v2 in enumerate(v1): ... if 'f' in v2: ... print l1, l2, v2 ... 0 0 foo 1 0 foo/bar 1 1 baz/foo ``` In this example I a...
1,800
36,831,274
I want to connect my Django web app database to my postgresql database I have on my Pythonanywhere paid account. Before coding anything, I just wanted to get everything talking to each other. This is the settings.py DATABASE section from my django app. I'm running Python 3.5 and Django 1.9. ``` DATABASES = { 'default'...
2016/04/25
[ "https://Stackoverflow.com/questions/36831274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314523/" ]
You need to setup django first if you are using it as a standalone script. Would have been easier to try with `./manage.py shell`. but if you want to test with a standalone script, here goes: ``` import sys,os if __name__ == '__main__': # pragma nocover # Setup environ sys.path.append(os.getcwd()) os.en...
The error you are getting is because you need to properly initialize the django environment before you can write custom scripts against it. The easiest way to solve this is to run a python shell that already has the django configuration loaded, you can do this with `python manage.py shell`. Once this shell has loaded...
1,803
56,652,022
I am working with an Altera DE1-SoC board where I am reading data from a sensor using a C program. The data is being read continually, in a while loop and written to a text file. I want to read this data using a python program and display the data. The problem is that I am not sure how to avoid collision during the re...
2019/06/18
[ "https://Stackoverflow.com/questions/56652022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6649616/" ]
Loop the *TableDefs* collection. For each *TableDef*, loop the *Fields* collection. For each *Field*, check the property *Type* (= 101, as I recall) or *IsComplex* = True. IsComplex is also True for *Multi-Value* fields, but if you don't use these, you should be fine.
Here is an example on VBA. It prints in immediate (open VBA editor by `Alt` + `F11`, then press `Ctrl` + `G`) messages about tables with Attachment type field. ```vb Public Sub subTest() Dim db As DAO.Database Dim td As DAO.TableDef Dim fld As DAO.Field Dim boolIsAttachmentFieldPresent ...
1,804
60,494,341
I have a large csv data file, sample of the data as below. ``` name year value China 1997 481970 Japan 1997 8491480 Germany 1997 4678022 China 1998 589759 Japan 1998 ...
2020/03/02
[ "https://Stackoverflow.com/questions/60494341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12807398/" ]
Assuming the input shown reproducibly in the Note at the end convert it to a zoo object `z` which, by specifying `split=`, will also convert it to wide form at the same time. Then expand it using `merge` and use linear interpolation with `na.approx`. Alternately replace `na.approx` with `na.spline`. Finally convert the...
An option using `data.table`: ``` DT[, date := as.IDate(paste0(year, "-12-31"))][, c("y0", "y1") := .(value, shift(value, -1L, fill=value[.N])), name] longDT <- DT[, { eom <- seq(min(date)+1L, max(date)+1L, by="1 month") - 1L v <- unlist(mapply(function(a, d) a + (0:11) * d, y0, (y1 - y0)/12, SIMPLIFY=FAL...
1,806
49,687,860
After upgrade pycharm to 2018.1, and upgrade python to 3.6.5, pycharm reports "unresolved reference 'join'". The last version of pycharm doesn't show any warning for the line below: ``` from os.path import join, expanduser ``` May I know why? (I used python 3.6.? before) I tried almost everything I can find, such ...
2018/04/06
[ "https://Stackoverflow.com/questions/49687860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8335451/" ]
Sadly, it seems that PyCharm will try to evaluate the path to an existing file/folder, which in some cases will not exist and thus create this warning. It's not very useful when you are building a path for something that's supposed to be created, because obviously it will not exist yet, but PyCharm will still complain...
Check that pycharms is using the correct interpreter.
1,807
63,404,899
I'm trying to write a highly modular Python logging system (using the logging module) and include information from the trace module in the log message. For example, I want to be able to write a line of code like: ``` my_logger.log_message(MyLogFilter, "this is a message") ``` and have it include the trace of where ...
2020/08/14
[ "https://Stackoverflow.com/questions/63404899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3014653/" ]
> > or if I'm completely off on the wrong track and if that's the case, what I should be doing instead. > > > My strong suggestion is that you view logging as a solved problem and avoid reinventing the wheel. If you need more than the standard library's `logging` module provides, it's probably something like [str...
It turns out the missing piece to the puzzle is using the "traceback" module rather than the "trace" one. It's simple enough to parse the output of traceback to pull out the source filename and line number of the ".log\_message()" call. If my logging needs become any more complicated then I'll definitely look into str...
1,808
51,074,335
Want to find the delimiter in the text file. The text looks: ``` ID; Name 1; John Mak 2; David H 4; Herry ``` The file consists of tabs with the delimiter. I tried with following: [by referring](https://stackoverflow.com/questions/21407993/find-delimiter-in-txt-to-convert-to-csv-using-python) ```...
2018/06/28
[ "https://Stackoverflow.com/questions/51074335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4268241/" ]
`sniff` can conclude with only one single character as the delimiter. Since your CSV file contains two characters as the delimiter, `sniff` will simply pick one of them. But since you also pass in the optional second argument to `sniff`, it will only pick what's contained in that value as a possible delimiter, which in...
Sniffing is not guaranteed to work. Here is one approach that will work with any kind of delimiter. You start with what you assume is the most common delimiter `;` if that fails, then you try others until you manage to parse the row. ``` import csv with open('sample.csv') as f: reader = csv.reader(f, delimiter=';...
1,809
40,523,328
I have code below for a simple test of `sympy.solve`: ``` #!/usr/bin/python from sympy import * x = Symbol('x', real=True) #expr = sympify('exp(1 - 10*x) - 15') expr = exp(1 - x) - 15 print "Expressiong:", expr out = solve(expr) for item in out: print "Answer:", item expr = exp(1 - 10*x) - 15 print expr out = ...
2016/11/10
[ "https://Stackoverflow.com/questions/40523328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2298014/" ]
I can also confirm that the `solve` output for the equation `exp(1 - 10*x) - 15 == 0` appears unecessarily complicated. I would suggest for univariate equations to first consider `sympy.solveset`. For this example, it gives the following nicely formatted solutions. ``` import sympy as sp sp.init_printing(pretty_print=...
`solve` gives real and complex roots if symbols allow. An equation like `exp(2*x)-4` can be though of as `y**2 - 4` with `y = exp(x)` and `y` (thus `x`) will have two solutions. There are 10 solutions if the 2 is replaced with 10. (But there are actually many more solutions besides as `solveset` indicates.) You based ...
1,810
53,289,402
I have a windows setup file (.exe), which is used to install a software. This is a third party executable. During installation, it expects certain values and has a UI. I want to run this setup .exe silently without any manual intervention (even for providing the parameter values). After spending some time googling abou...
2018/11/13
[ "https://Stackoverflow.com/questions/53289402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1773169/" ]
***Deployment***: Note that it is not always possible to run a setup.exe silently with full control of parameters and with reliable silent running. It depends on how the installer was designed. In these cases I normally resort to repackaging - some more detail below on this. Some general tips for dealing with deployme...
You can also try creating a shortcut to the exe and adding (one at a time) common help parameters in the shortcut target and see if one gives you a help dialog. Some common parameters are /? /help -help --help This also depends on the developer implementing a help parameter, but most installer builders default to imp...
1,811
62,515,497
I have a directory with quite some files. I have `n` search patterns and would like to list all files that match `m` of those. Example: From the files below, list the ones that contain at least *two* of `str1`, `str2`, `str3` and `str4`. ```sh $ ls -l dir/ total 16 -rw-r--r--. 1 me me 10 Jun 22 14:22 a -rw-r--r--. 1 ...
2020/06/22
[ "https://Stackoverflow.com/questions/62515497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2656118/" ]
``` $ cat reg.txt str1 str2 str3 str4 ``` ``` $ cat prog.awk # reads regexps from the first input file # parameterized by `m' # requires gawk or mawk for `nextfile' FNR == NR { reg[NR] = $0 next } FNR == 1 { for (i in reg) tst[i] cnt = 0 } { for (i in tst) { if ($0 ~ reg[i]) { if (++cnt == m) ...
Here's an option using `awk` since you tagged it with that too: ``` find dir -type f -exec \ awk '/str1|str2|str3|str4/{c++} END{if(c>=2) print FILENAME;}' {} \; ``` It will however count duplicates, so a file containing ``` str1 str1 ``` will be listed.
1,812
44,282,257
I am new in python. I have a scrapy project. I am using conda virtual environment where I have written a pipeline class like this: ``` from cassandra.cqlengine import connection from cassandra.cqlengine.management import sync_table, create_keyspace_network_topology from recentnews.cassandra.model.NewsPaperDataModel im...
2017/05/31
[ "https://Stackoverflow.com/questions/44282257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1427144/" ]
So it appeared that [there was a folder named `recentnews/cassandra/`](https://stackoverflow.com/questions/44282257/importerror-no-module-named-cqlengine-but-worked-on-python-command?noredirect=1#comment75573040_44282257) in the OP's scrapy project (namespace `recentnews.cassandra`). When scrapy imports the item pipel...
When you create a virtual environment, by default the user-installed packages are not copied. You would therefore have to run `pip install casandra` (or whatever the package is called) in your virtual environment. That will probably fix this problem.
1,815
50,877,817
The first column corresponds to a single process and the second column are the components that go into the process. I want to have a loop that can examine all the processes and evaluate what other processes have the same individual components. Ultimately, I want a loop to find what processes have 50% or more of their c...
2018/06/15
[ "https://Stackoverflow.com/questions/50877817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9946677/" ]
Here is what I ended up doing: ``` // Get the tile's cartesian center. var cartesian = new Cesium.Cartesian3(1525116.05769, -4463608.36127, 4278734.88048); // Get the tile's cartographic center. var cartographic = Cesium.Cartographic.fromCartesian(cartesian); // Rotate the model. model.rotation.x = -cartographic.lat...
Just convert "gltfUpAxis" to "Z" would work fine. Or you can try "Y" too. ``` "asset": { "gltfUpAxis": "Z", "version": "1.0" }, ```
1,816
67,022,905
I have a simple text file that has groups of key:value pairs with a blank row between each group of key:values. The number of key:value pairs can vary from group to group. Sample data and my code so far. ``` key1: value1 key2: value2 key3: value3 key1: value4 key2: value5 key3: value6 ``` The code is close to what ...
2021/04/09
[ "https://Stackoverflow.com/questions/67022905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3123307/" ]
Using [`Array.from()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) and [`Array.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce), this could be done as follows: ``` Array.from(map.entries()).reduce((a, b) => a[1] <...
Here is one approach * Convert it to an array of key/value pairs * Sort the array by the value * Extract the second item of the first pair Like so ``` let map: Map<string, number> = new Map(); map.set("a", 12); map.set("b", 124); map.set("c", 14); map.set("d", 155); const key = Array.from(map).sort((a, b) => (a[1]...
1,817
2,319,495
I need to keep a large number of Windows XP machines running the same version of python, with an assortment of modules, one of which is python-win32. I thought about installing python on a network drive that is mounted by all the client machines, and just adjust the path on the clients. Python starts up fine from the n...
2010/02/23
[ "https://Stackoverflow.com/questions/2319495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18308/" ]
On every machine you have to basically run following `pywin32_postinstall.py -install` once. Assuming your python installation on the network is `N:\Python26`, run following command on every client: ``` N:\Python26\python.exe N:\Python26\Scripts\pywin32_postinstall.py -install ``` Another important thing is `Good Lu...
You could use [batch files running at boot](http://isg.ee.ethz.ch/tools/realmen/index.en.html) to * Mount the network share (`net use \\server\share`) * Copy the Python and packages installers from the network share to a local folder * Check version of the msi installer against the installed version * If different, un...
1,818
9,776,351
This question describes my conclusion after researching available options for creating a headless Chrome instance in Python and asks for confirmation or resources that describe a 'better way'. From what I've seen it seems that the quickest way to get started with a headless instance of Chrome in a Python application i...
2012/03/19
[ "https://Stackoverflow.com/questions/9776351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193601/" ]
Any reason you haven't considered Selenium with the Chrome Driver? <http://code.google.com/p/selenium/wiki/ChromeDriver> <http://code.google.com/p/selenium/wiki/PythonBindings>
[casperjs](http://casperjs.org/) is a headless webkit, but it wouldn't give you python bindings that I know of; it seems command-line oriented, but that doesn't mean you couldn't run it from python in such a way that satisfies what you are after. When you run casperjs, you provide a path to the javascript you want to e...
1,821
27,916,891
I wrote some python code like: ``` if platform == 'ios': do_something() elif platform == 'android': do_something_else() ``` And this piece of code was strongly criticized by one of my colleague. He accused me why I don't have an else block to handle the rest part. In my opinion, all I need to do is to deal ...
2015/01/13
[ "https://Stackoverflow.com/questions/27916891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3480199/" ]
`else` is not required from the syntax point of view and is not enforced by `PEP8`. If you intended do nothing if `platform` is not `ios` or `android` then this is perfectly ok. Alternatively, you can have a mapping "platform > function", something along these lines: ``` mapping = {'ios': do_something, 'android': do_...
It depends on your code but in this case either way would've been fine. There was a logical reason that your code needed to be that way and that's fine. You do not have to follow the rules all the time, you have to be able to try different stuff all the time.
1,831
27,955,947
We are trying to write an automated test for our iOS app using the Appium python client. We want to imitate Swipe event on an element but none of the APIs from appium.webdriver.common.touch\_action seem to be behaving the way we want. Basically we want to break down swipe in three events (KEYDOWN, MOVE, KEYUP). The f...
2015/01/15
[ "https://Stackoverflow.com/questions/27955947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631679/" ]
Your 'data' contains 4 contours. Each contour has one point that was drawn on image. What you need is 1 contour with 4 points. Push all your points to data[0]. On side note, you don't need to call drawContours() in loop. If you provide negative index of contour (third parameter), then all contours will be drawn. ``` ...
If you have only 4 points, I suggest you to use cv::Rectangle. If you can have a lot of points, you have to write a function using [cv::Line](http://docs.opencv.org/2.4.2/modules/core/doc/drawing_functions.html#line).
1,832
49,981,741
I am writing a python application and trying to manage the code in a structure. The directory structure that I have is something like the following:- ``` package/ A/ __init__.py base.py B/ __init__.py base.py app.py __init__.py ``` so I have a line in A/**init**.py that says ``` from .bas...
2018/04/23
[ "https://Stackoverflow.com/questions/49981741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7877397/" ]
This is occurred because you have two packages: *A* and *B*. Package *B* can't get access to content of package *A* via relative import because it cant move outside top-level package. In you case both packages are top-level. You need reorganize you project, for example like that ``` . ├── TL │   ├── A │   │   ├── __...
My problem was forgetting `__init__.py` in my top level directory. This allowed me to use relative imports for folders in that directory.
1,833
62,209,746
Still fairly new to python. I was wondering what would be a good way of detecting what output response a python program were to choose. As an example, if you were to make a speed/distance/time calculator, if only 2 input were ever given, how would you detect which was the missing input and therefore the output? I can...
2020/06/05
[ "https://Stackoverflow.com/questions/62209746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11098113/" ]
Python allows you to change types of variables on the fly. Since you are working with integers and `0` could be a useful value in your calculations, your default 'not present' value should be `None`: ``` def sdf(speed=None, time=None, distance=None): if speed is None: return calculate_speed(time, distance...
You should use multiple functions and call the one needed. ``` def CalculateTravelTime(distance, speed) def CalculateTravelSpeed(distance, time) def CalculateTravelDistance(speed, time) ```
1,834
48,788,169
I was doing cs231n assignment 2 and encountered this problem. I'm using tensorflow-gpu 1.5.0 Code as following ``` # define our input (e.g. the data that changes every batch) # The first dim is None, and gets sets automatically based on batch size fed in X = tf.placeholder(tf.float32, [None, 32, 32, 3]) y = tf.place...
2018/02/14
[ "https://Stackoverflow.com/questions/48788169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5856554/" ]
The problem is that the `y_out` argument to `sess.run()` is `None`, whereas it must be a `tf.Tensor` (or tensor-like object, such as a `tf.Variable`) or a `tf.Operation`. In your example, `y_out` is defined by the following code: ``` # define model def complex_model(X,y,is_training): pass y_out = complex_model(X...
I believe that **mrry** is right. If you give a second look the the notebook [Assignment 2 - Tensorflow.ipynb](https://github.com/BedirYilmaz/cs231-stanford/blob/master/assignment2/TensorFlow.ipynb), you will notice the description cell as follows : > > Training a specific model > > > In this section, we're going...
1,837
11,100,380
I've been studying tkinter in python3 and find it very hard to find good documentation and answers online. To help others struggling with the same problems I decided to post a solution for a simple problem that there seems to be no documentation for online. Problem: Create a wizard-like program, that presents the user...
2012/06/19
[ "https://Stackoverflow.com/questions/11100380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1466253/" ]
As you've taken the liberty to post an answer as a question. I'd like to post a comment as an answer and suggest that perhaps you should contribute this to TkDocs (click their [About tab](http://www.tkdocs.com/about.html) and they talk about contributing to the site). I think it'd be better if that site were to improv...
Thanks for your work- I used it as inspiration for this example that, while extremely light in terms of the content, is a cool way to make an arbitrary number of windows that you can switch between. You could move the location of the next and back buttons, turn them into arrows, whatever you want. ``` from tkinter im...
1,838
3,974,211
i saw a javascript implementation of sha-256. i waana ask if it is safe (pros/cons wathever) to use sha-256 (using javascript implementation or maybe python standard modules) alogrithm as a password generator: i remember one password, put it in followed(etc) by the website address and use the generated text as the pas...
2010/10/20
[ "https://Stackoverflow.com/questions/3974211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/481170/" ]
I think you are describing the approach used by [SuperGenPass](http://supergenpass.com/): Take a master password (same for every site), concatenate it with the site's domain name, and then hash the thing. Yes, SHA-256 would be secure for that, likely more secure than when SuperGenPass uses. However, you will end up w...
SHA-256 generates *very* long strings. You're better off using `random.choice()` with a string a fixed number of times.
1,839
52,236,797
Built Python 3.7 on my Raspberry pi zero in a attempt to upgrade from Python 3.5.3 The build was successful, ran into the module not found for smbus and switched that to smbus2, now when I import gpiozero I get Module not found. my DungeonCube.py program was working fine under Python 3.5.3, but now Python 3.7 seems to ...
2018/09/08
[ "https://Stackoverflow.com/questions/52236797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333299/" ]
I had same problem, realized that i used `pip3` to install the package, but I was trying to use it with `python` which invokes python2. I tried with `python3` it works just fine.
did you download the gpiozero module onto the raspberry pi? it does not come preinstalled with python. you could try to do "sudo python3 pip install gpiozero". if that doesnt work replace python3 with python @GarryOsborne .
1,840
15,976,639
First of all: Please keep in mind that I'm very much a beginner at programming. I'm trying to write a simple program in Python that will replace the consonants in a string with consonant+"o"+consonant. For example "b" would be replaced with "bob" and "d" would be replaced with "dod" (so the word "python" would be chan...
2013/04/12
[ "https://Stackoverflow.com/questions/15976639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2275161/" ]
`lexicon` is a dictionary with integers as keys and tuples as values. when you iterate over it's items, you're getting tuples of the form `(integer,tuple)`. You're then passing that integer and tuple to `text.replace` as `i` and `j` which is why it's complaining. Perhaps you meant: ``` for i,j in lexicon.values(): ...
no ... your keys in the handmade version are strings ... your kets in the other version are ints ... ints have no replace method
1,841
59,457,595
I am taking the data science course from Udemy. After running the code to show the iris data set, it does not show. Instead, it downloads a data file. I am running the following code: ```py from IPython.display import HTML HTML('<iframe src=http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data></if...
2019/12/23
[ "https://Stackoverflow.com/questions/59457595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4998064/" ]
If plot is not in the first line in the file, you could do this: ``` sed '1,/plot/!s/plot//' ``` If it can be on the first line, I see no other way but to loop it: ``` sed ':a;/plot/!{n;ba;};:b;n;s///;bb' ```
In case you are ok with an `awk` solution, could you please try following. ``` awk '/plot/ && ++count==1{print;next} !/plot/' Input_file ``` ***Explanation:*** Adding explanation for above code. ``` awk ' ##Starting awk program from here. /plot/ && ++count==1{ ##Checking condition if...
1,846
32,879,614
I was following the instructions [here](https://people.csail.mit.edu/hubert/pyaudio/compilation.html) and I'm having trouble getting the installation to work. Basically, the first part works fine. I downloaded portaudio, followed the instructions, and it all seemed to work. However, when I tried`python3 setup.py insta...
2015/10/01
[ "https://Stackoverflow.com/questions/32879614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047641/" ]
To install the latest version of pyaudio using conda: ``` source activate -your environment name- pip install pyaudio ``` You may run into the following error when installing from pip: ``` src/_portaudiomodule.c:29:23: fatal error: portaudio.h: No such file or directory #include "portaudio.h" compilation termin...
I was able to get it install with [anaconda](https://www.continuum.io/downloads), using [this package](https://anaconda.org/bokeh/pyaudio). Follow install instructions for linux [here](https://www.continuum.io/downloads#_unix), then do: ``` conda install -c bokeh pyaudio=0.2.7 ```
1,847
23,507,902
I use gsutil to transfer files from a Windows machine to Google Cloud Storage. I have not used it for more than 6 months and now when I try it I get: Failure: invalid\_grant From researching this I suspect the access token is no longer valid as it has not been used for 6 months, and I need a refresh token? I cannot...
2014/05/07
[ "https://Stackoverflow.com/questions/23507902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3610488/" ]
You can ask gsutil to configure itself. Go to the directory with gsutil and run this: ``` c:\gsutil> python gsutil config ``` Gsutil will lead you through the steps to setting up your credentials. That said, access tokens only normally last about a half hour. It's more likely that the previously-configured refresh ...
Brandon Yarbrough gave me suggestions which solved this problem. He suspected that the .boto file was corrupted and suggested I delete it and run gsutil config again. I did this and it solved the problem.
1,857
32,775,258
Trying to write `to_csv` with the following code: ``` file_name = time.strftime("Box_Office_Data_%Y/%m/%d_%H:%M.csv") allFilms.to_csv(file_name) ``` But am getting the following error: ``` FileNotFoundError Traceback (most recent call last) <ipython-input-36-aa2d6e13e9af> in <module>() ...
2015/09/25
[ "https://Stackoverflow.com/questions/32775258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5314975/" ]
The error is clear - ``` FileNotFoundError: [Errno 2] No such file or directory: 'Box_Office_Data_2015/09/24_22:11.csv' ``` If you get this error when trying to do `.to_csv()` , it means that the directory in which you are trying to save the file does not exist. So in your case, the directory - `Box_Office_Data_2015...
In your code `file_name = time.strftime("Box_Office_Data_%Y/%m/%d_%H:%M.csv")`. File name was like this `Box_Office_Data_2015/09/24_22:11.csv`, which means a path to a file. Try to replace the `/` with something like `_`. Try this: `file_name = time.strftime("Box_Office_Data_%Y_%m_%d_%H:%M.csv")`
1,859
56,507,997
I did `!pip install tree` on google colab notebook. It showed that `Pillow in /usr/local/lib/python3.6/dist-packages (from tree) (4.3.0)`. But when I use `!tree`. The notebook reminded me that `bin/bash: tree: command not found`. How to solve it? I tried several times but all failed. It showed: ``` Collecting tree ...
2019/06/08
[ "https://Stackoverflow.com/questions/56507997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11618792/" ]
You seem to have confused pip with the local package manager? `!apt-get install tree` does what you want: ``` . └── sample_data ├── anscombe.json ├── california_housing_test.csv ├── california_housing_train.csv ├── mnist_test.csv ├── mnist_train_small.csv └── README.md 1 directory, 6 files `...
I think you have installed wrong tree with pip <https://pypi.org/project/Tree/> Right code for install on Mac `brew install tree` ``` sudo apt-get install tree ``` the command for Debian / Ubuntu Linux / Mint `sudo apt install tree`
1,860
68,160,205
Before I describe the problem, here is a basic run-down of the overall process to give you a clearer picture. Additionally, I am a novice at PHP: 1. I have a WordPress website that uses CPanel as its web hosting software 2. The WordPress website has a form (made by UFB) that has the user upload an image 3. The image g...
2021/06/28
[ "https://Stackoverflow.com/questions/68160205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16332203/" ]
Set the [Request.URL](https://pkg.go.dev/net/http#Request.URL) to an [opaque URL](https://pkg.go.dev/net/url#URL.Opaque). The opaque URL is written to the request line as is. ``` request := &http.Request{ URL: &url.URL{Opaque: "http://127.0.0.1:10019/system?action=add_servers"} Body: ...
what value of the URL variable? I think you can define the URL variable use a specific host ``` var url = "http://127.0.0.1:10019/system?action=add_servers" ``` In case your path is dynamic from another variable, you can use `fmt.Sprintf`, like below ``` // assume url value var path = "/system?action=add_servers" ...
1,863
45,948,854
I have this situation : * *File1* named **source.txt** * *File2* named **destination.txt** **source.txt** contains these strings: ``` MSISDN=213471001120 MSISDN=213471001121 MSISDN=213471001122 ``` I want to see **destination.txt** contains these cases: MSISDN=213471001120 **only** for First execution of python c...
2017/08/29
[ "https://Stackoverflow.com/questions/45948854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6056999/" ]
You have to read the whole file, before writing again, because mode `w` empties the file: ``` with open('source.txt') as lines: lines = list(lines) with open('destination.txt', 'w') as first: first.write(lines[0]) with open('source.txt', 'w') as other: other.writelines(lines[1:]) ```
You're gonna need an external file to store the state of "how many times have I run before" ``` with open('source.txt', 'r') as source, open('counter.txt', 'r') as counter, open('destination.txt', 'w') as destination: num_to_read = int(counter.readline().strip()) for _ in range(num_to_read): line_to_wr...
1,864
61,877,065
I am trying to implement Okapi BM25 in python. While I have seen some tutorials how to do it, it seems I am stuck in the process. So I have collection of documents (and has as columns 'id' and 'text') and queries (and has as columns 'id' and 'text'). I have done the pre-processing steps and I have my documents and qu...
2020/05/18
[ "https://Stackoverflow.com/questions/61877065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13498967/" ]
`**kwargs` expects arguments to be passed by keyword, not by position. Once you do that, you can access the individual kwargs like you would in any other dictionary: ``` class Student: def __init__(self, **kwargs): self.name = kwargs.get('name') self.age = kwargs.get('age') self.salary = k...
**kwargs** is created as a dictionary inside the scope of the function. You need to pass a keyword which uses them as keys in the dictionary. (Try running the print statement below) ``` class Student: def __init__(self, **kwargs): #print(kwargs) self.name = kwargs["name"] self.age = kwargs[...
1,866
59,596,957
First, let me say: I know I shouldn't be iterating over a dataframe per: [How to iterate over rows - Don't!](https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas/55557758#55557758) [How to iterate over rows...](https://stackoverflow.com/questions/16476924/how-to-iterate-over-...
2020/01/05
[ "https://Stackoverflow.com/questions/59596957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/554517/" ]
In short, the answer is the performance benefit of using iterrows. This [post](https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6) could better explain the differences between the various options.
My problem is that I wanted to create a new column which was the difference of a value in the current row and a value in a prior row without using iteration. I think the more "panda-esque" way of doing this (without iteration) would be to use dataframe.shift() to create a new column which contains the prior rows data ...
1,868
36,190,757
I am trying to use the One Million Song Dataset, for this i had to install python tables, numpy, cython, hdf5, numexpr, and so. Yesterday i managed to install all i needed, and after having some troubles with hdf5, i downloaded the precompiled binary packages and saved them in my /bin folder, and the respective libra...
2016/03/23
[ "https://Stackoverflow.com/questions/36190757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2869143/" ]
I had the same problem, probably you have installed numpy without Anaconda, so there is a conflict because of this, which numpy to use: that one installed with pip or with conda. When I removed non-Anaconda numpy, error gone. ``` pip uninstall numpy ```
First remove `numpy` from `/usr/local/lib/python2.7/dist-packages/numpy-1.11.0-py2.7-linux-x86_64.egg` and then use the following command `sudo pip install numpy scipy` I had solve this error in my case.
1,869
59,227,170
i run a python program using `beautifulsoup` and `requests` to scrape embedded videos URL , but to download theses videos i need to bypass a ads popups and `javascript` reload only then the `m3u8` files start to appear in the network traffic; so i need to simulate the clicks to get to the `javascript` reload (if there...
2019/12/07
[ "https://Stackoverflow.com/questions/59227170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12496538/" ]
There is no rule against using selenium side by side with beautifulsoup and requests. You can use the selenium to bypass the clicks, popups and ads and use beautifulsoup and requests to download the videos after the urls have appeared. You can redirect selenium to different urls using the results you get from running a...
> > Blockquote > `i run a python program using beautifulsoup and requests to scrape embedded videos URL , but to download theses videos i need to bypass a ads popups and javascript reload only then the m3u8 files start to appear in the network traffic; > > > so i need to simulate the clicks to get to the javascri...
1,879
24,853,027
I have installed Django 1.6.5 with PIP and Python 2.7.8 from the website. I ran `django-admin.py startproject test123`, switched to `test123` directory, and ran the command `python manage.py runserver`, then i get this: ``` Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_...
2014/07/20
[ "https://Stackoverflow.com/questions/24853027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/637619/" ]
Followed this SO answer: [Uninstall python.org version of python2.7 in favor of default OS X python2.7](https://stackoverflow.com/questions/13538586/uninstall-python-org-version-of-python2-7-in-favor-of-default-os-x-python2-7) Then changed my `.bash_profile` Python path to `/usr/lib/python` for the default OSX python...
You most likely have another file named `operator.py` on your `PYTHONPATH` (probably in the current working directory), which shadows the standard library `operator` module.. Remove or rename the file.
1,880
45,718,546
In python 3, you can now open a file safely using the `with` clause like this: ``` with open("stuff.txt") as f: data = f.read() ``` Using this method, I don't need to worry about closing the connection I was wondering if I could do the same for the multiprocessing. For example, my current code looks like: ```...
2017/08/16
[ "https://Stackoverflow.com/questions/45718546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2208112/" ]
``` with multiprocessing.Pool( ... ) as pool: pool.starmap( ... ) ``` <https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool> > > New in version 3.3: Pool objects now support the context management protocol – see Context Manager Types. **enter**() returns the pool object, and **exit**...
Although its more than what the OP asked, if you want something that will work for both Python 2 and Python 3, you can use: ```py # For python 2/3 compatibility, define pool context manager # to support the 'with' statement in Python 2 if sys.version_info[0] == 2: from contextlib import contextmanager @context...
1,885
48,512,269
Hi guys I am trying to read from subprocess.PIPE without blocking the main process. I have found this code: ``` import sys from subprocess import PIPE, Popen from threading import Thread try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty # python 3.x ON_POSIX = 'posix' i...
2018/01/30
[ "https://Stackoverflow.com/questions/48512269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7395188/" ]
I was away from my project for a long time but finally I manged to solve the issue. ``` from subprocess import PIPE, Popen from threading import Thread p = Popen(['myprogram.exe'], stdout=PIPE) t = Thread(target=results) t.daemon = True t.start() def results(): a = p.stdout.readline() ``` Maybe this is not ex...
On a unix environment you can simply make the stdout/stderr/stdin file descriptors nonblocking like so: ``` import os, fcntl from subprocess import Popen, PIPE def nonblock(stream): fcntl.fcntl(stream, fcntl.F_SETFL, fcntl.fcntl(stream, fcntl.F_GETFL) | os.O_NONBLOCK) proc = Popen("for ((;;)) { date; sleep 1; }"...
1,886
28,371,555
I have written this script to test a single ip address for probing specific user names on smtp servers for a pentest. I am trying now to port this script to run the same tests, but to a range of ip addresses instead of a single one. Can anyone shed some light as to how that can be achieved? ``` #!/usr/bin/python impo...
2015/02/06
[ "https://Stackoverflow.com/questions/28371555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4283164/" ]
I would implement this by turning your code as it stands into a function to probe a single host, taking the host name/ip as an argument. Then, loop over your list of hosts (either from the command line, a file, interactive querying of a user, or wherever) and make a call to your single host probe for each host in the l...
Ok, so here is what I have done to get this going. The solution is not elegant at all but it does the trick, and also, I could not spend more time trying to find a solution on this purely in Python, so I have decided, after reading the answer from bmhkim above(thanks for the tips) to write a bash script to have it ite...
1,887
57,331,667
I'm using `poetry` library to manage project dependencies, so when I use `docker build --tag=helloworld .` I got this error ``` [AttributeError] 'NoneType' object has no attribute 'group' ``` Installing breaks on `umongo (2.1.0)` package Here is my `pyproject.toml` file ``` [tool.poetry.dependen...
2019/08/02
[ "https://Stackoverflow.com/questions/57331667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6804296/" ]
The following works for me: ``` FROM python:3.7.1-alpine WORKDIR /opt/project RUN pip install --upgrade pip && pip --no-cache-dir install poetry COPY ./pyproject.toml . RUN poetry install --no-dev ``` with pyproject.toml: ``` [tool.poetry] name = "57331667" version = "0.0.1" authors = ["skufler <skufler@email.c...
If you want to install it with pip3 in production, here's how the latest version of Poetry (late 2021) can export a requirements.txt file: ```sh # Production with no development dependencies poetry export --no-interaction --no-ansi --without-hashes --format requirements.txt --output ./requirements.prod.txt # For deve...
1,889
48,301,318
I have a Python script where I import `datadog` module. When I run `python datadog.py`, it fails with `ImportError: cannot import name statsd`. The script starts with following lines: ``` import os import mysql.connector from time import time from datadog import statsd ``` Actual error messages are following: ``` ...
2018/01/17
[ "https://Stackoverflow.com/questions/48301318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8495751/" ]
The problem is that your script is named `datadog.py`. So when it imports the module `datadog`, it imports itself.
First install statsd by ``` pip install statsd ``` then do ``` import statsd ```
1,891
69,970,902
s =[(1, 2), (2, 3), (3, 4), (1, 3)] Output should be: 1 2 2 3 3 4 1 3 #in python only **"WITHOUT USING FOR LOOP"** In below code ``` ns=[[4, 4], [5, 4], [3, 3]] for x in ns: n=x[0] m=x[1] f=list(range(1,n+1)) l=list(range(2,n+1)) permut = itertools.permutations(f, 2) permut=list(permut)...
2021/11/15
[ "https://Stackoverflow.com/questions/69970902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17415916/" ]
I had this issue last night, tried with php 7.3 and 7.4 in the end i just used the latest php 8.1 and this issue went away.
You could try going to `illuminate/log/Logger.php` and adding `use Monolog\Logger as Monolog;` at the beginning of the file. After that, change the constructor from this: ``` /** * Create a new log writer instance. * * @param \Psr\Log\LoggerInterface $logger * @param \Illuminate\Contracts\Ev...
1,892
14,142,144
I have a custom field located in my `/app/models.py` . My question is... What is the best practice here. Should I have a separate file i.e. `customField.py` and import to the `models.py`, or should it be all in the same `models.py` file? best practice ``` class HibernateBooleanField(models.BooleanField): __meta...
2013/01/03
[ "https://Stackoverflow.com/questions/14142144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578822/" ]
If you're on Oracle 11g you can use the DBMS\_PARALLEL\_EXECUTE package to run your procedure in multiple threads. [Find out more](http://docs.oracle.com/cd/E11882_01/appdev.112/e25788/d_parallel_ex.htm#CHDIJACH). If you're on an earlier version you can implement DIY parallelism using a technique from Tom Kyte. The H...
Sounds like you need a set of queries using the MySql `LIMIT` clause to implement paging (e.g. a query would get the first 1000, another would get the second 1000 etc..). You could form these queries and submit as `Callables` to an [Executor service](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Ex...
1,893
6,367,014
In my `settings.py`, I have the following: ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 1025 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAI...
2011/06/16
[ "https://Stackoverflow.com/questions/6367014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/749477/" ]
I had actually done this from Django a while back. Open up a legitimate GMail account & enter the credentials here. Here's my code - ``` from email import Encoders from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart def sendmail(to, subject, text, att...
below formate worked for me > > EMAIL\_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' > > > EMAIL\_USE\_TLS = True EMAIL\_HOST = 'mail.xxxxxxx.xxx' > > > EMAIL\_PORT = 465 > > > EMAIL\_HOST\_USER = 'support@xxxxx.xxx' > > > EMAIL\_HOST\_PASSWORD = 'xxxxxxx' > > >
1,894
58,414,393
Say i have a dataframe as shown below ``` Stock open high low close Avg 0 SBIN 255.85 256.00 255.80 255.90 Nan 1 HDFC 1222.25 1222.45 1220.45 1220.45 Nan 2 SBIN 255.95 255.95 255.85 255.85 Nan 3 HDFC 1222.00 1222.50 1221.70 1221.95 ...
2019/10/16
[ "https://Stackoverflow.com/questions/58414393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559306/" ]
You can use `groupby` and `rolling` ``` df['Avg'] = df.groupby('Stock', as_index=False)['close'].rolling(3).mean().reset_index(0,drop=True) df Out[1]: Stock open high low close Avg 0 SBIN 255.85 256.00 255.80 255.90 NaN 1 HDFC 1222.25 1222.45 1220.45 1220.45 ...
As I understood from your df you are trying to calculate something like moving average metric. To do this you can simply use for iteration: ``` for i in range(0, df.shape[0] - 2): df.loc[df.index[i + 2], 'AVG'] = np.round(((df.iloc[i, 1] + df.iloc[i + 1, 1] + df.iloc[i + 2, 1]) / 3), 1) ``` Where in pd.loc cla...
1,904
14,568,370
I have the following code ``` # logging from twisted.python import log import sys # MIME Multipart handling import email import email.mime.application import uuid # IMAP Connection from twisted.mail import imap4 from twisted.internet import protocol #SMTP Sending import os.path from OpenSSL.SSL import SSLv3_METHOD...
2013/01/28
[ "https://Stackoverflow.com/questions/14568370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410368/" ]
``` from twisted.internet.endpoints import TCP4ClientEndpoint d = TCP4ClientEndpoint(reactor, host, int(port)).connect(factory) ``` and ``` d.addCallback(lambda r: factory.deferred) ``` instead of ``` d = factory.deferred ``` in `connectToIMAPServer` should do it - your `factory.deferred` will be returned o...
I eventually edited the code around and just managed the deferred's callback or errback internally update code ``` # logging from twisted.python import log import sys # MIME Multipart handling import email import email.mime.application import uuid # IMAP Connection from twisted.mail import imap4 from twisted.intern...
1,905
35,266,464
I was trying to build this example: <https://www.linuxvoice.com/build-a-web-browser-with-20-lines-of-python/> I'll just repost it here for completeness: ``` from PyQt5.QtCore import QUrl from PyQt5.QtWidgets import QApplication from PyQt5.QtWebKitWidgets import QWebView import sys app = QApplication(sys.argv) ...
2016/02/08
[ "https://Stackoverflow.com/questions/35266464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5016028/" ]
SO here's the actual answer. I had the same issue and discovered it very fast. `view.setUrl(QUrl(“http://linuxvoice.com”))` Notice that their code uses quotes, look at how the quotes are compared to normal quotes. Normal: "" Theirs: “” Basically, they're using weird ASCII quotes that Python can't handle. Really snea...
You've got a stray byte somewhere in your code. It's popped up on StackOverflow previously and there's a good method for finding it: [Python "SyntaxError: Non-ASCII character '\xe2' in file"](https://stackoverflow.com/questions/21639275/python-syntaxerror-non-ascii-character-xe2-in-file).
1,906
43,322,201
I have a Flask application using python3. Sometimes it create daemon process to run script, then I want to kill daemon when timeout (use `signal.SIGINT`). However, some processes which created by `os.system` (for example, `os.system('git clone xxx')`) are still running after daemon was killed. so what should I do? Tha...
2017/04/10
[ "https://Stackoverflow.com/questions/43322201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7844505/" ]
In order to be able to kill a process you need its process id (usually referred to as a pid). `os.system` doesn't give you that, simply returning the value of the subprocess's return code. The newer `subprocess` module gives you much more control, at the expense of somewhat more complexity. In particular it allows you...
The following command on the command line will show you all the running instances of python. ``` $ ps aux | grep -i python username 6488 0.0 0.0 2434840 712 s003 R+ 1:41PM 0:00.00 python ``` The first number, `6488`, is the PID, process identifier. Look through the output of the command on your machine...
1,907
40,821,604
I want to write to an element in a nested list named `foo`, but the nesting depth and indexes is only known at runtime, in a (non-nested!) list variable named `indexes`. Examples: If `indexes` is `[4]`, I want `foo[4]`. If `indexes` is `[4,7]`, I want `foo[4][7]`. If `indexes` is `[4,7,3]`, I want `foo[4][7][3]`. ...
2016/11/26
[ "https://Stackoverflow.com/questions/40821604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174365/" ]
You can use the [`reduce()` function](https://docs.python.org/2/library/functions.html#reduce): ``` from functools import reduce # Python 3 forward compatibility import operator def access(lst, indexes): return reduce(operator.getitem, indexes, lst) ``` You *could* use `list.__getitem__` instead of [`operator....
You can set `item` to `foo`, then proceeds with the indexes list to access deeper nested elements: ``` def access (foo, indexes): item = foo for index in indexes: item = item[index] return item ```
1,908
22,864,305
Im a very new Python user (2.7) and have been working my way through the Learn Python The Hard Way course and up to chap 37 and decided to do read through some other learning materials and go over the basics again and do exercises there. I have been reading through this: <http://anh.cs.luc.edu/python/hands-on/3.1/hand...
2014/04/04
[ "https://Stackoverflow.com/questions/22864305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3286810/" ]
[`raw_input()`](https://docs.python.org/2.7/library/functions.html#raw_input) returns a string: ``` >>> credits = raw_input("> ") > 150 >>> type(credits) <type 'str'> ``` You need to cast it to `int`: ``` credits = int(raw_input("> ")) ```
In your code, at the if statement you are comparing a `str` type with a `int` type. so it is not working as you axpected. Cast the `credit` as `int` ``` print "How many credits do you currently have: " credits = raw_input("> ") credits = int(credits) if credits >= 120: print "You have graduated!" else: print "So...
1,909
11,958,728
python 2.6.8 ``` s= ''' foo bar baz ''' >>>re.findall(r'^\S*',s,re.MULTILINE) ['', 'foo', 'bar', 'baz', ''] >>>ptrn = re.compile(r'^\S*',re.MULTILINE) >>>ptrn.findall(s) ['', 'foo', 'bar', 'baz', ''] >>>ptrn.findall(s,re.MULTILINE) ['baz', ''] ``` Why is there a difference between using MULTILINE flag in findall?
2012/08/14
[ "https://Stackoverflow.com/questions/11958728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293804/" ]
When calling the `findall()` method on a regex object, the second parameter is not the `flags` argument (because that has already been used when compiling the regex) but the `pos` argument, telling the regex engine at which point in the string to start matching. `re.MULTILINE` is just an integer (that happens to be `8...
Because the `findall` method of the compiled object `ptrn` doesn't take the MULTILINE parameter. It takes a `position` argument. See here: <http://docs.python.org/library/re.html#re.RegexObject.findall> The MULTILINE specifier is only used when you call `re.compile()` The resulting `ptrn` object already 'knows' that ...
1,912
45,110,802
I am working on using an ElasticSearch database to store data I am pulling from online. However, when I try to index the data in the database I receive an error. Here is my code for creating and indexing the data: ``` es = Elasticsearch() es.index(index='weather', doc_type='data', body=doc) ``` However when I run ...
2017/07/14
[ "https://Stackoverflow.com/questions/45110802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6848466/" ]
''missing authentication token' means you need to authenticate before you can talk to this Elasticsearch instance. To index documents, the user must have write access. You can include a username and password in a URL like this: <http://user:password@hostname:port> For example, in a shell: ``` export ES_ENDPOINT="http...
Also, if you do it from Postman tool, for example: Go to Authorization tab, Basic Auth, write here username and password which you was received by clicking elasticsearch-setup-passwords.bat [![enter image description here](https://i.stack.imgur.com/pUSlW.png)](https://i.stack.imgur.com/pUSlW.png)
1,913
59,777,244
I am a very new programmer and wanted to try out the AIY voice kit that uses Google Assistant API. I have a step-by-step guide that pretty much tells me how to set it up but now when it's up and running the guide tells me to run "assistant\_library\_demo.py" which is to make sure that the google assistant understands y...
2020/01/16
[ "https://Stackoverflow.com/questions/59777244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12727174/" ]
You have to return the generate value to the Button. ``` <asp:Button OnClientClick="return Generate()" <script> var test = 2; function Generate() { if (test === 1) return true; else return false; } </script> ```
Your problem lies in `OnClientClick="Generate();" OnClick="Button2_Click"`. You're assigning two inline click events here, so they'll both trigger independently. You have to handle the `Button2_Click` function from inside `Generate`. One way you might do this is to call `Button2_Click` in the else condition: ``` ...
1,919
40,245,703
I'm using python to hit a foreman API to gather some facts about all the hosts that foreman knows about. Unfortunately, there is not *get-all-hosts-facts* (or something similar) in the v1 foreman API, so I'm having to loop through all the hosts and get the information. Doing so has lead me to an annoying problem. Each ...
2016/10/25
[ "https://Stackoverflow.com/questions/40245703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2872525/" ]
It would be better to assemble all of your data into one dict and then write it all out one time, instead of each time in the loop. ``` d = {} for i in hosts_data: log.info("Gathering host facts for host: {}".format(i['host']['name'])) try: facts = requests.get(foreman_host+api+"hosts/{}/facts".format(...
Instead of writing json inside the loop, insert the data into a `dict` with the correct structure. Then write that dict to json when the loop is finished. This assumes your dataset fit into memory.
1,920
66,528,149
I'm trying to deploy a Django application on Google App Engine. I followed the instructions given [here](https://cloud.google.com/python/django/appengine#macos-64-bit). The only problem is that when I execute the command `gcloud app deploy` I than get the error: > > ERROR: (gcloud.app.deploy) NOT\_FOUND: Unable to re...
2021/03/08
[ "https://Stackoverflow.com/questions/66528149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13922881/" ]
Same problem with Node, **just waited and tryed again** the command later and that's work for me (in the same shell, no steps between).
I had the same issue when deploying a Java application to an App Engine. Enabling the 'Cloud Build API' under the APIs & Services section in the Google console resolved the issue for me.
1,923
4,042,995
> > **Possible Duplicate:** > > [What is the equivalent of the C# “using” block in IronPython?](https://stackoverflow.com/questions/1757296/what-is-the-equivalent-of-the-c-using-block-in-ironpython) > > > I'm writing some IronPython using some disposable .NET objects, and wondering whether there is a nice "pyt...
2010/10/28
[ "https://Stackoverflow.com/questions/4042995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7532/" ]
Python 2.6 introduced the `with` statement, which provides for automatic clean up of objects when they leave the `with` statement. I don't know if the IronPython libraries support it, but it would be a natural fit. Dup question with authoritative answer: [What is the equivalent of the C# "using" block in IronPython?](...
If I understand correctly, it looks like the equivalent is the [`with`](http://docs.python.org/reference/compound_stmts.html#with) statement. If your classes define context managers, they will be called automatically after the with block.
1,933
54,560,326
so i'm fairly new to python and coding in general and i decided to make a text based trivia game as a sort of test. and I've coded everything for the first question. code which i will repeat for each question. my problem is specifically on lines 10-11. the intended function is to add one to the current score, then prin...
2019/02/06
[ "https://Stackoverflow.com/questions/54560326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11024647/" ]
`scoregained` isn't a function, it is a variable you assign but do not update. This would be a great place for a function, which you can reuse whenever you want to print the score. For example: ``` def print_score(score): print('Your score is {}'.format(score)) ``` You can reuse this function anytime you wish to...
I'd probably use something like: ``` def score_stats(score): print('Your score is {}'.format(score)) input('TRIVIA: press enter to start') score, strike = 0, 3 strikesleft = 'strikes left: {}'.format(strike) score_stats(score) Q1 = input('What is the diameter of the earth?') if Q1 == '7917.5': print('correct...
1,938