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
43,630,195
`A = [[[1,2,3],[4]],[[1,4],[2,3]]]` Here I want to find lists in A which sum of all sublists in list not grater than 5. Which the result should be `[[1,4],[2,3]]` I tried a long time to solve this problem in python. But I still can't figure out the right solution, which I stuck at loop out multiple loops. My code as...
2017/04/26
[ "https://Stackoverflow.com/questions/43630195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5702561/" ]
Simplification of @KindStranger method in a one-liner: ``` >> [sub for x in A for sub in x if max(sum(sub) for sub in x) <= 5] [[1, 4], [2, 3]] ```
The one with `all()` ``` [t for item in A for t in item if all(sum(t)<=5 for t in item)] ```
54,093,050
I'm following this code example from a [python course](https://www.python-course.eu/python3_properties.php): ``` class P: def __init__(self,x): self.x = x @property def x(self): return self.__x @x.setter def x(self, x): if x < 0: self.__x = 0 elif x > ...
2019/01/08
[ "https://Stackoverflow.com/questions/54093050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3128156/" ]
Your setter method should be like below: ``` @M_inv.setter def M_inv(self): M = self.var * np.eye(self.W.shape[1]) + np.matmul(self.W.T, self.W) self.__M_inv = np.linalg.inv(M) ``` The decorator `@M_inv.setter` and the function `def M_inv(self):` name should be same
The example is wrong. EDIT: Example was using a setter in `__init__` on purpose. Getters and setters, even though they act like properties, are just methods that access a private attribute. That attribute **must exist**. In the example, `self.__x` is never created. Here is my suggested use : ``` class PCAModel(obje...
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2...
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using booleans in arithmetic operations (also lambda functions) is very pythonic: ``` lst = [True, False, True] func = lambda x: sum(2 ** num * i for num, i in enumerate(x)) print(func(lst)) # 5 ```
This is another hacky way I came up with: ``` def f1(v): return int(''.join(str(int(b)) for b in v), 2) ``` Example: ``` >>> def f1(v): ... return int(''.join(str(int(b)) for b in v), 2) ... >>> f1([True, False, True]) 5 >>> ``` Another identical example using `map` (more readable in my view): ``` def f1...
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2...
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using a left shift is slightly faster than raising to powers (at least on my machine). Using a bitwise operation encourages the reader of the code to think in terms of binary data. ``` >>> sum(v << i for i, v in enumerate([True, False, True])) 5 ```
This is another hacky way I came up with: ``` def f1(v): return int(''.join(str(int(b)) for b in v), 2) ``` Example: ``` >>> def f1(v): ... return int(''.join(str(int(b)) for b in v), 2) ... >>> f1([True, False, True]) 5 >>> ``` Another identical example using `map` (more readable in my view): ``` def f1...
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2...
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Just for contrast here's a way that you would do this if you were writing python as if you were writing something like c. ``` def f(l): output = 0 for i in range(len(l)): output |= l[i] << i return output ```
This is another hacky way I came up with: ``` def f1(v): return int(''.join(str(int(b)) for b in v), 2) ``` Example: ``` >>> def f1(v): ... return int(''.join(str(int(b)) for b in v), 2) ... >>> f1([True, False, True]) 5 >>> ``` Another identical example using `map` (more readable in my view): ``` def f1...
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2...
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using a left shift is slightly faster than raising to powers (at least on my machine). Using a bitwise operation encourages the reader of the code to think in terms of binary data. ``` >>> sum(v << i for i, v in enumerate([True, False, True])) 5 ```
Using booleans in arithmetic operations (also lambda functions) is very pythonic: ``` lst = [True, False, True] func = lambda x: sum(2 ** num * i for num, i in enumerate(x)) print(func(lst)) # 5 ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2...
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using booleans in arithmetic operations (also lambda functions) is very pythonic: ``` lst = [True, False, True] func = lambda x: sum(2 ** num * i for num, i in enumerate(x)) print(func(lst)) # 5 ```
Its little more rigid solution but its very **computationally efficient** ``` >>> import numpy as np >>> predefined_bytes = 2**(np.arange(32)) >>> predefined_bytes array([ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, ...
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2...
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Just for contrast here's a way that you would do this if you were writing python as if you were writing something like c. ``` def f(l): output = 0 for i in range(len(l)): output |= l[i] << i return output ```
Using booleans in arithmetic operations (also lambda functions) is very pythonic: ``` lst = [True, False, True] func = lambda x: sum(2 ** num * i for num, i in enumerate(x)) print(func(lst)) # 5 ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2...
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using a left shift is slightly faster than raising to powers (at least on my machine). Using a bitwise operation encourages the reader of the code to think in terms of binary data. ``` >>> sum(v << i for i, v in enumerate([True, False, True])) 5 ```
Its little more rigid solution but its very **computationally efficient** ``` >>> import numpy as np >>> predefined_bytes = 2**(np.arange(32)) >>> predefined_bytes array([ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, ...
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2...
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using a left shift is slightly faster than raising to powers (at least on my machine). Using a bitwise operation encourages the reader of the code to think in terms of binary data. ``` >>> sum(v << i for i, v in enumerate([True, False, True])) 5 ```
Just for contrast here's a way that you would do this if you were writing python as if you were writing something like c. ``` def f(l): output = 0 for i in range(len(l)): output |= l[i] << i return output ```
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2...
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Just for contrast here's a way that you would do this if you were writing python as if you were writing something like c. ``` def f(l): output = 0 for i in range(len(l)): output |= l[i] << i return output ```
Its little more rigid solution but its very **computationally efficient** ``` >>> import numpy as np >>> predefined_bytes = 2**(np.arange(32)) >>> predefined_bytes array([ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, ...
54,757,300
I have an existing python array instantiated with zeros. How do I iterate through and change the values? I can't iterate through and change elements of a Python array? ``` num_list = [1,2,3,3,4,5,] mu = np.mean(num_list) sigma = np.std(num_list) std_array = np.zeros(len(num_list)) for i in std_array: temp_nu...
2019/02/19
[ "https://Stackoverflow.com/questions/54757300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671993/" ]
In your code you are iterating over the elements of the `numpy.array` `std_array`, but then using these elements as indices to dereference `std_array`. An easy solution would be the following. ``` num_arr = np.array(num_list) for i,element in enumerate(num_arr): temp_num = (element-mu)/sigma std_array[i]=temp_...
You `i` is an element from `std_array`, which is `float`. `Numpy` is therefore complaining that you are trying slicing with `float` where: > > only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) > and integer or boolean arrays are valid indices > > > If you don't have to use `for`, then `numpy`...
32,200,565
I`ve got this exception when using returnvalue in function ``` @inlineCallbacks def my_func(id): yield somefunc(id) @inlineCallbacks def somefunc(id): somevar = yield func(id) returnValue(somevar) returnValue(somevar) File "/usr/lib64/python2.7/site-packages/twisted/internet/defer.py", line 1105, in retur...
2015/08/25
[ "https://Stackoverflow.com/questions/32200565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4349456/" ]
Just download and install [wp-pagenavi](https://wordpress.org/plugins/wp-pagenavi/) plugin and then use: ``` if(method_exists('wp_pagenavi')){ wp_pagenavi(array('query' => $query)); } ``` Pass your query object in wp\_pagenavi method argument.
i guess, you are seeking a numbered pagination for custom query, than try this article [Kvcodes](http://www.kvcodes.com/2015/08/how-to-add-numeric-pagination-in-your-wordpress-theme-without-plugin/). here is the code. ``` function kvcodes_pagination_fn($pages = '', $range = 2){ $showitems = ($range * 2)+1; ...
59,723,005
For my report, I'm creating a special color plot in jupyter notebook. There are two parameters, `x` and `y`. ``` import numpy as np x = np.arange(-1,1,0.1) y = np.arange(1,11,1) ``` with which I compute a third quantity. Here is an example to demonstrate the concept: ``` values = [] for i in range(len(y)) : z ...
2020/01/13
[ "https://Stackoverflow.com/questions/59723005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A known (reasonably) numerically-stable version of the geometric mean is: ```py import torch def gmean(input_x, dim): log_x = torch.log(input_x) return torch.exp(torch.mean(log_x, dim=dim)) x = torch.Tensor([2.0] * 1000).requires_grad_(True) print(gmean(x, dim=0)) # tensor(2.0000, grad_fn=<ExpBackward>) ```...
torch.prod() helps: ``` import torch x = torch.FloatTensor(3).uniform_().requires_grad_(True) print(x) y = x.prod() ** (1.0/x.shape[0]) print(y) y.backward() print(x.grad) # tensor([0.5692, 0.7495, 0.1702], requires_grad=True) # tensor(0.4172, grad_fn=<PowBackward0>) # tensor([0.2443, 0.1856, 0.8169]) ``` EDIT: ?w...
5,268,391
Is it possible to pipe numpy data (from one python script ) into the other? suppose that `script1.py` looks like this: `x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']})` `print x` Suppose that from the linux command, I run the following: `python script1.py | script2.py` Will `script2.py` g...
2011/03/11
[ "https://Stackoverflow.com/questions/5268391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
No, data is passed through a pipe as text. You'll need to serialize the data in `script1.py` before writing, and deserialize it in `script2.py` after reading.
Check out the `save` and `load` functions. I don't think they would object to being passed a pipe instead of a file.
5,268,391
Is it possible to pipe numpy data (from one python script ) into the other? suppose that `script1.py` looks like this: `x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']})` `print x` Suppose that from the linux command, I run the following: `python script1.py | script2.py` Will `script2.py` g...
2011/03/11
[ "https://Stackoverflow.com/questions/5268391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
No, data is passed through a pipe as text. You'll need to serialize the data in `script1.py` before writing, and deserialize it in `script2.py` after reading.
See [this question](https://stackoverflow.com/questions/5033799/how-do-i-pass-large-numpy-arrays-between-python-subprocesses-without-saving-to-di). If you're willing to use the `subprocess` module, you can share memory between processes to pass numpy arrays rapidly. If not, I've found saving to a file beats the pants ...
5,268,391
Is it possible to pipe numpy data (from one python script ) into the other? suppose that `script1.py` looks like this: `x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']})` `print x` Suppose that from the linux command, I run the following: `python script1.py | script2.py` Will `script2.py` g...
2011/03/11
[ "https://Stackoverflow.com/questions/5268391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
Check out the `save` and `load` functions. I don't think they would object to being passed a pipe instead of a file.
See [this question](https://stackoverflow.com/questions/5033799/how-do-i-pass-large-numpy-arrays-between-python-subprocesses-without-saving-to-di). If you're willing to use the `subprocess` module, you can share memory between processes to pass numpy arrays rapidly. If not, I've found saving to a file beats the pants ...
26,373,356
I am not sure why I am getting an error that game is not defined: ``` #!/usr/bin/python # global variables wins = 0 losses = 0 draws = 0 games = 0 # Welcome and get name of human player print 'Welcome to Rock Paper Scissors!!' human = raw_input('What is your name?') print 'Hello ',human # start game game() def gam...
2014/10/15
[ "https://Stackoverflow.com/questions/26373356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4147288/" ]
You have to define the function `game` before you can call it. ``` def game(): ... game() ```
Okay, I spent some time tinkering with this today and now have the following: ``` import random import string # global variables global wins wins = 0 global losses losses = 0 global draws draws = 0 global games games = 0 # Welcome and get name of human player print 'Welcome to Rock Paper Scissors!!' human = raw_input...
26,373,356
I am not sure why I am getting an error that game is not defined: ``` #!/usr/bin/python # global variables wins = 0 losses = 0 draws = 0 games = 0 # Welcome and get name of human player print 'Welcome to Rock Paper Scissors!!' human = raw_input('What is your name?') print 'Hello ',human # start game game() def gam...
2014/10/15
[ "https://Stackoverflow.com/questions/26373356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4147288/" ]
Because, at the time the statement `game()` is executed you have not yet reached the statement `def game():` and game is, therefore, undefined. If you move `game()` to after `def game()` you will then get a similar error on `main()` which is harder to fix as you don't appear to be defining a function called `main` any...
Okay, I spent some time tinkering with this today and now have the following: ``` import random import string # global variables global wins wins = 0 global losses losses = 0 global draws draws = 0 global games games = 0 # Welcome and get name of human player print 'Welcome to Rock Paper Scissors!!' human = raw_input...
53,350,132
I'm trying to understand how to pull a specific item from the code below. ``` var snake = [[{x : 20, y : 30}],[{x : 40, y: 50}]]; ``` Coming from python I found this to be useful when dealing with for loops to have all my objects in an array within an array. Say for instance I want to pull the first `x:` value from...
2018/11/17
[ "https://Stackoverflow.com/questions/53350132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10444342/" ]
You are deleting a large number of rows. That is the problem. There is lots of overhead in deletions. If you are deleting a significant number of rows in a table -- and significant might only be a few percent -- then it is often faster to recreate the table: ``` select b.* into temp_b -- actually, I wouldn't use a t...
Your query looks fine to me. Your problem seems to be that you have a very large amount of data and need ways to optimize performance. What you can do is materialize your subquery, and make sure max\_id is indexed, for example by making it a primary key. So create a temporary table `Max_B`, and store the results of ...
51,869,152
Supposing that a have this dict with the keys and some range: ``` d = {"x": (0, 2), "y": (2, 4)} ``` I need to create dicts using the range above, I will get: ``` >>> keys = [k for k,v in d.items()] >>> >>> def newDict(keys,array): ... return dict(zip(keys,array)) ... >>> for i in range(0,2): ... for j in...
2018/08/16
[ "https://Stackoverflow.com/questions/51869152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2452792/" ]
This is known behavior that came about a few versions ago (I think 2016). This `#{style}` interpolation is not supported in attributes: > > Caution > > > Previous versions of Pug/Jade supported an interpolation syntax such > as: > > > a(href="/#{url}") Link This syntax is no longer supported. > Alternatives ar...
There is an easy way to do that, write directly the variable, without using quotes, brackets, $, !, or #, like this: ``` a(href=originalUrl) !{originalURL} ``` The result of this is a link with the text in originalURL Example: if originalUrl = 'www.google.es' ``` a(href='www.google.es') www.google.es ``` finally...
58,928,062
``` import pandas as pd from sqlalchemy import create_engine host='[email protected]' port=10000 schema ='result' table='new_table' engine = create_engine(f'hive://{host}:{port}/{schema}') conn=engine.connect() engine.execute('CREATE TABLE ' + table + ' (year int, GDP_rate int, GDP string)') data = { 'year': [2017, 2018...
2019/11/19
[ "https://Stackoverflow.com/questions/58928062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12300690/" ]
Kindly add method='multi' for batch insert df.to\_sql("table\_name", con = engine,index=False,method='multi')
A likely pyhive bug. See <https://github.com/dropbox/PyHive/issues/250>. The problem happens when inserting multiple rows.
48,524,013
So i'm starting to use Django but i had some problems trying to run my server. I have two versions of python installed. So in my mysite package i tried to run `python manage.py runserver` but i got this error: ``` Unhandled exception in thread started by <function wrapper at 0x058E1430> Traceback (most recent call ...
2018/01/30
[ "https://Stackoverflow.com/questions/48524013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9217311/" ]
Not sure what django version you are currently using but if you are working with Django 2.0 then python2 wouldn't work ( Cause Django2.0 support only Python 3.4+) So in your case if you are in Django2.0 (assuming you already have installed latest version of python in your machine) then you should run following command...
Have you tried to upgrade django with pip or pip3? ``` pip install --upgrade django --user ```
48,524,013
So i'm starting to use Django but i had some problems trying to run my server. I have two versions of python installed. So in my mysite package i tried to run `python manage.py runserver` but i got this error: ``` Unhandled exception in thread started by <function wrapper at 0x058E1430> Traceback (most recent call ...
2018/01/30
[ "https://Stackoverflow.com/questions/48524013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9217311/" ]
Not sure what django version you are currently using but if you are working with Django 2.0 then python2 wouldn't work ( Cause Django2.0 support only Python 3.4+) So in your case if you are in Django2.0 (assuming you already have installed latest version of python in your machine) then you should run following command...
**You need to upgrade Django** ``` pip install --upgrade django pip3 install --upgrade django ```
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
*For Linux and OSX* **Step 1: Download chromedriver** ``` # You can find more recent/older versions at http://chromedriver.storage.googleapis.com/ # Also make sure to pick the right driver, based on your Operating System wget http://chromedriver.storage.googleapis.com/81.0.4044.69/chromedriver_mac64.zip ``` For deb...
Had this issue with Mac Mojave running Robot test framework and Chrome 77. This solved the problem. Kudos @Navarasu for pointing me to the right track. ``` $ pip install webdriver-manager --user # install webdriver-manager lib for python $ python # open python prompt ``` Next, in python prompt: ``` from selenium im...
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
You can test if it actually is in the PATH, if you open a cmd and type in `chromedriver` (assuming your chromedriver executable is still named like this) and hit Enter. If `Starting ChromeDriver 2.15.322448` is appearing, the PATH is set appropriately and there is something else going wrong. Alternatively you can use ...
Could try to restart computer if it doesn't work after you are quite sure that PATH is set correctly. In my case on windows 7, I always got the error on WebDriverException: Message: for chromedriver, gecodriver, IEDriverServer. I am pretty sure that i have correct path. Restart computer, all work
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
When you unzip chromedriver, please do specify an exact location so that you can trace it later. Below, you are getting the right chromedriver for your OS, and then unzipping it to an exact location, which could be provided as argument later on in your code. `wget http://chromedriver.storage.googleapis.com/2.10/chrome...
In my case, this error disappears when I have copied chromedriver file to c:\Windows folder. Its because windows directory is in the path which python script check for chromedriver availability.
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
After testing to check that ChromeDriver is installed ``` chromedriver ``` You should see ``` Starting ChromeDriver version.number ChromeDriver was successful ``` Check the path of the ChromeDriver path ``` which chromedriver ``` Use the Path in your code ``` ... from selenium import webdriver options = Opt...
For mac osx users ``` brew tap homebrew/cask brew cask install chromedriver ```
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
You can test if it actually is in the PATH, if you open a cmd and type in `chromedriver` (assuming your chromedriver executable is still named like this) and hit Enter. If `Starting ChromeDriver 2.15.322448` is appearing, the PATH is set appropriately and there is something else going wrong. Alternatively you can use ...
For MAC users: 1. Download Chromedriver: <https://sites.google.com/a/chromium.org/chromedriver/downloads> 2.In Terminal type "sudo nano /etc/paths" 3.Add line with path to Cromedriver as example: "/Users/username/Downloads" 4. Try to run your test again!
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
Before you add the chromedriver to your path, make sure it's the same version as your browser. If not, you will need to match versions: either update/downgrade you chrome, and upgrade/downgrade your webdriver. I recommend updating your chrome version as much as possible, and the matching the webdriver. To update ...
**pip install webdriver-manager** If you run script by using python3: **pip3 install webdriver-manager** * Then in script please use: ``` from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) ```
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
Another way is download and unzip chromedriver and put '**chromedriver.exe'** in **C:\Program Files\Python38\Scripts** and then you need not to provide the path of driver, just driver= webdriver.Chrome()
Check the path of your chrome driver, it might not get it from there. Simply Copy paste the driver location into the code.
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
I see the discussions still talk about the old way of setting up chromedriver by downloading the binary and configuring the path manually. This can be done automatically using [webdriver-manager](https://pypi.org/project/webdriver-manager/) ``` pip install webdriver-manager ``` Now the above code in the question wi...
If you are using remote interpreter you have to also check if its executable PATH is defined. In my case switching from remote Docker interpreter to local interpreter solved the problem.
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
When I downloaded chromedriver.exe I just move it in PATH folder C:\Windows\System32\chromedriver.exe and had exact same problem. For me solution was to just change folder in PATH, so I just moved it at Pycharm Community bin folder that was also in PATH. ex: * C:\Windows\System32\chromedriver.exe --> Gave me excepti...
I had this problem on Webdriver 3.8.0 (Chrome 73.0.3683.103 and ChromeDriver 73.0.3683.68). The problem disappeared after I did ``` pip install -U selenium ``` to upgrade Webdriver to 3.14.1.
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
*For Linux and OSX* **Step 1: Download chromedriver** ``` # You can find more recent/older versions at http://chromedriver.storage.googleapis.com/ # Also make sure to pick the right driver, based on your Operating System wget http://chromedriver.storage.googleapis.com/81.0.4044.69/chromedriver_mac64.zip ``` For deb...
Before you add the chromedriver to your path, make sure it's the same version as your browser. If not, you will need to match versions: either update/downgrade you chrome, and upgrade/downgrade your webdriver. I recommend updating your chrome version as much as possible, and the matching the webdriver. To update ...
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most ...
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
in Anaconda install * python-graphviz * pydot This will fix your problem
In case if your operation system is **Ubuntu** I recommend to try command: ``` sudo apt-get install -y graphviz libgraphviz-dev ```
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most ...
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
As @grrr answered above, here is the code: ``` conda install -c anaconda python-graphviz conda install -c anaconda pydot ```
In case if your operation system is **Ubuntu** I recommend to try command: ``` sudo apt-get install -y graphviz libgraphviz-dev ```
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most ...
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
In case if your operation system is **Ubuntu** I recommend to try command: ``` sudo apt-get install -y graphviz libgraphviz-dev ```
I know the question has already been answered, but for future readers, I came here with the same jupyter notebook issue; after installing python-graphviz and pydot I still had the same issue. Here's what worked for me: Make sure that the python version of your terminal matches that of the jupyter notebook, so run this ...
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most ...
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
In case if your operation system is **Ubuntu** I recommend to try command: ``` sudo apt-get install -y graphviz libgraphviz-dev ```
I installed the grphviz package using conda. However, I kept getting "module not found error" even after restart kernel multiple times. Then following the suggestions on this page, I even installed "PyDot", however, it didn't really help. Finally, I installed the package using ``` pip install graphviz ``` and final...
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most ...
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
in Anaconda install * python-graphviz * pydot This will fix your problem
As @grrr answered above, here is the code: ``` conda install -c anaconda python-graphviz conda install -c anaconda pydot ```
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most ...
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
in Anaconda install * python-graphviz * pydot This will fix your problem
I know the question has already been answered, but for future readers, I came here with the same jupyter notebook issue; after installing python-graphviz and pydot I still had the same issue. Here's what worked for me: Make sure that the python version of your terminal matches that of the jupyter notebook, so run this ...
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most ...
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
in Anaconda install * python-graphviz * pydot This will fix your problem
I installed the grphviz package using conda. However, I kept getting "module not found error" even after restart kernel multiple times. Then following the suggestions on this page, I even installed "PyDot", however, it didn't really help. Finally, I installed the package using ``` pip install graphviz ``` and final...
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most ...
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
As @grrr answered above, here is the code: ``` conda install -c anaconda python-graphviz conda install -c anaconda pydot ```
I know the question has already been answered, but for future readers, I came here with the same jupyter notebook issue; after installing python-graphviz and pydot I still had the same issue. Here's what worked for me: Make sure that the python version of your terminal matches that of the jupyter notebook, so run this ...
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most ...
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
As @grrr answered above, here is the code: ``` conda install -c anaconda python-graphviz conda install -c anaconda pydot ```
I installed the grphviz package using conda. However, I kept getting "module not found error" even after restart kernel multiple times. Then following the suggestions on this page, I even installed "PyDot", however, it didn't really help. Finally, I installed the package using ``` pip install graphviz ``` and final...
58,838,759
I have multiple csv files containing item and invoicing data (proprietary and edifact files). They look roughly like this: ``` 0001;12345;Item1 0002;12345;EUR;1.99 0003;12345;EUR;1.99 ``` The always start with 0001 but do not necessarily have more than one row. How do I group them efficiently? Currently I read them...
2019/11/13
[ "https://Stackoverflow.com/questions/58838759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11766755/" ]
With my knowledge of EDIFACT-style files, they're basically hierarchical, with some row code (`0001` here) acting as a "start-of-group" symbol. So yeah – something like this is a fast, Pythonic way to group by that symbol. (`input_file` can just as well be a disk file, but for the sake of a self-contained example, it'...
If the files have the same columns, it would be interesting to read it in dataframes, and append to each one this thing. `df1= pd.read_csv(Path+File1, sep=';') df2= pd.read_csv(Path+File2, sep=';') df2.append(df1, ignore_index = True, sort=False).` Afterward, you can just sort by the first column that contains...
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > >...
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
> > ipython` 7.0.1 has requirement prompt-toolkit<2.1.0,>=2.0.0, but you'll have prompt-toolkit 1.0.15 which is incompatible > > > <https://github.com/jupyter/jupyter_console/issues/158> > > > Upgrading `prompt-toolkit` will fix the problem. ``` pip install --upgrade prompt-toolkit ```
It's more stable to create a kernel with an Anaconda virtualenv. Follow these steps. 1. Execute Anaconda prompt. 2. Type `conda create --name $ENVIRONMENT_NAME R -y` 3. Type `conda activate $ENVIRONMENT_NAME` 4. Type `python -m ipykernel install` 5. Type `ipython kernel install --user --name $ENVIRONMENT_NAME` Then,...
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > >...
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
> > ipython` 7.0.1 has requirement prompt-toolkit<2.1.0,>=2.0.0, but you'll have prompt-toolkit 1.0.15 which is incompatible > > > <https://github.com/jupyter/jupyter_console/issues/158> > > > Upgrading `prompt-toolkit` will fix the problem. ``` pip install --upgrade prompt-toolkit ```
I had the same problem, I fixed in the way its say in Github: <https://github.com/jupyter/notebook/issues/4079> * open Anaconda Prompt typing ``` python -m ipykernel install --user ```
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > >...
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
> > ipython` 7.0.1 has requirement prompt-toolkit<2.1.0,>=2.0.0, but you'll have prompt-toolkit 1.0.15 which is incompatible > > > <https://github.com/jupyter/jupyter_console/issues/158> > > > Upgrading `prompt-toolkit` will fix the problem. ``` pip install --upgrade prompt-toolkit ```
Check your environment variable `Path`! In the system variable `Path` add the following line > > C:\Users\\AppData\Roaming\Python\Python37\Scripts > > >
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > >...
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
> > ipython` 7.0.1 has requirement prompt-toolkit<2.1.0,>=2.0.0, but you'll have prompt-toolkit 1.0.15 which is incompatible > > > <https://github.com/jupyter/jupyter_console/issues/158> > > > Upgrading `prompt-toolkit` will fix the problem. ``` pip install --upgrade prompt-toolkit ```
First Select your environment name. In my case it was **"env"**. ![img](https://i.stack.imgur.com/LUP3s.png) Then install the jupyter notebook from there. It worked for me.
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > >...
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
It's more stable to create a kernel with an Anaconda virtualenv. Follow these steps. 1. Execute Anaconda prompt. 2. Type `conda create --name $ENVIRONMENT_NAME R -y` 3. Type `conda activate $ENVIRONMENT_NAME` 4. Type `python -m ipykernel install` 5. Type `ipython kernel install --user --name $ENVIRONMENT_NAME` Then,...
I had the same problem, I fixed in the way its say in Github: <https://github.com/jupyter/notebook/issues/4079> * open Anaconda Prompt typing ``` python -m ipykernel install --user ```
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > >...
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
It's more stable to create a kernel with an Anaconda virtualenv. Follow these steps. 1. Execute Anaconda prompt. 2. Type `conda create --name $ENVIRONMENT_NAME R -y` 3. Type `conda activate $ENVIRONMENT_NAME` 4. Type `python -m ipykernel install` 5. Type `ipython kernel install --user --name $ENVIRONMENT_NAME` Then,...
Check your environment variable `Path`! In the system variable `Path` add the following line > > C:\Users\\AppData\Roaming\Python\Python37\Scripts > > >
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > >...
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
It's more stable to create a kernel with an Anaconda virtualenv. Follow these steps. 1. Execute Anaconda prompt. 2. Type `conda create --name $ENVIRONMENT_NAME R -y` 3. Type `conda activate $ENVIRONMENT_NAME` 4. Type `python -m ipykernel install` 5. Type `ipython kernel install --user --name $ENVIRONMENT_NAME` Then,...
First Select your environment name. In my case it was **"env"**. ![img](https://i.stack.imgur.com/LUP3s.png) Then install the jupyter notebook from there. It worked for me.
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > >...
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
I had the same problem, I fixed in the way its say in Github: <https://github.com/jupyter/notebook/issues/4079> * open Anaconda Prompt typing ``` python -m ipykernel install --user ```
Check your environment variable `Path`! In the system variable `Path` add the following line > > C:\Users\\AppData\Roaming\Python\Python37\Scripts > > >
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > >...
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
First Select your environment name. In my case it was **"env"**. ![img](https://i.stack.imgur.com/LUP3s.png) Then install the jupyter notebook from there. It worked for me.
Check your environment variable `Path`! In the system variable `Path` add the following line > > C:\Users\\AppData\Roaming\Python\Python37\Scripts > > >
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I would use code like ``` path = "/Users/smcho/Desktop/bracket/[10,20]" replacements = {"[": "[[]", "]": "[]]"} new_path = "".join(replacements.get(c, c) for c in path) ```
``` import re path2 = re.sub(r'(\[|\])', r'[\1]', path1) ```
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I would use code like ``` path = "/Users/smcho/Desktop/bracket/[10,20]" replacements = {"[": "[[]", "]": "[]]"} new_path = "".join(replacements.get(c, c) for c in path) ```
X = TE$%ST C@"DE specialChars = "@#$%&" for specialChar in specialChars: ``` X = X.replace(specialChar, '') ``` Y = appname1.replace(" ", "") print(Y) TESTCODE
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I would use code like ``` path = "/Users/smcho/Desktop/bracket/[10,20]" replacements = {"[": "[[]", "]": "[]]"} new_path = "".join(replacements.get(c, c) for c in path) ```
There is also this generic python multiple replace recipe: [Single pass multiple replace](http://code.activestate.com/recipes/81330-single-pass-multiple-replace/)
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There is also this generic python multiple replace recipe: [Single pass multiple replace](http://code.activestate.com/recipes/81330-single-pass-multiple-replace/)
Or, to avoid regex, I would replace the opening bracket with a unique string, then replace the closing bracket and then replace the unique string - maybe a round about way, but to my mind it looks simpler - only a test would say if it is faster. Also, I'd tend to reuse the same name. i.e. ``` path1 = "/Users/smcho/De...
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
``` import re path2 = re.sub(r'(\[|])', r'[\1]', path) ``` Explanation: `\[|]` will match a bracket (opening or closing). Placing it in the parentheses will make it capture into a group. Then in the replacement string, `\1` will be substituted with the content of the group.
Or, to avoid regex, I would replace the opening bracket with a unique string, then replace the closing bracket and then replace the unique string - maybe a round about way, but to my mind it looks simpler - only a test would say if it is faster. Also, I'd tend to reuse the same name. i.e. ``` path1 = "/Users/smcho/De...
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
``` import re path2 = re.sub(r'(\[|])', r'[\1]', path) ``` Explanation: `\[|]` will match a bracket (opening or closing). Placing it in the parentheses will make it capture into a group. Then in the replacement string, `\1` will be substituted with the content of the group.
``` import re path2 = re.sub(r'(\[|\])', r'[\1]', path1) ```
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There is also this generic python multiple replace recipe: [Single pass multiple replace](http://code.activestate.com/recipes/81330-single-pass-multiple-replace/)
X = TE$%ST C@"DE specialChars = "@#$%&" for specialChar in specialChars: ``` X = X.replace(specialChar, '') ``` Y = appname1.replace(" ", "") print(Y) TESTCODE
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I would use code like ``` path = "/Users/smcho/Desktop/bracket/[10,20]" replacements = {"[": "[[]", "]": "[]]"} new_path = "".join(replacements.get(c, c) for c in path) ```
Or, to avoid regex, I would replace the opening bracket with a unique string, then replace the closing bracket and then replace the unique string - maybe a round about way, but to my mind it looks simpler - only a test would say if it is faster. Also, I'd tend to reuse the same name. i.e. ``` path1 = "/Users/smcho/De...
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
``` import re path2 = re.sub(r'(\[|])', r'[\1]', path) ``` Explanation: `\[|]` will match a bracket (opening or closing). Placing it in the parentheses will make it capture into a group. Then in the replacement string, `\1` will be substituted with the content of the group.
X = TE$%ST C@"DE specialChars = "@#$%&" for specialChar in specialChars: ``` X = X.replace(specialChar, '') ``` Y = appname1.replace(" ", "") print(Y) TESTCODE
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There is also this generic python multiple replace recipe: [Single pass multiple replace](http://code.activestate.com/recipes/81330-single-pass-multiple-replace/)
``` import re path2 = re.sub(r'(\[|\])', r'[\1]', path1) ```
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
[Faker](https://github.com/joke2k/faker "Faker") makes this easy ``` >>> from faker import Faker >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb >>> print(f1.uuid4()) a41f020c-2d4d-333f-f1d3-979f1043fae0 >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec74...
Simple solution based on the answer of @user10229295, with a comment about the seed. The Edit queue was full, so I opened a new answer: ``` import hashlib import uuid seed = 'Type your seed_string here' #Read comment below m = hashlib.md5() m.update(seed.encode('utf-8')) new_uuid = uuid.UUID(m.hexdigest()) ``` **C...
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
[Faker](https://github.com/joke2k/faker "Faker") makes this easy ``` >>> from faker import Faker >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb >>> print(f1.uuid4()) a41f020c-2d4d-333f-f1d3-979f1043fae0 >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec74...
Since the straight-forward solution hasn't been posted yet to generate consistent version 4 UUIDs: ```py import random import uuid rnd = random.Random() rnd.seed(123) # NOTE: Of course don't use a static seed in production random_uuid = uuid.UUID(int=rnd.getrandbits(128), version=4) ``` where you can see then: ``...
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
This is based on a solution used [here](https://github.com/ping/instagram_private_api): ``` import hashlib import uuid m = hashlib.md5() m.update(seed.encode('utf-8')) new_uuid = uuid.UUID(m.hexdigest()) ```
Gonna add this here if anyone needs to monkey patch in a seeded UUID. My code uses `uuid.uuid4()` but for testing I wanted consistent UUIDs. The following code is how I did that: ``` import uuid import random # ------------------------------------------- # Remove this block to generate different # UUIDs everytime you...
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
Almost there: ``` uuid.UUID(int=rd.getrandbits(128)) ``` This was determined with the help of `help`: ``` >>> help(uuid.UUID.__init__) Help on method __init__ in module uuid: __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None) unbound uuid.UUID method Create a UUID from eit...
Simple solution based on the answer of @user10229295, with a comment about the seed. The Edit queue was full, so I opened a new answer: ``` import hashlib import uuid seed = 'Type your seed_string here' #Read comment below m = hashlib.md5() m.update(seed.encode('utf-8')) new_uuid = uuid.UUID(m.hexdigest()) ``` **C...
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
Gonna add this here if anyone needs to monkey patch in a seeded UUID. My code uses `uuid.uuid4()` but for testing I wanted consistent UUIDs. The following code is how I did that: ``` import uuid import random # ------------------------------------------- # Remove this block to generate different # UUIDs everytime you...
Based on alex's solution, the following would provide a proper UUID4: ``` random.seed(123210912) a = "%32x" % random.getrandbits(128) rd = a[:12] + '4' + a[13:16] + 'a' + a[17:] uuid4 = uuid.UUID(rd) ```
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
[Faker](https://github.com/joke2k/faker "Faker") makes this easy ``` >>> from faker import Faker >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb >>> print(f1.uuid4()) a41f020c-2d4d-333f-f1d3-979f1043fae0 >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec74...
Gonna add this here if anyone needs to monkey patch in a seeded UUID. My code uses `uuid.uuid4()` but for testing I wanted consistent UUIDs. The following code is how I did that: ``` import uuid import random # ------------------------------------------- # Remove this block to generate different # UUIDs everytime you...
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
Almost there: ``` uuid.UUID(int=rd.getrandbits(128)) ``` This was determined with the help of `help`: ``` >>> help(uuid.UUID.__init__) Help on method __init__ in module uuid: __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None) unbound uuid.UUID method Create a UUID from eit...
Since the straight-forward solution hasn't been posted yet to generate consistent version 4 UUIDs: ```py import random import uuid rnd = random.Random() rnd.seed(123) # NOTE: Of course don't use a static seed in production random_uuid = uuid.UUID(int=rnd.getrandbits(128), version=4) ``` where you can see then: ``...
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
This is based on a solution used [here](https://github.com/ping/instagram_private_api): ``` import hashlib import uuid m = hashlib.md5() m.update(seed.encode('utf-8')) new_uuid = uuid.UUID(m.hexdigest()) ```
Since the straight-forward solution hasn't been posted yet to generate consistent version 4 UUIDs: ```py import random import uuid rnd = random.Random() rnd.seed(123) # NOTE: Of course don't use a static seed in production random_uuid = uuid.UUID(int=rnd.getrandbits(128), version=4) ``` where you can see then: ``...
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
Almost there: ``` uuid.UUID(int=rd.getrandbits(128)) ``` This was determined with the help of `help`: ``` >>> help(uuid.UUID.__init__) Help on method __init__ in module uuid: __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None) unbound uuid.UUID method Create a UUID from eit...
[Faker](https://github.com/joke2k/faker "Faker") makes this easy ``` >>> from faker import Faker >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb >>> print(f1.uuid4()) a41f020c-2d4d-333f-f1d3-979f1043fae0 >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec74...
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
Almost there: ``` uuid.UUID(int=rd.getrandbits(128)) ``` This was determined with the help of `help`: ``` >>> help(uuid.UUID.__init__) Help on method __init__ in module uuid: __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None) unbound uuid.UUID method Create a UUID from eit...
Based on alex's solution, the following would provide a proper UUID4: ``` random.seed(123210912) a = "%32x" % random.getrandbits(128) rd = a[:12] + '4' + a[13:16] + 'a' + a[17:] uuid4 = uuid.UUID(rd) ```
14,946,639
Say I have the following code: ``` if request.POST: id = request.POST.get('id') # block of code to use variable id do_work(id) do_other_work(id) ``` is there a shortcut (one line of code) that will test if it's request.POST for the conditional block and also assign variable id for the conditional block t...
2013/02/18
[ "https://Stackoverflow.com/questions/14946639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342553/" ]
No, you can't assign anything in an `if` test expression. If you didn't have the rest of the `if` block, ``` id = request.POST and request.POST.get('id') ``` would work. It doesn't make much sense, to do it, though, because `id = request.POST.get('id')` works just fine with empty `request.POST`. Please remember ...
I like this: ``` id = request.POST.get('id', False) if id is not False: # do something ```
66,534,294
I am using python 3.7 and have intalled IPython I am using ipython shell in django like ``` python manage.py shell_plus ``` and then ``` [1]: %load_ext autoreload [2]: %autoreload 2 ``` and then i am doing ``` [1]: from boiler.tasks import add [2]: add(1,2) "testing" ``` `change add function` ``` def add(x,y...
2021/03/08
[ "https://Stackoverflow.com/questions/66534294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2897115/" ]
> > Will this cause issues on the memory side? > > > Which side of what, and which side of it is the memory side? It may use more memory than necessary. > > What happens to that extra memory? > > > It remains unused. > > Does it have to be manually freed or is there a way to do it automatically? > > > ...
For your purposes, the memory allocator doesn't know, nor does it really care about how much memory you actually use in a block you malloc. The key here is to never use *more* memory than you malloc. The extra memory just sits there, available for your use if you want it. Note that allocating 10 bytes vs 4 bytes won't...
26,953,153
Beginner python coder here, keep things simple, please. So, I need this code below to scramble two letters without scrambling the first or last letters. Everything seems to work right up until the `scrambler()` function. ``` from random import randint def wordScramble(string): stringArray = string.split() fo...
2014/11/16
[ "https://Stackoverflow.com/questions/26953153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257122/" ]
If the labels 0, 100, 200 belong to one axis and the texts "Day One", ... to the other one you can set the colors of the labels of the first axis to transparent like this ``` axis.TextColor = OxyColors.Transparent; ``` Hope this helps.
If XAML use this ``` <oxy:Plot.Axes> <oxy:LinearAxis Position="Left" TextColor = OxyColors.Transparent/> </oxy:Plot.Axes> ``` If code ``` // Create a plot model PlotModel = new PlotModel { Title = "Updating by task running on the UI thread" }; // Add the axes, note that MinimumPadding and AbsoluteMinimum shoul...
18,782,584
How can I perform post processing on my SQL3 database via python? The following code doesn't work, but what I am trying to do is first create a new database if not exists already, then insert some data, and finally execute the query and close the connection. But I what to do so separately, so as to add additional funct...
2013/09/13
[ "https://Stackoverflow.com/questions/18782584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2295350/" ]
It would seem that FB has made some changes to its redirection script, when it detects a Windows Phone webbrowser control. What the C# SDK does, is generate the login page as "<http://www.facebook.com>....". When you open this URL on the webbrowser control, it gets redirected to "<http://m.facebook.com>..." which dis...
In my project I just listened for the WebView's navigated event. If it happens, it means that user did something on the login page (i.e. pressed login button). Then I parsed the uri of the page you mentioned which should contain OAuth callback url, if it is correct and the result is success I redirect manually to the c...
18,782,584
How can I perform post processing on my SQL3 database via python? The following code doesn't work, but what I am trying to do is first create a new database if not exists already, then insert some data, and finally execute the query and close the connection. But I what to do so separately, so as to add additional funct...
2013/09/13
[ "https://Stackoverflow.com/questions/18782584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2295350/" ]
It would seem that FB has made some changes to its redirection script, when it detects a Windows Phone webbrowser control. What the C# SDK does, is generate the login page as "<http://www.facebook.com>....". When you open this URL on the webbrowser control, it gets redirected to "<http://m.facebook.com>..." which dis...
Before trying to do all the proposed changes, please check that your Facebook App is not on Sandbox mode. This will eventually resolve your issue. ![enter image description here](https://i.stack.imgur.com/CElH5.png) If your facebook app is in sandbox mode, only the developer can login, using his email address. Any ot...
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
[Four spaces and no hard tabs](https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#whitespace-1), if you're a Pythonista.
``` 2 space 4 busy coder 3 space for heavy if statement using script kiddies 4 space for those who make real money pressing space 4 times 8 space for the man in ties and suit who doesn't need to code ```
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
[Four spaces and no hard tabs](https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#whitespace-1), if you're a Pythonista.
In the past I used 3 spaces. And that's still my preference. But 4 spaces seems to be the standard in the VB world. So I have switched to 4 to be in line with most code examples I see, and with the rest of my team.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
I like 8 spaces (I know, right?). It makes the start/ end of blocks really obvious. As to your question, a formal usability study would be required. Let's look at limits though: **0 spaces** ``` function test(){ var x = 1; for (i=0; i<=5; i++){ doSomething(); } } ``` No indentation is obviously bad. You can't tel...
I read that 2 spaces is actually optimal, based on a study where programmers were asked to estimate the level of nesting based on indentation, but that when asked, programmers thought 4 would be optimal. Citation needed, but can't find it.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
``` 2 space 4 busy coder 3 space for heavy if statement using script kiddies 4 space for those who make real money pressing space 4 times 8 space for the man in ties and suit who doesn't need to code ```
I read that 2 spaces is actually optimal, based on a study where programmers were asked to estimate the level of nesting based on indentation, but that when asked, programmers thought 4 would be optimal. Citation needed, but can't find it.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
No one have mentioned this so far so I feel I am obligated to post one. The choice of indent size (which I think what OP meant), affects not just how codes are indented but also affects how much code you can fit in a line and how they align. A development team needs to eventually come to some sort of agreement on the ...
I read that 2 spaces is actually optimal, based on a study where programmers were asked to estimate the level of nesting based on indentation, but that when asked, programmers thought 4 would be optimal. Citation needed, but can't find it.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
This discussion often involves misunderstandings, because ([as jwz describes](http://www.jwz.org/doc/tabs-vs-spaces.html)) it usually involves **three distinct issues**: * What happens when I press the `Tab` key in my text editor? * What happens when I request my editor to indent one or more lines? * What happens when...
Since you're using Python, you could, as said before, take python's style guide ([PEP 8](http://www.python.org/dev/peps/pep-0008/)) advice: > > Indentation > > > > ``` > Use 4 spaces per indentation level. > > ``` > > But the [Linux kernel CodingStyle](http://lxr.linux.no/linux+v2.6.29/Documentation/CodingStyl...
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
This discussion often involves misunderstandings, because ([as jwz describes](http://www.jwz.org/doc/tabs-vs-spaces.html)) it usually involves **three distinct issues**: * What happens when I press the `Tab` key in my text editor? * What happens when I request my editor to indent one or more lines? * What happens when...
I read that 2 spaces is actually optimal, based on a study where programmers were asked to estimate the level of nesting based on indentation, but that when asked, programmers thought 4 would be optimal. Citation needed, but can't find it.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
I like 8 spaces (I know, right?). It makes the start/ end of blocks really obvious. As to your question, a formal usability study would be required. Let's look at limits though: **0 spaces** ``` function test(){ var x = 1; for (i=0; i<=5; i++){ doSomething(); } } ``` No indentation is obviously bad. You can't tel...
The argument for tab over spaces is that it allows each person to customize their editor to see whatever level of indentation they want. The argument against tabs is that it's difficult to spot (for the writer) when they've mixed tabs and spaces. Occasionally you will want lines that aren't indented to a tab stop, whic...
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
[Four spaces and no hard tabs](https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#whitespace-1), if you're a Pythonista.
I read that 2 spaces is actually optimal, based on a study where programmers were asked to estimate the level of nesting based on indentation, but that when asked, programmers thought 4 would be optimal. Citation needed, but can't find it.
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
I think I recall that there is a section about indentation in [Code Complete](https://rads.stackoverflow.com/amzn/click/com/0735619670), quoting some studies about which level of identation makes the code most readable, but I do not have a copy of it with me right now, so I can't check it.
I've always used one tab as two spaces.
32,309,177
How do we do a DNS query, expecially MX query, in Python by not installing any third party libs. I want to query the MX record about a domain, however, it seems that `socket.getaddrinfo` can only query the A record. I have tried this: ``` python -c "import socket; print socket.getaddrinfo('baidu.com', 25, socket.AF_...
2015/08/31
[ "https://Stackoverflow.com/questions/32309177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1889327/" ]
Here's some rough low-level code for making a dns request using just the standard library if anyone's interested. ``` import secrets import socket # https://datatracker.ietf.org/doc/html/rfc1035 # https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#table-dns-parameters-4 def dns_request(name, qtype=...
First Install dnspython ``` import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', rdata.preference ```
38,414,650
I've recently found this page: [Making PyObject\_HEAD conform to standard C](https://www.python.org/dev/peps/pep-3123/) and I'm curious about this paragraph: > > Standard C has one specific exception to its aliasing rules precisely designed to support the case of Python: a value of a struct type may also be access...
2016/07/16
[ "https://Stackoverflow.com/questions/38414650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5960237/" ]
Your interpretation1 is correct, but the code isn't. The pointer `i` already points to the object, and thus to the first element, so you only need to cast it to the correct type: ``` int* n = ( int* )i; ``` then you simply dereference it: ``` *n = 345; ``` Or in one step: ``` *( int* )i = 345; ``` --- 1 (Quo...
You have a few issues, but this works for me: ``` #include <malloc.h> #include <stdio.h> struct with_int { int a; char b; }; int main(void) { struct with_int *i = (struct with_int *)malloc(sizeof(struct with_int)); i->a = 5; *(int *)i = 8; printf("%d\n", i->a); } ``` Output is: 8
38,414,650
I've recently found this page: [Making PyObject\_HEAD conform to standard C](https://www.python.org/dev/peps/pep-3123/) and I'm curious about this paragraph: > > Standard C has one specific exception to its aliasing rules precisely designed to support the case of Python: a value of a struct type may also be access...
2016/07/16
[ "https://Stackoverflow.com/questions/38414650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5960237/" ]
You have a few issues, but this works for me: ``` #include <malloc.h> #include <stdio.h> struct with_int { int a; char b; }; int main(void) { struct with_int *i = (struct with_int *)malloc(sizeof(struct with_int)); i->a = 5; *(int *)i = 8; printf("%d\n", i->a); } ``` Output is: 8
Like other answers have pointed out, I think you meant: ``` // Interpret (struct with_int *) as (int *), then // dereference it to assign the value 8. *((int *) i) = 8; ``` and not: ``` ((int *) &i)->a = 8; ``` However, none of the answers explain specifically why that error makes sense. Let me explain what `((i...
38,414,650
I've recently found this page: [Making PyObject\_HEAD conform to standard C](https://www.python.org/dev/peps/pep-3123/) and I'm curious about this paragraph: > > Standard C has one specific exception to its aliasing rules precisely designed to support the case of Python: a value of a struct type may also be access...
2016/07/16
[ "https://Stackoverflow.com/questions/38414650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5960237/" ]
Your interpretation1 is correct, but the code isn't. The pointer `i` already points to the object, and thus to the first element, so you only need to cast it to the correct type: ``` int* n = ( int* )i; ``` then you simply dereference it: ``` *n = 345; ``` Or in one step: ``` *( int* )i = 345; ``` --- 1 (Quo...
Like other answers have pointed out, I think you meant: ``` // Interpret (struct with_int *) as (int *), then // dereference it to assign the value 8. *((int *) i) = 8; ``` and not: ``` ((int *) &i)->a = 8; ``` However, none of the answers explain specifically why that error makes sense. Let me explain what `((i...
65,521,446
When typing a word in a dash input I would like to get autosuggestions, an example of what I mean is this CLI app I made in the past. [![enter image description here](https://i.stack.imgur.com/SPzmM.png)](https://i.stack.imgur.com/SPzmM.png) a link to the documentation: <https://python-prompt-toolkit.readthedocs.io/e...
2020/12/31
[ "https://Stackoverflow.com/questions/65521446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14008858/" ]
`:` is missing after the third `while` statement, also `except` and `print` statements have the same indentation level. You can use `try-except` without additional `while` loop, check if the input number is less then `11` and append the input the the list and if not break the while loop. ***Example***: ``` while Tru...
flows answered your question appropriately. Because I think you would like to ask for pairs of name and grade, I modified your program a little. ``` def student_data(): student_list = [] while True: # Ask for the name of the student student_name = input("Please enter the student name, press ...
67,655,396
I'm trying to migrate my custom user model and I run makemigrations command to make migrations for new models. But when I run migrate command it throws this error : > > conn = \_connect(dsn, connection\_factory=connection\_factory, > \*\*kwasync) django.db.utils.OperationalError > > > **Trace back:** ``` (ve...
2021/05/23
[ "https://Stackoverflow.com/questions/67655396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14472949/" ]
> > I'm trying to understand Linux OS library dependencies to effectively run python 3.9 and imported pip packages to work. > > > Your questions may have pretty broad answers and depend on a bunch of input factors you haven't mentioned. > > Is there a requirement for GCC to be installed for pip modules with c ex...
Python depends on compilers and a lot of other tools if you're going to compile the source (from the repository). This is from the offical repository, telling you what you need to compile it from source, [check it out](https://devguide.python.org/setup/#install-dependencies). > > **1.4. Install dependencies** > This ...
51,346,677
``` ERROR: build step 1 "gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02" failed: exit status 1 ERROR Finished Step #1 - "builder" Step #1 - "builder": Permission denied for "be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea" from request "/v2/PROJECT_ID/app-engine-build-cache/node-cache/m...
2018/07/15
[ "https://Stackoverflow.com/questions/51346677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8025518/" ]
> > ### Troubleshooting > > > If you find 403 (access denied) errors in your build logs, try the following steps: > > > Disable the Cloud Build API and re-enable it. Doing so should give your service account access to your project again. > > > Fixed an issue for me.
It shows in the 1st few lines of the log that image couldnt be pulled from registry due to unauthorized user credentials accessing the registry. Did you check the credentials? If you have a token based login, check if the token is not expired.
51,346,677
``` ERROR: build step 1 "gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02" failed: exit status 1 ERROR Finished Step #1 - "builder" Step #1 - "builder": Permission denied for "be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea" from request "/v2/PROJECT_ID/app-engine-build-cache/node-cache/m...
2018/07/15
[ "https://Stackoverflow.com/questions/51346677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8025518/" ]
Its a weird error, because it just says permission denied in logs. In my case Actual reason was unpaid bills, which keeps **Cloud Build API** enabled just for suspense but actually deployment doesn't work. So do these steps 1. Pay your bills if there is any pending, in short your Payment Method has to be active in `B...
It shows in the 1st few lines of the log that image couldnt be pulled from registry due to unauthorized user credentials accessing the registry. Did you check the credentials? If you have a token based login, check if the token is not expired.
51,346,677
``` ERROR: build step 1 "gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02" failed: exit status 1 ERROR Finished Step #1 - "builder" Step #1 - "builder": Permission denied for "be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea" from request "/v2/PROJECT_ID/app-engine-build-cache/node-cache/m...
2018/07/15
[ "https://Stackoverflow.com/questions/51346677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8025518/" ]
> > ### Troubleshooting > > > If you find 403 (access denied) errors in your build logs, try the following steps: > > > Disable the Cloud Build API and re-enable it. Doing so should give your service account access to your project again. > > > Fixed an issue for me.
Its a weird error, because it just says permission denied in logs. In my case Actual reason was unpaid bills, which keeps **Cloud Build API** enabled just for suspense but actually deployment doesn't work. So do these steps 1. Pay your bills if there is any pending, in short your Payment Method has to be active in `B...
45,417,077
I've got a module called `core`, which contains a number of python files. If I do: ``` from core.curve import Curve ``` Does `__init__.py` get called? Can I move import statements that apply to all core files into `__init__.py` to save repeating myself? What **should** go into `__init__.py`?
2017/07/31
[ "https://Stackoverflow.com/questions/45417077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222151/" ]
> > Is \_\_init\_\_.py run everytime I import anything from that module? > > > According to [docs](https://docs.python.org/2/tutorial/modules.html#importing-from-a-package) in most cases **yes**, it is.
You can add all your functions that you want to use in your directory ``` - core - __init__.py ``` in this `__init__.py` add your class and function references like ``` from .curve import Curve from .some import SomethingElse ``` and where you want to User your class just refer it like ``` from core import Cu...
45,417,077
I've got a module called `core`, which contains a number of python files. If I do: ``` from core.curve import Curve ``` Does `__init__.py` get called? Can I move import statements that apply to all core files into `__init__.py` to save repeating myself? What **should** go into `__init__.py`?
2017/07/31
[ "https://Stackoverflow.com/questions/45417077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222151/" ]
> > I've got a module called core, which contains a number of python files. > > > if it contains python files, it's not a module, it's a directory containing python files - and eventually a package if it contains an `__init__.py` file. > > If I do: `from core.curve import Curve` does `__init__.py` get called? > ...
> > Is \_\_init\_\_.py run everytime I import anything from that module? > > > According to [docs](https://docs.python.org/2/tutorial/modules.html#importing-from-a-package) in most cases **yes**, it is.
45,417,077
I've got a module called `core`, which contains a number of python files. If I do: ``` from core.curve import Curve ``` Does `__init__.py` get called? Can I move import statements that apply to all core files into `__init__.py` to save repeating myself? What **should** go into `__init__.py`?
2017/07/31
[ "https://Stackoverflow.com/questions/45417077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222151/" ]
> > I've got a module called core, which contains a number of python files. > > > if it contains python files, it's not a module, it's a directory containing python files - and eventually a package if it contains an `__init__.py` file. > > If I do: `from core.curve import Curve` does `__init__.py` get called? > ...
You can add all your functions that you want to use in your directory ``` - core - __init__.py ``` in this `__init__.py` add your class and function references like ``` from .curve import Curve from .some import SomethingElse ``` and where you want to User your class just refer it like ``` from core import Cu...