qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
9,701,227 | I don't understand the answers for a [similar question.](https://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`... | 2012/03/14 | [
"https://Stackoverflow.com/questions/9701227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94363/"
] | Consider the following:
```
In [214]: l = [None,None,None]
In [215]: reduce(lambda x,y: x== y, l)
Out[215]: False
In [216]: from functional import scanl
In [217]: scanl(lambda x,y: x== y, None, l)
Out[217]: <generator object _scanl at 0x0000000005770D38>
In [218]: list(scanl(lambda x,y: x== y, None, l))
Out[218]: ... | It's not different with `None`, actually, what happens within `reduce` in the first case is
* 1 compared with 1 (== `True`)
* `True` compared with 1 (== `True`)
In the second case, it's
* `None` compared with `None` (== `True`)
* `True` compared with `None` (== `False`)
The funny example would be:
```
>> from ope... |
56,966,429 | I want to do this
```py
from some_cool_library import fancy_calculation
arr = [1,2,3,4,5]
for i, item in enumerate(arr):
the_rest = arr[:i] + arr[i+1:]
print(item, fancy_calculation(the_rest))
[Expected output:] # some fancy output from the fancy_calculation
12.13452134
2416245.4315432
542.343152
15150.1152
... | 2019/07/10 | [
"https://Stackoverflow.com/questions/56966429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8809992/"
] | Try This-
```
SELECT A.smanTeam,
A.TotalTarget,
B.TotalSales,
B.TotalSales*100/A.TotalTarget TotalPercentage
FROM
(
SELECT smanTeam,SUM(Target) TotalTarget
FROM Sman S
INNER JOIN SalesTarget ST ON S.smanID = ST.smanID
GROUP BY smanTeam
)A
LEFT JOIN
(
SELECT smanTeam, SUM(Amount) TotalSales
FRO... | Try below query:
```
select smanTeam, sum(Target) TotalTarget, sum(Amount) TotalSales , sum(Target)/sum(Amount) TotalPercentage from (
select smanTeam, Target, Amount from Sman sm
join
(select smanID, sum(Target) Target from SalesTarget group by smanID) st
on sm.smanID = st.smanID
join
... |
48,435,417 | If I have python code that requires indenting (`for`, `with`, function, etc), will a single line comment end potentially the context of the construct if I place it incorrectly? For example, presuming `step1`, `step2` and `step3` are functions already defined, will:
```
def myFunc():
step1()
# step2()
step3()... | 2018/01/25 | [
"https://Stackoverflow.com/questions/48435417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1099237/"
] | Try it out:
```
def myFunc():
print(1)
# print(2)
print(3)
myFunc()
```
which outputs:
```
1
3
```
So yeah, the answer is "Line comments don't need to match indentation". That said, [PEP8 really prefers that they do, just for readability](https://www.python.org/dev/peps/pep-0008/#block-comments). | It doesn't really matter where you place the `#`
Either in the first identation level or close to the instruction, everything underneath it is going to be executed.
I suggest you to play with the code below and You'll figure it out yourself.
```
a = 1
b = 10
c = 100
d = 1000
if (a == 1):
result = a+b
# resul... |
48,435,417 | If I have python code that requires indenting (`for`, `with`, function, etc), will a single line comment end potentially the context of the construct if I place it incorrectly? For example, presuming `step1`, `step2` and `step3` are functions already defined, will:
```
def myFunc():
step1()
# step2()
step3()... | 2018/01/25 | [
"https://Stackoverflow.com/questions/48435417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1099237/"
] | Try it out:
```
def myFunc():
print(1)
# print(2)
print(3)
myFunc()
```
which outputs:
```
1
3
```
So yeah, the answer is "Line comments don't need to match indentation". That said, [PEP8 really prefers that they do, just for readability](https://www.python.org/dev/peps/pep-0008/#block-comments). | Python clearly considers comments when checking for indentation errors, which I hope the devs think of as a bug, and fix. I was just running a program that failed to errors, but suddently worked when I deleted some of the comments (and changed nothing else). |
48,435,417 | If I have python code that requires indenting (`for`, `with`, function, etc), will a single line comment end potentially the context of the construct if I place it incorrectly? For example, presuming `step1`, `step2` and `step3` are functions already defined, will:
```
def myFunc():
step1()
# step2()
step3()... | 2018/01/25 | [
"https://Stackoverflow.com/questions/48435417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1099237/"
] | Syntax-wise, blank lines are ignored. Blank lines include lines that have any amount of white space followed by a comment.
<https://docs.python.org/2/reference/lexical_analysis.html#blank-lines>
Indenting a comment the way you show in your example does not change the block of code included in your function.
Conventio... | It doesn't really matter where you place the `#`
Either in the first identation level or close to the instruction, everything underneath it is going to be executed.
I suggest you to play with the code below and You'll figure it out yourself.
```
a = 1
b = 10
c = 100
d = 1000
if (a == 1):
result = a+b
# resul... |
48,435,417 | If I have python code that requires indenting (`for`, `with`, function, etc), will a single line comment end potentially the context of the construct if I place it incorrectly? For example, presuming `step1`, `step2` and `step3` are functions already defined, will:
```
def myFunc():
step1()
# step2()
step3()... | 2018/01/25 | [
"https://Stackoverflow.com/questions/48435417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1099237/"
] | Syntax-wise, blank lines are ignored. Blank lines include lines that have any amount of white space followed by a comment.
<https://docs.python.org/2/reference/lexical_analysis.html#blank-lines>
Indenting a comment the way you show in your example does not change the block of code included in your function.
Conventio... | Python clearly considers comments when checking for indentation errors, which I hope the devs think of as a bug, and fix. I was just running a program that failed to errors, but suddently worked when I deleted some of the comments (and changed nothing else). |
32,270,272 | I need to get a particular attribute value from a tag whose inner word matches my query word. For example, consider a target html-
```html
<span data-attr="something" attr1="" ><i>other_word</i></span>
<span data-attr="required" attr1="" ><i>word_to_match</i></span>
<span data-attr="something1" attr1="" ><i>some_other... | 2015/08/28 | [
"https://Stackoverflow.com/questions/32270272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2636802/"
] | You're not too far off. You need to iterate the words in each line and check if they are in the dictionary. Also, you need to call `read_words`, otherwise `ret` doesn't exist in the `for` loop.
```
dictionary = read_words(dictionary)
for paper in library:
file = os.path.join(path, paper)
text = open(file, "r")... | If you want to check if any element in the list are in the line
**change this from this :**
```
if re.match("(.*)(ret[])(.*)", line):
```
**To this :**
```
if any(word in line for word in ret)
``` |
34,048,316 | I have a sample file which looks like
```
emp_id(int),name(string),age(int)
1,hasa,34
2,dafa,45
3,fasa,12
8f,123Rag,12
8,fafl,12
```
Requirement: Column data types are specified as strings and integers. Emp\_id should be a integer not string. these conditions ll be the same for name and age columns.
**My output sh... | 2015/12/02 | [
"https://Stackoverflow.com/questions/34048316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1696853/"
] | Here is an awk-solution:
```
awk -F"," 'NR==1{for(i=1; i <= NF; i++){
split($i,a,"(");
name[i]=a[1];
type[i] = ($i ~ "int" ? "INT" : "String")}next}
{for(i=1; i <= NF; i++){
if($i != int($i) && type[i] == "INT"){error[i]... | With `perl` I would tackle it like this:
* Define some regex patterns that match/don't match the string content.
* pick out the header row - separate it into names and types. (Optionally reporting if a type doesn't match).
* iterate your fields, matching by column, figuring out type and applying the regex to validate
... |
71,448,461 | I was writing a python code in VS Code and somehow it's not detecting the input() function like it should.
Suppose, the code is as simple as
```
def main():
x= int ( input() )
print(x)
if __name__ == "__main__":
main()
```
even then, for some reason it is throwing error and I cannot figure out why.
... | 2022/03/12 | [
"https://Stackoverflow.com/questions/71448461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16979277/"
] | The traceback shows you where to look. It's actually the `int` function throwing a `ValueError`. It looks as if you're feeding it a filepath whereas it it's expecting a number.
You could add a check to repeat the input if incorrect like so:
```py
user_input = None
while not user_input:
raw_input = input("Put in a... | it's working!!!
see my example that says why you don't understand this:
```py
>>> x1 = input('enter a number: ')
enter a number: 10
>>> x1
'10'
>>> x2 = int(x1)
>>> x2
10
>>> x1 = input() # no text
100
>>> # it takes
>>> x1
'100'
>>> # but how you try?
>>> x1 = input()
NOT-NUMBER OR EMPTY-TEXT
>>> x2 = int(x1)
Trace... |
71,448,461 | I was writing a python code in VS Code and somehow it's not detecting the input() function like it should.
Suppose, the code is as simple as
```
def main():
x= int ( input() )
print(x)
if __name__ == "__main__":
main()
```
even then, for some reason it is throwing error and I cannot figure out why.
... | 2022/03/12 | [
"https://Stackoverflow.com/questions/71448461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16979277/"
] | The traceback shows you where to look. It's actually the `int` function throwing a `ValueError`. It looks as if you're feeding it a filepath whereas it it's expecting a number.
You could add a check to repeat the input if incorrect like so:
```py
user_input = None
while not user_input:
raw_input = input("Put in a... | The int() func is try to convert your string to Integer so it should be just numbers. It seems you are giving number and characters as an input so it raise the Value Error. if you want you can check if it is just numbers or not
```
x = input()
if x.isdigit():
x = int(x)
``` |
37,124,504 | All,
I wrote a small python program to create a file which is used as an input file to run an external program called srce3d. Here it is:
```
fin = open('eff.pwr.template','r')
fout = open('eff.pwr','wr')
for line in fin:
if 'li' in line:
fout.write( line.replace('-2.000000E+00', `-15.0`) )... | 2016/05/09 | [
"https://Stackoverflow.com/questions/37124504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5590629/"
] | Firstly you are missing the function calls for close.
```
fin.close() ## the round braces () were missing.
fout.close()
```
A better way to do the same is using contexts.
```
with open('eff.pwr.template','r') as fin, open('eff.pwr','wr') as fout:
## do all processing here
``` | You didn't actually close the file – you have to *call* `file.close`. So,
```
fin.close
fout.close
```
should be
```
fin.close()
fout.close()
``` |
29,411,952 | I need to delete all the rows in a csv file which have more than a certain number of columns.
This happens because sometimes the code, which generates the csv file, skips some values and prints the following on the same line.
Example: Consider the following file to parse. I want to remove all the rows which have mo... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29411952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3014331/"
] | This can be done straight forward with `awk`:
```
awk -F, 'NF<=3' file
```
This uses the `awk` variable `NF` that holds the number of fields in the current line. Since we have set the field separator to the comma (with `-F,` or, equivalent, `-v FS=","`), then it is just a matter of checking when the number of fields... | Try the following (do not omit to replace your file path and your max column):
```bash
#! /bin/bash
filepath=test.csv
max_columns=3
for line in $(cat $filepath);
do
count=$(echo "$line" | grep -o "," | wc -l)
if [ $(($count + 1)) -le $max_columns ]
then
echo $line
fi
done
```
Co... |
47,635,838 | I'm trying to use the LinearSVC of sklearn and export the decision tree to a .dot file. I can fit the classifier with sample data and then use it on some test data but the export to the .dot file gives a NotFittedError.
```
data = pd.read_csv("census-income-data.data", skipinitialspace=True, usecols=list(range(0, 41))... | 2017/12/04 | [
"https://Stackoverflow.com/questions/47635838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6534294/"
] | You are using a [function](http://scikit-learn.org/stable/modules/generated/sklearn.tree.export_graphviz.html#sklearn-tree-export-graphviz) to plot a decision-tree. Look at the first argument: *decision\_tree*, like an object of [this](http://scikit-learn.org/stable/modules/tree.html).
A SVM is not a decision-tree! It... | In `sklearn.tree.export_graphviz`, the first parameter is a fitted decision tree.
You give a fitted estimator, but not a decision tree.
**Indeed, `LinearSVC` is not a decision tree.**
Try with `sklearn.tree.DecisionTreeClassifier` instead of `sklearn.svm.LinearSVC`. |
47,443,434 | I'm new to python/data science in general, trying to understand why the below isn't working:
```
import pandas as pd
url = 'https://s3.amazonaws.com/nyc-tlc/trip+data/fhv_tripdata_2017-06.csv'
trip_df = []
for chunk in pd.read_csv(url, chunksize=1000, nrows=10000):
trip_df.append(chunk)
trip_df = pd.concat(trip_df... | 2017/11/22 | [
"https://Stackoverflow.com/questions/47443434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8992936/"
] | Try this:
```
reader = pd.read_csv(url, chunksize=1000, nrows=10000)
df = pd.concat([x for x in reader], ignore_index=True)
```
>
> how would I just get part of it, say 5,000 rows?
>
>
>
```
df = pd.read_csv(url, nrows=5000)
``` | Just get the 5000 rows in the command line with
```
wget -q -O - https://s3.amazonaws.com/nyc-tlc/trip+data/fhv_tripdata_2017-06.csv | head -n 5000 > tmp.csv
```
and then proceed with tmp.csv |
47,443,434 | I'm new to python/data science in general, trying to understand why the below isn't working:
```
import pandas as pd
url = 'https://s3.amazonaws.com/nyc-tlc/trip+data/fhv_tripdata_2017-06.csv'
trip_df = []
for chunk in pd.read_csv(url, chunksize=1000, nrows=10000):
trip_df.append(chunk)
trip_df = pd.concat(trip_df... | 2017/11/22 | [
"https://Stackoverflow.com/questions/47443434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8992936/"
] | This works for me
```py
with contextlib.closing(urllib.request.urlopen(url=url)) as rd:
for df in pd.read_csv(rd, chunksize=5, index_col=0):
print(df)
```
while just
```py
pd.read_csv(url, chunksize=5, index_col=0)
```
crashes with MemoryError. | Just get the 5000 rows in the command line with
```
wget -q -O - https://s3.amazonaws.com/nyc-tlc/trip+data/fhv_tripdata_2017-06.csv | head -n 5000 > tmp.csv
```
and then proceed with tmp.csv |
10,931,150 | php has the [`strtr`](http://php.net/manual/en/function.strtr.php) function:
```
strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y
```
It replaces dictionary keys in a string with corresponding values and (important) doesn't replace already replaced strings. A naive attempt to write the sa... | 2012/06/07 | [
"https://Stackoverflow.com/questions/10931150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989121/"
] | Here is a naive algorithm:
Use an index to walk the original string character by character and check for each index whether one of the search strings is equal to the string from the current index on. If a match is found, push the replacement in a buffer and proceed the index by the length of the matched string. If no ... | [`str.translate`](http://docs.python.org/library/stdtypes.html#str.translate) is the equivalent, but can only map to single characters. |
10,931,150 | php has the [`strtr`](http://php.net/manual/en/function.strtr.php) function:
```
strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y
```
It replaces dictionary keys in a string with corresponding values and (important) doesn't replace already replaced strings. A naive attempt to write the sa... | 2012/06/07 | [
"https://Stackoverflow.com/questions/10931150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989121/"
] | The following uses regular expressions to do it:
```
import re
def strtr(s, repl):
pattern = '|'.join(map(re.escape, sorted(repl, key=len, reverse=True)))
return re.sub(pattern, lambda m: repl[m.group()], s)
print(strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}))
```
Like the PHP's version, this gives pr... | [`str.translate`](http://docs.python.org/library/stdtypes.html#str.translate) is the equivalent, but can only map to single characters. |
10,931,150 | php has the [`strtr`](http://php.net/manual/en/function.strtr.php) function:
```
strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y
```
It replaces dictionary keys in a string with corresponding values and (important) doesn't replace already replaced strings. A naive attempt to write the sa... | 2012/06/07 | [
"https://Stackoverflow.com/questions/10931150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989121/"
] | ```
def strtr(strng, replace):
if replace and strng:
s, r = replace.popitem()
return r.join(strtr(subs, dict(replace)) for subs in strng.split(s))
return strng
j=strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'})
assert j=='bbz-x-y', j
``` | [`str.translate`](http://docs.python.org/library/stdtypes.html#str.translate) is the equivalent, but can only map to single characters. |
10,931,150 | php has the [`strtr`](http://php.net/manual/en/function.strtr.php) function:
```
strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y
```
It replaces dictionary keys in a string with corresponding values and (important) doesn't replace already replaced strings. A naive attempt to write the sa... | 2012/06/07 | [
"https://Stackoverflow.com/questions/10931150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989121/"
] | [`str.translate`](http://docs.python.org/library/stdtypes.html#str.translate) is the equivalent, but can only map to single characters. | The answers on this thread are so out-dated. Here we go...
### Option #1: Use the str.format() function to handle this:
```
"Hello there {first_name} {last_name}".format(first_name="Bob", last_name="Roy")
```
### Option #2: Use the Template class
```
from string import Template
t = Template('Hello there $first_nam... |
10,931,150 | php has the [`strtr`](http://php.net/manual/en/function.strtr.php) function:
```
strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y
```
It replaces dictionary keys in a string with corresponding values and (important) doesn't replace already replaced strings. A naive attempt to write the sa... | 2012/06/07 | [
"https://Stackoverflow.com/questions/10931150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989121/"
] | Here is a naive algorithm:
Use an index to walk the original string character by character and check for each index whether one of the search strings is equal to the string from the current index on. If a match is found, push the replacement in a buffer and proceed the index by the length of the matched string. If no ... | The answers on this thread are so out-dated. Here we go...
### Option #1: Use the str.format() function to handle this:
```
"Hello there {first_name} {last_name}".format(first_name="Bob", last_name="Roy")
```
### Option #2: Use the Template class
```
from string import Template
t = Template('Hello there $first_nam... |
10,931,150 | php has the [`strtr`](http://php.net/manual/en/function.strtr.php) function:
```
strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y
```
It replaces dictionary keys in a string with corresponding values and (important) doesn't replace already replaced strings. A naive attempt to write the sa... | 2012/06/07 | [
"https://Stackoverflow.com/questions/10931150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989121/"
] | The following uses regular expressions to do it:
```
import re
def strtr(s, repl):
pattern = '|'.join(map(re.escape, sorted(repl, key=len, reverse=True)))
return re.sub(pattern, lambda m: repl[m.group()], s)
print(strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}))
```
Like the PHP's version, this gives pr... | The answers on this thread are so out-dated. Here we go...
### Option #1: Use the str.format() function to handle this:
```
"Hello there {first_name} {last_name}".format(first_name="Bob", last_name="Roy")
```
### Option #2: Use the Template class
```
from string import Template
t = Template('Hello there $first_nam... |
10,931,150 | php has the [`strtr`](http://php.net/manual/en/function.strtr.php) function:
```
strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y
```
It replaces dictionary keys in a string with corresponding values and (important) doesn't replace already replaced strings. A naive attempt to write the sa... | 2012/06/07 | [
"https://Stackoverflow.com/questions/10931150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989121/"
] | ```
def strtr(strng, replace):
if replace and strng:
s, r = replace.popitem()
return r.join(strtr(subs, dict(replace)) for subs in strng.split(s))
return strng
j=strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'})
assert j=='bbz-x-y', j
``` | The answers on this thread are so out-dated. Here we go...
### Option #1: Use the str.format() function to handle this:
```
"Hello there {first_name} {last_name}".format(first_name="Bob", last_name="Roy")
```
### Option #2: Use the Template class
```
from string import Template
t = Template('Hello there $first_nam... |
36,900,272 | Being a complete begginer in python, I decided to install the python interpreter 3.4.4, and also PyDev plugin for eclipse IDE. I am also using windows 10.
I have encountered a problem regarding certain imports, namely : `from PIL import Image, ImageTk`, which is apparently an unresolved import.
I have looked at certa... | 2016/04/27 | [
"https://Stackoverflow.com/questions/36900272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4375983/"
] | Found the solution, here's what I did:
1. Set the PYTHONPATH [like it is shown in this article](https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7/4855685#4855685), make sure python.exe is accessible via cmd,
2. Via cmd, type `pip install pillow`. Alternatively, you can enter the sam... | For Python import problems in PyDev, the project web site has a page on [interpreter configuration](http://www.pydev.org/manual_101_interpreter.html) that is a good place to start. I recently had a similar problem that I solved by adding a module to the forced builtins tab. |
21,845,390 | hello friends i just started to use GitHub and i just want to know it is possible to download github repository to my local computer through by Using GitHub Api or Api libraries (ie. python library " pygithub3" for Github api) | 2014/02/18 | [
"https://Stackoverflow.com/questions/21845390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3321823/"
] | Using [`github3.py`](http://github3py.rtfd.org/) you can clone all of your repositories (including forks and private repositories) by doing:
```
import github3
import subprocess
g = github3.login('username', 'password')
for repo in g.iter_repos(type='all'):
subprocess.call(['git', 'clone', repo.clone_url])
```
... | As illustrated in [this Gist](https://gist.github.com/jharjono/1159239), the simplest solution is simply to call git clone.
```python
#!/usr/bin/env python
# Script to clone all the github repos that a user is watching
import requests
import json
import subprocess
# Grab all the URLs of the watched repo
user = 'jharj... |
36,238,155 | I have a script in python that consists of multiple list of functions, and at every end of a list I want to put a back function that will let me return to the beginning of the script and choose another list. for example:
```
list = ("1. List of all users",
"2. List of all groups",
"3. Reset password",
"4. ... | 2016/03/26 | [
"https://Stackoverflow.com/questions/36238155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5974999/"
] | Maybe your EditTexts are not initialized, you need something like `quantity1 = (EditText) findViewById(R.id.YOUR_EDIT_TEXT_ID)` for both. | Check what you are passing...check my example.
```
package general;
public class TestNumberFormat {
public static void main(String[] args){
String addquantity = "40";
String subquantity = "30";
int final_ = Integer.parseInt(addquantity) - Integer.parseInt(subquantity);
System.out.println("PRI... |
36,238,155 | I have a script in python that consists of multiple list of functions, and at every end of a list I want to put a back function that will let me return to the beginning of the script and choose another list. for example:
```
list = ("1. List of all users",
"2. List of all groups",
"3. Reset password",
"4. ... | 2016/03/26 | [
"https://Stackoverflow.com/questions/36238155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5974999/"
] | Maybe your EditTexts are not initialized, you need something like `quantity1 = (EditText) findViewById(R.id.YOUR_EDIT_TEXT_ID)` for both. | Maybe you got an space in your string.
Use following
```
String addquantity = quantity1.getText().toString().trim();
String subquantity = quantity2.getText().toString().trim();
``` |
66,602,480 | I am learning fastapi, and I am starting a uvicorn server on localhost. Whenever there is an error/exception, I am not getting the traceback.
All I am getting is : `INFO: 127.0.0.1:56914 - "POST /create/user/ HTTP/1.1" 500 Internal Server Error`
So, It is difficult to debug, I am trying out logging module of python
`... | 2021/03/12 | [
"https://Stackoverflow.com/questions/66602480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14354318/"
] | Solution / Fix
==============
Now, when you execute uvicorn by the in-Python command `uvicorn.run(app)`, this is your next move:
take the ucivorn default logging config and add the handler from your application to it:
```py
config = {}
# this is default (site-packages\uvicorn\main.py)
config['log_config'] = {
... | For "500 Internal Server Error" occurring during a post request, if you invoke FastAPI in debug mode:
```
app = FastAPI(debug=True)
```
Retry the request with Chrome dev tools Network tab open. When you see the failing request show up (note - my route url was '/rule' here):
[ of Red Hat is to make files group owned by GID 0 - the user in the container is always in the root group. You won't be able to chown, but you can selectively expose which files to write to.
A second op... | Can you see the logs using
```
kubectl logs <podname> -p
```
This should give you the errors why the pod failed. |
35,744,408 | I have an astrophysic project by using data file. It's a csv data file.
I'm using the following code in Python :
```
#!/usr/bin/python
# coding: utf-8
import numpy as np
# Fichier contenant le champ 169 #
file = '/astromaster/home/xxx/Bureau/Stage/Champs/Field_169/Field169_combined_final_roughcal.csv'
###... | 2016/03/02 | [
"https://Stackoverflow.com/questions/35744408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You are seeing this because whatever process your image is starting isn't a long running process and finds no TTY and the container just exits and gets restarted repeatedly, which is a "crash loop" as far as openshift is concerned.
Your dockerfile mentions below :
ENTRYPOINT ["container-entrypoint"]
What actually th... | The [recommendation](https://docs.openshift.org/latest/creating_images/guidelines.html#openshift-specific-guidelines) of Red Hat is to make files group owned by GID 0 - the user in the container is always in the root group. You won't be able to chown, but you can selectively expose which files to write to.
A second op... |
35,744,408 | I have an astrophysic project by using data file. It's a csv data file.
I'm using the following code in Python :
```
#!/usr/bin/python
# coding: utf-8
import numpy as np
# Fichier contenant le champ 169 #
file = '/astromaster/home/xxx/Bureau/Stage/Champs/Field_169/Field169_combined_final_roughcal.csv'
###... | 2016/03/02 | [
"https://Stackoverflow.com/questions/35744408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The [recommendation](https://docs.openshift.org/latest/creating_images/guidelines.html#openshift-specific-guidelines) of Red Hat is to make files group owned by GID 0 - the user in the container is always in the root group. You won't be able to chown, but you can selectively expose which files to write to.
A second op... | I am able to resolve this by creating a script as "run.sh" with the content at end:
```
while :; do
sleep 300
done
```
and in Dockerfile:
```
ADD run.sh /run.sh
RUN chmod +x /*.sh
CMD ["/run.sh"]
```
This way it works, thanks everybody for pointing out the reason ,which helped me in finding the resolution. But on... |
35,744,408 | I have an astrophysic project by using data file. It's a csv data file.
I'm using the following code in Python :
```
#!/usr/bin/python
# coding: utf-8
import numpy as np
# Fichier contenant le champ 169 #
file = '/astromaster/home/xxx/Bureau/Stage/Champs/Field_169/Field169_combined_final_roughcal.csv'
###... | 2016/03/02 | [
"https://Stackoverflow.com/questions/35744408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You are seeing this because whatever process your image is starting isn't a long running process and finds no TTY and the container just exits and gets restarted repeatedly, which is a "crash loop" as far as openshift is concerned.
Your dockerfile mentions below :
ENTRYPOINT ["container-entrypoint"]
What actually th... | Can you see the logs using
```
kubectl logs <podname> -p
```
This should give you the errors why the pod failed. |
35,744,408 | I have an astrophysic project by using data file. It's a csv data file.
I'm using the following code in Python :
```
#!/usr/bin/python
# coding: utf-8
import numpy as np
# Fichier contenant le champ 169 #
file = '/astromaster/home/xxx/Bureau/Stage/Champs/Field_169/Field169_combined_final_roughcal.csv'
###... | 2016/03/02 | [
"https://Stackoverflow.com/questions/35744408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You are seeing this because whatever process your image is starting isn't a long running process and finds no TTY and the container just exits and gets restarted repeatedly, which is a "crash loop" as far as openshift is concerned.
Your dockerfile mentions below :
ENTRYPOINT ["container-entrypoint"]
What actually th... | I am able to resolve this by creating a script as "run.sh" with the content at end:
```
while :; do
sleep 300
done
```
and in Dockerfile:
```
ADD run.sh /run.sh
RUN chmod +x /*.sh
CMD ["/run.sh"]
```
This way it works, thanks everybody for pointing out the reason ,which helped me in finding the resolution. But on... |
62,056,688 | ```
eleUserMessage = driver.find_element_by_id("xxxxxxx")
eleUserMessage.send_keys(email)
```
Im trying to use selenium with python to auto fill out a form and fill in my details. So far I have read in my info from a .txt file and stored them in variables for easy reference. When I Find the element and try to... | 2020/05/28 | [
"https://Stackoverflow.com/questions/62056688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13631666/"
] | Because you are storing your details in a text file, it is likely that when you create the email variable there is a newline at the end of the string as this is how text files work. This would explain why the form gets submitted because it is the equivalent of typing the email followed by the enter key. You can try to ... | if you just want to fill out a form ,then submit the finished form.
you can try :
```
eleUserMessage = driver.find_element_by_xpath("//select[@name='name']")
all_options = eleUserMessage.find_elements_by_tag_name("option")
for option in all_options:
print("Value is: %s" % option.get_attribute("valu... |
57,275,797 | This question may seem very basic, however, I would like to improve the code I have written. I have a function that will need either 2 or 3 parameters, depending on some other conditions. I'm checking the length and passing either 2 or 3 with and if statement (see code). I'm sure there must be a better and compact way ... | 2019/07/30 | [
"https://Stackoverflow.com/questions/57275797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2255752/"
] | Not sure what data types you have and how your method looks like, but with \*args you can solve that:
```
def cdf(ppt_fut, *params):
print(ppt_fut)
print(params)
```
Then you can call it like that:
```
cdf(1, 2, 3, 4) # -> prints: 1 (2,3,4)
cdf(1, 2, 3) # -> prints: 1 (2,3)
```
The `params` is in this cas... | You can unpack elements of a list into a function call with `*`.
You don't need to know how many items there are in the list to do this. But this means you can introduce errors if the number of items don't match the function arguments. It's therefore a good idea to check your data for some basic sanity as well.
For ... |
57,275,797 | This question may seem very basic, however, I would like to improve the code I have written. I have a function that will need either 2 or 3 parameters, depending on some other conditions. I'm checking the length and passing either 2 or 3 with and if statement (see code). I'm sure there must be a better and compact way ... | 2019/07/30 | [
"https://Stackoverflow.com/questions/57275797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2255752/"
] | Not sure what data types you have and how your method looks like, but with \*args you can solve that:
```
def cdf(ppt_fut, *params):
print(ppt_fut)
print(params)
```
Then you can call it like that:
```
cdf(1, 2, 3, 4) # -> prints: 1 (2,3,4)
cdf(1, 2, 3) # -> prints: 1 (2,3)
```
The `params` is in this cas... | Welcome to python. Please consider using [pep8](https://www.python.org/dev/peps/pep-0008/#introduction) for formatting your code. It is a great way to respect conventions and make your code more readable for other people.
[Variable names](https://www.python.org/dev/peps/pep-0008/#function-and-variable-names) should be... |
26,328,648 | [Answered first part, please scroll for second question edit]
Currently coding a web scraper in python.
I have the following example string:
`Columbus Blue Jackets at Buffalo Sabres - 10/09/2014`
I want to split it so that I have [Columbus Blue Jackets, Buffalo Sabres, 10/09/2014]
I read up on regular expressions i... | 2014/10/12 | [
"https://Stackoverflow.com/questions/26328648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2621303/"
] | ```
print re.split(r"\s+at\s+|\s+-\s+",teams)
```
Output:`['Columbus Blue Jackets', 'Buffalo Sabres', '10/09/2014']`
Try this.You can do it in one line.Here `teams` is your string.This will give you desired results.
Edit:
```
def getTable(url):
currentMatchup = Crawl.setup(url)
teams = currentMatchup.title... | Capture them into groups with lazy dot-match-all repetition.
```
(.*?)\s+at\s+(.*?)\s+-\s+(\d{2}/\d{2}/\d{4})
```
[***Demo***](http://regex101.com/r/lU3wV3/1)
---
```
import re;
match = re.search(r"(.*?)\s+at\s+(.*?)\s+-\s+(\d{2}/\d{2}/\d{4})", "Columbus Blue Jackets at Buffalo Sabres - 10/09/2014")
print match.g... |
26,328,648 | [Answered first part, please scroll for second question edit]
Currently coding a web scraper in python.
I have the following example string:
`Columbus Blue Jackets at Buffalo Sabres - 10/09/2014`
I want to split it so that I have [Columbus Blue Jackets, Buffalo Sabres, 10/09/2014]
I read up on regular expressions i... | 2014/10/12 | [
"https://Stackoverflow.com/questions/26328648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2621303/"
] | You could split the input string according to `<space>at<space>` or `<space>-<space>`,
```
>>> s = "Columbus Blue Jackets at Buffalo Sabres - 10/09/2014"
>>> re.split(r'\s+(?:at|-)\s+', s)
['Columbus Blue Jackets', 'Buffalo Sabres', '10/09/2014']
>>> s = 'Montreal Canadiens at Buffalo Sabres - 10/09/2014'
>>> re.split... | ```
print re.split(r"\s+at\s+|\s+-\s+",teams)
```
Output:`['Columbus Blue Jackets', 'Buffalo Sabres', '10/09/2014']`
Try this.You can do it in one line.Here `teams` is your string.This will give you desired results.
Edit:
```
def getTable(url):
currentMatchup = Crawl.setup(url)
teams = currentMatchup.title... |
26,328,648 | [Answered first part, please scroll for second question edit]
Currently coding a web scraper in python.
I have the following example string:
`Columbus Blue Jackets at Buffalo Sabres - 10/09/2014`
I want to split it so that I have [Columbus Blue Jackets, Buffalo Sabres, 10/09/2014]
I read up on regular expressions i... | 2014/10/12 | [
"https://Stackoverflow.com/questions/26328648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2621303/"
] | You could split the input string according to `<space>at<space>` or `<space>-<space>`,
```
>>> s = "Columbus Blue Jackets at Buffalo Sabres - 10/09/2014"
>>> re.split(r'\s+(?:at|-)\s+', s)
['Columbus Blue Jackets', 'Buffalo Sabres', '10/09/2014']
>>> s = 'Montreal Canadiens at Buffalo Sabres - 10/09/2014'
>>> re.split... | Capture them into groups with lazy dot-match-all repetition.
```
(.*?)\s+at\s+(.*?)\s+-\s+(\d{2}/\d{2}/\d{4})
```
[***Demo***](http://regex101.com/r/lU3wV3/1)
---
```
import re;
match = re.search(r"(.*?)\s+at\s+(.*?)\s+-\s+(\d{2}/\d{2}/\d{4})", "Columbus Blue Jackets at Buffalo Sabres - 10/09/2014")
print match.g... |
63,557,957 | I am a beginner in python, pycharm and Linux, I want to open an existing Django project. But when I use "python manage.py runserver", I am getting a series of trace-back errors which I am attaching below.
I have installed all the LAMP stack i.e., Linux OS, Apache2 Web server,MariaDB and MYSQLclient with latest versions... | 2020/08/24 | [
"https://Stackoverflow.com/questions/63557957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14156220/"
] | The input pipeline of a dataset is always traced into a graph (as if you used [`@tf.function`](https://www.tensorflow.org/api_docs/python/tf/function)) to make it faster, which means, among other things, that you cannot use `.numpy()`. You can however use [`tf.numpy_function`](https://www.tensorflow.org/api_docs/python... | A bit wordy, but try it like this:
```
def transform(example):
str_example = example.numpy().decode("utf-8")
json_example = json.loads(str_example)
overall = json_example.get('overall', None)
text = json_example.get('reviewText', None)
return (overall, text)
line_dataset... |
2,293,968 | For my project, the role of the Lecturer (defined as a class) is to offer projects to students. Project itself is also a class. I have some global dictionaries, keyed by the unique numeric id's for lecturers and projects that map to objects.
Thus for the "lecturers" dictionary (currently):
```
lecturer[id] = Lecture... | 2010/02/19 | [
"https://Stackoverflow.com/questions/2293968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273875/"
] | `set` is better since you don't care about order and have no duplicate.
You can parse the file easily with the [csv](http://docs.python.org/library/csv.html?highlight=sv#module-csv) module (with a `delimiter` of `' '`).
Once you have the `lec_name` you must check if that lecturer's already know; for that purpose, kee... | Sets are useful when you want to guarantee you only have one instance of each item. They are also faster than a list at calculating whether an item is present in the collection.
Lists are faster at adding items, and also have an ordering.
This sounds like you would like a set. You sound like you are very close alread... |
2,293,968 | For my project, the role of the Lecturer (defined as a class) is to offer projects to students. Project itself is also a class. I have some global dictionaries, keyed by the unique numeric id's for lecturers and projects that map to objects.
Thus for the "lecturers" dictionary (currently):
```
lecturer[id] = Lecture... | 2010/02/19 | [
"https://Stackoverflow.com/questions/2293968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273875/"
] | `set` is better since you don't care about order and have no duplicate.
You can parse the file easily with the [csv](http://docs.python.org/library/csv.html?highlight=sv#module-csv) module (with a `delimiter` of `' '`).
Once you have the `lec_name` you must check if that lecturer's already know; for that purpose, kee... | Thanks for the help [Alex](https://stackoverflow.com/users/95810/alex-martelli) and [Oddthinking](https://stackoverflow.com/users/8014/oddthinking)! I think I've figured out what was going on:
I modified the code snippet that I added to the question. Basically, every time it read the line I think it was recreating th... |
2,293,968 | For my project, the role of the Lecturer (defined as a class) is to offer projects to students. Project itself is also a class. I have some global dictionaries, keyed by the unique numeric id's for lecturers and projects that map to objects.
Thus for the "lecturers" dictionary (currently):
```
lecturer[id] = Lecture... | 2010/02/19 | [
"https://Stackoverflow.com/questions/2293968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273875/"
] | Sets are useful when you want to guarantee you only have one instance of each item. They are also faster than a list at calculating whether an item is present in the collection.
Lists are faster at adding items, and also have an ordering.
This sounds like you would like a set. You sound like you are very close alread... | Thanks for the help [Alex](https://stackoverflow.com/users/95810/alex-martelli) and [Oddthinking](https://stackoverflow.com/users/8014/oddthinking)! I think I've figured out what was going on:
I modified the code snippet that I added to the question. Basically, every time it read the line I think it was recreating th... |
2,112,632 | Is it possible to create a grid like below?
I didn't found anything in the forum.
```
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of ... | 2010/01/21 | [
"https://Stackoverflow.com/questions/2112632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237934/"
] | Check out [NumPy](http://numpy.scipy.org/) - specifically, the [N-dimensional array](http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html) object. | Your code example won't compile unless you put commas between the list elements.
For example, this will compile:
```
value = [
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12]
]
```
If you're interested in taking strings like you show, and **parsing** them into a list of lists (or nump... |
2,112,632 | Is it possible to create a grid like below?
I didn't found anything in the forum.
```
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of ... | 2010/01/21 | [
"https://Stackoverflow.com/questions/2112632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237934/"
] | Check out [NumPy](http://numpy.scipy.org/) - specifically, the [N-dimensional array](http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html) object. | What you have above does not work, e.g if pasted into a file and then run as a script, or pasted into the interpreter. I get:
```
SyntaxError: invalid token
```
Again, I suspect that what you have done is paste text (a string) containing these characters. They are not integers, and you will get nowhere unless you r... |
2,112,632 | Is it possible to create a grid like below?
I didn't found anything in the forum.
```
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of ... | 2010/01/21 | [
"https://Stackoverflow.com/questions/2112632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237934/"
] | Check out [NumPy](http://numpy.scipy.org/) - specifically, the [N-dimensional array](http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html) object. | As for parsing the actual data, and you don't want to read it from a file or use sensible methods, there is always this:
```
s = """[[08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08]
...etc
"""
s = s.replace("]", "").replace("[", "").split()
numbers = [int(x) for x in s]
```
Then you got a 1d array of ... |
2,112,632 | Is it possible to create a grid like below?
I didn't found anything in the forum.
```
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of ... | 2010/01/21 | [
"https://Stackoverflow.com/questions/2112632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237934/"
] | Check out [NumPy](http://numpy.scipy.org/) - specifically, the [N-dimensional array](http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html) object. | You can define the numbers in a string and split it easily in row/columns:
```
nums = """\
1 2 3
4 5 6
7 8 9 10
"""
rows = [map(int, row.split()) for row in nums.splitlines()]
print rows ##> [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
``` |
2,112,632 | Is it possible to create a grid like below?
I didn't found anything in the forum.
```
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of ... | 2010/01/21 | [
"https://Stackoverflow.com/questions/2112632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237934/"
] | Your code example won't compile unless you put commas between the list elements.
For example, this will compile:
```
value = [
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12]
]
```
If you're interested in taking strings like you show, and **parsing** them into a list of lists (or nump... | What you have above does not work, e.g if pasted into a file and then run as a script, or pasted into the interpreter. I get:
```
SyntaxError: invalid token
```
Again, I suspect that what you have done is paste text (a string) containing these characters. They are not integers, and you will get nowhere unless you r... |
2,112,632 | Is it possible to create a grid like below?
I didn't found anything in the forum.
```
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of ... | 2010/01/21 | [
"https://Stackoverflow.com/questions/2112632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237934/"
] | Your code example won't compile unless you put commas between the list elements.
For example, this will compile:
```
value = [
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12]
]
```
If you're interested in taking strings like you show, and **parsing** them into a list of lists (or nump... | As for parsing the actual data, and you don't want to read it from a file or use sensible methods, there is always this:
```
s = """[[08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08]
...etc
"""
s = s.replace("]", "").replace("[", "").split()
numbers = [int(x) for x in s]
```
Then you got a 1d array of ... |
2,112,632 | Is it possible to create a grid like below?
I didn't found anything in the forum.
```
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of ... | 2010/01/21 | [
"https://Stackoverflow.com/questions/2112632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237934/"
] | You can define the numbers in a string and split it easily in row/columns:
```
nums = """\
1 2 3
4 5 6
7 8 9 10
"""
rows = [map(int, row.split()) for row in nums.splitlines()]
print rows ##> [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
``` | What you have above does not work, e.g if pasted into a file and then run as a script, or pasted into the interpreter. I get:
```
SyntaxError: invalid token
```
Again, I suspect that what you have done is paste text (a string) containing these characters. They are not integers, and you will get nowhere unless you r... |
2,112,632 | Is it possible to create a grid like below?
I didn't found anything in the forum.
```
#euler-project problem number 11
#In the 20 times 20 grid below,
#four numbers along a diagonal line have been marked in red.
#The product of these numbers is 26 times 63 times 78 times 14 = 1788696.
#What is the greatest product of ... | 2010/01/21 | [
"https://Stackoverflow.com/questions/2112632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237934/"
] | You can define the numbers in a string and split it easily in row/columns:
```
nums = """\
1 2 3
4 5 6
7 8 9 10
"""
rows = [map(int, row.split()) for row in nums.splitlines()]
print rows ##> [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
``` | As for parsing the actual data, and you don't want to read it from a file or use sensible methods, there is always this:
```
s = """[[08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08]
...etc
"""
s = s.replace("]", "").replace("[", "").split()
numbers = [int(x) for x in s]
```
Then you got a 1d array of ... |
58,846,573 | I'm building a voice assistant using python. I want to make it available as a web application. How do I build the same?
Thanks | 2019/11/13 | [
"https://Stackoverflow.com/questions/58846573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10441927/"
] | When you set
```
channel_shift_range=10,
brightness_range=(0.7, 1.3)
```
This modifies the RNG of this generator so that the Image RNG and the Mask RNG are not in sync anymore.
I propose you use a custom Sequence for this task until the KP new API is released. (see <https://github.com/keras-team/governance/blob/m... | For anyone else struggling with this - concatenating the images and masks along the channel axis is a handy way to synchronise the augmentations
```
image_mask = np.concatenate([image, mask], axis=3)
image_mask = augmenter.flow(image_mask).next()
image = image_mask [:, :, :, 0]
mask = image_mask [:, :, :, 1]
``` |
56,047,365 | I need a python code to extract the selected word using python.
```
<a class="tel ttel">
<span class="mobilesv icon-hg"></span>
<span class="mobilesv icon-rq"></span>
<span class="mobilesv icon-ba"></span>
<span class="mobilesv icon-rq"></span>
<span class="mobilesv icon-ba"></span>
<span class="mobilesv icon-ikj"></s... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56047365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8235643/"
] | You can change line 1 to `import Data.List hiding (find)`, assuming you never intend to use the `find` defined there. | In your situation your options are:
1. Rename your own `find` into something else.
2. Import `Data.List` as qualified: `import qualified Data.List`. You can add `as L` to shorten code that uses stuff from `Data.List`. |
35,811,400 | I have about 650 csv-based matrices. I plan on loading each one using Numpy as in the following example:
```
m1 = numpy.loadtext(open("matrix1.txt", "rb"), delimiter=",", skiprows=1)
```
There are matrix2.txt, matrix3.txt, ..., matrix650.txt files that I need to process.
My end goal is to multiply each matrix by ea... | 2016/03/05 | [
"https://Stackoverflow.com/questions/35811400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973851/"
] | **1. Variant: Nice code but reads all matrices at once**
```
matrixFileCount = 3
matrices = [np.loadtxt(open("matrix%s.txt" % i ), delimiter=",", skiprows=1) for i in range(1,matrixFileCount+1)]
allC = itertools.combinations([x for x in range(matrixFileCount)], 2)
allCMultiply = [np.dot(matrices[c[0]], matrices[c[1]])... | Kordi's answer loads *all* of the matrices before doing the multiplication. And that's fine if you know the matrices are going to be small. If you want to conserve memory, however, I'd do the following:
```
import numpy as np
def get_dot_product(fnames):
assert len(fnames) > 0
accum_val = np.loadtxt(fnames[0]... |
35,811,400 | I have about 650 csv-based matrices. I plan on loading each one using Numpy as in the following example:
```
m1 = numpy.loadtext(open("matrix1.txt", "rb"), delimiter=",", skiprows=1)
```
There are matrix2.txt, matrix3.txt, ..., matrix650.txt files that I need to process.
My end goal is to multiply each matrix by ea... | 2016/03/05 | [
"https://Stackoverflow.com/questions/35811400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973851/"
] | A Python3 solution, if "each matrix by each other" actually means just multiplying them in a row and *the matrices have compatible dimensions* ( (n, m) · (m, o) · (o, p) · ... ), which you hint at with "(1 ongoing and 1 that...)", then use (if available):
```
from functools import partial
fnames = map("matrix{}.txt".f... | **1. Variant: Nice code but reads all matrices at once**
```
matrixFileCount = 3
matrices = [np.loadtxt(open("matrix%s.txt" % i ), delimiter=",", skiprows=1) for i in range(1,matrixFileCount+1)]
allC = itertools.combinations([x for x in range(matrixFileCount)], 2)
allCMultiply = [np.dot(matrices[c[0]], matrices[c[1]])... |
35,811,400 | I have about 650 csv-based matrices. I plan on loading each one using Numpy as in the following example:
```
m1 = numpy.loadtext(open("matrix1.txt", "rb"), delimiter=",", skiprows=1)
```
There are matrix2.txt, matrix3.txt, ..., matrix650.txt files that I need to process.
My end goal is to multiply each matrix by ea... | 2016/03/05 | [
"https://Stackoverflow.com/questions/35811400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973851/"
] | **1. Variant: Nice code but reads all matrices at once**
```
matrixFileCount = 3
matrices = [np.loadtxt(open("matrix%s.txt" % i ), delimiter=",", skiprows=1) for i in range(1,matrixFileCount+1)]
allC = itertools.combinations([x for x in range(matrixFileCount)], 2)
allCMultiply = [np.dot(matrices[c[0]], matrices[c[1]])... | How about a really simple solution avoiding `map`, `reduce` and the like? The default `numpy` array object does element-wise multiplication by default.
```
size = (197, 11)
result = numpy.ones(size)
for i in range(1, 651):
result *= numpy.loadtext(open("matrix{}.txt".format(i), "rb"),
... |
35,811,400 | I have about 650 csv-based matrices. I plan on loading each one using Numpy as in the following example:
```
m1 = numpy.loadtext(open("matrix1.txt", "rb"), delimiter=",", skiprows=1)
```
There are matrix2.txt, matrix3.txt, ..., matrix650.txt files that I need to process.
My end goal is to multiply each matrix by ea... | 2016/03/05 | [
"https://Stackoverflow.com/questions/35811400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973851/"
] | A Python3 solution, if "each matrix by each other" actually means just multiplying them in a row and *the matrices have compatible dimensions* ( (n, m) · (m, o) · (o, p) · ... ), which you hint at with "(1 ongoing and 1 that...)", then use (if available):
```
from functools import partial
fnames = map("matrix{}.txt".f... | Kordi's answer loads *all* of the matrices before doing the multiplication. And that's fine if you know the matrices are going to be small. If you want to conserve memory, however, I'd do the following:
```
import numpy as np
def get_dot_product(fnames):
assert len(fnames) > 0
accum_val = np.loadtxt(fnames[0]... |
35,811,400 | I have about 650 csv-based matrices. I plan on loading each one using Numpy as in the following example:
```
m1 = numpy.loadtext(open("matrix1.txt", "rb"), delimiter=",", skiprows=1)
```
There are matrix2.txt, matrix3.txt, ..., matrix650.txt files that I need to process.
My end goal is to multiply each matrix by ea... | 2016/03/05 | [
"https://Stackoverflow.com/questions/35811400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973851/"
] | A Python3 solution, if "each matrix by each other" actually means just multiplying them in a row and *the matrices have compatible dimensions* ( (n, m) · (m, o) · (o, p) · ... ), which you hint at with "(1 ongoing and 1 that...)", then use (if available):
```
from functools import partial
fnames = map("matrix{}.txt".f... | How about a really simple solution avoiding `map`, `reduce` and the like? The default `numpy` array object does element-wise multiplication by default.
```
size = (197, 11)
result = numpy.ones(size)
for i in range(1, 651):
result *= numpy.loadtext(open("matrix{}.txt".format(i), "rb"),
... |
43,814,236 | Example dataset columns: ["A","B","C","D","num1","num2"]. So I have 6 columns - first 4 for grouping and last 2 are numeric and means will be calculated based on groupBy statements.
I want to groupBy all possible combinations of the 4 grouping columns.
I wish to avoid explicitly typing all possible groupBy's such as gr... | 2017/05/05 | [
"https://Stackoverflow.com/questions/43814236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6647085/"
] | Syntax errors are a computer not being able to posses an imput.
Like this:
`answer = 1 +/ 6`
The computer does not recognize the `+/`
a semantics error are human errors. The computer will execute the code, but it will not be as wanted
Like this:
```
if(player = win){
print "You Lose"
}
```
It will print "Y... | Syntax error is an error which will make your code "unprocessable".
```
if true {}
```
instead of
```
if (true) {}
```
for example
Semantics error and logical errors are the same. Your code is correct, but doesn't do what you think it does.
```
while(c = true) {}
```
instead of
```
while (c == true) {}
```
... |
38,686,830 | I'm using python to input data to my script
then trying to return it back
on demand to show the results
I tried to write it as simple as possible since it's only practicing and trying to get the hang of python
here's how my script looks like
```
#!/usr/python
## imports #####
##################
import os
import... | 2016/07/31 | [
"https://Stackoverflow.com/questions/38686830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2310584/"
] | You are getting an error because your JSON data is an array and what you have done is:
```
XmlNode xml = JsonConvert.DeserializeXmlNode(sBody, "BiddingHistory");
```
the above line of code will only work for JSON objects.
So, if your JSON is an Array, then try this:
```
XmlNode xml = JsonConvert.DeserializeXmlNode... | Use service stack from nuget [Service Stack](https://www.nuget.org/packages/ServiceStack/)
add reference to your program
```
using ServiceStack;
```
Convert your json to object
```
var jRst = JsonConvert.DeserializeObject(body);
```
after that you can get xml using service stack like below
```
var xml = jRst.To... |
9,372,672 | I want to use vlc.py to play mpeg2 stream <http://wiki.videolan.org/Python_bindings>.
There are some examples here: <http://git.videolan.org/?p=vlc/bindings/python.git;a=tree;f=examples;hb=HEAD>
When I run the examples, it just can play video file, I want to know is there any examples to play video stream ? | 2012/02/21 | [
"https://Stackoverflow.com/questions/9372672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335499/"
] | According to [this](http://pastebin.com/edncPpW0) Pastebin entry, linked to in [this](https://mailman.videolan.org/pipermail/vlc-devel/2012-September/090310.html) mailing list, it can be solved using a method like this:
```
import vlc
i = vlc.Instance('--verbose 2'.split())
p = i.media_player_new()
p.set_mrl('rtp://@2... | This is a bare bones solution:
```
import vlc
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new('http://localhost/postcard/GWPE.avi')
Media.get_mrl()
player.set_media(Media)
player.play()
```
if the media is a local file you will have to alter:
```
Media = Instance.media_new... |
9,372,672 | I want to use vlc.py to play mpeg2 stream <http://wiki.videolan.org/Python_bindings>.
There are some examples here: <http://git.videolan.org/?p=vlc/bindings/python.git;a=tree;f=examples;hb=HEAD>
When I run the examples, it just can play video file, I want to know is there any examples to play video stream ? | 2012/02/21 | [
"https://Stackoverflow.com/questions/9372672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335499/"
] | According to [this](http://pastebin.com/edncPpW0) Pastebin entry, linked to in [this](https://mailman.videolan.org/pipermail/vlc-devel/2012-September/090310.html) mailing list, it can be solved using a method like this:
```
import vlc
i = vlc.Instance('--verbose 2'.split())
p = i.media_player_new()
p.set_mrl('rtp://@2... | ```
import vlc
vlcInstance = vlc.Instance()
player = vlcInstance.media_player_new()
player.set_mrl("rtsp://URL_PATH")
player.play()
```
I was able to open a stream with the following code, combining the previous answers.
Tested this with a network webcam |
9,372,672 | I want to use vlc.py to play mpeg2 stream <http://wiki.videolan.org/Python_bindings>.
There are some examples here: <http://git.videolan.org/?p=vlc/bindings/python.git;a=tree;f=examples;hb=HEAD>
When I run the examples, it just can play video file, I want to know is there any examples to play video stream ? | 2012/02/21 | [
"https://Stackoverflow.com/questions/9372672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335499/"
] | This is a bare bones solution:
```
import vlc
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new('http://localhost/postcard/GWPE.avi')
Media.get_mrl()
player.set_media(Media)
player.play()
```
if the media is a local file you will have to alter:
```
Media = Instance.media_new... | ```
import vlc
vlcInstance = vlc.Instance()
player = vlcInstance.media_player_new()
player.set_mrl("rtsp://URL_PATH")
player.play()
```
I was able to open a stream with the following code, combining the previous answers.
Tested this with a network webcam |
40,890,768 | Tensorflow is now available on Windows:
```
https://developers.googleblog.com/2016/11/tensorflow-0-12-adds-support-for-windows.html
```
I used pip install tensorflow.
I try running the intro code:
```
https://www.tensorflow.org/versions/r0.12/get_started/index.html
```
I get this error:
```
C:\Python\Python3... | 2016/11/30 | [
"https://Stackoverflow.com/questions/40890768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1239984/"
] | From the path of your Python interpreter (`C:\Python\Python35-32`), it appears that you are using the 32-bit version of Python 3.5. The official TensorFlow packages are only available for 64-bit architectures (`x64`/`amd64`), so you have two options:
1. Install the [64-bit version](https://www.python.org/ftp/python/3.... | The problem is not with platform (amd64) but with GPU drivers. You need to either install packages which runs on CPU or use that GPU ones you already installed but install also CUDA drivers. |
40,890,768 | Tensorflow is now available on Windows:
```
https://developers.googleblog.com/2016/11/tensorflow-0-12-adds-support-for-windows.html
```
I used pip install tensorflow.
I try running the intro code:
```
https://www.tensorflow.org/versions/r0.12/get_started/index.html
```
I get this error:
```
C:\Python\Python3... | 2016/11/30 | [
"https://Stackoverflow.com/questions/40890768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1239984/"
] | From the path of your Python interpreter (`C:\Python\Python35-32`), it appears that you are using the 32-bit version of Python 3.5. The official TensorFlow packages are only available for 64-bit architectures (`x64`/`amd64`), so you have two options:
1. Install the [64-bit version](https://www.python.org/ftp/python/3.... | you can find cudnn64\_5.dll file inside **"cuda\bin"**[this is cudnn-8.0-windows7-x64-v5.1\_4 zip extraction folder].Then copy above file into **"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin"**.
This is work for Python 3.5 bit 64 version and Windows 7 bit 64 environment |
40,890,768 | Tensorflow is now available on Windows:
```
https://developers.googleblog.com/2016/11/tensorflow-0-12-adds-support-for-windows.html
```
I used pip install tensorflow.
I try running the intro code:
```
https://www.tensorflow.org/versions/r0.12/get_started/index.html
```
I get this error:
```
C:\Python\Python3... | 2016/11/30 | [
"https://Stackoverflow.com/questions/40890768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1239984/"
] | From the path of your Python interpreter (`C:\Python\Python35-32`), it appears that you are using the 32-bit version of Python 3.5. The official TensorFlow packages are only available for 64-bit architectures (`x64`/`amd64`), so you have two options:
1. Install the [64-bit version](https://www.python.org/ftp/python/3.... | IF you are installing the GPU version please make sure you have following on your system:
* CUDA® Toolkit 9.0. For details, see NVIDIA's documentation Ensure
that you append the relevant Cuda pathnames to the %PATH% environment
variable as described in the NVIDIA documentation.
* The NVIDIA drivers associated with CU... |
55,681,488 | There is an existing question [How to write binary data to stdout in python 3?](https://stackoverflow.com/questions/908331/how-to-write-binary-data-to-stdout-in-python-3) but all of the answers suggest `sys.stdout.buffer` or variants thereof (e.g., manually rewrapping the file descriptor), which have a problem: they do... | 2019/04/15 | [
"https://Stackoverflow.com/questions/55681488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23845/"
] | Can't you interleave calls to `write` with `flush` ?
```
sys.stdout.write("A")
sys.stdout.buffer.write(b"B")
```
Results in:
>
> BA
>
>
>
---
```
sys.stdout.write("A")
sys.stdout.flush()
sys.stdout.buffer.write(b"B")
sys.stdout.flush()
```
Results in:
>
> AB
>
>
> | You can define a local function called `_print` (or even override the system `print` function by naming it `print`) as follows:
```
import sys
def _print(data):
"""
If data is bytes, write to stdout using sys.stdout.buffer.write,
otherwise, assume it's str and convert to bytes with utf-8
encoding befo... |
48,935,995 | I am a newbie in python. I have a question about the dimension of array.
I have (10,192,192,1) array which type is (class 'numpy.ndarray').
I would like to divid this array to 10 separated array like 10 \* (1,192,192,1). but I always got (192,192,1) array when I separate.
How can I get separated arrays as a same dimen... | 2018/02/22 | [
"https://Stackoverflow.com/questions/48935995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8032125/"
] | An intent object couldn't be created after the finish. Try it before `finish();`
```
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
```
**Update:** In your case import the intent like this.
```
import android.content.Intent
``` | As your code implies, you are calling `finish()` method before calling your new activity. In other words, the following lines of code will never run:
```
// Opening the Login Activity using Intent.
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
```
In order to sol... |
48,935,995 | I am a newbie in python. I have a question about the dimension of array.
I have (10,192,192,1) array which type is (class 'numpy.ndarray').
I would like to divid this array to 10 separated array like 10 \* (1,192,192,1). but I always got (192,192,1) array when I separate.
How can I get separated arrays as a same dimen... | 2018/02/22 | [
"https://Stackoverflow.com/questions/48935995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8032125/"
] | An intent object couldn't be created after the finish. Try it before `finish();`
```
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
```
**Update:** In your case import the intent like this.
```
import android.content.Intent
``` | You should try to clean and rebuild your project. Also delete the already build apks and then the issue might be resolved and you will be allowed to import
import android.content.Intent for using Intent. |
15,512,741 | I have a .txt file that is UTF-8 formatted and have problems to read it into Python. I have a large number of files and a conversion would be cumbersome.
So if I read the file in via
```
for line in file_obj:
...
```
I get the following error:
```
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/... | 2013/03/19 | [
"https://Stackoverflow.com/questions/15512741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There are two choices.
1. Specify the encoding when opening the file, instead of using the default.
2. Open the file in binary mode, and explicitly `decode` from `bytes` to `str`.
The first is obviously the simpler one. You don't show how you're opening the file, but assuming your code looks like this:
```
with open... | For Python 2 and 3 solution, use codecs:
```
import codecs
file_obj = codecs.open('ur file', "r", "utf-8")
for line in file_obj:
...
```
Otherwise -- Python 3 -- use abarnert's [solution](https://stackoverflow.com/a/15512760/298607) |
45,414,796 | I have a list of objects with multiple attributes. I want to filter the list based on one attribute of the object (country\_code), i.e.
Current list
```
elems = [{'region_code': 'EUD', 'country_code': 'ROM', 'country_desc': 'Romania', 'event_number': '6880'},
{'region_code': 'EUD', 'country_code': 'ROM', 'country_de... | 2017/07/31 | [
"https://Stackoverflow.com/questions/45414796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5142595/"
] | I think your first approach is already pretty close to being optimal. Dictionary lookup is fast (just as fast as in a `set`) and the loop is easy to understand, even though a bit lengthy (by Python standards), but you should not sacrifice readability for brevity.
You can, however, shave off one line using `setdefault`... | I think that your approach is just fine. It would be slightly better to check `elem['country_code'] not in unique` instead of `elem['country_code'] not in unique.keys()`.
However, here is another way to do it with a list comprehension:
```
visited = set()
res = [e for e in elems
if e['country_code'] not in vi... |
58,997,105 | Fatal Python error: failed to get random numbers to initialize Python
Environment windows 10, VSC 15
Using CreateProcessA winapi and passing lpenvironment variable to run python with scripts.
when lpenvironment is passed null, it works fine.
If I set environment variable PATH and PYTHONPATH = "paths", and pass that L... | 2019/11/22 | [
"https://Stackoverflow.com/questions/58997105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9758247/"
] | The environment you pass to `CreateProcessA` must include `SYSTEMROOT`, otherwise the Win32 API call `CryptAcquireContext` will fail when called inside python during initialization.
When passing in NULL as lpEnvironment, your new process inherits the environment of the calling process, which has `SYSTEMROOT` already d... | To follow up with an example how this can very easily be triggered in pure Python software out in the real world, there are times where it is useful for Python to open up an instance of itself to do some task, where the sub-task need a specific `PYTHONPATH` be set. Often times this may be done lazily on less fussy plat... |
28,859,295 | If I am in **/home/usr** and I call python **/usr/local/rcom/bin/something.py**
How can I make the script inside **something.py** know he resides in **/usr/local/rcom/bin**?
The `os.path.abspath` is calculated with the `cwd` which is **/home/usr** in this case. | 2015/03/04 | [
"https://Stackoverflow.com/questions/28859295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67153/"
] | Assign the result of `df.groupby('User_ID')['Datetime'].apply(lambda g: len(g)>1)` to a variable so you can perform boolean indexing and then use the index from this to call `isin` and filter your orig df:
```
In [366]:
users = df.groupby('User_ID')['Datetime'].apply(lambda g: len(g)>1)
users
Out[366]:
User_ID
18975... | first, make sure you have no duplicate entries:
```
df = df.drop_duplicates()
```
then, figure out the counts for each:
```
counts = df.groupby('User_ID').Datetime.count()
```
finally, figure out where the indexes overlap:
```
df[df.User_ID.isin(counts[counts > 1].index)]
``` |
4,585,776 | I am trying for a while installing [Hg-Git addon](http://hg-git.github.com/) to my Windows 7 Operating system
1. I have crossed several difficulties like installing Python and other utilities described in [this blog](http://blog.sadphaeton.com/2009/01/20/python-development-windows-part-2-installing-easyinstallcould-b... | 2011/01/03 | [
"https://Stackoverflow.com/questions/4585776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/559792/"
] | Ok i got it so ... For others - you need to clone this repo
**HTTPS:**
```
git clone https://github.com/jelmer/dulwich.git
```
**SSH:**
```
git clone [email protected]:jelmer/dulwich.git
```
or just download source - after that you need to go to its folder when you downloaded in command line type:
```
python setu... | I created a powershell script which does the installation in one step. The prereq is you have some build tools and python already installed:
<http://ig2600.blogspot.com/2013/02/using-git-via-hg-on-windows.html> |
4,585,776 | I am trying for a while installing [Hg-Git addon](http://hg-git.github.com/) to my Windows 7 Operating system
1. I have crossed several difficulties like installing Python and other utilities described in [this blog](http://blog.sadphaeton.com/2009/01/20/python-development-windows-part-2-installing-easyinstallcould-b... | 2011/01/03 | [
"https://Stackoverflow.com/questions/4585776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/559792/"
] | In case it helps anyone, I have Windows 7 64bit and TortoiseHg and following their [instructions](http://tortoisehg.bitbucket.io/manual/1.0/nonhg.html#hg-git-git) was easy and worked without issue.
>
> **Installation**
>
>
> TortoiseHg Windows installers come with the python-git bindings (named
> dulwich) that hg-... | I created a powershell script which does the installation in one step. The prereq is you have some build tools and python already installed:
<http://ig2600.blogspot.com/2013/02/using-git-via-hg-on-windows.html> |
25,343,981 | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | 2014/08/16 | [
"https://Stackoverflow.com/questions/25343981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180189/"
] | Would something like this work?
```
self.map = {
S_Block : self._render_block,
S_Empty : self._render_empty,
S_Function: self._render_function
}
def render(self, s):
return self.map[type(s)](s)
```
Keeping a reference to a class object as a key in a dictionary and having it's ... | The overloading syntax you are looking for can be achieved using [Guido van Rossum's multimethod decorator](http://www.artima.com/weblogs/viewpost.jsp?thread=101605).
Here is a variant of the multimethod decorator which can decorate class methods (the original decorates plain functions). I've named the variant `multi... |
25,343,981 | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | 2014/08/16 | [
"https://Stackoverflow.com/questions/25343981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180189/"
] | Would something like this work?
```
self.map = {
S_Block : self._render_block,
S_Empty : self._render_empty,
S_Function: self._render_function
}
def render(self, s):
return self.map[type(s)](s)
```
Keeping a reference to a class object as a key in a dictionary and having it's ... | If you're using Python 3.4 (or are willing to install the [backport](https://pypi.python.org/pypi/singledispatch) for Python 2.6+), you can use [`functools.singledispatch`](https://docs.python.org/3/library/functools.html#functools.singledispatch) for this\*:
```
from functools import singledispatch
class S_Block(obj... |
25,343,981 | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | 2014/08/16 | [
"https://Stackoverflow.com/questions/25343981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180189/"
] | Would something like this work?
```
self.map = {
S_Block : self._render_block,
S_Empty : self._render_empty,
S_Function: self._render_function
}
def render(self, s):
return self.map[type(s)](s)
```
Keeping a reference to a class object as a key in a dictionary and having it's ... | To add some performance measurements to the @unutbu 's answer:
```
@multimethod(float)
def foo(bar: float) -> str:
return 'float: {}'.format(bar)
def foo_simple(bar):
return 'string: {}'.format(bar)
```
---
```
import time
string_type = "test"
iterations = 10000000
start_time1 = time.time()
for i in rang... |
25,343,981 | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | 2014/08/16 | [
"https://Stackoverflow.com/questions/25343981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180189/"
] | Would something like this work?
```
self.map = {
S_Block : self._render_block,
S_Empty : self._render_empty,
S_Function: self._render_function
}
def render(self, s):
return self.map[type(s)](s)
```
Keeping a reference to a class object as a key in a dictionary and having it's ... | An alternate implementation with [functools.singledispatch](https://docs.python.org/3/library/functools.html#functools.singledispatch), using the decorators as defined in [PEP-443](https://www.python.org/dev/peps/pep-0443/):
```python
from functools import singledispatch
class S_Unknown: pass
class S_Block: pass
clas... |
25,343,981 | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | 2014/08/16 | [
"https://Stackoverflow.com/questions/25343981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180189/"
] | The overloading syntax you are looking for can be achieved using [Guido van Rossum's multimethod decorator](http://www.artima.com/weblogs/viewpost.jsp?thread=101605).
Here is a variant of the multimethod decorator which can decorate class methods (the original decorates plain functions). I've named the variant `multi... | To add some performance measurements to the @unutbu 's answer:
```
@multimethod(float)
def foo(bar: float) -> str:
return 'float: {}'.format(bar)
def foo_simple(bar):
return 'string: {}'.format(bar)
```
---
```
import time
string_type = "test"
iterations = 10000000
start_time1 = time.time()
for i in rang... |
25,343,981 | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | 2014/08/16 | [
"https://Stackoverflow.com/questions/25343981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180189/"
] | The overloading syntax you are looking for can be achieved using [Guido van Rossum's multimethod decorator](http://www.artima.com/weblogs/viewpost.jsp?thread=101605).
Here is a variant of the multimethod decorator which can decorate class methods (the original decorates plain functions). I've named the variant `multi... | An alternate implementation with [functools.singledispatch](https://docs.python.org/3/library/functools.html#functools.singledispatch), using the decorators as defined in [PEP-443](https://www.python.org/dev/peps/pep-0443/):
```python
from functools import singledispatch
class S_Unknown: pass
class S_Block: pass
clas... |
25,343,981 | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | 2014/08/16 | [
"https://Stackoverflow.com/questions/25343981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180189/"
] | If you're using Python 3.4 (or are willing to install the [backport](https://pypi.python.org/pypi/singledispatch) for Python 2.6+), you can use [`functools.singledispatch`](https://docs.python.org/3/library/functools.html#functools.singledispatch) for this\*:
```
from functools import singledispatch
class S_Block(obj... | To add some performance measurements to the @unutbu 's answer:
```
@multimethod(float)
def foo(bar: float) -> str:
return 'float: {}'.format(bar)
def foo_simple(bar):
return 'string: {}'.format(bar)
```
---
```
import time
string_type = "test"
iterations = 10000000
start_time1 = time.time()
for i in rang... |
25,343,981 | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | 2014/08/16 | [
"https://Stackoverflow.com/questions/25343981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180189/"
] | If you're using Python 3.4 (or are willing to install the [backport](https://pypi.python.org/pypi/singledispatch) for Python 2.6+), you can use [`functools.singledispatch`](https://docs.python.org/3/library/functools.html#functools.singledispatch) for this\*:
```
from functools import singledispatch
class S_Block(obj... | An alternate implementation with [functools.singledispatch](https://docs.python.org/3/library/functools.html#functools.singledispatch), using the decorators as defined in [PEP-443](https://www.python.org/dev/peps/pep-0443/):
```python
from functools import singledispatch
class S_Unknown: pass
class S_Block: pass
clas... |
25,343,981 | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | 2014/08/16 | [
"https://Stackoverflow.com/questions/25343981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180189/"
] | An alternate implementation with [functools.singledispatch](https://docs.python.org/3/library/functools.html#functools.singledispatch), using the decorators as defined in [PEP-443](https://www.python.org/dev/peps/pep-0443/):
```python
from functools import singledispatch
class S_Unknown: pass
class S_Block: pass
clas... | To add some performance measurements to the @unutbu 's answer:
```
@multimethod(float)
def foo(bar: float) -> str:
return 'float: {}'.format(bar)
def foo_simple(bar):
return 'string: {}'.format(bar)
```
---
```
import time
string_type = "test"
iterations = 10000000
start_time1 = time.time()
for i in rang... |
13,621,095 | I want to use mmseg in Go as in other languages, for example, in python you can use pymmseg
So, is there is a similar Go package?
Or, how can I call the C functions from Go?
Or, how can I call shared library (\*.so) from Go like in python? | 2012/11/29 | [
"https://Stackoverflow.com/questions/13621095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/860788/"
] | you can call use C Libs as described in this tutorial:
<http://cheesesun.blogspot.de/2009/12/basic-cgo.html>
and:
<http://siganakis.com/linking-c-libraries-with-go-lang-and-stdc99>
or you may have a look at this library:
<https://github.com/awsong/MMSEGO>
its for chinese, but you may could use it to put your own ... | Use `cgo` to call C code from Go.
[Command cgo](http://golang.org/cmd/cgo/)
[C? Go? Cgo!](http://blog.golang.org/2011/03/c-go-cgo.html) |
64,143,930 | I'm trying to read a json file as a pandas dataframe and convert it to a numpy array:
```
sample.json = [[["1", "2"], ["3", "4"]], [["7", "8"], ["9", "10"]]]
-------------------------------------------------------------------
df = pd.read_json('sample.json', dtype=float)
data = df.to_numpy()
pr... | 2020/09/30 | [
"https://Stackoverflow.com/questions/64143930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14061296/"
] | Why not load the JSON file with the builtin `json` module and convert to a numpy array?
```
import json
import numpy as np
data = json.loads("""[[["1", "2"], ["3", "4"]], [["7", "8"], ["9", "10"]]]""")
np.array(data, dtype=float)
array([[[ 1., 2.],
[ 3., 4.]],
[[ 7., 8.],
[ 9., 10.]]])
`... | Your data is 3-dimensional, not 2-dimensional. DataFrames are 2-dimensional, so the only way that it can convert your `sample.json` to a dataframe is by having a 2-dimensional table containing 1-dimensional items.
The easiest is to skip the pandas part completely:
```
import json
with open('/home/robby/temp/sample.js... |
52,090,461 | I want to use firebase-admin on GAE.
So I installed firebase-admin following method.
<https://cloud.google.com/appengine/docs/standard/python/tools/using-libraries-python-27>
appengine\_config.py
```
from google.appengine.ext import vendor
# Add any libraries install in the "lib" folder.
vendor.add('lib')
```
req... | 2018/08/30 | [
"https://Stackoverflow.com/questions/52090461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8118439/"
] | The `firebase-admin` package [requires `six>=1.6.1`](http://%60https://github.com/firebase/firebase-admin-python/blob/master/setup.py#L45), so manually copying in version `1.11.0` to your app won't cause problems with that library.
However, you should ensure that the code in your app that you originally added the `six... | If there's a different version of a library in the lib directory and in the app.yaml, the one in the lib directory is the one which will be available to your app.
So, effectively, your app will be using six 1.11.0. You can verify that by logging `six.__version__` and see what version you get.
To avoid confusions, I wo... |
53,908,319 | Numbers that do not contain 4 convert just fine, but once number that contain 4 is tested, it does not convert properly.
I am new to python and I am struggling to see what was wrong in the code. The code for converting Arabic number to Roman numerals work for numbers that does not contain 4 in them. I have tried to te... | 2018/12/24 | [
"https://Stackoverflow.com/questions/53908319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10827443/"
] | Welcome to SO!
The problem is the way you are trying to define and change your variables. For example, this piece of code:
```
elif I == 4:
I == 0
IV == 1
```
should look like this instead:
```
elif I == 4:
I = 0
IV = 1
```
`==` is a boolean Operator that will return `True` if tw... | This converts any positive integer to roman numeral string:
```
def roman(num: int) -> str:
chlist = "VXLCDM"
rev = [int(ch) for ch in reversed(str(num))]
chlist = ["I"] + [chlist[i % len(chlist)] + "\u0304" * (i // len(chlist))
for i in range(0, len(rev) * 2)]
def period(p: int, ... |
53,908,319 | Numbers that do not contain 4 convert just fine, but once number that contain 4 is tested, it does not convert properly.
I am new to python and I am struggling to see what was wrong in the code. The code for converting Arabic number to Roman numerals work for numbers that does not contain 4 in them. I have tried to te... | 2018/12/24 | [
"https://Stackoverflow.com/questions/53908319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10827443/"
] | Welcome to SO!
The problem is the way you are trying to define and change your variables. For example, this piece of code:
```
elif I == 4:
I == 0
IV == 1
```
should look like this instead:
```
elif I == 4:
I = 0
IV = 1
```
`==` is a boolean Operator that will return `True` if tw... | ```
print("ARABIC TO ROMAN CONVERTER [1-3999]:- \n \n")
x=int(input("ENTER THE ARABIC NUMBER: "))
b=["",'I','II','III','IV','V','VI','VII','VIII','IX','X','XX','XXX','XL','L','LX','LXX','LXXX','XC','C','CX','CXX','CXXX','CXL','CL','CLX','CLXX','CLXXX','CXC','CC','CCC','CD','D','DC','DCC','DCCC','CM','M']
d=["",'X','XX'... |
53,908,319 | Numbers that do not contain 4 convert just fine, but once number that contain 4 is tested, it does not convert properly.
I am new to python and I am struggling to see what was wrong in the code. The code for converting Arabic number to Roman numerals work for numbers that does not contain 4 in them. I have tried to te... | 2018/12/24 | [
"https://Stackoverflow.com/questions/53908319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10827443/"
] | Welcome to SO!
The problem is the way you are trying to define and change your variables. For example, this piece of code:
```
elif I == 4:
I == 0
IV == 1
```
should look like this instead:
```
elif I == 4:
I = 0
IV = 1
```
`==` is a boolean Operator that will return `True` if tw... | Done in 2 lines! (Has an upper limit of 4000)
Here's the code:
```
n,k = {0:'',1:'I',2:'II',3:'III',4:'IV',5:'V',6:'VI',7:'VII',8:'VIII',9:'IX',10:'X',20:'XX',30:'XXX',40:'XL',50:'L',60:'LX',70:'LXX',80:'LXXX',90:'XC',100:'C',200:'CC',300:'CCC',400:'CD',500:'D',600:'DC',700:'DCC',800:'DCCC',900:'CM',1000:'M',2000:'MM'... |
53,908,319 | Numbers that do not contain 4 convert just fine, but once number that contain 4 is tested, it does not convert properly.
I am new to python and I am struggling to see what was wrong in the code. The code for converting Arabic number to Roman numerals work for numbers that does not contain 4 in them. I have tried to te... | 2018/12/24 | [
"https://Stackoverflow.com/questions/53908319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10827443/"
] | This converts any positive integer to roman numeral string:
```
def roman(num: int) -> str:
chlist = "VXLCDM"
rev = [int(ch) for ch in reversed(str(num))]
chlist = ["I"] + [chlist[i % len(chlist)] + "\u0304" * (i // len(chlist))
for i in range(0, len(rev) * 2)]
def period(p: int, ... | ```
print("ARABIC TO ROMAN CONVERTER [1-3999]:- \n \n")
x=int(input("ENTER THE ARABIC NUMBER: "))
b=["",'I','II','III','IV','V','VI','VII','VIII','IX','X','XX','XXX','XL','L','LX','LXX','LXXX','XC','C','CX','CXX','CXXX','CXL','CL','CLX','CLXX','CLXXX','CXC','CC','CCC','CD','D','DC','DCC','DCCC','CM','M']
d=["",'X','XX'... |
53,908,319 | Numbers that do not contain 4 convert just fine, but once number that contain 4 is tested, it does not convert properly.
I am new to python and I am struggling to see what was wrong in the code. The code for converting Arabic number to Roman numerals work for numbers that does not contain 4 in them. I have tried to te... | 2018/12/24 | [
"https://Stackoverflow.com/questions/53908319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10827443/"
] | Done in 2 lines! (Has an upper limit of 4000)
Here's the code:
```
n,k = {0:'',1:'I',2:'II',3:'III',4:'IV',5:'V',6:'VI',7:'VII',8:'VIII',9:'IX',10:'X',20:'XX',30:'XXX',40:'XL',50:'L',60:'LX',70:'LXX',80:'LXXX',90:'XC',100:'C',200:'CC',300:'CCC',400:'CD',500:'D',600:'DC',700:'DCC',800:'DCCC',900:'CM',1000:'M',2000:'MM'... | ```
print("ARABIC TO ROMAN CONVERTER [1-3999]:- \n \n")
x=int(input("ENTER THE ARABIC NUMBER: "))
b=["",'I','II','III','IV','V','VI','VII','VIII','IX','X','XX','XXX','XL','L','LX','LXX','LXXX','XC','C','CX','CXX','CXXX','CXL','CL','CLX','CLXX','CLXXX','CXC','CC','CCC','CD','D','DC','DCC','DCCC','CM','M']
d=["",'X','XX'... |
33,797,793 | Here is part of program 'Trackbar as the Color Palette' in python which is include with opencv. I want to use it in c++.
My problem is the last line.
```
r = cv2.getTrackbarPos('R','image')
g = cv2.getTrackbarPos('G','image')
b = cv2.getTrackbarPos('B','image')
img[:] = [b,g,r]
```
Without this command I just have ... | 2015/11/19 | [
"https://Stackoverflow.com/questions/33797793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5580005/"
] | You probably want to set all pixels of the `CV_8UC3` image `img` to the color given by `b`, `g` and `r`;
You can do this in OpenCV like:
```
img.setTo(Vec3b(b, g, r));
```
or equivalently:
```
img.setTo(Scalar(b, g, r));
```
---
In your code you're missing basically all the important parts:
* the infinite loop... | I think, you are looking for std::for\_each(). This code is untested. It is intended to show the concept, It might contain bugs:
```
// color type - use whatever you have
using color = std::array<char, 3>;
// prepare image, wherever you get that from
auto img = std::vector<color>{width * height, color{{0x00, 0x00, 0x... |
36,308,537 | I am trying to create a variable in python with prefix as `list` and then number which will be generated dynamically in the script. For example
I am trying to have a list10 where list is the prefix and 10 is the number generated dynamically.
In TCL we give like
```
list${i}
```
Is there same way in python too? | 2016/03/30 | [
"https://Stackoverflow.com/questions/36308537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1336962/"
] | The pythonic way to do this would be to make a dictionary to store your lists with the generated names as the dictionary's keys:
```
d = {}
d['list1'] = [1, 2, 3]
d['list2'] = ['a', 'b', 'c']
```
EDIT: generate key names
You can create keys like this:
```
key = 'list' + str(1) # or whatever number you are using
d... | You can use `locals()`, `vars()`, or `globals()` and inject your variable name there. For eg.
```
>>> list10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'list10' is not defined
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'x': [], '_... |
5,882,362 | What is the difference between `thread.start_new_thread` and `threading.Thread.start` in python?
I have noticed that when `start_new_thread` is called, the new thread terminates as soon as the calling thread terminates. `threading.Thread.start` is the opposite: the calling thread waits for other threads to terminat... | 2011/05/04 | [
"https://Stackoverflow.com/questions/5882362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322419/"
] | The `thread` module is the low-level threading API of Python. Its direct usage isn't recommended, unless you really need to. The `threading` module is a high-level API, built on top of `thread`. The `Thread.start` method is actually implemented using `thread.start_new_thread`.
The `daemon` attribute of `Thread` must b... | See the [threading.Thread.daemon](http://docs.python.org/library/threading.html#threading.Thread.daemon) flag - basically whenever no non-daemon threads are running, the interpreter terminates. |
53,748,145 | I'm trying to containerize my django file, and I keep running into the issue:`(2006, ’Can\‘t connect to local MySQL server through socket \‘/var/run/mysqld/mysqld.sock\’ (2 “No such file or directory”)`
I found out later mysql.sock is in this location:`/tmp/mysql.sock` instead of `/var/run/mysqld/mysqld.sock`, how do ... | 2018/12/12 | [
"https://Stackoverflow.com/questions/53748145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10241176/"
] | Without external dependencies, you can use [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) to extract elements from `A` that don't have ids in `B` and `concat` that with `B`:
```js
const A = [{id: 1, name: 'x'}, {id: 2, name: 'y'}, {id: 3, name: 'z'}];
const B... | Since you are already using lodash, you can use `_.unionBy` which merges the arrays using a criterion by which uniqueness is computed:
```
let result = _.unionBy(B, A, "id");
```
Start with `B` before `A`, so that in case of duplicates, `B` values are taken instead of `A` ones.
**Example:**
```js
let A = [
{ id... |
53,748,145 | I'm trying to containerize my django file, and I keep running into the issue:`(2006, ’Can\‘t connect to local MySQL server through socket \‘/var/run/mysqld/mysqld.sock\’ (2 “No such file or directory”)`
I found out later mysql.sock is in this location:`/tmp/mysql.sock` instead of `/var/run/mysqld/mysqld.sock`, how do ... | 2018/12/12 | [
"https://Stackoverflow.com/questions/53748145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10241176/"
] | Without external dependencies, you can use [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) to extract elements from `A` that don't have ids in `B` and `concat` that with `B`:
```js
const A = [{id: 1, name: 'x'}, {id: 2, name: 'y'}, {id: 3, name: 'z'}];
const B... | Use lodash's `_.differenceBy(A, B)` to remove all items that exist in `B` from `A`, and then combine with `B` items. This will preserve the order of A items before B items.
```js
const A = [{"id":"a","arr":"A"},{"id":"b","arr":"A"},{"id":"c","arr":"A"},{"id":"d","arr":"A"}];
const B = [{"id":"c","arr":"B"},{"id":"d"... |
53,748,145 | I'm trying to containerize my django file, and I keep running into the issue:`(2006, ’Can\‘t connect to local MySQL server through socket \‘/var/run/mysqld/mysqld.sock\’ (2 “No such file or directory”)`
I found out later mysql.sock is in this location:`/tmp/mysql.sock` instead of `/var/run/mysqld/mysqld.sock`, how do ... | 2018/12/12 | [
"https://Stackoverflow.com/questions/53748145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10241176/"
] | Without external dependencies, you can use [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) to extract elements from `A` that don't have ids in `B` and `concat` that with `B`:
```js
const A = [{id: 1, name: 'x'}, {id: 2, name: 'y'}, {id: 3, name: 'z'}];
const B... | Here is a solution that follows more of the redux styled approach...
```
// imported redux actions (these are simply strings)
import {
SOME_DEFINED_ACTION_CASE
} from '../actions/someActions';
const initialState = {
reduxList: []
}
// reducer function
export default function someReducer(state = initialState,... |
53,748,145 | I'm trying to containerize my django file, and I keep running into the issue:`(2006, ’Can\‘t connect to local MySQL server through socket \‘/var/run/mysqld/mysqld.sock\’ (2 “No such file or directory”)`
I found out later mysql.sock is in this location:`/tmp/mysql.sock` instead of `/var/run/mysqld/mysqld.sock`, how do ... | 2018/12/12 | [
"https://Stackoverflow.com/questions/53748145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10241176/"
] | Since you are already using lodash, you can use `_.unionBy` which merges the arrays using a criterion by which uniqueness is computed:
```
let result = _.unionBy(B, A, "id");
```
Start with `B` before `A`, so that in case of duplicates, `B` values are taken instead of `A` ones.
**Example:**
```js
let A = [
{ id... | Use lodash's `_.differenceBy(A, B)` to remove all items that exist in `B` from `A`, and then combine with `B` items. This will preserve the order of A items before B items.
```js
const A = [{"id":"a","arr":"A"},{"id":"b","arr":"A"},{"id":"c","arr":"A"},{"id":"d","arr":"A"}];
const B = [{"id":"c","arr":"B"},{"id":"d"... |
53,748,145 | I'm trying to containerize my django file, and I keep running into the issue:`(2006, ’Can\‘t connect to local MySQL server through socket \‘/var/run/mysqld/mysqld.sock\’ (2 “No such file or directory”)`
I found out later mysql.sock is in this location:`/tmp/mysql.sock` instead of `/var/run/mysqld/mysqld.sock`, how do ... | 2018/12/12 | [
"https://Stackoverflow.com/questions/53748145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10241176/"
] | Since you are already using lodash, you can use `_.unionBy` which merges the arrays using a criterion by which uniqueness is computed:
```
let result = _.unionBy(B, A, "id");
```
Start with `B` before `A`, so that in case of duplicates, `B` values are taken instead of `A` ones.
**Example:**
```js
let A = [
{ id... | Here is a solution that follows more of the redux styled approach...
```
// imported redux actions (these are simply strings)
import {
SOME_DEFINED_ACTION_CASE
} from '../actions/someActions';
const initialState = {
reduxList: []
}
// reducer function
export default function someReducer(state = initialState,... |
55,577,893 | I want to run a recursive function in Numba, using nopython mode. Until now I'm only getting errors. This is a very simple code, the user gives a tuple with less than five elements and then the function creates another tuple with a new value added to the tuple (in this case, the number 3). This is repeated until the fi... | 2019/04/08 | [
"https://Stackoverflow.com/questions/55577893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2136601/"
] | There are several reasons why you shouldn't do that:
* This is generally a kind of approach that will likely be faster in pure Python than in a numba-decorated function.
* Iteration will be simpler and probably faster, however beware that concatenating tuples is generally an `O(n)` operation, even in numba. So the ove... | According to [this list of proposals](https://numba.pydata.org/numba-doc/latest/proposals/typing_recursion.html) in the current releases:
>
> Recursion support in numba is currently limited to self-recursion with
> explicit type annotation for the function. This limitation comes from
> the inability to determine th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.