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
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find...
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
### Solution For the descending order we multiply here by -1 each value in the array then sort the array and then multiply back with -1. Ultimately we build the result string with string concatenation and print it out ``` import java.util.Arrays; public class MyClass { public static void main(String args[]) { ...
Hope it will work as per your requirement-> ``` public static void main(String[] args) { Integer[] arr = {1,3,3,9,60 }; List<Integer> flat = Arrays.stream(arr).sorted((a, b) -> findfirst(b) - findfirst(a)).collect(Collectors.toList()); System.out.println(flat); } ...
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find...
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
### Solution For the descending order we multiply here by -1 each value in the array then sort the array and then multiply back with -1. Ultimately we build the result string with string concatenation and print it out ``` import java.util.Arrays; public class MyClass { public static void main(String args[]) { ...
A lot of problems become easier when using Java streams. In this case you could convert all numbers to String and then sort in an order which picks the higher String value of two pairings, then finally join each number to one long one. This works for your test data, but does NOT work for other data-sets: ``` List<Int...
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find...
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
### Solution For the descending order we multiply here by -1 each value in the array then sort the array and then multiply back with -1. Ultimately we build the result string with string concatenation and print it out ``` import java.util.Arrays; public class MyClass { public static void main(String args[]) { ...
compare first number of each int then if it is the biggest put it at beginning then you continue, if first char is equal step into the second etc etc the bigest win, if it same at max-char-size. the first selected would be pushed then the second one immediatly after as you already know. In that maneer 9 > 60 cuz 960>6...
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find...
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
> > It is impossible to just sort the array to form the number that I wanted. > > > Actually, it isn't impossible. What you need is to design and implement an *ordering* that will result in the (decimal) numbers that will make the final number to be largest to sort first; e.g. for the numbers in your question, th...
Hope it will work as per your requirement-> ``` public static void main(String[] args) { Integer[] arr = {1,3,3,9,60 }; List<Integer> flat = Arrays.stream(arr).sorted((a, b) -> findfirst(b) - findfirst(a)).collect(Collectors.toList()); System.out.println(flat); } ...
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find...
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
> > It is impossible to just sort the array to form the number that I wanted. > > > Actually, it isn't impossible. What you need is to design and implement an *ordering* that will result in the (decimal) numbers that will make the final number to be largest to sort first; e.g. for the numbers in your question, th...
A lot of problems become easier when using Java streams. In this case you could convert all numbers to String and then sort in an order which picks the higher String value of two pairings, then finally join each number to one long one. This works for your test data, but does NOT work for other data-sets: ``` List<Int...
65,770,185
I try to make a python script that gets the dam occupancy rates from a website. Here is the code: ``` baraj_link = "https://www.turkiye.gov.tr/istanbul-su-ve-kanalizasyon-idaresi-baraj-doluluk-oranlari" response = requests.get(baraj_link) soup = BeautifulSoup(response.text, "lxml") values_list = [] values = soup.find...
2021/01/18
[ "https://Stackoverflow.com/questions/65770185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375618/" ]
> > It is impossible to just sort the array to form the number that I wanted. > > > Actually, it isn't impossible. What you need is to design and implement an *ordering* that will result in the (decimal) numbers that will make the final number to be largest to sort first; e.g. for the numbers in your question, th...
compare first number of each int then if it is the biggest put it at beginning then you continue, if first char is equal step into the second etc etc the bigest win, if it same at max-char-size. the first selected would be pushed then the second one immediatly after as you already know. In that maneer 9 > 60 cuz 960>6...
30,207,041
Been using the safe and easy confines of PyCharm for a bit now, but I'm trying to get more familiar with using a text editor and the terminal together, so I've forced myself to start using iPython Notebook and Emacs. Aaaaand I have some really dumb questions. * after firing up ipython notebook from terminal with the c...
2015/05/13
[ "https://Stackoverflow.com/questions/30207041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4698759/" ]
* Yes, you can not use the same terminal. Solutions: open another terminal or run `ipython notebook` inside [`screen`](http://www.gnu.org/software/screen/manual/screen.html). If you use Windows you might want to take a look into [this question](https://stackoverflow.com/questions/5473384/terminal-multiplexer-for-micros...
* You can run your IPython notebook process in background. On Unix platforms you can perform that with (note the leading `&`): ``` ipython notebook & ``` Or after a "normal" run, hit `[Control+z]` and run the `bg` command ([some lecture](http://web.mit.edu/gnu/doc/html/features_5.html)). * you can convert `.ipynb`...
44,813,375
I am interested in the truth value of Python sets like `{'a', 'b'}`, or the empty set `set()` (which is not the same as the empty dictionary `{}`). In particular, I would like to know whether `bool(my_set)` is `False` if and only if the set `my_set` is empty. Ignoring primitive (such as numerals) as well as user-defin...
2017/06/28
[ "https://Stackoverflow.com/questions/44813375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6867099/" ]
After looking at the source code for CPython, I would guess this is a documentation error, however, it could be implementation dependent and therefore would be a good issue to raise on the Python bug tracker. Specifically, [object.c](https://github.com/python/cpython/blob/a66f9c6bb134561a24374f10e8c35417d356ce14/Objec...
That part of the docs is poorly written, or rather, poorly maintained. The following clause: > > instances of user-defined classes, if the class defines a `__bool__()` or `__len__()` method, when that method returns the integer zero or bool value False. > > > really applies to *all* classes, user-defined or not, ...
44,813,375
I am interested in the truth value of Python sets like `{'a', 'b'}`, or the empty set `set()` (which is not the same as the empty dictionary `{}`). In particular, I would like to know whether `bool(my_set)` is `False` if and only if the set `my_set` is empty. Ignoring primitive (such as numerals) as well as user-defin...
2017/06/28
[ "https://Stackoverflow.com/questions/44813375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6867099/" ]
After looking at the source code for CPython, I would guess this is a documentation error, however, it could be implementation dependent and therefore would be a good issue to raise on the Python bug tracker. Specifically, [object.c](https://github.com/python/cpython/blob/a66f9c6bb134561a24374f10e8c35417d356ce14/Objec...
The documentation for [`__bool__`](https://docs.python.org/3/reference/datamodel.html#object.__bool__) states that this method is called for truth value testing and if it is not defined then [`__len__`](https://docs.python.org/3/reference/datamodel.html#object.__len__) is evaluated: > > Called to implement truth valu...
44,813,375
I am interested in the truth value of Python sets like `{'a', 'b'}`, or the empty set `set()` (which is not the same as the empty dictionary `{}`). In particular, I would like to know whether `bool(my_set)` is `False` if and only if the set `my_set` is empty. Ignoring primitive (such as numerals) as well as user-defin...
2017/06/28
[ "https://Stackoverflow.com/questions/44813375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6867099/" ]
The documentation for [`__bool__`](https://docs.python.org/3/reference/datamodel.html#object.__bool__) states that this method is called for truth value testing and if it is not defined then [`__len__`](https://docs.python.org/3/reference/datamodel.html#object.__len__) is evaluated: > > Called to implement truth valu...
That part of the docs is poorly written, or rather, poorly maintained. The following clause: > > instances of user-defined classes, if the class defines a `__bool__()` or `__len__()` method, when that method returns the integer zero or bool value False. > > > really applies to *all* classes, user-defined or not, ...
59,063,829
I tried to get a vector dot product in a nested list For example : ``` A = np.array([[1,2,1,3],[2,1,2,3],[3,1,2,4]]) ``` And I tried to get: ``` B = [[15], [19, 23]] ``` Where 15 = np.dot(A[0],A[1]), 19 = np.dot(A[0],A[2]), 23 = np.dot(A[1],A[2]) The fist inner\_list in B is the dot product of A[0] and A[1], ...
2019/11/27
[ "https://Stackoverflow.com/questions/59063829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10595338/" ]
Here is a explicit for loop coupled with list comprehension solution: ``` In [1]: import numpy as np In [2]: A = np.array([[1,2,1,3],[2,1,2,3],[3,1,2,4]]) In [5]: def get_dp(A): ...: out = [] ...: for i, a in enumerate(A[1:]): ...: out.append([np.dot(a, b) for b in A[:i+1]]) ...: retu...
An iterator class that spits out elements same as B. If you want the full list, you can `list(iter_dotprod(A))` example: ```py class iter_dotprod: def __init__(self, nested_arr): self.nested_arr = nested_arr self.hist = [] def __iter__(self): self.n = 0 return self def _...
64,799,010
I am trying to get all ec2 instances details in a csv file, followed another post "https://stackoverflow.com/questions/62815990/export-aws-ec2-details-to-xlsx-csv-using-boto3-and-python". But was having attribute error for Instances. So I am trying this: ``` import boto3 import datetime import csv ec2 = ...
2020/11/12
[ "https://Stackoverflow.com/questions/64799010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14614887/" ]
Since you are using `DictWriter`, your `output` should be: ``` output = { 'Instancename': Instancename, 'Id': Id, 'State': State, 'Platform': str(Platform), 'InstanceType': InstanceType , 'Launched': str(Lau...
A [`DictWriter`](https://docs.python.org/3/library/csv.html#csv.DictWriter) - as the name would suggest - writes `dicts` i.e. dictionaries to a CSV file. The dictionary must have the keys that correspond to the column names. See the example in the docs I linked. In the code you posted, you are passing `output` - a str...
72,842,182
I am using flask with this code: ```py from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True, port=8000) ``` ```html <form method="GET"> <p>Phone number:</p> <i...
2022/07/02
[ "https://Stackoverflow.com/questions/72842182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409503/" ]
In most cases, if you are using `react-hook-form`, you don't need to track form fields with `useState` hook. Using a `Controller` component is the right way to go. But there is a problem with `onChange` handler in your 1st method. When you submit form, you are getting default date `null` because `field` is destructed...
I couldn't replicate your setup, but my guess is that in the first render the reference to the 'setOriginalReleaseDate' is lost when being passed through the Controller's render arrow function. ``` ... onChange={(newValue) => { setOriginalReleaseDate(newValue); ...
72,842,182
I am using flask with this code: ```py from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True, port=8000) ``` ```html <form method="GET"> <p>Phone number:</p> <i...
2022/07/02
[ "https://Stackoverflow.com/questions/72842182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409503/" ]
Just modified the above answer with a bracket. ```js const [reqDate, setreqDate] = useState(new Date()); <Controller name="reqDate" defaultValue={reqDate} control={control} render={ ({ field: { onChange, ...restField } }) => <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker...
I couldn't replicate your setup, but my guess is that in the first render the reference to the 'setOriginalReleaseDate' is lost when being passed through the Controller's render arrow function. ``` ... onChange={(newValue) => { setOriginalReleaseDate(newValue); ...
72,842,182
I am using flask with this code: ```py from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True, port=8000) ``` ```html <form method="GET"> <p>Phone number:</p> <i...
2022/07/02
[ "https://Stackoverflow.com/questions/72842182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409503/" ]
``` InputDate.propTypes = { name: PropTypes.string, label: PropTypes.string, }; export default function InputDate({ name, label }) { const { control } = useFormContext(); return ( <Controller name={name} control={control} render={({ field: { onChange, value }, fieldState: { error } }) => (...
I couldn't replicate your setup, but my guess is that in the first render the reference to the 'setOriginalReleaseDate' is lost when being passed through the Controller's render arrow function. ``` ... onChange={(newValue) => { setOriginalReleaseDate(newValue); ...
72,842,182
I am using flask with this code: ```py from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True, port=8000) ``` ```html <form method="GET"> <p>Phone number:</p> <i...
2022/07/02
[ "https://Stackoverflow.com/questions/72842182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409503/" ]
Just modified the above answer with a bracket. ```js const [reqDate, setreqDate] = useState(new Date()); <Controller name="reqDate" defaultValue={reqDate} control={control} render={ ({ field: { onChange, ...restField } }) => <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker...
In most cases, if you are using `react-hook-form`, you don't need to track form fields with `useState` hook. Using a `Controller` component is the right way to go. But there is a problem with `onChange` handler in your 1st method. When you submit form, you are getting default date `null` because `field` is destructed...
72,842,182
I am using flask with this code: ```py from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True, port=8000) ``` ```html <form method="GET"> <p>Phone number:</p> <i...
2022/07/02
[ "https://Stackoverflow.com/questions/72842182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409503/" ]
Just modified the above answer with a bracket. ```js const [reqDate, setreqDate] = useState(new Date()); <Controller name="reqDate" defaultValue={reqDate} control={control} render={ ({ field: { onChange, ...restField } }) => <LocalizationProvider dateAdapter={AdapterDateFns}> <DatePicker...
``` InputDate.propTypes = { name: PropTypes.string, label: PropTypes.string, }; export default function InputDate({ name, label }) { const { control } = useFormContext(); return ( <Controller name={name} control={control} render={({ field: { onChange, value }, fieldState: { error } }) => (...
48,399,812
I have a python script that has to be executed with start and end dates. I want to execute this file for each day in the year 2012, so I thought a while-loop inside a bash script would do the job but my bash-skills are not sufficient. This is what I tried: ``` day_start = 2012-01-01 while [ "$day_start" != 2013-01...
2018/01/23
[ "https://Stackoverflow.com/questions/48399812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7436993/" ]
Answer is simply stupid... Just restart your OS X. I don't know why, it looks like that operation system needs to rebuild some data after doing scenario from this question
Found submitted issue and solved it using the steps given here <https://github.com/desktop/desktop/issues/3625> * Open Keychain Access.app * Right click on login * Click locking * Click unlocking
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This ...
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
`a if b else c` syntax was introduced in Python 2.5. Most people have already upgraded to the recent version but in legacy code you may find another approach: ``` some_var = a<b and a or c ``` If you ever will be using this syntax remember that `a` must not evaluate to False.
Try this in Python: ``` return i if i < x else x ``` It's exactly the equivalent of the following expression in Java, C, C++ C# ``` return i < x ? i : x; ``` Read more about Python's [conditional expressions](http://docs.python.org/reference/expressions.html#conditional-expressions).
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This ...
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
You can use `(x if cond else y)`, e.g. ``` >>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a ``` That will work will [lambda function](http://www.python.org/dev/peps/pep-0308/) too.
`a if b else c` syntax was introduced in Python 2.5. Most people have already upgraded to the recent version but in legacy code you may find another approach: ``` some_var = a<b and a or c ``` If you ever will be using this syntax remember that `a` must not evaluate to False.
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This ...
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
`a if b else c` syntax was introduced in Python 2.5. Most people have already upgraded to the recent version but in legacy code you may find another approach: ``` some_var = a<b and a or c ``` If you ever will be using this syntax remember that `a` must not evaluate to False.
Ternary operator in python. > > a if b else c > > > ``` >>> a=1 >>> b=2 >>> a if a<b else b 1 >>> a if a>b else b 2 ```
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This ...
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
You can use `(x if cond else y)`, e.g. ``` >>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a ``` That will work will [lambda function](http://www.python.org/dev/peps/pep-0308/) too.
As the other answers state, Python's version for this is: `i if i < x else x` (of course for this particular example, one would prefer writing `min(i, x)` , as it is easier on the eyes) However, this expression syntax was just made available on Python 2.5 (I think it was around 2004). before that, the following id...
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This ...
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
You can use `(x if cond else y)`, e.g. ``` >>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a ``` That will work will [lambda function](http://www.python.org/dev/peps/pep-0308/) too.
Yes, it looks like this: ``` return i if i < x else x ``` It's called the conditional operator in python.
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This ...
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
Yes, it looks like this: ``` return i if i < x else x ``` It's called the conditional operator in python.
Ternary operator in python. > > a if b else c > > > ``` >>> a=1 >>> b=2 >>> a if a<b else b 1 >>> a if a>b else b 2 ```
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This ...
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
`a if b else c` syntax was introduced in Python 2.5. Most people have already upgraded to the recent version but in legacy code you may find another approach: ``` some_var = a<b and a or c ``` If you ever will be using this syntax remember that `a` must not evaluate to False.
As the other answers state, Python's version for this is: `i if i < x else x` (of course for this particular example, one would prefer writing `min(i, x)` , as it is easier on the eyes) However, this expression syntax was just made available on Python 2.5 (I think it was around 2004). before that, the following id...
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This ...
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
You can use `(x if cond else y)`, e.g. ``` >>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a ``` That will work will [lambda function](http://www.python.org/dev/peps/pep-0308/) too.
Ternary operator in python. > > a if b else c > > > ``` >>> a=1 >>> b=2 >>> a if a<b else b 1 >>> a if a>b else b 2 ```
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This ...
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
You can use `(x if cond else y)`, e.g. ``` >>> x = 0 >>> y = 1 >>> print("a" if x < y else "b") a ``` That will work will [lambda function](http://www.python.org/dev/peps/pep-0308/) too.
Try this in Python: ``` return i if i < x else x ``` It's exactly the equivalent of the following expression in Java, C, C++ C# ``` return i < x ? i : x; ``` Read more about Python's [conditional expressions](http://docs.python.org/reference/expressions.html#conditional-expressions).
8,957,186
> > **Possible Duplicate:** > > [Python Ternary Operator](https://stackoverflow.com/questions/394809/python-ternary-operator) > > > In some languages including Java, C/C++, C#, etc. you can assign a value based on the result of an inline boolean expression. For example, ``` return (i < x) ? i : x ``` This ...
2012/01/21
[ "https://Stackoverflow.com/questions/8957186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1162865/" ]
Yes, it looks like this: ``` return i if i < x else x ``` It's called the conditional operator in python.
Try this in Python: ``` return i if i < x else x ``` It's exactly the equivalent of the following expression in Java, C, C++ C# ``` return i < x ? i : x; ``` Read more about Python's [conditional expressions](http://docs.python.org/reference/expressions.html#conditional-expressions).
44,781,806
I seem to be breaking `tkinter` on linux by using some multi-threading. As far as I can see, I am managing to trigger a garbage collection on a thread which is not the main GUI thread. This is causing `__del__` to be run on a `tk.StringVar` instance, which tries to call the `tcl` stack from the wrong thread, causing ch...
2017/06/27
[ "https://Stackoverflow.com/questions/44781806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3403507/" ]
I had exactly the same problem It was a nightmare to find the cause of the issue. I exaustivelly verified that no tkinter object was being called from any thread. I made a mechanism based in queues to handle tkinter objects in threads. There are many examples on the web on how to do that, or... search for a module 'mt...
Tkinter is not thread safe. Calling Tkinter objects in a thread may cause things such as "The **del** method on Widget verifies that the Widget instance is being deleted from the other thread." You can use locking and queues to make it done properly. Check this example: [Tkinter: How to use threads to preventing main...
72,882,082
Can someone explain me what is going on here and how to prevent this? I have a **main.py** with the following code: ```python import utils import torch if __name__ == "__main__": # Foo print("Foo") # Bar utils.bar() model = torch.hub.load("ultralytics/yolov5", "yolov5s") ``` I outsourced some...
2022/07/06
[ "https://Stackoverflow.com/questions/72882082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4875142/" ]
It is not `DELETE * FROM`, but `DELETE FROM`. ``` DELETE FROM mlode WHERE kd >= DATE '2019-01-01'; ```
``` BEGIN TRANSACTION DELETE FROM [TABLE] WHERE [DATEFIELD] > DATEFROMPARTS(2018, 12, 30) COMMIT TRANSACTION ```
19,699,314
Below is my test code. When running with python2.7 it shows that the program won't receive any signal until all spawned threads finish. While with python3.2, only the main thread's sigintHandler gets called. I'am confused with how python handles threads and signal, so how do I spawn a thread and do signal hand...
2013/10/31
[ "https://Stackoverflow.com/questions/19699314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922727/" ]
You can give like ``` $(this).datepicker({ "dateFormat": 'mm/dd/yy', "changeMonth": true, "changeYear": true, "yearRange": year + ":" + year }); ```
Read [yearRange](http://api.jqueryui.com/datepicker/#option-yearRange) ``` var year_text = year + ":" + year ; ``` or ``` "yearRange": year + ":" + year ```
19,699,314
Below is my test code. When running with python2.7 it shows that the program won't receive any signal until all spawned threads finish. While with python3.2, only the main thread's sigintHandler gets called. I'am confused with how python handles threads and signal, so how do I spawn a thread and do signal hand...
2013/10/31
[ "https://Stackoverflow.com/questions/19699314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/922727/" ]
You can give like ``` $(this).datepicker({ "dateFormat": 'mm/dd/yy', "changeMonth": true, "changeYear": true, "yearRange": year + ":" + year }); ```
You can set it like this ``` $(function() { var minYear=1990; var maxYear=2000; $( "#datepicker" ).datepicker({ yearRange: minYear+':'+ maxYear, changeYear: true }); }); ``` [CHECK THIS LIVE JSFIDDLE DEMO](http://jsfiddle.net/kGjdL/457/)
48,577,536
**Background** I would like to do mini-batch training of "stateful" LSTMs in Keras. My input training data is in a large matrix "X" whose dimensions are m x n where ```python m = number-of-subsequences n = number-of-time-steps-per-sequence ``` Each row of X contains a subsequence which picks up where the subsequenc...
2018/02/02
[ "https://Stackoverflow.com/questions/48577536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4441470/" ]
You can set you ViewHolder class as [`inner`](https://kotlinlang.org/docs/reference/nested-classes.html)
Use the `companion object`: ``` class MyAdapter(private val dataList: ArrayList<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() { class ViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener { fun bindData() { //some statements } override fun onClic...
48,577,536
**Background** I would like to do mini-batch training of "stateful" LSTMs in Keras. My input training data is in a large matrix "X" whose dimensions are m x n where ```python m = number-of-subsequences n = number-of-time-steps-per-sequence ``` Each row of X contains a subsequence which picks up where the subsequenc...
2018/02/02
[ "https://Stackoverflow.com/questions/48577536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4441470/" ]
You can set you ViewHolder class as [`inner`](https://kotlinlang.org/docs/reference/nested-classes.html)
You can also put ``` private val TAG: String? = MyAdapter::class.simpleName ``` on top level of the file.
48,577,536
**Background** I would like to do mini-batch training of "stateful" LSTMs in Keras. My input training data is in a large matrix "X" whose dimensions are m x n where ```python m = number-of-subsequences n = number-of-time-steps-per-sequence ``` Each row of X contains a subsequence which picks up where the subsequenc...
2018/02/02
[ "https://Stackoverflow.com/questions/48577536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4441470/" ]
Use the `companion object`: ``` class MyAdapter(private val dataList: ArrayList<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() { class ViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener { fun bindData() { //some statements } override fun onClic...
You can also put ``` private val TAG: String? = MyAdapter::class.simpleName ``` on top level of the file.
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ...
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
I can't reproduce your problem with a simple test: ``` Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> group = u'Luleå' >>> logging.warning('Group: %s', group) WARNING:root:Group: Luleå >>> logging.wa...
have you tried manually making any result unicode? ``` logging.debug(u'new groups %s' % unicode(list_of_groups("UTF-8")) ```
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ...
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Here's my test code: ``` #-*- coding: utf-8 -*- class Wrap: def __init__(self, s): self.s = s def __repr__(self): return repr(self.s) def __unicode__(self): return unicode(self.s) def __str__(self): return str(self.s) ...
I can't reproduce your problem with a simple test: ``` Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> group = u'Luleå' >>> logging.warning('Group: %s', group) WARNING:root:Group: Luleå >>> logging.wa...
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ...
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
have you tried manually making any result unicode? ``` logging.debug(u'new groups %s' % unicode(list_of_groups("UTF-8")) ```
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ...
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
I encountered the same issues: see <http://hustoknow.blogspot.com/2012/09/unicode-quirks-in-django.html>. You can declare a **str**() method to override the Django default behavior, which will help to avoid this issue. Or you always have to prefix the u' in front of your logging() statements.
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ...
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
I can't reproduce your problem with a simple test: ``` Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import logging >>> group = u'Luleå' >>> logging.warning('Group: %s', group) WARNING:root:Group: Luleå >>> logging.wa...
I think, that this bug of Python is the reason of described behavior <https://bugs.python.org/issue19846> Check locale settings, if you getting UnicodeDecodeError on Python 3. This answer <https://stackoverflow.com/a/40803148/4862792> helps me for windows, but on production with locale LANG\_C I`ve got this problem on...
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ...
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Here's my test code: ``` #-*- coding: utf-8 -*- class Wrap: def __init__(self, s): self.s = s def __repr__(self): return repr(self.s) def __unicode__(self): return unicode(self.s) def __str__(self): return str(self.s) ...
have you tried manually making any result unicode? ``` logging.debug(u'new groups %s' % unicode(list_of_groups("UTF-8")) ```
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ...
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
I think, that this bug of Python is the reason of described behavior <https://bugs.python.org/issue19846> Check locale settings, if you getting UnicodeDecodeError on Python 3. This answer <https://stackoverflow.com/a/40803148/4862792> helps me for windows, but on production with locale LANG\_C I`ve got this problem on...
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ...
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
Check: ``` import locale locale.getpreferredencoding() ``` must be 'utf8'. I have 'cp1252'. Helped me add to manage.py: ``` import _locale _locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8']) ``` Windows 10, Django 1.10.3, Python 3.5.2, fixed problems with russian language
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ...
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Here's my test code: ``` #-*- coding: utf-8 -*- class Wrap: def __init__(self, s): self.s = s def __repr__(self): return repr(self.s) def __unicode__(self): return unicode(self.s) def __str__(self): return str(self.s) ...
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
2,111,765
totally confused by now... I am developing in python/django and using python logging. All of my app requires unicode and all my models have only a **unicode**()`, return u'..' methods implemented. Now when logging I have come upon a really strange issue that it took a long time to discover that I could reproduce it. I ...
2010/01/21
[ "https://Stackoverflow.com/questions/2111765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256037/" ]
Try to use this code in the top of your views.py ``` #-*- coding: utf-8 -*- ... ```
I don't understand what it is you don't understand, if you see what I mean. Your middle paragraph: > > So, my understanding is that the list starts to generate itself and does repr() on all its elements and they return their values - in this case it should be 's2 | ÅÄÖÖ', then the list presents itself as (ascii, the...
46,591,968
im new to python and im failing to achieve this. I have two lists of lists: ``` list1 = [['user1', 'id1'], ['user2', 'id2'], ['user3', 'id3']...] list2 = [['id1', 'group1'], ['id1', 'group2'], ['id2', 'group1'], ['id2', 'group4']...] ``` And what i need is a single list like this: ``` [['user1','id1','group1'],['u...
2017/10/05
[ "https://Stackoverflow.com/questions/46591968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8419741/" ]
There's no such thing in python. There are methods for multidimensional arrays in `numpy`, but they are not really suitable for text. Your second list functions as a dictionary, so make one ``` dict2 = {key:value for key, value in list2} ``` and then ``` new_list = [[a, b, dict2[b]] for a, b in list1] ```
If you have to use lists of lists, you can use a comprehension to achieve this. ``` list1 = [['user1', 'id1'], ['user2', 'id2']] list2 = [['id1', 'group1'], ['id1', 'group2'], ['id2', 'group1'], ['id2', 'group4']] listOut = [[x[0],x[1],y[1]] for x in list1 for y in list2 if x[1] == y[0]] output => [['user1', 'id1', ...
46,591,968
im new to python and im failing to achieve this. I have two lists of lists: ``` list1 = [['user1', 'id1'], ['user2', 'id2'], ['user3', 'id3']...] list2 = [['id1', 'group1'], ['id1', 'group2'], ['id2', 'group1'], ['id2', 'group4']...] ``` And what i need is a single list like this: ``` [['user1','id1','group1'],['u...
2017/10/05
[ "https://Stackoverflow.com/questions/46591968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8419741/" ]
There's no such thing in python. There are methods for multidimensional arrays in `numpy`, but they are not really suitable for text. Your second list functions as a dictionary, so make one ``` dict2 = {key:value for key, value in list2} ``` and then ``` new_list = [[a, b, dict2[b]] for a, b in list1] ```
You can try this code : ``` list1 = [['user1', 'id1'], ['user2', 'id2'], ['user3', 'id3']] list2 = [['id1', 'group1'], ['id1', 'group2'], ['id2', 'group1'], ['id2', 'group4']] final_list=[] for sublist in list1: for item in sublist: for sublist1 in list2: for item1 in sublist1: ...
57,660,887
I just need contexts to be an Array ie., 'contexts' :[{}] instead of 'contexts':{} Below is my python code which helps in converting python data-frame to required JSON format This is the sample df for one row ``` name type aim context xxx xxx specs 67646546 United States of America data = {'e...
2019/08/26
[ "https://Stackoverflow.com/questions/57660887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11922956/" ]
I think this does it: ``` import pandas as pd import json df = pd.DataFrame([['xxx xxx','specs','67646546','United States of America']], columns = ['name', 'type', 'aim', 'context' ]) data = {'entities':[]} for key,grp in df.groupby('name'): for idx, row in grp.iterrows(): temp_dic...
The problem is here in the following code ``` temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':{'attributes':{},'context':{'dcountry':row['dcountry']}}}} ``` As you can see , you are already creating a `contexts` `dict` and assigning values to it. What you could do is something like this ``` ...
3,764,791
Is there any fb tag i can use to wrap around my html anchor tag so that if the user isn't logged in, they will get prompted to login before getting access to the link? I'm using python/django in backend. Thanks, David
2010/09/21
[ "https://Stackoverflow.com/questions/3764791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225128/" ]
This is just an interpretation question, but I would say that you would take the decimal representation of a number, and count the total number of digits that are 6, 4, or 9. For example: * 100 --> 0 * 4 --> 1 * 469 --> 3 * 444 --> 3 Get it now?
One interpretation - example: Given `678799391`, the number of digits would be `0` for `4`, `1` for `6` and `3` for `9`. The sum of the occurences would be `0 + 1 + 3 = 4`.
3,764,791
Is there any fb tag i can use to wrap around my html anchor tag so that if the user isn't logged in, they will get prompted to login before getting access to the link? I'm using python/django in backend. Thanks, David
2010/09/21
[ "https://Stackoverflow.com/questions/3764791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225128/" ]
This is just an interpretation question, but I would say that you would take the decimal representation of a number, and count the total number of digits that are 6, 4, or 9. For example: * 100 --> 0 * 4 --> 1 * 469 --> 3 * 444 --> 3 Get it now?
Convert the whole number to a list and check each one individually. ``` (define (number->list x) (string->list (number->string x)) (define (6-4-or-9 x) (cond ((= x 6) true)) ((= x 4) true)) ((= x 9) true)))) (define (count-6-4-9 x) (cond ((6-4-or-9 (car (number->list x))))....... ``` I'm sure you can see where ...
3,764,791
Is there any fb tag i can use to wrap around my html anchor tag so that if the user isn't logged in, they will get prompted to login before getting access to the link? I'm using python/django in backend. Thanks, David
2010/09/21
[ "https://Stackoverflow.com/questions/3764791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225128/" ]
This is just an interpretation question, but I would say that you would take the decimal representation of a number, and count the total number of digits that are 6, 4, or 9. For example: * 100 --> 0 * 4 --> 1 * 469 --> 3 * 444 --> 3 Get it now?
If you are not using lists, you can work with modulo `%` of 10 and dividing whole numbers `/` with 10. Below is the recursive solution : ``` (define (digits n) (if(not (< n 1)) (+ 1 (digits (/ n 10))) 0)) ```
3,764,791
Is there any fb tag i can use to wrap around my html anchor tag so that if the user isn't logged in, they will get prompted to login before getting access to the link? I'm using python/django in backend. Thanks, David
2010/09/21
[ "https://Stackoverflow.com/questions/3764791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225128/" ]
This is just an interpretation question, but I would say that you would take the decimal representation of a number, and count the total number of digits that are 6, 4, or 9. For example: * 100 --> 0 * 4 --> 1 * 469 --> 3 * 444 --> 3 Get it now?
First, we must understand what the question is asking: It is asking you to write a procedure that counts the number of times the numbers 4, 6, or 9 show up in another inputted number. For instance, inputting `10345` should return `1`. Let's see why: The digits of `10345` are `1`, `0`, `3`, `4`, and `5`. We have to ask...
60,578,442
When I tried to add value of language python3 returns error that this object is not JSON serializible. models: ``` from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser class Admin(AbstractUser): class Meta(AbstractUser.Meta): pass class HahaUser(AbstractBas...
2020/03/07
[ "https://Stackoverflow.com/questions/60578442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13023793/" ]
The result of account.language is an instance. So, in your `registration_view`, data['language'] got an instance rather than string or number. That's the reason why data's language is not JSON serializable. Based on your requirements, you can change it to `data['language'] = account.language.name`
As exception says, `language` is an object of `Language` model and it's not a primitive type. So you should use some attributes of Language model like `language_id` or `language_name` instead of language object. ```py from rest_framework import serializers from main import models class RegistrationSerializer(seriali...
60,578,442
When I tried to add value of language python3 returns error that this object is not JSON serializible. models: ``` from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser class Admin(AbstractUser): class Meta(AbstractUser.Meta): pass class HahaUser(AbstractBas...
2020/03/07
[ "https://Stackoverflow.com/questions/60578442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13023793/" ]
As exception says, `language` is an object of `Language` model and it's not a primitive type. So you should use some attributes of Language model like `language_id` or `language_name` instead of language object. ```py from rest_framework import serializers from main import models class RegistrationSerializer(seriali...
Thank you for help, but I'd solve it myself. I just add str() to foreign keys on my view where I generate JSON response. ``` from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import RegistrationSerializer @api_view(['P...
60,578,442
When I tried to add value of language python3 returns error that this object is not JSON serializible. models: ``` from django.db import models from django.contrib.auth.models import AbstractUser, AbstractBaseUser class Admin(AbstractUser): class Meta(AbstractUser.Meta): pass class HahaUser(AbstractBas...
2020/03/07
[ "https://Stackoverflow.com/questions/60578442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13023793/" ]
The result of account.language is an instance. So, in your `registration_view`, data['language'] got an instance rather than string or number. That's the reason why data's language is not JSON serializable. Based on your requirements, you can change it to `data['language'] = account.language.name`
Thank you for help, but I'd solve it myself. I just add str() to foreign keys on my view where I generate JSON response. ``` from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import RegistrationSerializer @api_view(['P...
47,978,878
Hi I am using APScheduler in a Django project. How can I plan a call of a function in python when the job is done? A callback function. I store job as Django models in DB. As it completes, I want to mark it as `completed=1` in the table.
2017/12/26
[ "https://Stackoverflow.com/questions/47978878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4537090/" ]
The easiest and generic way to do it would be to add your callback function to the end of the scheduled job. You can also build on top of the scheduler class to include a self.function\_callback() at the end of the tasks. Quick example: ``` def tick(): print('Tick! The time is: %s' % datetime.now()) time.slee...
[Listener](https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-events) allows to hook various [events](https://apscheduler.readthedocs.io/en/latest/modules/events.html#event-codes) of APScheduler. I have succeeded to get the *next run time* of my job using EVENT\_JOB\_SUBMITTED. (Updated) I confirmed...
1,780,066
hopefully someone here can shed some light on my issue :D I've been creating a Windows XP service in python that is designed to monitor/repair selected Windows/Application/Service settings, atm I have been focusing on default DCOM settings. The idea is to backup our default configuration within another registry key f...
2009/11/22
[ "https://Stackoverflow.com/questions/1780066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/94071/" ]
So I guess it's time to admit my stupidity.... :P It turns out this was not a python issue, py2exe issue, nor a WMI issue. :( This was more or less a simple permission issue. So simple I overlooked it for the better part of a month. :( Rule of thumb, if you want to create a service that calls to specific registry ke...
I am not an expert at this, but here are my two cents worth: [This article](http://www.firebirdsql.org/devel/python/docs/3.3.0/installation.html) tells me that you might need to be logged in as someone with the required target system permissions. However, I find that a little excessive. Have you tried compiling your...
69,153,402
Lets say I have a list that references another list, as follows: ``` list1 = [1,2,3,4,5] list2 = [list1[0], list1[1], list1[2]] ``` I wish to interact with list1 through list2, as follows: ``` list2[1] = 'a' print(list1[1]) ``` and that result should be 'a'. Is this possible? Help me python geniuses
2021/09/12
[ "https://Stackoverflow.com/questions/69153402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14272990/" ]
What we do is not derive `ListOfSomething` from the list base class. We would make `ListOfSomething` the singleton and have a generic list class. ```cpp class ListOfSomething { public: static ListOfSomething& instance() { static ListOfSomething los; return los; } // Obtain a reference to the ...
As explained by Bart, the trick here is to pass the name of the derived class as a template parameter. Here is the final form of the class that works as originally desired: ``` template <class T> class ListOf<T> { public: static T *method(); }; ``` and you invoke it like this ``` class ListOfSomething : public Li...
45,561,366
I'm a beginner at video processing using python. I have a raw video data captured from a camera and I need to check whether the video has bright or dark frames in it. So far what I have achieved is I can read the raw video using numpy in python. Below is my code. ``` import numpy as np fd = open('my_video_file.raw...
2017/08/08
[ "https://Stackoverflow.com/questions/45561366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4680053/" ]
If you have colorfull frames with red, green and blue channels, i.e NxMx3 matrix then you can convert this matrix from RGB representation to HSV (Hue, Saturation, Value) representation which is also will be NxMx3 matrix. Then you can take Value page from this matrix, i.e. third channel of this matrix and calculate aver...
Just a little insight on your problem. (You might want to read up a little more on digital image representation, [e.g. here](http://pippin.gimp.org/image_processing/chap_dir.html)). The frames of your video are read in in `uint8` format, i.e. pixels are encoded with values ranging from 0 to 255. In general, higher val...
55,713,339
I'm trying to implement the following formula in python for X and Y points [![enter image description here](https://i.stack.imgur.com/Lv0au.png)](https://i.stack.imgur.com/Lv0au.png) I have tried following approach ``` def f(c): """This function computes the curvature of the leaf.""" tt = c n = (tt[0]*...
2019/04/16
[ "https://Stackoverflow.com/questions/55713339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5347207/" ]
You do not specify exactly what the structure of the parameter `pts` is. But it seems that it is a two-dimensional array where each row has two values `x` and `y` and the rows are the points in your curve. That itself is problematic, since [the documentation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.g...
I think your problem is that x and y are arrays of double values. The array x is the independent variable; I'd expect it to be sorted into ascending order. If I evaluate y[i], I expect to get the value of the curve at x[i]. When you call that numpy function you get an array of derivative values that are the same shap...
2,344,712
The hindrance we have to ship python is the large size of the standard library. Is there a minimal python distribution or an easy way to pick and choose what we want from the standard library? The platform is linux.
2010/02/26
[ "https://Stackoverflow.com/questions/2344712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282368/" ]
If all you want is to get the minimum subset you need (rather than build an `exe` which would constrain you to Windows systems), use the standard library module [modulefinder](http://docs.python.org/library/modulefinder.html) to list all modules your program requires (you'll get all dependencies, direct and indirect). ...
Have you looked at [py2exe](http://www.py2exe.org/)? It provides a way to ship Python programs without requiring a Python installation.
2,344,712
The hindrance we have to ship python is the large size of the standard library. Is there a minimal python distribution or an easy way to pick and choose what we want from the standard library? The platform is linux.
2010/02/26
[ "https://Stackoverflow.com/questions/2344712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282368/" ]
Have you looked at [py2exe](http://www.py2exe.org/)? It provides a way to ship Python programs without requiring a Python installation.
Like Hank Gay and Alex Martelli suggest, you can use py2exe. In addition I would suggest looking into using something like [IronPython](http://ironpython.net/). Depending on your application, you can use libraries that are built into the .NET framework (or MONO if for Linux). This reduces your shipping size, but adds m...
2,344,712
The hindrance we have to ship python is the large size of the standard library. Is there a minimal python distribution or an easy way to pick and choose what we want from the standard library? The platform is linux.
2010/02/26
[ "https://Stackoverflow.com/questions/2344712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282368/" ]
If all you want is to get the minimum subset you need (rather than build an `exe` which would constrain you to Windows systems), use the standard library module [modulefinder](http://docs.python.org/library/modulefinder.html) to list all modules your program requires (you'll get all dependencies, direct and indirect). ...
Like Hank Gay and Alex Martelli suggest, you can use py2exe. In addition I would suggest looking into using something like [IronPython](http://ironpython.net/). Depending on your application, you can use libraries that are built into the .NET framework (or MONO if for Linux). This reduces your shipping size, but adds m...
22,164,245
I'm using a java program to split an array among histogram bins. Now, I want to manually label the histogram bins. So - I want to convert some thing like the sequence: {-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.5,1,1.5,2,2.5,4} into the following image - ![enter image description here](https://i.stack.imgu...
2014/03/04
[ "https://Stackoverflow.com/questions/22164245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1826912/" ]
Well, the simplest approach is (Python): ``` import matplotlib.pyplot as plt d = [-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.5,1,1.5,2,2.5,4] hist(d) plt.show() ``` As for putting special labels on the histogram, that's covered in the question: [Matplotlib - label each bin](https://stackoverflow.com/ques...
On the java side, an useful (and not too big) library could be GRAL <http://trac.erichseifert.de/gral/> An histogram example is here: <http://trac.erichseifert.de/gral/browser/gral-examples/src/main/java/de/erichseifert/gral/examples/barplot/HistogramPlot.java> And specifically about axis rotation: <http://www.erichs...
22,164,245
I'm using a java program to split an array among histogram bins. Now, I want to manually label the histogram bins. So - I want to convert some thing like the sequence: {-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.5,1,1.5,2,2.5,4} into the following image - ![enter image description here](https://i.stack.imgu...
2014/03/04
[ "https://Stackoverflow.com/questions/22164245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1826912/" ]
To arrange data in bins then display them with equal width bars you can use `matplotlib` in Python The previous Python answer doesn't bin the values, set them at equal distance nor handle (-infinity, 0.9) bin The code here hopefully does: ```py import matplotlib.pyplot as plt import numpy as np # data and bins d = ...
On the java side, an useful (and not too big) library could be GRAL <http://trac.erichseifert.de/gral/> An histogram example is here: <http://trac.erichseifert.de/gral/browser/gral-examples/src/main/java/de/erichseifert/gral/examples/barplot/HistogramPlot.java> And specifically about axis rotation: <http://www.erichs...
35,050,766
I am currently using Python and R together (using rmagic/rpy2) to help select different user input variables for a certain type of analysis. I have read a csv file and created a dataframe in R. What I have also done is allowed the users to input a number of variables of which the names must match those in the header ...
2016/01/28
[ "https://Stackoverflow.com/questions/35050766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5849513/" ]
Consider having Python call the R script as child process via command line passing the string variables as arguments. In R, use the double bracket column reference to use strings: **Python** Script *(using subprocess module)* ``` import subprocess var_1 = 'age' var_2 = 'sex' Rfilename = '/path/to/SomeScript.R' # B...
Yes it is possible: ``` var_1 <- "head(iris$Species)" eval(parse(text=var_1)) # [1] setosa setosa setosa setosa setosa setosa # Levels: setosa versicolor virginica ```
54,396,064
I would like to ask how to exchange dates from loop in to an array in python? I need an array of irregular, random dates with hours. So, I prepared a solution: ``` import datetime import radar r2 =() for a in range(1,10): r2 = r2+(radar.random_datetime(start='1985-05-01', stop='1985-05-04'),) r3 = list(r2) prin...
2019/01/28
[ "https://Stackoverflow.com/questions/54396064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10842659/" ]
You can convert the datetime to a string with [`str()`](https://docs.python.org/3/library/stdtypes.html#str) like: ### Code: ``` str(radar.random_datetime(start='1985-05-01', stop='1985-05-04')) ``` ### Test Code: ``` import radar r2 = () for a in range(1, 10): r2 = r2 + (str( radar.random_datetime(st...
Use [strftime](http://docs.python.org/2/library/time.html#time.strftime) to convert the date generated by radar before adding it to the list. e.g. ``` import datetime import radar r2 =() for a in range(1,10): t=datetime.datetime(radar.random_datetime(start='1985-05-01', stop='1985-05-04')) r2 = r2+(t.strftime('%Y-%m...
23,086,078
I have list that has 20 coordinates (x and y coordinates). I can calculate the distance between any two coordinates, but I have a hard time writing an algorithm that will iterate through the list and calculate the distance between the first node and every other node. for example, ``` ListOfCoordinates = [(1,2), (3,4)...
2014/04/15
[ "https://Stackoverflow.com/questions/23086078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3536195/" ]
Whenever you need something combinatorics-oriented ("I need first and second, then first and third, then...") chances are the `itertools` module has what you need. ``` from math import hypot def distance(p1,p2): """Euclidean distance between two points.""" x1,y1 = p1 x2,y2 = p2 return hypot(x2 - x1, y...
``` In [6]: l = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] In [7]: def distance(a, b): return (a[0] - b[0], a[1] - b[1]) ...: In [8]: for m in l[1:]: print(distance(l[0], m)) ...: (-2, -2) (-4, -4) (-6, -6) (-8, -8) (-10, -10) ```...
23,086,078
I have list that has 20 coordinates (x and y coordinates). I can calculate the distance between any two coordinates, but I have a hard time writing an algorithm that will iterate through the list and calculate the distance between the first node and every other node. for example, ``` ListOfCoordinates = [(1,2), (3,4)...
2014/04/15
[ "https://Stackoverflow.com/questions/23086078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3536195/" ]
Whenever you need something combinatorics-oriented ("I need first and second, then first and third, then...") chances are the `itertools` module has what you need. ``` from math import hypot def distance(p1,p2): """Euclidean distance between two points.""" x1,y1 = p1 x2,y2 = p2 return hypot(x2 - x1, y...
You can create a `distance` function that takes two tuples, which are coordinate pairs, as parameters. ``` def distance(p1, p2): return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ``` Since you only need an algorithm to calculate distances between the *first* node and every other node, create a loop that...
23,086,078
I have list that has 20 coordinates (x and y coordinates). I can calculate the distance between any two coordinates, but I have a hard time writing an algorithm that will iterate through the list and calculate the distance between the first node and every other node. for example, ``` ListOfCoordinates = [(1,2), (3,4)...
2014/04/15
[ "https://Stackoverflow.com/questions/23086078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3536195/" ]
Whenever you need something combinatorics-oriented ("I need first and second, then first and third, then...") chances are the `itertools` module has what you need. ``` from math import hypot def distance(p1,p2): """Euclidean distance between two points.""" x1,y1 = p1 x2,y2 = p2 return hypot(x2 - x1, y...
I wanted a single line script to do this. The following script did the job for me. ``` import numpy as np yd = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)] distances_matrix = np.array([np.linalg.norm((item*np.ones((len(yd),len(item))))-yd,axis=1) for item in yd]) print(distances_matrix) output: [[ 0. 2.828...
74,180,904
I am learning python and I am almost done with making tick tack toe but the code for checking if the game is a tie seems more complicated then it needs to be. is there a way of simplifying this? ``` if a1 != " " and a2 != " " and a3 != " " and b1 != " " and b2 != " " and b3 != " " and c1 != " " and c2 != " " and c...
2022/10/24
[ "https://Stackoverflow.com/questions/74180904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20321517/" ]
I think there is no implemented method in the SDK for that but after looking a bit, I found this one: [request](https://cloud.google.com/storage/docs/json_api/v1/objects/list#request) You could try to execute an HTTP GET specifying the parameters (you can find an example of the use of parameters here: [query\_paramete...
By default the google API iterators manage page size for you. The RowIterator returns a single row by default, backed internally by fetched pages that rely on the backend to select an appropriate size. If however you want to specify a fixed max page size, you can use the [`google.golang.org/api/iterator`](https://pkg....
18,004,605
I got stuck on another part of this exercise. The program that is being coded allows you to drill phrases (It gives you a piece of code, you write out the English translation) and I'm confused on how the "convert" function works. Full code: <http://learnpythonthehardway.org/book/ex41.html> ``` def convert(snippet, phr...
2013/08/01
[ "https://Stackoverflow.com/questions/18004605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2640186/" ]
If it can help you, ``` class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))] ``` is equivalent to ``` class_names = [] for w in random.sample(WORDS, snippet.count("%%%")): class_names.append(w.capitalize()) ``` The .count() will return the number of occurence of "%%%...
`w.capitalize()` is like `.uppercase()`, but it only captilizes the first character.
17,708,683
I'm trying to deploy a Flask app on a Linode VPS running Ubuntu 10.10. I've been following this tutorial (<https://library.linode.com/web-servers/nginx/python-uwsgi/ubuntu-10.10-maverick#sph_configure-nginx>) but I keep getting a 502 Bad Gateway error. Here this is /etc/default/uwsgi: ``` PYTHONPATH=/var/www/reframei...
2013/07/17
[ "https://Stackoverflow.com/questions/17708683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2193598/" ]
With `uwsgi_pass 127.0.0.1:9001;` you declared to Nginx your intent to talk to uWSGI through TCP socket, but have not warned uWSGI about it. Try adding a corresponding socket line to your `/etc/default/uwsgi` file: ``` PYTHONPATH=/var/www/reframeit-im MODULE=wsgi socket=127.0.0.1:9001 ```
Please add "protocol = uwsgi" apart from what Flavio has suggested. As below ``` PYTHONPATH=/var/www/reframeit-im MODULE=wsgi socket=127.0.0.1:9001 protocol = uwsgi ```
66,996,147
I have a python list that looks like this: ``` my_list = [2, 4, 1 ,0, 3] ``` My goal is to iterate over this list in a manner where the next index is the current value and then to append all the index in another list and then stop the iteration once a cycle is over. Hence, > > Starting from 0 it contains the value...
2021/04/08
[ "https://Stackoverflow.com/questions/66996147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1813039/" ]
A `while` loop is a better structure here; set `i` to point to the first element in `my_list` and then iterate until you find `i` in `new_list`: ```py my_list = [2,4,1,0,3] new_list = [] i = 0 while i not in new_list: new_list.append(i) i = my_list[i] print(new_list) ``` Output: ```py [0, 2, 1, 4, 3] ```...
You can try this. using variable swapping you can reassign rather than appending and creating a new variable ``` my_list = [2,4,1,0,3] n= len(my_list) for i in range(n-1): for j in range(0,n-i-1): if my_list[j] > my_list[j+1]: my_list[j], my_list[j+1] = my_list[j+1],my_list[j] print(my_list) ...
35,132,569
What I'm trying to do is build a regressor based on a value in a feature. That is to say, I have some columns where one of them is more important (let's suppose it is `gender`) (of course it is different from the target value Y). I want to say: - If the `gender` is Male then use the randomForest regressor - El...
2016/02/01
[ "https://Stackoverflow.com/questions/35132569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3497084/" ]
You might be able to implement your own regressor. Let us assume that `gender` is the first feature. Then you could do something like ``` class MyRegressor(): '''uses different regressors internally''' def __init__(self): self.randomForest = initializeRandomForest() self.kNN = initializekNN() ...
I personally am new to Python but I would use the data type of a list. I would then proceed to making a membership check and reference the list you just wrote. Then proceed to say that if member = true then run/use randomForest regressor. If false use/run another regressor.
60,873,608
Need substition for using label/goto -used in languages like C,..- in python So basically, I am a newb at python (and honestly, programming).I have been experimenting with super basic stuff and have hit a "roadblock". ``` print("Hello User!") print("Welcome to your BMI Calculator.") print("Please choose your system o...
2020/03/26
[ "https://Stackoverflow.com/questions/60873608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13130669/" ]
I don't recommend you start your programming career with `goto`, that's how you can get perfectly written `spaghetti code`. Let's review your use case here, you want to go back to asking user if he did not gave you an expected input, why not use a loop instead of `goto`? ``` ans = "unexpected" while(ans != "A" and an...
Put everything in 'while (true)' starting with first 'if' statement. And remove last 'else' statement.
3,162,450
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" ...
2010/07/01
[ "https://Stackoverflow.com/questions/3162450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93580/" ]
You need to provide more information about the source of the text (the web? user input?), the domain (is it just clothes?), the potential formatting and vocabulary... Assuming worst case scenario you need to start learning NLP. A very good free book is the documentation of NLTK: <http://www.nltk.org/book> . It is also...
Possibly look at "Collective Intelligence" by Toby Segaran. I seem to remember that addressing the basics of this in one chapter.
3,162,450
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" ...
2010/07/01
[ "https://Stackoverflow.com/questions/3162450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93580/" ]
You need to provide more information about the source of the text (the web? user input?), the domain (is it just clothes?), the potential formatting and vocabulary... Assuming worst case scenario you need to start learning NLP. A very good free book is the documentation of NLTK: <http://www.nltk.org/book> . It is also...
After some researching I have found that this problem is commonly referred to as *Information Extraction* and have amassed a few papers and stored them in a Mendeley Collection <http://www.mendeley.com/research-papers/collections/3237331/Information-Extraction/> Also as Tai Weiss noted NLTK for python is a good start...
3,162,450
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" ...
2010/07/01
[ "https://Stackoverflow.com/questions/3162450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93580/" ]
You need to provide more information about the source of the text (the web? user input?), the domain (is it just clothes?), the potential formatting and vocabulary... Assuming worst case scenario you need to start learning NLP. A very good free book is the documentation of NLTK: <http://www.nltk.org/book> . It is also...
If you are only working for cases like the example you cited, you are better off using some manual rule-based that is 100% predictable and covers 90% of the cases it might encounter production.. You could enumerable lists of all possible brands and categories and detect which is which in an input string cos there's u...
3,162,450
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" ...
2010/07/01
[ "https://Stackoverflow.com/questions/3162450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93580/" ]
Possibly look at "Collective Intelligence" by Toby Segaran. I seem to remember that addressing the basics of this in one chapter.
If you are only working for cases like the example you cited, you are better off using some manual rule-based that is 100% predictable and covers 90% of the cases it might encounter production.. You could enumerable lists of all possible brands and categories and detect which is which in an input string cos there's u...
3,162,450
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" ...
2010/07/01
[ "https://Stackoverflow.com/questions/3162450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93580/" ]
After some researching I have found that this problem is commonly referred to as *Information Extraction* and have amassed a few papers and stored them in a Mendeley Collection <http://www.mendeley.com/research-papers/collections/3237331/Information-Extraction/> Also as Tai Weiss noted NLTK for python is a good start...
If you are only working for cases like the example you cited, you are better off using some manual rule-based that is 100% predictable and covers 90% of the cases it might encounter production.. You could enumerable lists of all possible brands and categories and detect which is which in an input string cos there's u...
68,890,393
I'm trying to install a Python package called "mudes" on another server using terminal. When I want to install it using ``` pip install mudes ``` or ``` pip3 install mudes ``` , I get the following error: ``` Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-hn4hol_z/spacy/ ``` I ha...
2021/08/23
[ "https://Stackoverflow.com/questions/68890393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I had the same issue trying to install pycaret. I'm no expert so I don't know why but this work for me ``` pip3 install --upgrade pip ```
The setuptools might be outdated. Try running this command first and see if it helps. ``` pip install --upgrade setuptools ```
68,890,393
I'm trying to install a Python package called "mudes" on another server using terminal. When I want to install it using ``` pip install mudes ``` or ``` pip3 install mudes ``` , I get the following error: ``` Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-hn4hol_z/spacy/ ``` I ha...
2021/08/23
[ "https://Stackoverflow.com/questions/68890393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I had the same issue trying to install pycaret. I'm no expert so I don't know why but this work for me ``` pip3 install --upgrade pip ```
Looks like spacy is not installed. ``` pip3 install spacy ``` It worked for me, check if it helps you.
46,510,770
I'm kind of new to python and I need to run a script all day. However, the memory used by the script keeps increasing over time until python crashes... I've tried stuff but nothing works :( Maybe I'm doing something wrong I don't know. Here's what my code looks like : ``` while True: try: import functions and...
2017/10/01
[ "https://Stackoverflow.com/questions/46510770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8703130/" ]
The closest thing Xcode has is a button at the bottom of the project navigator to show only files with source-control status. Clicking the button shows files that have uncommitted changes. [![enter image description here](https://i.stack.imgur.com/PmT8M.png)](https://i.stack.imgur.com/PmT8M.png)
As Mark answered you can filter all the modified files, after that don't forget to turn on **Comparison**, so you can see where the code got changed. [![enter image description here](https://i.stack.imgur.com/Wmugd.png)](https://i.stack.imgur.com/Wmugd.png)
58,854,194
I'm getting the following error when using the [Microsoft Python Speech-to-Text Quickstart ("Quickstart: Recognize speech from an audio file")](https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-file?tabs=linux&pivots=programming-language-python#sample-code) with t...
2019/11/14
[ "https://Stackoverflow.com/questions/58854194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908967/" ]
mp3-encoded audio is not supported as an input format. Please use a WAV(PCM) file with 16-bit samples, 16 kHz sample rate, and a single channel (Mono).
The default audio streaming format is WAV (16kHz or 8kHz, 16-bit, and mono PCM). Outside of WAV / PCM, the compressed input formats listed below are also supported. However if you use C#/Java/C++/Objective C and if you want to use compressed audio formats such as **.mp3**, you can handle it by using **GStreamer** Fo...
58,854,194
I'm getting the following error when using the [Microsoft Python Speech-to-Text Quickstart ("Quickstart: Recognize speech from an audio file")](https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-file?tabs=linux&pivots=programming-language-python#sample-code) with t...
2019/11/14
[ "https://Stackoverflow.com/questions/58854194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908967/" ]
mp3-encoded audio is not supported as an input format. Please use a WAV(PCM) file with 16-bit samples, 16 kHz sample rate, and a single channel (Mono).
I guess there is no official method for usage of SDK with different formats (mp3 or different framerate) I'd like to use the Azure method that is able to use any type of audio file input Until now I am using my made-up method for dealing with this problem, first convert the proper file and delete it after finish my jo...
58,854,194
I'm getting the following error when using the [Microsoft Python Speech-to-Text Quickstart ("Quickstart: Recognize speech from an audio file")](https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/quickstarts/speech-to-text-from-file?tabs=linux&pivots=programming-language-python#sample-code) with t...
2019/11/14
[ "https://Stackoverflow.com/questions/58854194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908967/" ]
The default audio streaming format is WAV (16kHz or 8kHz, 16-bit, and mono PCM). Outside of WAV / PCM, the compressed input formats listed below are also supported. However if you use C#/Java/C++/Objective C and if you want to use compressed audio formats such as **.mp3**, you can handle it by using **GStreamer** Fo...
I guess there is no official method for usage of SDK with different formats (mp3 or different framerate) I'd like to use the Azure method that is able to use any type of audio file input Until now I am using my made-up method for dealing with this problem, first convert the proper file and delete it after finish my jo...
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ |...
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
There is no need for an external library. The prints out the data with the column names. All lines with the 'columns' variable can be eliminated if you do not need the column names. ``` sql = "SELECT * FROM someTable" cursor.execute(sql) conn.commit() results = cursor.fetchall() widths = [] columns = [] tavnit = '|' ...
The data is in some list it seems, and are printing the header. Consider some formatting like this: ``` res = ['trebuchet ms', 8868, 417] res = ['lucida sans unicode', 3525, 116] ``` and ``` print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res)) ``` give you ``` trebuchet ms 8868 417 lucid...
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ |...
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
There is no need for an external library. The prints out the data with the column names. All lines with the 'columns' variable can be eliminated if you do not need the column names. ``` sql = "SELECT * FROM someTable" cursor.execute(sql) conn.commit() results = cursor.fetchall() widths = [] columns = [] tavnit = '|' ...
You need to do two passes: 1. Calculate the column widths 2. Print the table So ``` table = cur.fetchall() widths = [0]*len(table[0]) # Assuming there is always one row for row in table: widths = [max(w,len(c)) for w,c in zip(widths,row)] ``` Now you can print the table trivially. Remember the `string.rjust`...
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ |...
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
Best and easiest way to print MySQL results into MySQL Table format using Python Library `tabulate` `user@system$ pip install tabulate` **Python Code:** ``` import mysql.connector from tabulate import tabulate mydb = mysql.connector.connect( host="localhost", user="root", ...
I modified [dotancohen's answer](https://stackoverflow.com/a/20383011/4795539) so only the resulting list of dict is needed as input. This is useful if you already have a library method returning results: ``` def format_table(self, results:list): if not len(results): return [] widths = [] max_width...
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ |...
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
Best and easiest way to print MySQL results into MySQL Table format using Python Library `tabulate` `user@system$ pip install tabulate` **Python Code:** ``` import mysql.connector from tabulate import tabulate mydb = mysql.connector.connect( host="localhost", user="root", ...
The data is in some list it seems, and are printing the header. Consider some formatting like this: ``` res = ['trebuchet ms', 8868, 417] res = ['lucida sans unicode', 3525, 116] ``` and ``` print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res)) ``` give you ``` trebuchet ms 8868 417 lucid...
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ |...
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
There is no need for an external library. The prints out the data with the column names. All lines with the 'columns' variable can be eliminated if you do not need the column names. ``` sql = "SELECT * FROM someTable" cursor.execute(sql) conn.commit() results = cursor.fetchall() widths = [] columns = [] tavnit = '|' ...
I modified [dotancohen's answer](https://stackoverflow.com/a/20383011/4795539) so only the resulting list of dict is needed as input. This is useful if you already have a library method returning results: ``` def format_table(self, results:list): if not len(results): return [] widths = [] max_width...
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ |...
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
The data is in some list it seems, and are printing the header. Consider some formatting like this: ``` res = ['trebuchet ms', 8868, 417] res = ['lucida sans unicode', 3525, 116] ``` and ``` print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res)) ``` give you ``` trebuchet ms 8868 417 lucid...
I modified [dotancohen's answer](https://stackoverflow.com/a/20383011/4795539) so only the resulting list of dict is needed as input. This is useful if you already have a library method returning results: ``` def format_table(self, results:list): if not len(results): return [] widths = [] max_width...
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ |...
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
Use [`prettytable`](http://code.google.com/p/prettytable/) ``` x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.set_field_align("City name", "l") # Left align city names x.set_padding_width(1) # One space between column edges and contents (default) x.add_row(["Adelaide",1295, 1158259, 600.5]) ...
Best and easiest way to print MySQL results into MySQL Table format using Python Library `tabulate` `user@system$ pip install tabulate` **Python Code:** ``` import mysql.connector from tabulate import tabulate mydb = mysql.connector.connect( host="localhost", user="root", ...
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ |...
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
Best and easiest way to print MySQL results into MySQL Table format using Python Library `tabulate` `user@system$ pip install tabulate` **Python Code:** ``` import mysql.connector from tabulate import tabulate mydb = mysql.connector.connect( host="localhost", user="root", ...
You need to do two passes: 1. Calculate the column widths 2. Print the table So ``` table = cur.fetchall() widths = [0]*len(table[0]) # Assuming there is always one row for row in table: widths = [max(w,len(c)) for w,c in zip(widths,row)] ``` Now you can print the table trivially. Remember the `string.rjust`...
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ |...
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
You need to do two passes: 1. Calculate the column widths 2. Print the table So ``` table = cur.fetchall() widths = [0]*len(table[0]) # Assuming there is always one row for row in table: widths = [max(w,len(c)) for w,c in zip(widths,row)] ``` Now you can print the table trivially. Remember the `string.rjust`...
I modified [dotancohen's answer](https://stackoverflow.com/a/20383011/4795539) so only the resulting list of dict is needed as input. This is useful if you already have a library method returning results: ``` def format_table(self, results:list): if not len(results): return [] widths = [] max_width...
10,865,483
What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that: ``` +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ |...
2012/06/02
[ "https://Stackoverflow.com/questions/10865483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986743/" ]
Use [`prettytable`](http://code.google.com/p/prettytable/) ``` x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.set_field_align("City name", "l") # Left align city names x.set_padding_width(1) # One space between column edges and contents (default) x.add_row(["Adelaide",1295, 1158259, 600.5]) ...
The data is in some list it seems, and are printing the header. Consider some formatting like this: ``` res = ['trebuchet ms', 8868, 417] res = ['lucida sans unicode', 3525, 116] ``` and ``` print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res)) ``` give you ``` trebuchet ms 8868 417 lucid...
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always retur...
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
It seems that all answers deal with `True` and `False` as defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects: ``` >>> True = 1 >>> (2 > 1) True >>> (2 > 1) == True...
`==` and `is` are both comparison operators, which would return a boolean value - `True` or `False`. True has a numeric value of 1 and False has a numeric value of 0. The operator `==` compare the values of two objects and objects compared are most often are the same types (int vs int, float vs float), If you compare ...
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always retur...
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
It seems that all answers deal with `True` and `False` as defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects: ``` >>> True = 1 >>> (2 > 1) True >>> (2 > 1) == True...
Another reason to [compare values using `==`](https://docs.python.org/3/reference/expressions.html#comparisons) is that both `None` and `False` are [“falsy”](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false) values. And sometimes it’s useful to use `None` to ...
4,591,125
I did several Boolean Comparisons: ``` >>> (True or False) is True True >>> (True or False) == True True ``` It sounds like `==` and `is` are interchangeable for Boolean-values. Sometimes it's more clear to use `is` I want to know that: Are `True` and `False` pre-allocated in python? Is `bool(var)` always retur...
2011/01/04
[ "https://Stackoverflow.com/questions/4591125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348785/" ]
You probably shouldn't ever need to compare booleans. If you are doing something like: ``` if some_bool == True: ... ``` ...just change it to: ``` if some_bool: ... ``` No `is` or `==` needed. As commenters have pointed out, there are valid reasons to compare booleans. If both booleans are unknown and you wa...
It seems that all answers deal with `True` and `False` as defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects: ``` >>> True = 1 >>> (2 > 1) True >>> (2 > 1) == True...