qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
18,118,226 | I am new python. I have some predefined xml files. I have a script which generate new xml files. I want to write an automated script which compares xmls files and stores the name of differing xml file names in output file?
Thanks in advance | 2013/08/08 | [
"https://Stackoverflow.com/questions/18118226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2286286/"
] | I think you're looking for the [`filecmp` module](http://docs.python.org/2/library/filecmp.html). You can use it like this:
```
import filecmp
cmp = filecmp.cmp('f1.xml', 'f2.xml')
# Files are equal
if cmp:
continue
else:
out_file.write('f1.xml')
```
Replace `f1.xml` and `f2.xml` with your xml files. | Building on @Xaranke's answer:
```
import filecmp
out_file = open("diff_xml_names.txt")
# Not sure what format your filenames will come in, but here's one possibility.
filePairs = [('f1a.xml', 'f1b.xml'), ('f2a.xml', 'f2b.xml'), ('f3a.xml', 'f3b.xml')]
for f1, f2 in filePairs:
if not filecmp.cmp(f1, f2):
... | 6,715 |
44,513,308 | Can I use macros with the PythonOperator? I tried following, but I was unable to get the macros rendered:
```
dag = DAG(
'temp',
default_args=default_args,
description='temp dag',
schedule_interval=timedelta(days=1))
def temp_def(a, b, **kwargs):
print '{{ds}}'
print '{{execution_date}}'
p... | 2017/06/13 | [
"https://Stackoverflow.com/questions/44513308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4116268/"
] | Macros only get processed for templated fields. To get Jinja to process this field, extend the `PythonOperator` with your own.
```py
class MyPythonOperator(PythonOperator):
template_fields = ('templates_dict','op_args')
```
I added `'templates_dict'` to the `template_fields` because the `PythonOperator` itself h... | In my opinion a more native Airflow way of approaching this would be to use the included PythonOperator and use the `provide_context=True` parameter as such.
```py
t1 = MyPythonOperator(
task_id='temp_task',
python_callable=temp_def,
provide_context=True,
dag=dag)
```
Now you have access to all of th... | 6,719 |
3,853,136 | The following code runs fine in my IDE (PyScripter), however it won't run outside of it. When I go into computer then python26 and double click the file (a .pyw in this case) it fails to run. I have no idea why it's doing this, can anyone please shed some light?
This is in windows 7 BTW.
My code:
```
#!/usr/bin/e... | 2010/10/04 | [
"https://Stackoverflow.com/questions/3853136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/433417/"
] | unless you've been messing around with your standard library, it seems that you have a file named `threading.py` somewhere on your python path that is replacing the standard one. Try:
```
>>>import threading
>>>print threading.__file__
```
and make sure that it's the one in your python lib directory (it should be`C:... | You most likely need to adjust your [PYTHONPATH](http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH); this is a list of directories Python uses to find modules. See also [How to add to the pythonpath in windows 7?](https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7). | 6,720 |
64,405,461 | Trying to add Densenet121 functional block to the model.
I need Keras model to be written in this format, not using
```
model=Sequential()
model.add()
```
method
What's wrong the function, build\_img\_encod
```
---------------------------------------------------------------------------
AttributeError ... | 2020/10/17 | [
"https://Stackoverflow.com/questions/64405461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14309081/"
] | The reason why you get that error is that you need to provide the `input_shape` of the `base_model`, instead of the `base_model` per say.
Replace this line: `model = keras.models.Model(inputs=base_model, outputs = img_dense_encoder)`
with: `model = keras.models.Model(inputs=base_model.input, outputs = img_dense_encod... | ```
def build_img_encod( ):
dense = DenseNet121(input_shape=(150,150,3),
include_top=False,
weights='imagenet')
for layer in dense.layers:
layer.trainable = False
img_input = Input(shape=(150,150,3))
base_model = dense(img_inp... | 6,722 |
39,612,416 | I have a linux machine to which i installed Anaconda.
I am following:
<https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html>
pip instaltion part.
To be more specific:
```
which python
```
gives
```
/home/user/anaconda2/bin/python
```
After which i entered:
```
export TF_BINARY_URL=https://... | 2016/09/21 | [
"https://Stackoverflow.com/questions/39612416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6857504/"
] | The problem is here:
```
xs foldLeft((0,0,0))(logic _)
```
Never go for the dotless notation unless it's for an operator. This way it works.
```
xs.foldLeft((0,0,0))(logic _)
```
Without a context I believe this is idiomatic enough. | I don't get the goal of your code but the problem you described can be solved this way:
```
val to = xs.foldLeft((0,0,0))(logic)
``` | 6,723 |
61,858,954 | I'm trying to get two attributes at the time from my json data and add them as an item on my python list. However, when trying to add those two: `['emailTypeDesc']['createdDate']` it throws an error. Could someone help with this? thanks in advance!
json:
```
{
'readOnly': False,
'senderDetails': {'firstName': 'John'... | 2020/05/17 | [
"https://Stackoverflow.com/questions/61858954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9488179/"
] | I think you're misunderstanding the syntax. `mails['emailTypeDesc']['createdDate']` is looking for the key `'createdDate'` *inside* the object `mails['emailTypeDesc']`, but in fact they are two items at the same level.
Since `mails['emailTypeDesc']` is a string, not a dictionary, you get the error you have quoted. It ... | Strings in JSON must be in double quotes, not single.
Edit: As well as names. | 6,726 |
74,558,107 | Is it possible to calculate an expression using python but without entering python shell? What I want to achieve is to use python in a following manner:
```
tail file.txt -n `python 123*456`
```
instead of having to calculate 123\*456 in a separate step. | 2022/11/24 | [
"https://Stackoverflow.com/questions/74558107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4746861/"
] | I don't understand your question: you say "I would like to do something using Python", but when you show what you want to do, Python seems not to be needed for achieving that.
Let me show you: what you want to achieve, can be done as follows:
```
tail -f file.txt -n $((123*456))
```
The `$((...))` notation is capab... | You can try the `-c` option. For e.g, `tail test_log.txt -n `python -c "print(1 + 2)"`` | 6,727 |
58,165,158 | I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript:
```
C:\WINDOWS\system32> pip install pinyin_utils ... | 2019/09/30 | [
"https://Stackoverflow.com/questions/58165158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1738579/"
] | You could take [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) and spread the items.
```js
let array = [[1,2], [10, 15], [30, 40], [-1, -50]],
max = array.map(a => Math.max(...a));
console.log(max);
``` | Empty numeric values wouldn't help you either using your logic, because you are setting wrong initial values for comparison. See this, same as yours, with minor fix:
```
let arr = [[1,2], [10, 15], [30, 40], [-1, -50]];
let newArr = [arr[0][0], arr[1][0], arr[2][0], arr[3][0]];
for (let x = 0; x < arr.length; x++... | 6,728 |
59,307,815 | I am currently developing a python project where I am concerned with performance because my CPU is always using like 90-98% of its computing capacity.
So I was thinking about what could I change in my code to make it faster, and noticed that I have a string variable which always receives one of two values:
```
state... | 2019/12/12 | [
"https://Stackoverflow.com/questions/59307815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619301/"
] | To parse HTML and XML documents (page source) and get elements with locators, you can use [beautifulsoup](/questions/tagged/beautifulsoup "show questions tagged 'beautifulsoup'"), [how to use it](https://pypi.org/project/beautifulsoup4/).
Regular expression do not parsing HTML documents. You get **NULL** because `Ch... | From the code you have posted, the strings you have hardcoded are all the same other than the index of the DD element. Since the Status index is always 7 less than the index of Checkpath, you can just loop through 15-12, do your search, and then Status is just 15-7. The code is below.
```
src = driver.page_source
loop... | 6,733 |
8,275,650 | I am stuck trying to perform this task and while trying I can't help thinking there will be a nicer way to code it than the way I have been trying.
I have a line of text and a keyword. I want to make a new list going down each character in each list. The keyword will just repeat itself until the end of the list. If th... | 2011/11/26 | [
"https://Stackoverflow.com/questions/8275650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1066430/"
] | You've got two questions mashed into one. The first is: how do you remove non-alphanumeric chars from a string? You can do it a few ways, but regular expression substitution is a nice way.
```
import re
def removeWhitespace( s ):
return re.sub( '\s', '', s )
```
The second part of the question is about how to k... | I think you could use `enumerate` in that situation:
```
# remove unwanted stuff
l = [ c for c in Text if c.isalpha() ]
for n,k in enumerate(l):
print n, (Keyword[n % len(Keyword)], Text[l])
```
that gives you:
```
0 ('l', 'h')
1 ('e', 'i')
2 ('m', 't')
3 ('o', 'h')
4 ('n', 'e')
5 ('l', 'r')
6 ('e', 'e')
```
... | 6,735 |
8,912,338 | I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via
```
(gdb) python mystruct = gdb.parse_and_eval("mystruct")
```
Now I got this variable called mystruct which is a GDB.Value object. And I can access all the members of the struct by simply u... | 2012/01/18 | [
"https://Stackoverflow.com/questions/8912338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154311/"
] | From GDB [documentation](http://sourceware.org/gdb/onlinedocs/gdb/Values-From-Inferior.html#Values-From-Inferior):
You can get the type of `mystruct` like so:
```
tp = mystruct.type
```
and iterate over the [fields](http://sourceware.org/gdb/onlinedocs/gdb/Types-In-Python.html#Types-In-Python) via `tp.fields()`
No... | Evil workaround:
```
python print eval("dict(" + str(mystruct)[1:-2] + ")")
```
I don't know if this is generalisable. As a demo, I wrote a minimal example `test.cpp`
```
#include <iostream>
struct mystruct
{
int i;
double x;
} mystruct_1;
int main ()
{
mystruct_1.i = 2;
mystruct_1.x = 1.242;
std::cout ... | 6,738 |
66,079,303 | I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel.
I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main.
After the publishing on main `nginx` forward requests to te... | 2021/02/06 | [
"https://Stackoverflow.com/questions/66079303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12535379/"
] | There are four solutions. In all of them, x = 0x4121, y = 0x48ab. There are four options for z (two of its bits are free to be 0 or 1), namely 0x1307, 0x1387, 0x1707, 0x1787.
This can be calculated by treating the variables are arrays of 16 bits and implementing the bitwise operations on them in terms of operations on... | Here is one using SWI-Prolog's [`library(clpb)`](https://eu.swi-prolog.org/pldoc/man?section=clpb) to solve constraints over boolean variables (thanks Markus Triska!).
Very simple translation (I have never used this library but it's rather straightforward):
```none
:- use_module(library(clpb)).
% sat(Expr) sets up a... | 6,741 |
41,129,921 | I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise.
I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1... | 2016/12/13 | [
"https://Stackoverflow.com/questions/41129921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332936/"
] | Here is a crude but functional solution (for the narrower question) using `datetime.strptime()`:
```
import datetime
def is_expected_datetime_format(timestamp):
format_string = '%Y-%m-%dT%H:%M:%S.%f%z'
try:
colon = timestamp[-3]
if not colon == ':':
raise ValueError()
colon... | Given the constraints you've put on the problem, you could easily solve it with a regular expression.
```
>>> import re
>>> re.match(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}[+-]\d\d:\d\d$', '2016-12-13T21:20:37.593194+00:00')
<_sre.SRE_Match object; span=(0, 32), match='2016-12-13T21:20:37.593194+00:00'>
```
If you ... | 6,750 |
19,593,456 | Can the "standard" subprocess pipeline technique (e.g. <http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline>) be "upgraded" to two pipelines?
```
# How about
p1 = Popen(["cmd1"], stdout=PIPE, stderr=PIPE)
p2 = Popen(["cmd2"], stdin=p1.stdout)
p3 = Popen(["cmd3"], stdin=p1.stderr)
p1.stdout.close(... | 2013/10/25 | [
"https://Stackoverflow.com/questions/19593456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/690620/"
] | You could use bash's [process substitution](http://en.wikipedia.org/wiki/Process_substitution):
```
from subprocess import check_call
check_call("cmd1 > >(cmd2) 2> >(cmd3)", shell=True, executable="/bin/bash")
```
It redirects `cmd1`'s stdout to `cmd2` and `cmd1`'s stderr to `cmd3`.
If you don't want to use `bash`... | The solution here is to create a couple of background threads which read the output from one process and then write that into the inputs of several processes:
```
targets = [...] # list of processes as returned by Popen()
while True:
line = p1.readline()
if line is None: break
for p in targets:
p.s... | 6,758 |
56,293,981 | I'm writing a python script which has to internally create output path from the input path. However, I am facing issues to create the path which I can use irrespective of OS.
I have tried to use os.path.join and it has its own limitations.
Apart from that, I think simple string concatenation is not the way to go.
Path... | 2019/05/24 | [
"https://Stackoverflow.com/questions/56293981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5729921/"
] | From the documentation `os.path.join` can join "**one or more** path components...". So you could split `"\internal\morelevel\outputpath"` up into each of its components and pass all of them to your `os.path.join` function instead. That way you don't need to "hard-code" the separator between the path components. For ex... | Assuming your original path is "C:\projects\django\hereisinput", your other part of the path as "internal\morelevel\outputpath" (notice this is a relative path, not absolute), you could always move your primary back one folder (or more) and then append the second part. Do note that your first path needs to contain only... | 6,759 |
41,247,105 | I am trying to run this script in parallel, for i<=4 in each set. The `runspr.py` is itself parallel, and thats fine. What I am trying to do is running only 4 i loop in any instance.
In my present code, it will run everything.
```
#!bin/bash
for i in *
do
if [[ -d $i ]]; then
echo "$i id dir"
cd $i
... | 2016/12/20 | [
"https://Stackoverflow.com/questions/41247105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2005559/"
] | You don't need to use `for` loop. You can use [`gnu parallel`](https://www.gnu.org/software/parallel/parallel_tutorial.html) like this with `find`:
```
find . -mindepth 1 -maxdepth 1 -type d ! -print0 |
parallel -0 --jobs 4 'cd {}; python3 ~/bin/runspr.py SCF'
``` | Another possible solution is:
```
find . -mindepth 1 -maxdepth 1 -type d ! -print0 |
xargs -I {} -P 4 sh -c 'cd {}; python3 ~/bin/runspr.py SCF'
``` | 6,760 |
58,478,181 | I'm looking at breaking the enigma cipher with python, and need to generate plugboard combinations - what I need is a function which takes a `length` parameter and returns a generator object of all possible combinations as a list.
Example code:
```py
for comb in func(2):
print(comb)
```
```py
# Example output
['... | 2019/10/20 | [
"https://Stackoverflow.com/questions/58478181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I think what you're looking for is [itertools.combinations](https://docs.python.org/3/library/itertools.html#itertools.combinations)
```
>>> from itertools import combinations
>>> list(combinations('abcd', 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(comb) for comb in combi... | Is this something close to what you're after? Let me know and I can revise.
The `plugboard()` function returns (`yield`) a `generator` object which can be accessed either by an iterable loop, or by calling the `next()` function.
```
from itertools import product
def plugboard(chars, length):
for comb in product(... | 6,761 |
63,810,966 | I try to remove outliers in a python list. But it removes only the first one (190000) and not the second (20000). What is the problem ?
```
import statistics
dataset = [25000, 30000, 52000, 28000, 150000, 190000, 200000]
def detect_outlier(data_1):
threshold = 1
mean_1 = statistics.mean(data_1)
std_1 = st... | 2020/09/09 | [
"https://Stackoverflow.com/questions/63810966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9669017/"
] | It is because you are trying to make operations on the same data address.
dataset's address is equals to the data\_1 address and when you are removing an element from the list, it pass the next element according to the foreach structure of Python. You must not make operations on a list during iteration.
Shortly, try t... | ```
import statistics
def detect_outlier(data_1):
threshold = 1
mean_1 = statistics.mean(data_1)
std_1 = statistics.stdev(data_1)
result_dataset = [y for y in data_1 if abs((y - mean_1)/std_1)<=threshold ]
return result_dataset
if __name__=="__main__":
dataset = [25000, 30000, 52000, 28000, 1... | 6,762 |
61,660,067 | This is the code i used:
```
df = None
from pyspark.sql.functions import lit
for category in file_list_filtered:
data_files = os.listdir('HMP_Dataset/'+category)
for data_file in data_files:
print(data_file)
temp_df = spark.read.option('header', 'false').option('delimiter', ' ').csv('HMP_Dat... | 2020/05/07 | [
"https://Stackoverflow.com/questions/61660067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13491209/"
] | You can try *regular expressions* in order to parse. First, let's extract a model: since commands are in format
```
Start (zero or more Modifiers)
```
E.g.
```
%today-5day+3hour%
```
where `today` is `Start` and `-5day` and `+3hour` are `Modifiers` we want two *models*
```
using System.Linq;
using System.Text.R... | This is a small example of parsing a string that has today and day in it (using the example of %today-5day%).
Note: this will only work if the value passed in for the added days is between 0-9, to handle large numbers you will have to loop over the result of the string.
You can follow this code block to parse other ... | 6,763 |
46,574,860 | I am trying to get percentage frequencies in pyspark. I did this in python as follows
```
Companies = df['Company'].value_counts(normalize = True)
```
Getting the frequencies is fairly straightforward:
```
# Dates in descending order of complaint frequency
df.createOrReplaceTempView('Comp')
CompDF = spark.sql("SE... | 2017/10/04 | [
"https://Stackoverflow.com/questions/46574860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8722941/"
] | As Suresh implies in the comments, assuming that `total_count` is the number of rows in dataframe `Companies`, you can use `withColumn` to add a new column named `percentages` in `CompDF`:
```
total_count = Companies.count()
df = CompDF.withColumn('percentage', CompDF.cnt/float(total_counts))
``` | May be modifying the SQL query will get you the result you want.
```
"SELECT Company,cnt/(SELECT SUM(cnt) from (SELECT Company, count(*) as cnt
FROM Comp GROUP BY Company ORDER BY cnt DESC) temp_tab) sum_freq from
(SELECT Company, count(*) as cnt FROM Comp GROUP BY Company ORDER BY cnt
DESC)"
``` | 6,764 |
67,205,402 | I have a file and its name is (Pro\_data.sh) which contains these commands:
```
python preprocess.py dex
python preprocess.py lex
python process.py
```
I do not know how can I run the file in the python terminal (pycharm as an example).
I can run each command alone but I want to know the right way to run the .sh ... | 2021/04/22 | [
"https://Stackoverflow.com/questions/67205402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10585944/"
] | Is this what you're looking for?
main.py
```
import os
os.system('sh x.sh')
```
x.sh
```
python test2.py
```
test2.py
```
print('up')
```
output from main.py
```
up
``` | .sh is a mac/Linux shell. for windows: create one with the name Pro\_data.bat and put those three commands in it, and run Prod\_data.bat
**Prod\_data.bat**
```
python preprocess.py dex
python preprocess.py lex
python process.py
``` | 6,765 |
4,743,016 | I search a python builder IDE for wxpython similar to boa constructor.
any suggestions ? | 2011/01/20 | [
"https://Stackoverflow.com/questions/4743016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348081/"
] | Well, there is [wxGlade](http://wxglade.sourceforge.net/), [DialogBlocks](http://www.dialogblocks.com/) and [wxDesigner](http://www.wxdesigner-software.de/), with both DialogBlocks and wxDesigner being commercial tools. There also used to be a open-source editor called wxFormBuilder, but the site hosting it seems down ... | Boa constructor is working here....works with windows 10
<https://bitbucket.org/cwt/boa-constructor/overview> | 6,766 |
68,640,517 | I am trying to run a simple python script within a docker run command scheduled with Airflow.
I have followed the instructions here [Airflow init](https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html).
My `.env` file:
```
AIRFLOW_UID=1000
AIRFLOW_GID=0
```
And the `docker-compose.yaml` is based ... | 2021/08/03 | [
"https://Stackoverflow.com/questions/68640517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4390189/"
] | There was a bug in Docker Provider 2.0.0 which prevented Docker Operator to run with Docker-In-Docker solution.
You need to upgrade to the latest Docker Provider 2.1.0
<https://airflow.apache.org/docs/apache-airflow-providers-docker/stable/index.html#id1>
You can do it by extending the image as described in <https://... | I had the same issue and all "recommended" ways of solving the issue here and setting up mount\_dir params as descripted [here](https://airflow.apache.org/docs/apache-airflow-providers-docker/stable/_api/airflow/providers/docker/operators/docker/index.html) just lead to other errors. The one solution that helped me was... | 6,767 |
5,532,902 | I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h".
I wrote one that does it iteratively:
```
def Reverse( s ):
result = ""
n = 0
start = 0
while ( s[n:] != "" ):
while ( s[n:] != "" and s[n] != ' ' ):
... | 2011/04/03 | [
"https://Stackoverflow.com/questions/5532902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615585/"
] | If this isn't just a homework question and you're actually trying to reverse a string for some greater goal, just do `s[::-1]`. | I know it's too late to answer original question and there are multiple better ways which are answered here already. My answer is for documentation purpose in case someone is trying to implement tail recursion for string reversal.
```
def tail_rev(in_string,rev_string):
if in_string=='':
return rev_string
... | 6,768 |
69,422,541 | I am using the python code below to attempt to create a graph that fills the entire figure. The problem is I need the graph portion to stretch to fill the entire figure, there should not be any of the green showing and the graphed data should start at one side and go all the way to the other. I have found similar examp... | 2021/10/03 | [
"https://Stackoverflow.com/questions/69422541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2231017/"
] | Just use `IsNullOrWhiteSpace`; it does what `IsNullOrEmpty` does:
>
> Return `true` if the value parameter is null or Empty, or if value consists exclusively of white-space characters.
> *-- documentation for IsNullOrWhiteSpace*
>
>
>
And it is mapped by EF Core to an SQL of
```
@value IS NULL OR LTRIM(RTRIM(@va... | You cannot translate this method to SQL Server. However, you can use a method that returns Expression. For example:
```
public static Expression<Func<Student, bool>> IsSomething()
{
return (s) => string.IsNullOrEmpty(s.FirstName) || string.IsNullOrWhiteSpace(s.FirstName);
}
```
Usually, you should call AsEnumera... | 6,778 |
15,034,105 | Let say I have the a list of list
```
[ ['B','2'] , ['o','0'], ['y']]
```
and I want to combine the list into something like this without using iteratool
```
["Boy","B0y","2oy","20y"]
```
I can't use itertool because I have to use python 2.5. | 2013/02/22 | [
"https://Stackoverflow.com/questions/15034105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968057/"
] | [`itertools.product()`](http://docs.python.org/2/library/itertools.html#itertools.product) does what you want.
```
>>> [''.join(x) for x in itertools.product(*[['B', '2'], ['o', '0'], ['y']])]
['Boy', 'B0y', '2oy', '20y']
``` | If you don't want to use itertools, this list comprehension produces your output:
```
>>> LoL=[['B','2'], ['o','0'], ['y']]
>>> [a+b+c for a in LoL[0] for b in LoL[1] for c in LoL[2]]
['Boy', 'B0y', '2oy', '20y']
```
This is a more compact version of this:
```
LoL=[['B','2'], ['o','0'], ['y']]
r=[]
for a in LoL[0]:... | 6,779 |
51,115,744 | How to set path for python 3.7.0?
I tried the every possible way but it still shows the error!
>
> Could not install packages due to an EnvironmentError: [WinError 5]
>
>
> Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt'
>
>
> Consider using the `--u... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51115744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10014902/"
] | You can add --user in the end of your command. This works well in my case!
```
--user
```
My example:
```
python -m pip install --upgrade pip --user
``` | Just try on Administrator cmd
```
pip install --user numpy
``` | 6,780 |
10,396,640 | My current plan is to determine which is the first entry in a number of [Tkinter](http://wiki.python.org/moin/TkInter) listboxes highlighted using `.curselection()` and combining all of the resulting tuples into a list, producing this:
```
tupleList = [(), (), ('24', '25', '26', '27'), (), (), (), ()]
```
I'm wonder... | 2012/05/01 | [
"https://Stackoverflow.com/questions/10396640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367581/"
] | ```
>>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()]
>>> min(int(j) for i in nums for j in i)
24
``` | ```
>>> from itertools import chain
>>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()]
>>> min(map(int,chain.from_iterable(nums)))
24
``` | 6,790 |
61,629,693 | I have a 3D numpy array with integer values, something defined as:
```
import numpy as np
x = np.random.randint(0, 100, (10, 10, 10))
```
Now what I want to do is find the last slice (or alternatively the first slice) along a given axes (say 1) where a particular value occurs. At the moment, I do something like:
`... | 2020/05/06 | [
"https://Stackoverflow.com/questions/61629693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2713740/"
] | You probably can optimize this to be faster, but here is a vectorized version of what you search:
```
axis = 1
mask = np.where(x==val)[axis]
first, last = np.amin(mask), np.amax(mask)
```
It first finds the element `val` in your array using `np.where` and returns the `min` and `max` of indices along desired axis. | Per your question, you want to check if there's any such valid slice and hence, get the start/first, stop/last indices. In absence of any such valid slice, we must return None's there. That needs extra check. Also, we can use `masking` to get those indices in an efficient manner, like so -
```
def slice_info(x, val):
... | 6,793 |
44,987,098 | Is it possible to install [nodejs](/questions/tagged/nodejs "show questions tagged 'nodejs'") packages (/modules) from files like in [ruby](/questions/tagged/ruby "show questions tagged 'ruby'")'s Gemfile as done with `bundle install` or [python](/questions/tagged/python "show questions tagged 'python'")'s requirements... | 2017/07/08 | [
"https://Stackoverflow.com/questions/44987098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Just create your package JSON, you can use yarn to manage your packages instead of npm, it's faster.
Inside your package you can create a section of scripts accessed by `npm run`
`scripts: {
customBuild: 'your sh code/ruby/script whateve'
}`
And after you can run on terminal, `npm run customBuild` for example | you can use NPM init to create a package.json file which will store the node packages your application is dependent on, then use npm install which will install the node packages indicated in the package.json file | 6,794 |
55,317,792 | My sonar branch coverage results are not importing into sonarqube.
coverage.xml are generating in jenkins workspace.
following are the below jenkins and error details :
WARN: No report was found for sonar.python.coverage.reportPaths using pattern coverage-reports/coverage.xml
I have tried in my ways but nothing worked... | 2019/03/23 | [
"https://Stackoverflow.com/questions/55317792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11248384/"
] | You are having that error because you are specifying the coverage report path option wrong, and therefore sonar is using the default location `coverage-reports/coverage.xml`.
The correct option is `-Dsonar.python.coverage.reportPath` (in singular). | I still have this problem on Azure Pipelines. Tried many ways without success.
WARN: No report was found for sonar.python.coverage.reportPaths using pattern coverage.xml | 6,795 |
35,857,389 | Encountered the following problem when trying to use the module scipy.optimize.slsqp.
```
>>> import scipy.optimize.slsqp
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/site-packages/scipy/optimize/__init__.py",
line 233, in <module>
from ._minimize import ... | 2016/03/08 | [
"https://Stackoverflow.com/questions/35857389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6020400/"
] | Depending on the scope you use it would be loaded in an application context, therefore one time (say in a singleton class loaded at the application startup).
But I wouldn't recommend this approach, I would recommend a proper designed database where you can put your csv data into. This way you would have the database ... | I can read from a CSV file to build your arrays. You can then add the arrays to session scope. The CSV file will only be read at the servlet that processes it. Future usage will be retrieved from session. | 6,796 |
51,529,408 | I must be missing something but I look around and couldn't find reference to this issue.
I have the very basic code, as seen in flask-mongoengine documentation.
test.py:
```
from flask import Flask
from flask_mongoengine import MongoEngine
```
When I run
python test.py
...
```
from flask_mongoengine import Mong... | 2018/07/26 | [
"https://Stackoverflow.com/questions/51529408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5112112/"
] | Since your using a virtual environment did you try opening your editor from your virtual environment?
For example opening the vscode editor from command-line is "code". Go to your virtual environment via the terminal and activate then type "code" at your prompt.
```
terminal:~path/to/virtual-enviroment$ source bin/act... | I had this issue and managed to fix it by deactivating, reinstalling flask-mongoengine and reactivating the venv (all in the Terminal):
```
deactivate
pip install flask-mongoengine
# Not required but good to check it was properly installed
pip freeze
venv\Scripts\activate
flask run
``` | 6,797 |
55,659,835 | I am new to Python and I am trying to separate polygon data into x and y coordinates. I keep getting error: "AttributeError: ("'MultiPolygon' object has no attribute 'exterior'", 'occurred at index 1')"
From what I understand Python object MultiPolygon does not contain data exterior. But how do I remedy this to make ... | 2019/04/12 | [
"https://Stackoverflow.com/questions/55659835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11053854/"
] | I have updated your function `getPolyCoords()` to enable the handling of other geometry types, namely, `MultiPolygon`, `Point`, and `LineString`. Hope it works for your project.
```
def getPolyCoords(row, geom, coord_type):
"""Returns the coordinates ('x|y') of edges/vertices of a Polygon/others"""
# Parse th... | See the shapely docs about [multipolygons](https://shapely.readthedocs.io/en/stable/manual.html#MultiPolygons)
A multipolygon is a sequence of polygons, and it is the polygon object that has the exterior attribute. You need to iterate through the polygons of the multipolygon, and get `exterior.coords` of each polygon.... | 6,798 |
65,146,279 | I need to run K-means clustering algorithm to cluster textual data but by using cosine distance measure instead of Euclidean distance. Any reliable implementation of this in python?
***Edit:***
I have tried to use NLTK as following:
```
NUM_CLUSTERS=3
kclusterer = KMeansClusterer(NUM_CLUSTERS, distance=
... | 2020/12/04 | [
"https://Stackoverflow.com/questions/65146279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10153492/"
] | If you want to do it yourself: [https://stanford.edu/~cpiech/cs221/handouts/kmeans.html](https://stanford.edu/%7Ecpiech/cs221/handouts/kmeans.html)
just change the distance measruing entry. The distance measuring is in the for loop over `i` of the pseudo code. | You can use NLTK for this. The K-means from NLTK allows you to specify which measure of distance you want to use.
[nltk](https://www.nltk.org/) | 6,799 |
53,327,240 | I have been trying to find a way to get python to ready my `csv`. Take the values that are in the date columns (`3months | 6months | 12months`) and plot it onto a graph however I have been struggling to find resources and have no previous experience with python.
If anyone could point me in the right direction it woul... | 2018/11/15 | [
"https://Stackoverflow.com/questions/53327240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10471828/"
] | The pattern `(?!\S)` uses a negative lookahead to check what follows is not a non whitespace character.
What you could so is replace the `(?!\S)` with a word boundary `\b` to let it not be part of a larger match:
`(?i)(?<!\S)lending\s?qb\b`
[Regex demo](https://regex101.com/r/nyHoT5/1)
Another way could be to use a... | This `(?!\S)` is a forward whitespace boundary.
It is really this `(?![^\s])` a negative of a negative
with the added benefit of it matching at the EOS (end of string).
What that means is you can use the negative class form to add characters
that qualify as a boundary.
So, just put the period and comma in w... | 6,800 |
42,358,433 | I have a simple Python test code as under:
**tmp.py**
```
import time
while True:
print "New val"
time.sleep(1)
```
If I run it as below, I see the logs on terminal normally:
```
python tmp.py
```
But if I redirect the logs to a log file, it takes quite a while before the logs appear in the file:
```
... | 2017/02/21 | [
"https://Stackoverflow.com/questions/42358433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2091948/"
] | The best option for your case is to set the environment variable `PYTHONUNBUFFERED`.
This is a little more robust than calling `#/usr/bin/python -u`, as this may not work in some virtual envs.
In your terminal:
```
export PYTHONUNBUFFERED=1
python tmp.py >/tmp/logs.log 2>&1 #or however else you want to call your sc... | The issue is that the output is buffered, that means python saves the output in a buffer and flushes it every now and then, but not necessarily after each print.
You could fix by forcing a flush after each print by explicitly calling `sys.stdout.flush()`.
```
import time
import sys
while True:
print "New val"
... | 6,805 |
65,700,886 | My experience in python is close to 0, bear with me.
I want to install <https://pypi.org/project/locuplot/> on an EC2 machine to create some plots after running Locust in headless mode.
However, I do not manage to install it:
```
yum update -y
yum install python3 -y
yum install python3-devel -y
yum install python3-p... | 2021/01/13 | [
"https://Stackoverflow.com/questions/65700886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11868615/"
] | You have
```
pip install locuplot
```
in your last line, but `locuplot` does only work with python3 and, depending on your setup, `pip` might default to the python2 installation, so you should do
```
pip3 install locuplot
```
instead | Thanks to FlyingTeller found the issue.
The reason is that it requires python>=3.8
```
amazon-linux-extras install python3
python3.8 -m pip install locuplot
pip install locuplot
``` | 6,806 |
29,166,538 | From what I read about variable scopes and importing resource files in [robotframework doc](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#id487) i would expect this to work (python 2.7, RF 2.8.7):
Test file:
```
*** Settings ***
Resource VarRes.txt
Suite Setup Precondit... | 2015/03/20 | [
"https://Stackoverflow.com/questions/29166538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4629534/"
] | The following works for me:
JavaScript:
```
// Traian Băsescu encodes to VHJhaWFuIELEg3Nlc2N1
var base64 = btoa(unescape(encodeURIComponent( $("#Contact_description").val() )));
```
PHP:
```
$utf8 = base64_decode($base64);
``` | The problem is that Javascript strings are encoded in UTF-16, and browsers do not offer very many good tools to deal with encodings. A great resource specifically for dealing with Base64 encodings and Unicode can be found at MDN: <https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decodin... | 6,807 |
26,013,487 | I need to change the path of the python's core dump file, or completely disable it. I'm aware that it's possible to change the pattern and location of the core dumps in linux using:
```
/proc/sys/kernel/core_pattern
```
But this is not a suitable solution on a shared server and/or on a grid engine.
So, how can I c... | 2014/09/24 | [
"https://Stackoverflow.com/questions/26013487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536294/"
] | You can use shell command `ulimit` to control it:
```
ulimit -c 0 # Disable core file creation
```
Without the value, it will print current limit (the maximum size of core file will be created):
```
ulimit -c
``` | I think, this page gives you what you are looking for:
<http://sigquit.wordpress.com/2009/03/13/the-core-pattern/>
Quoting from the page:
>
> "...the kernel configuration includes a file named “core\_pattern”:
>
>
>
>
```
/proc/sys/kernel/core_pattern
```
>
> In my system, that file contains just this sin... | 6,808 |
56,863,556 | I want to convert Binary Tree into Array using Python and i don't know how to give index to tree-node?
I have done this using the formula
left\_son=(2\*p)+1;
and right\_son=(2\*p)+2; in java But i'm stuck in python. Is there any Function to give index to tree-node in python ? | 2019/07/03 | [
"https://Stackoverflow.com/questions/56863556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8627333/"
] | You can represent a binary tree in python as a one-dimensional list the exact same way.
For example if you have at tree represented as:
```
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15]
```
`0` is the root
`1` & `2` are the next level
the children of `1` & `2` are `[3, 4]` and `[5, 6]`
This corresponds... | Incase of a binary tree, you'll have to perform a level order traversal. And as you keep traversing, you'll have to store the values in the array in the order they appear during the traversal. This will help you in restoring the properties of a binary tree and will also maintain the order of elements. Here is the code ... | 6,809 |
45,804,534 | I'm trying to load Parquet data into `PySpark`, where a column has a space in the name:
```
df = spark.read.parquet('my_parquet_dump')
df.select(df['Foo Bar'].alias('foobar'))
```
Even though I have aliased the column, I'm still getting this error and error propagating from the `JVM` side of `PySpark`. I've attached... | 2017/08/21 | [
"https://Stackoverflow.com/questions/45804534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1922392/"
] | Have you tried,
```py
df = df.withColumnRenamed("Foo Bar", "foobar")
```
When you select the column with an alias you're still passing the wrong column name through a select clause. | I tried @ktang 's method and it worked for me as well. I'm working with SQL and Python, so it may be different for you, but it worked nonetheless.
Ensure there are no spaces in your column names/headers. Despite the list of characters provided in the error message, space ( ) doesn't seem to be acceptable by Pyspark.
... | 6,810 |
20,862,510 | How do you determine if an incoming url Request to an Openshift app is 'http' or 'https'? I wrote an Openshift python 3.3 app back in June '13. I was able to tell if the incoming url to my Openshift app was 'http' or 'https' by the following code:
```
if request['HTTP_X_FORWARDED_PROTO'] == 'https': #do something
... | 2013/12/31 | [
"https://Stackoverflow.com/questions/20862510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1924325/"
] | This is a bug and will be fixed.
EDIT: Opened <https://bugzilla.redhat.com/show_bug.cgi?id=1048331> to track | In the meantime I found that this works.
if request.environ['HTTP\_X\_FORWARDED\_PROTO'] == 'http': # or https | 6,811 |
32,111,279 | I want to read a pdf file in python. Tried some of the ways- PdfReader and pdfquery but not getting the result in string format. Want to have some of the content from that pdf file. is there any way to do that? | 2015/08/20 | [
"https://Stackoverflow.com/questions/32111279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4075219/"
] | [PDFminer](http://www.unixuser.org/%7Eeuske/python/pdfminer/index.html) is a tool for extracting information from PDF documents. | Does it matter in your case if file is pdf or not. If you just want to read your file as string, just open it as you would open a normal file.
E.g.-
```
with open('my_file.pdf') as file:
content = file.read()
``` | 6,812 |
56,914,592 | I have a lot of PNG images that I want to classify, using a trained CNN model.
To speed up the process, I would like to use multiple-processing with CPUs (I have 72 available, here I'm just using 4). I don't have a GPU available at the moment, but if necessary, I could get one.
**My workflow:**
1. read a figure with... | 2019/07/06 | [
"https://Stackoverflow.com/questions/56914592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11124934/"
] | Does a processing-speed or a size-of-RAMor a number-of-CPU-coresor an introduced add-on processing latency matter most?[ALL OF THESE DO:](https://stackoverflow.com/revisions/18374629/3)
--------------------------------------------------------------------------------------------------------------------------------------... | One python package I know that may help you is `joblib`. Hope it can solve your problem.
```
from joblib import Parallel, delayed
```
```
# load model
mymodel = load_model('190704_1_fcs_plotclassifier.h5')
# Define callback function to collect the output in 'outcomes'
outcomes = []
def collect_result(result):
... | 6,813 |
12,167,192 | I want to create a dict which can be accessed as:
```
d[id_1][id_2][id_3] = amount
```
As of now I have a huge ugly function:
```
def parse_dict(id1,id2,id3,principal, data_dict):
if data_dict.has_key(id1):
values = data_dict[id1]
if values.has_key[id2]
..
else:
... | 2012/08/28 | [
"https://Stackoverflow.com/questions/12167192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | You may want to consider using [`defaultdict`](http://docs.python.org/library/collections.html):
For example:
```
json_dict = defaultdict(lambda: defaultdict(dict))
```
will create a `defaultdict` of `defaultdict`s of `dict`s (I know..but it is right), to access it, you can simply do:
```
json_dict['context']['nam... | Maybe you need to have a look at multi-dimensional arrays - for example in numpy:
<http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html> | 6,815 |
50,552,153 | I have used the following code to find the last digit of sum of fibonacci numbers
```
#using python3
def fibonacci_sum(n):
if n < 2: print(n)
else:
a, b = 0, 1
sum=1
for i in range(1,n):
a, b = b, (a+b)
sum=sum+b
lastdigit=(sum)%10
print(lastdigit)
n = ... | 2018/05/27 | [
"https://Stackoverflow.com/questions/50552153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5405806/"
] | Keeping track of the last digit only
====================================
Note that whenever you add integers, the last digit of the sum depends only on the last digits of the addents. This means we only have to keep the last digit on every iteration. The same applies to the sum, at all time we only need to keep its l... | You're asking for code that returns the last digit of the sum of the first n Fibonacci numbers.
First thing to note is that fib(1) + fib(2) + ... + fib(n) = fib(n+2)-1.
That's easily proved: Let S(n) be the sum of the first n Fibonacci numbers. Then S(1) = 1, S(2) = 2, and S(n) - S(n-1) = fib(n). The result follows b... | 6,822 |
63,559,190 | I am trying to loop through the files in a folder with python. I have found different ways to do that such as using os package or glob. But for some reason, they don't maintain the order the files appear in the folder. For example, my folder has `img_10`, `img_20`, `img_30`... But when i loop through them, my code read... | 2020/08/24 | [
"https://Stackoverflow.com/questions/63559190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11446390/"
] | You need to pass the data in an `array`(`->with()` method) or you can use `compact` method too.
```php
return view('admin.faq.index', compact('faqs'));
```
Or
```php
return view('admin.faq.index')->with(array('faqs'=>$faqs));
``` | try to use the `compact` method as below:
```
public function index(Request $request)
{
$faqs = Faq::all();
return view('admin.faq.index',compact('faqs'));
}
``` | 6,823 |
36,177,019 | Okays so I'm new to python and I just really need some help with this. This is my code so far. I keep getting a syntax error and I have no idea what im doing wrong
```
count = int(input("What number do you want the timer to start: "))
count == ">" -1:
print("count")
print("")
count = count - 1
time.sleep(1)
``` | 2016/03/23 | [
"https://Stackoverflow.com/questions/36177019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5970976/"
] | You need to ensure you import the time library before you can access the time.sleep method.
Also it may be more effective to a for use a loop to repeat code. The structure of your if statement is also incorrect and is not a correct expression.
```
IF <Expression> is TRUE:
DO THIS.
```
Also consider using a ran... | In the 2nd line, you can't deduct 1 from ">" which is a string.
What you need here is apparently a for loop. EDIT: You forgot the import too!
```
import time
count = int(input("What number do you want the timer to start: "))
for i in range(count):
print("count")
print(i)
count = count - 1
time.sleep(1)... | 6,826 |
52,008,168 | I have this python code that should make a video:
```
import cv2
import numpy as np
out = cv2.VideoWriter("/tmp/test.mp4",
cv2.VideoWriter_fourcc(*'MP4V'),
25,
(500, 500),
True)
data = np.zeros((500,500,3))
for i in xrange(500):
... | 2018/08/24 | [
"https://Stackoverflow.com/questions/52008168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/325809/"
] | So it looks like you did a DBinspect on an existing database to generate this model. I'm guessing this is failing because Django ORM expects your table to have a primary key. "id" is the default name for a Django generated model primary key field. I suspect when you are trying to call `Characterweapons.objects.all()` i... | The best solution that I found, in this case, was to perform my own query, for example:
```
fact = MyModelWithoutPK.objects.raw("SELECT * FROM my_model_without_pk WHERE my_search=some_search")
```
This way you don't have to implement or add another middleware.
see more at [Django docs](https://docs.djangoproject.com... | 6,830 |
7,772,965 | I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error:
```
$ virtualenv -q --no-site-packages venv
$ pip install -E venv M2Crypto==0.20.2
Downloading/unpacking M2Crypto==0.20.2
Downloading M2Crypto-0.20.2.t... | 2011/10/14 | [
"https://Stackoverflow.com/questions/7772965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] | You just don't have `swig` installed.
**Try:**
```
sudo yum install swig
```
**And then:**
```
sudo easy_install M2crypto
``` | ```
sudo yum install m2crypto
```
worked for me to get around this problem. | 6,831 |
52,733,094 | I am using Ubuntu 16.04 lts. My default python binary is python2.7. When I am trying to install ipykernel for hydrogen in atom editor, with the following command
```
python -m pip install ipykernel
```
It is giving the following errors
```
ERROR: ipykernel requires Python version 3.4 or above.
```
I am trying to ... | 2018/10/10 | [
"https://Stackoverflow.com/questions/52733094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8881054/"
] | Starting with version 5.0 of the [kernel](https://ipykernel.readthedocs.io/en/latest/changelog.html#id3), and version 6.0 of [IPython](https://ipython.readthedocs.io/en/stable/whatsnew/version6.html#ipython-6-0), compatibility with Python 2 was dropped.
As far as I know, the only solution is to install an earlier relea... | Try using `Anaconda`
You can learn how to install Anaconda from [here](https://conda.io/docs/user-guide/install/linux.html)
After that, try creating a virtual environment via:
```
conda create -n yourenvname python=2.7 anaconda
```
And activate it via:
```
source activate yourenvname
```
After that, try insta... | 6,841 |
56,789,173 | I have a simple class in which I want to generate methods based on inherited class fields:
```
class Parent:
def __init__(self, *args, **kwargs):
self.fields = getattr(self, 'TOGGLEABLE')
self.generate_methods()
def _toggle(self, instance):
print(self, instance) # Prints correctly
... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56789173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5729960/"
] | maybe this is too hackish, and maybe there's a more elegant (i.e. dedicated) way to achieve this, but:
you can create a wrapper function that passes the func\_name to the inner `_toggle` func:
```py
class Parent:
def __init__(self, *args, **kwargs):
self.fields = getattr(self, 'TOGGLEABLE')
self.g... | Another approach to solve the same problem would be to use `__getattr__` in the following way:
```
class Parent:
def _toggle(self, instance, func_name):
print(self, instance) # Prints correctly
print(func_name)
def __getattr__(self, attr):
if not attr.startswith("toggle_"):
... | 6,842 |
39,400,319 | My opinion of the Azure-Python SDK is not high for Azure RM. What takes 1 line in PowerShell takes 10 in Python. That is the opposite of what python is supposed to do.
So, my idea is to create python package which comes with a directory containing a few template .ps1 scripts. You would define a few variables like vmna... | 2016/09/08 | [
"https://Stackoverflow.com/questions/39400319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6293857/"
] | @RobTruxal, the new CLI for Azure will be in Python and will be released as a preview soon. You can already try it from the github account:
<https://github.com/Azure/azure-cli>
The Azure SDK for Python is not supposed to mimic the Powershell cmdlets, but to be a language SDK (like C#, Java, Ruby, etc.).
If you have a... | @RobTruxal, It seems that a feasible way to call PowerShell in Python is using the module `subprocess`, such as the code below as reference.
```
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", "your-script.ps1", "arguments"])
```
You need to write your powershell ... | 6,843 |
62,295,329 | I'm trying to play an mp3 file using python VLC but it seems like nothing is happening and there is no error message. Below is the code:
```
import vlc
p = vlc.MediaPlayer(r"C:\Users\user\Desktop\python\projects\etc\lady_maria.mp3")
p.play()
```
I tried below code as I've read from another post:
```
import vlc
mp3 ... | 2020/06/10 | [
"https://Stackoverflow.com/questions/62295329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11639529/"
] | If audio files are playing fine on the system:-
for pygame library adjust volume using:
```
mixer.music.set_volume(1.0) # float value from 0.0 to 1.0 for volume setting
``` | I can't work out what the actual issue is given the code in the OP. Please try this test code.
```
import pygame
WINDOW_WIDTH = 200
WINDOW_HEIGHT = 200
### initialisation
pygame.init()
pygame.font.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
# Rain sound from: http... | 6,844 |
67,109,676 | example1.py:
```
from tkinter import *
root = Tk()
filename = 'james'
Lbl = Label(root,text="ciao")
Lbl.pack()
root.mainloop()
```
example2.py:
```
from example1 import filename
print(filename)
```
Why python open tkinter window if I run only example2.py?
It is necessary for me that filename is in the example1... | 2021/04/15 | [
"https://Stackoverflow.com/questions/67109676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9811405/"
] | **This is because the standard rules of Python**
yup! Python automatically excecutes the Python file which you imported.In Your Case its example1 file.
**To prevent This Use this instance:**
```
if __name__ == '__main__':
root.mainloop()
```
in your file [see](https://www.geeksforgeeks.org/what-does-the-... | First, I don't know how to solve your problem. but I know what you want to know.
I understand you have two python file ('example 1' and 'example 2'). And you want to import 'filename' from 'example 1'. But Tkinter is worked and you want to know why. right?
The import function is not pick-up tool.
\*\*\* That's mean ... | 6,846 |
5,249,353 | I'm learning python. I have a list of simple entries and I want to convert it in a dictionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it?
```
list = ['first_key', 'first_value', 'second_key', 'second_value']
```
Thanks in advance! | 2011/03/09 | [
"https://Stackoverflow.com/questions/5249353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619378/"
] | ```
myDict = dict(zip(myList[::2], myList[1::2]))
```
Please do not use 'list' as a variable name, as it prevents you from accessing the list() function.
If there is much data involved, we can do it more efficiently using iterator functions:
```
from itertools import izip, islice
myList = ['first_key', 'first_value... | The most concise way is
```
some_list = ['first_key', 'first_value', 'second_key', 'second_value']
d = dict(zip(*[iter(some_list)] * 2))
``` | 6,847 |
45,636,955 | I've got the following python method, it gets a string and returns an integer. I'm looking for the correct `input` that will print "Great Success!"
```
input = "XXX"
def enc(pwd):
inc = 0
for i in range(1, len(pwd) + 1):
_1337 = pwd[i - 1]
_move = ord(_1337) - 47
if i == 1:
... | 2017/08/11 | [
"https://Stackoverflow.com/questions/45636955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8451227/"
] | It's encoding the input in base 42 (starting from `chr(47)` which is `'/'`), and easy to decode:
```
def dec(x):
while x:
yield chr(47 + x % 42)
x //= 42
print ''.join(dec(0xEA9D1ED352B8))
```
The output is: `?O95PIVII` | You can try to bruteforce it.
Just make a while loop where the input is encrypted by the function until you have the same hash.
But with no informations about the length of the input and so on it could take a while. | 6,853 |
38,697,820 | I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript:
```
#!/usr/bin/python
sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" "
exec (sqoopcom)
```
I got an error, Invalid syntax, how... | 2016/08/01 | [
"https://Stackoverflow.com/questions/38697820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5312431/"
] | The build in `exec` statement that you're using is for interpreting python code inside a python program.
What you want is to execute an external (shell) command. For that you could use `call` from the **subprocess module**
```
import subprocess
subprocess.call(["echo", "Hello", "World"])
```
<https://docs.python.or... | You need to skip " on --query param
```
sqoopcom="sqoop import --direct --connect abcd --username abc --P --query \"queryname\" --target-dir /pwd/dir --m 1 --fetch-size 1000 --verbose --fields-terminated-by , --escaped-by \\ --enclosed-by '\"'/dir/part-m-00000"
``` | 6,855 |
46,225,871 | ```
x = open("file.txt",'w')
s = chr(931) # 'Σ'
x.write(s)
```
Error
```
Traceback (most recent call last):
File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u03a3' in position ... | 2017/09/14 | [
"https://Stackoverflow.com/questions/46225871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4772772/"
] | Your default encoding seems to be cp1252, not utf-8.
You need to specify the encoding, to be sure it's utf-8.
### this works fine:
```
with open('outfile.txt', 'w', encoding='utf-8') as f:
f.write('Σ')
```
### this raises your error:
```
with open('outfile.txt', 'w', encoding='cp1252') as f:
f.write('Σ')
... | I solve the problem by saving as bytes instead of string
```
def save_byte():
x = open("file.txt",'wb')
s = chr(931) # 'Σ'
s = s.encode()
x.write(s)
x.close()
```
outout:
Σ | 6,858 |
7,139,293 | I'm currently building my android project from the project folder with ant like the following:
```
MyProject/
build.xml
```
The ant command that I use to build is:
```
$ MyProject/ant install
```
In my java code, I have some unused imports and variables, for instance:
```
import java.io.IOException;
String ... | 2011/08/21 | [
"https://Stackoverflow.com/questions/7139293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/117642/"
] | You can use [PMD](http://pmd.sourceforge.net/) to do this and much more. It includes checks for both unused local variables and unused imports. It can be [integrated with ant](https://pmd.github.io/pmd-6.17.0/pmd_userdocs_tools_ant.html) and you can configure it to fail the build if any errors are detected. If you are ... | You do not have to do this if you have proguard enabled. <http://developer.android.com/guide/developing/tools/proguard.html> | 6,859 |
3,032,519 | When I was using the built-in simple server, everything is OK, the admin interface is beautiful:
`python manage.py runserver`
However, when I try to serve my application using a wsgi server with `django.core.handlers.wsgi.WSGIHandler`, Django seems to forget where the admin media files is, and the admin page is not s... | 2010/06/13 | [
"https://Stackoverflow.com/questions/3032519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225262/"
] | When I look into the source code of Django, I find out the reason.
Somewhere in the `django.core.management.commands.runserver` module, a `WSGIHandler` object is
wrapped inside an `AdminMediaHandler`.
According to the document, `AdminMediaHandler` is a
>
> WSGI middleware that intercepts calls
> to the admin med... | Django by default doesn't serve the media files since it usually is better to serve these static files on another server (for performance etc.). So, when deploying your application you have to make sure you setup another server (or virtual server) which serves the media (including the admin media). You can find the adm... | 6,860 |
72,991,013 | How can I get an input like this in python3
The first input is = 2 and based on this first input I want to get 2 get new inputs
For example:
```
2 # how many inputs?
1 2 # 2 numbers inputs
```
or
```
3 # how many inputs?
3 5 8 # in one line getting 3 inputs
```
Here is another example:
```
4
6 8 7 9
```
How ... | 2022/07/15 | [
"https://Stackoverflow.com/questions/72991013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19312041/"
] | This might be an approach:
```
<?php
$input = "1234-ABC 2345 rBC 9998DDD 9657 lJi";
preg_match_all('/(\d{4}[-\s]*[a-z]{3})/i', $input, $matches);
$output = array_shift($matches);
array_walk($output, function(&$value) {
$value = strtoupper(str_replace(" ", "", $value));
});
print_r($output);
```
The output obvi... | You regular expression `(\d{4})( *)(-*)( *)([a-zA-Z]{3})` was correct but you needed to use `preg_match_all` to return multiple matches.
This is a demo:
<https://onlinephp.io/c/e5acb>
```
<?php
function parsePlates($subject){
$plates = [];
preg_match_all('/(\d{4})( *)(-*)( *)([a-zA-Z]{3})/sim', $subject, $r... | 6,863 |
38,442,107 | I tried the following:
```
#!/usr/bin/env python
import keras
from keras.models import model_from_yaml
model_file_path = 'model-301.yaml'
weights_file_path = 'model-301.hdf5'
# Load network
with open(model_file_path) as f:
yaml_string = f.read()
model = model_from_yaml(yaml_string)
model.load_weights(weights_fi... | 2016/07/18 | [
"https://Stackoverflow.com/questions/38442107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/562769/"
] | The problem is also referenced on the [issues page](https://github.com/fchollet/keras/issues/3210) of the keras project.
You need to install a version of `pydot` <= 1.1.0 because the function `find_graphviz` was [removed](https://github.com/erocarrera/pydot/commit/bc639e76b214b1795ebd6263680ee55d9d4fca9f#diff-44fda7721... | If you have not already installed `pydot` python package - try to install it. If you have `pydot` reinstallation should help with your problem. | 6,864 |
10,782,285 | >
> **Possible Duplicate:**
>
> [How to generate all permutations of a list in Python](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python)
>
>
>
I am given a list `[1,2,3]` and the task is to create all the possible permutations of this list.
Expected output:
```
... | 2012/05/28 | [
"https://Stackoverflow.com/questions/10782285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1407910/"
] | [itertools.permutations](http://docs.python.org/library/itertools.html#itertools.permutations) does this for you.
Otherwise, a simple method consist in finding the permutations recursively: you successively select the first element of the output, then ask your function to find all the permutations of the remaining ele... | this is a rudimentary solution...
the idea is to use recursion to go through all permutation and reject the non valid permutations.
```
def perm(list_to_perm,perm_l,items,out):
if len(perm_l) == items:
out +=[perm_l]
else:
for i in list_to_perm:
if i not in ... | 6,865 |
35,042,340 | I am using [Backbone.LocalStorage](https://github.com/jeromegn/Backbone.localStorage) plugin with backbone app. It is working fine in chrome and safari however, it is giving me below error in firefox.
>
> DOMException [SecurityError: "The operation is insecure."
> code: 18
> nsresult: 0x80530012
> location: <http:... | 2016/01/27 | [
"https://Stackoverflow.com/questions/35042340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1136062/"
] | Make sure Firefox has cookies enabled.
The setting can be found under Menu/Options/Privacy/History
In the dropdown, select either 'Remember History' or if You prefer use custom settings for history, but select option Accept cookies from sites
Hope it helps. | Make sure your domains are same. verify [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) which means same domain, subdomain, protocol (http vs https) and same port.
[What is Same Origin Policy?](http://en.wikipedia.org/wiki/Same_origin_policy)
[How does pushState protect against potential conte... | 6,866 |
54,204,181 | I am trying to set the return value of a `get` request in python in order to do a unit test, which tests if the `post` request is called with the correct arguments. Assume I have the following code to test
```
# main.py
import requests
from django.contrib.auth.models import User
def function_with_get():
client =... | 2019/01/15 | [
"https://Stackoverflow.com/questions/54204181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7226268/"
] | I think you almost have it, except you're missing the return value for `session()` - because `session` is instantiated to create the `client` instance. I think you can drop the `[0]` too.
Try:
```
mock_sess**.return\_value.**get.return_value.content = 'User1'
``` | Try with .text because this should work for strings.
```
s = requests.Session()
s.get('https://httpbin.org/cookies/ set/sessioncookie/123456789')
r = s.get('https://httpbin.org/ cookies')
print(r.text)
```
<http://docs.python-requests.org/en/master/user/advanced/> | 6,872 |
37,932,363 | So I need to make this plot in python. I wish to remove my legend's border. However, when I tried the different solutions other posters made, they were unable to work with mine. Please help.
**This doesn't work:**
```
plt.legend({'z$\sim$0.35', 'z$\sim$0.1','z$\sim$1.55'})
plt.legend(frameon=False)
```
---
```
plt... | 2016/06/20 | [
"https://Stackoverflow.com/questions/37932363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6491230/"
] | It's very strange because the command :
```
plt.legend(frameon=False)
```
Should work very well.
You can also try this command, to compare :
```
plt.legend(frameon=None)
```
You can also read the documentation on this page about [plt.legend](http://matplotlib.org/api/legend_api.html)
I scripted something as exam... | Try this if you want to draw only one plot (without subplot)
```
plt.legend({'z$\sim$0.35', 'z$\sim$0.1','z$\sim$1.55'}, frameon=False)
```
It is enough one plt.legend. The second one rewrites the first one. | 6,873 |
69,364,940 | The text is like "1-2years. 3years. 10years."
I want get result `[(1,2),(3),(10)]`.
I use python.
I first tried `r"([0-9]?)[-]?([0-9])years"`. It works well except for the case of 10. I also tried `r"([0-9]?)[-]?([0-9]|10)years"` but the result is still `[(1,2),(3),(1,0)]`. | 2021/09/28 | [
"https://Stackoverflow.com/questions/69364940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10490005/"
] | You need to listen for click event on newly added element. hence added a click listener on **newSpan** element after adding it into DOM.
You are listening for event for removeLists element only but when you add a new element in the DOM, the newly doesn't have the click event. Hence, we have to listen for the event exp... | Please change some code.
Please add remove event function to listItemMake() function.
```js
const toDoInput = document.querySelector("input");
const addButton = document.querySelector("button");
const listParent = document.querySelector("ul");
const listItemMake = () => {
if (toDoInput.value !== "") {
const new... | 6,875 |
8,948,034 | I want to retrieve and work with basic Vimeo data in python 3.2, given a video's URL. I'm a newcomer to JSON (and python), but it looked like the right fit for doing this.
1. Request Vimeo video data (via an API-formatted .json URL)
2. Convert returned JSON data into python dict
3. Display dict keys & data ("id", "tit... | 2012/01/20 | [
"https://Stackoverflow.com/questions/8948034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73807/"
] | This works for me:
```
import urllib.request, json
response = urllib.request.urlopen('http://vimeo.com/api/v2/video/31161781.json')
content = response.read()
data = json.loads(content.decode('utf8'))
```
Or with Requests:
```
import requests
data = requests.get('http://vimeo.com/api/v2/video/31161781.json').json(... | Check out: <http://www.voidspace.org.uk/python/articles/urllib2.shtml>
```
>>> import urllib2
>>> import json
>>> req = urllib2.Request("http://vimeo.com/api/v2/video/31161781.json")
>>> response = urllib2.urlopen(req)
>>> content_string = response.read()
>>> content_string
'[{"id":31161781,"title":"Kevin Fanning talk... | 6,883 |
48,117,638 | I would like to know how to have setup.py install c modules locally. Locally as in not in `/usr/local/python..` and not in `~/local/python...`, but in `[where_all_my_code_is]/bin` and I can import it from scripts within the [where\_all\_my\_code\_is] folder.
I have some c code. src/foo/foo.c
```
#include <Python.h>
s... | 2018/01/05 | [
"https://Stackoverflow.com/questions/48117638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2886575/"
] | Here is one option:
setup using
```
$ python3 setup.py install --root . --install-lib lib
```
add local `lib` path to the python path
```
$ export PYTHONPATH:$PYTHONPATH:./lib
```
Now python scripts in `.` can import the `c` modules we just compiled.
Something fancier would need to be used for the exact scenari... | you would have to create custom package for the type of os you are using, deb or rpm or ebuild these system level tools install files into /usr/bin and /usr/lib instead of your local builds which go to /usr/local or user builds ~/local. | 6,888 |
37,955,984 | I don't have a clue what's causing this error. It appears to be a bug that there isn't a fix for. Could anyone tell give me a hint as to how I might get around this? It's frustrating me to no end. Thanks.
```
Operations to perform:
Apply all migrations: admin, contenttypes, optilab, auth, sessions
Running migrations... | 2016/06/21 | [
"https://Stackoverflow.com/questions/37955984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2075859/"
] | This appears to be the line that's causing the errror:
```
INSERT INTO "optilab_lasersubstrate" () SELECT FROM "optilab_lasersubstrate__old";
```
You are usually expected to have a list of columns in those parenthesis. Eg `INSERT INTO "optilab_lasersubstrate" (col1,col2,etc)` however the migration has produced a b... | Edit base.py in the lines that breaks and update it to:
```
def execute(self, query, params=None):
if params is None:
if '()' not in str(query):
return Database.Cursor.execute(self, query)
query = self.convert_query(query)
if '()' not in str(query):
return Database.Cursor.execut... | 6,889 |
33,281,217 | I'm crawling through a simple, but long HTML chunk, which is similar to this:
```html
<table>
<tbody>
<tr>
<td> Some text </td>
<td> Some text </td>
</tr>
<tr>
<td> Some text
<br/>
Some more text
</td>
</tr>
</tbody>
</table>
```
I'm collect... | 2015/10/22 | [
"https://Stackoverflow.com/questions/33281217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256965/"
] | Because `<br/>` is a self-closing tag, it does not have any `text` content. Instead, you need to access it's `tail` content. The `tail` content is the content after the element's closing tag, but before the next opening tag. To access this content in your for loop you will need to use the following:
```
for element in... | To me below is working to extract all the text after `br`-
```
normalize-space(//table//br/following::text()[1])
```
**Working example is** [**at**](http://www.xpathtester.com/xpath/283dca20a024adbb5ece93de6c914531). | 6,890 |
30,975,911 | I have a python list of list as follows. I want to flatten it to a single list.
```
l = [u'[190215]']
```
I am trying.
```
l = [item for value in l for item in value]
```
It turns the list to `[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']`
How to remove the `u` from the list. | 2015/06/22 | [
"https://Stackoverflow.com/questions/30975911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567797/"
] | The `u` means a [`unicode`](https://docs.python.org/2/howto/unicode.html) string which should be perfectly fine to use.
But if you want to convert `unicode` to `str` (which just represents plain bytes in Python 2) then you may `encode` it using a character encoding such as `utf-8`.
```
>>> items = [u'[190215]']
>>> [i... | You can convert your unicode to normal string with `str` :
```
>>> list(str(l[0]))
['[', '1', '9', '0', '2', '1', '5', ']']
``` | 6,891 |
43,201,211 | I hope you can help.
I am currently writing a code to extract historical data for various games on SteamSpy.com. After backing the project on Patreon, you get to view the long history of various metrics for each game. I would like to make comparisons between multiple games, and as such I want to extract the data.
I k... | 2017/04/04 | [
"https://Stackoverflow.com/questions/43201211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3494191/"
] | You could try
```
SELECT
REPLACE(CONVERT(VARCHAR(11), Date, 6), ' ', '/') + ' 12:00:00 AM' AS Date
FROM
TableFiles
``` | just an idea: select convert(**date**, yourvalue ) + 0.5) .... should use only date part and add an half day? | 6,900 |
65,160,481 | I'm trying to install neovim on Windows and import my previous init.vim file.
I've previously defined my snippets in ultisnips.
I'm using windows and ahve tested this in another version of windows and it works, however, at the moment when I run
```
:checkhealth
```
I get the following error:
```
## Python 3 provide... | 2020/12/05 | [
"https://Stackoverflow.com/questions/65160481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427492/"
] | **Make sure you have Python3 installed, the following answer also works with Python2.**
Check for help:
```
:help provider-python
```
Go to the `PYTHON QUICKSTART` and you will see one of this two options:
* For Python 2 plugins:
* For Python 3 plugins:
*Because you're problem is with python 3 follow this steps t... | It seems, that neovim is confusing python 2 and python 3 somehow. For me it worked just to have renamed python executable in PATH of python 2, that is python.exe -> python2.exe, and now it seems to work fine. However it is maybe not the perfect solution. | 6,901 |
69,700,550 | Shown below is the code from my launch.json file for my Flask application. I have various environment variables defined in the `"env": {}` portion. However, when I run my Flask application from the run.py script, it doesn't seem to recognize the variables. Although the `"FLASK_DEBUG"` is set to `"1"`, the application s... | 2021/10/24 | [
"https://Stackoverflow.com/questions/69700550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16425143/"
] | This is very inefficient\*, but it meets your requirements:
```ml
let transpose (matrix : List<List<_>>) =
[
if matrix.Length > 0 then
assert(matrix |> List.distinctBy List.length |> List.length = 1)
for i = 0 to matrix.[0].Length - 1 do
yield [
f... | For better performance, you can convert the list of list to an Array2D, and then create your transposed list from the Array2D.
```
let transpose' xss =
let xss = array2D xss
let dimx = Array2D.length1 xss - 1
let dimy = Array2D.length2 xss - 1
[ for y=0 to dimy do [
for x=0 to dimx do
... | 6,906 |
64,768,621 | Hello I am new into python . practicing web scraping with some demo sites .
I am trying to scrape this website <http://books.toscrape.com/> and want to extract
1. href
2. name/title
3. start rating/star-rating
4. price/price\_color
5. in-stock availbility/instock availability
i written a basic code which goes to each... | 2020/11/10 | [
"https://Stackoverflow.com/questions/64768621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13597511/"
] | It's for folders that are added in you .proj file, but doesn't exist on a hard drive.
My guess is that you are using some kind of version control (git or svn or else) and someone made change to project structure (added folder) but forgot to add that folder to version control system. | For me red cross appeared on all projects because while cloning component from git/stash, most of the files and folder path were too long and are not acceptable.
Tried cloning at different path which is smaller and red crosses disappeared. | 6,907 |
17,055,642 | I was wondering if there is already available a library which does something similar to scrapely
<https://github.com/scrapy/scrapely>
WHat it does is that you give an example url and then you give the data you want to extract from that html..
```
url1 = 'http://pypi.python.org/pypi/w3lib/1.1'
data = {'name': 'w3lib ... | 2013/06/11 | [
"https://Stackoverflow.com/questions/17055642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/902885/"
] | The likeliest problem is that you're using backslashes in your file name, so they get interpreted as control characters. The IO error is because the filename is mangled.
try
```
stockPath = "C:\\Users\\Dryan\\Desktop\\table.csv" # double slashes to get single slashes in the string
```
or
```
stockPath = "C:/Use... | As joojaa said, try to avoid using backslashes when you can. I try to always convert any incoming path to a forward slashes version, and just before outputting it I normalize it using os.path.normpath.
```
clean_path = any_path_i_have_to_deal_with.replace("\\", "/")
# do stuff with it
# (concat, XML save, assign to ... | 6,908 |
68,728,817 | I need some help with respect to changing a dataframe in python.
```
NODE SIGNAL-STRENGTH LOCATION
0 A 76 1
1 A 78 1
2 A 78 1
3 A 79 1
4 A 79 2
5 A ... | 2021/08/10 | [
"https://Stackoverflow.com/questions/68728817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14548962/"
] | You can do it with a `FULL` join of the tables:
```
SELECT COALESCE(a.name, b.name) AS name,
CASE WHEN a.name IS NULL THEN false ELSE true END AS is_in_A,
CASE WHEN b.name IS NULL THEN false ELSE true END AS is_in_B
FROM a FULL OUTER JOIN b
ON b.name = a.name
```
If your database does not support boole... | You can use `union all` and aggregation:
```
select name, sum(in_a), sum(in_b)
from ((select name, 1 as in_a, 0 as in_b
from a
) union all
(select name, 0, 1
from b
)
) ab
group by name;
``` | 6,909 |
63,156,890 | I'm really new to coding and after learning all the syntax for HTML and CSS I figured I'd move on to python but I'd actually learn how to use it to become a python programmer instead of just learning the syntax
So as one of my first small projects I figured id make a small piece of code that'd ask the user for some it... | 2020/07/29 | [
"https://Stackoverflow.com/questions/63156890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14016707/"
] | I recommend searching about the python basics and loops
This will make it
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'coo... | Is this what you want?
```
# items and their prices
items = {'banana': 3,
'apple': 2,
'milk': 12,
'bread': 15,
'orange': 3,
'cheese': 14,
'chicken': 42,
'peanuts':32 ,
'butter': 20,
'cooldrink': 18,
}
price = 0
while True:
... | 6,910 |
22,567,083 | I'm trying to run this simple example I found [here](https://groups.google.com/forum/#!msg/pyqtgraph/haiJsGhxTaQ/sTtMa195dHsJ), on MacOS X with Anaconda python.
```
import pyqtgraph as pg
import time
plt = pg.plot()
def update(data):
plt.plot(data, clear=True)
class Thread(pg.QtCore.QThread):
newData = pg.Q... | 2014/03/21 | [
"https://Stackoverflow.com/questions/22567083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2585497/"
] | The `pyqtgraph.plot` method seems buggy to me (anyway, I wasn't able to get it to produce any useful output, but maybe I'm doing something wrong).
However, if I create a `PlotWidget` and set up the application "manually", it all works as expected:
```
import pyqtgraph as pg
import numpy as np
import time
app = pg.Qt... | When you call `QThread.start()`, that function returns immediately. What happens is,
1. Thread #1 - creates new thread, #2
2. Thread #2 is created
3. Thread #1 regains control and runs.
4. Thread #1 dies or `thread` variable is cleaned up by GC (garbage collector) - I'm assuming the 2nd scenario should not happen
To ... | 6,918 |
11,466,909 | ```
node helloworld.js alex
```
I want it to console.log() alex. How do I pass "alex" as an argument into the code?
In python ,it is `sys.argv[1]` | 2012/07/13 | [
"https://Stackoverflow.com/questions/11466909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179736/"
] | You can access command line arguments using `process.argv` in node.js.
The array also includes the node command and the application file, so the first custom command line argument will have an index = 2.
```
process.argv[2] === 'alex'; // true
```
<http://nodejs.org/api/process.html#process_process_argv> | If your requirements are more complex and you can take advantage of a command line argument parser, there are several choices. Two that seem popular are
* <https://www.npmjs.org/package/minimist> (simple and minimal)
* <https://www.npmjs.org/package/nomnom> (option parser with generated usage and commands)
More optio... | 6,921 |
55,400,056 | I have two lists of dicts: `list1` and `list2`.
```
print(list1)
[{'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'bard', 'desc': 'besd', 'city': 2, 'ID': 1},
{'name': 'baer', 'desc': 'bees', 'city': 2, 'ID': 1},
{'name': 'aaaa', 'desc': 'bnbb', 'city': 1, 'ID': 2},
{'name': 'cgcc', 'desc': 'dgdd', ... | 2019/03/28 | [
"https://Stackoverflow.com/questions/55400056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10095977/"
] | You can use [`itertools.product`](https://docs.python.org/3.7/library/itertools.html#itertools.product) and `filter`:
```
from itertools import product
list1 = [{'name': 'fooa', 'desc': 'bazv', 'city': 1, 'ID': 1},
{'name': 'bard', 'desc': 'besd', 'city': 2, 'ID': 1},
{'name': 'baer', 'desc': 'bees'... | Having nested loops is not "not pythonic". However, you can achieve the same result with a list comprehension. I don't think it's more readable though:
```
[(i, j) for j in list2 for i in list1 if i['ID'] == j['ID'] and i['city'] == j['city']]
``` | 6,922 |
3,824,373 | I am quite new at python and regex so please bear with me.
I am trying to read in a file, match a particular name using a regex while ignoring the case, and store each time I find it. For example, if the file is composed of `Bill bill biLl biLL`, I need to store each variation in a dictionary or list.
Current code:
``... | 2010/09/29 | [
"https://Stackoverflow.com/questions/3824373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461063/"
] | I'd use findall:
```
re.findall(r'bill', open(filename).read(), re.I)
```
Easy as pie:
```
>>> s = 'fooBiLL bill BILL bIlL foo bar'
>>> import re
>>> re.findall(r'bill', s, re.I)
['BiLL', 'bill', 'BILL', 'bIlL']
``` | I think that you want [re.findall](http://localhost/docs/python-2.7-docs-html/library/re.html#re.findall). This is of course available on the compiled regular expression as well. The particular error code that you are getting though, would seem to indicate that you are [not matching your pattern](http://localhost/docs/... | 6,925 |
65,890,917 | I would like to obtain a nested dictionary from a string, which can be split by delimiter, `:`.
```
s='A:B:C:D'
v=['some','object']
desired={'A':{'B':{'C':{'D':v}}}}
```
Is there a "pythonic" way to generate this? | 2021/01/25 | [
"https://Stackoverflow.com/questions/65890917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12844579/"
] | Hmmm . . . You want the most recent value from the `tracker` table. Then compare that to the existing values and insert where there are differences:
```
INSERT INTO Tracker (customer_id, value, date_of_value)
SELECT v.customer_id, v.value, GETDATE()
FROM (SELECT v.*,
ROW_NUMBER() OVER (PARTITI... | We can create a trigger on the main table to insert a new row into the tracker table:
```sql
CREATE TRIGGER trg_Tracking
ON MainTable
AFTER INSERT, UPDATE AS
IF (NOT UPDATE(value) OR NOT EXISTS
(SELECT customer_id, value FROM inserted
EXCEPT
SELECT customer_id, value FROM deleted))
RETURN; -- e... | 6,926 |
72,366,129 | I want to reach a document, but I always get this error:
**FileNotFoundError: [Errno 44] No such file or directory: 'dbs/school/students.ini' )**
I've tried putting "/" or "./" before the dbs, but it doesn't work, so I want to know how can I reach that document, the dbs folder is in the same directory where I run the... | 2022/05/24 | [
"https://Stackoverflow.com/questions/72366129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19059715/"
] | Probably you need to add the file to your paths in your html code like:
```
<py-env>
- paths:
- dbs/school/students.ini
</py-env>
```
This way it should be added to your python environment. | i had the same issue, the solution i found was to insert my file into a github public branch and get the link from my github file, the code is below:
```
from pyodide.http import open_url
url_content = open_url('https://raw.githubusercontent.com/')
```
to know more about it read
<https://pyodide.org/en/stable/usage... | 6,927 |
22,489,243 | I'm writing tutorial about "advanced" regular expressions for Python,
and I cannot understand
```
lastindex
```
attribute. Why is it always 1 in the given examples:
<http://docs.python.org/2/library/re.html#re.MatchObject.lastindex>
I mean this example:
```
re.match('((ab))', 'ab').lastindex
```
Why is it 1? Se... | 2014/03/18 | [
"https://Stackoverflow.com/questions/22489243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1377803/"
] | `lastindex` is the index of the last group that matched. The examples in the documentation include one that uses 2 capturing groups:
```
(a)(b)
```
where `lastindex` is set to 2 as the last capturing group to match was `(b)`.
The attribute comes in handy when you have optional capturing groups; compare:
```
>>> re... | In regex groups are captured using `()`. In python `re` the `lastindex` holds the last capturing group.
Lets see this small code example:
```
match = re.search("(\w+).+?(\d+).+?(\W+)", "input 123 ---")
if match:
print match.lastindex
```
In this example, the output will be 3 as I have used three `()` in my rege... | 6,928 |
12,059,852 | I am new to python or coding , so please be patient with my question,
So here's my busy XML
```
<?xml version="1.0" encoding="utf-8"?>
<Total>
<ID>999</ID>
<Response>
<Detail>
<Nix>
<Check>pass</Check>
</Nix>
<MaxSegment>
<Status>V</Status>
... | 2012/08/21 | [
"https://Stackoverflow.com/questions/12059852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/918460/"
] | Figured it out, add the `UIPopoverController` delegate in addition to the `UISplitViewControllerDelegate`:
```c
//Sent when switching to portrait
- (void)splitViewController:(UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopov... | When you get that first delegate notification, you're passed a reference to the UIPopoverController that will present the hidden view controller. Register as its delegate, then use the [`-popoverControllerDidDismissPopover:`](http://developer.apple.com/library/ios/documentation/uikit/reference/UIPopoverControllerDelega... | 6,929 |
50,107,263 | I have the following dataframe:
```
0 1 2 3 4
0 1.JPG NaN NaN NaN NaN
1 2883 2957.0 3412.0 3340.0 miscellaneous
2 3517 3007.0 4062.0 3371.0 miscellaneous
3 5678 3158.0 6299.0 3423.0 miscellaneous
4 ... | 2018/04/30 | [
"https://Stackoverflow.com/questions/50107263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4663377/"
] | You can use:
```
for n,g in df.assign(grouper = df['0'].where(df['1'].isnull())
.ffill().astype('category'))\
.dropna().groupby('grouper'):
g.drop('grouper', axis=1).to_csv(n+'.csv', header=None, index=False)
```
***Note:*** used astype('category') to pickup tha... | ```
# program splits one big csv file into individiual image csv 's
import pandas as pd
import numpy as np
df = pd.read_csv('results.csv', header=None)
#df1 = df.replace(np.nan, '1', regex=True)
print(df)
for n,g in df.assign(grouper = df[0].where(df[1].isnull())
.ffill().astype... | 6,930 |
36,243,814 | I noticed this while playing around with graph\_tool. Some module attributes only seem to be available when run from ipython. The simplest example (example.py)
```
import graph_tool as gt
g = gt.Graph()
gt.draw.sfdp_layout(g)
```
Runs without error from ipython using `run example.y', but from the command line,`pyth... | 2016/03/27 | [
"https://Stackoverflow.com/questions/36243814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1308706/"
] | based on comments:
if you are attempting to create a database programmatically, you can't use a connection to an unborn database, so in this situation you must open a connection to `master` database, something like that:
```
"Server = localhost; Database = master; User Id = 123; Password = abc;"
``` | ```
String str;
SqlConnection myConn = new SqlConnection("Server=localhost;User Id = 123; Password = abc;database=master");
str = "CREATE DATABASE database1";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.Exec... | 6,931 |
2,125,612 | I'm building my first python app on app-engine and wondering if I should use Django or not.
What are the strong points of each? If you have references that support your answer, please post them. Maybe we can make a wiki out of this question. | 2010/01/24 | [
"https://Stackoverflow.com/questions/2125612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16628/"
] | Aral Balkan wrote [a really nice piece](http://aralbalkan.com/1313) addressing this very question. Its a year or so old, so take it with a grain of salt - I think that a lot more emphasis should be put on the awesomeness of django's Object-Relational-Model. Basically, IMHO, it all comes down to whether or not you have ... | If it's not a small project, I try to use Django. You can use the App Engine Patch (<http://code.google.com/p/app-engine-patch/>). However, the ORM cannot use Django's meaning your models.py will still be using GAE's Datastore.
One of the advantages of using Django on GAE is session management. GAE does not have a bui... | 6,932 |
72,297,725 | On my OSX M1 Mac I have the following keyring setup which works with Google Artifact Repository to resolve dependencies when using python on the command line shell.
Refer to <https://cloud.google.com/artifact-registry/docs/python/store-python>
```
$ keyring --list-backends
keyring.backends.chainer.ChainerBack... | 2022/05/19 | [
"https://Stackoverflow.com/questions/72297725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78000/"
] | Based on your description, I suppose you have successfully set up the Python virtual environment (venv) and installed all the dependencies via the terminal (Step 1-4 in <https://cloud.google.com/artifact-registry/docs/python/store-python>). And you want PyCharm also run your Python codes using that virtual environment.... | It's basically the same as what you found already on your link but you missed the following site :)
1. Setup service account with `roles/artifactregistry.writer` rights
2. Create key file (json file with your credentials) using `gcloud iam service-accounts keys create FILE_NAME.json --iam-account=SERVICE_ACCOUNT_NAME@... | 6,933 |
12,790,065 | When I use the python Sybase package, and do a cursor fetch(), one of the columns is a datetime - in the sequence returned, it has a DateTimeType object for this value.
I can find it is in the sybasect module but can't find any documentation for this datatype.
I would like to be able to convert it to a string output - ... | 2012/10/08 | [
"https://Stackoverflow.com/questions/12790065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1133237/"
] | I think this is what are you looking for
```
$db = Zend_Db::factory( ...options... );
$select = $db->select()
->from(array('org' => 'orgTable'),
array(
'orgid' => 'org.orgid',
'role' =>'org.role',
'userid' =>'... | Here is a `Zend_Db_Select` that returns the result you are looking for.
```
$select = $db->select()
->from(array('org' => 'orgTable'), array('orgid', 'role'))
->join(array('user' => 'userTable'), 'org.userid = user.userid', array('userid', 'firstname'))
->where('o... | 6,934 |
36,331,946 | I installed Linux Mint as Virtual Machine.
When I do:
```
python --version
```
I get:
```
Python 2.7.6
```
I installed seperate python folder acording to [this](http://www.experts-exchange.com/articles/18641/Upgrade-Python-2-7-6-to-Python-2-7-10-on-Linux-Mint-OS.html).
and When I do:
```
python2.7 --version
```... | 2016/03/31 | [
"https://Stackoverflow.com/questions/36331946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1712099/"
] | mPDF uses autosizing tables and this influences, among other things, the font-size as well. When outputting tables with mPDF you need to set:
```
<table style="overflow: wrap">
```
on every table according to this [answer](https://stackoverflow.com/questions/23760018/mpdf-font-size-not-working).
You can set font-s... | kindly use
```
$mpdf->keep_table_proportions = false;
``` | 6,936 |
62,264,821 | Here is my [python](/questions/tagged/python "show questions tagged 'python'") code:
```py
while exit:
serialnumber = int(input("serial number of product :"))
try:
if len(str(serialnumber)) == 6:
break
else:
print("serial number cant be used")
serialnumber = int... | 2020/06/08 | [
"https://Stackoverflow.com/questions/62264821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13653559/"
] | You don't need to do any math manually. Simply declare a `DIBSECTION` variable, and then pass a pointer to it to `GetObject()` along with `sizeof()` as the size of that variable, eg:
```
DIBSECTION dib;
GetObject(hBitmap, sizeof(dib), &dib);
``` | I took out a piece of paper and added up everything myself.
A `DIBSECTION` contains 5 parts.
```
typedef struct tagDIBSECTION {
BITMAP dsBm;
BITMAPINFOHEADER dsBmih;
DWORD dsBitfields[3];
HANDLE dshSection;
DWORD dsOffset;
} DIBSECTION, *LPDIBSECTION, *PDIBSECTION;
... | 6,937 |
62,563,923 | This seems really basic but I can't seem to figure it out. I am working in a Pyspark Notebook on EMR and have taken a pyspark dataframe and converted it to a pandas dataframe using `toPandas()`.
Now, I would like to save this dataframe to the local environment using the following code:
```
movie_franchise_counts.to_c... | 2020/06/24 | [
"https://Stackoverflow.com/questions/62563923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13136602/"
] | Your not passing anything to updateSettings `google.script.run.updateSettings();`>
I would do it like this:
```
<input type = "button" value="Submit" onClick="google.script.run.updateSettings(this.parentNode);" />
```
I'm running this as a dialog and it runs okay now. I added values to the radio buttons and now th... | Got it to work. The secret was needed to just JSON to properly store the form input criteria.
**CODE**
```
function updateSettings(formObject) {
var uiForm = SpreadsheetApp.getUi();
JSON.stringify(formObject);
var formText = formObject.formQ1;
var formRadio = formObject.formQ2;
if (formR... | 6,938 |
72,688,811 | I tried to implement the binary tree program in python. I want to add one more function to get the level of a specific node.
eg:-
```
10 # level 0
/ \
5 15 # level 1
/ \
3 7 # level 2
```
if we search the level of node 3, it should return
```
class BinaryTree:
def __init__(self, d... | 2022/06/20 | [
"https://Stackoverflow.com/questions/72688811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14931124/"
] | If by "simplify", you mean "shorten", then this is as good as it gets:
```
public get isUsersLimitReached(): boolean {
return !this.isAdmin && usersCount >= this.max_users;
}
```
Other than that, there's really not much to work with here. | A user limit is reached only if the user is not admin and count exceeds.
```
public get isUsersLimitReached(): boolean {
return !this.isAdmin && usersCount >= this.max_users;
}
``` | 6,939 |
67,775,753 | This is extended question to [Can we send data from Google cloud storage to SFTP server using GCP Cloud function?](https://stackoverflow.com/questions/67772938/can-we-send-data-from-cloud-storage-to-sftp-server-using-gcp-cloud-function)
```py
with pysftp.Connection(host=myHostName, username=myUsername,
... | 2021/05/31 | [
"https://Stackoverflow.com/questions/67775753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452168/"
] | For google, there is a formula googlefinance. For yahoo, all datas are imported in the code source within a big json you can fetch by this way
```
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString)
``... | See formula GOOGLEFINANCE in Google Sheets. It's not totally live (about 20 minutes delay) but for many purposes is enough. I use it mostly for currency exchange rates but there far more options:
<https://support.google.com/docs/answer/3093281?hl=en>
Yahoo Finance and most of live sites are protected against webscrap... | 6,940 |
46,282,656 | I have a test project that looks like this:
```
_ test_project
├- __init__.py
├- main.py
└- output.py
```
`__init__.py` is empty, and the other two files look like this:
```
# main.py
from . import output
```
and
```
# output.py
print("hello world")
```
I would like to import `output.py` just for the side effe... | 2017/09/18 | [
"https://Stackoverflow.com/questions/46282656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5203563/"
] | Relative imports can only be performed in a package. So, run the code as a package.
```
$ cd /pathabovetest_project
$ python -m test_project.main
``` | Just do `import output`, that worked for me. | 6,943 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.