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
576,557
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)? --- Remarkably similar to: [If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/41...
2009/02/23
[ "https://Stackoverflow.com/questions/576557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69746/" ]
No, 3.x is largely incompatible with 2.x (that was actually a major motivation for doing it). In fact, you probably shouldn't be using 3.0 at all-- it's rather unusable at the moment, and is still mostly intended for library developers to port to it so that it can be usable.
In most cases it's not required anymore learn to Python 2 along with Python 3 for the following reasons. 1. Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained, and dedicating effort to learning it doesn't make sense anymore for most people. Als...
576,557
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)? --- Remarkably similar to: [If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/41...
2009/02/23
[ "https://Stackoverflow.com/questions/576557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69746/" ]
Python 2.6 and Python 3.0 are *very* compatible with each other. There honestly aren't very many differences between the two. At this point, third-party library support is far better for the 2.x series (last I checked, a few libraries I use hadn't been updated from 2.5, but going from 2.5 to 2.6 is just a recompile, bu...
NO. Python 3 code is backwards incompatible with 2.6. I recommend to begin with 2.6, because your code will be more **useful**.
576,557
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)? --- Remarkably similar to: [If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/41...
2009/02/23
[ "https://Stackoverflow.com/questions/576557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69746/" ]
It would be easier to use 2.6 right now because most external libraries are not compatible with 3 yet.
NO. Python 3 code is backwards incompatible with 2.6. I recommend to begin with 2.6, because your code will be more **useful**.
576,557
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)? --- Remarkably similar to: [If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/41...
2009/02/23
[ "https://Stackoverflow.com/questions/576557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69746/" ]
NO. Python 3 code is backwards incompatible with 2.6. I recommend to begin with 2.6, because your code will be more **useful**.
In most cases it's not required anymore learn to Python 2 along with Python 3 for the following reasons. 1. Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained, and dedicating effort to learning it doesn't make sense anymore for most people. Als...
576,557
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)? --- Remarkably similar to: [If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/41...
2009/02/23
[ "https://Stackoverflow.com/questions/576557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69746/" ]
Python 2.6 and Python 3.0 are *very* compatible with each other. There honestly aren't very many differences between the two. At this point, third-party library support is far better for the 2.x series (last I checked, a few libraries I use hadn't been updated from 2.5, but going from 2.5 to 2.6 is just a recompile, bu...
It would be easier to use 2.6 right now because most external libraries are not compatible with 3 yet.
576,557
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)? --- Remarkably similar to: [If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/41...
2009/02/23
[ "https://Stackoverflow.com/questions/576557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69746/" ]
Python 2.6 and Python 3.0 are *very* compatible with each other. There honestly aren't very many differences between the two. At this point, third-party library support is far better for the 2.x series (last I checked, a few libraries I use hadn't been updated from 2.5, but going from 2.5 to 2.6 is just a recompile, bu...
In most cases it's not required anymore learn to Python 2 along with Python 3 for the following reasons. 1. Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained, and dedicating effort to learning it doesn't make sense anymore for most people. Als...
576,557
If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)? --- Remarkably similar to: [If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?](https://stackoverflow.com/questions/410609/if-im-going-to-learn-python-should-i-learn-2-x-or-just-jump-into-3-0/41...
2009/02/23
[ "https://Stackoverflow.com/questions/576557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69746/" ]
It would be easier to use 2.6 right now because most external libraries are not compatible with 3 yet.
In most cases it's not required anymore learn to Python 2 along with Python 3 for the following reasons. 1. Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained, and dedicating effort to learning it doesn't make sense anymore for most people. Als...
70,168,761
I am trying to click on a check box. Below is the HTML Code ``` <div class="mb-1 p-3 termsCheck"> <input class="form-check-input float-end" type="checkbox" value="" id="flexCheckDefault" required=""> <label class="form-check-label float-end" for="flexCheckDefault"><span> Agree to Terms ...
2021/11/30
[ "https://Stackoverflow.com/questions/70168761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13572791/" ]
`max_func` should return a function that takes an argument (`x`), applies it to `f` and `g` and then return the maximal value: ``` def max_func(f, g): def mf(x): return max(f(x), g(x)) return mf ```
In your code, you are calling only f(x) in both if and else statement. You can try: ``` def max_func(f,g): if f(x)> g(x): return f(x) else: return g(x) def new_function (x:int): -> int return new_function ```
70,168,761
I am trying to click on a check box. Below is the HTML Code ``` <div class="mb-1 p-3 termsCheck"> <input class="form-check-input float-end" type="checkbox" value="" id="flexCheckDefault" required=""> <label class="form-check-label float-end" for="flexCheckDefault"><span> Agree to Terms ...
2021/11/30
[ "https://Stackoverflow.com/questions/70168761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13572791/" ]
`max_func` should return a function that takes an argument (`x`), applies it to `f` and `g` and then return the maximal value: ``` def max_func(f, g): def mf(x): return max(f(x), g(x)) return mf ```
High order functional programming can get real weird real quickly. Since this seems to be a homework exercise, I won't give you the straight answer, but consider this: ```py def make_function_print_arg(f): def new_function(x): print(f"Calling function with {x}") return f(x) return new_function ``` This d...
70,168,761
I am trying to click on a check box. Below is the HTML Code ``` <div class="mb-1 p-3 termsCheck"> <input class="form-check-input float-end" type="checkbox" value="" id="flexCheckDefault" required=""> <label class="form-check-label float-end" for="flexCheckDefault"><span> Agree to Terms ...
2021/11/30
[ "https://Stackoverflow.com/questions/70168761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13572791/" ]
High order functional programming can get real weird real quickly. Since this seems to be a homework exercise, I won't give you the straight answer, but consider this: ```py def make_function_print_arg(f): def new_function(x): print(f"Calling function with {x}") return f(x) return new_function ``` This d...
In your code, you are calling only f(x) in both if and else statement. You can try: ``` def max_func(f,g): if f(x)> g(x): return f(x) else: return g(x) def new_function (x:int): -> int return new_function ```
41,950,021
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists. I'm using `Python3`. My code: ``` players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] vote = 0 cont = 0 while(vote >= 0 and vote <23): vote = input(...
2017/01/31
[ "https://Stackoverflow.com/questions/41950021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7493136/" ]
Change ``` vote = input('Enter the name of the player you wish to vote for') ``` to ``` vote = int(input('Enter the name of the player you wish to vote for')) ``` You are getting the input from the console as a string, so you must cast that input string to an `int` object in order to do numerical operations.
When you use the input function it automatically turns it into a string. You need to go: ``` vote = int(input('Enter the name of the player you wish to vote for')) ``` which turns the input into a int type value
41,950,021
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists. I'm using `Python3`. My code: ``` players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] vote = 0 cont = 0 while(vote >= 0 and vote <23): vote = input(...
2017/01/31
[ "https://Stackoverflow.com/questions/41950021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7493136/" ]
Change ``` vote = input('Enter the name of the player you wish to vote for') ``` to ``` vote = int(input('Enter the name of the player you wish to vote for')) ``` You are getting the input from the console as a string, so you must cast that input string to an `int` object in order to do numerical operations.
If you're using Python3.x `input` will return a string,so you should use `int` method to convert string to integer. [Python3 Input](https://docs.python.org/3/library/functions.html#input) > > If the prompt argument is present, it is written to standard output > without a trailing newline. The function then reads a ...
41,950,021
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists. I'm using `Python3`. My code: ``` players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] vote = 0 cont = 0 while(vote >= 0 and vote <23): vote = input(...
2017/01/31
[ "https://Stackoverflow.com/questions/41950021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7493136/" ]
Change ``` vote = input('Enter the name of the player you wish to vote for') ``` to ``` vote = int(input('Enter the name of the player you wish to vote for')) ``` You are getting the input from the console as a string, so you must cast that input string to an `int` object in order to do numerical operations.
`input()` by default takes the input in form of strings. ``` if (0<= vote <=24): ``` vote takes a string input (suppose `4`,`5`,etc) and becomes uncomparable. The correct way is: `vote = int(input("Enter your message")`will convert the input to integer (`4` to 4 or `5` to 5 depending on the input)
41,950,021
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists. I'm using `Python3`. My code: ``` players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] vote = 0 cont = 0 while(vote >= 0 and vote <23): vote = input(...
2017/01/31
[ "https://Stackoverflow.com/questions/41950021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7493136/" ]
If you're using Python3.x `input` will return a string,so you should use `int` method to convert string to integer. [Python3 Input](https://docs.python.org/3/library/functions.html#input) > > If the prompt argument is present, it is written to standard output > without a trailing newline. The function then reads a ...
When you use the input function it automatically turns it into a string. You need to go: ``` vote = int(input('Enter the name of the player you wish to vote for')) ``` which turns the input into a int type value
41,950,021
I'm learning python and working on exercises. One of them is to code a voting system to select the best player between 23 players of the match using lists. I'm using `Python3`. My code: ``` players= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] vote = 0 cont = 0 while(vote >= 0 and vote <23): vote = input(...
2017/01/31
[ "https://Stackoverflow.com/questions/41950021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7493136/" ]
If you're using Python3.x `input` will return a string,so you should use `int` method to convert string to integer. [Python3 Input](https://docs.python.org/3/library/functions.html#input) > > If the prompt argument is present, it is written to standard output > without a trailing newline. The function then reads a ...
`input()` by default takes the input in form of strings. ``` if (0<= vote <=24): ``` vote takes a string input (suppose `4`,`5`,etc) and becomes uncomparable. The correct way is: `vote = int(input("Enter your message")`will convert the input to integer (`4` to 4 or `5` to 5 depending on the input)
41,908,655
i need to create a dataframe containing tuples from a series of dataframes arrays. What I need is the following: I have dataframes `a` and `b`: ``` a = pd.DataFrame(np.array([[1, 2],[3, 4]]), columns=['one', 'two']) b = pd.DataFrame(np.array([[5, 6],[7, 8]]), columns=['one', 'two']) a: one two 0 1 2 1 3...
2017/01/28
[ "https://Stackoverflow.com/questions/41908655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6316272/" ]
you can use `numpy.rec.fromarrays((a.values, b.values)).tolist()`: ``` In [34]: pd.DataFrame(np.rec.fromarrays((a.values, b.values)).tolist(), columns=a.columns, index=a.index) Out[34]: one two 0 (1, 5) (2, 6) 1 (3, 7) (4, 8) ``` merging three DF's: ``` In ...
You could use `zip` over columns of `a`, `b` ``` In [31]: pd.DataFrame({x: zip(a[x], b[x]) for x in a.columns}) Out[31]: one two 0 (1, 5) (2, 6) 1 (3, 7) (4, 8) ```
68,767,995
I have a string like this: ``` txt = ''' lea_po () { val : 96.9; wh : "CP D "; related : DD; leak () { va : 0.008; when : " SI"; in : V; } **stagestat (" E I P", "I 2 ") { data : " H H/L - R : - - - : L - - , \ - : - - - : L - - , \ - - - ...
2021/08/13
[ "https://Stackoverflow.com/questions/68767995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13699970/" ]
* Make sure you have `Unicode True` at the start of your script. * Make sure you save your script as UTF-8 BOM or UTF-16LE BOM. * !include nsDialogs before commctrl.nsh * Make sure you are using the Unicode version of all plug-ins. Characters that "look Chinese" is a symptom of treating ASCII as UTF-16. Strings cut of...
Have you tried to add command "unicode True" at the top of the script?
47,344,625
content of my python file ``` class myclass(object): def __init__(self): pass def myfun(self): pass print ("hello world") ``` Output on executing file ``` hello world ``` Query ``` since I did not create object of class . How's it still able to print "hello world" ```
2017/11/17
[ "https://Stackoverflow.com/questions/47344625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3812837/" ]
The class body executes at class definition time, and that's how the language is designed. From section [9.3.1 Class Definition](https://docs.python.org/3/tutorial/classes.html#class-definition-syntax) syntax: > > In practice, the statements inside a class definition will usually be function definitions, but other ...
It will get a call, as python work like that. Your code will always return output. **hello world** ``` class myclass(object): def __init__(self): pass def myfun(self): print("hello world") pass ``` If you want to avoid it you have to add print statement inside the method.
54,005,909
I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on. I want to loop through the list and score as follow...
2019/01/02
[ "https://Stackoverflow.com/questions/54005909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903663/" ]
List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object. > > Note there are a few minor mistakes in listings below - to make sure > I'm not solving someone's homework for free. I also realize this is > not the most efficient way of doing so....
The main problem with your code is, that the loop is one short, you have 7 entries. Then you should convert the numbers to `int`, so that the comparison is correct. In your code, you get for ties 0 points. Instead of having a list, with flattend pairs, you should use tuple pairs. ``` ns_list = [] for row in arr["hits"...
54,005,909
I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on. I want to loop through the list and score as follow...
2019/01/02
[ "https://Stackoverflow.com/questions/54005909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903663/" ]
List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object. > > Note there are a few minor mistakes in listings below - to make sure > I'm not solving someone's homework for free. I also realize this is > not the most efficient way of doing so....
So we can do it like so: ``` import itertools d = [(i['_source']['nsp'], i['_source']['nsscore']) for i in arr['hits']['hits']] d [('2', '430'), ('3', '420'), ('4', '460'), ('5', '400'), ('7', '0'), ('1', '430'), ('6', '480')] c = itertools.combinations(d, 2) counts = {} for tup in c: p1, p2 = tup i...
54,005,909
I am attempting to create a contract bridge match point scoring system. In the list below the 1st, 3rd, etc. numbers are the pair numbers (players) and the 2nd, 4th etc. numbers are the scores achieved by each pair. So pair 2 scored 430, pair 3 scored 420 and so on. I want to loop through the list and score as follow...
2019/01/02
[ "https://Stackoverflow.com/questions/54005909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1903663/" ]
List appears to be a poor data structure for this, I think you are making everything worse by flattening your elasticsearch object. > > Note there are a few minor mistakes in listings below - to make sure > I'm not solving someone's homework for free. I also realize this is > not the most efficient way of doing so....
I first convert the list of your score to a dictionary object using itertools, then iterating through each key, and for each key, compare the values available in the list and add accordingly the score you provided and since in this approach you will always add the value 1 because you will always compare it with itself...
50,159,438
I tried reproducing some of the examples described [here](https://www.boost.org/doc/libs/1_63_0/libs/python/doc/html/numpy/tutorial/ndarray.html), but I experience the following problem with the code below, which was written by just copy-pasting relevant parts of the linked page. ``` #include <boost/python.hpp> #inclu...
2018/05/03
[ "https://Stackoverflow.com/questions/50159438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7141288/" ]
This week I had the same issue. To solve my problem I use dynamic memory: ``` np::ndarray test(){ int *data = malloc(sizeof(int) * 5); for (int i=0; i < 5; ++i){ data[i] = i + 1; } p::tuple shape = p::make_tuple(5); p::tuple stride = p::make_tuple(sizeof(int)); p::object own; np::dt...
Creating a new reference to the array before returning it solved the problem. Good news is that `np::ndarray` has a [`copy()`](https://github.com/boostorg/python/blob/4f6d547c0af4c400dc5d059ccd847426ff21852f/src/numpy/ndarray.cpp#L177) method that achieves exactly the same thing. Thus, you should add ``` np::ndarray n...
70,042,756
I'm running a python code to calculate the distance between certain coordinates. The original data looks like: ``` a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude ``` and I'm looking forward to get the distance between every pair, the result should look like: ``` [1, 2, 100(km)] [1, 3, 200...
2021/11/20
[ "https://Stackoverflow.com/questions/70042756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17454717/" ]
1- run : ``` php artisan make:middleware AccountType ``` 2- Add it to the *routeMiddleware* array in your kernel file by opening `app/Http/Kernel.php`: ``` 'accType' => \App\Http\Middleware\AccountType::class, ``` 3- Edit `AccountType` file: ``` public function handle($request, Closure $next) { // If user accou...
If your want to have a multi authenticate system, whit different logics, its better to implement multiple guard and define them in your desire models : ``` [...] 'guards' => [ [...] 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'writer' => [ 'driver' => 'session...
70,042,756
I'm running a python code to calculate the distance between certain coordinates. The original data looks like: ``` a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude ``` and I'm looking forward to get the distance between every pair, the result should look like: ``` [1, 2, 100(km)] [1, 3, 200...
2021/11/20
[ "https://Stackoverflow.com/questions/70042756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17454717/" ]
In addition to the solution given by @nagidi, you can update the `middleware` handle condition to check either `account_type` is profile or business. ``` public function handle($request, Closure $next, $type) { if (Auth::user() && Auth::user()->account_type == $type) { return $next($request); ...
1- run : ``` php artisan make:middleware AccountType ``` 2- Add it to the *routeMiddleware* array in your kernel file by opening `app/Http/Kernel.php`: ``` 'accType' => \App\Http\Middleware\AccountType::class, ``` 3- Edit `AccountType` file: ``` public function handle($request, Closure $next) { // If user accou...
70,042,756
I'm running a python code to calculate the distance between certain coordinates. The original data looks like: ``` a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude ``` and I'm looking forward to get the distance between every pair, the result should look like: ``` [1, 2, 100(km)] [1, 3, 200...
2021/11/20
[ "https://Stackoverflow.com/questions/70042756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17454717/" ]
1- run : ``` php artisan make:middleware AccountType ``` 2- Add it to the *routeMiddleware* array in your kernel file by opening `app/Http/Kernel.php`: ``` 'accType' => \App\Http\Middleware\AccountType::class, ``` 3- Edit `AccountType` file: ``` public function handle($request, Closure $next) { // If user accou...
**How to create your own middleware for multi User Role in Laravel** Let assumed your roles array could be `["admin","student","staff"];` Create a middleware role checking for the role "admin". Repeat steps 1-4 for each role. I found this much easier for myself, others may have their own approaches **Step 1** Run a...
70,042,756
I'm running a python code to calculate the distance between certain coordinates. The original data looks like: ``` a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude ``` and I'm looking forward to get the distance between every pair, the result should look like: ``` [1, 2, 100(km)] [1, 3, 200...
2021/11/20
[ "https://Stackoverflow.com/questions/70042756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17454717/" ]
In addition to the solution given by @nagidi, you can update the `middleware` handle condition to check either `account_type` is profile or business. ``` public function handle($request, Closure $next, $type) { if (Auth::user() && Auth::user()->account_type == $type) { return $next($request); ...
If your want to have a multi authenticate system, whit different logics, its better to implement multiple guard and define them in your desire models : ``` [...] 'guards' => [ [...] 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'writer' => [ 'driver' => 'session...
70,042,756
I'm running a python code to calculate the distance between certain coordinates. The original data looks like: ``` a = np.array([[1,40,70],[2,41,71],[3,42,73]]) #id, latitude, longitude ``` and I'm looking forward to get the distance between every pair, the result should look like: ``` [1, 2, 100(km)] [1, 3, 200...
2021/11/20
[ "https://Stackoverflow.com/questions/70042756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17454717/" ]
In addition to the solution given by @nagidi, you can update the `middleware` handle condition to check either `account_type` is profile or business. ``` public function handle($request, Closure $next, $type) { if (Auth::user() && Auth::user()->account_type == $type) { return $next($request); ...
**How to create your own middleware for multi User Role in Laravel** Let assumed your roles array could be `["admin","student","staff"];` Create a middleware role checking for the role "admin". Repeat steps 1-4 for each role. I found this much easier for myself, others may have their own approaches **Step 1** Run a...
47,845,358
Given a string, find the rank of the string amongst its permutations sorted lexicographically. Note that the characters might be repeated. If the characters are repeated, we need to look at the rank in unique permutations. Look at the example for more details. Input : 'aba' Output : 2 The order permutations with ...
2017/12/16
[ "https://Stackoverflow.com/questions/47845358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7549959/" ]
``` long long int pow_mod(long long int a,long long int b) { long long MOD=1000003; if(a == 1) return 1; long long int x =1 ,y = a; while(b>0) { if(b%2) { x = (x*y)%MOD; } y = (y*y)%MOD; b = b>>1; } return x; } int Solution::findRank(s...
You could generate the permutations, sort them, and find your original string: ``` from itertools import permutations def permutation_index(s): return sorted(''.join(x) for x in permutations(s)).index(s) ```
20,048,001
``` f = open('file.txt') print f.read() ``` That was pretty straight forward wasn't it? That works because python knows how to read and write`.txt` files. How do these formats even work? I wish to build a python program to read atleast the major formats of documents (including pdfs), spreadsheets and presentations. ...
2013/11/18
[ "https://Stackoverflow.com/questions/20048001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2672265/" ]
No, you have completely misunderstood what your code is doing. Python doesn't "know" how to read .txt files, because there is no "format" here. It is just opening a plain file and printing out the bytes it finds there. Something like PDF or DOC is completely different. The bytes by themselves do not mean anything: the...
You will need to look up the specification for each format you want to deal with, [this](http://www.idpf.org/epub/301/spec/epub-overview.html) is the specification for ePub for example, it's a bit broad but you get the idea, then you need figure out yourself how you want to deal with it.
20,048,001
``` f = open('file.txt') print f.read() ``` That was pretty straight forward wasn't it? That works because python knows how to read and write`.txt` files. How do these formats even work? I wish to build a python program to read atleast the major formats of documents (including pdfs), spreadsheets and presentations. ...
2013/11/18
[ "https://Stackoverflow.com/questions/20048001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2672265/" ]
No, you have completely misunderstood what your code is doing. Python doesn't "know" how to read .txt files, because there is no "format" here. It is just opening a plain file and printing out the bytes it finds there. Something like PDF or DOC is completely different. The bytes by themselves do not mean anything: the...
There is absolutely no magic involved in reading a `.txt` fileโ€”it's just ASCII bytes, and opening and reading a file does just that: reads bytes. It's the simplest possible file format you could ever find (because there is no format). PDF is to plain Plain Text what Coca Cola is to distilled water. PDFs however have a...
13,536,350
On using this regular expression in python : `pathstring = '<span class="titletext">(.*)</span>'` `pathFinderTitle = re.compile(pathstring)` My output is: ``` Govt has nothing to do with former CAG official RP Singh: Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper"> <table class="al-attribu...
2012/11/23
[ "https://Stackoverflow.com/questions/13536350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733583/" ]
`.*` is a *greedy* match of any characters; it is going to consume as many characters as possible. Instead, use the non-greedy version `.*?`, as in ``` pathstring = '<span class="titletext">(.*?)</span>' ```
`.*` will match `</span>` so it keeps on going until the last one. The best answer is: Don't parse html with regular expressions. Use the [lxml](http://lxml.de/installation.html) library (or something similar). ``` from lxml import html html_string = '<blah>' tree = html.fromstring(html_string) titles = tree.xpath("...
13,536,350
On using this regular expression in python : `pathstring = '<span class="titletext">(.*)</span>'` `pathFinderTitle = re.compile(pathstring)` My output is: ``` Govt has nothing to do with former CAG official RP Singh: Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper"> <table class="al-attribu...
2012/11/23
[ "https://Stackoverflow.com/questions/13536350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733583/" ]
`.*` is a *greedy* match of any characters; it is going to consume as many characters as possible. Instead, use the non-greedy version `.*?`, as in ``` pathstring = '<span class="titletext">(.*?)</span>' ```
You could also just as easily use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) which is great for doing this kind of thing. ``` #using BeautifulSoup4, install by "pip install BeautifulSoup4" from bs4 import BeautifulSoup soup = BeautifulSoup(html) result = soup.find('span', 'titletext') ``` And the...
13,536,350
On using this regular expression in python : `pathstring = '<span class="titletext">(.*)</span>'` `pathFinderTitle = re.compile(pathstring)` My output is: ``` Govt has nothing to do with former CAG official RP Singh: Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper"> <table class="al-attribu...
2012/11/23
[ "https://Stackoverflow.com/questions/13536350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733583/" ]
I would suggest using [pyquery](http://pypi.python.org/pypi/pyquery) instead of going mad on regular expressions... It's based on lxml and makes HTML parsing easy as using jQuery. Something like this is everything you need: ``` doc = PyQuery(html) doc('span.titletext').text() ``` You could also use [beautifulsoup](...
`.*` will match `</span>` so it keeps on going until the last one. The best answer is: Don't parse html with regular expressions. Use the [lxml](http://lxml.de/installation.html) library (or something similar). ``` from lxml import html html_string = '<blah>' tree = html.fromstring(html_string) titles = tree.xpath("...
13,536,350
On using this regular expression in python : `pathstring = '<span class="titletext">(.*)</span>'` `pathFinderTitle = re.compile(pathstring)` My output is: ``` Govt has nothing to do with former CAG official RP Singh: Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper"> <table class="al-attribu...
2012/11/23
[ "https://Stackoverflow.com/questions/13536350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733583/" ]
I would suggest using [pyquery](http://pypi.python.org/pypi/pyquery) instead of going mad on regular expressions... It's based on lxml and makes HTML parsing easy as using jQuery. Something like this is everything you need: ``` doc = PyQuery(html) doc('span.titletext').text() ``` You could also use [beautifulsoup](...
You could also just as easily use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) which is great for doing this kind of thing. ``` #using BeautifulSoup4, install by "pip install BeautifulSoup4" from bs4 import BeautifulSoup soup = BeautifulSoup(html) result = soup.find('span', 'titletext') ``` And the...
13,536,350
On using this regular expression in python : `pathstring = '<span class="titletext">(.*)</span>'` `pathFinderTitle = re.compile(pathstring)` My output is: ``` Govt has nothing to do with former CAG official RP Singh: Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper"> <table class="al-attribu...
2012/11/23
[ "https://Stackoverflow.com/questions/13536350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733583/" ]
`.*` will match `</span>` so it keeps on going until the last one. The best answer is: Don't parse html with regular expressions. Use the [lxml](http://lxml.de/installation.html) library (or something similar). ``` from lxml import html html_string = '<blah>' tree = html.fromstring(html_string) titles = tree.xpath("...
You could also just as easily use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) which is great for doing this kind of thing. ``` #using BeautifulSoup4, install by "pip install BeautifulSoup4" from bs4 import BeautifulSoup soup = BeautifulSoup(html) result = soup.find('span', 'titletext') ``` And the...
32,878,530
I have a Python/Django project that I manage using PyCharm. Everything was working perfectly under Mac OSX Yosemite. This morning I upgraded to the final release version of El Capitan, now I cannot run the project. The error I get is: > > Error loading MySQLdb module: No module named MySQLdb > > > I've tried all ...
2015/10/01
[ "https://Stackoverflow.com/questions/32878530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1402166/" ]
Happened to me as well. I removed the package, installed mysql using [Homebrew](http://brew.sh/) and then reinstall the package. ``` pip uninstall MySQL-python brew install mysql pip install MySQL-python ``` If you run into any issues with brew, be sure to check their [troubleshooting page on El Capitan](https://git...
View this post : [MySQL Improperly Configured Reason: unsafe use of relative path](https://stackoverflow.com/questions/31343299/mysql-improperly-configured-reason-unsafe-use-of-relative-path) And if you have updated Xcode, open 1 time Xcode for agreement the licence.
62,804,653
I see that all of the examples per the documentation use some form of a simple web application (For example, Flask in Python). Is it possible to use cloud run as a non web application? For example, deploy cloud run to use a python script and then use GCP Scheduler to invoke cloud run every hour to run that script? Basi...
2020/07/08
[ "https://Stackoverflow.com/questions/62804653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11287314/" ]
It's mandatory to answer to HTTP request. It's the contract of Cloud Run * Stateless (no volume attached to the container) * Answer to HTTP request However, if you already have a python script, it's easy to wrap it in a flask webserver. Let's say, you have something like this (I assume that the file name is `main.py`...
It depends what is being installed in the container image, as there is no requirement that one would have to install a web-server. For [example](https://github.com/syslogic/cloudbuild-android), with such an image I can build Android applications, triggered whenever a repository changes (file excludes recommend) ...and ...
62,804,653
I see that all of the examples per the documentation use some form of a simple web application (For example, Flask in Python). Is it possible to use cloud run as a non web application? For example, deploy cloud run to use a python script and then use GCP Scheduler to invoke cloud run every hour to run that script? Basi...
2020/07/08
[ "https://Stackoverflow.com/questions/62804653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11287314/" ]
It's mandatory to answer to HTTP request. It's the contract of Cloud Run * Stateless (no volume attached to the container) * Answer to HTTP request However, if you already have a python script, it's easy to wrap it in a flask webserver. Let's say, you have something like this (I assume that the file name is `main.py`...
I've struggled with deployment my function which no need to handle any request in Cloud Run by putting functions in Flask app and found out that Cloud Run provides us 2 kinds of jobs, services and jobs. [**Illustration from codelabs**](https://i.stack.imgur.com/LehWZ.png) From cloud run jobs [documentation](https://c...
26,268,268
I have the following string in a seperate .txt file: ``` L#$KJ#()JSEFS(DF)(SD*F #KJ$H#K$JH@#K$JHD) SF SDFLKJ#{P@$OJ{SDPFODS{PFO{ #K$HK#JHSFHD(*SHF)SF{HP #L$H@โ€#$Hโ€@#L$KH#โ€@L$K #~L$KJ#:$SD)FJ)S(DJF)(S #$KJH#$ SDLKFJD(FJ)SDJFSDLFKS ~L#$KJ:@LK$#J$ LSJDF(S*JDF(*SJDF(*J(DSF*J ``` I have to take every element by column...
2014/10/08
[ "https://Stackoverflow.com/questions/26268268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3643019/" ]
From <https://docs.recurly.com/api/recurlyjs/jsonp_endpoints> ``` $.ajax({ dataType: 'jsonp', url: 'https://{subdomain}.recurly.com/jsonp/{subdomain}/plans/{plan_code}', data: { currency: 'USD', }, success: function (data) { // do stuff }, } ```
You should *not* use the V2 API from the browser. Doing so risks exposing your private API key. If someone has your API key they can make calls charging customers, modifying subscriptions, causing all sorts of problems. Look at the JSONP endpoints that Byaxy linked to.
14,389,513
I need to parse html table of the following structure: ``` <table class="table1" width="620" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr width="620"> <th width="620">Smth1</th> ... </tr> <tr bgcolor="ffffff" width="620"> <td width="620">Smth2</td> ... </tr> <tr bgcolor="...
2013/01/17
[ "https://Stackoverflow.com/questions/14389513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1988698/" ]
You didn't include the XPath, so I'm not sure what you're trying to do, but if I understood correctly, this should work ``` xpath1 = "tbody/tr" r = requests.post(url,data) html = lxml.html.fromstring(r.text) rows = html.xpath(xpath1) data = list() for row in rows: data.append([c.text for c in row.getchildren()]) ...
Your `.xpath(xpath1)` XPath expression failed to find any elements. Check that expression for errors.
39,448,121
I'm trying to upload a file using ftp in python, but I get an error saying: ``` ftplib.error_perm: 550 Filename invalid ``` when I run the following code: ``` ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '') ftp.cwd("/incoming") file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb') ftp.storbinary('STOR c:\Automation...
2016/09/12
[ "https://Stackoverflow.com/questions/39448121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6434729/" ]
The problem is that on the server, the path `c:\Automation\FTP_Files\MaxErrors1.json` is not valid. Instead try just doing: ``` ftp.storbinary('STOR MaxErrors1.json', file) ```
The argument to STOR needs to be the destination file name, not the source path. You should just do `ftp.storbinary('STOR MaxErrors1.json', file)`.
39,448,121
I'm trying to upload a file using ftp in python, but I get an error saying: ``` ftplib.error_perm: 550 Filename invalid ``` when I run the following code: ``` ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '') ftp.cwd("/incoming") file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb') ftp.storbinary('STOR c:\Automation...
2016/09/12
[ "https://Stackoverflow.com/questions/39448121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6434729/" ]
The problem is that on the server, the path `c:\Automation\FTP_Files\MaxErrors1.json` is not valid. Instead try just doing: ``` ftp.storbinary('STOR MaxErrors1.json', file) ```
you should upload file without absolute path in ftp server for example : ``` import ftplib session = ftplib.FTP('server.address.com','USERNAME','PASSWORD') file = open('kitten.jpg','rb') # file to send session.storbinary('STOR kitten.jpg', file) # send the file file.close() ...
20,457,271
So im new at python and i would like some help in making code where: When an input is typed if the input has a minimum of three words that match any one thing on a list it would replace the input with the text in the list that matches the criteria Example: Jan -Scans List- -Finds Janice- -Replaces and gives output as...
2013/12/08
[ "https://Stackoverflow.com/questions/20457271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3065432/" ]
You will need to: * make a replacement words dictionary * get some input * do sanity checking to make sure it fits your parameters * split it into a `list` * loop through your new `list` and replace each word with its replacement in your `dict`, if it is in there I won't write all of this for you. But here's a tip fo...
You Could try this ``` getname = [] for word in args "%s"% (room.usernames).get(args,word) ```
50,641,831
I am running a playbook against a RHEL 7.4 image which sits behind a proxy. SELINUX and the firewall have been disabled. I am using Ansible 2.5.3 Here is the task ``` - name: Add Docker repository. get_url: url: "{{ docker_yum_repo_url }}" dest: '/etc/yum.repos.d/docker-{{ docker_edition }}.repo' owner: root ...
2018/06/01
[ "https://Stackoverflow.com/questions/50641831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768233/" ]
Build your app with sourcemaps, then use a tool like [`source-map-explorer`](https://www.npmjs.com/package/source-map-explorer) that details the size of every part of library that you're using. Some tips with common libraries : * If you're using RxJS 5.5 or higher, use the `.pipe(operator1(), operator2())` syntax, it...
I had a similar issue with large prod bundles and fixed the issue with this command; ``` npm run build ``` I had been using `npm run ng build --prod` but the --prod flag doesn't execute and I was left with a vendor.bundle.js which was 2.9mbs ``` chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 3.89 ...
50,641,831
I am running a playbook against a RHEL 7.4 image which sits behind a proxy. SELINUX and the firewall have been disabled. I am using Ansible 2.5.3 Here is the task ``` - name: Add Docker repository. get_url: url: "{{ docker_yum_repo_url }}" dest: '/etc/yum.repos.d/docker-{{ docker_edition }}.repo' owner: root ...
2018/06/01
[ "https://Stackoverflow.com/questions/50641831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768233/" ]
Build your app with sourcemaps, then use a tool like [`source-map-explorer`](https://www.npmjs.com/package/source-map-explorer) that details the size of every part of library that you're using. Some tips with common libraries : * If you're using RxJS 5.5 or higher, use the `.pipe(operator1(), operator2())` syntax, it...
Sorry For Late Reply. This answer will work for all newer versions of Angular. 1. If you are using Angular Material, Then import from the specific package exporter. Ex: ``` import {MatButtonModule} from '@angular/material/button'; ``` istead of ``` import {MatButtonModule} from '@angular/material'; ``` 2. Avoid...
50,641,831
I am running a playbook against a RHEL 7.4 image which sits behind a proxy. SELINUX and the firewall have been disabled. I am using Ansible 2.5.3 Here is the task ``` - name: Add Docker repository. get_url: url: "{{ docker_yum_repo_url }}" dest: '/etc/yum.repos.d/docker-{{ docker_edition }}.repo' owner: root ...
2018/06/01
[ "https://Stackoverflow.com/questions/50641831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768233/" ]
I had a similar issue with large prod bundles and fixed the issue with this command; ``` npm run build ``` I had been using `npm run ng build --prod` but the --prod flag doesn't execute and I was left with a vendor.bundle.js which was 2.9mbs ``` chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 3.89 ...
Sorry For Late Reply. This answer will work for all newer versions of Angular. 1. If you are using Angular Material, Then import from the specific package exporter. Ex: ``` import {MatButtonModule} from '@angular/material/button'; ``` istead of ``` import {MatButtonModule} from '@angular/material'; ``` 2. Avoid...
49,520,600
I'm creating a program in python where i need to ask the user for there team name and team members. I need to have the team names in a list and have the team members embedded within the team name. Any Help? ``` # Creating Teams print("Welcome to the program") print("==================================================...
2018/03/27
[ "https://Stackoverflow.com/questions/49520600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9560138/" ]
`equalsIgnoreCase` just returns a boolean, which indicates, whether two strings are equal if the case of the strings is not considered. What you need is ``` String aLower = a.toLowerCase(); String bLower = b.toLowerCase(); if(aLower.startsWith(bLower)) { // do something } ``` That way you just convert both stri...
Try this : ``` System.out.println((a.toLowerCase()).startsWith(b.toLowerCase())); ```
38,064,044
I am implementing a simple DSL. I have the following input string: ``` txt = 'Hi, my name is <<name>>. I was born in <<city>>.' ``` And I have the following data: ``` { 'name': 'John', 'city': 'Paris', 'more': 'xxx', 'data': 'yyy', ... } ``` I need to implement the following function: ``` def tokenize...
2016/06/27
[ "https://Stackoverflow.com/questions/38064044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647991/" ]
Yes, this is a perfect target for regexp. Find the begin/end quotation marks, replace them with braces, and extract the symbol names into a list. Do you have a solid description of legal symbols? You'll want a search such as ``` /\<\<([a-zA-Z]+[a-zA-Z0-9_]*)\>\>/ ``` For classical variable names (note that this excl...
``` import re def tokenize(text): found_variables = [] def replace_and_capture(match): found_variables.append(match.group(1)) return "{{{}}}".format(match.group(1)) return re.sub(r'<<([^>]+)>>', replace_and_capture, text), found_variables fmt, vars = tokenize('Hi, my name is <<name>>. I wa...
66,565,415
basically im new to python programming and I've just learnt about user input. Im trying to make an if statement that checks if the input is a str or int and then prints a message. If anyone knows how then please comment it, thanks. ``` print("How old are you?") dog = input() final = int(dog) + int(100) if dog == str:...
2021/03/10
[ "https://Stackoverflow.com/questions/66565415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15051671/" ]
Re how to check types, you can do like this: ```py my_string = "hello" if isinstance(my_string, str): print("I'm a string") else: print("I'm not") # outputs: "I'm a string" ``` However, as commented the input method is always returning a value of type str. So if you want to ensure that the value is only con...
I would use the `type` method to check: ``` print("How old are you?") dog = input() final = int(dog) + int(100) #use type method to check the type of the variable if type(dog) == str: print("No") else: print("\nHeres you name + 100!") print(f"{final}") print("Thanks for playing!") ``` Another thing ...
57,899,891
I read this (from [here](https://docs.python.org/3.5/reference/datamodel.html#object.__hash__)): > > User-defined classes have `__eq__()` and `__hash__()` methods by default; with them, all objects compare unequal (except with themselves) and `x.__hash__()` returns an appropriate value such that x == y implies both t...
2019/09/12
[ "https://Stackoverflow.com/questions/57899891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3530284/" ]
No, it's more like: ``` def __eq__(self, other) return self is other ``` You can't use `hash()` because it's possible for different objects to have the same hash value.
You can read the following reference: <https://eev.ee/blog/2012/03/24/python-faq-equality/> in the default method where you just try to compare 2 objects while not override the ***eq*** it will see if they are the same 2 objects, more like the following: ``` def __eq__(self, other) return self is other ```
57,899,891
I read this (from [here](https://docs.python.org/3.5/reference/datamodel.html#object.__hash__)): > > User-defined classes have `__eq__()` and `__hash__()` methods by default; with them, all objects compare unequal (except with themselves) and `x.__hash__()` returns an appropriate value such that x == y implies both t...
2019/09/12
[ "https://Stackoverflow.com/questions/57899891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3530284/" ]
No, it's more like: ``` def __eq__(self, other) return self is other ``` You can't use `hash()` because it's possible for different objects to have the same hash value.
You can refer to [existing question](https://stackoverflow.com/questions/2909106/whats-a-correct-and-good-way-to-implement-hash) It explains how to use `__hash__()` with `__eq__()` correctly
57,899,891
I read this (from [here](https://docs.python.org/3.5/reference/datamodel.html#object.__hash__)): > > User-defined classes have `__eq__()` and `__hash__()` methods by default; with them, all objects compare unequal (except with themselves) and `x.__hash__()` returns an appropriate value such that x == y implies both t...
2019/09/12
[ "https://Stackoverflow.com/questions/57899891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3530284/" ]
You can read the following reference: <https://eev.ee/blog/2012/03/24/python-faq-equality/> in the default method where you just try to compare 2 objects while not override the ***eq*** it will see if they are the same 2 objects, more like the following: ``` def __eq__(self, other) return self is other ```
You can refer to [existing question](https://stackoverflow.com/questions/2909106/whats-a-correct-and-good-way-to-implement-hash) It explains how to use `__hash__()` with `__eq__()` correctly
12,757,832
I began learning Python a little time ago, and I got the first problem. Here's the code: ``` fh = open('/usr/share/dict/words') for line in fh.readlines(): print(line, end='') ``` When I execute it in the Terminal (OS X), it tells me `invalid syntax` error where `end` equal sign is placed. What's the problem her...
2012/10/06
[ "https://Stackoverflow.com/questions/12757832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/764638/" ]
Apparently because the `WebView` had editable content the events were being consumed by a child responder. The workaround was to listen to `WebViewDidChangeNotification` when this happens.
Here is what I think is occurring NSFontManager apparently sends the messages along the responder chain and not to the delegate. I would set my CustomWebViewController to be the delegate of the window.
5,919,318
I want to nest my custom validators within my schema, like this: ``` MySchema(Schema): class MyValidator(validators.FancyValidator): def _to_python(self, value, state): ... class MyOtherValidator(validators.FancyValidator): def _to_python(self, value, state): ... fi...
2011/05/07
[ "https://Stackoverflow.com/questions/5919318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315709/" ]
My advice is: you should move the `FancyValidator` subclass definitions to global scope, either (1) in the same module just before the definition of the `Schema` in which they're used, or (2) in a separate module for greater reuse. Unless there is a specific reason why nesting is required, a few extra class names in th...
In python, anything that you define in your class is a field. Be it static variables, variables set with self, methods or classes. If you want to "hide" the classes, or make them "less public", as is probably the right wording in the python dictionary, you should start their names with \_\_. ``` >>> dir(X()) ['A', '_B...
50,294,263
I'm trying to write simple multi-threaded python script: ``` from multiprocessing.dummy import Pool as ThreadPool def resize_img_folder_multithreaded(img_fldr_src,img_fldr_dst,max_num_of_thread): images = glob.glob(img_fldr_src+'/*.'+img_file_extension) pool = ThreadPool(max_num_of_thread) pool.starmap...
2018/05/11
[ "https://Stackoverflow.com/questions/50294263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3134181/" ]
Blame the GIL. Python has this mechanism called the GIL, global interpreter lock. It is basically a mutex that prevents native threads from executing Python bytecodes at once. This must be done since Python's (at least, CPython) memory management is not thread-safe. In other words, the GIL will prevent you from runni...
You should only use multiprocessing with the number of cpu cores you have available. You are also not using a Queue, so the pool of resources are doing the same work. You need to add a queue to your code. [Filling a queue and managing multiprocessing in python](https://stackoverflow.com/questions/17241663/filling-a-q...
50,294,263
I'm trying to write simple multi-threaded python script: ``` from multiprocessing.dummy import Pool as ThreadPool def resize_img_folder_multithreaded(img_fldr_src,img_fldr_dst,max_num_of_thread): images = glob.glob(img_fldr_src+'/*.'+img_file_extension) pool = ThreadPool(max_num_of_thread) pool.starmap...
2018/05/11
[ "https://Stackoverflow.com/questions/50294263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3134181/" ]
Blame the GIL. Python has this mechanism called the GIL, global interpreter lock. It is basically a mutex that prevents native threads from executing Python bytecodes at once. This must be done since Python's (at least, CPython) memory management is not thread-safe. In other words, the GIL will prevent you from runni...
The problem come from the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) or GIL. GIL only let one thread run at a time so if you want to do parallel computation use [Processing.Pool](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool): ``` im...
50,294,263
I'm trying to write simple multi-threaded python script: ``` from multiprocessing.dummy import Pool as ThreadPool def resize_img_folder_multithreaded(img_fldr_src,img_fldr_dst,max_num_of_thread): images = glob.glob(img_fldr_src+'/*.'+img_file_extension) pool = ThreadPool(max_num_of_thread) pool.starmap...
2018/05/11
[ "https://Stackoverflow.com/questions/50294263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3134181/" ]
The problem come from the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) or GIL. GIL only let one thread run at a time so if you want to do parallel computation use [Processing.Pool](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool): ``` im...
You should only use multiprocessing with the number of cpu cores you have available. You are also not using a Queue, so the pool of resources are doing the same work. You need to add a queue to your code. [Filling a queue and managing multiprocessing in python](https://stackoverflow.com/questions/17241663/filling-a-q...
35,814,637
I am trying to call a Torch 7 program from within a Python cgi-bin script. If I run the following Python script from the command line: ``` # -*- coding: utf-8 -*- from subprocess import call call (['th', 'sample.lua', 'cv/lm_lstm_epoch3.54_0.9324.t7', '-gpuid', '-1', '-primetext', '"ืืžืจ ื”ื’ืื•ืŸ ื”ื’ืจืคืงื ื”ืžืŸ ืื™ืฉ ื˜ื•ื‘ ื”ื™ื” ืฉ...
2016/03/05
[ "https://Stackoverflow.com/questions/35814637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6001121/" ]
You want to use [check\_output](https://docs.python.org/3/library/subprocess.html#subprocess.check_output) to store the output of the command you are executing. [call](https://docs.python.org/3/library/subprocess.html#subprocess.call) will not do this. Call will only give you the return code of what you are executing. ...
May be you could try [lutorpy](https://github.com/imodpasteur/lutorpy) then you can run the torch code directly with python. You can use require("sample") to import your sample.lua module, and then run the inner function just like you run a python function.
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
**EDIT:** The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller: ``` impor...
A one liner list comprehension using inbuilt `min` function by modifying the key argument to look for an absolute difference ``` upper_lower_bound_list=[3,9] myNumberlist=[ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ``` List comprehension ``` [min(upper_lower_b...
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
**EDIT:** The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller: ``` impor...
Another option using list comprehensions and lambda functions: ``` round_the_num = lambda list, upper, lower: [upper if x > (upper + lower) / 2 else lower for x in list] round_the_num(l, 9, 3) ```
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
***Timing comparison*** *of available answers* [![enter image description here](https://i.stack.imgur.com/nwLAw.png)](https://i.stack.imgur.com/nwLAw.png) My interpretation would be: From performance point of view you should go with Abhishek Patel or Carles Mitjans for smaller lists. For lists containing severa...
You can write a custom function that does a list-comprehension, like: ``` lst = [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] def return_the_num(l, lst, h): return [l if abs(l-x) < abs(h-x) else h for x in lst] print(return_the_num(3, lst, 9)) # [9, 9...
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
**EDIT:** The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller: ``` impor...
You can write a custom function that does a list-comprehension, like: ``` lst = [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] def return_the_num(l, lst, h): return [l if abs(l-x) < abs(h-x) else h for x in lst] print(return_the_num(3, lst, 9)) # [9, 9...
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
**EDIT:** The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller: ``` impor...
***Timing comparison*** *of available answers* [![enter image description here](https://i.stack.imgur.com/nwLAw.png)](https://i.stack.imgur.com/nwLAw.png) My interpretation would be: From performance point of view you should go with Abhishek Patel or Carles Mitjans for smaller lists. For lists containing severa...
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
**EDIT:** The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller: ``` impor...
I really like @AbhishekPatel's idea about comparing against the mid point. But I'd put it into a LC using the result as an index for a bounds tuple: ``` the_list = [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] hi = 9 lo = 3 mid = (hi + lo) / 2 [(lo, hi)[mid < v] fo...
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
**EDIT:** The best approach in my opinion up to now is using numpy (to avoid "manual" looping) with a simple calculation of the difference arrays between `the_list` and the two bounds (so no expensive multiplication here), to then only conditionally add the one or the other, depending on which is smaller: ``` impor...
Perhaps you could write a function and use it in a list comprehension. ``` def return_bound(x, l, h): low = abs(x - l) high = abs(x - h) if low < high: return l else: return h ``` Test: ``` >>> mylist = [7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.06793...
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
***Timing comparison*** *of available answers* [![enter image description here](https://i.stack.imgur.com/nwLAw.png)](https://i.stack.imgur.com/nwLAw.png) My interpretation would be: From performance point of view you should go with Abhishek Patel or Carles Mitjans for smaller lists. For lists containing severa...
A one liner list comprehension using inbuilt `min` function by modifying the key argument to look for an absolute difference ``` upper_lower_bound_list=[3,9] myNumberlist=[ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ``` List comprehension ``` [min(upper_lower_b...
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
***Timing comparison*** *of available answers* [![enter image description here](https://i.stack.imgur.com/nwLAw.png)](https://i.stack.imgur.com/nwLAw.png) My interpretation would be: From performance point of view you should go with Abhishek Patel or Carles Mitjans for smaller lists. For lists containing severa...
I really like @AbhishekPatel's idea about comparing against the mid point. But I'd put it into a LC using the result as an index for a bounds tuple: ``` the_list = [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] hi = 9 lo = 3 mid = (hi + lo) / 2 [(lo, hi)[mid < v] fo...
53,728,124
I'm working on a data-set on which I have certain values which are needed to be rounded to either lower/upper bound. eg. if I want the upper bound to be **9** and lower to **3** and we have numbers like - ``` [ 7.453511737983394, 8.10917072790058, 6.2377799380575, 5.225853201122676, 4.067932296134156 ] ...
2018/12/11
[ "https://Stackoverflow.com/questions/53728124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7618421/" ]
***Timing comparison*** *of available answers* [![enter image description here](https://i.stack.imgur.com/nwLAw.png)](https://i.stack.imgur.com/nwLAw.png) My interpretation would be: From performance point of view you should go with Abhishek Patel or Carles Mitjans for smaller lists. For lists containing severa...
You can generalize by finding the midpoint, and checking which side of the midpoint each number in the list is on ``` def round_the_list(list, bound_1, bound_2): mid = (bound_1+bound_2)/2 for i in range(len(list)): if list[i] > mid: # or >= depending on your rounding decision list[i] = ...
67,374,632
I want to take two lists and want to count the values that appear in both but considering **the same position**. ``` a = [1, 2, 3, 4, 5] b = [4, 5, 3, 6, 5] returnMatches(a, b) ``` would return `2`, for instance. ``` a = [1, 2, 3, 4, 5] b = [1, 2, 3, 3, 5] returnMatches(a, b) ``` would return `4`, for instance....
2021/05/03
[ "https://Stackoverflow.com/questions/67374632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152497/" ]
Try ```py output = sum([x == y for x, y in zip(a, b)]) ``` I am not sure if it needs further clarification. You might want to look into "list comprehension" and `zip()` if you are not familiar with them.
```py returnMatches = lambda a,b:sum([x==y for x,y in zip(a,b)] ``` This is the same as: ```py def returnMatches(a, b): matches = 0 for x, y in zip(a, b): matches += 1 return matches ``` Take a look at `zip()` for more information on that builtin
67,374,632
I want to take two lists and want to count the values that appear in both but considering **the same position**. ``` a = [1, 2, 3, 4, 5] b = [4, 5, 3, 6, 5] returnMatches(a, b) ``` would return `2`, for instance. ``` a = [1, 2, 3, 4, 5] b = [1, 2, 3, 3, 5] returnMatches(a, b) ``` would return `4`, for instance....
2021/05/03
[ "https://Stackoverflow.com/questions/67374632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152497/" ]
Look up what [`zip`](https://docs.python.org/3.3/library/functions.html#zip) is and how [list comprehension and generator expressions](https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions) work: ``` def count_matches(a, b): return sum(x == y for x, y in zip(a, b)) ```
```py returnMatches = lambda a,b:sum([x==y for x,y in zip(a,b)] ``` This is the same as: ```py def returnMatches(a, b): matches = 0 for x, y in zip(a, b): matches += 1 return matches ``` Take a look at `zip()` for more information on that builtin
74,575,794
Consider the following simple code: ``` import re def my_match(s): if re.match("^[a-zA-Z]+", s): return True else: return False ``` Is there a way to collapse this in a single `return` statement? In `C` we could do for example: ``` return match("^[a-zA-Z]+", s) ? true : false; ``` Is th...
2022/11/25
[ "https://Stackoverflow.com/questions/74575794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738154/" ]
Python also supports this, although the syntaxes is a little different than most languages. ``` import re def my_match(s): return True if re.match("^[a-zA-Z]+", s) else False ``` In general, the Python syntax is `val_when_true if cond else val_when_false`, compared to the `cond ? val_when_true : val_when_false`...
A more generell solution would be to use the following code line. It excludes a fit with length 0 as it specificly checks for the None statement. In this case an empty string is impossible but it is more explicit. ```py return re.match("^[a-zA-Z]+", s) is not None ```
74,575,794
Consider the following simple code: ``` import re def my_match(s): if re.match("^[a-zA-Z]+", s): return True else: return False ``` Is there a way to collapse this in a single `return` statement? In `C` we could do for example: ``` return match("^[a-zA-Z]+", s) ? true : false; ``` Is th...
2022/11/25
[ "https://Stackoverflow.com/questions/74575794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738154/" ]
A more generell solution would be to use the following code line. It excludes a fit with length 0 as it specificly checks for the None statement. In this case an empty string is impossible but it is more explicit. ```py return re.match("^[a-zA-Z]+", s) is not None ```
The other answers show the ternary equivalent in Python. But since Python also assigns `truthiness` to values and expressions, you could simply use: ``` my_match = lambda s : bool(re.match("^[a-zA-Z]+", s)) ```
74,575,794
Consider the following simple code: ``` import re def my_match(s): if re.match("^[a-zA-Z]+", s): return True else: return False ``` Is there a way to collapse this in a single `return` statement? In `C` we could do for example: ``` return match("^[a-zA-Z]+", s) ? true : false; ``` Is th...
2022/11/25
[ "https://Stackoverflow.com/questions/74575794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738154/" ]
A more generell solution would be to use the following code line. It excludes a fit with length 0 as it specificly checks for the None statement. In this case an empty string is impossible but it is more explicit. ```py return re.match("^[a-zA-Z]+", s) is not None ```
`re.match()` returns a value that can be evaluated for *truthiness*. So if you don't need to return the *exact* values `True` and `False`, you can just directly return the result of the `match()` function: ``` def my_match(s): return re.match("^[a-zA-Z]+", s) ``` And then the caller can say: ``` if my_match(x):...
74,575,794
Consider the following simple code: ``` import re def my_match(s): if re.match("^[a-zA-Z]+", s): return True else: return False ``` Is there a way to collapse this in a single `return` statement? In `C` we could do for example: ``` return match("^[a-zA-Z]+", s) ? true : false; ``` Is th...
2022/11/25
[ "https://Stackoverflow.com/questions/74575794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738154/" ]
Python also supports this, although the syntaxes is a little different than most languages. ``` import re def my_match(s): return True if re.match("^[a-zA-Z]+", s) else False ``` In general, the Python syntax is `val_when_true if cond else val_when_false`, compared to the `cond ? val_when_true : val_when_false`...
The other answers show the ternary equivalent in Python. But since Python also assigns `truthiness` to values and expressions, you could simply use: ``` my_match = lambda s : bool(re.match("^[a-zA-Z]+", s)) ```
74,575,794
Consider the following simple code: ``` import re def my_match(s): if re.match("^[a-zA-Z]+", s): return True else: return False ``` Is there a way to collapse this in a single `return` statement? In `C` we could do for example: ``` return match("^[a-zA-Z]+", s) ? true : false; ``` Is th...
2022/11/25
[ "https://Stackoverflow.com/questions/74575794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/738154/" ]
Python also supports this, although the syntaxes is a little different than most languages. ``` import re def my_match(s): return True if re.match("^[a-zA-Z]+", s) else False ``` In general, the Python syntax is `val_when_true if cond else val_when_false`, compared to the `cond ? val_when_true : val_when_false`...
`re.match()` returns a value that can be evaluated for *truthiness*. So if you don't need to return the *exact* values `True` and `False`, you can just directly return the result of the `match()` function: ``` def my_match(s): return re.match("^[a-zA-Z]+", s) ``` And then the caller can say: ``` if my_match(x):...
17,217,225
Consider: ``` >>> a = {'foo': {'bar': 3}} >>> b = {'foo': {'bar': 3}} >>> a == b True ``` According to the python doc, [you can indeed use](http://docs.python.org/2/library/stdtypes.html#dict) the `==` operator on dictionaries. What is actually happening here? Is Python recursively checking each element of the di...
2013/06/20
[ "https://Stackoverflow.com/questions/17217225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3788/" ]
Python is recursively checking each element of the dictionaries to ensure equality. See the [C `dict_equal()` implementation](http://hg.python.org/cpython/file/6f535c725b27/Objects/dictobject.c#l1839), which checks each and every key and value (provided the dictionaries are the same length); if dictionary `b` has the s...
The dictionaries are equal if they have the same keys and the same values for each corresponding key. See some examples: ``` dict(a=1, b=2) == dict(a=2, b=1) False dict(a=1, b=2) == dict(a=1, b=2, c=0) False dict(a=1, b=2) == dict(b=2, a=1) True ```
17,217,225
Consider: ``` >>> a = {'foo': {'bar': 3}} >>> b = {'foo': {'bar': 3}} >>> a == b True ``` According to the python doc, [you can indeed use](http://docs.python.org/2/library/stdtypes.html#dict) the `==` operator on dictionaries. What is actually happening here? Is Python recursively checking each element of the di...
2013/06/20
[ "https://Stackoverflow.com/questions/17217225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3788/" ]
Python is recursively checking each element of the dictionaries to ensure equality. See the [C `dict_equal()` implementation](http://hg.python.org/cpython/file/6f535c725b27/Objects/dictobject.c#l1839), which checks each and every key and value (provided the dictionaries are the same length); if dictionary `b` has the s...
From [docs](http://docs.python.org/2/reference/expressions.html#not-in): > > Mappings (dictionaries) compare equal if and only if their sorted > (key, value) lists compare equal .[[5]](http://docs.python.org/2/reference/expressions.html#id24) Outcomes other than equality are > resolved consistently, but are not oth...
17,217,225
Consider: ``` >>> a = {'foo': {'bar': 3}} >>> b = {'foo': {'bar': 3}} >>> a == b True ``` According to the python doc, [you can indeed use](http://docs.python.org/2/library/stdtypes.html#dict) the `==` operator on dictionaries. What is actually happening here? Is Python recursively checking each element of the di...
2013/06/20
[ "https://Stackoverflow.com/questions/17217225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3788/" ]
From [docs](http://docs.python.org/2/reference/expressions.html#not-in): > > Mappings (dictionaries) compare equal if and only if their sorted > (key, value) lists compare equal .[[5]](http://docs.python.org/2/reference/expressions.html#id24) Outcomes other than equality are > resolved consistently, but are not oth...
The dictionaries are equal if they have the same keys and the same values for each corresponding key. See some examples: ``` dict(a=1, b=2) == dict(a=2, b=1) False dict(a=1, b=2) == dict(a=1, b=2, c=0) False dict(a=1, b=2) == dict(b=2, a=1) True ```
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
OPSIN (<https://opsin.ch.cam.ac.uk/>) is another solution for name2structure conversion. It can be used by installing the cli, or via <https://github.com/gorgitko/molminer> (OPSIN is used by the RDKit KNIME nodes also)
The accepted answer uses the [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) but for some reason the website seems to be buggy for me and the API seems to be messed up. So another way to connvert smiles to IUPAC name is with the the PubChem python API, which can work if your smiles is in ...
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
RDKit cant convert names to SMILES. [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) can convert names and other identifiers (like CAS No) and has an API so you can convert with a script. ``` from urllib.request import urlopen from urllib.parse import quote def CIRconvert(ids): try: ...
PubChemPy has some great features that can be used for this purpose. It supports IUPAC systematic names, trade names and all known synonyms for a given Compound as documented in PubChem database: <https://pubchempy.readthedocs.io/en/latest/> ``` >>> import pubchempy as pcp >>> results = pcp.get_compounds('Glucose', 'n...
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
RDKit cant convert names to SMILES. [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) can convert names and other identifiers (like CAS No) and has an API so you can convert with a script. ``` from urllib.request import urlopen from urllib.parse import quote def CIRconvert(ids): try: ...
if you change the first line to: from urllib2 import url open it should work for python 2.7
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
PubChemPy has some great features that can be used for this purpose. It supports IUPAC systematic names, trade names and all known synonyms for a given Compound as documented in PubChem database: <https://pubchempy.readthedocs.io/en/latest/> ``` >>> import pubchempy as pcp >>> results = pcp.get_compounds('Glucose', 'n...
You can use batch query of pubchem: * <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange.cgi> * <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange-help.html>
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
PubChemPy has some great features that can be used for this purpose. It supports IUPAC systematic names, trade names and all known synonyms for a given Compound as documented in PubChem database: <https://pubchempy.readthedocs.io/en/latest/> ``` >>> import pubchempy as pcp >>> results = pcp.get_compounds('Glucose', 'n...
You can use the pubchem API (PUG REST) for this (<https://pubchemdocs.ncbi.nlm.nih.gov/pug-rest-tutorial>) Basically, the url you are calling will take the compound as a "name", you then give the name, then you specify that you want the "property" of "CanonicalSMILES", as text ``` identifiers = ['3-Methylheptane', ...
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
OPSIN (<https://opsin.ch.cam.ac.uk/>) is another solution for name2structure conversion. It can be used by installing the cli, or via <https://github.com/gorgitko/molminer> (OPSIN is used by the RDKit KNIME nodes also)
You can use the pubchem API (PUG REST) for this (<https://pubchemdocs.ncbi.nlm.nih.gov/pug-rest-tutorial>) Basically, the url you are calling will take the compound as a "name", you then give the name, then you specify that you want the "property" of "CanonicalSMILES", as text ``` identifiers = ['3-Methylheptane', ...
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
RDKit cant convert names to SMILES. [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) can convert names and other identifiers (like CAS No) and has an API so you can convert with a script. ``` from urllib.request import urlopen from urllib.parse import quote def CIRconvert(ids): try: ...
The accepted answer uses the [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) but for some reason the website seems to be buggy for me and the API seems to be messed up. So another way to connvert smiles to IUPAC name is with the the PubChem python API, which can work if your smiles is in ...
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
OPSIN (<https://opsin.ch.cam.ac.uk/>) is another solution for name2structure conversion. It can be used by installing the cli, or via <https://github.com/gorgitko/molminer> (OPSIN is used by the RDKit KNIME nodes also)
You can use batch query of pubchem: * <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange.cgi> * <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange-help.html>
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
RDKit cant convert names to SMILES. [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) can convert names and other identifiers (like CAS No) and has an API so you can convert with a script. ``` from urllib.request import urlopen from urllib.parse import quote def CIRconvert(ids): try: ...
You can use batch query of pubchem: * <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange.cgi> * <https://pubchem.ncbi.nlm.nih.gov/idexchange/idexchange-help.html>
54,930,121
I was just wondering, is there any way to convert IUPAC or common molecular names to SMILES? I want to do this without having to manually convert every single one utilizing online systems. Any input would be much appreciated! For background, I am currently working with python and RDkit, so I wasn't sure if RDkit could...
2019/02/28
[ "https://Stackoverflow.com/questions/54930121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11131756/" ]
PubChemPy has some great features that can be used for this purpose. It supports IUPAC systematic names, trade names and all known synonyms for a given Compound as documented in PubChem database: <https://pubchempy.readthedocs.io/en/latest/> ``` >>> import pubchempy as pcp >>> results = pcp.get_compounds('Glucose', 'n...
The accepted answer uses the [Chemical Identifier Resolver](https://cactus.nci.nih.gov/chemical/structure) but for some reason the website seems to be buggy for me and the API seems to be messed up. So another way to connvert smiles to IUPAC name is with the the PubChem python API, which can work if your smiles is in ...
46,289,914
I have python code as follow. jv\_list is populated from resultset retrieve from D.B. query. ``` jv_list = list(result.get_points()) print(jv_list) ``` I am printing jv\_list and it is giving me below mention output. ``` [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': ...
2017/09/19
[ "https://Stackoverflow.com/questions/46289914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597746/" ]
Try this sequence of commands ``` >>> X = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] >>> for x in X: ... x['answer'] = float(x['length-bytes'])/float(x['in']) ... >>> X [{'in': '19834', 'length-bytes': '79923888', 'run-time': '1...
You can't reliably do that, dictionaries are unordered. With this data structure, you will need to address the elements via their keys. that is `jv_list[0]['length_bytes'] / jv_list[0]['in']` for each pair of elements you want to divide by each other.
46,289,914
I have python code as follow. jv\_list is populated from resultset retrieve from D.B. query. ``` jv_list = list(result.get_points()) print(jv_list) ``` I am printing jv\_list and it is giving me below mention output. ``` [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': ...
2017/09/19
[ "https://Stackoverflow.com/questions/46289914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597746/" ]
If this is what you mean ``` x = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] for i in x: print(float(i['length-bytes'])/float(i['in'])) ``` results as ``` 4029.64041544822 ```
You can't reliably do that, dictionaries are unordered. With this data structure, you will need to address the elements via their keys. that is `jv_list[0]['length_bytes'] / jv_list[0]['in']` for each pair of elements you want to divide by each other.
46,289,914
I have python code as follow. jv\_list is populated from resultset retrieve from D.B. query. ``` jv_list = list(result.get_points()) print(jv_list) ``` I am printing jv\_list and it is giving me below mention output. ``` [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': ...
2017/09/19
[ "https://Stackoverflow.com/questions/46289914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597746/" ]
Try this sequence of commands ``` >>> X = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] >>> for x in X: ... x['answer'] = float(x['length-bytes'])/float(x['in']) ... >>> X [{'in': '19834', 'length-bytes': '79923888', 'run-time': '1...
If you want the result of `length-bytes / in`, you can use those keys and retrieve their values: ``` jv_list = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] result = float(jv_list[0]['length-bytes']) / float(jv_list[0]['in']) print(re...
46,289,914
I have python code as follow. jv\_list is populated from resultset retrieve from D.B. query. ``` jv_list = list(result.get_points()) print(jv_list) ``` I am printing jv\_list and it is giving me below mention output. ``` [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': ...
2017/09/19
[ "https://Stackoverflow.com/questions/46289914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597746/" ]
Try this sequence of commands ``` >>> X = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] >>> for x in X: ... x['answer'] = float(x['length-bytes'])/float(x['in']) ... >>> X [{'in': '19834', 'length-bytes': '79923888', 'run-time': '1...
Based on your data structure it seems this would be the answer. ``` float(jv_list[0]['length-bytes']) / float(jv_list[0]['in']) ```
46,289,914
I have python code as follow. jv\_list is populated from resultset retrieve from D.B. query. ``` jv_list = list(result.get_points()) print(jv_list) ``` I am printing jv\_list and it is giving me below mention output. ``` [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': ...
2017/09/19
[ "https://Stackoverflow.com/questions/46289914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597746/" ]
If this is what you mean ``` x = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] for i in x: print(float(i['length-bytes'])/float(i['in'])) ``` results as ``` 4029.64041544822 ```
Try this sequence of commands ``` >>> X = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] >>> for x in X: ... x['answer'] = float(x['length-bytes'])/float(x['in']) ... >>> X [{'in': '19834', 'length-bytes': '79923888', 'run-time': '1...
46,289,914
I have python code as follow. jv\_list is populated from resultset retrieve from D.B. query. ``` jv_list = list(result.get_points()) print(jv_list) ``` I am printing jv\_list and it is giving me below mention output. ``` [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': ...
2017/09/19
[ "https://Stackoverflow.com/questions/46289914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597746/" ]
If this is what you mean ``` x = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] for i in x: print(float(i['length-bytes'])/float(i['in'])) ``` results as ``` 4029.64041544822 ```
If you want the result of `length-bytes / in`, you can use those keys and retrieve their values: ``` jv_list = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] result = float(jv_list[0]['length-bytes']) / float(jv_list[0]['in']) print(re...
46,289,914
I have python code as follow. jv\_list is populated from resultset retrieve from D.B. query. ``` jv_list = list(result.get_points()) print(jv_list) ``` I am printing jv\_list and it is giving me below mention output. ``` [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': ...
2017/09/19
[ "https://Stackoverflow.com/questions/46289914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597746/" ]
If this is what you mean ``` x = [{u'in': u'19834', u'length-bytes': u'79923888', u'run-time': u'1h50m43.489993955s', u'time': u'2017-09-08T21:20:39.846582783Z'}] for i in x: print(float(i['length-bytes'])/float(i['in'])) ``` results as ``` 4029.64041544822 ```
Based on your data structure it seems this would be the answer. ``` float(jv_list[0]['length-bytes']) / float(jv_list[0]['in']) ```
30,702,519
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between: ``` #!/bin/bash #your bash code python -c " #your py code " ``` vs ``` python - <<DOC #your py code DOC ``` I checked the web but couldn't compile the bits around the topic. Do you think one i...
2015/06/08
[ "https://Stackoverflow.com/questions/30702519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3598271/" ]
The main flaw of using a here document is that the script's standard input will be the here document. So if you have a script which wants to process its standard input, `python -c` is pretty much your only option. On the other hand, using `python -c '...'` ties up the single-quote for the shell's needs, so you can onl...
If you prefer to use `python -c '...'` without having to escape with the double-quotes you can first load the code in a bash variable using here-documents: ``` read -r -d '' CMD << '--END' print ("'quoted'") --END python -c "$CMD" ``` The python code is loaded verbatim into the CMD variable and there's no need to es...
30,702,519
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between: ``` #!/bin/bash #your bash code python -c " #your py code " ``` vs ``` python - <<DOC #your py code DOC ``` I checked the web but couldn't compile the bits around the topic. Do you think one i...
2015/06/08
[ "https://Stackoverflow.com/questions/30702519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3598271/" ]
The main flaw of using a here document is that the script's standard input will be the here document. So if you have a script which wants to process its standard input, `python -c` is pretty much your only option. On the other hand, using `python -c '...'` ties up the single-quote for the shell's needs, so you can onl...
If you are using bash, you can avoid heredoc problems if you apply a little bit more of boilerplate: ``` python <(cat <<EoF name = input() print(f'hello, {name}!') EoF ) ``` This will let you run your embedded Python script without you giving up the standard input. The overhead is mostly the same of using `cmda | ...
30,702,519
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between: ``` #!/bin/bash #your bash code python -c " #your py code " ``` vs ``` python - <<DOC #your py code DOC ``` I checked the web but couldn't compile the bits around the topic. Do you think one i...
2015/06/08
[ "https://Stackoverflow.com/questions/30702519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3598271/" ]
The main flaw of using a here document is that the script's standard input will be the here document. So if you have a script which wants to process its standard input, `python -c` is pretty much your only option. On the other hand, using `python -c '...'` ties up the single-quote for the shell's needs, so you can onl...
How to use here-docs with input =============================== [tripleee's answer](https://stackoverflow.com/a/30703682/1136208) has all the details, but there's Unix tricks to work around this limitation: > > So if you have a script which wants to process its standard input, `python -c` is pretty much your only op...
30,702,519
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between: ``` #!/bin/bash #your bash code python -c " #your py code " ``` vs ``` python - <<DOC #your py code DOC ``` I checked the web but couldn't compile the bits around the topic. Do you think one i...
2015/06/08
[ "https://Stackoverflow.com/questions/30702519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3598271/" ]
If you prefer to use `python -c '...'` without having to escape with the double-quotes you can first load the code in a bash variable using here-documents: ``` read -r -d '' CMD << '--END' print ("'quoted'") --END python -c "$CMD" ``` The python code is loaded verbatim into the CMD variable and there's no need to es...
How to use here-docs with input =============================== [tripleee's answer](https://stackoverflow.com/a/30703682/1136208) has all the details, but there's Unix tricks to work around this limitation: > > So if you have a script which wants to process its standard input, `python -c` is pretty much your only op...
30,702,519
I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between: ``` #!/bin/bash #your bash code python -c " #your py code " ``` vs ``` python - <<DOC #your py code DOC ``` I checked the web but couldn't compile the bits around the topic. Do you think one i...
2015/06/08
[ "https://Stackoverflow.com/questions/30702519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3598271/" ]
If you are using bash, you can avoid heredoc problems if you apply a little bit more of boilerplate: ``` python <(cat <<EoF name = input() print(f'hello, {name}!') EoF ) ``` This will let you run your embedded Python script without you giving up the standard input. The overhead is mostly the same of using `cmda | ...
How to use here-docs with input =============================== [tripleee's answer](https://stackoverflow.com/a/30703682/1136208) has all the details, but there's Unix tricks to work around this limitation: > > So if you have a script which wants to process its standard input, `python -c` is pretty much your only op...