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
14,129,983
I need a script that updates my copy of a repository. When I type "svn up" I usually am forced to enter a password, how do I automate the password entry? What I've tried: ``` import pexpect, sys, re pexpect.run("svn cleanup") child = pexpect.spawn('svn up') child.logfile = sys.stdout child.expect("Enter passphrase...
2013/01/02
[ "https://Stackoverflow.com/questions/14129983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/424631/" ]
If you don't want to type password many times, but still have a secure solution you can use **ssh-agent** to keep your key passphrases for a while. If you use your default private key simply type `ssh-add` and give your passphrase when asked. More details on `ssh-add` command usage are here: [linux.die.net/man/1/ssh-a...
You should really just use ssh with public keys. In the absence of that, you can simply create a new file in `~/.subversion/auth/svn.simple/` with the contents: ``` K 8 passtype V 6 simple K 999 password V 7 password_goes_here K 15 svn:realmstring V 999 <url> real_identifier K 8 username V 999 username_goes_here END ...
2,186
23,390,397
So i've been at this one for a little while and cant seem to get it. Im trying to execute a python script via terminal and want to pass a string value with it. That way, when the script starts, it can check that value and act accordingly. Like this: ``` sudo python myscript.py mystring ``` How can i go about doing t...
2014/04/30
[ "https://Stackoverflow.com/questions/23390397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1661607/" ]
Try the following inside ur script: ``` import sys arg1 = str(sys.argv[1]) print(arg1) ```
Since you are passing a string, you need to pass it in quotes: ``` sudo python myscript.py 'mystring' ``` Also, you shouldn't have to run it with sudo.
2,187
57,809,780
I'm trying to convert a .tif image in python using the module skimage. It's not working properly. ``` from skimage import io img = io.imread('/content/IMG_0007_4.tif') io.imsave('/content/img.jpg', img) ``` Here is the error: ``` /usr/local/lib/python3.6/dist-packages/imageio/core/functions.py in get_writer(uri, fo...
2019/09/05
[ "https://Stackoverflow.com/questions/57809780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8229169/" ]
1. I don't think HAVING will work without GROUP. 2. I would move the having clause outside the include section and use the AS aliases. So, roughly: `group: ['id'], // and whatever else you need having : { 'documents.total_balance_due' : {$eq : 0 }}` (Making some guesses vis the aliases)
> > To filter the date from joined table which uses groupby as well, you can make use of HAVING Property, which is accepted by Sequelize. > > > So with respect to your question, I am providing the answer. You can make use of this code: ``` const Sequelize = require('sequelize'); let searchQuery = { attribut...
2,188
26,290,871
How can I build a python distribution RPM that is only dependent on an *earlier* version of python? **Why?** I'm trying to build a distribution RPMs for RHEL6/CentOS 6, which only includes Python 2.6, but I am building usually on machines with Python 2.7. This is an open source project, and I have already ensured t...
2014/10/10
[ "https://Stackoverflow.com/questions/26290871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/95122/" ]
Re-organized the answer. Actually, there's no "rpm-package". There're rpm-packages for RHEL6, rpm-packages for FedoraNN, rpm-packagse for OpenSUSE-X.Y and so on. And besides there're Debian, Ubuntu, Arch and Gentoo :) You have the following possibilities with your Python package: 1. You may completely avoid rpm-, de...
I do not do very much python work but have done some RPM packaging. You probably need to somehow do what one would normally do in the RPM's spec file and specify and require a particular release of your python package like so ... ``` # this would be in your spec file requires: python <= 2.6 ``` Take a look here for ...
2,189
31,910,680
I installed the networking module **Scapy**. When I import scapy (`import scapy`) everything works fine. When I import all from scapy (`from scapy.all import *`), it brings up this error: ``` Traceback (most recent call last): File "/Users/***/Downloads/test.py", line 5, in <module> from scapy.all import * File "/Libr...
2015/08/10
[ "https://Stackoverflow.com/questions/31910680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4844191/" ]
**You can now install this easily** with [Homebrew](http://brew.sh) by using the command: ``` brew install libdnet ``` after you've installed Homebrew.
**Up-to-date edit: this issue has been fixed on recent versions of scapy, simply update your scapy version using `pip install scapy>=2.4.0`** You have to install libdnet. Not the python library (which does not work on python3 as you mentioned), but the library itself. There has to be library file libdnet.so somewhere ...
2,190
73,920,457
How for I get the "rest of the list" after the the current element for an iterator in a loop? I have a list: `[ "a", "b", "c", "d" ]` They are not actually letters, they are words, but the letters are there for illustration, and there is no reason to expect the list to be small. For each member of the list, I need ...
2022/10/01
[ "https://Stackoverflow.com/questions/73920457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1783593/" ]
Seems like there are plenty of answers here, but another way to solve your given problem: ```py def f(depth, l): for idx, item in enumerate(l): step = f"{depth * ' '} {depth} {item[0]}" print(step) f(depth + 1, l[idx + 1:]) f(0,[ "a", "b", "c", "d" ]) ```
``` def f(depth, alist): # you dont need this if you only care about first # for i in list: print(f"{depth} {alist[0]}") next_depth = depth + 1 rest_list = alist[1:] f(next_depth,rest_list) ``` this doesnt seem like a very useful method though ``` def f(depth, alist): # if you actually want to iterate...
2,193
48,535,962
My data has a feature called level, and the data may have levels(-1,0,1,2,3) but my data now has only 2 levels 0 and -1. I'm using python for binary classification. How to do one-hot-encoding with all levels? What is the right approach to deal with this problem? Can I include all levels as I may expect them in test dat...
2018/01/31
[ "https://Stackoverflow.com/questions/48535962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9186358/" ]
Currently it is assigning the last value as all parameter have same name. You can use `[]` after variable name , it will create newcoach array with all values within it. ``` $test = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14"; echo '<pre>'; parse_str($test,$result); print_r($result); ``` ...
Use this function ``` function proper_parse_str($str) { # result array $arr = array(); # split on outer delimiter $pairs = explode('&', $str); # loop through each pair foreach ($pairs as $i) { # split into name and value list($name,$value) = explode('=', $i, 2); # if name already exists ...
2,195
39,303,710
I am new to Python and machine learning and i am trying to work out how to fix this issue with date time. next\_unix is 13148730, because that is how many seconds are in five months, which is the time in between my dates. I have searched and i can't seem to find anything that works. ``` last_date = df.iloc[1,0] last_u...
2016/09/03
[ "https://Stackoverflow.com/questions/39303710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2770803/" ]
If my understanding is correct then you can get desired result with the following: ``` SELECT i.*, CASE WHEN prop1.PROPERTY_ID = 1 THEN prop1.VALUE ELSE '' END AS PROPERTY_ONE, CASE WHEN prop1.PROPERTY_ID = 2 THEN prop1.VALUE ELSE '' END AS PROPERTY_TWO FROM ITEM i LEFT JOIN ITEM_PROPERTY prop1 on i.ITEM_I...
``` Select i.*, GROUP_CONCAT(prop.VALUE) as PROPERTY_VALUE From ITEM i Left Join ITEM_PROPERTY prop on i.ITEM_ID = prop.ITEM_D ```
2,198
50,693,966
I have a directory containing many images(\*.jpg). Each image has a name. In the same directory i have a file containing python code(below). ``` import numpy as np import pandas as pd import glob fd = open('melanoma.csv', 'a') for img in glob.glob('*.jpg'): dataFrame = pd.read_csv('allcsv.csv') name = dataFra...
2018/06/05
[ "https://Stackoverflow.com/questions/50693966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6612871/" ]
First, your code reads the .csv file once for every image. Second, you have a nested `for`-loop. Both is not ideal. I recommend the following approach: **Step 1 - Create list of image file names** ``` import glob image_names = [f.replace('.jpg', '') for f in glob.glob("*.jpg")] ``` **Step 2 - Create dataframe with...
This is just a solution for storing the matched values to a new file melanoma.csv. Your code can be further improved and optimized. ``` import numpy as np import pandas as pd import glob # Create a dictionary object d={} for img in glob.glob('*.jpg'): dataFrame = pd.read_csv('allcsv.csv') name = dataFrame[...
2,202
39,771,366
I am a beginner in python. However, I have some problems when I try to use the readline() method. ``` f=raw_input("filename> ") a=open(f) print a.read() print a.readline() print a.readline() print a.readline() ``` and my txt file is ``` aaaaaaaaa bbbbbbbbb ccccccccc ``` However, when I tried to run it on a Mac t...
2016/09/29
[ "https://Stackoverflow.com/questions/39771366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6899656/" ]
When you open a file you get a pointer to some place of the file (by default: the begining). Now whenever you run `.read()` or `.readline()` this pointer moves: 1. `.read()` reads until the end of the file and moves the pointer to the end (thus further calls to any reading gives nothing) 2. `.readline()` reads until n...
You need to understand the concept of file pointers. When you read the file, it is fully consumed, and the pointer is at the end of the file. > > It seems that the readline() is not working at all. > > > It is working as expected. There are no lines to read. > > when I disable print a.read(), the readline() ...
2,203
883,313
On a django site, I want to generate an excel file based on some data in the database. I'm thinking of using [xlwt](http://pypi.python.org/pypi/xlwt), but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library? I've also found this [snip...
2009/05/19
[ "https://Stackoverflow.com/questions/883313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/92763/" ]
You can save your XLS file to a [StringIO](http://docs.python.org/library/stringio.html) object, which is file-like. You can return the StringIO object's `getvalue()` in the response. Be sure to add headers to mark it as a downloadable spreadsheet.
If your data result doesn't need formulas or exact presentation styles, you can always use CSV. any spreadsheet program would directly read it. I've even seen some webapps that generate CSV but name it as .XSL just to be sure that Excel opens it
2,206
14,484,386
I'm interrogating a nested dictionary using the dict.get('keyword') method. Currently my syntax is... ``` M = cursor_object_results_of_db_query for m in M: X = m.get("gparents").get("parent").get("child") for x in X: y = x.get("key") ``` However, sometimes one of the "parent" or "child" tags doesn't...
2013/01/23
[ "https://Stackoverflow.com/questions/14484386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1052117/" ]
Since these are all python `dict`s and you are calling the `dict.get()` method on them, you can use an empty `dict` to chain: ``` [m.get("gparents", {}).get("parent", {}).get("child") for m in M] ``` By leaving off the default for the last `.get()` you fall back to `None`. Now, if any of the intermediary keys is not...
Another approach is to recognize that if the key isn't found, `dict.get` returns `None`. However, `None` doesn't have an attribute `.get`, so it will throw an `AttributeError`: ``` for m in M: try: X = m.get("gparents").get("parent").get("child") except AttributeError: continue for x in X: ...
2,216
20,375,954
I have a large collection of images which I'm trying to sort according to quality by crowd-sourcing. Images can be assigned 1, 2, 3, 4, or 5 stars according to how much the user likes them. A 5-star image would be very visually appealing, a 1-star image might be blurry and out of focus. At first I created a page showi...
2013/12/04
[ "https://Stackoverflow.com/questions/20375954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216605/" ]
Sounds like you need a ranking algorithm similar to what is used in sport to rank players. Think of the comparison of two images as a match and the one the user selects as the better one is the winner of the match. After some time, many players have played many matches and sometimes against the same person. They win so...
Let each image start with a ranking of 3 (the mean of 1 … 5), then for each comparison (which wasn't equal) lower the rank of the loser image and increase the rank of the winner image. I propose to simply *count* the +1s and the -1s, so that you have a number of wins and a number of losses for each image. Then the val...
2,219
51,865,923
I have been trying out DroneKit Python and have been working with some of the examples provided. Having got to a point of some knowledge of working with DroneKit I have started writing some python code to perform a single mission. My only problem is that the start location for my missions are always defaulting to `Lat ...
2018/08/15
[ "https://Stackoverflow.com/questions/51865923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10231182/" ]
If you really don't want to wrap you can use `@media` queries to change `flex-direction` of your quizlist class to `column`. ```css input[type="radio"] { display: none; } input[type="radio"]:checked+.quizlabel { border: 2px solid #0052e7; transition: .1s; background-color: #0052e...
I think this is what you're aiming for? The boxes weren't getting smaller because of the text inside of them, so you needed to add `flex-wrap:wrap;` to the `.quizlist` so that way they would go onto the next row. You also needed to add a `flex` and `flex-grow` to specify the widths you want them to flex to. If you don...
2,222
71,949,010
After I install Google cloud sdk in my computer, I open the terminal and type "gcloud --version" but it says "python was not found" note: I unchecked the box saying "Install python bundle" when I install Google cloud sdk because I already have python 3.10.2 installed. so, how do fix this? Thanks in advance.
2022/04/21
[ "https://Stackoverflow.com/questions/71949010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17138122/" ]
As mentioned in the [document](https://cloud.google.com/sdk/docs/install-sdk#windows): > > Cloud SDK requires Python; supported versions are Python 3 (preferred, > 3.5 to 3.8) and Python 2 (2.7.9 or later). By default, the Windows version of Cloud SDK comes bundled with Python 3 and Python 2. To use > Cloud SDK, your...
On ubuntu Linux, you can define this variable in the `.bashrc` file: ```bash export CLOUDSDK_PYTHON=/usr/bin/python3 ```
2,223
15,866,765
What is the recommended library for web client programming which involves HTTP requests. I know there is a package called [HTTP](https://github.com/haskell/HTTP) but it doesn't seem to support HTTPS. Is there any better library for it ? I expect a library with functionality something like [this](http://docs.python-re...
2013/04/07
[ "https://Stackoverflow.com/questions/15866765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1651941/" ]
[`Network.HTTP.Conduit`](http://hackage.haskell.org/package/http-conduit) has a clean API (it uses [`Network.HTTP.Types`](http://hackage.haskell.org/package/http-types)) and is quite simple to use if you know a bit about conduits. Example: ```hs {-# LANGUAGE OverloadedStrings #-} module Main where import Data.Conduit...
In addition to `Network.HTTP.Conduit` there [`Network.Http.Client`](http://hackage.haskell.org/package/http-streams) which exposes an [`io-streams`](http://hackage.haskell.org/package/io-streams-1.0.1.0) interface.
2,224
11,923,645
Lets say i have this code: ``` def dosomething(thing1, thing2=hello, thing3=world): print thing1 print thing2 print thing3 ``` I would like to be able to specify what thing3 is, but wihout having to say what thing2 is. (The code below is how i thought it might work...) ``` dosomething("This says 'hello ...
2012/08/12
[ "https://Stackoverflow.com/questions/11923645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1542540/" ]
Use keyword arguments ``` dosomething("This says 'hello fail!'", thing3='fail!') ```
Yes, you can: ``` dosomething("This says 'hello fail!'", thing3 = 'fail!') ```
2,230
32,550,447
If I have a set of integers which denote the values that a list element can take and a python list of a given length. I want to fill the list with all possible combinations. **example** > > list `length=3` and the `my_set ={1,-1}` > > > **Possible combinations** ``` [1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1], [-1,1...
2015/09/13
[ "https://Stackoverflow.com/questions/32550447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4355529/" ]
That's what `itertools.product` is for : ``` >>> from itertools import product >>> list(product({1,-1},repeat=3)) [(1, 1, 1), (1, 1, -1), (1, -1, 1), (1, -1, -1), (-1, 1, 1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)] >>> ``` And if you want the result as list you can use `map` to convert the iterator of tuples to lis...
Use the [`itertools.product()` function](https://docs.python.org/3/library/itertools.html#itertools.combinations): ``` from itertools import product result = [list(combo) for combo in product(my_set, repeat=length)] ``` The `list()` call is optional; if tuples instead of lists are fine to, then `result = list(produ...
2,231
64,087,848
I'm trying to check how much times does some value repeat in a row but I ran in a problem where my code is leaving the last number without checking it. ``` Ai = input() arr = [int(x) for x in Ai.split()] c = 0 frozen_num = arr[0] for i in range(0,len(arr)): print(arr) if frozen_num == arr[0]: arr.rem...
2020/09/27
[ "https://Stackoverflow.com/questions/64087848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12733326/" ]
You could use the `Counter` of the `Collections` module to measure all the occurrences of different numbers. ``` from collections import Counter arr = list(Counter(input().split()).values()) print(arr) ``` Output with an input of `1 1 1 1 5 5`: ``` 1 1 1 1 5 5 [4, 2] ```
If you want to stick with your method and not use external libraries, you can add an if statement that detects when you reach the last element of your array and process it differently from the others: ``` Ai=input() arr = [int(x) for x in Ai.split()] L=[] c = 0 frozen_num = arr[0] for i in range(0, len(arr)+1): pr...
2,234
49,813,481
I am trying to fit some data that I have using scipy.optimize.curve\_fit. My fit function is: ``` def fitfun(x, a): return np.exp(a*(x - b)) ``` What i want is to define `a` as the fitting parameter, and `b` as a parameter that changes depending on the data I want to fit. This means that for one set of data I wo...
2018/04/13
[ "https://Stackoverflow.com/questions/49813481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7654219/" ]
I don't know if this is the "proper" way of doing things, but I usually wrap my function in a class, so that I can access parameters from `self`. Your example would then look like: ``` class fitClass: def __init__(self): pass def fitfun(self, x, a): return np.exp(a*(x - self.b)) inst = fitCl...
You can define `b` as a global variable inside the fit function. ``` from scipy.optimize import curve_fit def fitfun(x, a): global b return np.exp(a*(x - b)) xdata = np.arange(10) #first sample data set ydata = np.exp(2 * (xdata - 10)) b = 10 coeffs, coeffs_cov = curve_fit(fitfun, xdata, ydata) print(coef...
2,235
63,153,688
I edited this post so that i could give more info about the goal I am trying to achieve. basically I want to be able to open VSCode in a directory that I can input inside a python file I am running trhough a shell command i created. So what I need is for the python file to ask me for the name of the folder I want to op...
2020/07/29
[ "https://Stackoverflow.com/questions/63153688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12288571/" ]
Store dataValue in some variable and use expectation to wait for your closure to execute and then test. Note: This example was written in swift 4 ``` let yourExpectationName = expectation(description: "xyz") var dataToAssert = [String]() //replace with you data type sut.apiSuccessClouser = { dataValue in dataToA...
apiSuccessClouser in MockApiService is a property of type closure `(()->Void?)?`. In line `sut.apiSuccessClouser = { ... }` you assign the the property apiSuccessClouser a closure but you never access this closure so that the `print("apiSuccessClouser")` to be executed. to execute the print("apiSuccessClouser") you n...
2,243
54,060,243
Hi ultimately I'm trying to install django on my computer, but I'm unable to do this as the when I run pip in the command line I get the following error message: `''pip' is not recognized as an internal or external command, operable program or batch file.'` I've added the following locations to my path environment: ...
2019/01/06
[ "https://Stackoverflow.com/questions/54060243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9815902/" ]
You can put a conditional expression on a single item update to make the update fail if the condition is not met. However it will not fail an entire batch, just the single update. The batch update response would contain information on which updates succeeded and which failed
It's possible to do it, by using conditional expression for filter expression. But please don't do it. DynamoDB is a key-value NoSQL. It means that you can get the right data by keys only. If you do the filter, it will loop through a lot of records and slow down you app. You can check this article: [5 things that you...
2,245
98,687
I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework. The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect. What is the best "...
2008/09/19
[ "https://Stackoverflow.com/questions/98687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2168/" ]
IMO, the "more obvious/more idiomatic/better solution" is to use an existing ORM rather than invent DAO-like classes. It appears to me that ORM's are more popular than "raw" SQL connections. Why? Because Python *is* OO, and the mapping from a SQL row to an object *is* absolutely essential. There aren't many use cases ...
i did it for opensearch so you can refer it. ``` from opensearchpy import OpenSearch def get_connection(): connection = None try: connection = OpenSearch( hosts=[{'host': settings.OPEN_SEARCH_HOST, 'port': settings.OPE...
2,248
18,808,150
I have two accounts on my system, an admin account and a user account. I use the admin account to install macport and have set the default python using ``` sudo port select --set python python27 ``` On the user account I can run all the python I need using ``` /opt/local/bin/python ``` but how do I select that...
2013/09/15
[ "https://Stackoverflow.com/questions/18808150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816807/" ]
This is really a shell question. `which python` returns the first python on your PATH environment variable. The PATH variable is a list of paths that the shell searches for executables. This is usually set in .profile, .bash\_profile or .bashrc. If you reorder your paths, such that `/opt/local/bin` comes before `/usr/b...
You can use `alias python=/opt/local/bin/python` in your .bashrc, or the equivalent rc file for your shell.
2,258
57,903,358
I am attempting to build an image for the jetson-nano using yocto poky-warrior and meta-tegra warrior-l4t-r32.2 layer. I've been following [this thread](https://stackoverflow.com/questions/56481980/yocto-for-nvidia-jetson-fails-because-of-gcc-7-cannot-compute-suffix-of-object/56528785#56528785) because he had the same...
2019/09/12
[ "https://Stackoverflow.com/questions/57903358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5999131/" ]
When using Callable in dictConfig, the Callable you put into the value of dictConfig has to be a Callable which returns a Callable as discussed in the Python Bug Tracker: * <https://bugs.python.org/issue41906> E.g. ```py def my_filter_wrapper(): # the returned Callable has to accept a single argument (the LogRec...
I suggest using [loguru](https://github.com/Delgan/loguru) as logging package. you can easily add a handler for your logger.
2,259
31,444,776
I want to create a bunch of simple geometric shapes (colored rectangles, triangles, squares ...) using pygame and then later analyze their relations and features. I first tried [turtle](https://docs.python.org/2/library/turtle.html) but apparently that is only a graphing library and cannot keep track of the shapes it c...
2015/07/16
[ "https://Stackoverflow.com/questions/31444776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4321788/" ]
PyGame is a gaming library - it helps with making graphics and audio and controllers for games. It doesn't have support to detect objects in a preexisting image. What you want is OpenCV (It has Python bindings) - this is made to "understand" things about an image. One popular math algorithm used to detect shapes (or ...
Yes, It can, but pygame is also good for making games but unfortunately, you can't convert them to IOS or Android, in the past, there was a program called PGS4A which allowed you to convert pygame projects to android but sadly, the program has been discontinued and now, there is no way. On this case, my sggestion would...
2,261
51,772,333
I am new to python and would love to know this. Suppose I want to scrape stock price data from a website to excel. Now the data keeps refreshing every second, how do I refresh the data on my excel sheet automatically using python. I have read about win32 but couldn’t understand it’s use much. Any help would be dearly...
2018/08/09
[ "https://Stackoverflow.com/questions/51772333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10041192/" ]
As stated in the documentation: > > Help on built-in function readlines: > > > readlines(hint=-1, /) method of \_io.TextIOWrapper instance > Return a list of lines from the stream. > > > > ``` > hint can be specified to control the number of lines read: no more > lines will be read if the total size (in bytes/c...
The method `readlines()` reads all lines in a file until it hits the EOF (end of file). The "cursor" is then at the end of the file and a subsequent call to `readlines()` will not yield anything, because EOF is directly found. Hence, after `line_3 = fRead.readlines()[3]` you have consumed the whole file but only store...
2,262
34,124,259
I'm new here and fairly new to python and I have a question. I had a similar question during my midterm a while back and it has bugged me that I cannot seem to figure it out. The overall idea was that I had to find the longest string in a nested list. So I came up with my own example to try and figure it out but for ...
2015/12/06
[ "https://Stackoverflow.com/questions/34124259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5647743/" ]
As Simon mentioned, you should be using `FindAllString` to find all matches. Also, you need to remove the ^ from the beginning of the RE (^ anchors the pattern to the beginning of the string). You should also move the regexp.Compile outside the loop for efficiency.
<https://play.golang.org/p/Q_yfub0k80> As mentioned here, `FindAllString` returns a slice of all successive matches of the regular expression. But, `FindString` returns the leftmost match.
2,263
49,147,937
I am trying to get specific coordinates in an image. I have marked a red dot in the image at several locations to specify the coordinates I want to get. In GIMP I used the purist red I could find (HTML notation **ff000**). The idea was that I would iterate through the image until I found a pure shade of red and then pr...
2018/03/07
[ "https://Stackoverflow.com/questions/49147937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4902160/" ]
You can do it with cv2 this way: ``` image = cv2.imread('image.jpg') lower_red = np.array([0,0,220]) # BGR-code of your lowest red upper_red = np.array([10,10,255]) # BGR-code of your highest red mask = cv2.inRange(image, lower_red, upper_red) #get all non zero values coord=cv2.findNonZero(mask) ```
You can do this with PIL and numpy. I'm sure there is a similar implementation with cv2. ``` from PIL import Image import numpy as np img = Image.open('image.png') width, height = img.size[:2] px = np.array(img) for i in range(height): for j in range(width): if(px[i,j,0] == 255 & px[i,j,1] == 0 & px[i,j,2]...
2,264
57,462,530
I need to have a python GUI communicating with an mbed (LPC1768) board. I am able to send a string from the mbed board to python's IDLE but when I try to send a value back to the mbed board, it does not work as expected. I have written a very basic program where I read a string from the mbed board and print it on Pyth...
2019/08/12
[ "https://Stackoverflow.com/questions/57462530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11671221/" ]
If using index labels between 2 and 4 use `loc`: ``` df.loc[2:4, 'number'].max() ``` Output: ``` 10 ``` If using index integer positions 2nd through the 4th labels, then use `iloc`: ``` df.iloc[2:5, df.columns.get_loc('number')].max() ``` *Note: you must use `get_loc` to get the integer position of the column ...
Even can be used: ``` >>> df.iloc[2:4,:].loc[:,'number'].max() 10 ```
2,265
51,062,920
i'm tryng to import **mysqlclient** library for python with **pip**, when i use the command `pip install mysqlclient` it return an error: ``` Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz I...
2018/06/27
[ "https://Stackoverflow.com/questions/51062920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9595624/" ]
First install python 3.6.5, then run ``` pip install mysqlclient==1.3.12 ```
For me, it was a mixture of an old setup tools and missing packages ``` pip install --upgrade setuptools apt install gcc libssl-dev ```
2,266
60,520,272
I'm new to python and I've looked up a little bit of info and i cant't find the problem with my code, please help. Code: ``` array = [] print ('Enter values in array: ') for i in range(0,5): n = input("value: ") array.append(n) a = input("Enter search term: ") for i in range(len(array)): found = False ...
2020/03/04
[ "https://Stackoverflow.com/questions/60520272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13003923/" ]
You don't? > > Should prettier not be installed locally with your project's dependencies or globally on the machine, the version of prettier that is bundled with the extension will be used. > > > <https://github.com/prettier/prettier-vscode#prettier-resolution>
It seems like you want Prettier to be your code formatter in VS Code for all of your projects. In VS Code navigate to: > > File > Preferences > Settings > > > Search for "Default formatter" And then select "esbenp.prettier-vscode"
2,276
6,361,775
I know there are quite a few solutions for this problem but mine was peculiar in the sense that, I might get truncated utf16 data and yet have to make the best effort of dealing with conversions where decode and encode will fail with UnicodeDecodeError. So came up with the following code in python. Please let me know y...
2011/06/15
[ "https://Stackoverflow.com/questions/6361775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/684799/" ]
What about: ``` data = open(filename).read() try: data = data.decode("utf-16") except UnicodeDecodeError: data = data[:-1].decode("utf-16") ``` I.e. if it's truncated mid-way through a code unit, snip the last byte off, and do it again. That should get you back to a valid UTF-16 string, without having to try...
This just jumped out at me as a "best practice" improvement. File accesses should really be wrapped in `with` blocks. This will handle opening and cleaning up for you.
2,277
52,372,489
I am wanting to get the average brightness of a file in python. Having read a previous question [[Problem getting terminal output from ImageMagick's compare.exe ( Either by pipe or Python )](https://stackoverflow.com/questions/5145508/problem-getting-terminal-output-from-imagemagicks-compare-exe-either-by-pipe]) I have...
2018/09/17
[ "https://Stackoverflow.com/questions/52372489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7869335/" ]
This seems to works for me to return the mean as a variable that can be printed. **(This is a bit erroneous. See the correction near the bottom)** ``` #!/opt/local/bin/python3.6 import subprocess cmd = '/usr/local/bin/convert lena.jpg -format "%[fx:100*mean]" info:' mean=subprocess.call(cmd, shell=True) print (mean...
You can probably improve the subprocess, and eliminate the temporary text file with `Popen` + `PIPE`. ```py cmd=['/usr/bin/convert', full, '-format', '%[fx:100*image.mean]', 'info:'] pid = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess....
2,280
41,861,138
I am trying to loop through subreddits, but want to ignore the sticky posts at the top. I am able to print the first 5 posts, unfortunately including the stickies. Various pythonic methods of trying to skip these have failed. Two different examples of my code below. ``` subreddit = reddit.subreddit(sub) ...
2017/01/25
[ "https://Stackoverflow.com/questions/41861138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4750577/" ]
[It looks like you can get the id of a stickied post based on docs](http://praw.readthedocs.io/en/latest/code_overview/models/subreddit.html?highlight=sticky). So perhaps you could get the id(s) of the stickied post(s) (note that with the 'number' parameter of the sticky method you can say give me the first, or second,...
As an addendum to @Al Avery's answer, you can do a complete search for the IDs of all stickies on a given subreddit by doing something like ``` def get_all_stickies(sub): stickies = set() for i in itertools.count(1): try: sid = sub.sticky(i) except pawcore.NotFound: brea...
2,281
32,221,890
I want a user to input a list with object in every new line. The user will copy and past a whole list to the program and not enter a new object every time. For example, here is the users input: > > january > > february > > march > > april > > may > > june > > > and he gets a list just like th...
2015/08/26
[ "https://Stackoverflow.com/questions/32221890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4982967/" ]
You should use <http://eonasdan.github.io/bootstrap-datetimepicker/> datetimePicker, by setting the format of the `dateTimePicker` to `'hh:mm:ss'` You have to use - `moment.js` - For more formats, you should check: <http://momentjs.com/docs/#/displaying/format/> I have created a JSFiddle. <http://jsfiddle.net/jagtx6...
[DEMO](http://jsfiddle.net/SantoshPandu/B4BzK/466/) HTML ``` <div class="container"> <div class="row"> <div class="col-sm-6 form-group"> <label for="dd" class="sr-only">Time Pick</label> <input type="text" id="dd" name="dd" data-format="MM/DD/YYYY" placeholder="date" class=...
2,284
53,451,057
I would like to display the following ``` $ env/bin/python >>>import requests >>> requests.get('http://dabapps.com') <Response [200]> ``` as a code sample within a bullet paragraph for Github styled markdown. How do I do it?
2018/11/23
[ "https://Stackoverflow.com/questions/53451057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5722359/" ]
> > h:25:59: friend declaration delares a non template function. > > > You are missing to declare the function as a template that takes `Pairwise<K, V>`: header.h: ``` #ifndef HEADER_H_INCLUDED /* or pragma once */ #define HEADER_H_INCLUDED /* if you like it */ #include <iostream> // or <ostream> template<t...
As you write it, you define the operator as a member function, which is very likely not intended. Divide it like ... ``` template<typename K, typename V> struct Pairwise{ K first; V second; Pairwise() = default; Pairwise(K, V); //print out as a string in main friend ostream& operator<<(ostream ...
2,287
43,513,121
As per my application requirement, I need to get the server IP and the server name from the python program. But my application is resides inside the specific docker container on top of the Ubuntu. I have tried like the below ``` import os os.system("hostname") # to get the hostname os.system("hostname -i") # to get ...
2017/04/20
[ "https://Stackoverflow.com/questions/43513121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3666266/" ]
You won't be able to get the host system's name this way. To get it, you can either define an environment variable, either in your Dockerfile, or when running your container (-e option). Alternatively, you can mount your host `/etc/hostname` file into the container, or copy it... This is an example run command I use t...
An alternative might be the following: ENV: ``` NODENAME: '{{.Node.Hostname}}' ``` This will get you the Hostname of the Node, where the container is running as an environment variable (tested on Docker-Swarm / CoreOs Stable).
2,290
7,052,874
I had a custom script programmed and it is using the authors own module that is hosted on Google code in a Mercurial repo. I understand how to clone the repo but this will just stick the source into a folder on my computer. Is there a proper way to add the module into my python install to make it available for my proje...
2011/08/13
[ "https://Stackoverflow.com/questions/7052874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893341/" ]
In exactly the same way. Just pass the address of the repo to `pip install`, using the `-e` parameter: ``` pip install -e hg+http://code.google.com/path/to/repo ```
If the module isn't on pypi, clone the repository with Hg and see if there's a setup.py file. If there is, open a command prompt, cd to that directory, and run: ``` python setup.py install ```
2,293
48,601,123
Here I have a mistake that I can't find the solution. Please excuse me for the quality of the code, I didn't start classes until 6 months ago. I've tried to detach category objects with expunge but once it's added it doesn't work.I was thinking when detaching the object with expunge it will work. and I can't find a sol...
2018/02/03
[ "https://Stackoverflow.com/questions/48601123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8551016/" ]
This error happens when you try to add an object to a session but it is already loaded. The only line that I see you use .add function is at the end where you run: `connection.connect.add(article)` So my guess is that this Model is already loaded in the session and you don't need to add it again. You can add a try, e...
unloading all objects from session and then adding it again in session might help. ```py db.session.expunge_all() db.session.add() ```
2,294
10,732,812
I'm trying to read some numbers from a text file and convert them to a list of floats, but nothing I try seems to work right. Here's my code right now: ``` python_data = open('C:\Documents and Settings\redacted\Desktop\python_lengths.txt','r') python_lengths = [] for line in python_data: python_lengths.append(lin...
2012/05/24
[ "https://Stackoverflow.com/questions/10732812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367212/" ]
That is happening because `.split()` always returns a list of items even if there was just 1 element present. If you change your `python_lengths.append(line.split())` to `python_lengths.extend(line.split())` you will get your flat list you expected.
@eumiro's answer is correct, but here is something else that can help: ``` numbers = [] with open('C:\Documents and Settings\redacted\Desktop\python_lengths.txt','r') as f: for line in f.readlines(): numbers.extend(line.split()) numbers.sort() print numbers ```
2,296
41,528,941
I'm new to python and html. I am trying to retrieve the number of comments from a page using requests and BeautifulSoup. In this example I am trying to get the number 226. Here is the code as I can see it when I inspect the page in Chrome: ``` <a title="Go to the comments page" class="article__comments-counts" href="...
2017/01/08
[ "https://Stackoverflow.com/questions/41528941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7389440/" ]
The page, and specifically the number of comments, does involve JavaScript to be loaded and shown. But, *you don't have to use Selenium*, make a request to the API behind it: ``` import requests with requests.Session() as session: session.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) A...
This page use JavaScript to get the comment number, this is what the page look like when disable the JavaScript: [![enter image description here](https://i.stack.imgur.com/V8mcE.png)](https://i.stack.imgur.com/V8mcE.png) You can find the real url which contains the number in Chrome's Developer tools: [![enter image de...
2,298
26,575,303
Hello people I hope you an help me out with this problem: I am currently implementing an interpreter for a scripting language. The language needs a native call interface to C functions, like java has JNI. My problem is, that i want to call the original C functions without writing a wrapper function, which converts the...
2014/10/26
[ "https://Stackoverflow.com/questions/26575303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4180673/" ]
Yes we can. No FFI library needed, no restriction to C calls, only pure C++11. ``` #include <iostream> #include <list> #include <iostream> #include <boost/any.hpp> template <typename T> auto fetch_back(T& t) -> typename std::remove_reference<decltype(t.back())>::type { typename std::remove_reference<decltype(t.ba...
The way to do this is to use pointers to functions: ``` void (*native)(int a, int b) ; ``` The problem you will face is finding the address of the function to store in the pointer is system dependent. On Windoze, you will probably be loading a DLL, finding the address of the function by name within the DLL, then st...
2,299
36,655,197
i have problem running Django server in Intellij / Pycharm (I tried in both). There is that red cross: [![enter image description here](https://i.stack.imgur.com/ssyv5.jpg)](https://i.stack.imgur.com/ssyv5.jpg) And this is the error i get: [![Error running Django: Please select Django module](https://i.stack.imgur....
2016/04/15
[ "https://Stackoverflow.com/questions/36655197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3671716/" ]
If your IntelliJ is up to date, there is another solution. I had the exact same problem in **IntelliJ 2017.2** and it was driving me crazy until I read this [post from a IntelliJ maintainer](https://intellij-support.jetbrains.com/hc/en-us/community/posts/206936385-Intellij-Doesn-t-Recognize-Django-project). If you us...
Try adding `DJANGO_SETTINGS_MODULE=untitled.settings` to the environment variables listed in the configuration menu by clicking the dropdown titled 'Django' in your first photo.
2,302
63,412,757
I am training a variational autoencoder, using pytorch-lightning. My pytorch-lightning code works with a Weights and Biases logger. I am trying to do a parameter sweep using a W&B parameter sweep. The hyperparameter search procedure is based on what I followed from [this repo.](https://github.com/borisdayma/lightning-...
2020/08/14
[ "https://Stackoverflow.com/questions/63412757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10290585/" ]
The problem is that the structure of my code and the way that I was running the wandb commands was not in the correct order. Looking at [this pytorch-ligthning](https://github.com/AyushExel/COVID19WB/blob/master/main.ipynb) with `wandb` is the correct structure to follow. Here is my refactored code: ``` #!/usr/bin/en...
Do you launch python in your shell by typing `python` or `python3`? Your script could be calling python 2 instead of python 3. If this is the case, you can explicitly tell wandb to use python 3. See [this section of documentation](https://docs.wandb.com/sweeps/faq#sweep-with-custom-commands), in particular "Running Sw...
2,305
44,737,199
I've written a script to select certain field from a webpage using python with selenium. There is a dropdown on that page from which I want to select "All". However, i tried many different ways with my script to make it but could not. Here is how the dropdown look like. [![enter image description here](https://i.stack...
2017/06/24
[ "https://Stackoverflow.com/questions/44737199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9189799/" ]
This will work for you: ``` #option1 select_obj = Select(driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]')) select_obj.select_by_visible_text('All') #option2 select_obj = Select(driver.find_element_by_id('ctl00_body_MedicineSummaryControl_cmbPageSelection')) select_obj....
I initially thought of suggesting that you try to tab from an element that is before the dropdown select, similar to the concept in this code: ``` driver.find_element_by_id('<id of element before the dropdown select>').send_keys(Keys.TAB) driver.find_element_by_id('//select[@id="ctl00_body_MedicineSummaryControl_cmbPa...
2,306
2,361,328
I generally make my desktop interfaces with [Qt](http://www.pyside.org/), but some recent TK screenshots convince me Tk isn't just ugly motif any more. Additionally [Tkinter](http://docs.python.org/library/tkinter.html) comes bundled with Python, which makes distribution easier. So is it worth learning or should I st...
2010/03/02
[ "https://Stackoverflow.com/questions/2361328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105066/" ]
The answer to your question is a resounding **yes**. Qt is good, I have nothing against it. But Tk is better and far easier to use and quite [well documented](http://wiki.python.org/moin/TkInter) - not just on the Python webspace, but there are also many third-party tutorials out there. [This](http://www.pythonware.co...
As a step up to other GUI toolkits, sure. If you know other toolkits then you already understand TkInter and can leave it until you actually need it.
2,309
60,144,779
My formatting is terrible. Screenshot is here: [![enter image description here](https://i.stack.imgur.com/KrTnL.png)](https://i.stack.imgur.com/KrTnL.png) ```py n = int(input("enter the number of Fibonacci sequence you want. ") n1 = 0 n2 = 1 count = 0 if n <= 0: print("please enter a postive integer") elif n == 1:...
2020/02/10
[ "https://Stackoverflow.com/questions/60144779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870387/" ]
A ')' is missing in first line i guess, that's an issue.
When such error arises, do check for the preceding line also. There are very high chances of error being in the preceding line, as in this case. There's a `)` missing in the input line. You closed 1 `)` for the input() function, but did not close for `int` constructor.
2,316
70,709,117
i'm using this code to open edge with the defaut profile settings: ``` from msedge.selenium_tools import Edge, EdgeOptions edge_options = EdgeOptions() edge_options.use_chromium = True edge_options.add_argument("user-data-dir=C:\\Users\\PopA2\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default") edge_options.a...
2022/01/14
[ "https://Stackoverflow.com/questions/70709117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17603014/" ]
there is an issue in your style code.if you remove it than works smoothly ```html <!DOCTYPE html> <html> <head> <title>Page Title</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs...
for navigation design add these style to your code ```html <!DOCTYPE html> <html> <head> <title>Page Title</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/s...
2,317
30,078,967
I want to create new form view associated to new data model, I create a new menu item "menu1" that has a submenu "menus" and then, I want to customize the action view. This is my code: **My xml file:** **My data model:** ```python from openerp.osv import fields, osv class hr_cutomization(osv.osv): _inherit = "hr....
2015/05/06
[ "https://Stackoverflow.com/questions/30078967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4018649/" ]
Manage to sort it out with the following. ``` Add-WebConfigurationProperty //system.webServer/httpProtocol/customHeaders "IIS:\sites\test.test1.com" -AtIndex 0 -Name collection -Value @{name='Access-Control-Allow-Origin';value='*'} Add-WebConfigurationProperty //system.webServer/httpProtocol/customHeaders "IIS:\sit...
I think your XPath expression doesn't match the node you're trying to manipulate. Try this: ``` Add-WebConfigurationProperty -PSPath $sitePath ` -Filter 'system.webServer/httpProtocol/customHeaders/add[@name="Access-Control-Allow-Origin"]' ` -Name 'value' -Value '*' -Force ```
2,322
38,390,242
I work with python-pandas dataframes, and I have a large dataframe containing users and their data. Each user can have multiple rows. I want to sample 1-row per user. My current solution seems not efficient: ``` df1 = pd.DataFrame({'User': ['user1', 'user1', 'user2', 'user3', 'user2', 'user3'], 'B': ...
2016/07/15
[ "https://Stackoverflow.com/questions/38390242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358785/" ]
This is what you want: ``` df1.groupby('User').apply(lambda df: df.sample(1)) ``` [![enter image description here](https://i.stack.imgur.com/C1B60.png)](https://i.stack.imgur.com/C1B60.png) Without the extra index: ``` df1.groupby('User', group_keys=False).apply(lambda df: df.sample(1)) ``` [![enter image descri...
``` df1_user_sample_one = df1.groupby('User').apply(lambda x:x.sample(1)) ``` Using DataFrame.groupby.apply and lambda function to sample 1
2,323
54,727,804
I have a generator function which reads lines from a file and parses them to objects. The files are far too large to consider processing the entire file into a list which is why I've used the generator and not a list. I'm concerned because when calling the generator, my code will sometimes break. if it finds what it i...
2019/02/16
[ "https://Stackoverflow.com/questions/54727804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453851/" ]
This only releases resources promptly on CPython. To really be careful about resource release in this situation, you'd have to do something like ``` with contextlib.closing(read_massive_file(my_file)) as gen: for entry in gen: ... ``` but I've never seen anyone do it. --- When a generator is discarded ...
You never save the return value of `read_massive_file`; the only reference is held internally by the code generated by the `for` loop. As soon as that loop completes, the generator should be garbage collected. It would be different if you had written ``` foo = read_massive_file(my_file): for entry in foo: ... els...
2,329
20,739,353
Recently, I've found plot.ly site and am trying to use it. But, When I use Perl API, I can't success. My steps are same below. 1. I sign up plot.ly with google account 2. Installed Perl module(WebService::Plotly) 3. Type basic example("<https://plot.ly/api/perl/docs/line-scatter>") ..skip.. ``` use WebService::Plotl...
2013/12/23
[ "https://Stackoverflow.com/questions/20739353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3128831/" ]
please check below things, have found for you from some diff links: ``` 1. Make sure that PHP is installed. This sounds silly, but you never know. 2. Make sure that the PHP module is listed and uncommented inside of your Apache's httpd.conf This should be something like LoadModule php5_module "c:/php/...
I had the same problem with Debian 10 (buster) and PHP 7.3.19.1 and apache2 version 2.4.38 and phpmyadmin 5.02. The file `usr/share/phpmyadmin/index.php` was not interpreted. After verifying all the manual installation I ran the following commands: ``` apt-get update apt-get install libapache2-mod-php7.3 systemctl res...
2,330
55,619,345
I am making a card game in python. I used the code for a class of a stack that I found online : ``` class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.insert(0,item) def pop(self): return self.items.pop(0) ...
2019/04/10
[ "https://Stackoverflow.com/questions/55619345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7193131/" ]
After declaring `Cards` to be an instance of `Stack`, you don't need to refer to `Stack` anymore. Just use `Cards`. ``` Cards = Stack() Cards.push(15) x = Cards.peek() y = Cards.pop() ``` Also, the first line of code `Cards = []` is useless, as you immediately reassign `Cards` to be something else.
You shouldn't reassign `Cards` on each line. `Cards` is the `Stack` object, it needs to stay the same. It should be used as the variable with which you call all the other methods. ``` Cards = Stack() Cards.push(15) item = Cards.peek() item2 = Cards.pop() # item == item2 ```
2,340
37,738,498
I'm running into a problem I've never encountered before, and it's frustrating the hell out of me. I'm using `rpy2` to interface with `R` from within a python script and normalize an array. For some reason, when I go to piece my output together and print to a file, it takes **ages** to print. It also slows down as it p...
2016/06/10
[ "https://Stackoverflow.com/questions/37738498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4438552/" ]
If I am understanding this correctly everything is running fine and with good performance up to (and including) the line: ``` normalized_matrix = np.array(Rnormalized_matrix) ``` At that line the resulting matrix is turned into a numpy array (literally - it can be even faster when avoiding to copy the data, as in <h...
For one thing, I usually use a generator to avoid the temporary list of many tiny strings. ``` out_data = "\t".join("{0:.2f}".format(piece) for piece in norm_data) ``` But it's hard to tell if this part was the slow one.
2,341
64,334,348
**Question:** What is the difference between `open(<name>, "w", encoding=<encoding>)` and `open(<name>, "wb") + str.encode(<encoding>)`? They seem to (sometimes) produce different outputs. **Context:** While using [PyFPDF](https://pypi.org/project/fpdf/) (version 1.7.2), I subclassed the `FPDF` class, and, among...
2020/10/13
[ "https://Stackoverflow.com/questions/64334348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5278549/" ]
You can only have a single transaction in progress at a time with a producer instance. If you have multiple threads doing separate processing and they all need exactly once semantics, you should have a producer instance per thread.
Not sure if this was resolved. you can use apache common pool2 to create a producer instance pool. In the create() method of the factory implementation you can generate and assign a unique transactionalID to avoid a conflict (ProducerFencedException)
2,342
50,026,785
I need to download a package using pip. I ran `pip install <package>` but got the following error: ``` [user@server ~]$ pip install sistr_cmd Collecting sistr_cmd Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.c...
2018/04/25
[ "https://Stackoverflow.com/questions/50026785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8967045/" ]
``` myzipWith :: (a->b->c) -> [a] -> [b] ->[c] myzipWith func [] [] = [] myzipWith func (headA:restA) (headB:restB) = [func headA headB] ++ myzipWith func restA restB ``` But note the append (`++`) isn't necessary. This would be more idiomatic (and efficient): ``` func headA headB : myzipWith func restA rest...
``` myzipWith func (a:as) (b:bs) = [func a b] ++ (myzipWith func as bs) ``` The syntax `function (x:xs)` splits the list passed to `function` into two parts: the first element `x` and the rest of the list `xs`.
2,343
25,296,807
Is it possible in python to create an un-linked copy of a function? For example, if I have ``` a = lambda(x): x b = lambda(x): a(x)+1 ``` I want `b(x)` to always `return x+1`, regardless if `a(x)` is modified not. Currently, if I do ``` a = lambda(x): x b = lambda(x): a(x)+1 print a(1.),b(1.) a = lambda(x): x*0 pri...
2014/08/13
[ "https://Stackoverflow.com/questions/25296807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3939154/" ]
You could define b like this: ``` b = lambda x, a=a: a(x)+1 ``` This makes `a` a parameter of `b`, and therefore a local variable. You default it to the value of `a` in the current environment, so `b` will hold onto that value. You don't need to copy `a`, just keep its current value, so that if a new value is create...
I might need to know a little more about your constraints before I can give a satisfactory answer. Why couldn't you do something like ``` a = lambda(x): x c = a b = lambda(x): c(x)+1 ``` Then no matter what happens to `a`, `b` will stay the same. This works because of the somewhat unusual way that assignment works i...
2,344
62,707,514
As we all know, filling out the web forms automatically is possible using JavaScript. Basically, We find the ID of related element using Inspect (Ctrl + I) in i.e Chrome and write a javascript code in the chrome console to automate what we want to do by code. Just like that, is it possible to automate desktop apps usi...
2020/07/03
[ "https://Stackoverflow.com/questions/62707514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13177703/" ]
You can do this in python using **selenium**. Selenium is an open-source testing tool, used for functional testing and also compatible with non-functional testing. You can refer to this [link](https://www.guru99.com/selenium-python.html) to get started.
[Pywinauto](https://pywinauto.github.io/) is a GUI automation library written in pure Python and well developed for Windows GUI.
2,345
48,949,121
i have a python script that read from CSV file and check if the records meet the conditions. * if yes the system display the result * if no the system raise Exception based on the Error. the csv file includes a filed that has **float values** but some of these records may not have any value so will be empty. the pro...
2018/02/23
[ "https://Stackoverflow.com/questions/48949121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9162690/" ]
That behaviour is often caused by an updated installation of MongoDB. There is a "feature compatibility level" switch built into MongoDB which allows for updates to a newer version that do not alter (some of) the behaviour of the old version in a non-expected (oh well) way. The [documentation](https://docs.mongodb.com/...
To everyone in the same case, the solution dnickless gave works for me: > > In case you've upgrade from an older version try running this: > > > `db.adminCommand( { setFeatureCompatibilityVersion: "3.6" } )` > > >
2,346
16,453,644
I have a Pandas DataFrame with a `date` column (eg: `2013-04-01`) of dtype `datetime.date`. When I include that column in `X_train` and try to fit the regression model, I get the error `float() argument must be a string or a number`. Removing the `date` column avoided this error. What is the proper way to take the `da...
2013/05/09
[ "https://Stackoverflow.com/questions/16453644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/741099/" ]
The best way is to explode the date into a set of categorical features encoded in boolean form using the 1-of-K encoding (e.g. as done by [DictVectorizer](http://scikit-learn.org/stable/modules/feature_extraction.html#loading-features-from-dicts)). Here are some features that can be extracted from a date: * hour of th...
You have two options. You can convert the date to an ordinal i.e. an integer representing the number of days since year 1 day 1. You can do this by a `datetime.date`'s `toordinal` function. Alternatively, you can turn the dates into categorical variables using sklearn's [OneHotEncoder](http://scikit-learn.org/dev/mod...
2,347
46,191,793
I followed the guide here: <https://plot.ly/python/filled-chord-diagram/> And I produced this: [![enter image description here](https://i.stack.imgur.com/wVzNc.png)](https://i.stack.imgur.com/wVzNc.png) In the guide, I followed the `ribbon_info` code to add hoverinfo to the connecting ribbons but nothing shows. I c...
2017/09/13
[ "https://Stackoverflow.com/questions/46191793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6593031/" ]
just apply `json.dumps()` to this native python dictionary composed in one-line: ``` {k.replace(" ","_"):v.strip() for k,v in (x.split(":") for x in ["Passanger status:\n passanger cfg086d96 is unknown\n\n"])} ``` the inner generator comprehension avoids to call `split` for each part of the dict key/value. The value...
You can try this one also ``` data_dic = dict() data = "Passanger status:\n passanger cfg086d96 is unknown\n\n" x1 , x2 = map(str,data.split(":")) data_dic[x1] = x2 print data_dic ``` If you find it simple Output : ``` {'Passanger status': '\n passanger cfg086d96 is unknown\n\n'} ``` and for space to underscore...
2,356
73,935,930
How (in python) can I change numbers to be going up. For example, 1 (time.sleep(0.05)) then it changes to two, and so on. But there will be text already above it, so you can't use a simple `os.system('clear')` So like this: > > print("how much money do you want to make?")< > 'number going up without deleting the "ho...
2022/10/03
[ "https://Stackoverflow.com/questions/73935930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20149657/" ]
Like this: ``` import sys import time for i in range(10): time.sleep(0.3) sys.stdout.write("\rDoing thing %i" % i) sys.stdout.flush() ``` Edit: This was taken from [Replace console output in Python](https://stackoverflow.com/questions/6169217/replace-console-output-in-python)
The question is very unclear, but maybe you mean the following: ```py import time for item in [0.05,2,3]: time.sleep(item) ``` and ```py number = 3 print("how much money do you want to make? {}".format(number)) ```
2,357
36,115,429
I faced a compile error in my python script as following: ``` formula = "ASD" start = 0 end = 2 print(formula, start, end, type(start), type(end)) print(formula[start, end]) ``` the output is: ``` ASD 0 2 <class 'int'> <class 'int'> Traceback (most recent call last): File "test.py", line 5, in <module> print(...
2016/03/20
[ "https://Stackoverflow.com/questions/36115429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3001445/" ]
The syntax to slice is with `:` not with `,` ``` >>> print(formula[start:end]) AS ```
You seem to be performing a slicing operation, in order to do this you need to use `:` and not `,`: ``` formula[start:end] ``` Demo: ``` formula = "ASD" start = 0 end = 2 print(formula, start, end, type(start), type(end)) print(formula[start:end]) ``` output: ``` ASD 0 2 <class 'int'> <class 'int'> AS ```
2,359
17,528,976
I am working on an anonymizer program which sensors the given words in the list. This is what i have so far. I am new to python so not sure how can i achieve this. ``` def isAlpha(c): if( c >= 'A' and c <='Z' or c >= 'a' and c <='z' or c >= '0' and c <='9'): return True else: return False def ...
2013/07/08
[ "https://Stackoverflow.com/questions/17528976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2559375/" ]
You have several problems with your code: 1. There already exists an `islpha` function; it is a `str` method (see example below). 2. Your `trucatedInput` is a `str`, which is an immutable type. You can't reassign parts of an immutable type; i.e. `myStr[3]='x'` would normally fail. If you really want to do this, you're...
You could use [string.replace()](http://docs.python.org/2/library/string.html#string.replace) ``` truncatedInput.replace('DRAT', 'xxxx') ``` This will replace the first occurence of DRAT with xxxx, even if it is part of a longer sentence. If you want different functionality let me know.
2,361
67,756,936
I have this: ```py def f(message): l = [] for c in message: l.append(c) l.append('*') return "".join(l) ``` It works but how do I make it so that it doesn't add "\*" at the end. I only want it to be between the inputted word. I'm new to python and was just trying new things.
2021/05/30
[ "https://Stackoverflow.com/questions/67756936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16072743/" ]
May be you can try this. It uses list comprehension ``` input_str = 'dog' def f(x): return '*'.join(x) print(f('dog')) #ouput d*o*g print(f(input_str)) #ouput d*o*g ```
Well, technically you could just slice the returned string cutting off the last astrix. ``` message="dog" def f(message): l = [] for c in message: l.append(c) l.append('*') return "".join(l[:-1]) print(f(message)) ``` this way it returns ``` d*o*g ...
2,363
24,736,813
I want to extend the datetime.date class adding it an attribute called `status` that represents if the date is a work day, an administrative non-work day, courts closed day,... I've read from [How to extend a class in python?](https://stackoverflow.com/questions/15526858/how-to-extend-a-class-in-python), [How to exten...
2014/07/14
[ "https://Stackoverflow.com/questions/24736813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3160820/" ]
`datetime.date` is an immutable type, meaning you need to override the [`__new__` method](https://docs.python.org/3/reference/datamodel.html#object.__new__) instead: ``` class Fecha(datetime.date): def __new__(cls, year, month, day, status): instance = super(Fecha, cls).__new__(cls, year, month, day) ...
problem is in super call ``` super(Fecha, self).__init__(year, month, day) ``` Try this.
2,364
55,739,404
I have a Python 3.6 script that calls out to a third-party tool using subprocess. `main_script.py:` ``` #!/usr/bin/env python import subprocess result = subprocess.run(['third-party-tool', '-arg1'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ``` The problem is, `main_script.py` must be run from wi...
2019/04/18
[ "https://Stackoverflow.com/questions/55739404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3638628/" ]
From the documentation of subprocess: <https://docs.python.org/3/library/subprocess.html> The accepted args are ``` subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None...
Thanks for your help, nullUser; your solution is a concise and correct answer to my question. However, when I tried it out, my third-party-tool now fails for some other (unknown) reason. There was probably some other environment variable I don't know about that's getting lost with the new shell. Fortunately, I found a...
2,365
13,661,723
How can I run online python code that owns/requires a set of modules? (e.g. numpy, matplotlib) Answers/suggestions to questions [2737539](https://stackoverflow.com/questions/2737539/python-3-online-interpreter-shell) and [3356390](https://stackoverflow.com/questions/3356390/is-there-an-online-interpreter-for-python-3) ...
2012/12/01
[ "https://Stackoverflow.com/questions/13661723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I found one that supports multiple modules, i checked `numpy, scipy, psutil, matplotlib, etc` and all of them are supported. Check out pythonanyware compiler, a sample console is [here](https://www.pythonanywhere.com/try-ipython/), however you can signup for accounts [here](https://www.pythonanywhere.com/pricing/), i b...
You may try this as sandbox, it support numpy as well: <http://ideone.com>
2,366
46,027,022
I need to create a script that calculates the distance between two coordinates. The issue I'm having though is when I assign the coordinate to object one, it is stored as a string and am unable to convert it to a list or integer/float. How can I convert this into either a list or integer/float? The script and error I g...
2017/09/03
[ "https://Stackoverflow.com/questions/46027022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5874828/" ]
You have to convert the entered string to int/float by first splitting the string into the point components, then casting to the appropriate type: ``` x, y = map(float, one.split(',')) ``` To keep the entered values as a single custom datatype, named `Point` for example, you can use a [`namedtuple`](https://docs.pyt...
Convert the input into the specific type as int or float Into a list: ``` _list = list(map(int, input("Enter an x,y coordinate.").split(","))) ``` or into variables: ``` a, b = map(int, input("Enter an x,y coordinate.").split(",")) ```
2,367
22,225,666
Suppose you want to write a function which yields a list of objects, and you know in advance the length `n` of such list. In python the list supports indexed access in O(1), so it is arguably a good idea to pre-allocate the list and access it with indexes instead of allocating an empty list and using the `append()` me...
2014/03/06
[ "https://Stackoverflow.com/questions/22225666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282614/" ]
In between those two options the first one is clearly better as no Python for loop is involved. ``` >>> %timeit [None] * 100 1000000 loops, best of 3: 469 ns per loop >>> %timeit [None for x in range(100)] 100000 loops, best of 3: 4.8 us per loop ``` **Update:** And `list.append` has an [`O(1)` complexity](https:/...
When you append an item to a list, Python 'over-allocates', see the [source-code](http://svn.python.org/projects/python/trunk/Objects/listobject.c) of the list object. This means that for example when adding 1 item to a list of 8 items, it actually makes room for 8 new items, and uses only the first one of those. The n...
2,369
37,254,610
ipdb is triggering an import error for me when I run my Django site locally. I'm working on Python 2.7 and within a virtual environment. `which ipdb` shows the path `(/usr/local/bin/ipdb)`, as does `which ipython`, which surprised me since I thought it should show my venv path (but shouldn't it work if it's global, an...
2016/05/16
[ "https://Stackoverflow.com/questions/37254610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695507/" ]
You have Code like below. What ever you don't need just remove it. ``` String address = addresses.get(0).getAddressLine(0); String city = addresses.get(0).getLocality(); String state = addresses.get(0).getAdminArea(); String country = addresses.get(0).getCountryName(); String postalCode = addresses.get(0).getPostalCod...
You appears to be using the Javascript version of the Google Places API. Let me know if I've guessed incorrectly! All you need to do is add `&region=US` when you load the Google Maps API. E.g.: ``` <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&region=US"> ``` Note that this ...
2,372
63,012,839
I'm looking for a fast way to fill a QTableModel with over 10000 rows of data in python. Iterating over the items in a double for-loop takes over 40 seconds.
2020/07/21
[ "https://Stackoverflow.com/questions/63012839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6796677/" ]
You don't need to explicitly add items to a QTableModel, you can build your own model around an existing data structure like a list of lists or a numpy array like below. ``` from PyQt5 import QtWidgets, QtCore, QtGui import sys from PyQt5.QtCore import QModelIndex, Qt import numpy as np class MyTableModel(QtCore.QAbs...
I would recommend creating a numpy array of QStandardItem and filling the Model using the appendColumn function: ``` start = time.time() data = np.empty(rows, cols, dtype=object) # generate empty data-Array #### Fill the data array with strings here ### items = np.vectorize(QStandardItem)(data) ...
2,373
7,243,364
Well, probably a strange question, I know. But searching google for python and braces gives only one type of answers. What I want to as is something low-level and, probably, not very pythonic. Is there a clear way to write a function working with: ``` >>>my_function arg1, arg2 ``` instead of ``` >>>my_function(arg...
2011/08/30
[ "https://Stackoverflow.com/questions/7243364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/581732/" ]
You can do that sort of thing in Ruby, but you can't in Python. Python values clean language and explicit and obvious structure. > > >>> import this > > The Zen of Python, by Tim Peters > > > Beautiful is better than ugly. > > **Explicit is better than implicit.** > > Simple is better than complex. > ...
The requirement for braces lies in the Python interpreter and not in the code for the `print` method (or any other method) itself. (And as eph points out in the comments, `print` is a statement not a method.)
2,374
48,247,921
I'm attempting to get the TensorFlow Object Detection API <https://github.com/tensorflow/models/tree/master/research/object_detection> working on Windows by following the install instructions <https://github.com/tensorflow/models/tree/master/research/object_detection> Which seem to be for Linux/Mac. I can only get ...
2018/01/14
[ "https://Stackoverflow.com/questions/48247921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4835204/" ]
As mentioned in the comment, `utils` is a submodule so you actually need to add `object_detection` to `PYTHONPATH`, not `object_detection/utils`. I'm glad it worked for you.
cd Research/Object\_Detection cd .. Research 1. export PATH=~/anaconda3/bin:$PATH RESEARCH 2. git clone <https://github.com/tensorflow/models.git> RESEARCH 3.export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim 4.protoc object\_detection/protos/string\_int\_label\_map.proto --python\_out=. CD OBJECT\_DETECTION 5. ...
2,378
19,819,443
I'm writing a code in Python. Within the code, a blackbox application written in c++ is called. Sometimes this c++ application does not converge and an error message come up. This error does not terminate the Python code, but it pause the run. After clicking ok for the error message, the python code continues running t...
2013/11/06
[ "https://Stackoverflow.com/questions/19819443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2961551/" ]
I believe that in your case Python program doesn't actually continue the execution, unless the program started as a subprocess completes - this is the behaviour or [subprocess.check\_call](http://docs.python.org/2/library/subprocess.html#subprocess.check_call) which you say is used to start the subprocess. As long as ...
Timur is correct. Unless the C++ program explicitly provides a way for you to check the status, respond to the dialog, or make it run without showing the dialog, there is nothing built into python that can solve this problem as far as i know. There are some workarounds that might work for you, though. Depending on you...
2,381
15,106,713
I've searched the databases and cookbooks but can't seem to find the right answer. I have a very simple python code which sums up self powers in a range. I need the last ten digits of this very, very large number and I've tried the getcontext().prec however I'm still hitting a limit. Here's the code: ``` def SelfPowe...
2013/02/27
[ "https://Stackoverflow.com/questions/15106713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2082350/" ]
If you want the *last ten digits* of a number, don't compute the whole thing (it will take too much memory and time). Instead, consider using the "three-argument" form of `pow` to compute powers mod a specific base, and you will find the problem is much easier.
Testing on Python 3.2 I was able to ``` print(SelfPowers(10000)) ``` though it took some seconds. How large a number were you thinking? **Edit:** It looks like you want to use `1000`? In such case, upgrade to Python 3 and you should be fine.
2,382
58,850,484
I want to save list below output onto a text file ``` with open("selectedProd.txt", 'w') as f: for x in myprod["prod"]: if x["type"]=="discount" or x["type"]=="normal" or x["type"]=="members" : f.write(x["name"],x["id"], x["price"]) ``` I'm getting error ``` f.write(x["name"],x["id"], x["price"]) ...
2019/11/14
[ "https://Stackoverflow.com/questions/58850484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10411973/" ]
I think I find a solution, but If there something better pls, let me know... I add `this.dialogRef.closeAll()` ``` class UserEffects { constructor( private actions$: Actions, private dialogRef: MatDialog, private notificationService: NotificationService, ) {} @Effect() addNewUser$ = this.actio...
In the constructor of your `@Effect`, you need to provide the dependency: ``` private dialogRef: MatDialogRef<MyDialogComponentToClose> ``` And you need to import `MatDialogModule` inside your module where your effect is.
2,383
49,440,741
I have a python code base where I have refactored a module (file) into a package (directory) as the file was getting a bit large and unmanageable. However, I cannot get my unit tests running as desired with the new structure. I place my unit test files directly alongside the code it tests (this is a requirement and ca...
2018/03/23
[ "https://Stackoverflow.com/questions/49440741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23744/" ]
You can invoke the `unittest` module from the command line with arguments: ``` python -m unittest model.square_test ``` If you are using python3 you can use file names too: ``` python3 -m unittest model/square_test.py ```
suggestions: add `app/__init__.py`, and treat `app` as package instead of `model` one way is for all tests, using explicit `from app.model.square import Square` The relative import should be fine, as long as using `nosetests -vw .` in `app/` directory. These all under the price of removing `app/test.py` Another co...
2,391
30,314,368
I have a CSV file that looks something like this: ``` 2014-6-06 08:03:19, 439105, 1053224, Front Entrance 2014-6-06 09:43:21, 439105, 1696241, Main Exit 2014-6-06 10:01:54, 1836139, 1593258, Back Archway 2014-6-06 11:34:26, 845646, external, Exit 2014-6-06 04:45:13, 1464748, 439105, Side Exit ``...
2015/05/18
[ "https://Stackoverflow.com/questions/30314368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4573703/" ]
It looks like you are grabbing the first element after you split the line. That is going to give you the date, according to your example CSV file. What you probably want instead (again, assuming the example is the way it will always work) is to grab the 3rd element, so something like this: ``` csv_domain = line.split...
if you can go with something else then python, grep would work like this: ``` grep file.csv "some regex" > newfile.csv ``` would give you ONLY the lines that match the regex, while: ``` grep -v file.csv "some regex" > newfile.csv ``` gives everything BUT the lines matching the regex
2,392
52,870,674
When I execute the following command I get the below error from Tensorflow "missing file or folder". I've checked all online solutions for this error, but nothing is resolving my error. `python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record` **The error:**...
2018/10/18
[ "https://Stackoverflow.com/questions/52870674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9933958/" ]
I resolved the problem If you are making `.CSV file` using a `xml_to_csv file.py`, you have to check the file extension such as .jpg, .png, .jpeg in `train_labels.csv` file. In my case, the xtension names won't be there ! [![enter image description here](https://i.stack.imgur.com/JtuNs.png)](https://i.stack.imgur....
My csv-file contained imagenames with jpg extension and I still had this error OP posted. I tried solving it with: ``` python3 generate_tf_record.py --csv_input=data/train_labels.csv --output_path=train.record python3 generate_tf_record.py --csv_input=data/test_labels.csv --output_path=test.record ``` All images we...
2,394
51,505,249
``` list = [1,2,,3,4,5,6,1,2,56,78,45,90,34] range = ["0-25","25-50","50-75","75-100"] ``` I am coding in python. I want to sort a list of integers in range of numbers and store them in differrent lists.How can i do it? I have specified my ranges in the the range list.
2018/07/24
[ "https://Stackoverflow.com/questions/51505249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10033784/" ]
Create a dictionary with max-value of each *bin* as key. Iterate through your numbers and append them to the list that's the value of each *bin-key*: ``` l = [1,2,3,4,5,6,1,2,56,78,45,90,34] # your range covers 25 a piece - and share start/endvalues. # I presume [0-25[ ranges def inRanges(data,maxValues): """So...
Another stable bin approach for your special case (regular intervaled bins) would be to use a calculated key - this would get rid of the key-search in each step. Stable search means the order of numbers in the list is the same as in the input data: ``` def inRegularIntervals(data, interval): """Sorts elements of ...
2,397
30,513,482
I'm trying to export two overloaded functions to Python. So I first define the pointers to these functions and then I use them to expose the functions to Python. ``` BOOST_PYTHON_MODULE(mylib){ // First define pointers to overloaded function double (*expt_pseudopot02_v1)(double,double,double,const VECTOR&, ...
2015/05/28
[ "https://Stackoverflow.com/questions/30513482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/938720/" ]
In short, the functions being exposed exceed the default maximum arity of 15. As noted in the [configuration documentation](http://www.boost.org/doc/libs/1_58_0/libs/python/doc/v2/configuration.html), one can define `BOOST_PYTHON_MAX_ARITY` to control the maximum allowed arity of any function, member function, or const...
As @bogdan pointed the function returning boost::python::list is having 16 parameters and max boost python arity by default is set to 15. Use `#define BOOST_PYTHON_MAX_ARITY 16` to increase the limit or (better) consider wrapping parameters into struct.
2,398
20,997,283
Does anyone know of some `Python` package or function that can upload a Pandas `DataFrame` (or simply a `.csv`) to a PostgreSQL table, **even if the table doesn't yet exist**? (i.e. it runs a CREATE TABLE with the appropriate column names and columns types based on a mapping between the python data types and closest ...
2014/01/08
[ "https://Stackoverflow.com/questions/20997283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/176995/" ]
Since pandas 0.14, the sql functions also support postgresql (via SQLAlchemy, so all database flavors supported by SQLAlchemy work). So you can simply use `to_sql` to write a pandas DataFrame to a PostgreSQL database: ``` import pandas as pd from sqlalchemy import create_engine import psycopg2 engine = create_engine('...
They just made a package for this. <https://gist.github.com/catawbasam/3164289> Not sure how well it works.
2,399
57,476,304
am getting below exception while trying to use multiprocessing with flask sqlalchemy. ``` sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically. [12/Aug/2019 18:09:52] "GET /api/resources HTTP/1.1" 500 - Traceback (most recent call last): File "/usr/local/lib/...
2019/08/13
[ "https://Stackoverflow.com/questions/57476304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8085047/" ]
I had the same issue. Following Sam's link helped me solve it. Before I had (not working): ``` from multiprocessing import Pool with Pool() as pool: pool.map(f, [arg1, arg2, ...]) ``` This works for me: ``` from multiprocessing import get_context with get_context("spawn").Pool() as pool: pool.map(f, [arg1,...
The answer from dibrovsd@github was really useful for me. If you are using a PREFORKING server like uwsgi or gunicorn, this would also help you. Post his comment here for your reference. > > Found. This happens when uwsgi (or gunicorn) starts when multiple workers are forked from the first process. > > If there i...
2,400
59,010,815
This is my code: I have used the find element by id RESULT\_RadioButton-7\_0, but I am getting the following error: ``` from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome(executable_path="/home/real/Desktop/Selenium_with_python/SeleniumProjects/chromedriver_linux64/c...
2019/11/23
[ "https://Stackoverflow.com/questions/59010815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11132456/" ]
Based on the page link you provided, it looks like your locator strategy is correct here. If you are getting an error—most likely `NoSuchElementException`, I am assuming it might have something to do with waiting for the page to load before attempting to find the element. Let's use the `ExpectedConditions` class to wai...
Unless you need to wait on the element (which doesn't seem necessary), you should be able to do the following: ``` element_to_click_or_whatever = driver.find_element_by_id('RESULT_RadioButton-7_0') ``` If you look at the source for [`find_element_by_id`](https://github.com/SeleniumHQ/selenium/blob/master/py/selenium...
2,401
3,631,556
I have found several topics with this title, but none of their solutions worked for me. I have two Django sites running on my server, both through Apache using different virtualhosts on two ports fed by my Nginx frontend (using for static files). One site uses MySql and runs just fine. The other uses Sqlite3 and gets t...
2010/09/02
[ "https://Stackoverflow.com/questions/3631556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/438289/" ]
It could be that the server uses a different working directory than the `manage.py` command. Since you provide a relative path to the sqlite database, it is created in the working directory. Try it with an absolute path, e.g.: ``` 'NAME': '/tmp/mysite.sqlite3', ``` Remember that you have to either run `./manage.py s...
You have unapplied migrations. your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. python manage.py migrate This one worked for me.
2,403
47,249,474
I'm working on a python GUI application, using tkinter, which displays text in Hebrew. On Windows (10, python 3.6, tkinter 8.6) Hebrew strings are displayed fine. On Linux (Ubuntu 14, both python 3.4 and 3.6, tkinter 8.6) Hebrew strings are displayed incorrectly - with no BiDi awareness - **am I missing something?*...
2017/11/12
[ "https://Stackoverflow.com/questions/47249474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1499700/" ]
I searched a bit and it is a known issue that tk/tcl uses Windows bidi support since about 2011, but their is apparently nothing equivalent on linux. Example: <https://wiki.tcl.tk/3158>. One answer to [Python/Tkinter: Using Tkinter for RTL (right-to-left) languages like Arabic/Hebrew?](https://stackoverflow.com/questio...
As on of the main authors of FriBidi and a contributor to the bidi text support in Gtk, I strongly suggest that you don't use TkInter for anything Hebrew or any other text other than Latin, Greek, or Cyrillic scripts. In theory you can rearrange the text ordering with the stand alone fribidi executable on on Linux, or ...
2,413
24,872,243
I created and ImageField model for my blog app in my "test" django project on my local server using sqllite. I have in my settings.py `MEDIA_ROOT = '/Users/me/Sites/python/djangotut/media/' MEDIA_ROOT_URL = 'http://127.0.0.1:8000/media/images/photos/'` and my blog/models.py ``` photo = models.ImageField(upload_...
2014/07/21
[ "https://Stackoverflow.com/questions/24872243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3142105/" ]
Use weight sum technique for layouts, so that the controls in your each line consumes the assigned percentage of space ( there won't be any need to put them in Grid or other UI Controls)
Use a nested ViewGroup: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_hori...
2,414
47,074,966
I am trying to create a simple test-scorer that grades your test and gives you a response - but a simple if/else function isn't running - Python - ``` testScore = input("Please enter your test score") if testScore <= 50: print "You didn't pass... sorry!" elif testScore >=60 and <=71: print "You passed, but you...
2017/11/02
[ "https://Stackoverflow.com/questions/47074966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You missed testScore in elif statement ``` testScore = input("Please enter your test score") if testScore <= 50: print "You didn't pass... sorry!" elif testScore >=60 and testScore<=71: print "You passed, but you can do better!" ```
The below shown way would be the better way of solving it, you always need to make the type conversion to integer when you are comparing/checking with numbers. > > input() in python would generally take as string > > > ``` testScore = input("Please enter your test score") if int(testScore) <= 50: print("Yo...
2,415
66,697,840
I guess once upon a time, I was able to find this information by Googling but not this time. I believe each script file (e.g. my.py, run.sh, etc) could have the path to an executable that is supposed to parse & run the script file. For example, a bash script file `run.sh` could start with: ``` #!/bin/bash ``` Then,...
2021/03/18
[ "https://Stackoverflow.com/questions/66697840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7254686/" ]
If you want to pass json data with axios,you need to set `Content-Type`,here is a demo: axios(I use 1 to replace `${rockId}` to test): ``` var payload = "this is a test"; const request = axios.put(`/api/rocks/1/rockText`, JSON.stringify(payload), { headers: { 'Content-Type': 'application/json' } }); `...
The issue is that the model binder cannot resolve the payload. The reason is that it's expecting a string, but you're actually passing a json object with a property `rockText`. I would create a class to represent the json you're sending: ``` public class Rock { public string RockText { get; set; } } [HttpPut("{i...
2,418
29,956,883
I am fairly new to python. I want to create a program that can generate random numbers and write them to a file, but I am curious to as whether it is possible to write the output to a `.txt` file, but in individual lists. (*every time the program executes the script, it creates a new list*) Here is my code so far: `...
2015/04/30
[ "https://Stackoverflow.com/questions/29956883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4848614/" ]
ABout append or `a` - > > Opens a file for appending. The file pointer is at the end of the file > if the file exists. That is, the file is in the append mode. If the > file does not exist, it creates a new file for writing. > > > ``` def main(): import random data = open("Random.txt", "a" ) #open file...
If you read through the documentation for [open()](https://docs.python.org/2/library/functions.html#open) you'll note: > > Modes 'r+', 'w+' and 'a+' open the file for updating (reading and > writing); note that 'w+' truncates the file. Append 'b' to the mode to > open the file in binary mode, on systems that differ...
2,419
70,141,901
I have get\_Time function working fine but I would like to take the result it produces and store it int the "t" variable inside the function simple\_Interest function. Here is the code I have now. ``` y = input("Enter value for year: ") m = input("Enter value for month: ") p = input("Enter value for principle: ") r = ...
2021/11/28
[ "https://Stackoverflow.com/questions/70141901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17529617/" ]
Try this. ``` static int indexOfLastNumber(String s) { int removedLength = s.replaceFirst("\\d+\\D*$", "").length(); return s.length() == removedLength ? 0 : removedLength; } static void test(String s) { System.out.println(s + " : " + indexOfLastNumber(s)); } public static void main(String[] args) { ...
Note: the '1' is at index 9 in your String. If you don't want, it not necessary to use RegEx for this. A method like this should do the job: ```java public static int findLastNumbersIndex(String s) { boolean numberFound = false; boolean charBeforeNumberFound = false; //start at the end of the String int ind...
2,421
38,593,309
How do get logging from custom authorizer lambda function in API Gateway? I do not want to enable logging for API. I need logging from authorizer lambda function. I use a python lambda function and have prints in the code. I want to view the prints in **Cloud Watch** logs. But logs are not seen in cloud watch. I do not...
2016/07/26
[ "https://Stackoverflow.com/questions/38593309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2184930/" ]
I deleted the lambda function, IAM role, custom authorizer from API Gateway. Recreated all the above with the same settings and published the API. It started working and logging as expected. I do not know what was preventing earlier to log to cloud watch logs. Weird!!
When I set up my authorizer, I set a Lambda Event payload for a custom header, and I had neglected to set that header in my browser session. According to the documentation at *<https://docs.aws.amazon.com/apigateway/latest/developerguide/configure-api-gateway-lambda-authorization-with-console.html>*, section 9b, the AP...
2,424
838,991
I'm using pycurl to upload a file via put and python cgi script to receive the file on the server side. Essentially, the code on the server side is: ``` while True: next = sys.stdin.read(4096) if not next: break #.... write the buffer ``` This seems to work with text, but not binary files (I'm on win...
2009/05/08
[ "https://Stackoverflow.com/questions/838991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You need to run Python in binary mode. Change your CGI script from: ``` #!C:/Python25/python.exe ``` or whatever it says to: ``` #!C:/Python25/python.exe -u ``` Or you can do it programmatically like this: ``` msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) ``` before starting to read from `stdin`.
Use [mod\_wsgi](http://code.google.com/p/modwsgi/) instead of cgi. It will provide you an input file for the upload that's correctly opened.
2,425
40,762,324
I want to write a function to compare two values, val1 and val2, and if val1 is larger than val2, add 1 point to a\_points (Think of it like Team A) and vice versa (add one point to b\_points if val2 is larger.) If the two values are even I won't add any points to a\_points or b\_points. My problem is **test\_val wil...
2016/11/23
[ "https://Stackoverflow.com/questions/40762324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7017454/" ]
Global variables are generally a **bad idea**. Don't use them unless you really have to. The proper way to implement such counter is to use a class. ``` class MyCounter(object): def __init__(self): self.a_points = 0 self.b_points = 0 def test_val(self, val1, val2): if val1 > val2: ...
``` a_points=0 b_points=0 def test_val(a_points,b_points,val1,val2): global a_points global b_points if val1 > val2: a_points+=1 return a_points elif val2 > val1: b_points+=1 return b_points elif val1==val2: # If you pass, it won't return a_points nor b_po...
2,426
38,044,264
``` import pandas as pd import numpy as np from datetime import datetime, time # history file and batch size for processing. historyFilePath = 'EURUSD.SAMPLE.csv' batch_size = 5000 # function for date parsing dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f') # load data into a pandas iterator wi...
2016/06/26
[ "https://Stackoverflow.com/questions/38044264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5310427/" ]
This snippet of code should be what you want ``` # Create some fake data, similar to yours import pandas as pd s = pd.Series(pd.date_range('2014-08-17 17:00:01.1230000', periods=4)) print(s) print(type(s[0])) # Create a new series using just the date portion of the original data. # This effectively truncates the tim...
Here's how I did it with my data: ``` import pandas as pd import numpy as np rng = pd.date_range('1/1/2011', periods=72, freq='H') df = pd.DataFrame({"Data": np.random.randn(len(rng))}, index=rng) df["Time_Since_Midnight"] = (df.index - pd.to_datetime(df.index.date)) / np.timedelta64(1, 'ms') ``` By converting the ...
2,436
32,778,316
I am a vim user and edited a large python file using vim, everything is OK and it could run properly. Now I want to build a huge projects and I want to edit this python file in Intellij, but the indentation in intellij is completely wrong, and it's hard for me to edit one line by one line. Do you know what happened? (i...
2015/09/25
[ "https://Stackoverflow.com/questions/32778316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3390810/" ]
Yes, use [perfect forwarding](https://stackoverflow.com/questions/3582001/advantages-of-using-forward): ``` template <typename P> bool VectorList::put (P &&p) { //can't forward p here as it could move p and we need it later if (not_good_for_insert(p)) return false; // ... Node node = create_node(...
The ideal solution is to accept a universal reference, as [TartanLlama](https://stackoverflow.com/a/32778379/412080) advises. The ideal solution works if you can afford having the function definition in the header file. If your function definition cannot be exposed in the header (e.g. you employ Pimpl idiom or interfa...
2,437
13,096,339
> > **Possible Duplicate:** > > [Python Question: Year and Day of Year to date?](https://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date) > > > Is there a method in Python to figure out which month a certain day of the year is in, e.g. today is day 299 (October 26th). I would l...
2012/10/27
[ "https://Stackoverflow.com/questions/13096339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1198201/" ]
``` print (datetime.datetime(2012,1,1) + datetime.timedelta(days=299)).month ``` Here's a little more usable version that returns both the month and day: ``` def get_month_day(year, day, one_based=False): if one_based: # if Jan 1st is 1 instead of 0 day -= 1 dt = datetime.datetime(year, 1, 1) + date...
I know of no such method, but you can do it like this: ``` print datetime.datetime.strptime('2012 299', '%Y %j').month ``` The above prints `10`
2,440
18,897,631
Guys i'm a newbie to the socket programming Following program is a client program which request a file from the server,But i'm getting the error as show below.. My input is GET index.html and the code is Can anyone solve this error...? ``` #!/usr/bin/env python import httplib import sys http_server = sys.argv[0] co...
2013/09/19
[ "https://Stackoverflow.com/questions/18897631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2795866/" ]
sys.argv[0] is not what you think it is. sys.argv[0] is the name of the program or script. The script's first argument is sys.argv[1].
The problem is that the first item in `sys.argv` is the script name. So your script is actually using your filename as the hostname. Change the 5th line to: ``` http_server = sys.argv[1] ``` [More info here.](http://docs.python.org/2/library/sys.html#sys.argv)
2,441