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 |
|---|---|---|---|---|---|
54,450,504 | I was looking for this information for a while, but as additional packages and python versions can be installed through `homebrew` and `pip` I have the feeling that my environment is messed up. Furthermore a long time ago, I had installed some stuff with `sudo pip install` and as well `sudo python ~/get-pip.py`.
Is th... | 2019/01/30 | [
"https://Stackoverflow.com/questions/54450504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767754/"
] | Instead of telling him WHY he should not do something, how about telling him HOW he could do it? Maybe his example is not an appropriate need for it, but there's other situations where being able to create a macro would be nice.
For example... I have an HTML page that I'm working on that deals with unit conversions an... | Technically inline JavaScript with a `<script>` tag could do what you are asking. You could even look into the many templating solutions available via JavaScript libraries.
That would not actually provide any benefit, though. JavaScript changes what is ultimately displayed, not the file itself. Since your use case doe... |
54,450,504 | I was looking for this information for a while, but as additional packages and python versions can be installed through `homebrew` and `pip` I have the feeling that my environment is messed up. Furthermore a long time ago, I had installed some stuff with `sudo pip install` and as well `sudo python ~/get-pip.py`.
Is th... | 2019/01/30 | [
"https://Stackoverflow.com/questions/54450504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767754/"
] | Technically inline JavaScript with a `<script>` tag could do what you are asking. You could even look into the many templating solutions available via JavaScript libraries.
That would not actually provide any benefit, though. JavaScript changes what is ultimately displayed, not the file itself. Since your use case doe... | Just an observation from a novice. If everyone did as purists suggest (i.e.-the right way), then the web would still be using the same coding conventions it was using 30 years ago. People do things, innovate, and create new ways, then new standards, and deprecate others all the time. Just because someone says "spaces a... |
54,450,504 | I was looking for this information for a while, but as additional packages and python versions can be installed through `homebrew` and `pip` I have the feeling that my environment is messed up. Furthermore a long time ago, I had installed some stuff with `sudo pip install` and as well `sudo python ~/get-pip.py`.
Is th... | 2019/01/30 | [
"https://Stackoverflow.com/questions/54450504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767754/"
] | Instead of telling him WHY he should not do something, how about telling him HOW he could do it? Maybe his example is not an appropriate need for it, but there's other situations where being able to create a macro would be nice.
For example... I have an HTML page that I'm working on that deals with unit conversions an... | This …
>
> My html file contains in many places the code ` `
>
>
>
… is actually what is wrong in your file!
` ` is not meant to use for layout purpose, you should fix that and use CSS instead to layout it correctly.
` ` is meant to stop breaking words at the end of a line that are s... |
54,450,504 | I was looking for this information for a while, but as additional packages and python versions can be installed through `homebrew` and `pip` I have the feeling that my environment is messed up. Furthermore a long time ago, I had installed some stuff with `sudo pip install` and as well `sudo python ~/get-pip.py`.
Is th... | 2019/01/30 | [
"https://Stackoverflow.com/questions/54450504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767754/"
] | Instead of telling him WHY he should not do something, how about telling him HOW he could do it? Maybe his example is not an appropriate need for it, but there's other situations where being able to create a macro would be nice.
For example... I have an HTML page that I'm working on that deals with unit conversions an... | Just an observation from a novice. If everyone did as purists suggest (i.e.-the right way), then the web would still be using the same coding conventions it was using 30 years ago. People do things, innovate, and create new ways, then new standards, and deprecate others all the time. Just because someone says "spaces a... |
55,223,059 | May I know why I get the error message -
NameError: name 'X\_train\_std' is not defined
```
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(C=1000.0, random_state=0)
lr.fit(X_train_std, y_train)
plot_decision_regions(X_combined_std,
y_combined, classifier=lr,
... | 2019/03/18 | [
"https://Stackoverflow.com/questions/55223059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658840/"
] | I want to share a text about Dependency Injection, It makes us to change our mind using dependency injection :
***Do not (always) use DI: Injectables versus newables***
>
> Something that was immensely useful to me when learning about DI
> frameworks was the realisation that using a DI framework does not mean
> t... | We can inject same class with @Named
```
@Provides
@Named(CMS.Client.DELIVERY_API_CLIENT)
fun provideCMSClient(): CDAClient {
return CDAClient.builder()
.setSpace("4454")
.setToken("777")
.build()
}
@Provides
@Nam... |
67,867,496 | Please forgive my ignorant question.
I'm in the infant stage of learning Python.
I want to convert Before\_text into After\_text.
```
<Before_text>
Today, I got up early, so I’m absolutely exhausted. I had breakfast: two slices \n
of cold toast and a disgusting coffee, then I left the house at 8 o’clock still \n
feeli... | 2021/06/07 | [
"https://Stackoverflow.com/questions/67867496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14949033/"
] | If you want to use [fileinput.input()](https://docs.python.org/3/library/fileinput.html) you should provide input filenames as arguments (`sys.argv`), simple example, if you have `cat.py` as follows
```
import fileinput
for line in fileinput.input():
print(line, end='')
```
and text files `file1.txt`, `file2.txt... | According to the docs, `fileinput.input()` is a shortcut that takes things from the command line input and tries to open them one at a time, or if nothing is specified it uses `stdin` as its input.
Please show us how you are invoking your script. I suspect you have an `-f` in there that the function is trying to open. |
60,174,534 | I know this is kind of stupid since BigQueryML now provides Kmeans with good initialization. Nonetheless I was required to train a model in tensorflow and then pass it to BigQuery for prediction.
I saved my model and everything works fine, until I try to upload it to bigquery. I get the following error:
```
TensorFl... | 2020/02/11 | [
"https://Stackoverflow.com/questions/60174534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12880545/"
] | You can check the shape in the savedmodel file by using the command line program saved\_model\_cli that ships with tensorflow.
Make sure your export signature in tensorflow specifies the shape of the output tensor. | The main issue is that the output tensor shape of TF built-in KMeans estimator model has unknown rank in the saved model.
Two possible ways to solve this:
* Try training the KMeans model on BQML directly.
* Reimplement the TF KMeans estimator model to reshape the output tensor into a specific tensor shape. |
60,174,534 | I know this is kind of stupid since BigQueryML now provides Kmeans with good initialization. Nonetheless I was required to train a model in tensorflow and then pass it to BigQuery for prediction.
I saved my model and everything works fine, until I try to upload it to bigquery. I get the following error:
```
TensorFl... | 2020/02/11 | [
"https://Stackoverflow.com/questions/60174534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12880545/"
] | What this error means: The TF model output named "output" is of completely undefined shape. (unknown\_rank=true means that the model isn't even specifying a number of dimensions).
For BigQuery to be able to use the TensorFlow model it has to be able to convert the model output into a BigQuery type: Either a single pri... | The main issue is that the output tensor shape of TF built-in KMeans estimator model has unknown rank in the saved model.
Two possible ways to solve this:
* Try training the KMeans model on BQML directly.
* Reimplement the TF KMeans estimator model to reshape the output tensor into a specific tensor shape. |
14,101,852 | I have this text file: www2.geog.ucl.ac.uk/~plewis/geogg122/python/delnorte.dat
I want to extract column 3 and 4.
I am using np.loadtxt - getting the error:
```
ValueError: invalid literal for float(): 2000-01-01
```
I am only interested in the year 2005. How can I extracted both columns? | 2012/12/31 | [
"https://Stackoverflow.com/questions/14101852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860229/"
] | You can provide a custom conversion function for a specific column to `loadtxt`.
Since you are only interested in the year I use a `lambda`-function to split the date on `-` and to convert the first part to an `int`:
```
data = np.loadtxt('delnorte.dat',
usecols=(2,3),
converters={2: lambda s: int... | You should not use NumPy.loadtxt to read these values, you should rather use the [`csv` module](http://pastebin.com/JyVC4XfF) to load the file and read its data. |
14,101,852 | I have this text file: www2.geog.ucl.ac.uk/~plewis/geogg122/python/delnorte.dat
I want to extract column 3 and 4.
I am using np.loadtxt - getting the error:
```
ValueError: invalid literal for float(): 2000-01-01
```
I am only interested in the year 2005. How can I extracted both columns? | 2012/12/31 | [
"https://Stackoverflow.com/questions/14101852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860229/"
] | You can provide a custom conversion function for a specific column to `loadtxt`.
Since you are only interested in the year I use a `lambda`-function to split the date on `-` and to convert the first part to an `int`:
```
data = np.loadtxt('delnorte.dat',
usecols=(2,3),
converters={2: lambda s: int... | I agree with using the csv module. I adapted this answer: [reading csv files in scipy/numpy in Python](https://stackoverflow.com/questions/2859404/reading-csv-files-in-scipy-numpy-in-python)
to apply to your question. Not sure if you desire the data in a numpy array or if a list is sufficient.
```
import numpy as np
i... |
20,005,173 | Maximum, minimum and total numbers using python. For example:
```
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
```
Here is my code. I need some help with this.
```
def maxmin():
minimum = None
maximum = None
w... | 2013/11/15 | [
"https://Stackoverflow.com/questions/20005173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725323/"
] | ```
def maxmintotal():
num = 0
numbers = []
while True:
num = int(input('Please enter a number, or -10 to stop: ' ))
if num == -10:
break
numbers.append(num)
print('Numbers:', len(numbers))
print('Maximum:', max(numbers))
print('Minumum:', min(numbers))
`... | You have to define `num` before you use it in the `while`, also your nested `if` should be out of the other `if`:
```
def maxmin():
minimum = None
maximum = None
num = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (... |
20,005,173 | Maximum, minimum and total numbers using python. For example:
```
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
```
Here is my code. I need some help with this.
```
def maxmin():
minimum = None
maximum = None
w... | 2013/11/15 | [
"https://Stackoverflow.com/questions/20005173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725323/"
] | ```
def maxmintotal():
num = 0
numbers = []
while True:
num = int(input('Please enter a number, or -10 to stop: ' ))
if num == -10:
break
numbers.append(num)
print('Numbers:', len(numbers))
print('Maximum:', max(numbers))
print('Minumum:', min(numbers))
`... | This function should give you the output that you want:
```
def maxmin():
minimum, maximum, total = None, None, 0
while(True):
number = input('Please enter a number, or -10 to stop: ')
num = int(number)
if num == -10:
break
if total == 0:
minimum, maximum... |
20,005,173 | Maximum, minimum and total numbers using python. For example:
```
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
```
Here is my code. I need some help with this.
```
def maxmin():
minimum = None
maximum = None
w... | 2013/11/15 | [
"https://Stackoverflow.com/questions/20005173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725323/"
] | I would do this:
```
def maxmin():
minimum = None
maximum = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maxi... | You have to define `num` before you use it in the `while`, also your nested `if` should be out of the other `if`:
```
def maxmin():
minimum = None
maximum = None
num = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (... |
20,005,173 | Maximum, minimum and total numbers using python. For example:
```
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
```
Here is my code. I need some help with this.
```
def maxmin():
minimum = None
maximum = None
w... | 2013/11/15 | [
"https://Stackoverflow.com/questions/20005173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725323/"
] | You have to define `num` before you use it in the `while`, also your nested `if` should be out of the other `if`:
```
def maxmin():
minimum = None
maximum = None
num = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (... | This function should give you the output that you want:
```
def maxmin():
minimum, maximum, total = None, None, 0
while(True):
number = input('Please enter a number, or -10 to stop: ')
num = int(number)
if num == -10:
break
if total == 0:
minimum, maximum... |
20,005,173 | Maximum, minimum and total numbers using python. For example:
```
>>>maxmin()
Enter integers, one per line, terminated by -10 :
2
1
3
7
8
-10
Output : total =5, minimum=1, maximum = 8
```
Here is my code. I need some help with this.
```
def maxmin():
minimum = None
maximum = None
w... | 2013/11/15 | [
"https://Stackoverflow.com/questions/20005173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725323/"
] | I would do this:
```
def maxmin():
minimum = None
maximum = None
while True:
num = input('Please enter a number, or -10 to stop: ')
if num == -10:
break
if (minimum) is None or (num < minimum):
minimum = num
if (maximum) is None or (num > maximum):
maximum = num
print ("Maxi... | This function should give you the output that you want:
```
def maxmin():
minimum, maximum, total = None, None, 0
while(True):
number = input('Please enter a number, or -10 to stop: ')
num = int(number)
if num == -10:
break
if total == 0:
minimum, maximum... |
71,197,496 | I have python script that creates dataflow template in the specified GCS path. I have tested the script using my GCP Free Trial and it works perfect.
My question is using same code in production environment I want to generate a template but I can not use Cloud-Shell as there are restrictions also can not directly run t... | 2022/02/20 | [
"https://Stackoverflow.com/questions/71197496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2458847/"
] | First, you can do this with RXJS, or promises, but either way intentionally makes room for asynchronous programming, so when your `transform` method synchronously returns `this.value` at the end, I don't think you're getting what you're expecting? I'm guessing the reason it is compiling but you don't think it is workin... | If I understand the problem well, your code has a fundamental problem and the fact that "*Everything works well, if I use Observables*" is a fruit of a very special case.
Let's look at this very stripped down version of your code
```
function translationObservable(key) {
return of("Obs translates key: " + key);
}
... |
73,066,287 | I have a project hosted on Microsoft Azure. It has Azure Functions that are Python code and they recently stopped working (500 Internal Server Error). The code has errors I haven't had before and no known changes were made (but the possibility exists because people from other teams could have changed a configuration so... | 2022/07/21 | [
"https://Stackoverflow.com/questions/73066287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6126073/"
] | I was facing the same issue last Thursday. However, we have tried most of the solutions which are available on Internet but none of them help us.
And in the end, we have just updated Azure Function Runtime Python 3.6 to 3.7 and Boomm.. it's working.
Moreover, we have also noticed that when we tried to create new Azur... | We had the exact same issue on Friday. What worked for us was to replace pyodbc with pypyodbc. We did this so that we didn't have to change it in our code:
```
import pypyodbc as pyodbc
```
Also, we upgraded our Azure Functions to use Python 3.7 (will probably update to 3.9 soon). Azure will not be supporting Python... |
60,520,118 | I want to scrape phone no but phone no only displays after clicked so please is it possible to scrape phone no directly using python?My code scrape phone no but with starr\*\*\*. here is the link from where I want to scrape phone no:<https://hipages.com.au/connect/abcelectricservicespl/service/126298> please guide me!
... | 2020/03/04 | [
"https://Stackoverflow.com/questions/60520118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7514427/"
] | Find the Id or class of that element and use jQuery to change the name.
If the element is a Anchor tag, use the below code.
```
jQuery(document).ready(function($)
{
$("#button_id").text("New Text");
});
```
If the element is button, use below code based on type of button.
```
<input type='button' value='Add' id='... | From the screenshot, it seems like you are trying to change the text of a menu link (My Account). If so make sure that you haven't given any custom name for My Account page in the Wordpress navigation.
Inspect the page using developer tools and find the Class/Id of that element.
Then you can use jQuery to alter the co... |
4,300,979 | Defining a function,
MyFunction(argument, \*args):
[do something to argument[arg] for arg in \*args]
if \*args is empty, the function doesn't do anything, but I want to make the default behavior 'use the entire set if length of \*args == 0'
```
def Export(source, target, *args, sep=','):
for item in source:
... | 2010/11/29 | [
"https://Stackoverflow.com/questions/4300979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508440/"
] | Is there a way to pass an "entire set" argument to `SubsetOutput`, so you can bury the conditional inside its call rather than have an explicit `if`? This could be `None` or `[]`, for example.
```
# Pass None to use full subset.
def Export(source, target, *args, sep=','):
for item in source:
SubsetOutput(W... | Just check its not none, you don't have to create a separate argument
```
def test(*args):
if not args:
return #break out
return True #or whatever you want
``` |
4,300,979 | Defining a function,
MyFunction(argument, \*args):
[do something to argument[arg] for arg in \*args]
if \*args is empty, the function doesn't do anything, but I want to make the default behavior 'use the entire set if length of \*args == 0'
```
def Export(source, target, *args, sep=','):
for item in source:
... | 2010/11/29 | [
"https://Stackoverflow.com/questions/4300979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508440/"
] | Just check its not none, you don't have to create a separate argument
```
def test(*args):
if not args:
return #break out
return True #or whatever you want
``` | How about this:
```
def MyFunc(argument, *args):
( DoSomething for i in (filter(args.__contains__ ,argument) if args else argument) )
``` |
4,300,979 | Defining a function,
MyFunction(argument, \*args):
[do something to argument[arg] for arg in \*args]
if \*args is empty, the function doesn't do anything, but I want to make the default behavior 'use the entire set if length of \*args == 0'
```
def Export(source, target, *args, sep=','):
for item in source:
... | 2010/11/29 | [
"https://Stackoverflow.com/questions/4300979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508440/"
] | Is there a way to pass an "entire set" argument to `SubsetOutput`, so you can bury the conditional inside its call rather than have an explicit `if`? This could be `None` or `[]`, for example.
```
# Pass None to use full subset.
def Export(source, target, *args, sep=','):
for item in source:
SubsetOutput(W... | How about this:
```
def MyFunc(argument, *args):
( DoSomething for i in (filter(args.__contains__ ,argument) if args else argument) )
``` |
52,172,821 | I'm currently trying to convert a nested dict into a list of objects with "children" and "leaf".
Here my input dict and the output I'm trying to obtain:
Input:
```
{
"a": {
"aa": {}
},
"b": {
"c": {
"d": {
'label': 'yoshi'
}
},
"e": {... | 2018/09/04 | [
"https://Stackoverflow.com/questions/52172821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2688174/"
] | I have commented the function as I feel necessary.
```
def convert(d):
children = []
#iterate over each child's name and their dict (child's childs)
for child, childs_childs in d.items():
#check that it is not a left node
if childs_childs and \
all(isinstance(v,dict) for k,v in c... | Try this solution (`data` is your input dictionary):
```
def walk(text, d):
result = {'text': text}
# get all children
children = [walk(k, v) for k, v in d.items() if k != 'label']
if children:
result['children'] = children
else:
result['leaf'] = True
# add label if exists
... |
52,172,821 | I'm currently trying to convert a nested dict into a list of objects with "children" and "leaf".
Here my input dict and the output I'm trying to obtain:
Input:
```
{
"a": {
"aa": {}
},
"b": {
"c": {
"d": {
'label': 'yoshi'
}
},
"e": {... | 2018/09/04 | [
"https://Stackoverflow.com/questions/52172821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2688174/"
] | Here's a rough solution. Here I assumed that all labeled nodes are leaves that just have label information.
```
def make_objects(d):
result = []
for k, v in d.items():
if v == {}:
result.append({"text": k, "leaf":True})
elif len(v) ==1 and "label" in v:
result.append({"t... | Try this solution (`data` is your input dictionary):
```
def walk(text, d):
result = {'text': text}
# get all children
children = [walk(k, v) for k, v in d.items() if k != 'label']
if children:
result['children'] = children
else:
result['leaf'] = True
# add label if exists
... |
44,382,348 | I am just 4 days old to python. I am just trying to understand the root \_\_init\_\_.py import functionality. Googled lot to understand the same but not able to find one useful link (may be my search key is not relevant) . Please share some links.
I am getting error as "ImportError: cannot import name Person"
Below i... | 2017/06/06 | [
"https://Stackoverflow.com/questions/44382348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6346252/"
] | Either, as @gonczor suggested, you can simply leave \_\_init\_\_ empty (moreover, you don't need the root one) and import directly from the package:
```
from model.myclass import Person
```
Or, if you intentionally want to flatten the interface of the package, this is as simple as this:
model/\_\_init\_\_.py
```
f... | The error basically says the interpreter can't find anything that would match `Person` in a given namespace, in your case `model` package. It's because it's in `model.myclass` package, but it's imported to `root` and not to `run`.
Modules in python are basically directories with `__init__.py` script. But it's tricky t... |
55,668,648 | I need to find the starting index of the specific sequences (sequence of strings) in the list in python.
For ex.
```
list = ['In', 'a', 'gesture', 'sure', 'to', 'rattle', 'the', 'Chinese', 'Government', ',', 'Steven', 'Spielberg', 'pulled', 'out', 'of', 'the', 'Beijing', 'Olympics', 'to', 'protest', 'against', 'China... | 2019/04/13 | [
"https://Stackoverflow.com/questions/55668648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404345/"
] | You could simply iterate over list of your words and check at every index if following words match any of your sequences.
```
words = ['In', 'a', 'gesture', 'sure', 'to', 'rattle', 'the', 'Chinese', 'Government', ',', 'Steven', 'Spielberg', 'pulled', 'out', 'of', 'the', 'Beijing', 'Olympics', 'to', 'protest', 'against... | **You can do something like:**
```
def find_sequence(seq, _list):
seq_list = seq.split()
all_occurrence = [idx for idx in [i for i, x in enumerate(_list) if x == seq_list[0]] if seq_list == list_[idx:idx+len(seq_list)]]
return -1 if not all_occurrence else all_occurrence[0]
```
---
**Output:**
```
for ... |
69,682,188 | For the sake of practice, I am writing a class BankAccount to learn OOP in python. In an attempt to make my program more redundant am trying to write a test function `test_BankBankAccount()` to practice how to do test functions as well.
The test function `test_BankBankAccount()` is suppose to test that the methods `de... | 2021/10/22 | [
"https://Stackoverflow.com/questions/69682188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925420/"
] | @KoenLostrie is absolutely correct as to *Why your trigger does not fire on Insert*. But that is just half the problem. But, the other issue stems from the same misconception: NULL values The call to `check_salary` passes `:old.job_id` but it is still null, resulting in cursor ( `for i in (Select ...)`) returning no ro... | Congrats on the well documented question.
The issue is with the `WHEN` clause of the trigger. On insert the old value is `NULL` and in oracle, you can't compare to NULL using "=" or "!=".
Check this example:
```
PDB1--KOEN>create table trigger_test
2 (name VARCHAR2(10));
Table TRIGGER_TEST created.
PDB1--KOEN>... |
69,682,188 | For the sake of practice, I am writing a class BankAccount to learn OOP in python. In an attempt to make my program more redundant am trying to write a test function `test_BankBankAccount()` to practice how to do test functions as well.
The test function `test_BankBankAccount()` is suppose to test that the methods `de... | 2021/10/22 | [
"https://Stackoverflow.com/questions/69682188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925420/"
] | Congrats on the well documented question.
The issue is with the `WHEN` clause of the trigger. On insert the old value is `NULL` and in oracle, you can't compare to NULL using "=" or "!=".
Check this example:
```
PDB1--KOEN>create table trigger_test
2 (name VARCHAR2(10));
Table TRIGGER_TEST created.
PDB1--KOEN>... | Thanks for the wonderful answers! I've learned a lot thanks to them.
Upon inspecting my code especially my trigger, I made a mistake on passing the `:old.job_id` to my `check_salary` procedure instead of the `:new.job_id`, that's why i keep wondering why my INSERT is working even if the salary that is being passed is ... |
69,682,188 | For the sake of practice, I am writing a class BankAccount to learn OOP in python. In an attempt to make my program more redundant am trying to write a test function `test_BankBankAccount()` to practice how to do test functions as well.
The test function `test_BankBankAccount()` is suppose to test that the methods `de... | 2021/10/22 | [
"https://Stackoverflow.com/questions/69682188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16925420/"
] | @KoenLostrie is absolutely correct as to *Why your trigger does not fire on Insert*. But that is just half the problem. But, the other issue stems from the same misconception: NULL values The call to `check_salary` passes `:old.job_id` but it is still null, resulting in cursor ( `for i in (Select ...)`) returning no ro... | Thanks for the wonderful answers! I've learned a lot thanks to them.
Upon inspecting my code especially my trigger, I made a mistake on passing the `:old.job_id` to my `check_salary` procedure instead of the `:new.job_id`, that's why i keep wondering why my INSERT is working even if the salary that is being passed is ... |
38,797,047 | I'm running ubuntu 12.04 and usually use python 2.7, but I need a python package that was built with python 3.4 and that uses lxml. After updating aptitude, I can install python 3.2 and lxml, but the package I want only works with 3.4. After installing python 3.4, I try to install lxml dependencies using
```
pip3 inst... | 2016/08/05 | [
"https://Stackoverflow.com/questions/38797047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1106278/"
] | You are running
```
pip3 install libxml2-dev
```
when you should be running
```
sudo apt-get install libxml2 libxml2-dev
```
(you may also need `libxslt` and its dev version as well)
`pip` doesn't install system libraries, `apt` and friends do that. | See <http://www.lfd.uci.edu/~gohlke/pythonlibs/#libxml-python>
Download the package and then do a `pip install <package.whl>`. |
28,627,414 | Welcome... I'm creating a project where I parse xlsx files with xlrd library. Everything works just fine. Then I configured RabbitMQ and Celery. Created some tasks in main folder which works and can be accessed from iPython. The problems starts when I'm in my application (application created back in time in my project)... | 2015/02/20 | [
"https://Stackoverflow.com/questions/28627414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4563194/"
] | You would need to extend the scale class and override the `calculateXLabelRotation` method to use a user inputted rotation rather than trying to work it out it's self. If you do this you would then need to extend the bar or line chart and override the init method to make use of this scale class. (or you could make thes... | Note that **for chart.js 3.x the way of specifying the axis scale options has changed**: see <https://www.chartjs.org/docs/master/getting-started/v3-migration.html#scales>
Consequently in the above answer for 2.x you need to remove the square brackets like this:
```
var myChart = new Chart(ctx, {
type: 'bar',
dat... |
28,627,414 | Welcome... I'm creating a project where I parse xlsx files with xlrd library. Everything works just fine. Then I configured RabbitMQ and Celery. Created some tasks in main folder which works and can be accessed from iPython. The problems starts when I'm in my application (application created back in time in my project)... | 2015/02/20 | [
"https://Stackoverflow.com/questions/28627414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4563194/"
] | If you are using chart.js 2.x, just set **maxRotation: 90** and **minRotation: 90** in ticks options. It works for me!
And if you want to all x-labels, you may want to set **autoSkip: false**.
The following is an example.
```
var myChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scales: {
... | Note that **for chart.js 3.x the way of specifying the axis scale options has changed**: see <https://www.chartjs.org/docs/master/getting-started/v3-migration.html#scales>
Consequently in the above answer for 2.x you need to remove the square brackets like this:
```
var myChart = new Chart(ctx, {
type: 'bar',
dat... |
29,790,344 | I want to generate the following xml file:
```
<foo if="bar"/>
```
I've tried this:
```
from lxml import etree
etree.Element("foo", if="bar")
```
But I got this error:
```
page = etree.Element("configuration", if="ok")
^
SyntaxError: invalid syntax
```
Any ideas?
I'm usi... | 2015/04/22 | [
"https://Stackoverflow.com/questions/29790344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4131226/"
] | ```
etree.Element("foo", {"if": "bar"})
```
The attributes can be passed in as a dict:
```
from lxml import etree
root = etree.Element("foo", {"if": "bar"})
print etree.tostring(root, pretty_print=True)
```
output
```
<foo if="bar"/>
``` | 'if' is a reserved word in Python, which means that you can't use it as an identifier. |
29,790,344 | I want to generate the following xml file:
```
<foo if="bar"/>
```
I've tried this:
```
from lxml import etree
etree.Element("foo", if="bar")
```
But I got this error:
```
page = etree.Element("configuration", if="ok")
^
SyntaxError: invalid syntax
```
Any ideas?
I'm usi... | 2015/04/22 | [
"https://Stackoverflow.com/questions/29790344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4131226/"
] | ```
etree.Element("foo", **{"if": "bar"})
``` | 'if' is a reserved word in Python, which means that you can't use it as an identifier. |
29,790,344 | I want to generate the following xml file:
```
<foo if="bar"/>
```
I've tried this:
```
from lxml import etree
etree.Element("foo", if="bar")
```
But I got this error:
```
page = etree.Element("configuration", if="ok")
^
SyntaxError: invalid syntax
```
Any ideas?
I'm usi... | 2015/04/22 | [
"https://Stackoverflow.com/questions/29790344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4131226/"
] | ```
etree.Element("foo", {"if": "bar"})
```
The attributes can be passed in as a dict:
```
from lxml import etree
root = etree.Element("foo", {"if": "bar"})
print etree.tostring(root, pretty_print=True)
```
output
```
<foo if="bar"/>
``` | ```
etree.Element("foo", **{"if": "bar"})
``` |
21,662,881 | My approach is:
```
def build_layers():
layers = ()
for i in range (0, 32):
layers += (True)
```
but this leads to
```
TypeError: can only concatenate tuple (not "bool") to tuple
```
Context: This should prepare a call of [bpy.ops.pose.armature\_layers](http://www.blender.org/documentation/blender... | 2014/02/09 | [
"https://Stackoverflow.com/questions/21662881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241590/"
] | `(True)` is not a tuple.
Do this instead:
```
layers += (True, )
```
Even better, use a generator:
```
(True, ) * 32
``` | Since tuples are immutable, each concatenation creates a new tuple. It is better to do something like:
```
def build_layers(count):
return tuple([True]*count)
```
If you need some logic to the tuple constructed, just use a list comprehension or generator expression in the tuple constructor:
```
>>> tuple(bool(o... |
21,662,881 | My approach is:
```
def build_layers():
layers = ()
for i in range (0, 32):
layers += (True)
```
but this leads to
```
TypeError: can only concatenate tuple (not "bool") to tuple
```
Context: This should prepare a call of [bpy.ops.pose.armature\_layers](http://www.blender.org/documentation/blender... | 2014/02/09 | [
"https://Stackoverflow.com/questions/21662881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241590/"
] | `(True)` is not a tuple.
Do this instead:
```
layers += (True, )
```
Even better, use a generator:
```
(True, ) * 32
``` | only a tuple can be add to tuple so this would be a working code
```
def build_layers():
layers = ()
for i in range (0, 32):
layers += (True,)
```
However adding tuple is not very pythonic
```
def build_layers():
layers = []
for i in range (0, 32):
layers.append(True)
return tupl... |
57,612,054 | I'm testing an API endpoint that is supposed to raise a ValidationError in a Django model (note that the exception is a Django exception, not DRF, because it's in the model).
```
from rest_framework.test import APITestCase
class TestMyView(APITestCase):
# ...
def test_bad_request(self):
# ...
... | 2019/08/22 | [
"https://Stackoverflow.com/questions/57612054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686617/"
] | **Question**: Isn't DRF's APIClient supposed to handle every exception?
**Answer**: No. It's a test client, it won't handle any uncaught exceptions, that's how test clients work. Test clients propagate the exception so that the test fails with a "crash" when an exception isn't caught. You can test that exceptions are... | Something in your code is causing a python error which is halting execution before your POST request can return a valid HTTP response. Your code doesn't even reach the line `self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)` because there is no response.
If you're calling your tests in the normal way... |
57,612,054 | I'm testing an API endpoint that is supposed to raise a ValidationError in a Django model (note that the exception is a Django exception, not DRF, because it's in the model).
```
from rest_framework.test import APITestCase
class TestMyView(APITestCase):
# ...
def test_bad_request(self):
# ...
... | 2019/08/22 | [
"https://Stackoverflow.com/questions/57612054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686617/"
] | **Question**: Isn't DRF's APIClient supposed to handle every exception?
**Answer**: No. It's a test client, it won't handle any uncaught exceptions, that's how test clients work. Test clients propagate the exception so that the test fails with a "crash" when an exception isn't caught. You can test that exceptions are... | Django >3.0
===========
Starting with Django 3.0, `Client` constructor takes `raise_request_exception` parameter. Set it `False` and response 500 will returned instead of raising an exception.
Source:
<https://docs.djangoproject.com/en/3.2/releases/3.0/#tests>
```py
self.client = Client(raise_request_exception=False... |
2,261,671 | I have a bit counting method that I am trying to make as fast as possible. I want to try the algorithm below from [Bit Twiddling Hacks](http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel), but I don't know C. What is 'type T' and what is the python equivalent of (T)~(T)0/3?
>
> A generalization ... | 2010/02/14 | [
"https://Stackoverflow.com/questions/2261671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270316/"
] | T is a integer type, which I'm assuming is unsigned. Since this is C, it'll be fixed width, probably (but not necessarily) one of 8, 16, 32, 64 or 128. The fragment `(T)~(T)0` that appears repeatedly in that code sample just gives the value 2\*\*N-1, where N is the width of the type T. I suspect that the code may requi... | What you copied is a template for generating code. It's not a good idea to transliterate that template into another language and expect it to run fast. Let's expand the template.
(T)~(T)0 means "as many 1-bits as fit in type T". The algorithm needs 4 masks which we will compute for the various T-sizes we might be inte... |
74,335,162 | I have a file with a function and a file that calls the functions. Finally, I run .bat
I don't know how I can add an argument when calling the .bat file. So that the argument was added to the function as below.
file\_with\_func.py
```
def some_func(val):
print(val)
```
run\_bat.py
```
from bin.file_with_func i... | 2022/11/06 | [
"https://Stackoverflow.com/questions/74335162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17356459/"
] | You need to turn a bunch of POJO's (Plain Old JavaScript Objects) into a class with methods specialized for this kind of object. The idiomatic way is to create a class that takes the POJO's data in some way (since I'm lazy I just pass the entire thing). TypeScript doesn't change how you approach this - you just need to... | >
> The problem is that deserialized json is just a data container...
>
>
>
That's right. In order to deserialize JSON to a class instance with methods, you need to tell deserializer which class is used to create the instance.
However, it's not a good idea to define such class information using `interface` in Typ... |
67,267,305 | I have a custom training loop that can be simplified as follow
```
inputs = tf.keras.Input(dtype=tf.float32, shape=(None, None, 3))
model = tf.keras.Model({"inputs": inputs}, {"loss": f(inputs)})
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9, nesterov=True)
for inputs in batches:
with tf.Gra... | 2021/04/26 | [
"https://Stackoverflow.com/questions/67267305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782553/"
] | Create the EMA object before the training loop:
```
ema = tf.train.ExponentialMovingAverage(decay=0.9999)
```
And then just apply the EMA after your optimization step. The ema object will keep shadow variables of your model's variables. (You don't need the call to `tf.control_dependencies` here, see the note in the ... | EMA with customizing `model.fit`
--------------------------------
Here is a working example of **Exponential Moving Average** with customizing the `fit`. [Ref](https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage).
```
from tensorflow import keras
import tensorflow as tf
class EMACustomModel... |
21,243,719 | I am using python (2.7) and I have a long nested list of X,Y coordinates specifying end points of lines. I need to shift the Y coordinates by a specified amount. For instance, this is what I would like to do:
```
lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
```
perform some coding that is ... | 2014/01/20 | [
"https://Stackoverflow.com/questions/21243719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3216653/"
] | I'd do something like:
```
>>> dy = 100
>>> lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
>>> newlines = [tuple((x,y+dy) for x,y in subline) for subline in lines]
>>> newlines
[((2, 198), (66, 132)), ((67, 131), (96, 102)), ((40, 152), (88, 103))]
```
which is roughly the same as:
```
newl... | Tuples are immutable, so as currently structured it's impossible without making either the line or the point a list, or rebuilding from scratch each time
point as a list, line as a tuple:
```
line = lines[0]
for point in line:
point[1] += 100
```
line as a list, point as a tuple:
```
line = lines[0]
for i, (x,... |
21,243,719 | I am using python (2.7) and I have a long nested list of X,Y coordinates specifying end points of lines. I need to shift the Y coordinates by a specified amount. For instance, this is what I would like to do:
```
lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
```
perform some coding that is ... | 2014/01/20 | [
"https://Stackoverflow.com/questions/21243719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3216653/"
] | I'd do something like:
```
>>> dy = 100
>>> lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
>>> newlines = [tuple((x,y+dy) for x,y in subline) for subline in lines]
>>> newlines
[((2, 198), (66, 132)), ((67, 131), (96, 102)), ((40, 152), (88, 103))]
```
which is roughly the same as:
```
newl... | In programming, divide things into smaller units.
Define a function that shifts one point:
```
def shift_point(point, dx=0, dy=0):
x, y = point
return (x + dx, y + dy)
```
Then one that shifts a line:
```
def shift_line(line, dx=0, dy=0):
point1, point2 = line
return (shift_point(point1, dx, dy),
... |
21,243,719 | I am using python (2.7) and I have a long nested list of X,Y coordinates specifying end points of lines. I need to shift the Y coordinates by a specified amount. For instance, this is what I would like to do:
```
lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))]
```
perform some coding that is ... | 2014/01/20 | [
"https://Stackoverflow.com/questions/21243719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3216653/"
] | In programming, divide things into smaller units.
Define a function that shifts one point:
```
def shift_point(point, dx=0, dy=0):
x, y = point
return (x + dx, y + dy)
```
Then one that shifts a line:
```
def shift_line(line, dx=0, dy=0):
point1, point2 = line
return (shift_point(point1, dx, dy),
... | Tuples are immutable, so as currently structured it's impossible without making either the line or the point a list, or rebuilding from scratch each time
point as a list, line as a tuple:
```
line = lines[0]
for point in line:
point[1] += 100
```
line as a list, point as a tuple:
```
line = lines[0]
for i, (x,... |
63,871,922 | I am using **Ubuntu 20.04**.I upgraded Tensorflow-2.2.0 to Tensorflow-2.3.0. When the version was **2.2.0**, tensorflow was utilizing GPU well. But after upgrading to version **2.3.0** it doesn't detecting GPU.
I have seen this [Link](https://stackoverflow.com/questions/63515767/tensorflow-2-3-0-does-not-detect-gpu) f... | 2020/09/13 | [
"https://Stackoverflow.com/questions/63871922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13442402/"
] | In your `~/.bashrc` add:
```
LD_LIBRARY_PATH=/usr/local/cuda-10.1/lib64
```
If you have a different location for the lib64 folder, you need to adjust it accordingly.
As a side note, if you want to switch between multiple CUDA versions frequently you can also set an environment variable for a specific command direct... | >
> 2020-09-13 21:28:48.883415: W tensorflow/stream\_executor/platform/default/dso\_loader.cc:59] Could not load dynamic library 'libcublas.so.10'; dlerror: libcublas.so.10: cannot open shared object file: No such file or directory;
>
>
>
In my case, this caused by being installed
`libcublas10` and `libcublas-d... |
787,711 | I'm trying to write a function to return the truth value of a given PyObject. This function should return the same value as the if() truth test -- empty lists and strings are False, etc.
I have been looking at the python/include headers, but haven't found anything that seems to do this. The closest I came was PyObject\... | 2009/04/24 | [
"https://Stackoverflow.com/questions/787711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Isn't this it, in object.h:
```
PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
```
? | Use
`int PyObject_IsTrue(PyObject *o)`
Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.
(from [Python/C API Reference Manual](http://docs.python.org/c-api/object.html)) |
54,399,465 | I have a dataframe like this,
```
ColA Result_ColA ColB Result_ColB Result_ColC
1 True 1 True True
2 False 2 True False
3 True 3 True False
```
I want to identify the row numbers inside a list in python, which has a value False present in any of the Resul... | 2019/01/28 | [
"https://Stackoverflow.com/questions/54399465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7638174/"
] | Alternatively you could use countDocuments() to check the number of documents in the query? This will just count the number rather than returning it. | Pass id in `findOne()`
Make a one common function.
```
const objectID = require('mongodb').ObjectID
getMongoObjectId(id) {
return new objectID(id)
}
```
Now just call function
```
findOne({_id:common.getMongoObjectId('ID value hear')})
```
It will same as `where` condition in mysql. |
21,508,816 | sorry if this is dumb question, but this is the first time i've used python and Mongo DB.
Anyway, the problem I have is that I am trying to insert() a string to be stored in my data base -by read()-ing data in with a loop and then giving insert() line 1 and line2 in a single string (This is probably a messy way of doin... | 2014/02/02 | [
"https://Stackoverflow.com/questions/21508816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3196428/"
] | The relevant part of your code is this:
```
post=collection.insert()
```
What you're doing there is calling the `insert` method without arguments rather than assigning that method to `post`. As the [`insert` method](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.inser... | It appears as has been pointing out that you are attempting to create a [closure](https://stackoverflow.com/questions/4020419/closures-in-python) on the insert method. In this case I don't see the point as it will never be passed anywhere and/or need to reference something in the scope outside of where it was used. Jus... |
63,993,901 | I have just started my first python project. When it comes to running the shell script, the following error appears. What can be the cause of that problem? Maybe it is easy to solve. Thanks for your help, I am glad to provide more specific information as you need.
Thanks.[enter image description here](https://i.stack.... | 2020/09/21 | [
"https://Stackoverflow.com/questions/63993901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14315301/"
] | This is a very "basic" example:
```
chars = 'abcdefghijklmnopqrstuvwxyz'
my_list = []
for c1 in chars:
for c2 in chars:
for c3 in chars:
for c4 in chars:
my_list.append(c1+c2+c3+c4)
print(my_list)
``` | It's not easy to know what you consider "magical", but I don't see the magic in loops.
Here is one variation:
```
cs = 'abcdefghijklmnopqrstuvwxyz'
list(map(''.join, [(a,b,c,d) for a in cs for b in cs for c in cs for d in cs]))
``` |
63,993,901 | I have just started my first python project. When it comes to running the shell script, the following error appears. What can be the cause of that problem? Maybe it is easy to solve. Thanks for your help, I am glad to provide more specific information as you need.
Thanks.[enter image description here](https://i.stack.... | 2020/09/21 | [
"https://Stackoverflow.com/questions/63993901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14315301/"
] | You can accomplish this succinctly with using [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product):
```
import itertools
import string
for elem in itertools.product(string.ascii_lowercase, repeat=5):
...
```
Here's a sample for the first 30 values yielded by this approach:
... | It's not easy to know what you consider "magical", but I don't see the magic in loops.
Here is one variation:
```
cs = 'abcdefghijklmnopqrstuvwxyz'
list(map(''.join, [(a,b,c,d) for a in cs for b in cs for c in cs for d in cs]))
``` |
43,724,030 | I try out creating Word documents with python-docx. The created file is in letter dimensions 8.5 x 11 inches. But in Germany the standard format is A4 8.27 x 11.69 inches.
```
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
document.settings
p... | 2017/05/01 | [
"https://Stackoverflow.com/questions/43724030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5418245/"
] | It appears that a `Document` is made of several [`Section`](http://python-docx.readthedocs.io/en/latest/api/section.html#docx.section.Section)s with `page_height` and `page_width` attributes.
To set the dimensions of the first section to A4, you could try (untested):
```
section = document.sections[0]
section.page_he... | I believe you want this, from the [documentation](http://python-docx.readthedocs.io/en/latest/user/sections.html#page-dimensions-and-orientation).
>
> Three properties on Section describe page dimensions and orientation.
> Together these can be used, for example, to change the orientation of
> a section from portra... |
43,724,030 | I try out creating Word documents with python-docx. The created file is in letter dimensions 8.5 x 11 inches. But in Germany the standard format is A4 8.27 x 11.69 inches.
```
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
document.settings
p... | 2017/05/01 | [
"https://Stackoverflow.com/questions/43724030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5418245/"
] | ```
from docx.shared import Mm
document = Document()
section = document.sections[0]
section.page_height = Mm(297)
section.page_width = Mm(210)
section.left_margin = Mm(25.4)
section.right_margin = Mm(25.4)
section.top_margin = Mm(25.4)
section.bottom_margin = Mm(25.4)
section.header_distance = Mm(12.7)
section.footer_... | I believe you want this, from the [documentation](http://python-docx.readthedocs.io/en/latest/user/sections.html#page-dimensions-and-orientation).
>
> Three properties on Section describe page dimensions and orientation.
> Together these can be used, for example, to change the orientation of
> a section from portra... |
43,724,030 | I try out creating Word documents with python-docx. The created file is in letter dimensions 8.5 x 11 inches. But in Germany the standard format is A4 8.27 x 11.69 inches.
```
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
document.settings
p... | 2017/05/01 | [
"https://Stackoverflow.com/questions/43724030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5418245/"
] | ```
from docx.shared import Mm
document = Document()
section = document.sections[0]
section.page_height = Mm(297)
section.page_width = Mm(210)
section.left_margin = Mm(25.4)
section.right_margin = Mm(25.4)
section.top_margin = Mm(25.4)
section.bottom_margin = Mm(25.4)
section.header_distance = Mm(12.7)
section.footer_... | It appears that a `Document` is made of several [`Section`](http://python-docx.readthedocs.io/en/latest/api/section.html#docx.section.Section)s with `page_height` and `page_width` attributes.
To set the dimensions of the first section to A4, you could try (untested):
```
section = document.sections[0]
section.page_he... |
21,368,393 | I installed Anaconda, but now that I wanted to use StringFunction in scitools.std I get error: ImportError: No module named scitools.std! So I did this:
```
sudo apt-get install python-scitools
```
Still didn't work. How can I help my computer "find scitools"?
Thank you for your time.
Kind regards,
Marius | 2014/01/26 | [
"https://Stackoverflow.com/questions/21368393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317563/"
] | Why not use PostGIS for this?
-----------------------------
You're overlooking what's possibly the ideal storage for this kind of data - PostGIS's data types, particularly the `geography` type.
```
SELECT ST_GeogFromText('POINT(35.21076593772987 11.22855348629825)');
```
By using `geography` you're storing your dat... | [All of the character types](http://www.postgresql.org/docs/current/static/datatype-character.html) (TEXT, VARCHAR, CHAR) behave similarly from a performance point of view. They are normally stored in-line in the table row, unless they are very large, in which case they may be stored in a separate file (called a TOAST ... |
21,368,393 | I installed Anaconda, but now that I wanted to use StringFunction in scitools.std I get error: ImportError: No module named scitools.std! So I did this:
```
sudo apt-get install python-scitools
```
Still didn't work. How can I help my computer "find scitools"?
Thank you for your time.
Kind regards,
Marius | 2014/01/26 | [
"https://Stackoverflow.com/questions/21368393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317563/"
] | [All of the character types](http://www.postgresql.org/docs/current/static/datatype-character.html) (TEXT, VARCHAR, CHAR) behave similarly from a performance point of view. They are normally stored in-line in the table row, unless they are very large, in which case they may be stored in a separate file (called a TOAST ... | Don't focus on the fact that these numbers are coordinates. Instead, notice that they are strings of numbers in a very limited range, and all of roughly the same magnitude. You are most likely interested in how these numbers change (looks like a trajectory of an object off the coast of Tunisia if I just punch these coo... |
21,368,393 | I installed Anaconda, but now that I wanted to use StringFunction in scitools.std I get error: ImportError: No module named scitools.std! So I did this:
```
sudo apt-get install python-scitools
```
Still didn't work. How can I help my computer "find scitools"?
Thank you for your time.
Kind regards,
Marius | 2014/01/26 | [
"https://Stackoverflow.com/questions/21368393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317563/"
] | Why not use PostGIS for this?
-----------------------------
You're overlooking what's possibly the ideal storage for this kind of data - PostGIS's data types, particularly the `geography` type.
```
SELECT ST_GeogFromText('POINT(35.21076593772987 11.22855348629825)');
```
By using `geography` you're storing your dat... | Don't focus on the fact that these numbers are coordinates. Instead, notice that they are strings of numbers in a very limited range, and all of roughly the same magnitude. You are most likely interested in how these numbers change (looks like a trajectory of an object off the coast of Tunisia if I just punch these coo... |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml fil... | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | Make sure webpreferences is like this.
```
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
``` | I fix this issue to add `webPreferences:{ nodeIntegration: true,preload: '${__dirname}/preload.js}',` in `electron.js` file and add `preload.js` file in your directory (I added in `/public` directory where my `electron.js` file exists)
**electron.js**
```
mainWindow = new BrowserWindow({
title: 'Electron App',
heig... |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml fil... | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | It looks like adding the preference:
```
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
```
is needed to enable `require` in the renderer process. | Don't set `contextIsolation` to false!
But use the `contextBridge.exposeInMainWorld` to add all what you need into the `window` object.
main.js
```js
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, '../preload.js')
}
```
preload.js
```js
const {
contextBridge,
ipcRenderer,
...
} ... |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml fil... | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | Make sure webpreferences is like this.
```
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
``` | Indeed, you have to set `nodeIntegration` to `true` in your BrowserWindow webPreferences since the version [5.0.0](https://electronjs.org/releases/stable#release-notes-for-v500) the default values of nodeIntegration and webviewTag are false to improve security. Electron associated PR: [16235](https://github.com/electro... |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml fil... | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | Make sure webpreferences is like this.
```
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
``` | Don't set `contextIsolation` to false!
But use the `contextBridge.exposeInMainWorld` to add all what you need into the `window` object.
main.js
```js
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, '../preload.js')
}
```
preload.js
```js
const {
contextBridge,
ipcRenderer,
...
} ... |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml fil... | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | It looks like adding the preference:
```
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
```
is needed to enable `require` in the renderer process. | I fix this issue to add `webPreferences:{ nodeIntegration: true,preload: '${__dirname}/preload.js}',` in `electron.js` file and add `preload.js` file in your directory (I added in `/public` directory where my `electron.js` file exists)
**electron.js**
```
mainWindow = new BrowserWindow({
title: 'Electron App',
heig... |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml fil... | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | It looks like adding the preference:
```
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
```
is needed to enable `require` in the renderer process. | Indeed, you have to set `nodeIntegration` to `true` in your BrowserWindow webPreferences since the version [5.0.0](https://electronjs.org/releases/stable#release-notes-for-v500) the default values of nodeIntegration and webviewTag are false to improve security. Electron associated PR: [16235](https://github.com/electro... |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml fil... | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | Since Electron 12, contextIsolation is be enabled by default, the implication being that require() cannot be used in the renderer process unless contextIsolation is false, more info in this link <https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true>
So include the followin... | Make sure webpreferences is like this.
```
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
``` |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml fil... | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | It looks like adding the preference:
```
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
```
is needed to enable `require` in the renderer process. | Since Electron 12, contextIsolation is be enabled by default, the implication being that require() cannot be used in the renderer process unless contextIsolation is false, more info in this link <https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true>
So include the followin... |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml fil... | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | Since Electron 12, contextIsolation is be enabled by default, the implication being that require() cannot be used in the renderer process unless contextIsolation is false, more info in this link <https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true>
So include the followin... | Indeed, you have to set `nodeIntegration` to `true` in your BrowserWindow webPreferences since the version [5.0.0](https://electronjs.org/releases/stable#release-notes-for-v500) the default values of nodeIntegration and webviewTag are false to improve security. Electron associated PR: [16235](https://github.com/electro... |
56,265,979 | i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file
output:
```
Enter your message >> who is your father
I was programmed by .
```
i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc
below is the aiml fil... | 2019/05/22 | [
"https://Stackoverflow.com/questions/56265979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9422110/"
] | It looks like adding the preference:
```
var mainWindow = new electron.BrowserWindow({
...
webPreferences: {
nodeIntegration: true,
}
});
```
is needed to enable `require` in the renderer process. | Make sure webpreferences is like this.
```
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
``` |
65,741,617 | I'm very new to all of this, so bear with me.
I started, and activated, a virtual environment. But when I pip install anything, it installs to the computer, not the the virtual env.
I'm on a Mac, trying to build a Django website.
Example:
With the virtual machine activated. I type:
```
python -m pip install Django
... | 2021/01/15 | [
"https://Stackoverflow.com/questions/65741617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15014571/"
] | Run this line from your project folder where "env" is your virtual enviroment
```
# A virtualenv's python:
$ env/bin/python -m pip install django
``` | If you want to install to your virtualenvironment you have to activate it, otherwise it will install to the main folder. |
65,741,617 | I'm very new to all of this, so bear with me.
I started, and activated, a virtual environment. But when I pip install anything, it installs to the computer, not the the virtual env.
I'm on a Mac, trying to build a Django website.
Example:
With the virtual machine activated. I type:
```
python -m pip install Django
... | 2021/01/15 | [
"https://Stackoverflow.com/questions/65741617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15014571/"
] | Run this line from your project folder where "env" is your virtual enviroment
```
# A virtualenv's python:
$ env/bin/python -m pip install django
``` | Confirm you’re in the virtual environment by checking the location of your Python interpreter, it should point to the env directory.
On macOS and Linux:
```
which python
.../env/bin/python
```
As long as your virtual environment is activated pip will install packages into that specific environment and you’ll be abl... |
35,633,516 | In [PEP 754](https://www.python.org/dev/peps/pep-0754/#id5)'s rejection notice, it's stated that:
>
> This PEP has been rejected. After sitting open for four years, it has
> failed to generate sufficient community interest.
>
>
> Several ideas of this PEP were implemented for Python 2.6.
> float('inf') and repr(f... | 2016/02/25 | [
"https://Stackoverflow.com/questions/35633516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4532996/"
] | My guess is that no one wanted to clutter the namespace needlessly.
If you want to do math, you can still do:
```
import math
print(math.inf)
print(-math.inf)
print(math.nan)
```
Output:
```
inf
-inf
nan
``` | you can use
float('inf')
np.nan |
21,977,987 | When I run a program from a USB memory, and remove the USB memory the program still goes on running (I mean with out really copying the program into the Windows PC).
However, does the program make its copy inside the Windows in any hidden location or temporary folder while running by the python IDLE. From where the pyt... | 2014/02/24 | [
"https://Stackoverflow.com/questions/21977987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There are plenty of ways someone can get your program, even if you remove the USB drive.
* They can install a program that triggers when a USB stick is inserted, search the stick for `.py` files, and copies them to disk.
* If the Python installation you're using is on the disk instead of the USB drive, they can replac... | It sounds like you are doing something you probably shouldn't be doing. Depending on how much people want your code they could go as far as physically freezing the ram and doing a forensic IT analysis. In short, you can't prevent code cloning on a machine you don't administer. |
17,973,507 | I have a long list of xy coordinates, and would like to convert it into numpy array.
```
>>> import numpy as np
>>> xy = np.random.rand(1000000, 2).tolist()
```
The obvious way would be:
```
>>> a = np.array(xy) # Very slow...
```
However, the above code is unreasonably slow. Interestingly, to transpose the long ... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17973507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2003079/"
] | Implementing this in Cython without the extra checking involved to determine dimensionality, etc. nearly eliminates the time difference you are seeing.
Here's the `.pyx` file I used to verify that.
```
from numpy cimport ndarray as ar
import numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(Fal... | This is because the fastest-varying index of your list is the last one, so `np.array()` has to traverse the array many times because the first index is much larger. If your list was transposed, `np.array()` would be faster than your `longlist2array`:
```
In [65]: import numpy as np
In [66]: xy = np.random.rand(10000,... |
17,973,507 | I have a long list of xy coordinates, and would like to convert it into numpy array.
```
>>> import numpy as np
>>> xy = np.random.rand(1000000, 2).tolist()
```
The obvious way would be:
```
>>> a = np.array(xy) # Very slow...
```
However, the above code is unreasonably slow. Interestingly, to transpose the long ... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17973507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2003079/"
] | This is because the fastest-varying index of your list is the last one, so `np.array()` has to traverse the array many times because the first index is much larger. If your list was transposed, `np.array()` would be faster than your `longlist2array`:
```
In [65]: import numpy as np
In [66]: xy = np.random.rand(10000,... | If you have pandas, you can use `pandas.lib.to_object_array()`, it's the fastest method:
```
import numpy as np
import pandas as pd
a = np.random.rand(100000, 2)
b = a.tolist()
%timeit np.array(b, dtype=float, ndmin=2)
%timeit np.array(b, dtype=object).astype(float)
%timeit np.array(zip(*b)).T
%timeit pd.lib.to_objec... |
17,973,507 | I have a long list of xy coordinates, and would like to convert it into numpy array.
```
>>> import numpy as np
>>> xy = np.random.rand(1000000, 2).tolist()
```
The obvious way would be:
```
>>> a = np.array(xy) # Very slow...
```
However, the above code is unreasonably slow. Interestingly, to transpose the long ... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17973507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2003079/"
] | Implementing this in Cython without the extra checking involved to determine dimensionality, etc. nearly eliminates the time difference you are seeing.
Here's the `.pyx` file I used to verify that.
```
from numpy cimport ndarray as ar
import numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(Fal... | If you have pandas, you can use `pandas.lib.to_object_array()`, it's the fastest method:
```
import numpy as np
import pandas as pd
a = np.random.rand(100000, 2)
b = a.tolist()
%timeit np.array(b, dtype=float, ndmin=2)
%timeit np.array(b, dtype=object).astype(float)
%timeit np.array(zip(*b)).T
%timeit pd.lib.to_objec... |
68,957,505 | ```
input = (Columbia and (India or Singapore) and Malaysia)
output = [Columbia, India, Singapore, Malaysia]
```
Basically ignore the python keywords and brackets
I tried with the below code, but still not able to eliminate the braces.
```
import keyword
my_str=input()
l1=list(my_str.split(" "))
l2=[x for x in l... | 2021/08/27 | [
"https://Stackoverflow.com/questions/68957505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15695277/"
] | If you want to do it using first principles, you can use the code that is presented on the [Wikipedia page for Halton sequence](https://en.wikipedia.org/wiki/Halton_sequence):
```py
def halton(b):
"""Generator function for Halton sequence."""
n, d = 0, 1
while True:
x = d - n
if x == 1:
... | In Python, SciPy is the main scientific computing package, and it [contains a Halton sequence generator](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.qmc.Halton.html), among other QMC functions.
For plotting, the standard way with SciPy is matplotlib; if you're not familiar with that, the [tutorial... |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image =... | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | For each position, look for the 4 possibles values, that for each a condition of existance
```
for i in range(len(arr)):
for j in range(len(arr[i])):
key = f'{i}{j}'
if i != 0:
d[key].append(arr[i - 1][j])
if j != 0:
d[key].append(arr[i][j - 1])
if i != (len(... | One approach using a dictionary comprehension:
```
from itertools import product
arr = [[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
def cross(i, j, a):
res = []
for ii, jj in zip([0, 1, 0, -1], [-1, 0, 1, 0]):
ni = (i + ii)
nj = (j + jj)
if (-1 < ni < len(a[0])) and (-1 < nj < len(... |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image =... | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | For each position, look for the 4 possibles values, that for each a condition of existance
```
for i in range(len(arr)):
for j in range(len(arr[i])):
key = f'{i}{j}'
if i != 0:
d[key].append(arr[i - 1][j])
if j != 0:
d[key].append(arr[i][j - 1])
if i != (len(... | **I modified the code a little bit because I was not sure how the defaultdict thing worked in yours but I hope this solves your problem.**
```
arr =[[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
d = {'00': [], '01': [], '02': [], '10': [], '11': [], '12': [], '20': [], '21': [], '22': []}
for i in range(len(arr)):
... |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image =... | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | For each position, look for the 4 possibles values, that for each a condition of existance
```
for i in range(len(arr)):
for j in range(len(arr[i])):
key = f'{i}{j}'
if i != 0:
d[key].append(arr[i - 1][j])
if j != 0:
d[key].append(arr[i][j - 1])
if i != (len(... | construct the four surrounding elements directly and exclude any values that are not in the range
```
from collections import defaultdict
arr, d =[[0, 2, 3], [2, 0, 4],[3, 4, 0]], defaultdict(list)
x_length, y_length = len(arr), len(arr[0])
for i in range(x_length):
for j in range(y_length):
items = [[x,... |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image =... | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | One approach using a dictionary comprehension:
```
from itertools import product
arr = [[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
def cross(i, j, a):
res = []
for ii, jj in zip([0, 1, 0, -1], [-1, 0, 1, 0]):
ni = (i + ii)
nj = (j + jj)
if (-1 < ni < len(a[0])) and (-1 < nj < len(... | **I modified the code a little bit because I was not sure how the defaultdict thing worked in yours but I hope this solves your problem.**
```
arr =[[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
d = {'00': [], '01': [], '02': [], '10': [], '11': [], '12': [], '20': [], '21': [], '22': []}
for i in range(len(arr)):
... |
73,104,518 | using opencv for capturing image in python
i want to make this image :
code for this :
```
# Image Processing
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (51,51), 15)
th3 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
ret, test_image =... | 2022/07/25 | [
"https://Stackoverflow.com/questions/73104518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16383903/"
] | One approach using a dictionary comprehension:
```
from itertools import product
arr = [[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
def cross(i, j, a):
res = []
for ii, jj in zip([0, 1, 0, -1], [-1, 0, 1, 0]):
ni = (i + ii)
nj = (j + jj)
if (-1 < ni < len(a[0])) and (-1 < nj < len(... | construct the four surrounding elements directly and exclude any values that are not in the range
```
from collections import defaultdict
arr, d =[[0, 2, 3], [2, 0, 4],[3, 4, 0]], defaultdict(list)
x_length, y_length = len(arr), len(arr[0])
for i in range(x_length):
for j in range(y_length):
items = [[x,... |
28,376,849 | The Eclipse PyDev plugin includes fantastic integrated `autopep8` support. It formats the code to PEP8 style automatically on save, with several knobs and options to tailor it to your needs.
But the `autopep8` import formatter breaks `site.addsitedir()` usage.
```
import site
site.addsitedir('/opt/path/lib/python')
... | 2015/02/07 | [
"https://Stackoverflow.com/questions/28376849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2125392/"
] | Oldie but still relevant as I found this one issue.
I'm using VSCode and autopep8.
You can disable formatting by adding `# nopep8` to the relevant lines.
ps. Checked the docs for a link but could not find it :( | The best option I can find is to turn off import sorts in PyDev. This is not a complete solution, but it's better than completely turning off `autopep8` code formatting.
Just uncheck the `Sort imports on save?` option in the Eclipse/PyDev Preferences.
For Eclipse Kepler, Service Release 2, with PyDev 3.9.2, you can... |
6,916,054 | I'm working with python using Matplotlib and PIL and a need to look into a image select and cut the area that i have to work with, leaving only the image of the selected area.I alredy know how to cut imagens with pil(using im.crop) but how can i select the coordinates to croped the image with mouse clicks?
To better e... | 2011/08/02 | [
"https://Stackoverflow.com/questions/6916054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/669332/"
] | You could use [matplotlib.widgets.RectangleSelector](http://matplotlib.sourceforge.net/api/widgets_api.html?highlight=matplotlib.widgets#matplotlib.widgets.RectangleSelector) (thanks to Joe Kington for this suggestion) to handle button press events:
```
import numpy as np
import matplotlib.pyplot as plt
import Image
i... | are you using tk? it will depend on what window management you are using. High level though, you'll want something like:
```
def onMouseDown():
// get and save your coordinates
def onMouseUp():
// save these coordinates as well
// now compare your coordinates to fingure out which corners
// are being... |
50,489,637 | I am learning C++, is there something like python-pip in C++? I am uing `json`/`YAML` packages in my 1st project, I want to know which is the correct way to manage dependencies in my project, and after I finished developing, which is the correct way to migrate dependencies to production environment? | 2018/05/23 | [
"https://Stackoverflow.com/questions/50489637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5735646/"
] | C++ doesn't have a standard package manager or build system: this is one of the major pain points of the language. You have a few options:
* Manually install dependencies when required.
* Use your OS's package manager.
* Adopt a third-party package manager such as [conan.io](http://conan.io).
None of the above soluti... | As far as I know, there is no central library management system in C++ similar to `pip`. You need to download and install the packages you need manually or through some package manager if your OS supports it.
As for managing multiple libraries in a C++ project, you could use [CMAKE](https://cmake.org/) or something si... |
18,755,963 | I have designed a GUI using python tkinter. And now I want to set style for Checkbutton and Labelframe, such as the font, the color .etc
I have read some answers on the topics of tkinter style, and I have used the following method to set style for both Checkbutton and Labelframe.
But they don't actually work.
```
Roo... | 2013/09/12 | [
"https://Stackoverflow.com/questions/18755963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771241/"
] | You need to configure the Label sub-component:
```
from tkinter import *
from tkinter import ttk
root = Tk()
s = ttk.Style()
s.configure('Red.TLabelframe.Label', font=('courier', 15, 'bold'))
s.configure('Red.TLabelframe.Label', foreground ='red')
s.configure('Red.TLabelframe.Label', background='blue')
lf = ttk.Lab... | As the accepted answer didn't really help me when I wanted to do a simple changing of weight of a `ttk.LabelFrame` font (if you do it like recommended, you end up with a misplaced label), I'll provide what worked for me.
You have to use `labelwidget` option argument of `ttk.LabelFrame` first preparing a seperate `ttk.... |
18,755,963 | I have designed a GUI using python tkinter. And now I want to set style for Checkbutton and Labelframe, such as the font, the color .etc
I have read some answers on the topics of tkinter style, and I have used the following method to set style for both Checkbutton and Labelframe.
But they don't actually work.
```
Roo... | 2013/09/12 | [
"https://Stackoverflow.com/questions/18755963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771241/"
] | You need to configure the Label sub-component:
```
from tkinter import *
from tkinter import ttk
root = Tk()
s = ttk.Style()
s.configure('Red.TLabelframe.Label', font=('courier', 15, 'bold'))
s.configure('Red.TLabelframe.Label', foreground ='red')
s.configure('Red.TLabelframe.Label', background='blue')
lf = ttk.Lab... | For completeness sake, I was looking how to change border color style (specifically color) of ttk.LabelFrame and finally found how it worked so wanted to post on the posts that I came across while searching.
I create global styles for my ttk widgets, there are ways to apply this to single widgets as well.
```
style =... |
18,755,963 | I have designed a GUI using python tkinter. And now I want to set style for Checkbutton and Labelframe, such as the font, the color .etc
I have read some answers on the topics of tkinter style, and I have used the following method to set style for both Checkbutton and Labelframe.
But they don't actually work.
```
Roo... | 2013/09/12 | [
"https://Stackoverflow.com/questions/18755963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771241/"
] | As the accepted answer didn't really help me when I wanted to do a simple changing of weight of a `ttk.LabelFrame` font (if you do it like recommended, you end up with a misplaced label), I'll provide what worked for me.
You have to use `labelwidget` option argument of `ttk.LabelFrame` first preparing a seperate `ttk.... | For completeness sake, I was looking how to change border color style (specifically color) of ttk.LabelFrame and finally found how it worked so wanted to post on the posts that I came across while searching.
I create global styles for my ttk widgets, there are ways to apply this to single widgets as well.
```
style =... |
38,163,087 | Having an issue where I would fill out the form and when I click to save the input, it would show the info submitted into the `query` but my `production_id` value would return as `None`.
**Here is the error:**
```
Environment:
Request Method: POST
Request URL: http://192.168.33.10:8000/podfunnel/episodeinfo/
Django... | 2016/07/02 | [
"https://Stackoverflow.com/questions/38163087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3557390/"
] | It looks like `production_id` can be `None` in your view, in which case you can't use it when you call reverse. It would be better to use `production.id` instead. You have just saved the production in your view, so `production.id` will be set.
```
return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwar... | You can't always redirect to `episodeimagefiles` if you didn't provide appropriate initial value for `production_id`:
```
# See if a production_id is passed on the kwargs, if so, retrieve and fill current data.
# if not just provide empty form since will be new.
production_id = kwargs.get('production_id', ... |
63,033,970 | Using python3.8.1, installing newest version, on Windows 10:
`pip install PyNaCl` gives me this error (last 10 lines):
```
File "C:\Program Files (x86)\Python3\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Program Files (x86)\Python3\lib\distutils\dist.p... | 2020/07/22 | [
"https://Stackoverflow.com/questions/63033970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8558929/"
] | I ultimately solved it by using `python -m pip install --no-use-pep517 pynacl` | Upgrading pip within the venv worked for me:
```
.\env\Scripts\activate
pip install -U pip
pip install -r requirements.txt
deactivate
``` |
28,891,405 | I am trying to contract some vertices in igraph (using the python api) while keeping the names of the vertices. It isn't clear to me how to keep the name attribute of the graph. The nodes of the graph are people and I'm trying to collapse people with corrupted names.
I looked at the R documentation and I still don't s... | 2015/03/06 | [
"https://Stackoverflow.com/questions/28891405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639290/"
] | In Python, the keyword argument you need is called `combine_attrs` and not `vertex.attr.comb`. See `help(Graph.contract_vertices)` from the Python command line after having imported igraph. Also, the keyword argument accepts either a single specifier (such as `first`) or a dictionary. Your first example is invalid beca... | Nevermind. You can just enter a dictionary without using the wording
```
vertex.attr.comb
``` |
70,806,221 | So I have a "terminal" like program written in python and in this program I need to accept "mkdir" and another input and save the input after mkdir as a variable. It would work how sys.argv works when executing a python program but this would have to work from inside the program and I have no idea how to make this work... | 2022/01/21 | [
"https://Stackoverflow.com/questions/70806221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17746152/"
] | May use the pattern (`\\[[^\\]]+(\\[|$)|(^|\\])[^\\[]+\\]`) in `str_detect`
```
library(dplyr)
library(stringr)
df %>%
filter(str_detect(Utterance, "\\[[^\\]]+(\\[|$)|(^|\\])[^\\[]+\\]"))
id Utterance
1 1 [but if I came !ho!me
2 3 =[yeah] I mea... | If you need a function to validate (nested) parenthesis, here is a stack based one.
```
valid_delim <- function(x, delim = c(open = "[", close = "]"), max_stack_size = 10L){
f <- function(x, delim, max_stack_size){
if(is.null(names(delim))) {
names(delim) <- c("open", "close")
}
if(nchar(x) > 0L){
... |
70,806,221 | So I have a "terminal" like program written in python and in this program I need to accept "mkdir" and another input and save the input after mkdir as a variable. It would work how sys.argv works when executing a python program but this would have to work from inside the program and I have no idea how to make this work... | 2022/01/21 | [
"https://Stackoverflow.com/questions/70806221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17746152/"
] | Another possible solution, using `purrr::map_dfr`.
**EXPLANATION**
I provide, in what follows, an explanation for my solution, as asked for by @ChrisRuehlemann:
1. With `str_extract_all(df$Utterance, "\\[|\\]")`, we extract all `[` and `]` of each utterance as a list and according to the order they appear in the utt... | If you need a function to validate (nested) parenthesis, here is a stack based one.
```
valid_delim <- function(x, delim = c(open = "[", close = "]"), max_stack_size = 10L){
f <- function(x, delim, max_stack_size){
if(is.null(names(delim))) {
names(delim) <- c("open", "close")
}
if(nchar(x) > 0L){
... |
66,830,558 | I just started a new project in django, I run the command 'django-admin startproject + project\_name', and 'python manage.py startapp + app\_name'. Created a project and app.
I also added my new app to the settings:
[settings pic](https://i.stack.imgur.com/aMIpy.png)
After that I tried to create my first module on 'm... | 2021/03/27 | [
"https://Stackoverflow.com/questions/66830558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15493450/"
] | You want a `dict: {letter:positions}` , for that a `defaultdict` is well suited
```
from collections import defaultdict
def nb_occurances(word):
dict_occ = {}
positions = defaultdict(list)
for i, c in enumerate(word):
dict_occ[c] = word.count(c)
positions[c].append(i)
return dict_occ, ... | Did you consider using the `collections.Counter` class?
```py
from collections import Counter
def nb_occurances(str):
ctr = Counter(str)
for ch, cnt in ctr.items():
print(ch, '->', cnt)
nb_occurances('ababccab')
```
Prints:
```
a -> 3
b -> 3
c -> 2
``` |
66,830,558 | I just started a new project in django, I run the command 'django-admin startproject + project\_name', and 'python manage.py startapp + app\_name'. Created a project and app.
I also added my new app to the settings:
[settings pic](https://i.stack.imgur.com/aMIpy.png)
After that I tried to create my first module on 'm... | 2021/03/27 | [
"https://Stackoverflow.com/questions/66830558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15493450/"
] | You want a `dict: {letter:positions}` , for that a `defaultdict` is well suited
```
from collections import defaultdict
def nb_occurances(word):
dict_occ = {}
positions = defaultdict(list)
for i, c in enumerate(word):
dict_occ[c] = word.count(c)
positions[c].append(i)
return dict_occ, ... | Another solution
```py
def nb_occurances(ch):
dict_occ = {} # dictionary of occurances count
dict_pos = {} # dictionary of positions
for i, c in enumerate(ch):
dict_occ[c] = ch.count(c)
if c not in dict_pos:
dict_pos[c] = []
dict_pos[c] += [i]
return dict_occ, dict... |
66,830,558 | I just started a new project in django, I run the command 'django-admin startproject + project\_name', and 'python manage.py startapp + app\_name'. Created a project and app.
I also added my new app to the settings:
[settings pic](https://i.stack.imgur.com/aMIpy.png)
After that I tried to create my first module on 'm... | 2021/03/27 | [
"https://Stackoverflow.com/questions/66830558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15493450/"
] | You want a `dict: {letter:positions}` , for that a `defaultdict` is well suited
```
from collections import defaultdict
def nb_occurances(word):
dict_occ = {}
positions = defaultdict(list)
for i, c in enumerate(word):
dict_occ[c] = word.count(c)
positions[c].append(i)
return dict_occ, ... | ```
from collections import defaultdict
s = "ababac"
dict = defaultdict(list)
for i in range(len(s)):
dict[s[i]].append(i)
for key in dict:
print(key, dict[key])
```
keep a dictionary where the key,value is character, list |
66,830,558 | I just started a new project in django, I run the command 'django-admin startproject + project\_name', and 'python manage.py startapp + app\_name'. Created a project and app.
I also added my new app to the settings:
[settings pic](https://i.stack.imgur.com/aMIpy.png)
After that I tried to create my first module on 'm... | 2021/03/27 | [
"https://Stackoverflow.com/questions/66830558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15493450/"
] | You want a `dict: {letter:positions}` , for that a `defaultdict` is well suited
```
from collections import defaultdict
def nb_occurances(word):
dict_occ = {}
positions = defaultdict(list)
for i, c in enumerate(word):
dict_occ[c] = word.count(c)
positions[c].append(i)
return dict_occ, ... | You can try with below code.
input : `hello` and
output : `{'h': [0], 'e': [1], 'l': [2, 3], 'o': [4]}`
```
from collections import defaultdict
chaine = input ("chaine : ")
def nb_occurances(ch):
positions = defaultdict(list)
for i,j in enumerate(ch):
positions[j].append(i)
return positions
print ... |
43,573,582 | I'm trying to make a graph with a pretty massive key:
```
my_plot = degrees.plot(kind='bar',stacked=True,title="% of Degrees by Field",fontsize=20,figsize=(24, 16))
my_plot.set_xlabel("Institution", fontsize=20)
my_plot.set_ylabel("% of Degrees by Field", fontsize=20)
my_plot.legend(["Agriculture, Agriculture Oper... | 2017/04/23 | [
"https://Stackoverflow.com/questions/43573582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7907634/"
] | >
> but as a2[][] is locally declared then its elements should not be initialosed by deaflt
>
>
>
There's a big difference between a *variable* and an array entry.
`b` not being initialized is a common coding error, so the compiler calls it out.
But `a2` is initialized, and the contents of an array are set to th... | ```
public class HelloWorld{
public static void main(String []args){
System.out.println("sampleArray[0] is ");
int sampleArray[] = new int[7];
System.out.println(sampleArray[0]);
}
}
Output
sampleArray[0] is
0
``` |
54,445,338 | A python list consist of a number of items that is equally divided by 3.
The list looks like this:
```
the_list = ['ab','cd','e','fgh','i', 'jklm']
```
I want to merge 3 items at the time for the entire list. How should I do that? (the list could have any number of items as long as the number of items can be divid... | 2019/01/30 | [
"https://Stackoverflow.com/questions/54445338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2466763/"
] | You can slice the list while iterating an index over the length of the list with a step of 3 in a list comprehension:
```
[''.join(the_list[i:i + 3]) for i in range(0, len(the_list), 3)]
```
You can also create an iterator from the list and use `zip` with `itertools.repeat` to group 3 items at a time:
```
from iter... | Here's one way using a list comprehension and `range`:
```
output = [''.join(the_list[i:i+3]) for i in range(0, len(the_list), 3)]
``` |
9,701,227 | I don't understand the answers for a [similar question.](https://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`... | 2012/03/14 | [
"https://Stackoverflow.com/questions/9701227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94363/"
] | Because
```
1 == True # 1 == (1 == 1)
```
is `True`, but
```
None == True # None == (None == None)
```
is `False` (and `None == False` is `False` as well, so once you got `False`, it stays `False`).
That's how `reduce` works: It passes each element and the **result** of the previous evaluation to the callback. ... | Your second example return `False` because the first time `None == None` gives `True`, but `True == None` gives `False`.
Take a look at the [`reduce` doc](http://docs.python.org/library/functions.html#reduce) to see how it works.
Also note that "comparisons to singletons like `None` should always be done with `is` or... |
9,701,227 | I don't understand the answers for a [similar question.](https://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`... | 2012/03/14 | [
"https://Stackoverflow.com/questions/9701227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94363/"
] | It's not different with `None`, actually, what happens within `reduce` in the first case is
* 1 compared with 1 (== `True`)
* `True` compared with 1 (== `True`)
In the second case, it's
* `None` compared with `None` (== `True`)
* `True` compared with `None` (== `False`)
The funny example would be:
```
>> from ope... | Your second example return `False` because the first time `None == None` gives `True`, but `True == None` gives `False`.
Take a look at the [`reduce` doc](http://docs.python.org/library/functions.html#reduce) to see how it works.
Also note that "comparisons to singletons like `None` should always be done with `is` or... |
9,701,227 | I don't understand the answers for a [similar question.](https://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`... | 2012/03/14 | [
"https://Stackoverflow.com/questions/9701227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94363/"
] | Consider the following:
```
In [214]: l = [None,None,None]
In [215]: reduce(lambda x,y: x== y, l)
Out[215]: False
In [216]: from functional import scanl
In [217]: scanl(lambda x,y: x== y, None, l)
Out[217]: <generator object _scanl at 0x0000000005770D38>
In [218]: list(scanl(lambda x,y: x== y, None, l))
Out[218]: ... | Your second example return `False` because the first time `None == None` gives `True`, but `True == None` gives `False`.
Take a look at the [`reduce` doc](http://docs.python.org/library/functions.html#reduce) to see how it works.
Also note that "comparisons to singletons like `None` should always be done with `is` or... |
9,701,227 | I don't understand the answers for a [similar question.](https://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`... | 2012/03/14 | [
"https://Stackoverflow.com/questions/9701227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/94363/"
] | Because
```
1 == True # 1 == (1 == 1)
```
is `True`, but
```
None == True # None == (None == None)
```
is `False` (and `None == False` is `False` as well, so once you got `False`, it stays `False`).
That's how `reduce` works: It passes each element and the **result** of the previous evaluation to the callback. ... | It's not different with `None`, actually, what happens within `reduce` in the first case is
* 1 compared with 1 (== `True`)
* `True` compared with 1 (== `True`)
In the second case, it's
* `None` compared with `None` (== `True`)
* `True` compared with `None` (== `False`)
The funny example would be:
```
>> from ope... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.