qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
50,388,396 | I try to compile this code but I get this errror :
```
NameError: name 'dtype' is not defined
```
Here is the python code :
```
# -*- coding: utf-8 -*-
from __future__ import division
import pandas as pd
import numpy as np
import re
import missingno as msno
from functools import partial
import seaborn as sns
sns.... | 2018/05/17 | [
"https://Stackoverflow.com/questions/50388396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9360453/"
] | As written by Amr Keleg,
>
> If `data` is a pandas dataframe then you can check the type of a
> column as follows:
> `df['colname'].dtype` or `df.colname.dtype`
>
>
>
In that case you need e.g.
```
df['colname'].dtype == np.dtype('datetime64')
```
or
```
df.colname.dtype == np.dtype('datetime64')
``` | I have just realized that I could have used:
```
from pandas.api.types import is_string_dtype, is_numeric_dtype
``` |
52,607,623 | I have 3 variables in python (age, gender, race) and I want to create a unique categorical binary code out of them. Firstly, the age is an integer and I want to threshold it for each decade 10-20, 20-30, 30-40 etc., gender 2 values and the race contains 4 values. How can I return a complete categorical code out of the ... | 2018/10/02 | [
"https://Stackoverflow.com/questions/52607623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1194864/"
] | Here is a method returning a 7 bit code with first 4 bits for age bracket, next 2 for race, and 1 for gender.
4 bits for age imposes the constraint that there can be a total of 16 age brackets only, which is reasonable as it covers the age range 0-159.
The 4 bit age code is simply the 4 bit representation of the inte... | You can have a `n+1+4` dimensional vector encoding. Given binary code you require, this would be one way of doing it.
You first `n` entries would encode decade. `1` if it belongs to that decade, `0` else. Next `(n+1)th` entry could be `1` if male and `0` if female. Similarly for race, `1` if it belongs to that categor... |
52,607,623 | I have 3 variables in python (age, gender, race) and I want to create a unique categorical binary code out of them. Firstly, the age is an integer and I want to threshold it for each decade 10-20, 20-30, 30-40 etc., gender 2 values and the race contains 4 values. How can I return a complete categorical code out of the ... | 2018/10/02 | [
"https://Stackoverflow.com/questions/52607623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1194864/"
] | Here is a method returning a 7 bit code with first 4 bits for age bracket, next 2 for race, and 1 for gender.
4 bits for age imposes the constraint that there can be a total of 16 age brackets only, which is reasonable as it covers the age range 0-159.
The 4 bit age code is simply the 4 bit representation of the inte... | My answer here:
Being age **a**, gender **g** and race **r**,
```
code = np.array([int(i) for i in "{0:04b}{1:01b}{2:02b}".format(a//10,g,r)])
```
for age=58, gender=1 and race=3, output will be:
```
array([0, 1, 0, 1, 1, 1, 1])
``` |
30,296,531 | So here is my first test for S3 buckets using boto:
```
import boto
user_name, access_key, secret_key = "testing-user", "xxxxxxxxxxxxx", "xxxxxxxx/xxxxxxxxxxxx/xxxxxxxxxx(xxxxx)"
conn = boto.connect_s3(access_key, secret_key)
buckets = conn.get_all_buckets()
```
I get the following error:
```
Traceback (most recen... | 2015/05/18 | [
"https://Stackoverflow.com/questions/30296531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221660/"
] | Had the same issue. In my case, my generated security key had a special character '+' in between. So I deleted my key and regenerated a new key and it worked with the new key with no '+'.
[Source](https://stackoverflow.com/a/12262106) | Today, I saw an error response with `SignatureDoesNotMatch` while playing around an S3 API locally and replacing **localhost** with **127.0.0.1** fixed the problem in my case. |
43,837,305 | I have a GitHub repository containing a AWS Lambda function. I am currently using Travis CI to build, test and then deploy this function to Lambda if all the tests succeed using
```
deploy:
provider: lambda
(other settings here)
```
My function has the following dependencies specified in its `requirements.tx... | 2017/05/07 | [
"https://Stackoverflow.com/questions/43837305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3474089/"
] | After quite a bit of tinkering I think I've found something that works. I thought I'd post it here in case others have the same problem.
I decided to use [Wercker](http://www.wercker.com/) as they have quite a generous free tier and allow you to customize the docker image for your builds.
Turns out there is a docker ... | Although I appreciate you may not want to add further complications to your project, you could potentially use a Python-focused Lambda management tool for setting up your builds and deployments, say something like [Gordon](https://github.com/jorgebastida/gordon). You could also just use this tool to do your deployment ... |
53,268,375 | I have a use case which often requires to copy a blob (file) from one Azure region to another. The file size spans from 25 to 45GB. Needless to say, this sometimes goes very slowly, with inconsistent performance. This might take up to two hours, sometimes more. Distance plays a role, but it differs. Even within the sam... | 2018/11/12 | [
"https://Stackoverflow.com/questions/53268375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/794967/"
] | Data model is wrong. Should be something like this:
```
SQL> create table customer
2 (customer_id number primary key,
3 first_name varchar2(20),
4 last_name varchar2(20),
5 phone varchar2(20));
Table created.
SQL> create table items
2 (item_id number primary key,
3 item... | There is no relation between the two tables which you wish to combine data from. Kindly create a foreign key relation between the two tables which would help you get a common value based on which you could extract data.
For e.g. - The column Customer\_id from customers table could be the foreign key in table orders wh... |
53,268,375 | I have a use case which often requires to copy a blob (file) from one Azure region to another. The file size spans from 25 to 45GB. Needless to say, this sometimes goes very slowly, with inconsistent performance. This might take up to two hours, sometimes more. Distance plays a role, but it differs. Even within the sam... | 2018/11/12 | [
"https://Stackoverflow.com/questions/53268375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/794967/"
] | Data model is wrong. Should be something like this:
```
SQL> create table customer
2 (customer_id number primary key,
3 first_name varchar2(20),
4 last_name varchar2(20),
5 phone varchar2(20));
Table created.
SQL> create table items
2 (item_id number primary key,
3 item... | In your last query you have shown that your tables are linked ( customer.customer\_id = orders.order\_id ), but in the tables you have created, there is no link between them. I think this should work:
Step 1: Create a Customer table as follow:
```
Create table customer
(customer_id id primary key,
first_nam... |
53,268,375 | I have a use case which often requires to copy a blob (file) from one Azure region to another. The file size spans from 25 to 45GB. Needless to say, this sometimes goes very slowly, with inconsistent performance. This might take up to two hours, sometimes more. Distance plays a role, but it differs. Even within the sam... | 2018/11/12 | [
"https://Stackoverflow.com/questions/53268375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/794967/"
] | There is no relation between the two tables which you wish to combine data from. Kindly create a foreign key relation between the two tables which would help you get a common value based on which you could extract data.
For e.g. - The column Customer\_id from customers table could be the foreign key in table orders wh... | In your last query you have shown that your tables are linked ( customer.customer\_id = orders.order\_id ), but in the tables you have created, there is no link between them. I think this should work:
Step 1: Create a Customer table as follow:
```
Create table customer
(customer_id id primary key,
first_nam... |
55,574,215 | I'm logging some Unicode characters to a file using "logging" in Python 3. The code works in the terminal, but fails with a UnicodeEncodeError in PyCharm.
I load my logging configuration using `logging.config.fileConfig`. In the configuration, I specify a file handler with `encoding = utf-8`. Logging to console works ... | 2019/04/08 | [
"https://Stackoverflow.com/questions/55574215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1654411/"
] | on different os need different solutions:
on Windows:
1. download the libfile, <http://www.rarlab.com/rar/UnRARDLL.exe>, install it;
2. you'd better choose the default path, C:\Program Files (x86)\UnrarDLL\
3. the most important is add the environment path, the varname enter UNRAR\_LIB\_PATH, pay attention, it must be... | Additionally, after you do the things as mentioned by Tom.chen.kang and balandongiv, if you're using a 32bit DLL with 64bit Python, or vice-versa, then you'll probably get an error like this when you try to import unrar:-
>
> OSError: [WinError 193] %1 is not a valid Win32 application
>
>
>
In that case do this:
... |
55,574,215 | I'm logging some Unicode characters to a file using "logging" in Python 3. The code works in the terminal, but fails with a UnicodeEncodeError in PyCharm.
I load my logging configuration using `logging.config.fileConfig`. In the configuration, I specify a file handler with `encoding = utf-8`. Logging to console works ... | 2019/04/08 | [
"https://Stackoverflow.com/questions/55574215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1654411/"
] | In addition to @tom answer for `Windows 10` environment, the following steps should help:
1. Download the libfile via the [link](http://www.rarlab.com/rar/UnRARDLL.exe) and install it.
2. For easy replication the following steps, choose the default path, C:\Program Files (x86)\UnrarDLL\
3. Go to Environment Variables ... | Additionally, after you do the things as mentioned by Tom.chen.kang and balandongiv, if you're using a 32bit DLL with 64bit Python, or vice-versa, then you'll probably get an error like this when you try to import unrar:-
>
> OSError: [WinError 193] %1 is not a valid Win32 application
>
>
>
In that case do this:
... |
58,799,259 | I am using Windows 10, PostgreSQL 12, Python 3.7.5 . I create username `odoo`, password `odoo`, create database `mydb`.
Source code is <https://github.com/odoo/odoo/tree/aa0554d224337e1d966479a351a3ed059d297765>
I run command
```
python odoo-bin -r odoo -w odoo --addons-path=addons --db-filter=mydb$
```
Error
```... | 2019/11/11 | [
"https://Stackoverflow.com/questions/58799259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3728901/"
] | I think you need to configure the DB to trust your IP address:
make the following chages in `pg_hba.conf`:
```
# IPv4 local connections:
host all all 127.0.0.1/32 trust
host all all MY_IP/24 trust
```
see also [this](https://www.odoo.com/documentation/13.0/setup/install.html#id3) | odoo 13 a default user name odoo that user with postgress it use a recently db created.
you can pass a database configuration on your config file
odoo 13 /debian/odoo.conf
```
[options]
; This is the password that allows database operations:
; admin_passwd = admin
db_host = False
db_port = False
db_user = odoo
db_p... |
58,799,259 | I am using Windows 10, PostgreSQL 12, Python 3.7.5 . I create username `odoo`, password `odoo`, create database `mydb`.
Source code is <https://github.com/odoo/odoo/tree/aa0554d224337e1d966479a351a3ed059d297765>
I run command
```
python odoo-bin -r odoo -w odoo --addons-path=addons --db-filter=mydb$
```
Error
```... | 2019/11/11 | [
"https://Stackoverflow.com/questions/58799259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3728901/"
] | To [create a PostgreSQL user](https://www.odoo.com/documentation/13.0/setup/install.html#postgresql), follow these steps:
1. Add PostgreSQL’s `bin` directory (by default: `C:\Program Files\PostgreSQL\<version>\bin`) to
your `PATH`.
2. Create a postgres user with a password using the pg admin gui:
* Open **pgAdminIII... | odoo 13 a default user name odoo that user with postgress it use a recently db created.
you can pass a database configuration on your config file
odoo 13 /debian/odoo.conf
```
[options]
; This is the password that allows database operations:
; admin_passwd = admin
db_host = False
db_port = False
db_user = odoo
db_p... |
54,525,141 | I have a python environment (it could be conda, virtualenv, venv or global python) - I have a python script - hello.py - that I want to execute within that environment.
If I get the path to the python binary within the environment, for example, in windows with a conda environment called myenv, `/path/to/myenv/Scripts... | 2019/02/04 | [
"https://Stackoverflow.com/questions/54525141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/456735/"
] | Yes, you're right! Furthermore you can evaluate the used executable by using the following snippet:
```
import sys
print(sys.executable)
```
Then you will see the absolute path, e.g. `/opt/miniconda/envs/epm/bin/python`.
If you're using a Unix system, you can run:
```
$ echo "import sys; print(sys.version); print... | I suspect not. There are a few environment variables (e.g. `PATH`) which are changed when you activate a virtualenv. You can open up `myenv/bin/activate` in a text editor to see what it does.
Is there a particular reason you want to call the executable directly, rather than use the environment as designed? (e.g. `. ./... |
36,911,060 | I have a JSON file containing various objects each containing elements. With my python script, I only keep the objects I want, and then put the elements I want in a list. But the element has a prefix, which I'd like to suppress form the list.
The post-script JSON looks like that:
```
{
"ip_prefix": "184.72.128... | 2016/04/28 | [
"https://Stackoverflow.com/questions/36911060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532788/"
] | You can also add this variable by using a preprocess hook. The following code will add the `is_front` variable so it can be used in the `html.html.twig` template:
```
// Adds the is_front variable to html.html.twig template.
function mytheme_preprocess_html(&$variables) {
$variables['is_front'] = \Drupal::service('p... | If you want to show a node within the front page and it should look just like the actual node page, you can create a new display for the node, like "On Frontpage". For that display you create a new node template (be careful to use the right naming convention for the twig file, otherwise it won't work). Then you tell th... |
31,573,399 | I have a largish pandas dataframe (1.5gig .csv on disk). I can load it into memory and query it. I want to create a new column that is combined value of two other columns, and I tried this:
```
def combined(row):
row['combined'] = row['col1'].join(str(row['col2']))
return row
df = df.apply(combined, axis=1)
```
... | 2015/07/22 | [
"https://Stackoverflow.com/questions/31573399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3137396/"
] | I would try using list comprehension + [`itertools`](https://docs.python.org/2/library/itertools.html):
```
df = pd.DataFrame({
'a': ['ab'] * 200,
'b': ['ffff'] * 200
})
import itertools
[a.join(b) for (a, b) in itertools.izip(df.a, df.b)]
```
It might be "unpandas", but pandas doesn't seem to have a `.str... | One nice way to create a new column in [`pandas`](http://pandas.pydata.org) or [`dask.dataframe`](http://dask.pydata.org/en/latest/dataframe.html) is with the [`.assign`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html) method.
```
In [1]: import pandas as pd
In [2]: df = pd.DataFra... |
48,125,575 | I am trying to read the following code for back propagation in python
```
probs = exp_scores /np.sum(exp_scores, axis=1, keepdims=True)
#Backpropagation
delta3 = probs
delta3[range(num_examples), y] -= 1
dW2 = (a1.T).dot(delta3)
....
```
but I cannot understand the following line of the code:
```
delta3[range(num... | 2018/01/06 | [
"https://Stackoverflow.com/questions/48125575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7962244/"
] | There are two things here. First it is using numpy slicing to select only a fraction of `delta3`. Secondly it is removing 1 to every element of this fraction of the matrix.
More precisely, `delta3[range(num_example), y]` is selecting lines of the matrix `delta3` ranging from 0 to `num_examples` but only selecting colu... | If you're interested, *why* it's computed this way, it's the backpropagation through cross-entropy loss:
* `probs` is the vector of class probabilities (computed in a forward pass via softmax).
* `delta3` is the error signal from the loss function.
* `y` holds the ground truth classes for the mini-batch.
Everything e... |
49,958,177 | I am a beginner to python and am working on python 3.6.5 , I was trying to create a Chatbot but I don't understand how to use a comma to separate the two strings(red and Red) because the shell says that it is an invalid syntax(the comma is highlighted but nothing else). What have I done wrong?:
```
colour=input("What ... | 2018/04/21 | [
"https://Stackoverflow.com/questions/49958177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9679321/"
] | Use `in`
```
colour= input("What is your favourite colour? ")
if colour in ("red", "Red"):
print("Red is my favourite colour as well")
``` | You could you use if colour in ['red', 'Red', 'RED', 'ReD'] as mentionned earlier, or you could just sanitize the input:
```
colour= input("What is your favourite colour? ")
if colour.lower() == "red":
print("Red is my favourite colour as well")
``` |
20,322,969 | I am not sure if there is a solution for this on stack overflow; so apologies if this is a duplicate.
There are number of ways of converting the string:
```
s = '[1, 2, 3]'
```
to a list
```
t = [1, 2, 3]
```
but I am looking for the most straightforward pythonic way of doing this. Also, performance matters. | 2013/12/02 | [
"https://Stackoverflow.com/questions/20322969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778980/"
] | One should use [ast.literal\_eval](http://docs.python.org/2/library/ast.html#ast.literal_eval):
```
>>> import ast
>>> ast.literal_eval('[1,2,3]')
[1, 2, 3]
``` | Why never use json library.
```
import json
# convert str to list
t = json.loads(s)
# back to string
s2 = json.dumps(t)
``` |
49,949,398 | I am facing an issue while importing java code which uses some external jar say selenium\_standalone\_server jar.
I tried with normal code with no jars used in java, in this case i am able to import and run the code, but when i uses some jars in java code and then try to import that class to jython it gives error.
He... | 2018/04/20 | [
"https://Stackoverflow.com/questions/49949398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814582/"
] | **1)** We group by Name (assuming `rollapply` should be done separately for each `Name`) and then use `width = list(-seq(4))` with `rollapply` which uses offsets -1, -2, -3, -4 for each application of `mean`. (Offset 0 would be the current point but we want the 4 prior here.)
Not clear what you are referring to regard... | An option is to use `zoo::rollapply` along with `dplyr::lag` as:
```
library(dplyr)
library(lubridate)
library(zoo)
df %>% mutate(DATE = mdy(DATE)) %>% #Convert to Date
arrange(Name, DATE) %>% #Order on Name and DATE
mutate(Avg = rollapply(Values, 4, mean, fill= NA, align = "right")) %>%
mutate(Av... |
53,846,322 | I am exporting LOG\_INTERVAL value as 5. How can I add this env value in python as `time.sleep`?
```
import os
import time
print("Goodbye, World!")
time.sleep(os.environ.get('LOG_INTERVAL'))
```
```
error:- Goodbye, World!
Traceback (most recent call last):
File "test.py", line 4, in
time.sleep(os.environ.get... | 2018/12/19 | [
"https://Stackoverflow.com/questions/53846322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10809642/"
] | The value you get from the environment is a string. You have to convert it to a number in order for it to be an acceptable value for `time.sleep()`
```
time.sleep(float(os.environ.get('LOG_INTERVAL'))
``` | I think `LOG_INTERVAL` will be returned as a string.
Check it's type with `type(os.environ.get('LOG_INTERVAL'))`
If it is an int or a string containing nothing but numbers or fullstops `time.sleep(float(os.environ.get('LOG_INTERVAL')))` should convert it to a float and do the trick. |
53,846,322 | I am exporting LOG\_INTERVAL value as 5. How can I add this env value in python as `time.sleep`?
```
import os
import time
print("Goodbye, World!")
time.sleep(os.environ.get('LOG_INTERVAL'))
```
```
error:- Goodbye, World!
Traceback (most recent call last):
File "test.py", line 4, in
time.sleep(os.environ.get... | 2018/12/19 | [
"https://Stackoverflow.com/questions/53846322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10809642/"
] | ```
time.sleep(float(os.environ.get('LOG_INTERVAL', 0))
```
I added the default `0` to @tripleee 's reply, so if the variable is not defined, your code doesn't crash. | I think `LOG_INTERVAL` will be returned as a string.
Check it's type with `type(os.environ.get('LOG_INTERVAL'))`
If it is an int or a string containing nothing but numbers or fullstops `time.sleep(float(os.environ.get('LOG_INTERVAL')))` should convert it to a float and do the trick. |
53,846,322 | I am exporting LOG\_INTERVAL value as 5. How can I add this env value in python as `time.sleep`?
```
import os
import time
print("Goodbye, World!")
time.sleep(os.environ.get('LOG_INTERVAL'))
```
```
error:- Goodbye, World!
Traceback (most recent call last):
File "test.py", line 4, in
time.sleep(os.environ.get... | 2018/12/19 | [
"https://Stackoverflow.com/questions/53846322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10809642/"
] | The value you get from the environment is a string. You have to convert it to a number in order for it to be an acceptable value for `time.sleep()`
```
time.sleep(float(os.environ.get('LOG_INTERVAL'))
``` | ```
time.sleep(float(os.environ.get('LOG_INTERVAL', 0))
```
I added the default `0` to @tripleee 's reply, so if the variable is not defined, your code doesn't crash. |
5,559,810 | **Question**
It seems that PyWin32 is comfortable with giving null-terminated unicode strings as return values. I would like to deal with these strings the 'right' way.
Let's say I'm getting a string like: `u'C:\\Users\\Guest\\MyFile.asy\x00\x00sy'`. This appears to be a C-style null-terminated string hanging out in ... | 2011/04/05 | [
"https://Stackoverflow.com/questions/5559810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182642/"
] | I'd say it's a bug. The right way to deal with it would probably be fixing pywin32, but in case you aren't feeling adventurous enough, just trim it.
You can get everything before the first `'\x00'` with `filename.split('\x00', 1)[0]`. | This doesn't happen on the version of PyWin32/Windows/Python I tested; I don't get any nulls in the returned string even if it's very short. You might investigate if a newer version of one of the above fixes the bug. |
5,559,810 | **Question**
It seems that PyWin32 is comfortable with giving null-terminated unicode strings as return values. I would like to deal with these strings the 'right' way.
Let's say I'm getting a string like: `u'C:\\Users\\Guest\\MyFile.asy\x00\x00sy'`. This appears to be a C-style null-terminated string hanging out in ... | 2011/04/05 | [
"https://Stackoverflow.com/questions/5559810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182642/"
] | I'd say it's a bug. The right way to deal with it would probably be fixing pywin32, but in case you aren't feeling adventurous enough, just trim it.
You can get everything before the first `'\x00'` with `filename.split('\x00', 1)[0]`. | ISTR that I had this issue some years ago, then I discovered that such Win32 filename-dialog-related functions return a sequence of `'filename1\0filename2\0...filenameN\0\0'`, while including possible garbage characters depending on the buffer that Windows allocated.
Now, you might prefer a list instead of the raw ret... |
5,559,810 | **Question**
It seems that PyWin32 is comfortable with giving null-terminated unicode strings as return values. I would like to deal with these strings the 'right' way.
Let's say I'm getting a string like: `u'C:\\Users\\Guest\\MyFile.asy\x00\x00sy'`. This appears to be a C-style null-terminated string hanging out in ... | 2011/04/05 | [
"https://Stackoverflow.com/questions/5559810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182642/"
] | This doesn't happen on the version of PyWin32/Windows/Python I tested; I don't get any nulls in the returned string even if it's very short. You might investigate if a newer version of one of the above fixes the bug. | ISTR that I had this issue some years ago, then I discovered that such Win32 filename-dialog-related functions return a sequence of `'filename1\0filename2\0...filenameN\0\0'`, while including possible garbage characters depending on the buffer that Windows allocated.
Now, you might prefer a list instead of the raw ret... |
49,737,459 | Forgive me the possibly trivial question, but: *How do I run the script published by pybuilder?*
---
I'm trying to follow the official [Pybuilder Tutorial](http://pybuilder.github.io/documentation/tutorial.html#.WsqupUuYNhE).
I've walked through the steps and successfully generated a project that
* runs unit tests... | 2018/04/09 | [
"https://Stackoverflow.com/questions/49737459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2707792/"
] | Apparently the following workflow:
* pyb publish
* pip install .tar.gz
* runMyScript.py
* uninstall
is exactly what is proposed by the creator of PyBuilder [in this talk](http://www.youtube.com/watch?v=iQU18hAjux4&t=14m42s).
**Note that the linked video is from 2014. If someone can propose a more streamlined recentl... | Create task in build.py
```
@task
def run(project):
path.append("src/main/python")
from test_pack import test_app
test_app.main()
```
Try:
`pyb run` |
16,650,680 | The following was ported from the pseudo-code from the Wikipedia article on [Newton's method](http://en.wikipedia.org/wiki/Newton%27s_method):
```
#! /usr/bin/env python3
# https://en.wikipedia.org/wiki/Newton's_method
import sys
x0 = 1
f = lambda x: x ** 2 - 2
fprime = lambda x: 2 * x
tolerance = 1e-10
epsilon = sys... | 2013/05/20 | [
"https://Stackoverflow.com/questions/16650680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216356/"
] | A common way of approximating the derivative of `f` at `x` is using a finite difference:
```
f'(x) = (f(x+h) - f(x))/h Forward difference
f'(x) = (f(x+h) - f(x-h))/2h Symmetric
```
The best choice of `h` depends on `x` and `f`: mathematically the difference approaches the derivative ... | You can approximate `fprime` any number of ways. One of the simplest would be something like:
```
lambda fprime x,dx=0.1: (f(x+dx) - f(x-dx))/(2*dx)
```
the idea here is to sample `f` around the point `x`. The sampling region (determined by `dx`) should be small enough that the variation in `f` over that region is a... |
16,650,680 | The following was ported from the pseudo-code from the Wikipedia article on [Newton's method](http://en.wikipedia.org/wiki/Newton%27s_method):
```
#! /usr/bin/env python3
# https://en.wikipedia.org/wiki/Newton's_method
import sys
x0 = 1
f = lambda x: x ** 2 - 2
fprime = lambda x: 2 * x
tolerance = 1e-10
epsilon = sys... | 2013/05/20 | [
"https://Stackoverflow.com/questions/16650680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216356/"
] | A common way of approximating the derivative of `f` at `x` is using a finite difference:
```
f'(x) = (f(x+h) - f(x))/h Forward difference
f'(x) = (f(x+h) - f(x-h))/2h Symmetric
```
The best choice of `h` depends on `x` and `f`: mathematically the difference approaches the derivative ... | **Answer**
Define the functions `formula` and `derivative` as the following directly after your `import`.
```
def formula(*array):
calculate = lambda x: sum(c * x ** p for p, c in enumerate(array))
calculate.coefficients = array
return calculate
def derivative(function):
return (p * c for p, c in enu... |
21,397,757 | Personally I think it's better to distribute .py files as these will then be compiled by the end-user's own python, which may be more patched.
What are the pros and cons of distributing .pyc files versus .py files for a commercial, closed-source python module?
In other words, are there any compelling reasons to distr... | 2014/01/28 | [
"https://Stackoverflow.com/questions/21397757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/906984/"
] | Close the unused file descriptors it will work fine
In the inner most child
```
close(f1[1]);
```
In the parent process
```
close(f1[0]);
```
And also syntax error in the line write is called change it to
```
write(f1[1], M1, sizeof(M1)) < 0)
``` | change your `if` statement to
```
if (write(f1[1], M1, sizeof(M1)) < 0)
```
instead of
```
if(write(f1[1], M1, sizeof(M1) < 0))
``` |
2,177,250 | I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time?
Here's my code:
```
import os
import ... | 2010/02/01 | [
"https://Stackoverflow.com/questions/2177250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183487/"
] | A couple thoughts. First, you might use the [`glob`](http://docs.python.org/library/glob.html) module to get smaller groups of files. Second, sorting by line count is going to be very time consuming, as you have to open every file and count lines. If you can partition by byte count, you can avoid opening the files by u... | ```
import os,shutil
os.chdir("/mydir/")
numlines=20
destination = os.path.join("/destination","dir1")
for file in os.listdir("."):
if os.path.isfile(file):
flag=0
for n,line in enumerate(open(file)):
if n > numlines:
flag=1
break
if flag:
... |
2,177,250 | I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time?
Here's my code:
```
import os
import ... | 2010/02/01 | [
"https://Stackoverflow.com/questions/2177250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183487/"
] | you might try using [`glob.iglob`](http://docs.python.org/library/glob.html) that returns an iterator:
```
topdir = os.path.join('/somedir', 'labels', '*')
for filename in glob.iglob(topdir):
if filelen(filename) > 15:
#do stuff
```
Also, please don't use `dir` for a variable name: you're shadowing th... | ```
import os,shutil
os.chdir("/mydir/")
numlines=20
destination = os.path.join("/destination","dir1")
for file in os.listdir("."):
if os.path.isfile(file):
flag=0
for n,line in enumerate(open(file)):
if n > numlines:
flag=1
break
if flag:
... |
2,177,250 | I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time?
Here's my code:
```
import os
import ... | 2010/02/01 | [
"https://Stackoverflow.com/questions/2177250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183487/"
] | you might try using [`glob.iglob`](http://docs.python.org/library/glob.html) that returns an iterator:
```
topdir = os.path.join('/somedir', 'labels', '*')
for filename in glob.iglob(topdir):
if filelen(filename) > 15:
#do stuff
```
Also, please don't use `dir` for a variable name: you're shadowing th... | A couple thoughts. First, you might use the [`glob`](http://docs.python.org/library/glob.html) module to get smaller groups of files. Second, sorting by line count is going to be very time consuming, as you have to open every file and count lines. If you can partition by byte count, you can avoid opening the files by u... |
2,177,250 | I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time?
Here's my code:
```
import os
import ... | 2010/02/01 | [
"https://Stackoverflow.com/questions/2177250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183487/"
] | A couple thoughts. First, you might use the [`glob`](http://docs.python.org/library/glob.html) module to get smaller groups of files. Second, sorting by line count is going to be very time consuming, as you have to open every file and count lines. If you can partition by byte count, you can avoid opening the files by u... | how about using a shell script? you could pick one file at a time:
```
for f in `ls`;
loop
if `wc -l f`>20; then
mv f newfolder
fi
end loop
```
ppl please correct if i am wrong in any way |
2,177,250 | I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time?
Here's my code:
```
import os
import ... | 2010/02/01 | [
"https://Stackoverflow.com/questions/2177250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183487/"
] | A couple thoughts. First, you might use the [`glob`](http://docs.python.org/library/glob.html) module to get smaller groups of files. Second, sorting by line count is going to be very time consuming, as you have to open every file and count lines. If you can partition by byte count, you can avoid opening the files by u... | The currently accepted answer just plain doesn't work. This function:
```
def many_line(fname, many=15):
for i, line in enumerate(line):
if i > many:
return True
return False
```
has two problems: Firstly, the `fname` arg is not used and the file is not opened. Secondly, the call to `enum... |
2,177,250 | I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time?
Here's my code:
```
import os
import ... | 2010/02/01 | [
"https://Stackoverflow.com/questions/2177250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183487/"
] | A couple thoughts. First, you might use the [`glob`](http://docs.python.org/library/glob.html) module to get smaller groups of files. Second, sorting by line count is going to be very time consuming, as you have to open every file and count lines. If you can partition by byte count, you can avoid opening the files by u... | You can use os.scandir which is a generator, and therefore does not read all file names at once (comes with python 3.5, otherwise or just simply: pip install scandir).
Example:
```
import os
for file in os.scandir(path):
do_something_with_file(path+file.name)
```
scandir documentation: <https://pyp... |
2,177,250 | I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time?
Here's my code:
```
import os
import ... | 2010/02/01 | [
"https://Stackoverflow.com/questions/2177250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183487/"
] | you might try using [`glob.iglob`](http://docs.python.org/library/glob.html) that returns an iterator:
```
topdir = os.path.join('/somedir', 'labels', '*')
for filename in glob.iglob(topdir):
if filelen(filename) > 15:
#do stuff
```
Also, please don't use `dir` for a variable name: you're shadowing th... | how about using a shell script? you could pick one file at a time:
```
for f in `ls`;
loop
if `wc -l f`>20; then
mv f newfolder
fi
end loop
```
ppl please correct if i am wrong in any way |
2,177,250 | I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time?
Here's my code:
```
import os
import ... | 2010/02/01 | [
"https://Stackoverflow.com/questions/2177250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183487/"
] | you might try using [`glob.iglob`](http://docs.python.org/library/glob.html) that returns an iterator:
```
topdir = os.path.join('/somedir', 'labels', '*')
for filename in glob.iglob(topdir):
if filelen(filename) > 15:
#do stuff
```
Also, please don't use `dir` for a variable name: you're shadowing th... | The currently accepted answer just plain doesn't work. This function:
```
def many_line(fname, many=15):
for i, line in enumerate(line):
if i > many:
return True
return False
```
has two problems: Firstly, the `fname` arg is not used and the file is not opened. Secondly, the call to `enum... |
2,177,250 | I have a folder with 100k text files. I want to put files with over 20 lines in another folder. How do I do this in python? I used os.listdir, but of course, there isn't enough memory for even loading the filenames into memory. Is there a way to get maybe 100 filenames at a time?
Here's my code:
```
import os
import ... | 2010/02/01 | [
"https://Stackoverflow.com/questions/2177250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183487/"
] | you might try using [`glob.iglob`](http://docs.python.org/library/glob.html) that returns an iterator:
```
topdir = os.path.join('/somedir', 'labels', '*')
for filename in glob.iglob(topdir):
if filelen(filename) > 15:
#do stuff
```
Also, please don't use `dir` for a variable name: you're shadowing th... | You can use os.scandir which is a generator, and therefore does not read all file names at once (comes with python 3.5, otherwise or just simply: pip install scandir).
Example:
```
import os
for file in os.scandir(path):
do_something_with_file(path+file.name)
```
scandir documentation: <https://pyp... |
50,916,340 | I'm looking for some general advice on how to either re-write application code to be non-naive, or whether to abandon neo4j for another data storage model. This is not *only* "subjective", as it relates significantly to specific, correct usage of the neo4j driver in Python and why it performs the way it does with my co... | 2018/06/18 | [
"https://Stackoverflow.com/questions/50916340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1507854/"
] | You could use a capturing group or to not have `DataHelper.ExecuteProc` in matching result put it in lookbehind:
```
(?<=DataHelper\.ExecuteProc\(")[^\\"]*(?:\\.[^\\"]*)*
```
See live [demo here](https://regex101.com/r/i3AgFx/1)
Breakdown:
* `(?<=` Start of positive lookbehind
+ `DataHelper\.ExecuteProc\("` Match... | You can do it like this:
```
var pattern = "\bDataHelper\..+?\(\"(?<procedure>[^\"]*?)\"";
var result = Regex.Match(input, pattern).Cast<Match>().Select(x=> x.Groups["procedure"].Value).ToList();
``` |
41,053,784 | I am new to python and trying to implement graph data structure in Python.
I have written this code, but i am not getting the desired result i want.
Code:
```
class NODE:
def __init__(self):
self.distance=0
self.colournode="White"
adjlist={}
def addno(A,B):
global adjlist
adjlist[A]=B
S... | 2016/12/09 | [
"https://Stackoverflow.com/questions/41053784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4825150/"
] | You node needs to have a label to print. You can't use just the variable name. The node has no way knowing name of your variable.
```
class NODE:
def __init__(self, name):
self.name=name
def __repr__(self):
return self.name
adjlist={}
def addno(A,B):
global adjlist
adjlist[A]=B
S=NODE... | You get that output because `Node` is an instance of a class ( you get that hint form the output of your program itself see this: `<main.NODE instance at 0x00000000029E6888>` ).
i think you are trying to implement `adjacency list` for some graph algorithm. in those cases you will mostly need the `color` and ``distance... |
64,024,941 | I am doing object detection using TensorFlow Object Detection API in Google colab. This is my directory structure.
```
object_detection/
training/
exported_model/
pipeline.config
model_main_tf2.py
exporter_main_v2.py
```
I run bellow for training.
```
!python model_main_tf2.py --model_dir=training --pipel... | 2020/09/23 | [
"https://Stackoverflow.com/questions/64024941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7907965/"
] | I found that while I run training even though it didn't produce any error It also not successful. Because It didn't generate files which should be generated after successful training like checkpoints. The `training/` directory was blank.
[this](https://github.com/tensorflow/models/blob/master/research/object_detection... | i follow the [struction](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/running_on_mobile_tf2.md) using export\_tflite\_graph\_tf2.py |
45,934,942 | I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:
```
from Tkinter import *
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0,... | 2017/08/29 | [
"https://Stackoverflow.com/questions/45934942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368577/"
] | ```
from Tkinter import *
def printData(firstName, lastName):
print(firstName)
print(lastName)
root.destroy()
def get_input():
firstName = entry1.get()
lastName = entry2.get()
printData(firstName, lastName)
root = Tk()
#Label 1
label1 = Label(root,text = 'First Name')
label1.pack()
label1.co... | You can create a popup information window as follow:
`showinfo("Window", "Hello World!")`
If you want to create a real popup window with input mask, you will need to generate a new TopLevel mask and open a second window.
```
win = tk.Toplevel()
win.wm_title("Window")
label = tk.Label(win, text="User input")
label.... |
45,934,942 | I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:
```
from Tkinter import *
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0,... | 2017/08/29 | [
"https://Stackoverflow.com/questions/45934942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368577/"
] | Your code is working just fine. Nevertheless for those using `python3` module name has changed from `Tkinter` to `tkinter` all in lowercase. Edit the name and you're good to go!
In a nutshell.
python2:
```
from Tkinter import *
```
python3:
```
from tkinter import *
```
Look at the screenshot below
[![Screens... | You can create a popup information window as follow:
`showinfo("Window", "Hello World!")`
If you want to create a real popup window with input mask, you will need to generate a new TopLevel mask and open a second window.
```
win = tk.Toplevel()
win.wm_title("Window")
label = tk.Label(win, text="User input")
label.... |
45,934,942 | I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:
```
from Tkinter import *
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0,... | 2017/08/29 | [
"https://Stackoverflow.com/questions/45934942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368577/"
] | Your code is working just fine. Nevertheless for those using `python3` module name has changed from `Tkinter` to `tkinter` all in lowercase. Edit the name and you're good to go!
In a nutshell.
python2:
```
from Tkinter import *
```
python3:
```
from tkinter import *
```
Look at the screenshot below
[![Screens... | ```
from Tkinter import *
def printData(firstName, lastName):
print(firstName)
print(lastName)
root.destroy()
def get_input():
firstName = entry1.get()
lastName = entry2.get()
printData(firstName, lastName)
root = Tk()
#Label 1
label1 = Label(root,text = 'First Name')
label1.pack()
label1.co... |
45,934,942 | I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:
```
from Tkinter import *
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0,... | 2017/08/29 | [
"https://Stackoverflow.com/questions/45934942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368577/"
] | ```
from Tkinter import *
def printData(firstName, lastName):
print(firstName)
print(lastName)
root.destroy()
def get_input():
firstName = entry1.get()
lastName = entry2.get()
printData(firstName, lastName)
root = Tk()
#Label 1
label1 = Label(root,text = 'First Name')
label1.pack()
label1.co... | check it again the code is executing properly but u can't see that output in jupyter notebook itself u can see it in windows column like beside the chrome icons in toggle bar .I'm also confused initially check it once |
45,934,942 | I have just started using Tkinter and trying to create a simple pop-up box in python. I have copy pasted a simple code from a website:
```
from Tkinter import *
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0,... | 2017/08/29 | [
"https://Stackoverflow.com/questions/45934942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368577/"
] | Your code is working just fine. Nevertheless for those using `python3` module name has changed from `Tkinter` to `tkinter` all in lowercase. Edit the name and you're good to go!
In a nutshell.
python2:
```
from Tkinter import *
```
python3:
```
from tkinter import *
```
Look at the screenshot below
[![Screens... | check it again the code is executing properly but u can't see that output in jupyter notebook itself u can see it in windows column like beside the chrome icons in toggle bar .I'm also confused initially check it once |
60,985,999 | This code works correctly in python 2.X version. I am trying to use the similar code in python version 3.
The problem is that I do not want to use requests module. I need to make it work using "urllib3".
```
import requests
import urllib
event = {'url':'http://google.com', 'email':'[email protected]', 'title':'test'}
u... | 2020/04/02 | [
"https://Stackoverflow.com/questions/60985999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] | You can do something like this:
```
Where x.RoleId == 2 && (loc == null || s.LocationId == loc)
``` | Simply extract your managers and filter them if needed. That way you can as well easily apply more filters and code readability isn't hurt.
```
var managers = CSDB.Managers.AsQueryable();
if(loc > 0)
managers = managers.Where(man => man.LocationId == loc);
var myResult = from allocation in CSDB.Allocations
... |
60,985,999 | This code works correctly in python 2.X version. I am trying to use the similar code in python version 3.
The problem is that I do not want to use requests module. I need to make it work using "urllib3".
```
import requests
import urllib
event = {'url':'http://google.com', 'email':'[email protected]', 'title':'test'}
u... | 2020/04/02 | [
"https://Stackoverflow.com/questions/60985999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] | You can do something like this:
```
Where x.RoleId == 2 && (loc == null || s.LocationId == loc)
``` | Also, you can do smth like this.
```
Where x.RoleId == 2 && (loc?.Equals(s.LocationId) ?? true)
```
If `loc` just `int` I would prefer to use a little bit changed [@Salah Akbari answer](https://stackoverflow.com/a/60986050/2946329):
```
Where x.RoleId == 2 && (loc == 0 || s.LocationId == loc)
``` |
60,985,999 | This code works correctly in python 2.X version. I am trying to use the similar code in python version 3.
The problem is that I do not want to use requests module. I need to make it work using "urllib3".
```
import requests
import urllib
event = {'url':'http://google.com', 'email':'[email protected]', 'title':'test'}
u... | 2020/04/02 | [
"https://Stackoverflow.com/questions/60985999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] | Also, you can do smth like this.
```
Where x.RoleId == 2 && (loc?.Equals(s.LocationId) ?? true)
```
If `loc` just `int` I would prefer to use a little bit changed [@Salah Akbari answer](https://stackoverflow.com/a/60986050/2946329):
```
Where x.RoleId == 2 && (loc == 0 || s.LocationId == loc)
``` | Simply extract your managers and filter them if needed. That way you can as well easily apply more filters and code readability isn't hurt.
```
var managers = CSDB.Managers.AsQueryable();
if(loc > 0)
managers = managers.Where(man => man.LocationId == loc);
var myResult = from allocation in CSDB.Allocations
... |
32,829,504 | in python is a mathematical operator classed as an interger.
for example why isnt this code working
```
import random
score = 0
randomnumberforq = (random.randint(1,10))
randomoperator = (random.randint(0,2))
operator = ['*','+','-']
answer = (randomnumberforq ,operator[randomoperator], randomnumberforq)
useranswer =... | 2015/09/28 | [
"https://Stackoverflow.com/questions/32829504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5080233/"
] | You can't just concatenate an operator to a couple of numbers and expect it to be evaluated. You could use `eval` to evaluate the final string.
```
answer = eval(str(randomnumberforq)
+ operator[randomoperator]
+ str(randomnumberforq))
```
A better way to accomplish what you're attemptin... | You try to convert a string to an integer, but which isn't a number:
```
int(operator[randomoperator])
```
Your operatators in the array "operator" are strings, which don't represent numbers and can't be converted to integer values. On the other hand the input() function desires string as parameter value. So write:
... |
32,829,504 | in python is a mathematical operator classed as an interger.
for example why isnt this code working
```
import random
score = 0
randomnumberforq = (random.randint(1,10))
randomoperator = (random.randint(0,2))
operator = ['*','+','-']
answer = (randomnumberforq ,operator[randomoperator], randomnumberforq)
useranswer =... | 2015/09/28 | [
"https://Stackoverflow.com/questions/32829504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5080233/"
] | That depends on what you're trying to do. You've given us no sample input or output, no comments, and no error message.
It looks like you're trying to write a simple practice engine for arithmetic. If so, then your basic problem is that you don't understand the operations allowed in programming. You can't just throw s... | You try to convert a string to an integer, but which isn't a number:
```
int(operator[randomoperator])
```
Your operatators in the array "operator" are strings, which don't represent numbers and can't be converted to integer values. On the other hand the input() function desires string as parameter value. So write:
... |
32,829,504 | in python is a mathematical operator classed as an interger.
for example why isnt this code working
```
import random
score = 0
randomnumberforq = (random.randint(1,10))
randomoperator = (random.randint(0,2))
operator = ['*','+','-']
answer = (randomnumberforq ,operator[randomoperator], randomnumberforq)
useranswer =... | 2015/09/28 | [
"https://Stackoverflow.com/questions/32829504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5080233/"
] | You can't just concatenate an operator to a couple of numbers and expect it to be evaluated. You could use `eval` to evaluate the final string.
```
answer = eval(str(randomnumberforq)
+ operator[randomoperator]
+ str(randomnumberforq))
```
A better way to accomplish what you're attemptin... | That depends on what you're trying to do. You've given us no sample input or output, no comments, and no error message.
It looks like you're trying to write a simple practice engine for arithmetic. If so, then your basic problem is that you don't understand the operations allowed in programming. You can't just throw s... |
26,453,920 | My problem is that I'm trying to pass a `list` as a variable to a function, and I'd like to mutlti-thread the function processing. I can't seem to use `pool.map` because it only accepts iterables. I can't seem to use `pool.apply` because it seems to block the pool while it works, so I don't really understand how it all... | 2014/10/19 | [
"https://Stackoverflow.com/questions/26453920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3972123/"
] | You can use `pool.map`:
```
p = Pool(4)
p.map(distance, all_x)
```
as per the first example in the [doc](https://docs.python.org/2/library/multiprocessing.html). It will do the iteration for you! | Another way to Approach it is to pack your variables inside a tuble and unpack inside the function.
example:
```
def Add(z):
x,y = z
return x + y
a = [ 0 , 1, 2, 3]
b = [ 5, 6, 7, 8]
ab = (a,b)
Add(ab)
``` |
27,830,428 | I have been trying to compact my code for a primality test in python so that it makes use of list comprehensions, but for some reason it doesn't return the correct results:
```
def isPrime(n):
if n > 1:
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
re... | 2015/01/07 | [
"https://Stackoverflow.com/questions/27830428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4430875/"
] | As you want `False` if **any** lesser number is a divisor, code it directly that way:
```
def isPrime(n):
return n<=1 or not any(i for i in range(2, int(n ** 0.5) + 1) if n % i == 0)
```
Note that this uses a **genexp**, not a **listcomp**, because that allows `any` to terminate the whole operation as soon as it... | you can use `all`:
```
>>> def prime_check(n):
... if n > 1:
... return all(False for i in range(2, int(n ** 0.5) + 1) if n % i == 0)
...
>>> prime_check(6)
False
>>> prime_check(23)
True
>>> prime_check(108)
False
>>> prime_check(111)
False
>>> prime_check(101)
True
``` |
27,830,428 | I have been trying to compact my code for a primality test in python so that it makes use of list comprehensions, but for some reason it doesn't return the correct results:
```
def isPrime(n):
if n > 1:
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
re... | 2015/01/07 | [
"https://Stackoverflow.com/questions/27830428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4430875/"
] | As you want `False` if **any** lesser number is a divisor, code it directly that way:
```
def isPrime(n):
return n<=1 or not any(i for i in range(2, int(n ** 0.5) + 1) if n % i == 0)
```
Note that this uses a **genexp**, not a **listcomp**, because that allows `any` to terminate the whole operation as soon as it... | The problem is that a list containg `False` evaluates to a boolean `True`:
```
>>> isPrime(4)
[False]
>>> bool([False])
True
``` |
32,622,825 | I need to get some numbers from this website
<http://www.preciodolar.com/>
But the data I need, takes a little time to load and shows a message of 'wait' until it completely loads.
I used find all and some regular expressions to get the data I need, but when I execute, `python` gives me the 'wait' message that app... | 2015/09/17 | [
"https://Stackoverflow.com/questions/32622825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435341/"
] | As you are using the ASP.NET you can use the following two options in Page Load.
Option : 1
`Request.ServerVariables["HTTP_REFERER"]`
Although note on the above it is possible for browsers to block the value (empty value).
Option : 2
You can check the `Request.UrlReferrer` of the current `HttpRequest`: it will usuall... | Session\_Start event is not suitable for these kind of things. Session\_start runs when a user first enters in your applications, think it like the first page load.
You can use a query string parameter to determine where the user redirected from.
For example, if user redirected from sso.aspx to default.aspx, use url ... |
48,996,494 | I have two network interfaces (wifi and ethernet) both with internet access. Let's say my interfaces are `eth` (ethernet) and `wlp2` (wifi). I need specific requests to go through `eth` interface and others through `wpl2`.
Something like:
```
// Through "eth"
request.post(url="http://myapi.com/store_ip", iface="eth")... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48996494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4585081/"
] | I found a way using `pycurl`. This works like a charm.
```
import pycurl
from io import BytesIO
import json
def curl_post(url, data, iface=None):
c = pycurl.Curl()
buffer = BytesIO()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.POST, True)
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json'... | Try changing the internal IP (192.168.0.200) to the corresponding iface in the code below.
```
import requests
from requests_toolbelt.adapters import source
def check_ip(inet_addr):
s = requests.Session()
iface = source.SourceAddressAdapter(inet_addr)
s.mount('http://', iface)
s.mount('https://', ifac... |
48,996,494 | I have two network interfaces (wifi and ethernet) both with internet access. Let's say my interfaces are `eth` (ethernet) and `wlp2` (wifi). I need specific requests to go through `eth` interface and others through `wpl2`.
Something like:
```
// Through "eth"
request.post(url="http://myapi.com/store_ip", iface="eth")... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48996494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4585081/"
] | I found a way using `pycurl`. This works like a charm.
```
import pycurl
from io import BytesIO
import json
def curl_post(url, data, iface=None):
c = pycurl.Curl()
buffer = BytesIO()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.POST, True)
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json'... | If you want to do this on Linux you could use `SO_BINDTODEVICE` flag for `setsockopt` (check [man 7 socket](https://man7.org/linux/man-pages/man7/socket.7.html#:%7E:text=since%20Linux%204.6.-,SO_BINDTODEVICE,-Bind%20this%20socket), for more details). In fact, it's what used [by curl](https://github.com/curl/curl/blob/3... |
48,996,494 | I have two network interfaces (wifi and ethernet) both with internet access. Let's say my interfaces are `eth` (ethernet) and `wlp2` (wifi). I need specific requests to go through `eth` interface and others through `wpl2`.
Something like:
```
// Through "eth"
request.post(url="http://myapi.com/store_ip", iface="eth")... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48996494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4585081/"
] | Here is the solution for Requests library without monkey-patching anything.
This function will create a Session bound to the given IP address. It is up to you to determine IP address of the desired network interface.
Tested to work with `requests==2.23.0`.
```
import requests
def session_for_src_addr(addr: str) -> ... | Try changing the internal IP (192.168.0.200) to the corresponding iface in the code below.
```
import requests
from requests_toolbelt.adapters import source
def check_ip(inet_addr):
s = requests.Session()
iface = source.SourceAddressAdapter(inet_addr)
s.mount('http://', iface)
s.mount('https://', ifac... |
48,996,494 | I have two network interfaces (wifi and ethernet) both with internet access. Let's say my interfaces are `eth` (ethernet) and `wlp2` (wifi). I need specific requests to go through `eth` interface and others through `wpl2`.
Something like:
```
// Through "eth"
request.post(url="http://myapi.com/store_ip", iface="eth")... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48996494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4585081/"
] | If you want to do this on Linux you could use `SO_BINDTODEVICE` flag for `setsockopt` (check [man 7 socket](https://man7.org/linux/man-pages/man7/socket.7.html#:%7E:text=since%20Linux%204.6.-,SO_BINDTODEVICE,-Bind%20this%20socket), for more details). In fact, it's what used [by curl](https://github.com/curl/curl/blob/3... | Try changing the internal IP (192.168.0.200) to the corresponding iface in the code below.
```
import requests
from requests_toolbelt.adapters import source
def check_ip(inet_addr):
s = requests.Session()
iface = source.SourceAddressAdapter(inet_addr)
s.mount('http://', iface)
s.mount('https://', ifac... |
48,996,494 | I have two network interfaces (wifi and ethernet) both with internet access. Let's say my interfaces are `eth` (ethernet) and `wlp2` (wifi). I need specific requests to go through `eth` interface and others through `wpl2`.
Something like:
```
// Through "eth"
request.post(url="http://myapi.com/store_ip", iface="eth")... | 2018/02/26 | [
"https://Stackoverflow.com/questions/48996494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4585081/"
] | Here is the solution for Requests library without monkey-patching anything.
This function will create a Session bound to the given IP address. It is up to you to determine IP address of the desired network interface.
Tested to work with `requests==2.23.0`.
```
import requests
def session_for_src_addr(addr: str) -> ... | If you want to do this on Linux you could use `SO_BINDTODEVICE` flag for `setsockopt` (check [man 7 socket](https://man7.org/linux/man-pages/man7/socket.7.html#:%7E:text=since%20Linux%204.6.-,SO_BINDTODEVICE,-Bind%20this%20socket), for more details). In fact, it's what used [by curl](https://github.com/curl/curl/blob/3... |
17,477,394 | I'm trying to install the M2Crypto on Python26 in Windows, but I am getting the below error.
>
> **error**: command 'swig.exe' failed: No such file or directory
>
>
>
This error occurs both using the "Easy Install" or "PIP Install" command. Follows the Log:
>
> running build
>
>
> running build\_py
>
>
> ru... | 2013/07/04 | [
"https://Stackoverflow.com/questions/17477394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1347355/"
] | This worked for me: (using winpython2.7)
```
pip install M2CryptoWin32
```
reference:
<https://github.com/dsoprea/M2CryptoWin32> | Putting this in answer format:
You could try to install a binary build from <http://chandlerproject.org/Projects/MeTooCrypto>
from mata's comment that resolved OP's issue |
48,888,239 | Here is my image:

I want to find the center of mass in this image. I can find the approximate location of the center of mass by drawing two perpendicular lines as shown in this image:
 will do what you want. Here's an example:
```
import imageio as iio
from skimage import filters
from skimage.color import rgb2gray # only needed for incorrectly saved images
from skimage.measure impo... | You need to know about **[Image Moments](https://en.wikipedia.org/wiki/Image_moment)**.
[Here](https://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html) there's a tutorial of how use it with opencv and python |
48,888,239 | Here is my image:

I want to find the center of mass in this image. I can find the approximate location of the center of mass by drawing two perpendicular lines as shown in this image:
 function to find the center of mass of an object.
For example, using this question's image:
```sh
wget https://i.stack.imgur.com/ffDLD.jpg
```
```py
i... | You need to know about **[Image Moments](https://en.wikipedia.org/wiki/Image_moment)**.
[Here](https://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html) there's a tutorial of how use it with opencv and python |
48,888,239 | Here is my image:

I want to find the center of mass in this image. I can find the approximate location of the center of mass by drawing two perpendicular lines as shown in this image:
 will do what you want. Here's an example:
```
import imageio as iio
from skimage import filters
from skimage.color import rgb2gray # only needed for incorrectly saved images
from skimage.measure impo... | You can use the [scipy.ndimage.center\_of\_mass](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.center_of_mass.html#scipy.ndimage.center_of_mass) function to find the center of mass of an object.
For example, using this question's image:
```sh
wget https://i.stack.imgur.com/ffDLD.jpg
```
```py
i... |
70,152,772 | I'm using an AWS Lambda function (in Python) to connect to an Oracle database (RDS) using cx\_Oracle library. But it is giving me the below error - "DPI-1047: Cannot locate a 64-bit Oracle Client library: "libclntsh.so: cannot open shared object file: No such file or directory".
Steps I've followed -
1. Created a pyt... | 2021/11/29 | [
"https://Stackoverflow.com/questions/70152772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17394264/"
] | Set the environment variable `DPI_DEBUG_LEVEL` to the value `64` and then rerun your code. The debugging output should help you figure out what is being searched. Note that you need to have the 64-bit instant client installed as well! | The reason I faced this issue was that I just downloaded cx\_Oracle library. In order to connect to the Oracle database from the Lambda function, we need to download the Oracle client and libaio libraries as well and club them with cx\_Oracle to create a Lambda Layer. Once I followed these steps, I was able to connect ... |
33,337,302 | this is a follow-up from [https://stackoverflow.com/questions/33336963/use-a-python-dictionary-to-insert-into-mysql/33337128#33337128](https://stackoverflow.com/questions/33336963/use-a-python-dictionary-to-insert-into-mysql/33337128#33337128/).
```
import pymysql
conn = pymysql.connect(server, user , password, "db"... | 2015/10/26 | [
"https://Stackoverflow.com/questions/33337302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751241/"
] | Think I figured it out.
I will add the info here in case someone else comes across this question:
I need to add `conn.commit()` to the script | You can use
```
try:
cur.execute(sql)
except Exception, e:
print e
```
If your code is wrong, the exception can tell you.
And it has another question.
the cols and vals are not match.
The values should be
```
vals = [dict[col] for col in cols]
``` |
5,948,110 | I have been using python for a while now and Im happy using it in most forms but I am wondering which form is more pythonic. Is it right to emulate objects and types or is it better to subclass or inherit from these types. I can see advantages for both and also the disadvantages. Whats the correct method to be doing th... | 2011/05/10 | [
"https://Stackoverflow.com/questions/5948110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462604/"
] | Key question you have to ask yourself here is:
>
> "How should my class change if the 'parent' class changes?"
>
>
>
Imagine new methods are added to `dict` which you don't override in your `UniqueDict`. If you want to express that **`UniqueDict` is simply a small derivation** in behaviour from `dict`'s behavio... | Subclassing is better as you won't have to implement a proxy for every single dict method. |
5,948,110 | I have been using python for a while now and Im happy using it in most forms but I am wondering which form is more pythonic. Is it right to emulate objects and types or is it better to subclass or inherit from these types. I can see advantages for both and also the disadvantages. Whats the correct method to be doing th... | 2011/05/10 | [
"https://Stackoverflow.com/questions/5948110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462604/"
] | Subclassing is better as you won't have to implement a proxy for every single dict method. | I would go for subclass, and for the reason I would refer to the motivation of [PEP 3119](http://www.python.org/dev/peps/pep-3119/#rationale):
>
> For example, if asking 'is this object
> a mutable sequence container?', one
> can look for a base class of 'list',
> or one can look for a method named
> '**getitem**... |
5,948,110 | I have been using python for a while now and Im happy using it in most forms but I am wondering which form is more pythonic. Is it right to emulate objects and types or is it better to subclass or inherit from these types. I can see advantages for both and also the disadvantages. Whats the correct method to be doing th... | 2011/05/10 | [
"https://Stackoverflow.com/questions/5948110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462604/"
] | Key question you have to ask yourself here is:
>
> "How should my class change if the 'parent' class changes?"
>
>
>
Imagine new methods are added to `dict` which you don't override in your `UniqueDict`. If you want to express that **`UniqueDict` is simply a small derivation** in behaviour from `dict`'s behavio... | I would go for subclass, and for the reason I would refer to the motivation of [PEP 3119](http://www.python.org/dev/peps/pep-3119/#rationale):
>
> For example, if asking 'is this object
> a mutable sequence container?', one
> can look for a base class of 'list',
> or one can look for a method named
> '**getitem**... |
71,297,371 | Ok so I am trying to mass format a large text document to convert
```
#{'000','001','002','003','004','005','006','007','008','009'}
```
into
```
#{'000':'001','002':'003','004':'005','006':'007','008':'009'}
```
using python and have my function working, however it will only work if I run it line by line.
and w... | 2022/02/28 | [
"https://Stackoverflow.com/questions/71297371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18335232/"
] | Here is a possible solution:
```
result = [(str(dt.timetuple()[:6])[1:-1], s.split('_')[0]) for dt, s in OUTPUT]
``` | >
> Eventually I hope to pass the new list of tuples to a pandas dataframe.
>
>
>
You can use `.read_sql_query()` to pull the information directly into a DataFrame:
```py
import pandas as pd
import sqlalchemy as sa
connection_url = sa.engine.URL.create(
"mssql+pyodbc",
username="scott",
password="tig... |
20,054,030 | I have been getting the below error while using pxssh to get into remote servers to run unix commands ( like uptime )
```
Traceback (most recent call last):
```
File "./ssh\_pxssh.py", line 33, in
login\_remote(hostname, username, password)
File "./ssh\_pxssh.py", line 12, in login\_remote
if not s.login(hostnam... | 2013/11/18 | [
"https://Stackoverflow.com/questions/20054030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3005660/"
] | I have solved it by adding **sync\_multiplier** argument to the login function.
```
s.login(hostname, username, password, sync_multiplier=5 auto_prompt_reset=False)
```
note that **sync\_multiplier** is a communication timeout argument to perform successful synchronization. it tries to read prompt for at least **syn... | I had the same problem when pxssh tried to login on a very slow connection.
The pexpect lib apparently was fooled by the remote motd prompt.
This remote motd prompt contained a uname -svr prompt, which itself contained a # character inside.
Apparently, pexpect saw it like a prompt. From that point, the lib was not in ... |
28,329,596 | please help me.
I have the string (json request) :
```
{"jsonrpc":"2.0","result":[{"hostid":"10158"}],"id":1}
```
i try to parsing it with command :
```
reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]'`
```
and still have `[{u'hostid': u'10158'}]`
How i c... | 2015/02/04 | [
"https://Stackoverflow.com/questions/28329596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] | You keep two complete copies of the file in memory at the same time, `@lines` and `$lines`. You might consider instead:
```
open (my $FH, "<", $file) or die "Can't open $file for read: $!";
$FH->input_record_separator(undef); # slurp entire file
my $lines = <$FH>;
close $FH or die "Cannot close $file: $!";
```
On su... | Working with XML using regexes is error prone and inefficient, as code which slurps the whole file as a string shows. To deal with XML you should be using an XML parser. In particular, you want a SAX parser which will work on the XML a piece at a time as opposed to a DOM parser which much read the whole file.
I'm goin... |
28,329,596 | please help me.
I have the string (json request) :
```
{"jsonrpc":"2.0","result":[{"hostid":"10158"}],"id":1}
```
i try to parsing it with command :
```
reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]'`
```
and still have `[{u'hostid': u'10158'}]`
How i c... | 2015/02/04 | [
"https://Stackoverflow.com/questions/28329596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] | Handle the file line by line:
```
while ( my $file = $doc_it->() ) { # go through all documents found
print "Stripping $file\n";
open (my $infh, "<", $file) or die "Can't open $file for read: $!";
open (my $outfh, ">", $file . ".tmp") or die "Can't open $file.tmp for write: $!";
while (<$infh>) {
... | You keep two complete copies of the file in memory at the same time, `@lines` and `$lines`. You might consider instead:
```
open (my $FH, "<", $file) or die "Can't open $file for read: $!";
$FH->input_record_separator(undef); # slurp entire file
my $lines = <$FH>;
close $FH or die "Cannot close $file: $!";
```
On su... |
28,329,596 | please help me.
I have the string (json request) :
```
{"jsonrpc":"2.0","result":[{"hostid":"10158"}],"id":1}
```
i try to parsing it with command :
```
reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]'`
```
and still have `[{u'hostid': u'10158'}]`
How i c... | 2015/02/04 | [
"https://Stackoverflow.com/questions/28329596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] | You keep two complete copies of the file in memory at the same time, `@lines` and `$lines`. You might consider instead:
```
open (my $FH, "<", $file) or die "Can't open $file for read: $!";
$FH->input_record_separator(undef); # slurp entire file
my $lines = <$FH>;
close $FH or die "Cannot close $file: $!";
```
On su... | While working on a somewhat large (1.2G) file with Perl 5.10.1 on Windows Server 2013, I have noticed that
```
foreach my $line (<LOG>) {}
```
fails with out of memory, while
```
while (my $line = <LOG>) {}
```
works in a simple script that just runs some regexp'es and prints lines I'm interesting in. |
28,329,596 | please help me.
I have the string (json request) :
```
{"jsonrpc":"2.0","result":[{"hostid":"10158"}],"id":1}
```
i try to parsing it with command :
```
reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]'`
```
and still have `[{u'hostid': u'10158'}]`
How i c... | 2015/02/04 | [
"https://Stackoverflow.com/questions/28329596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] | Handle the file line by line:
```
while ( my $file = $doc_it->() ) { # go through all documents found
print "Stripping $file\n";
open (my $infh, "<", $file) or die "Can't open $file for read: $!";
open (my $outfh, ">", $file . ".tmp") or die "Can't open $file.tmp for write: $!";
while (<$infh>) {
... | Working with XML using regexes is error prone and inefficient, as code which slurps the whole file as a string shows. To deal with XML you should be using an XML parser. In particular, you want a SAX parser which will work on the XML a piece at a time as opposed to a DOM parser which much read the whole file.
I'm goin... |
28,329,596 | please help me.
I have the string (json request) :
```
{"jsonrpc":"2.0","result":[{"hostid":"10158"}],"id":1}
```
i try to parsing it with command :
```
reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]'`
```
and still have `[{u'hostid': u'10158'}]`
How i c... | 2015/02/04 | [
"https://Stackoverflow.com/questions/28329596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] | Working with XML using regexes is error prone and inefficient, as code which slurps the whole file as a string shows. To deal with XML you should be using an XML parser. In particular, you want a SAX parser which will work on the XML a piece at a time as opposed to a DOM parser which much read the whole file.
I'm goin... | While working on a somewhat large (1.2G) file with Perl 5.10.1 on Windows Server 2013, I have noticed that
```
foreach my $line (<LOG>) {}
```
fails with out of memory, while
```
while (my $line = <LOG>) {}
```
works in a simple script that just runs some regexp'es and prints lines I'm interesting in. |
28,329,596 | please help me.
I have the string (json request) :
```
{"jsonrpc":"2.0","result":[{"hostid":"10158"}],"id":1}
```
i try to parsing it with command :
```
reference_id2=`echo "$reference_id" | python -c 'import json, sys; print json.load(sys.stdin)["result"]'`
```
and still have `[{u'hostid': u'10158'}]`
How i c... | 2015/02/04 | [
"https://Stackoverflow.com/questions/28329596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3731374/"
] | Handle the file line by line:
```
while ( my $file = $doc_it->() ) { # go through all documents found
print "Stripping $file\n";
open (my $infh, "<", $file) or die "Can't open $file for read: $!";
open (my $outfh, ">", $file . ".tmp") or die "Can't open $file.tmp for write: $!";
while (<$infh>) {
... | While working on a somewhat large (1.2G) file with Perl 5.10.1 on Windows Server 2013, I have noticed that
```
foreach my $line (<LOG>) {}
```
fails with out of memory, while
```
while (my $line = <LOG>) {}
```
works in a simple script that just runs some regexp'es and prints lines I'm interesting in. |
62,585,876 | Our python Dataflow pipeline works locally but not when deployed using the Dataflow managed service on Google Cloud Platform. It doesn't show signs that it is connected to the PubSub subscription. We have tried subscribing to both subscription and topic, neither of them worked. The messages accumulate in the PubSub sub... | 2020/06/25 | [
"https://Stackoverflow.com/questions/62585876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6019494/"
] | Very late answer, it may still help someone else. I had the same problem, solved it like this:
1. Thanks to user Paramnesia1 who wrote [this](https://www.reddit.com/r/googlecloud/comments/srh28m/dataflow_pipeline_not_consuming_messages_from/) answer, I figured out that I was not observing all the logs on Logs Explorer... | I think for Pulling from subscription we need to pass with\_attributes parameter as True.
with\_attributes – True - output elements will be PubsubMessage objects. False -
output elements will be of type bytes (message data only).
Found similar one here:
[When using Beam IO ReadFromPubSub module, can you pull messages... |
22,488,763 | I have been trying to insert data into the database using the following code in python:
```
import sqlite3 as db
conn = db.connect('insertlinks.db')
cursor = conn.cursor()
db.autocommit(True)
a="asd"
b="adasd"
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.close()
```
The code runs without any... | 2014/03/18 | [
"https://Stackoverflow.com/questions/22488763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2923505/"
] | You do have to commit after inserting:
```
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.commit()
```
or use the [connection as a context manager](http://docs.python.org/2/library/sqlite3.html#using-the-connection-as-a-context-manager):
```
with conn:
cursor.execute("Insert into links (l... | It can be a bit late but set the `autocommit = true` save my time! especially if you have a script to run some bulk action as `update/insert/delete`...
**Reference:** <https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.isolation_level>
it is the way I usually have in my scripts:
```
def get_connection... |
51,696,395 | I'm trying to install gogle-assistant-sdk on Windows 10, and I'm getting a weird error which I can't understand.
After installing python for all users and setting ENV variables when i run this command -
```
py -m pip install google-assistant-sdk[samples]
```
I got following error -
```
Command ""C:\Program Files... | 2018/08/05 | [
"https://Stackoverflow.com/questions/51696395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6007248/"
] | Try this one
In the platforms/android/cordova-safe/starter-conceal.gradle change this
compile('com.facebook.conceal:conceal:1.0.0@aar')
to this
compile('com.facebook.conceal:conceal:2.0.1@aar')
This has worked for me. | Open `platforms/android/cordova-safe/starter-conceal.gradle`, then update the version of **com.facebook.conceal:conceal** from **1.0.0** to **1.1.3**, so the code should now be
```
dependencies {
compile('com.facebook.conceal:conceal:1.1.3@aar') {
transitive = true
}
}
``` |
48,644,767 | I'm looking at [\_math.c](https://github.com/python/cpython/blob/master/Modules/_math.c) in git (line 25):
```
#if !defined(HAVE_ACOSH) || !defined(HAVE_ASINH)
static const double ln2 = 6.93147180559945286227E-01;
static const double two_pow_p28 = 268435456.0; /* 2**28 */
```
and I noticed that ln2 value is differen... | 2018/02/06 | [
"https://Stackoverflow.com/questions/48644767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828285/"
] | As user2357112 noted, this code came from FDLIBM. That was carefully written for IEEE-754 machines, where C doubles have 53 bits of precision. It doesn't really care what the actual log of 2 is, but cares a whole lot about the best 53-bit approximation to `log(2)`.
To reproduce the intended 53-bit-precise value, [17 d... | Python seems wrong, although I'm not sure it is an oversight or it has a deeper meaning. The explanation of BlackJack seems reasonable, but I don't understand, why they would give additional digits that are wrong.
You can check this yourself by using the formula under [More efficient series](https://en.wikipedia.org/w... |
48,644,767 | I'm looking at [\_math.c](https://github.com/python/cpython/blob/master/Modules/_math.c) in git (line 25):
```
#if !defined(HAVE_ACOSH) || !defined(HAVE_ASINH)
static const double ln2 = 6.93147180559945286227E-01;
static const double two_pow_p28 = 268435456.0; /* 2**28 */
```
and I noticed that ln2 value is differen... | 2018/02/06 | [
"https://Stackoverflow.com/questions/48644767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828285/"
] | As user2357112 noted, this code came from FDLIBM. That was carefully written for IEEE-754 machines, where C doubles have 53 bits of precision. It doesn't really care what the actual log of 2 is, but cares a whole lot about the best 53-bit approximation to `log(2)`.
To reproduce the intended 53-bit-precise value, [17 d... | Up to the precision of binary64 floating-point representation, these values are equal:
```
In [21]: 0.6931471805599453094172321214581 == 0.693147180559945286227
Out[21]: True
```
`0.693147180559945286227` is what you get if you store the most accurate representable approximation of ln(2) into a 64-bit float and then... |
73,348,659 | I've recently had to implement a simple bruteforce software in python, and I was getting terrible execution times (even for a O(n^2) time complexity), topping the 10 minutes of runtime for a total of 3700 \* 11125 \* 2 = 82325000 access operations on numpy arrays (intel i5 4300U).
I'm talking about access operations b... | 2022/08/14 | [
"https://Stackoverflow.com/questions/73348659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17474667/"
] | Let's do some simple list and array comparisons.
Make a list of 0s (as you do):
```
In [108]: timeit [0]*1000
2.83 µs ± 0.399 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
```
Make an array from that list - a lot more time:
```
In [109]: timeit np.array([0]*1000)
84.9 µs ± 103 ns per loop (mean ± st... | These are the 4 main advantages of an ndarray as far as i know :
1. It uses less storage for the pointers (1 byte instead of 8) because its a raw python object and not an array. It also only allows homogeneous numeric data types which also lead to a increase in performance.
2. Slicing doesnt copy the array (which is a... |
22,425,567 | I'm using [Loggly](https://www.loggly.com/) in order to have a centralized logs aggregator for my app running on AWS (Elastic beanstalk). However I'm not able to save my application logs using the Python logging library and the django logging configuration. In my Loggly control panel I can see a lot of logs coming from... | 2014/03/15 | [
"https://Stackoverflow.com/questions/22425567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267719/"
] | The problem is either in the local rsyslog service *receiving* the logs or in *sending* them. Your `LOGGING` setting is solid, but since you are taking control of everything (like the Django loggers) you should set `'disable_existing_loggers': True`. (Minor point: you can drop 'format' from the `loggly` loggers; the sy... | Googled around and saw your post on loggly's support. Did you see their reply and did it help you?
<http://community.loggly.com/customer/portal/questions/5898190-django-loggly-app-logs-not-saved> |
24,148,039 | I'm trying to use in python a shared\_ptr of a fundamental type (for instance int or double), but I don't know how to export it to python:
I have the following class:
```
class Holder
{
public:
Holder(int v) : value(new int(v)) {};
boost::shared_ptr<int> value;
};
```
The class is being exported in this way... | 2014/06/10 | [
"https://Stackoverflow.com/questions/24148039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/697884/"
] | One can use [`boost::python::class_`](http://www.boost.org/doc/libs/release/libs/python/doc/v2/class.html#class_-spec) to export `boost::shared_ptr<int>` to Python in the same manner as other types:
```cpp
boost::python::class_<boost::shared_ptr<int> >(...);
```
However, be careful in the semantics introduced when e... | Do you need to? Python has its own reference counting
mechanism, and it might be simpler just to use that. (But a lot
depends on what is going on on the C++ side.)
Otherwise: you probably need to define a Python object to
contain the shared pointer. This is relatively straightforward:
just define something like:
```... |
51,201,658 | I am trying to learn to code using python on my own but I ran into a problem.
I am using python's subprocess module to execute a .bat file, but the process seems to get stuck at the bat file. The python code currently looks like this:
```
import getpass
username = getpass.getuser()
from subprocess import Popen
p = P... | 2018/07/06 | [
"https://Stackoverflow.com/questions/51201658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10039856/"
] | You need to use `subprocess.PIPE` for `stdout` and `stderr`, or else they can't be fetched through `Popen.communicate`, and is the reason why your process is stuck.
```
from subprocess import Popen, PIPE
import getpass
username = getpass.getuser()
p = Popen("hidefolder.bat", cwd=r"C:\Users\%s\Desktop" % username, std... | I am a new programmer but i could solve my problem writting below code.
```
import subprocess
subprocess.call([r'ProcurementSoftwareRun.bat'])
print ('Software run successful')
```
My bat file was like:
```
@ECHO OFF
cmd /c start "" "C:\Program Files (x86)\UserName\ERPModule\PROCUREMENT.exe
exit
``` |
45,010,682 | I wanted to convert an object of type bytes to binary representation in python 3.x.
For example, I want to convert the bytes object `b'\x11'` to the binary representation `00010001` in binary (or 17 in decimal).
I tried this:
```
print(struct.unpack("h","\x11"))
```
But I'm getting:
```
error struct.error: unpack... | 2017/07/10 | [
"https://Stackoverflow.com/questions/45010682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987575/"
] | Starting from Python 3.2, you can use [`int.from_bytes`](https://docs.python.org/3/library/stdtypes.html#int.from_bytes).
Second argument, `byteorder`, specifies [endianness](https://en.wikipedia.org/wiki/Endianness) of your bytestring. It can be either `'big'` or `'little'`. You can also use `sys.byteorder` to get yo... | Iterating over a bytes object gives you 8 bit ints which you can easily format to output in binary representation:
```py
import numpy as np
>>> my_bytes = np.random.bytes(10)
>>> my_bytes
b'_\xd9\xe97\xed\x06\xa82\xe7\xbf'
>>> type(my_bytes)
bytes
>>> my_bytes[0]
95
>>> type(my_bytes[0])
int
>>> for my_byte in my... |
72,703,006 | I am trying to have this repo on docker: <https://github.com/facebookresearch/detectron2/tree/main/docker>
but when I want to docker compose it, I receive this error:
```
ERROR: Package 'detectron2' requires a different Python: 3.6.9 not in '>=3.7'
```
The default version of the python I am using is 3.10 but I don'... | 2022/06/21 | [
"https://Stackoverflow.com/questions/72703006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13334873/"
] | This is an [open issue with facebookresearch/detectron2](https://github.com/facebookresearch/detectron2/issues/4335). The developers updated the base Python requirement from 3.6+ to 3.7+ with [commit 5934a14](https://github.com/facebookresearch/detectron2/commit/5934a1452801e669bbf9479ae222ce1a8a51f52e) last week but d... | You can use pyenv: <https://github.com/pyenv/pyenv>
Just google `docker pyenv container`, will give you some entries like: <https://gist.github.com/jprjr/7667947>
If you follow the gist you can see how it has been updated, very easy to update to latest python that pyenv support. anything since 2.2 to 3.11
Only drawb... |
46,830,144 | There seem to be two kinds of generator-based coroutine:
1. From [a
reply](https://stackoverflow.com/a/46203922/156458)
by Jim Fasarakis Hilliard:
>
> **Generator-based coroutine**: A generator (`def` + `yield`) that is wrapped by [`types.coroutine`](https://docs.python.org/3/library/types.html#types.coroutine) . Yo... | 2017/10/19 | [
"https://Stackoverflow.com/questions/46830144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156458/"
] | They're the same kind of coroutine. `types.coroutine` and `asyncio.coroutine` are just two separate ways to create them.
`asyncio.coroutine` is older, predating the introduction of `async` coroutines, and its functionality has shifted somewhat from its original behavior now that `async` coroutines exist.
`asyncio.cor... | As far as I’m concerned, `async def` is the **proper** way to define a coroutine. `yield` and `yield from` have their purpose in generators, and they are also used to implement “futures”, which are the low-level mechanism that handles switching between different coroutine contexts.
I did [this diagram](https://default... |
49,922,073 | I just installed termcolor for python 2.7 on windows8.1. When I try to print colored text, I get the strange output.
```
from termcolor import colored
print colored('Hello world','red')
```
Here is the result:
```
[31mHello world[0m
```
Help to get out from this problem.Thanks,In advance | 2018/04/19 | [
"https://Stackoverflow.com/questions/49922073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9467325/"
] | See this [stackOverflow](https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python) post.
It basically says that in order to get the escape sequences working in Windows, you need to run os.system('color') first.
For example:
```
import termcolor
import os
os.system('color')
print(te... | `termcolor` or `colored` works perfectly fine under python 2.7 and I can't replicate your error on my Mac/Linux.
If you looks into the source code of `colored`, it basically print the string in the format as
```
\033[%dm%s\033[0m' % (COLORS[color], text)
```
Somehow your terminal environment does not recognise th... |
3,079,684 | As you know, Windows has a "Add/Remove Programs" system in the Control Panel.
Let's say I am preparing an installer and I want to register my program to list of installed programs and want it to be uninstallable from "Add/Remove Programs"?
Which protocols should I use. Any tutorials or docs about registering programs... | 2010/06/20 | [
"https://Stackoverflow.com/questions/3079684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54929/"
] | As stated on IRC:
"Windows keeps its uninstall information in the registry"
Its in HLLM\Software\Microsoft\Windows\CurrentVersion\uninstall\ keys.
You need a few things from the Win32 API, but I belive there's a fair amount of Python support for the win32 API.
Basically, a key in ...\Uninstall\ with a unique name ... | Inno Setup is open source so perhaps you can get some ideas from that. |
3,079,684 | As you know, Windows has a "Add/Remove Programs" system in the Control Panel.
Let's say I am preparing an installer and I want to register my program to list of installed programs and want it to be uninstallable from "Add/Remove Programs"?
Which protocols should I use. Any tutorials or docs about registering programs... | 2010/06/20 | [
"https://Stackoverflow.com/questions/3079684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54929/"
] | As stated on IRC:
"Windows keeps its uninstall information in the registry"
Its in HLLM\Software\Microsoft\Windows\CurrentVersion\uninstall\ keys.
You need a few things from the Win32 API, but I belive there's a fair amount of Python support for the win32 API.
Basically, a key in ...\Uninstall\ with a unique name ... | If you are developing for Windows platform I think using Windows Installer from Microsoft won't be a problem.
You can check documentation of Windows Installer from [Microsoft.com Windows Installer Page](http://msdn.microsoft.com/en-us/library/cc185688%28v=VS.85%29.aspx) |
3,079,684 | As you know, Windows has a "Add/Remove Programs" system in the Control Panel.
Let's say I am preparing an installer and I want to register my program to list of installed programs and want it to be uninstallable from "Add/Remove Programs"?
Which protocols should I use. Any tutorials or docs about registering programs... | 2010/06/20 | [
"https://Stackoverflow.com/questions/3079684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54929/"
] | If you are developing for Windows platform I think using Windows Installer from Microsoft won't be a problem.
You can check documentation of Windows Installer from [Microsoft.com Windows Installer Page](http://msdn.microsoft.com/en-us/library/cc185688%28v=VS.85%29.aspx) | Inno Setup is open source so perhaps you can get some ideas from that. |
53,119,083 | In the [`xonsh`](https://github.com/xonsh/xonsh/) shell how can I receive from a pipe to a python expression? Example with a `find` command as pipe provider:
```
find $WORKON_HOME -name pyvenv.cfg -print | for p in <stdin>: $(ls -dl @(p))
```
The `for p in <stdin>:` is obviously pseudo code. What do I have to replac... | 2018/11/02 | [
"https://Stackoverflow.com/questions/53119083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65889/"
] | The easiest way to pipe input into a Python expression is to use a function that is a [callable alias](https://xon.sh/tutorial.html#callable-aliases), which happens to accept a stdin file-like object. For example,
```
def func(args, stdin=None):
for line in stdin:
ls -dl @(line.strip())
find $WORKON_HOME... | Drawing on the answer from [Anthony Scopatz](https://stackoverflow.com/users/2312428/anthony-scopatz) you can do this on one line with a [callable alias](https://xon.sh/tutorial.html#callable-aliases) as a lambda. The function takes the third form, `def mycmd2(args, stdin=None)`. I discarded `args` with `_` because I d... |
62,032,878 | I am new in ebpf & xdp topic and want to do learn it. My question is how to use ebpf filter to filter the packet on specific payload matching? for example, if the data(payload) of the packet is 1234 its passes to the network stack otherwise it blocks the packet. I reached payload length. For example, if I want to match... | 2020/05/26 | [
"https://Stackoverflow.com/questions/62032878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13623550/"
] | What did you try? You should probably read a bit more about eBPF to try to understand how to process packets, the basic example you give does not sound too complicated.
Basically you would have to parse the headers to see where your payload begins. [Simple BPF parsing examples](https://git.kernel.org/pub/scm/linux/ker... | Your edit is pretty much a new question, so here an updated answer. Please consider opening a new question instead in the future.
There are a number of things that are wrong in your program. In particular:
```c
1| payload_offset = sizeof(struct udphdr);
2| payload_size = ntohs(udp->len) - sizeof(struct udphdr);... |
54,468,348 | From the cmd window I have to do this every time I run a script:
```
C:\>cd C:\Users\my name\AppData\Local\Programs\Python\Python37
C:\Users\my name\AppData\Local\Programs\Python\Python37>python "C:\\Users\\my name\\AppData\\Local\\Programs\\Python\\Python37\\scripts\\helloWorld.py"
hello world
```
How can I get aw... | 2019/01/31 | [
"https://Stackoverflow.com/questions/54468348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3524158/"
] | You need to pay attention to the current working directory of your python interpreter. It basically means the directory you are currently in where you execute the python interpreter, and it relies on that path to look for your script passed in. If you're inside the script already, you can easily check with `os.getcwd()... | There is a designated directory where you can put your .py scripts if you want to invoke them without specifying the full path.
Setting this up correctly will allow you to run the script simply by invoking the script name (if the .py extension is registered to the interpreter and not an editor).
Windows
=======
If y... |
63,841,244 | I have been trying to scrape data from [this site](http://www.indianbluebook.com/). I need to fill **Get the precise price of your car** form ie. the year, make, model etc.. I have written the following code till now:
```
import requests
import time
from selenium import webdriver
from selenium.webdriver.common.by impo... | 2020/09/11 | [
"https://Stackoverflow.com/questions/63841244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9952858/"
] | You can use the below approach to achieve the same.
```
#Set link according to data need
driver.get('http://www.indianbluebook.com/')
#Wait webpage to fully load necessary tables
def ajaxwait():
for i in range(1, 30):
x = driver.execute_script("return (window.jQuery != null) && jQuery.active")
tim... | To click on **BANGALORE** and then select **2020** from the dropdown, you need to induce [WebDriverWait](https://stackoverflow.com/questions/49775502/webdriverwait-not-working-as-expected/49775808#49775808) for the `element_to_be_clickable()` and you can use the following [Locator Strategies](https://stackoverflow.com/... |
59,410,323 | so I have a csv file which is of the form -
```
No. Name Money
1 Tom Cat 100
2 Dan Man 200
3 Marie Claw300
4 Catherine K. 400
```
I need to detect if the some part of my second column data is in my third column. Is there a wa... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59410323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12021224/"
] | Unfortunately you cannot use blade syntax within Vue unless you are writing the Vue code directly in the blade template, which would not be best practice. One thing I have found helpful is to write out all my Laravel API routes in a google docs so they are easier to refer to when referencing them in Vue. I hope that he... | You can only use blade syntax, if you're in a `.blade` file.
You have to statically set this route or others when calling a API
NOT RECOMMENDED:
Or you can define a js variable in your "master" blade file, which you're then using in the `Register.vue` file. |
59,410,323 | so I have a csv file which is of the form -
```
No. Name Money
1 Tom Cat 100
2 Dan Man 200
3 Marie Claw300
4 Catherine K. 400
```
I need to detect if the some part of my second column data is in my third column. Is there a wa... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59410323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12021224/"
] | There is no way of doing this without a `.blade` file. there is no support given for vue components to use laravel routes dynamically. but you could use some third party packages to achieve this something like `Ziggy`
<https://github.com/tightenco/ziggy> | You can only use blade syntax, if you're in a `.blade` file.
You have to statically set this route or others when calling a API
NOT RECOMMENDED:
Or you can define a js variable in your "master" blade file, which you're then using in the `Register.vue` file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.