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 |
|---|---|---|---|---|---|---|
48,490,272 | I'm trying to launch Safari with Selenium in python with all my sessions logged in (e.g. gmail) so I don't have to login manually.
The easy solution would be to launch safari with the default user profile, but I can't find documentation on how to do this.
```
from selenium import webdriver
driver = webdriver.Safari()... | 2018/01/28 | [
"https://Stackoverflow.com/questions/48490272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2827060/"
] | In the "[Creating Builds](https://dojotoolkit.org/documentation/tutorials/1.10/build/)" tutorial, it says:
>
> You might be asking yourself "if we build everything we need into a
> layer, why do we worry about the rest of the modules?" If you were to
> only keep the layer files and not have the rest of the modules
... | I don't know if this is a useful but I have a situation where I am creating a layer which loads from a completely different location to the core dojo app.
This means that I actually don't need the `dojo`, `dijit` and `dojox` to be in my build. I was having the issue of all files being bundled in to my location whethe... | 14,280 |
57,978,333 | While training a job on a SageMaker instance using H2o AutoML a message "This H2OFrame is empty" has come up after running the code, what should I do to fix the problem?
```
/opt/ml/input/config/hyperparameters.json
All Parameters:
{'nfolds': '5', 'training': "{'classification': 'true', 'target': 'y'}", 'max_runtime_s... | 2019/09/17 | [
"https://Stackoverflow.com/questions/57978333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8836963/"
] | thanks @Marcel Mendes Reis for following up on your solution in the comments. I will repost here for others to easily find:
*I realized the issue was due to the max\_runtime. When I trained the model with more time I didn't have the problem.* | Doing some tests I realized that the problem was because of the max\_runtime, I believe I didn't allow the model to train enough. | 14,281 |
72,122,475 | I have a custom field in employee module in Odoo to display the age.
That field is calculated from birtday field
```
for record in self:
today = datetime.date.today()
record['x_studio_age_2'] = today.year - record['birthday'].year - ((today.month, today.day) < (record['birthday'].month, record['birthday'].day... | 2022/05/05 | [
"https://Stackoverflow.com/questions/72122475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7259851/"
] | I think you should do someting like that.
`False` means value is not set.
```py
today = datetime.date.today()
for record in self:
if record['birthday']:
record['x_studio_age_2'] = today.year - record['birthday'].year - ((today.month, today.day) < (record['birthday'].month, record['birthday'].day))
else... | you have to check the birthday first , because if it's not set it will return false value as boolean | 14,282 |
64,583,022 | I imported a csv file with the variable βHEIGHTβ which has 10 values.
```
HEIGHT
62
58
72
63
66
62
63
62
62
67
```
I want to use numpy and numpy only to count the number of times the value β62β does not occur. The answer should be 6.
```
import numpy
import csv
with open(βmeasurements.csvβ),βrβ) as f:
rows=f.readli... | 2020/10/28 | [
"https://Stackoverflow.com/questions/64583022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14458035/"
] | Using numpy you can do:
```
data = np.array([62, 58, 72, 63, 66, 62, 63, 62, 62, 67])
(data != 62).sum()
```
That is, `data != 62` will make a numpy Boolean array, and `sum` will add these up, with `True` as `1`, giving the total count. | If you want to use *numpy and numpy only*,
Load the file using numpy:
```
dataset = np.loadtxt('measurements.csv', delimiter=',')
```
Seems like the height variable is in the 3rd column (index *2*). When you use `loadtxt`, you'll get a 2D array that looks like a table. You need the column with index 2, and you can ... | 14,283 |
2,896,179 | Can anyone help me out in fitting a gamma distribution in python? Well, I've got some data : X and Y coordinates, and I want to find the gamma parameters that fit this distribution... In the [Scipy doc](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gamma.html#scipy.stats.gamma), it turns out that a fi... | 2010/05/24 | [
"https://Stackoverflow.com/questions/2896179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348838/"
] | Generate some gamma data:
```
import scipy.stats as stats
alpha = 5
loc = 100.5
beta = 22
data = stats.gamma.rvs(alpha, loc=loc, scale=beta, size=10000)
print(data)
# [ 202.36035683 297.23906376 249.53831795 ..., 271.85204096 180.75026301
# 364.60240242]
```
Here we fit the data to the gamma distributi... | If you want a long example including a discussion about estimating or fixing the support of the distribution, then you can find it in <https://github.com/scipy/scipy/issues/1359> and the linked mailing list message.
Preliminary support to fix parameters, such as location, during fit has been added to the trunk versio... | 14,284 |
59,273,273 | I am attempting to open a serial connection to a usb device using PySerial, and with the following code I am getting the following error:
```
import serial
ser = serial.Serial('/dev/tty.usbserial-EN270425')
```
```
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/serial/serialpos... | 2019/12/10 | [
"https://Stackoverflow.com/questions/59273273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11313162/"
] | This is an interesting problem, for which I believe there is no standard function yet. This is not a huge problem because the hash itself contains an identifier telling us which hash algorithm was used. The important thing to note here is that `PASSWORD_DEFAULT` is a **constant**. Constants do not change.
To figure o... | ***Edit***
As of PHP 7.4.3 you can continue using `PASSWORD_DEFAULT === PASSWORD_BCRYPT`
*<https://3v4l.org/nN4Qi>*
---
You don't actually have to use `password_hash` twice. A better and faster way is to provide an already hashed value with `Bcrypt` and check it against `PASSWORD_DEFAULT` with
[password\_needs\_re... | 14,294 |
48,238,171 | I'm getting string data into my python code.Some time data is coming with an extra "and" or " or for example
```
Tom and Mark and
```
in this case I need to remove the last "and" & final outcome will look like
```
Tom and Mark
```
But when data will come like this
```
Harry and John
```
Then I will consider t... | 2018/01/13 | [
"https://Stackoverflow.com/questions/48238171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9184713/"
] | ```
[2, 4] [4, -3, -4, 4]
```
Sorted: `[2, 4] [-4, -3, 4, 4]`
```
qs are negative, p is positive:
2 + 4 + 2 + 3 = sum(4, 3) + 2*2
qs are larger than p:
4 - 2 + 4 - 2 = sum(4, 4) - 2*2
qs are negative, p is positive:
4 + 4 + 4 + 3 = sum(4, 3) + 2*4
qs are equal to p:
4 - 4 + 4 - 4 = 0
qs are smaller than p (not i... | It may or may not be more efficient to add or subtract the (unmodified) difference depending on sign instead of ("unconditionally") "adding `abs()`".
I'd expect a contemporary compiler, even JIT, to detect the equivalence, though.
```
! Sum of Absolute Differences between every pair of elements of two arrays;
INTEG... | 14,295 |
12,797,274 | I've just installed Python 2.7 on windows along with IPython.
I'm used to running IPython from within Emacs on Linux, e.g.
```
M-x shell
```
Then type '`ipython`' at the prompt.
This works fine under Linux, but under Windows it hangs after printing the IPython banner text, i.e. it looks like it's working, but then... | 2012/10/09 | [
"https://Stackoverflow.com/questions/12797274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1041868/"
] | In Windows it won't work as easily, and it's very annoying. First, make sure you have installed pyreadline.
Next, I have got it working with a bat file that is in my system path containing:
```
[ipython.bat]
@python.exe -i C:\devel\Python\2.7-bin\Scripts\ipython.py --pylab %*
```
Next get python-mode.el and delete... | I wish I had seen this post a while ago. My experiences with running python, ipython from within Emacs are the following:
I tried a number of options (Using python(x,y)-2.7.3.0 on Windows 7)
Using ipython.el:
It still works, provided that you change ipython-command. I do not recommend this, since you loose some func... | 14,296 |
44,123,641 | I am using the python libraries from the Assistant SDK for speech recognition via gRPC. I have the speech recognized and returned as a string calling the method `resp.result.spoken_request_text` from `\googlesamples\assistant\__main__.py` and I have the answer as an audio stream from the assistant API with the method `... | 2017/05/22 | [
"https://Stackoverflow.com/questions/44123641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415195/"
] | Currently (Assistant SDK Developer Preview 1), there is no direct way to do this. You can probably feed the audio stream into a Speech-to-Text system, but that really starts getting silly.
Speaking to the engineers on this subject while at Google I/O, they indicated that there are some technical complications on their... | Update: for
>
> google.assistant.embedded.v1alpha2
>
>
>
the assistant SDK includes the field `supplemental_display_text`
>
> which is meant to extract the assistant response as text which aids
> the user's understanding
>
>
>
or to be displayed on screens. Still making the text available to the develope... | 14,298 |
36,911,421 | If a class contains two constructors that take in different types of arguments as shown here:
```
public class Planet {
public double xxPos; //its current x position
public double yyPos; //its current y position
public double xxVel; //its current veolicity in the x direction
public double yyVel; //its curr... | 2016/04/28 | [
"https://Stackoverflow.com/questions/36911421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5249753/"
] | >
> 1) How does another class with a main that calls this class determine
> which constructor to use?
>
>
>
Compiler follows same process as overloaded method for static binding by checking unique method signature. To know about method signature [see this](https://docs.oracle.com/javase/tutorial/java/javaOO/metho... | ### 1) How does another class with a main that calls this class determine which constructor to use?
Classes don't determine anything, the programmer do, and he does it by placing the appropriate parameters. For example, if you have 2 constructors `public Test (int i)`and `public Test()`, when you call `new Test(5)` it... | 14,299 |
27,849,023 | **HTML**
--------
This is a form that accepts a user's input (url):
```
<form method="post" action="/" accept-charset="utf-8">
<input type="search" name="url" placeholder="Enter a url" />
<button>Go</button>
</form>
```
**PHP (Laravel)**
-----------------
This controller stores the value of the user's inpu... | 2015/01/08 | [
"https://Stackoverflow.com/questions/27849023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2097870/"
] | You can return a an array, but be sure that elements don't contain the delimiter.
Like `print(','.join(name, test))`.
Or you can encode to json like `json.dumps([name, test])`, then parse json in PHP. Second one is better, of course. | In this case, your Python script has to return a formatted response, that PHP script can parse properly and determine variables with their values
for example, your python code has to return something like that :
```
file_name=file.png;file_extension=png;creation_date=1/1/2015;
```
After that in your php code yo d... | 14,301 |
62,015,339 | ```
x = Flatten()(vgg.output)
variable = function (variable)
```
I can't find this type of expressions in python , can anyone help me to understand the above expression
Thanks in advance | 2020/05/26 | [
"https://Stackoverflow.com/questions/62015339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5952135/"
] | The `Flatten()` function here, returns another function, which takes `vgg.output` as argument. This happens because everything in python is a first class object. So you can return a function as the return value of function. This will be clear with an example:
Let's say we have a function `square` which returns the squ... | `x = Flattern()` is calling this function and assign returned data to `x`.
`v = function` like `v` is `function` alias. And you can do `v()` to call it. | 14,302 |
72,531,611 | I have Miniconda3 on a Linux system (Ubuntu 22.04). The environment has Python 3.10 as well as a functioning (in Python) installation of PyTorch (installed following official instructions).
I would like to setup a CMake project that uses PyTorch C++ API. The reason is not important and also I am aware that it's beta (... | 2022/06/07 | [
"https://Stackoverflow.com/questions/72531611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1559401/"
] | ```
import os
import pandas as pd
base_dir = '/path/to/dir'
#Get all files in the directory
data_list = []
for file in os.listdir(base_dir):
#If file is a json, construct it's full path and open it, append all json data to list
if file.endswith('json'):
json_path = os.path.join(base_dir, file)
... | You probably need to build a list of DataFrames. You may not be able to process every file in the given directory so try this:
```
import pandas as pd
from glob import glob
from os.path import join
BASEDIR = 'Datasets'
dataframes = []
for file in glob(join(BASEDIR, '*.json')):
try:
dataframes.append(pd.rea... | 14,304 |
38,690,035 | I have a Python script that creates a Lambda script in AWS along with all the policies and triggers. I use python boto3 library for that. I create the zip file for the lambda as on-the-fly rather than uploading a static zip file from the hard drive. I use this simple code from below to create my zip file. It creates th... | 2016/08/01 | [
"https://Stackoverflow.com/questions/38690035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4163842/"
] | With the info above I was able to start the in-memory solution. The deployment of that zip file worked but I could not use the resulting function. Got error:
```
Unable to import module '<function-name>': No module named <function-name>
```
I got it to work by specifying the file permissions.
I then use the in-mem... | I have experienced the exactly same problem you have. My solution is do NOT use on the fly zip file. Create a real zip file and add real file into it, and it just works. You can do that even in the lambda environment, by create filepath like "/tmp/yourfile.txt" you can create temp real file when lambda execute. | 14,306 |
67,542,736 | I'm trying to make lists of companies from long strings.
The company names tend to be randomly dispersed through the strings, but they always have a comma and a space before the names ', ', and they always end in Inc, LLC, Corporation, or Corp.
In addition, there is always a company listed at the very beginning of th... | 2021/05/15 | [
"https://Stackoverflow.com/questions/67542736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15930763/"
] | In C, the `for` loop is a "check before body" operation, you want the "check after body" variant, a `do while` loop, something like:
```c
int xs[] = {1,2,3,4,5};
{
int i = 0;
do {
foo(xs[i]);
} while (xs[i++] != 4);
}
```
You'll notice I've enclosed the entire chunk in its own scope (the outermos... | Try processing the loop as long as *the previous* element (if available) is not `4`:
```
int xs[] = {1,2,3,4,5};
for (int i = 0; i == 0 || xs[i - 1] != 4; i++) {
foo(xs[i]);
}
``` | 14,307 |
29,205,052 | Iam create project in django-oscar with the help of <http://django-oscar.readthedocs.org/en/latest/internals/getting_started.html> tutorial ,
i installed every packages which they mention in doc . after i run my project i getting (A server error occurred. Please contact the administrator. this error in ui) and the err... | 2015/03/23 | [
"https://Stackoverflow.com/questions/29205052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3632705/"
] | Try this
```
from oscar import get_core_apps
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.flatpages',
'compressor',
] + get_core_apps... | You dont import Oscar core apps. You need to import them and add to the INSTALLED\_APPS.
You can doing this by importing `from oscar import get_core_apps`
`get_core_apps` is a function that return (list) a default and required Oscar core apps.
So you need to concatenate it.
```
INSTALLED_APPS = [
'django.contrib.... | 14,309 |
24,331,551 | I was wondering how I would be able to sort a whole array by the values in one of its columns.
I have :
```
array([5,2,8,2,4])
```
and:
```
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
```
I want to append the fi... | 2014/06/20 | [
"https://Stackoverflow.com/questions/24331551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3712008/"
] | You can use [numpy.argsort](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html) to get a list with the sorted indices of your array. Using that you can then rearrange the columns of the matrix.
```
import numpy as np
c = np.array([5,2,8,2,4])
a = np.array([[ 0, 1, 2, 3, 4],
[... | You don't need numpy to do this; (although if you are using numpy, you can just use the `.transpose()` method of the array class.
What this essentially does, is transpose your array so that it's `array[column][row]`, and then takes each columns, and pairs them with the sortKeys you provided in a list of tuples (the `z... | 14,310 |
54,648,040 | I would like to get ELK version through REST API or parse html.
I search in API documentation without finding anything
Re-edit:
In python ... i'm not found better than
```
re.findall(r"version":"(\d\.\d\.\d)"", requests.get(my_elk).content.decode())[0]
``` | 2019/02/12 | [
"https://Stackoverflow.com/questions/54648040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3671796/"
] | Elasticsearch gives JSON, not HTML. So, you could use `jq`
```
$ curl -s localhost:9200 | jq '.version.number'
6.6.0
```
In Python, please don't use `re` module... Use `json` module and actually parse that content | There's no HTML, but if you call `GET /` in Kibana's Console or `curl -XGET http://localhost:9200/`, the return will be:
```
{
"name" : "instance-0000000039",
"cluster_name" : "c2edd39f6fa24b0d8e5c34e8d1d19849",
"cluster_uuid" : "VBkvp8OmTCaVuVvMioS3SA",
"version" : {
"number" : "6.6.0",
"build_flavor"... | 14,311 |
62,388,691 | I am newer for a python language. I want to be read the data from the text file(multiple lines in the text file), Then use the data that read from the text file to execute with the dictionary function.
```
def readCmd():
f = open('cmd.txt', "r")
line = f.readline()
for line in f:
print (line)
... | 2020/06/15 | [
"https://Stackoverflow.com/questions/62388691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11240783/"
] | You need to parse the input field value to an integer:
```js
parseInt($('#corporateA').val(), 10) // 89 (integer)
```
Also, as a tip, avoid prefixing the dollar-sign to non-jQuery objects.
### Proper usage
```js
let $corporateA = $('#corporateA'); // Storing a jQuery DOM object
let valA = parseInt($corporateA.val(... | You need to parse the values of the input fields, which are of type string into numbers.
There are two main strategies to achieve that.
1. Prefix every input field with a unary plus operator
2. Parse with the `parseInt` function
If you fail to parse the string into numbers, the binary `plus` operator will do string c... | 14,313 |
63,881,599 | I am trying to use the [kubernetes-client](https://github.com/kubernetes-client) in python in order to create an horizontal pod autoscaler in kubernetes. To do so i make use of the [create\_namespaced\_horizontal\_pod\_autoscaler](https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/AutoscalingV2beta... | 2020/09/14 | [
"https://Stackoverflow.com/questions/63881599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1488184/"
] | The above example permits the creation of a memory based hpa via the latest version of the [k8s python client](https://github.com/kubernetes-client/python) (v12.0.1).
```
my_metrics = []
my_metrics.append(client.V2beta2MetricSpec(type='Resource', resource= client.V2beta2ResourceMetricSource(name='memory',target=client... | Following error:
>
>
> ```
> v2beta2.MetricTarget.AverageUtilization: readUint32: unexpected character: \ufffd, error found in #10 byte of ..
>
> ```
>
>
means that its expecting `Uint32` and you are passing a `string`:
```
target=client.V2beta2MetricTarget(average_utilization='50',type='Utilization')
... | 14,314 |
12,439,762 | Given this (among more...):
```
compile_coffee() {
echo "Compile COFFEESCRIPT files..."
i=0
for folder in ${COFFEE_FOLDER[*]}
do
for file in $folder/*.coffee
do
file_name=$(echo "$file" | awk -F "/" '{print $NF}' | awk -F "." '{print $1}')
file_destination_path=$... | 2012/09/15 | [
"https://Stackoverflow.com/questions/12439762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/697150/"
] | This will give you 0.85 and 1.00 from your specified string, stored in `$values[1]` and `$values[2]` respectively.
```
$values = array();
preg_match('/Chop Suey<\/a><\/td><td align="right">([\d]+\.[\d]+)<\/td><td align="right">([\d]+\.[\d]+)<\/td>/', 'Chop Suey</a></td><td align="right">0.85</td><td align="right">1.00... | You could also be more dynamic with it. Instead of statically looking for "chop suey" why not look for other alignments.
Here is a sample to that. (very basic).
```
preg_match("/\d+.\d+/",$content,$output);
```
(above match, would give you all the decimals you need in correct order.)
```
$output[0] (is the arra... | 14,315 |
37,219,045 | I have a python script I run using Cygwin and I'd like to create a clickable icon on the windows desktop that could run this script without opening Cygwin and entering in the commands by hand. how can I do this? | 2016/05/13 | [
"https://Stackoverflow.com/questions/37219045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This comes straight from Python Docs (<https://docs.python.org/3.3/using/windows.html>):
**3.3.5. Executing scripts without the Python launcher**
Without the Python launcher installed, Python scripts (files with the extension .py) will be executed by python.exe by default. This executable opens a terminal, which stay... | The solution that worked like a charm for me >
From <https://www.tutorialexample.com/convert-python-script-to-exe-using-auto-py-to-exe-library-python-tutorial/>
`pip install auto-py-to-exe`
The GUI is available just by typing:
`auto-py-to-exe`
Then, I used this command to generate the desired output:
`pyinstaller ... | 14,316 |
53,780,882 | I have multiple times as a string:
```
"2018-12-14 11:20:16","2018-12-14 11:14:01","2018-12-14 11:01:58","2018-12-14 10:54:21"
```
I want to calculate the average time difference between all these times. The above example would be:
```
2018-12-14 11:20:16 - 2018-12-14 11:14:01 = 6 minutes 15 seconds
2018-12-14 11:... | 2018/12/14 | [
"https://Stackoverflow.com/questions/53780882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1323427/"
] | You have a bunch of problems. I'm not going to give you solutions to all of these. Just hints to get you started.
I assume you know...
* ... how to convert a time string to a `datetime.datetime` object,
* ... how to calculate the difference between two, i.e., a `datetime.timedelta`,
* ... how to compute a mean value ... | ```
from datetime import datetime
import numpy as np
ts_list = ["2018-12-14 11:20:16","2018-12-14 11:14:01","2018-12-14 11:01:58","2018-12-14 10:54:21"]
dif_list = []
for i in range(len(ts_list)-1):
dif_list.append((datetime.strptime(ts_list[i], '%Y-%m-%d %H:%M:%S')-datetime.strptime(ts_list[i+1], '%Y-%m-%d %H:%M:... | 14,326 |
44,367,508 | I have a for loop which runs a Python script ~100 times on 100 different input folders. The python script is most efficient on 2 cores, and I have 50 cores available. So I'd like to use GNU parallel to run the script on 25 folders at a time.
Here's my for loop (works fine, but is sequential of course), the python scr... | 2017/06/05 | [
"https://Stackoverflow.com/questions/44367508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084470/"
] | Replace `echo $folders | parallel ...` with `echo "$folders" | parallel ...`.
Without the double quotes, the shell parses spaces in `$folders` and passes them as separate arguments to `echo`, which causes them to be printed on one line. `parallel` provides each line as argument to the job.
To avoid such quoting issue... | you can pipe find directly to parallel:
```
find /home/rob/PartitionFinder/ -maxdepth 2 -type d | parallel -P 25 python script.py --raxml --quick --no-ml-tree {} --force -p 2
```
If you want to keep the string in `$folder`, you can pipe the echo to xargs.
```
echo $folders | xargs -n 1 | parallel -P 25 python scri... | 14,327 |
12,002,051 | Recently, I've found that the ipad can run python with a special python interpret. But editing the code on ipad is a terrible nightmare. So how can I push the python code which has been edited completely on PC into the ipad and run it? | 2012/08/17 | [
"https://Stackoverflow.com/questions/12002051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508702/"
] | If you are using Python for IOS, the following should work, although I haven't yet tried it myself.
Email the program to your own e-mail account as text. Then read the e-mail message on your iPad in any one of several e-mail applications. Cut and paste the text from the e-mail message into the python editor.
Don't cu... | I use Python 2.7 for IOS and download source python files through iFunBox into /var/mobile/Applications/Python 2.7 for IOS/Documents/User Scripts. Nevertheless I can't recommend this application as it's quite buggy and very slow when editing code. | 14,330 |
44,952,354 | I would like to use segment of the same string in a formatted string.
```python
input_string = 'abcdefhijk'
result_string = "A's name is abcd-defh; he does hijk"
```
The intuitive solution is
```python
"A's name is {0[0:4]}-{0{[3:7]}; he does {0[6:10]}".format(input_string)
```
And this obviously doesn't work.
Wh... | 2017/07/06 | [
"https://Stackoverflow.com/questions/44952354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5112950/"
] | In Python 3.6, you can make a similar construct to your "intuitive solution" with [f-strings](https://www.python.org/dev/peps/pep-0498/):
```
>>> input_string = 'abcdefhijk'
>>> f"A's name is {input_string[0:4]}-{input_string[3:7]}; he does {input_string[6:10]}"
"A's name is abcd-defh; he does hijk"
``` | Have you tried the below
```
result_string = "A's name is %s-%s; he does %s" %(input_string[:4], input_string[3:7], input_string[6:10])
``` | 14,340 |
65,745,683 | I have successfully installed python 3.9.1 with Numpy and Matplotlib on a new Mac mini with Apple Silicon. However, I cannot install SciPy : I get compilation errors when using
```
python3 -m pip install scipy
```
I also tried installing everything from brew, and `import scipy` works, but using it gives a seg fault.... | 2021/01/16 | [
"https://Stackoverflow.com/questions/65745683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206216/"
] | This one worked for me after wasting hours:
```
pip install --pre -i https://pypi.anaconda.org/scipy-wheels-nightly/simple scipy
``` | The following worked for me.
I'm currently using `Python 3.10.8`, installed using `brew`.
And currently, when installing `numpy==1.23.4`, `setuptools < 60.0.0` is required.
I'm using `(brew --prefix)/bin/python3 -m pip` for explicitly calling the `pip` from `python 3.10` installed by `brew`.
Here are the versions I... | 14,341 |
65,560,546 | I have a multi index dataframe like this:
```
PID Fid x y
A 1 2 3
2 6 1
3 4 6
B 1 3 5
2 2 4
3 5 7
```
I would like to delete the rows with the highest x-value per patient (PID). I need to get a new dataframe... | 2021/01/04 | [
"https://Stackoverflow.com/questions/65560546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14564287/"
] | You can try this:
```
idx = df.groupby(level=0)['x'].idxmax()
df[~df.index.isin(idx)]
x y
PID Fid
A 1 2 3
3 4 6
B 1 3 5
2 2 4
```
Or
You can use `pd.Index.difference` here.
```
df.loc[df.index.difference(df['x'].groupby(level=0).idxmax())] #Use level=0 if index is unnam... | Use [`GroupBy.transform`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html) for repeat max values per groups, compare by [`Series.ne`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ne.html) for not equal and filter in [`boolean inde... | 14,351 |
45,619,217 | I created my own user model by sub-classing AbstractBaseUser as is recommended by the docs. The goal here was to use a new field called mob\_phone as the identifying field for registration and log-in.
It works a charm - for the first user. It sets the username field as nothing - blank.But when I register a second user... | 2017/08/10 | [
"https://Stackoverflow.com/questions/45619217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5644300/"
] | Okay I'm an idiot. Literally seconds after posting this the obvious solution occurred to me:
```
username = models.CharField(max_length=40, unique=False, default='')
```
Just override the username field and make it non unique.
Rubber duck theory in action.... | It might be because you would have already entered some data in database which must be contradicting to the constraint. So try deleting that data or whole database and then run the command again. | 14,352 |
607,931 | I've deployed trac using apache/mod\_wsgi (no SSL) (preferable, since the
problem I'm facing with CGI is performance), and it works fine WITHOUT SVN
integration. But I actually need SVN, so when I configure the repository
path (i.e: repository\_dir = c:/projects/svn/my\_project) I can't even get my
project TRAC to even... | 2009/03/03 | [
"https://Stackoverflow.com/questions/607931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73377/"
] | Set a break point on the line that reads: NewFaqDropDownCategory.DataBind() and one in your event handler (NewFaqDropDownCategory\_SelectedIndexChanged).
I suspect the databind is being called right before your NewFaqDropDownCategory\_SelectedIndexChanged event fires causing your selected value to change.
If so, you n... | I think there is a bug in your LINQ query for the second drop down box
```
Dim faqs = (From f In db.faqs Where f.category = NewFaqDropDownCategory.SelectedValue)
```
Here you are comparing SelectedValue to category. Yet in the first combobox you said that the DataValueField should be category\_id. Try changing f.cat... | 14,353 |
67,366,722 | I am having issue parsing an xml result using python. I tried using etree.Element(text), but the error says Invalid tag name. Does anyone know if this is actually an xml and any way of parsing the result using a standard package? Thank you!
```
import requests, sys, json
from lxml import etree
response = requests.get(... | 2021/05/03 | [
"https://Stackoverflow.com/questions/67366722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14304103/"
] | You're using the wrong method to parse your XML. The `etree.Element`
class is for *creating* a single XML element. For example:
```
>>> a = etree.Element('a')
>>> a
<Element a at 0x7f8c9040e180>
>>> etree.tostring(a)
b'<a/>'
```
As Jayvee has pointed how, to parse XML contained in a string you use
the `etree.fromstr... | You can check if the xml is well formed by try converting it:
```
import requests, sys, json
from lxml import etree
response = requests.get("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=snp&id=1593319917&report=XML")
text=response.text
try:
doc=etree.fromstring(text)
print("valid")
except:
... | 14,356 |
73,142,014 | Am using the following ETL pipeline to get data into BigQuery. Data source are .csv & .xls files from a URL posted daily at 3 pm.
Cloud Scheduler publishes a message to a cloud pub/sub topic at 3:05 pm.
Pub/Sub pushes/triggers the subscribers-cloud functions
When triggered, these cloud functions (python script) downloa... | 2022/07/27 | [
"https://Stackoverflow.com/questions/73142014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12322651/"
] | In your architecture, Dataflow can only replace the PubSub + Cloud Functions. You still need a scheduler to run a dataflow (based on a template, maybe your custom template).
But, before using dataflow, why do you need it? I'm in charge of a datalake, to ingest data from different sources, but, because each element to ... | I do this kind of thing all the time and I can see why you'd wonder if there's a cleaner way. We use Composer (Ariflow) in GCP. In your scenario we would create one DAG with four sequential taks:
1. Copy file from URL to local bucket
2. Load file from local bucket to stage table
3. Merge stage table into final destina... | 14,357 |
34,405,936 | When I try to do `python manage.py syncdb` in my Django app, I get the error **ImportError: No module named azure.storage.blob**. But thing is, the following packages are installed if one does `pip freeze`:
`azure-common==1.0.0
azure-mgmt==0.20.1
azure-mgmt-common==0.20.0
azure-mgmt-compute==0.20.0
azure-mgmt-network=... | 2015/12/21 | [
"https://Stackoverflow.com/questions/34405936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4936905/"
] | I had a similar issue. To alleviate that, I followed this discussion here: <https://github.com/Azure/azure-storage-python/issues/51#issuecomment-148151993>
Basically, try `pip install azure==0.11.1` before trying `syncdb`, and I'm confident it will work for you! | There is a thread similar with yours, please check my answer for the thread [Unable to use azure SDK in Python](https://stackoverflow.com/questions/34213764/unable-to-use-azure-sdk-in-python).
Based on my experience, Python imports the third-party library packages from some library paths that you can check them thru c... | 14,358 |
7,548,562 | I've been getting weird results and I finally noticed that my habit of putting spaces in a tuple is causing the problem. If you can reproduce this problem and tell me why it works this way, you would be saving what's left of my hair. Thanks!
```
jcomeau@intrepid:/tmp$ cat haversine.py
#!/usr/bin/python
def dms_to_floa... | 2011/09/25 | [
"https://Stackoverflow.com/questions/7548562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493161/"
] | The spaces should make no difference. The difference is due to the case: `SW` vs `Sw`.
You don't check for `SW` here:
```
compass in ['S', 'W', 'Sw']]
```
Perhaps change it to this:
```
compass.upper() in ['S', 'W', 'SW']]
``` | Presuming that the "degrees" relate to degrees of latitude or longitude, I can't imagine why "SW" is treated as a viable option. Latitude is either N or S. Longitude is either E or W. Please explain.
Based on your sample of size 1, user input is not to be trusted. Consider checking the input, or at least ensuring that... | 14,359 |
64,120,358 | I try to make simple 3D plot with plot\_surface of matplotlib, below is the minimum example:
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
x_test = np.arange(0.001, 0.01, 0.0005)
y_test = np.arange(0.1, 100, 0.05)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
Xtest,... | 2020/09/29 | [
"https://Stackoverflow.com/questions/64120358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14361102/"
] | It's possible to have 2 nested scroll viewers in Xamarin.Forms.
Notice how it says 'scroll viewers ***should not*** be nested, this means that it is certainly possible but it is not recommended. I think nested scroll viewers creates a bad user-experience and makes for a clunky app, especially for Xamarin.Forms; but ag... | According to your screenshot, i make a code sample for your reference.
**Xaml:**
```
<ScrollView Orientation="Vertical">
<StackLayout Orientation="Horizontal">
<BoxView BackgroundColor="Blue" WidthRequest="150" />
<StackLayout Orientation="Vertical">
<ScrollView Orientation="Horizonta... | 14,360 |
50,962,836 | I am new with python-pptx. But I am familiar with its basic working. I have searched a lot but I could not find a way to change a particular text by another text in all slides. That text may be in any text\_frame of a slide. like all slides in a ppt have 'java' keyword, I want to change it by 'python' using python pptx... | 2018/06/21 | [
"https://Stackoverflow.com/questions/50962836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8847530/"
] | **Shortcuts**:
* `Shift` + `Command` + `L`: Show Library.
* `Shift` + `Command` + `M`: Show Media Library.
---
Xcode 10 has added a toolbar button to access the Object Library.
[](https://i.stack.imgur.com/3J26u.png)
From a [thread](https://forums... | The library can be opened via a new toolbar button, the View β Libraries menu, or the `Shift` + `Command` + `L` keyboard shortcut.The media library is available via a long press on the toolbar button, the View β Libraries menu, or the `Shift` + `Command` + `M` keyboard shortcut.
Library content has moved from the bott... | 14,361 |
35,678,885 | I am following an online course for making web apps with python/mongo/bootstrap.
I install mongodb using default settings
I run mongod in powershell from install directory
```
C:\Program Files\MongoDB\Server\3.2\bin>mongod
2016-02-27T23:31:14.684-0500 I CONTROL [initandlisten] MongoDB starting : pid=2456 port=2701... | 2016/02/28 | [
"https://Stackoverflow.com/questions/35678885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5885288/"
] | The easiest way to get a variable by name is to search for it in the [`tf.global_variables()`](https://www.tensorflow.org/api_docs/python/tf/global_variables) collection:
```
var_23 = [v for v in tf.global_variables() if v.name == "Variable_23:0"][0]
```
This works well for ad hoc reuse of existing variables. A more... | If you want to get any stored variables from a model, use`tf.train.load_variable("model_folder_name","Variable name")` | 14,371 |
54,404,263 | I have a python list A and a python list B with words as list elements. I need to check how often the list elements from list B are contained in list A. Is there a python method or how can I implement this efficient?
The python intersection method only tells me that a list element from list B occurs in list A, but not... | 2019/01/28 | [
"https://Stackoverflow.com/questions/54404263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10478079/"
] | ```
import collections
counter_A = collections.Counter(A)
for word in B:
print(word, '->', counter_A[word])
``` | You could convert list B to a set, so that checking if the element is in B is faster.
Then create a dictionary to count the amount of times that the element is in A if the element is also in the set of B
As mentioned in the comments `collections.Counter` does the "heavy lifting" for you | 14,375 |
51,696,655 | I am new to python and I have a scenario where there are multiple parquet files with file names in order. ex: par\_file1,par\_file2,par\_file3 and so on upto 100 files in a folder.
I need to read these parquet files starting from file1 in order and write it to a singe csv file. After writing contents of file1, file2 c... | 2018/08/05 | [
"https://Stackoverflow.com/questions/51696655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10183474/"
] | I'm having a similar need and I read current Pandas version supports a directory path as argument for the [read\_csv](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_parquet.html) function. So you can read multiple parquet files like this:
```
import pandas as pd
df = pd.read_parquet('path/t... | If you are going to copy the files over to your local machine and run your code you could do something like this. The code below assumes that you are running your code in the same directory as the parquet files. It also assumes the naming of files as your provided above: "order. ex: par\_file1,par\_file2,par\_file3 and... | 14,377 |
40,413,712 | I downloaded wheel to the most recent version
But I'm not entirely sure how to make of this semi-cryptic error message
```
Failed building wheel for mysql-python
Command "/Users/username/Desktop/Project/venv/bin/python -u -c "import setuptools,
tokenize;__file__='/private/var/folders/bg/_nsyc_vxasdfx___h11f3j... | 2016/11/04 | [
"https://Stackoverflow.com/questions/40413712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4407093/"
] | As for me, it is because my system lack of python3 developing lib. It warns that there is no "Python.h" while installing. The following command fix it for me.
`yum install python34-devel -y`
`pip3 install mysqlclient` | The topic is quite old but for the people who might be suffered from having this problem,this can be your solution:
First of all,you must open the file where you use Python like 3.5,3.6,Anaconda etc. Then open cmd in that file and run the command below:
```
$ pip install mysqlclient==1.3.12
``` | 14,387 |
56,588,265 | I've tried replacing each string but I can't get it to work. I can get all the data between `<span>...</span>` but I can't if is closed, how could I do it? I've tried replacing the text afterwards, but I am not able to do it. I am quite new to python.
I have also tried using `for x in soup.find_all('/span', class_ = "... | 2019/06/13 | [
"https://Stackoverflow.com/questions/56588265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11644852/"
] | This problem is basically because the library you are using is in version 1.0.1 [mxgraph-js](https://www.npmjs.com/package/mxgraph-js), this library is very basic with the other features that the latest versions 4.0.6 [mxgraph](https://unpkg.com/mxgraph@4.0.6/javascript/mxClient.js) brings.
In order for your prototype ... | I found a way to resolve this in my webpack project (vuejs) , maybe it's the same problem
because all the mx Object must in window dict
e.g. window['mxCell'] = mxCell
so I write this
```
const {mxCell .......} = mxgraph({
mxImageBasePath: ..... })
// register all object
window['mxClient'] = mxClient
window['mxG... | 14,388 |
40,764,894 | I am trying to run Pylint and I am getting the below error:
>
> pkg\_resources.DistributionNotFound: The 'backports.functools-lru-cache' distribution was not found and is required by pylint
>
>
>
I found the below link, but not sure what to do with these files or where to place them.
<https://pypi.python.org/simp... | 2016/11/23 | [
"https://Stackoverflow.com/questions/40764894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4663869/"
] | I had the same problem and I installed two missing dependencies (wrong configuration on the pylint or not updated pip??)
Just do:
```
pip install backports.functools_lru_cache
```
then if you get an error like:
```
raise DistributionNotFound(req)
```
pkg\_resources.DistributionNotFound: configparser
just do:
``... | I had this problem when running within a [virtual environment](https://virtualenv.pypa.io/en/stable/) on CentOS 7.
On CentOS, the backports module is packaged as a yum package (`python-backports.x86_64`).
The solution was to create the virtualenv using the [`--system-site-packages`](https://virtualenv.pypa.io/en/stab... | 14,389 |
13,358,283 | I tried to start a smtp server with python with the following code:
```
import smtplib
smtp_server = smtplib.SMTP('localhost')
```
And I get the following error:
```
File "test.py", line 2, in <module>
smtp_server = smtplib.SMTP('localhost')
File "/usr/local/lib/python2.7/smtplib.py", line 242, in __init__
... | 2012/11/13 | [
"https://Stackoverflow.com/questions/13358283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/639165/"
] | `smtplib` is SMTP protocol client. What you are looking for is [`smtpd`](http://docs.python.org/2/library/smtpd.html). | The problem is that smtplib does not provide an SMTP server implementation, it implements SMTP client. Most likely, the code tries to connect to localhost and fails. See <http://docs.python.org/2/library/smtplib.html>
Is the other machine you write about already running an SMTP server?
And what are you trying to do? | 14,391 |
42,762,924 | To view the installed libraries on an environment I run this code within a Jupyter Python notebook cell :
```
%%bash
pip freeze
```
This works, but how to conditionally execute this code ?
This is my attempt :
```
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact... | 2017/03/13 | [
"https://Stackoverflow.com/questions/42762924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470184/"
] | You can just use the standard Python way:
```
import subprocess
print(subprocess.check_output(['pip', 'freeze']))
```
Then your function will work in any Python environment. | The short explanation is that the notebook has interactive commands which are handled by the notebook itself, before the Python interpreter even sees them. `%%bash` is an example of such a command; you cannot put this in Python code, because it's not Python.
Using `bash` doesn't actually add anything here *per se;* us... | 14,392 |
61,343,399 | I want to ask about h3-py installation on windows
I have tried to install h3 on windows with python
I ran the command pip install h3 and it is installed.
After install, when I try to import it, i get this error:
```
from h3 import h3
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\site-package... | 2020/04/21 | [
"https://Stackoverflow.com/questions/61343399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7765614/"
] | We're in the process of migrating the wrapper to Cython at <https://github.com/uber/h3-py/tree/cython>
Would you mind trying to install this cython version with these (temporary) install steps:
```
pip install scikit-build
pip install git+https://github.com/uber/h3-py.git@cython
```
Edit:
We've released `3.6.1` al... | Apprently there was a problem with the package and after fixing it in the release v3.6.1 it works. they fixed install issues.
As mentioned in this issue on github :
<https://github.com/uber/h3-py/issues/32> | 14,393 |
2,152,463 | I get the following errors, I've placed [my name] for anonymity:
```
>>> python /Users/[myname]/Desktop/setuptools-0.6c11/ez_setup.py
File "<stdin>", line 1
python /Users/[myname]/Desktop/setuptools-0.6c11/ez_setup.py
^
SyntaxError: invalid syntax
```
If you... | 2010/01/28 | [
"https://Stackoverflow.com/questions/2152463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260666/"
] | The ez\_setup.py script may or may not work depending on your environment. If not, follow the instructions [here](http://pypi.python.org/pypi/setuptools). In particular, from the shell, make sure that the python 2.6 you installed is now invoked by the command `python`:
```
$ python
Python 2.6.4 (r264:75821M, Oct 27 20... | Try running that command from a shell (i.e. straight from Terminal.app), not from inside the python interpreter. | 14,394 |
69,460,583 | I am deploying my project with heroku. My Django version number is 3.2.8 and python 3.9.7. It is written on heroku. Heroku supports Python 3.9.7 deployment, but there is an error in my push process. The version above does not support it. What should I do? Thank you for your reply
This is my cmd
![enter image descriptio... | 2021/10/06 | [
"https://Stackoverflow.com/questions/69460583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17086297/"
] | I parsed the file you provided as an example [here](https://www.sec.gov/Archives/edgar/data/1087699/000108769999000001/0001087699-99-000001.txt). I first copied the data from the file to a txt file. The file `copied.txt` needs to be in the current working directory. This could give you an idea how to proceed.
```r
lib... | You can use `httr` package to request the page:
```
> install.packages("httr")
# follow instructions etc
```
Then in `R` shell (you might need a restart):
```r
> httr::GET("https://www.sec.gov/Archives/edgar/data/1087699/000108769999000001/0001087699-99-000001.txt")
```
This will download the file successfully ho... | 14,395 |
1,233,284 | I want to hit a URL from python in google app engine. Can any one please tell me how can i hit the URL using python in google app engine. | 2009/08/05 | [
"https://Stackoverflow.com/questions/1233284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use the [URLFetch API](http://code.google.com/appengine/docs/python/urlfetch/overview.html)
```
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
doSomethingWithResult(result.content)
``` | It always depends on post or get. urllib can post to a form somewhere else, if we want the rather tricky thing validate between different hashes (sha and md5)
```
import urllib
data = urllib.urlencode({"id" : str(d), "password" : self.request.POST['passwd'], "edit" : "edit"})
result = urlfetch.fetch(url="... | 14,396 |
46,309,485 | I have data that looks like this:
```
['6005600401']
['000000: PUSH1 0x05']
['000002: PUSH1 0x04']
['000004: ADD']
```
The initial representation it's derived from is here:
```
6005600401
000000: PUSH1 0x05
000002: PUSH1 0x04
000004: ADD
```
The output I'd like to create is like so:
```
PUSH1 0x60, PUSH1 0x40... | 2017/09/19 | [
"https://Stackoverflow.com/questions/46309485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3787253/"
] | Why not just split on ':'?
```
for line in status:
data = line.split(:)
if len(data) < 2:
continue
print(data[1].strip())
``` | This is one good way:
```
opcodes_list = list()
for element in status.split('\n'):
result = re.search(r"\b[A-Z].+", element)
if result:
opcodes_list.append(result.group(0))
``` | 14,397 |
37,467,680 | in the following code, there is indentation error at line 5.
what i want is when if condition at line 4 is true then break
should execute otherwise div=div+2 should execute.
```
max_num=input()
for num in range(2,max_num+1):
for div in range(3,max_num/2):
if(num%div==0):break
div=div+2
else: print num
if(nu... | 2016/05/26 | [
"https://Stackoverflow.com/questions/37467680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5774499/"
] | Please use 2 or 4 spaces for indentation. I see your indentation is inconsistent - one time you use 1 space and the others you use 3.
What you did **should** work as I see, but it's just inconsistent.
Here is a slightly more organized version:
```
max_num=input()
for num in range(2,max_num+1):
for div in range(... | I suggest add this code, but i would want to know what is the wanted result for yor code.
```
max_num=input()
for num in range(2,max_num+1):
for div in range(3,max_num/2):
if(num%div==0):break
else:div=div+2
print num
if(num==2): num=num+1
else : num=num+2
``` | 14,398 |
48,254,890 | I'm learning about how to import libraries from directories and I've stumbled upon an error I can't seem to figure out. I'm using the IMDBpy python library in a folder called lib. Below, I am importing the module which no longer returns any errors, but when I move to line number 6, I get the following error:
```
Trace... | 2018/01/14 | [
"https://Stackoverflow.com/questions/48254890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3808507/"
] | You can either write:
```
from lib.imdb import IMDb
ia = IMDb()
```
or:
```
from lib import imdb
ia = imdb.IMDb()
```
But importing `IMDb` and then calling `imdb.IMDb()` does not work.
One other point to mention: If your *testlib.py* resides above the `lib` foder, then you need to add a `__init__.py` file with... | As mentioned above, it is different importing an object from importing a function.
When you import a module such as `imdb` you may use its functions. However, when you import a function, you can only use that function, not the object/module where it came from.
Check this for better examples: [Python 3 modules](https:/... | 14,399 |
68,083,635 | I am using a Queensland government API. The format for it is JSON, and the keys have spaces in them. I am trying to access them with python and flask. I can pass through the data required to the HTML file yet cannot print it using flask.
```
{% block content %}
<div>
{% for suburb in data %}
<p>{{ suburb.Age }... | 2021/06/22 | [
"https://Stackoverflow.com/questions/68083635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16289640/"
] | There's lots of fundamental problems in the code. Most notably, `int**` is not a 2D array and cannot point at one.
* `i<2` typo in the `for(int j...` loop.
* `i < n` in the `for(int k...` loop.
* To allocate a 2D array you must do: `int (*a)[2] = malloc(sizeof(int) * 2 * 2);`. Or if you will `malloc( sizeof(int[2][2])... | You need to fix multiple errors here:
1/ line 5/24/28: `int **c = malloc(sizeof(int*) * n )`
2/ line 15: `k<n`
3/ Remark: use `a[i][j]` instead of `*(*(a+i)+j)`
4/ line 34: `j<2`
5/ check how to create a 2d matrix using pointers.
```
#include <stdio.h>
#include <stdlib.h>
int** multiply(int** a, int** b, int n) ... | 14,400 |
47,969,587 | I can't figure out how to open a dng file in opencv.
The file was created when using the pro options of the Samsung Galaxy S7.
The images that are created when using those options are a dng file as well as a jpg of size 3024 x 4032 (I believe that is the dimensions of the dng file as well).
I tried using the answer fr... | 2017/12/25 | [
"https://Stackoverflow.com/questions/47969587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8461821/"
] | As far as i know it is possible that DNG files can be compressed (even though it is lossless format), so you will need to decode your dng image first. <https://www.libraw.org/> is capable of doing that.
There is python wrapper for that library (<https://pypi.python.org/pypi/rawpy>)
```
import rawpy
import imageio
pa... | [process\_raw](https://github.com/DIYer22/process_raw) supports both read and write `.dng` format raw image. Here is a python example:
```py
import cv2
from process_raw import DngFile
# Download raw.dng for test:
# wget https://github.com/yl-data/yl-data.github.io/raw/master/2201.process_raw/raw-12bit-GBRG.dng
dng_pa... | 14,402 |
43,287,649 | Let's say this is normal:
```
@api.route('/something', methods=['GET'])
def some_function():
return jsonify([])
```
**Is it possible to use a function that is already defined?**
```
def some_predefined_function():
return jsonify([])
@api.route('/something', methods=['GET'])
some_predefined_function()
```
... | 2017/04/07 | [
"https://Stackoverflow.com/questions/43287649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680578/"
] | There are a few ways to add routes in Flask, and although `@api.route` is the most elegant one, it is not the only one.
Basically a decorator is just a fancy function, you can use it inline like this:
```
api.route('/api/galleries')(some_func)
```
Internally `route` is calling [add\_url\_rule](http://flask.pocoo.or... | Try this:
```
def some_predefined_function():
return jsonify([])
@api.route('/something', methods=['GET'])
def something():
return some_predefined_function()
``` | 14,403 |
42,077,768 | the code is
```
for(int i = 0; i < max; i++) {
//do something
}
```
I use this exact code many times when I program, always starting at 0 and using the interval i++. There is really only one variable that changes (max)
It could not be that much shorter, but considering how much this code is used, it would be... | 2017/02/06 | [
"https://Stackoverflow.com/questions/42077768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7525600/"
] | When looping through collections, you can use enhanced loops:
```
int[] numbers =
{1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println(item);
}
``` | Since a few people asked for something like this, here are a few things you could do, although whether these are really better is arguable and a matter of taste:
```
void times(int n, Runnable r) {
for (int i = 0; i < n; i++) {
r.run();
}
}
```
Usage:
```
times(10, () -> System.out.println("Hello, w... | 14,404 |
44,560,051 | For example, I have a 2D Array with dimensions 3 x 3.
```
[1 2 7
4 5 6
7 8 9]
```
And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of:
```
[2
5
8]
```
How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions.
T... | 2017/06/15 | [
"https://Stackoverflow.com/questions/44560051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8164362/"
] | ```
#Creating array
x = np.array([[1, 2, 7],[4,5, 6],[7,8,9]])
x
Out[]:
array([[1, 2, 7],
[4, 5, 6],
[7, 8, 9]])
#Deletion
a = np.delete(x,np.where(x ==7),axis=1)
a
Out[]:
array([[2],
[5],
[8]])
``` | `numpy` can help you do this!
```
import numpy as np
a = np.array([1, 2, 7, 4, 5, 6, 7, 8, 9]).reshape((3, 3))
b = np.array([col for col in a.T if 7 not in col]).T
print(b)
``` | 14,414 |
58,338,523 | The [documentation](https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blockblobservice.blockblobservice?view=azure-python#batch-set-standard-blob-tier-batch-set-blob-tier-sub-requests--timeout-none-) for the batch\_set\_standard\_blob\_tier function part of BlockBlobService in azure pyt... | 2019/10/11 | [
"https://Stackoverflow.com/questions/58338523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6603039/"
] | You need add `allowSyntheticDefaultImports` in your `tsconfig.json`.
`tsconfig.json`
```
{
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true
}
```
TS
```
import countries from './countries/es.json';
``` | import is not a good idea here later on if you want to move your file to some server you will need to rewrite the whole logic i would suggest to use [httpclient](https://angular.io/guide/http) get call here.So move you file to assets folder and then
```
constructor(private http:HttpClient){
this.http.get('assets/yourf... | 14,422 |
52,907,038 | I am looking for a method (if available) that can compare two values and raise an assertion error with a meaningful message when the comparison fails.
If I use `assert`, the failure message does not contain what values were compared when then assertion failed.
```
>>> a = 3
>>> b = 4
>>> assert a == b
Traceback (most... | 2018/10/20 | [
"https://Stackoverflow.com/questions/52907038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278326/"
] | You have to give the assertion message by hand:
```
assert a == b, '%s != %s' % (a, b)
# AssertionError: 3 != 4
``` | have you looked at numpy.testing?
<https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.testing.html>
Amongst others it has:
assert\_almost\_equal(actual, desired[, ...]) Raises an AssertionError if two items are not equal up to desired precision.
This assert prints out actual and desired. If you ramp up pre... | 14,425 |
69,843,983 | I main java and just started on python, and I ran into this error when I was trying to create a class. Can anyone tell me what is wrong?
```
import rectangle
a = rectangle(4, 5)
print(a.getArea())
```
this is what is in the rectangle class:
```
class rectangle:
l = 0
w = 0
def __init__(self, l, w):
... | 2021/11/04 | [
"https://Stackoverflow.com/questions/69843983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16533352/"
] | I don't know what you have implemented in the rectangle module but I suspect that what you're actually looking for is this:
```
from rectangle import rectangle
a = rectangle(4, 5)
print(a.getArea())
```
If not, give us an indication of what's in rectangle.py | your gonna need to specify what module the function is from
so either import all the functions
so change `import rectangle` to `from rectangle import *`
or switch the `rectangle(4,5)` to `rectangle.rectangle(4,5)` | 14,433 |
32,967,460 | I have a django site that is deployed in production and already ran `python manage.py runserver` and so now the server is running on the port of `8000`.
So what I want to do is to hit the running server and visited this on the domain `domainname.com:8000` and am not getting any response from the server.
Should I be d... | 2015/10/06 | [
"https://Stackoverflow.com/questions/32967460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1140228/"
] | >
> I have a django site that is deployed in production and already ran python manage.py runserver
>
>
>
That's not how you deploy Django projects in production, cf <https://docs.djangoproject.com/en/1.8/howto/deployment/>
The builtin dev server is only made for dev - it's unsafe, doesn't handle concurrent reque... | Additionally to @bruno desthuilliers answer, with which I totally agree, if nevertheless you insist, you have to run the server as:
```
python manage.py runserver 0.0.0.0:8000
```
so that to let it listen to any interface.
Relevant documentation: [django-admin](https://docs.djangoproject.com/en/1.8/ref/django-admin... | 14,434 |
61,114,206 | Recently I created a 24 game solver with python
Read this website if you do not know what the 24 game is:
<https://www.pagat.com/adders/24.html>
Here is the code:
```
from itertools import permutations, product, chain, zip_longest
from fractions import Fraction as F
solutions = []
def ask4():
num1 = input... | 2020/04/09 | [
"https://Stackoverflow.com/questions/61114206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10379866/"
] | On the network tab, you must select the post request and then go to the parameters you are sending and check if you are sending the data and if it is the right structure.
This is how it looks like on Chrome there is where you check the data you are sending
[:
mail.send(msg)
def send_email(subject, sender, recipients, text_body, html_body):
msg = Message(subject, sender = sender, recipien... | How about simply using ThreadPool and Queue? You can then process your stuff in a seperate thread in a synchronous manner and you won't have to worry about blocking at all. Well, Python is not suited for CPU bound tasks in the first place, so you should also think of spawning subprocesses. | 14,436 |
27,260,199 | So I have this issue where libv8-3.16.14.3 fails to install, even though it deceptively tells you it did install.
So the first sign of issue was when it did:
```
An error occurred while installing libv8 (3.16.14.3), and Bundler cannot continue.
Make sure that `gem install libv8 -v '3.16.14.3'` succeeds before bundlin... | 2014/12/02 | [
"https://Stackoverflow.com/questions/27260199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005826/"
] | I got this to work by first using Homebrew to install V8:
```
$ brew install v8
```
Then running the command you mentioned you found on Google:
```
$ gem install libv8 -v '3.16.14.3' -- --with-system-v8
```
And finally re-running bundle install:
```
$ bundle install
``` | As others have suggested:
```
$ brew install v8
$ gem install libv8 -v '3.16.14.3' -- --with-system-v8
$ bundle install
```
If that does not work, try running `bundle update`.
Running `bundle update` in addition was the only way it worked | 14,437 |
3,442,920 | I can't seem to find any information on debugging a python web application, specifically stepping through the execution of a web request.
is this just not possible? if no, why not? | 2010/08/09 | [
"https://Stackoverflow.com/questions/3442920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39677/"
] | If you put
```
import pdb
pdb.set_trace()
```
in your code, the web app will drop to a pdb debugger session upon executing `set_trace`.
Also useful, is
```
import code
code.interact(local=locals())
```
which drops you to the python interpreter. Pressing Ctrl-d resumes execution.
Still more useful, is
```
im... | use Python Debbuger, `import pdb; pdb.set_trace()` exactly where you want to start debugging, and your terminal will pause in that line.
More info here:
<http://plone.org/documentation/kb/using-pdb> | 14,440 |
17,919,788 | I tried to run my python scripts using crontab. As the amount of my python scripts accumulates, it is hard to manage in crontab.
Then I tries two python schedule task libraries named [Advanced Python Scheduler](http://pythonhosted.org/APScheduler/) and [schedule](https://github.com/dbader/schedule).
The two librarie... | 2013/07/29 | [
"https://Stackoverflow.com/questions/17919788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/975222/"
] | In 2013 - when this question was created - there were not as many workflow/scheduler management tools freely available on the market as they are today.
So, writing this answer in 2021, I would suggest using Crontab as long as you have only few scripts on very few machines.
With a growing collection of scripts, the ne... | One way is to use [management commands](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) and setup a crontab to run those. We use that in production and it works really well.
Another is to use something like celery to [schedule tasks](http://docs.celeryproject.org/en/latest/reference/celery.sch... | 14,443 |
15,096,667 | I'm trying to convert code from TCL into python using Tkinter.
I was wondering what would be the equivalent code in Tkinter for
"spawn ssh", "expect", and "send"?
For example, my simple tcl program would be something like:
```
spawn ssh root@138.120.###.###
expect "(yes/no)?" {send -- "yes\r"}
expect "password" {send... | 2013/02/26 | [
"https://Stackoverflow.com/questions/15096667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1988580/"
] | You could try to use [pexpect](http://www.noah.org/wiki/pexpect).
Expect is used to automate other command line tools.
Edit: Of curse you could just try to execute `package require Expect` through Tkinter, but what benefit would that have over a pure Tcl script? After all you write Tcl code then, wraped in python.
A... | [pxpect](http://pexpect.sourceforge.net) has a module called pxssh, that takes a lot of the the work out of manipulating simple ssh sessions. I found that this wasn't sufficient for heavy automation and wrote [remote](http://gethub.com/Telenav/python-remote) as an add-on to increase error handling.
using pxssh
```
fr... | 14,444 |
22,791,074 | 
what function should i use to draw the above performance profile of different algorithms, the running time data is from python implementation, stored in lists for different algorithm. Is there any build-in function in Python or Matlab to draw this ki... | 2014/04/01 | [
"https://Stackoverflow.com/questions/22791074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3029108/"
] | You can absolutely have a state without a URL. In fact, none of your states need URLs. That's a core part of the design. Having said that, I wouldn't do what you did above.
If you want two states to have the same URL, create an [abstract parent state](https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nest... | To add to the other answer, Multiple Named Views do not use a URL.
From the docs:
>
> If you define a views object, your state's templateUrl, template and
> templateProvider will be ignored. So in the case that you need a
> parent layout of these views, you can define an abstract state that
> contains a template... | 14,445 |
25,185,015 | I am using python request module for doing HTTP communications. I was using proxy before doing any communication.
```
import requests
proxy = {'http': 'xxx.xxx.xxx.xxx:port'}
OR
proxy = {'http': 'http://xxx.xxx.xxx.xxx:port'}
OR
proxy = {'http://xxx.xxx.xxx.xxx:port'}
request... | 2014/08/07 | [
"https://Stackoverflow.com/questions/25185015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000683/"
] | Try this:
```
proxy = {'http': 'http://xxx.xxx.xxx.xxx:port'}
```
I guess you just missed the `http://` in the value of the proxy dict.
Check: <http://docs.python-requests.org/en/latest/user/advanced/#proxies> | [Documentation](http://docs.python-requests.org/en/latest/user/advanced/#proxies) says:
>
> If you need to use a proxy, you can configure individual requests with
> the proxies argument to any request method:
>
>
>
```
import requests
proxies = {"http": "http://10.10.1.10:3128"}
requests.get("http://example.org"... | 14,446 |
61,226,690 | I am relatively new to Python so please pardon my ignorance. I want to know answer to following questions
1. How does pip know the location to install packages that it installs? After a built of trial and error
I suspect that it maybe hardcoded at time of installation.
2. Are executables like pip.exe what they call f... | 2020/04/15 | [
"https://Stackoverflow.com/questions/61226690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10796482/"
] | as I understand you only want to save user input only if contains text
so you have to clean the user input from HTML then check the output length
```
var regex = /(<([^>]+)>)/ig
body = "<p>test</p>"
hasText = !!body.replace(regex, "").length;
if(hasText) save()
``` | This worked for me so it wouldn't escape images.
```
function isQuillEmpty(value: string) {
if (value.replace(/<(.|\n)*?>/g, '').trim().length === 0 && !value.includes("<img")) {
return true;
}
return false;
}
``` | 14,447 |
37,308,794 | I'm new to this and trying to deploy a first app to the app engine. However, when i try to i get this message:
"This application does not exist (app\_id=u'udacity')."
I fear it might have to do with the app.yaml file so i'll just leave here what i have there:
application: udacity
version: 1
runtime: python27
api\_vers... | 2016/05/18 | [
"https://Stackoverflow.com/questions/37308794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6002144/"
] | Blocks are normal objects so you can store them in NSArray/NSDictionary. Having that said the implementation is straightforward.
```
#import <Foundation/Foundation.h>
/** LBNotificationCenter.h */
typedef void (^Observer)(NSString *name, id data);
@interface LBNotificationCenter : NSObject
- (void)addObserverForN... | Why don't you just add the blocks into the `NSDictionary` ? You can do it like it's explained [in this answer](https://stackoverflow.com/questions/6364648/keep-blocks-inside-a-dictionary) | 14,448 |
38,435,845 | I am newbie to elasticsearch, I know there is two official client elasticsearch supplies, but when I use the python elasticsearch, i can't find how to use the transport client..
I read the whole doc which is as following:
```
https://elasticsearch-py.readthedocs.io/en/master/index.html
```
I also search some docs... | 2016/07/18 | [
"https://Stackoverflow.com/questions/38435845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6114947/"
] | The transport client is written in Java, so the only way to use it from Python is by switching to Jython. | I think the previous answer is out of date now, if this is [the transport client you mean](https://elasticsearch-py.readthedocs.io/en/master/transports.html).
I've made use of this API to do things like use the [\_rank\_eval](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/search-rank-eval.html) API, whic... | 14,449 |
56,415,470 | IPython 7.5 documentation states:
>
> Change to Nested Embed
>
>
> The introduction of the ability to run async code had some effect on the IPython.embed() API. By default, embed
> will not allow you to run asynchronous code unless an event loop is specified.
>
>
>
However, there seem to be no description how ... | 2019/06/02 | [
"https://Stackoverflow.com/questions/56415470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6543759/"
] | ```
from IPython import embed
import nest_asyncio
nest_asyncio.apply()
```
Then `embed(using='asyncio')` might somewhat work. I don't know why they don't give us a real solution though. | This seems to be possible, but you have to use `ipykernel.embed.embed_kernel()` instead of `IPython.embed()`.
`ipykernel` requires you to connect to the embedded kernel remotely from a separate jupyter console though, so it is not as convenient as just being able to spawn the shell on the same window, but at least it ... | 14,450 |
62,175,337 | I want to fetch the next 5 records after the specific index.
For example, this is my dataframe:
```
Id Name code
1 java 45
2 python 78
3 c 65
4 c++ 25
5 html 74
6 css 63
7 javascript 45
8 php 44
... | 2020/06/03 | [
"https://Stackoverflow.com/questions/62175337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10971762/"
] | Set up properties on the file attached to the solution, basically you need to make sure the file is included to the solution output:
1. Set the `Build Action` property to `Content`.
2. Set the `Copy to the Output Directory` property to `Copy Always`.
For example, if the file is added to the project and you select it ... | You really need to add that that utility to you installer project.
Or you can embed the utility as a resource in your dll, extract it at run-time, copy to some folder, and execute. | 14,451 |
62,579,298 | I have a data frame that looks like this:
```
name Title
abc 'Tech support'
xyz 'UX designer'
ghj 'Manager IT'
... ....
```
I want to iterate through the data frame and using `df.str.contains` make another column that will categorize those jobs. T... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62579298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12724372/"
] | You can do something like this:
```
cat_dict = {"Support":"Support", "designer":"Designer", "Manager": "Management"}
df['category'] = (df['Title'].str.extract(fr"\b({'|'.join(cat_dict.keys())})\b")[0]
.map(cat_dict)
)
``` | General syntax of python if statement is:
```
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
```
As you can see in the syntax, to evaluate a *test expression*, it should be in the *if* or in the *elif* construct. The code throws the syntax error as the test expre... | 14,453 |
57,309,209 | I am working on a data frame with DateTimeIndex of hourly temperature data spanning a couple of years. I want to add a column with the minimum temperature between 20:00 of a day and 8:00 of the *following* day. Daytime temperatures - from 8:00 to 20:00 - are not of interest. The result can either be at the same hourly ... | 2019/08/01 | [
"https://Stackoverflow.com/questions/57309209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7057547/"
] | Use the `base` option to `resample`:
```
rs = df.resample('12h', base=8).min()
```
Then keep only the rows for 20:00:
```
rs[rs.index.hour == 20]
``` | you can use `TimeGrouper` with `freq=12h` and `base=8` to chunk the dataframe every 12h from 20:00 - (+day)08:00,
then you can just use `.min()`
try this:
```py
import pandas as pd
from io import StringIO
s = """
datetime temp
2009-07-01 01:00:00 17.16
2009-07-01 02:00:00 16.64
2009-07-01 ... | 14,456 |
54,403,437 | I want to script with python using Notepad ++ but it works strangely, actually it does not work, so I have pycharm an everything is going well but in notepad ++ when I save file with .py and click run it does not work is there a step by step instruction to follow?
I have same problem with sublime text editor so I am lu... | 2019/01/28 | [
"https://Stackoverflow.com/questions/54403437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10979398/"
] | You call `setPreferredSize` twice, which results in the first call doing basically nothing. That means you always have a `preferredSize` equal to the dimensions of the second image. What you *should* do is to set the size to `new Dimension(image.getWidth() + image2.getWidth(), image2.getHeight())` assuming both have th... | I found some errors in your code and I did not got what are you trying to do...
1] Over there you are actually not using the first setup
```
Dimension dimension = new Dimension(image.getWidth(), image.getHeight());
setPreferredSize(dimension); //not used
Dimension dimension2 = new Dimension(image2.getWidt... | 14,457 |
44,857,219 | When I use the command "pip install pyperclip" it gives me this error
```
creating /Library/Python/2.7/site-packages/pyperclip
error: could not create '/Library/Python/2.7/site-packages/pyperclip': Permission denied
----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, token... | 2017/07/01 | [
"https://Stackoverflow.com/questions/44857219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4081977/"
] | When ever you get error `Permission denied` its because you are trying to access the root using normal commands. So trying running the command as root to get rid of `Permissin denied` error. Run `sudo command` i.e `sudo pip install pyperclip` | Try it with
>
> sudo pip install pyperclip
>
>
>
Now if it throws some access deny error, try this:
>
> sudo pip -H install pyperclip
>
>
> | 14,461 |
7,238,401 | I've found similar but not identical questions [742371](https://stackoverflow.com/questions/742371/python-strange-behavior-in-for-loop-or-lists) and [4081217](https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop) with great answers, but haven't come to a solution to my problem.
I'm tr... | 2011/08/30 | [
"https://Stackoverflow.com/questions/7238401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/563343/"
] | How about something like this (just made up a silly condition so I could test it):
```
import random
myList = ['it1', 'test', 'blah', 10]
newList = []
def someCondition(var):
return random.randrange(0,2) == 0
def test():
while len(myList) > 0:
pos = 0
while pos < len(myList):
if... | A brute force approach would be to create a temporary list of booleans the same size as your original list initialized to `False` everywhere.
In each pass, whenever the item at index `i` of the original list meets the condition, update the value in the temporary array at index `i` with False.
In each subsequent pass,... | 14,464 |
65,063,178 | I am trying to create a hangman game using python in VScode. I imported pygame and now it won't let me do pygame.init(). I looked at other posts here and I tried it but I'm not sure why it is not working. Other posts said to go to setting.json and add
```
{ "python.linting.pylintArgs": [
"--extension-pkg-whitelist... | 2020/11/29 | [
"https://Stackoverflow.com/questions/65063178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14730665/"
] | 1. If you want to turn off Pylint notifications via settings, please use the following format:
>
>
> ```
> "python.linting.pylintArgs":
> [
> "--extension-pkg-whitelist=lxml", // The extension is "lxml" not "1xml"
> "--unsafe-load-any-extension=y"
> ],
>
> ```
>
>
[![enter image d... | Vscode has launched new python language server `pylance` install it from extensions. After that change you language server to pylance.
You will get amazing features like autoimport, auto completion, linter, debugger, etc.
Also check in which environment you have installed pygame. Switch the python interpreter using ctr... | 14,467 |
66,321,777 | I have a Flask server that will fetch keys from Redis. How would I maintain a list of already deleted keys? Every time I delete a key, it needs to be added to this list within Redis. Every time I try to check for a key in the cache, if it cannot be found I want to check if it is already deleted. This would allow me to ... | 2021/02/22 | [
"https://Stackoverflow.com/questions/66321777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/127251/"
] | I think you should separate the name and the number into different attributes:
```
name | number | id
```
and the SQL query should be something like this:
```
select ...
group by name, number;
```
depending on what you want to do.
Is something like this? | The grouping SQL statement will be
```
select id, name from commande_ligne group by name order by name
```
The outcome should show
product 78
id
5
6
11
Product 12
Id
14
15
That's the result that you will get | 14,468 |
67,108,896 | I am using python for webscraping (new to this) and am trying to grab the brand name from a website. It is not visible on the website but I have found the element for it:
`<span itemprop="Brand" style="display:none;">Revlon</span>`
I want to extract the "Revlon" text in the HTML. I am currently using html requests a... | 2021/04/15 | [
"https://Stackoverflow.com/questions/67108896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11472545/"
] | Here is a working solution with Selenium:
```
from seleniumwire import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
website = 'https://www.boots.com/revlon-colorstay-makeup-for-normal-dry-skin-10212694'
driver.get(website)
brand_name ... | try this method
.find("span", itemprop="Brand")
I think it's work
```
from bs4 import BeautifulSoup
import requests
urlpage = 'https://www.boots.com/revlon-colorstay-makeup-for-normal-dry-skin-10212694'
page = requests.get(urlpage)
# parse the html using beautiful soup and store in variable 'soup'
soup = BeautifulSo... | 14,473 |
56,613,286 | Say that I have a list of strings, such as
```
listStrings = [ 'cat', 'bat', 'hat', 'dad', 'look', 'ball', 'hero', 'up']
```
Is there a way would return all rows if a particular column contains 3 or more of the strings from the list?
For example
If the column contained 'My dad is a hero for saving the cat'
Then... | 2019/06/15 | [
"https://Stackoverflow.com/questions/56613286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259896/"
] | You could use something like this:
```
$reviews = Review::orderBy('created_at', 'DESC')
->orWhere('created_at','>=',now()->subDays($request->review == 7 ? 7 : 30)
->where('listing_id', $id)
->where('user_id', Auth::user()->id)
->paginate(6, ['*'], 'review');
```
but keep in mind you might still get w... | You can split Eloquent Builder by cursor.
```php
$cursor = Review::orderByDesc('created_at');
if ($request->review == "7") {
$cursor->orWhere('created_at','>=', 7));
}
$reviews = $cursor->where('listing_id', $id)
->where('user_id', Auth::user()->id)
->paginate(6, ['*'], 'review');
``` | 14,474 |
21,449,085 | I may get slammed because this question is too broad, but anyway I going to ask cause what else do I do? Digging through the Python source code should surely give me enough "good effort" points to warrant helping me?
I am trying to use Python 3.4's new email content manager <http://docs.python.org/dev/library/email.co... | 2014/01/30 | [
"https://Stackoverflow.com/questions/21449085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/627492/"
] | First: the βaddress fieldsβ in an email are in fact simply headers whose names have been agreed upon in standards, like `To` and `From`. So all you need are the email headers and body and you are done.
Given a modern `contentmanager`-powered `EmailMessage` instance such as Python 3.4 returns if you specify a policy (l... | If you have an email in a file and want to read it into Python, it's the [`email.Parser` you should probably look at](http://docs.python.org/dev/library/email.parser.html#parser-class-api) first. [Like Brandon](https://stackoverflow.com/a/22697432/923794), I don't quite see the need for using the `contentmanager`, but ... | 14,477 |
48,065,360 | I want to use python interpolate polynomial on points from a finite-field and get a polynomial with coefficients in that field.
Currently I'm trying to use SymPy and specifically interpolate (from `sympy.polys.polyfuncs`), but I don't know how to force the interpolation to happen in a specific gf. If not, can this be ... | 2018/01/02 | [
"https://Stackoverflow.com/questions/48065360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5603149/"
] | SymPy's [interpolating\_poly](http://docs.sympy.org/latest/modules/polys/reference.html#sympy.polys.specialpolys.interpolating_poly) does not support polynomials over finite fields. But there are enough details under the hood of SymPy to put together a class for finite fields, and find the coefficients of [Lagrange pol... | I'm the author of the [`galois`](https://github.com/mhostetter/galois) Python library. Polynomial interpolation can be performed with the `lagrange_poly()` function. Here's a simple example.
```py
In [1]: import galois
In [2]: galois.__version__
Out[2]: '0.0.32'
In [3]: GF = galois.GF(3**5)
In [4]: x = GF.Random(10... | 14,478 |
16,809,248 | My works relates to instrumentation of code fragments in python code. So in my work i would be writing a script in python such that I take another python file as input and insert any necessary code in the required place with my script.
The following code is a sample code of a file which i would be instrumenting:
```
... | 2013/05/29 | [
"https://Stackoverflow.com/questions/16809248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2135762/"
] | Use the [`ast` module](http://docs.python.org/2/library/ast.html) to parse the file properly.
This code prints the line number and column offset of each `def` statement:
```
import ast
with open('mymodule.py') as f:
tree = ast.parse(f.read())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
... | You could use a Regular Expression. To avoid `def` inside quotes then you can use negative look-arounds:
```
import re
for line in open('A.py'):
m = re.search(r"(?!<[\"'])\bdef\b(?![\"'])", line)
if m:
print r'@decorator #<------ inserted code'
print line
```
However, there might be other ... | 14,479 |
26,027,271 | I have a dictionary of configs (defined by the user as settings for a Django app).
And I need to check the config to make sure it fits the rules.
The rule is very simple. The 'range' within each option must be unique.
sample settings
===============
```
breakpoints = {
'small': {
'verbose_name': _('Sma... | 2014/09/24 | [
"https://Stackoverflow.com/questions/26027271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1682844/"
] | Its easy to scan for overlapping ranges if you sort the dataset first. 'None' appears to be used for different things in different places (as min its zero) as max its "greater than anything" - but that's harder to compare. If you have a real maximum, it makes the sorting a bit easier.
(edit: scan for max because there... | You can get from that a dict with the ranges as pairs:
```
ranges = { 'small': (None, 640), 'medium': (641, 1024), ...}
```
and then check, say, that `len(set(ranges.values())) == len(ranges)`
EDIT: this works if the requirement is for ranges to be different. See @tdelaney's answer for disjoint ranges. | 14,480 |
8,510,972 | I have seen a lot of posts on this topic, however I have not found regarding this warning:
```
CMake Warning:
Manually-specified variables were not used by the project:
BUILD_PYTHON_SUPPORT
```
when I compile with cmake. When building OpenCV with this warning, it turns out that it doesn't include python suppo... | 2011/12/14 | [
"https://Stackoverflow.com/questions/8510972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256664/"
] | It looks like you're using an old install guide. Use `BUILD_NEW_PYTHON_SUPPORT` instead.
So, execute CMake like this:
```
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_NEW_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON ..
```
Also, if you use the CMake GUI, it is easier to see all of the opt... | **Simple instructions to install opencv with python bindings in Linux - Ubuntu/Fedora**
1. Install gcc, g++/gcc-c++, cmake (apt-get or yum, in case of yum
use gcc-c++).
**#apt-get install gcc, g++, cmake**
2. Downlaod latest opencv from openCV's website
(<http://opencv.org/downloads.html>).
3. Untar it **#tar - xvf op... | 14,481 |
3,693,891 | I'm writing a program that (part of what is does is) executes other programs. I want to to be able to run as many types of programs (written in different languages) as possible using `Process.Start` . So, I'm thinking I should:
1. Open the file
2. Read in the first line
3. Check if it starts with `#!`
4. If so, use wh... | 2010/09/12 | [
"https://Stackoverflow.com/questions/3693891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65387/"
] | In Windows there is no real notion of "executable", like the specific permission that exists in \*NIX systems.
You have two options. The first one, like saurabh had suggested before me, is to rely on the system to associate between the file extension and the command to be performed. This approach (of using Process.St... | if you are using .net than Process.Start do lot of things for you.
if you pass a exe , it will run the exe.
If you pass a word document , it will open the word document
and may more | 14,482 |
16,082,243 | ```
<Control-Shift-Key-0>
<Control-Key-plus>
```
works but
```
<Control-Key-/>
```
doesn't.
I am unable to bind `ctrl` + `/` in python. Is there any documentation of all the possible keys? | 2013/04/18 | [
"https://Stackoverflow.com/questions/16082243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2219529/"
] | Use `<Control-slash>`:
```
def quit(event):
print "you pressed control-forwardslash"
root.quit()
root = tk.Tk()
root.bind('<Control-slash>', quit) # forward-slash
# root.bind('<Control-backslash>', quit) # backslash
root.mainloop()
```
---
I don't have a link to a complete list of these event names. ... | Here is a list of all the tk keysysm codes:
<https://www.tcl.tk/man/tcl8.6/TkCmd/keysyms.htm>
The two I was looking for was `<Win_L>` and `<Win_R>`. | 14,491 |
68,005,264 | I'm executing an extract query to google storage as follows:
```
job_config = bigquery.ExtractJobConfig()
job_config.compression = bigquery.Compression.GZIP
job_config.destination_format = (bigquery.DestinationFormat.CSV)
job_config.print_header = False
job_config.field_delimiter = "|"
extract_job = client.extract_ta... | 2021/06/16 | [
"https://Stackoverflow.com/questions/68005264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3447863/"
] | First of all, Start Events must not have an incoming Edge. It is not allowed by the BPMN standard. So you should replace your Start Events 2 and 3 within the process with intermediate Events.
The decission logic to skip or execute the Intermediate Event now representing the event of what was before Start Event 3 could... | Based on Simulat's answer I found a alternative solution which I think is the better fit. The red path should not be possible because of the logic gate with the red circle (the top path is only viable if `Start Event 3` has not occurred).
The problem I have with Simulat's answer are the intermediate events and the eve... | 14,492 |
54,272,604 | I have a recursive solution that works, but it turns out a lot of subproblems are being recalculated. I need help with MEMOIZATION.
So here's the problem statement:
>
> You are a professional robber planning to rob houses along a street.
> Each house has a certain amount of money stashed, the only constraint
> sto... | 2019/01/20 | [
"https://Stackoverflow.com/questions/54272604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7938658/"
] | The `helper` can be called with different `value` parameter for same `index`. So the `value` must be removed (subtracted from the stored `max_dict`). One way to do this is to add `value` just before returning, not earlier:
```
money = [2, 1, 1, 2]
max_dict = {}
def helper(value, index):
if index in max_dict:
... | Your approach for memoization won't work because when you reach some index `i`, if you've already computed some result for `i`, your algorithm fails to consider the fact that there might be a *better* result available by robbing a more optimal set of houses in the left portion of the array.
The solution to this dilemm... | 14,493 |
150,532 | Similar to [this](https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python) question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.
I first read all ten bytes into a string. I then want to parse out the individual ... | 2008/09/29 | [
"https://Stackoverflow.com/questions/150532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] | If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by:
```
>>> s = '\0\x02'
>>> struct.unpack('>H', s)
(2,)
```
Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use.
For other sizes of integer, you use differen... | I was going to recommend the `struct` package but then you said you had tried it. Try this:
```
self.major_version = struct.unpack('H', self.whole_string[3:5])
```
The `pack()` function convers Python data types to bits, and the `unpack()` function converts bits to Python data types. | 14,496 |
64,647,954 | I want to webscrape german real estate website immobilienscout24.de. I would like to download the HTML of a given URL and then work with the HTML offline. It is not intended for commercial use or publication and I do not intend on spamming the site, it is merely for coding practice. I would like to write a python tool ... | 2020/11/02 | [
"https://Stackoverflow.com/questions/64647954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14361382/"
] | Try to set `Accept-Language` HTTP header (this worked for me to get correct response from server):
```
import requests
from bs4 import BeautifulSoup
url = "https://www.immobilienscout24.de/Suche/de/wohnung-mieten?sorting=2#"
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:82.0) Gecko/201001... | Maybe have a go with [requests](https://requests.readthedocs.io/en/master/), the code below seems to work fine for me:
```
import requests
from bs4 import BeautifulSoup
r = requests.get('https://www.immobilienscout24.de/')
soup = BeautifulSoup(r.text, 'html.parser')
print(soup.prettify)
```
Another approach is to ... | 14,499 |
15,011,674 | Can you dereference a variable id retrieved from the [`id`](https://docs.python.org/library/functions.html#id) function in Python? For example:
```
dereference(id(a)) == a
```
I want to know from an academic standpoint; I understand that there are more practical methods. | 2013/02/21 | [
"https://Stackoverflow.com/questions/15011674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1248775/"
] | Here's a utility function based on a (now-deleted) comment made by "Tiran" in a weblog [discussion](https://web.archive.org/web/20090404012257/http://www.friday.com/bbum/2007/08/24/python-di/) @Hophat Abc references in [his own answer](https://stackoverflow.com/a/15012076/355230) that will work in both Python 2 and 3.
... | Not easily.
You could recurse through the [`gc.get_objects()`](http://docs.python.org/2/library/gc.html#gc.get_objects) list, testing each and every object if it has the same `id()` but that's not very practical.
The `id()` function is *not intended* to be dereferenceable; the fact that it is based on the memory addr... | 14,504 |
18,394,350 | Today, I wrote a short script for a prime sieve, and I am looking to improve on it. I am rather new to python and programming in general, and so I am wondering: what is a good way to reduce memory usage in a program where large lists of numbers are involved? Here is my example script:
```
def ES(n):
A = list(range... | 2013/08/23 | [
"https://Stackoverflow.com/questions/18394350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2467476/"
] | First, you're using a really weird, inefficient way to record whether something is composite. You don't need to store string representations of the numbers, or even the numbers themselves. You can just use a big list of booleans, where `prime[n]` is true if `n` is prime.
Second, there's no reason to worry about wastin... | Rather than using large lists, you can use generators.
```
def ESgen():
d = {}
q = 2
while 1:
if q not in d:
yield q
d[q*q] = [q]
else:
for p in d[q]:
d.setdefault(p+q,[]).append(p)
del d[q]
q += ... | 14,507 |
46,909,017 | I want to insert a row in a table of a database from a python script. The column fiels values are saved in variables of different formats: strings, integers, and floats. I search in forums, I tried differente options but no one is working
I tried this options:
```
cursor.execute('INSERT INTO table(device, number1, nu... | 2017/10/24 | [
"https://Stackoverflow.com/questions/46909017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3278790/"
] | you can use parameter binding. you don't need to worry about the datatypes of the variables that being passed.
```
cursor.execute('INSERT INTO table(device, number1, number2) VALUES (?, ?, ?)', ("dev1",1,2.4))
``` | Check if you're calling commit() post execution of query or also you can enable autocommit for connection.
```
connection_obj.commit()
``` | 14,508 |
46,917,831 | I am working on a simple Docker image that has a large number of environment variables. Are you able to import an environment variable file like with docker-compose? I cannot find anything about this in the docker file documentation.
**Dockerfile**
```
FROM python:3.6
ENV ENV1 9.3
ENV ENV2 9.3.4
...
ADD . /
RUN pi... | 2017/10/24 | [
"https://Stackoverflow.com/questions/46917831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3361028/"
] | Yes, there are a couple of ways you can do this.
Docker Compose
--------------
In Docker Compose, you can supply environment variables in the file itself, or point to an external env file:
```
# docker-compose.yml
version: '2'
services:
service-name:
image: service-app
environment:
- GREETING=hello
... | If you need environment variables runtime, it's easiest to create a launcher script that sets up the environment with multiple `export` statements and then launches your process.
If you need them build time, have a look at the `ARG` and `ENV` statements. You'll need one per variable. | 14,513 |
59,868,524 | My goal is to get a list of the names of all the new items that have been posted on <https://www.prusaprinters.org/prints> during the full 24 hours of a given day.
Through a bit of reading I've learned that I should be using Selenium because the site I'm scraping is dynamic (loads more objects as the user scrolls).
T... | 2020/01/22 | [
"https://Stackoverflow.com/questions/59868524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452116/"
] | To get text wait for visibility of the elements. Css selector for titles is `#printListOuter h3`:
```
titles = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, '#printListOuter h3')))
for title in titles:
print(title.text)
```
Shorter version:
```
wait = WebDriverWait(dri... | This is xpath of the name of the items:
```
.//div[@class='print-list-item']/div/a/h3/span
``` | 14,518 |
14,549,433 | Here is what my data frame looks like;
```
Zaman Operasyon Paket
1 2013-01-18 21:39:00 installed linux-api-headers
2 2013-01-18 21:39:00 installed tzdata
3 2013-01-18 21:39:00 installed glibc
4 2013-01-18 21:39:00 installed ncurses
5 2013-01-18 21:39:00 inst... | 2013/01/27 | [
"https://Stackoverflow.com/questions/14549433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/886669/"
] | You must express that you want *days*; this should do the trick:
```
table(factor(format(data$Zaman,"%D")))
``` | You get error with count because there isn't a function named `count`.
But you can use `count` of `plyr` package :
```
count(dat, vars = 'Zaman')
Zaman freq
1 2013-01-18 20:39:00 66
2 2013-01-18 20:40:00 16
3 2013-01-18 20:41:00 47
4 2013-01-18 20:52:00 1
5 2013-01-18 23:47:00 1
6 ... | 14,519 |
22,325,245 | I have an example script where I am searching for `[Data]` in a line. The odd thing is that it always matches when reading the file with `csv.reader`. See code below. Any ideas?
```
#!/opt/Python-2.7.3/bin/python
import csv
import re
import os
content = '''# foo
[Header],,
foo bar,blah,
[Settings]
Yadda,yadda
[Data... | 2014/03/11 | [
"https://Stackoverflow.com/questions/22325245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719016/"
] | If you want to find a line with string `[Data]` (with brackets), you should add `\` before brackets in pattern:
```
#if re.search("[Data]", line):
if re.search("\[Data\]", line):
```
Pattern `[Data]` without backslashes means that you want search any character from set (`D` or `a` or `t`) in line. | Edit: The error in the original code is how you set `founc_csv` the first time it finds data, and then never resets it to 0. That or you can simply remove the need for it entirely:
```
mycsv = []
for l in reader:
line = str(l)
if line == '[]':
continue
elif "[Data]" in line:
print line
... | 14,526 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.