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
60,577,610
I have a Post object with comments and I am trying to send ajax requests in a while loop to check if there have been new comments created, and if there were, add them to the DOM. How can you achieve that in django? Here are my models: ```py class Post(models.Model): name = models.CharField(max_length=255) da...
2020/03/07
[ "https://Stackoverflow.com/questions/60577610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11804213/" ]
The [merge function](https://www.apollographql.com/docs/react/caching/cache-field-behavior/#the-merge-function) in cache type policies is what you are looking for. It allows you to define a custom strategy for writing incoming data into the cache. When creating the cache you can define how to write specific fields. Le...
Try this one: ``` const { loading, error, data } = useQuery(GET_COMMENTS, { onCompleted: data => { // Do changes here } }); ``` You can check it here <https://www.apollographql.com/docs/react/api/react/hooks/>
60,577,610
I have a Post object with comments and I am trying to send ajax requests in a while loop to check if there have been new comments created, and if there were, add them to the DOM. How can you achieve that in django? Here are my models: ```py class Post(models.Model): name = models.CharField(max_length=255) da...
2020/03/07
[ "https://Stackoverflow.com/questions/60577610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11804213/" ]
The [merge function](https://www.apollographql.com/docs/react/caching/cache-field-behavior/#the-merge-function) in cache type policies is what you are looking for. It allows you to define a custom strategy for writing incoming data into the cache. When creating the cache you can define how to write specific fields. Le...
You can call your transformer function inside `onCompleted` and use its result as a state variable. ``` const [myData, setMyData] = useState([]); const { loading } = useQuery(GET_DATA_QUERY, { variables: { options: { limit: 20 } }, onCompleted: (response) => { const transformed = tranformData(r...
4,296,570
I'm a webdeveloper and I have a django project that I need to work on. I am running mac OSX 10.6.5 on a macbook pro. I used macports to install django and python 2.6. I now have some sort of problem, possibly related to my PATH / PYTHONPATH that prevents me from running django. In terminal echo $PATH gives: ``` ech...
2010/11/28
[ "https://Stackoverflow.com/questions/4296570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522909/" ]
First, Macports writes the file ~/.profile to set its PATH variables. If you have created a ~/.bash\_profile file then ~/.profile will be **ignored**. You will have to copy the contents over. To see what python version Macports has selected use: ``` port select --list python ``` which will show you something like t...
Is that really the Python interpreter installed by macports? 2.6.1 smells like the Apple provided one to me (2.6.1 is quite old). try, ``` which python ``` As an aside, I wouldn't install Django using macports. EDIT: Macports installed 2.6.6, the problem is the apple provided python is earlier on your path. ``` ...
4,296,570
I'm a webdeveloper and I have a django project that I need to work on. I am running mac OSX 10.6.5 on a macbook pro. I used macports to install django and python 2.6. I now have some sort of problem, possibly related to my PATH / PYTHONPATH that prevents me from running django. In terminal echo $PATH gives: ``` ech...
2010/11/28
[ "https://Stackoverflow.com/questions/4296570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522909/" ]
First, Macports writes the file ~/.profile to set its PATH variables. If you have created a ~/.bash\_profile file then ~/.profile will be **ignored**. You will have to copy the contents over. To see what python version Macports has selected use: ``` port select --list python ``` which will show you something like t...
Both Python 2.6.1 and 2.6.6 should work fine with django. But if you want to use 2.6.6, just add the location of that to your PATH variable now that you've taken the older python off of your path. To get Django working, try putting the location of django on your PYTHONPATH. On a mac, if django is installed in /Library...
4,296,570
I'm a webdeveloper and I have a django project that I need to work on. I am running mac OSX 10.6.5 on a macbook pro. I used macports to install django and python 2.6. I now have some sort of problem, possibly related to my PATH / PYTHONPATH that prevents me from running django. In terminal echo $PATH gives: ``` ech...
2010/11/28
[ "https://Stackoverflow.com/questions/4296570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522909/" ]
First, Macports writes the file ~/.profile to set its PATH variables. If you have created a ~/.bash\_profile file then ~/.profile will be **ignored**. You will have to copy the contents over. To see what python version Macports has selected use: ``` port select --list python ``` which will show you something like t...
I had the same problem. Turns out, after running ``` sudo port install py26-django ``` You have two different python environments. You end up python2.6 installed and symlinked from /opt/local/bin/python2.6, but this directory doesn't have "python", just "python2.6". So when you run "python", you still pick up the d...
64,698,542
The Nvidia model is showing error for strides, even if I initialize them to the default value of (1,1) I am using 'strides' as a replacement for the 'subsample' argument in previous versions of keras can someone explain the new syntax of using them. ``` def nvidia_model(): model = Sequential() model.add(Conv2D(24,...
2020/11/05
[ "https://Stackoverflow.com/questions/64698542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13301154/" ]
I never worked with `tensorflow`, but according to the documentation of [`Conv2D`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D) it's defined as ``` tf.keras.layers.Conv2D( filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), groups=1, activation=N...
``` model.add(Conv2D(24,5,5, strides = (2,2), input_shape= (66,200,3), activation='relu')) model.add(Conv2D(36,5,5, strides = (2,2), activation = 'relu')) model.add(Conv2D(48,5,5, strides = (2,2), activation = 'relu')) ``` For these lines use parentheses like the following example ``` model.add(Conv2D(24,(5,5), stri...
74,416,745
I have been successfully using Google Build for continuous integration with Google Cloud Run for the Django Application. However recently psycop2-binary started giving errors as below ``` Step #0 - "Buildpack": ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 202.7/202.7 kB 28.3 MB/s eta 0:00:00 Step #0 - "Buildpack": C...
2022/11/12
[ "https://Stackoverflow.com/questions/74416745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342009/" ]
In addition to your answer @london\_utku for new feature in psycopg 2.9.5 * Add support for Python 3.11. * Add support for rowcount in MERGE statements in binary packages (ticket #1497). * Wheel package compiled against OpenSSL 1.1.1r and PostgreSQL 15 libpq. You can also review all the Release notes for [Psycopg 2.9...
Updated psycopg2-binary to 2.9.5, and the situation is resolved.
34,357,513
I love python one liners: ``` u = payload.get("actor", {}).get("username", "") ``` Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine. Problem o...
2015/12/18
[ "https://Stackoverflow.com/questions/34357513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1222167/" ]
Why not use an Exception: ``` try: u = payload.get("actor", {}).get("username", "") except AttributeError: u = "" ```
If you really need to do it in 1 line, you'll have to implement the functionality yourself. Which is worth doing if you use this semantics many times in your program. There are two ways to do it: function or custom dictionary-like object for `payload`. 1) Function handles the case of `actor` being not a `dict`. It ca...
34,357,513
I love python one liners: ``` u = payload.get("actor", {}).get("username", "") ``` Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine. Problem o...
2015/12/18
[ "https://Stackoverflow.com/questions/34357513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1222167/" ]
### Using EAFP As xnx suggested, you can take advantage of the following python paradigm: > > [Easier to ask for forgiveness than permission](https://docs.python.org/3/glossary.html#term-eafp) > > > you can use it on `KeyError`s as well: ``` try: u = payload["actor"]["username"] except (AttributeError, KeyE...
Why not use an Exception: ``` try: u = payload.get("actor", {}).get("username", "") except AttributeError: u = "" ```
34,357,513
I love python one liners: ``` u = payload.get("actor", {}).get("username", "") ``` Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine. Problem o...
2015/12/18
[ "https://Stackoverflow.com/questions/34357513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1222167/" ]
Why not use an Exception: ``` try: u = payload.get("actor", {}).get("username", "") except AttributeError: u = "" ```
The answer hege\_hegedus gave is correct, however there's one caveat in that exception handling is a lot slower than going through if..else statement. For example if you're iterating over thousands of `payload` object and an actor entry is only occasionally not a dictionary, this code is perfectly valid. However if y...
34,357,513
I love python one liners: ``` u = payload.get("actor", {}).get("username", "") ``` Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine. Problem o...
2015/12/18
[ "https://Stackoverflow.com/questions/34357513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1222167/" ]
### Using EAFP As xnx suggested, you can take advantage of the following python paradigm: > > [Easier to ask for forgiveness than permission](https://docs.python.org/3/glossary.html#term-eafp) > > > you can use it on `KeyError`s as well: ``` try: u = payload["actor"]["username"] except (AttributeError, KeyE...
If you really need to do it in 1 line, you'll have to implement the functionality yourself. Which is worth doing if you use this semantics many times in your program. There are two ways to do it: function or custom dictionary-like object for `payload`. 1) Function handles the case of `actor` being not a `dict`. It ca...
34,357,513
I love python one liners: ``` u = payload.get("actor", {}).get("username", "") ``` Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine. Problem o...
2015/12/18
[ "https://Stackoverflow.com/questions/34357513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1222167/" ]
The answer hege\_hegedus gave is correct, however there's one caveat in that exception handling is a lot slower than going through if..else statement. For example if you're iterating over thousands of `payload` object and an actor entry is only occasionally not a dictionary, this code is perfectly valid. However if y...
If you really need to do it in 1 line, you'll have to implement the functionality yourself. Which is worth doing if you use this semantics many times in your program. There are two ways to do it: function or custom dictionary-like object for `payload`. 1) Function handles the case of `actor` being not a `dict`. It ca...
34,357,513
I love python one liners: ``` u = payload.get("actor", {}).get("username", "") ``` Problem I face is, I have no control over what 'payload' contains, other than knowing it is a dictionary. So, if 'payload' does not have "actor", or it does and actor does or doesn't have "username", this one-liner is fine. Problem o...
2015/12/18
[ "https://Stackoverflow.com/questions/34357513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1222167/" ]
### Using EAFP As xnx suggested, you can take advantage of the following python paradigm: > > [Easier to ask for forgiveness than permission](https://docs.python.org/3/glossary.html#term-eafp) > > > you can use it on `KeyError`s as well: ``` try: u = payload["actor"]["username"] except (AttributeError, KeyE...
The answer hege\_hegedus gave is correct, however there's one caveat in that exception handling is a lot slower than going through if..else statement. For example if you're iterating over thousands of `payload` object and an actor entry is only occasionally not a dictionary, this code is perfectly valid. However if y...
71,998,895
I'm trying to setup Pipenv on Ubuntu 22.04 LTS and I used: ``` sudo apt install pipenv ``` but I get an error: ``` FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.local/share/virtualenvs/hello-JDpq8NmY/bin/python' ``` I tried to update pip with: ``` curl -sS https://bootstrap.pypa.io/get-pip....
2022/04/25
[ "https://Stackoverflow.com/questions/71998895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12009223/" ]
Finally, I have caught the issue. You are editing in admin panel and I was sharing code for front end. Please try below steps for admin: Step 1 - file classes/Address.php ``` 'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 255], ``` Change this to **isAnything**...
Go to the file **classes/Address.php** file: ``` 'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isCustomerName', 'required' => true, 'size' => 32), ``` to : ``` 'lastname' =>array('type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 32), ``` validate to **isAnythi...
71,998,895
I'm trying to setup Pipenv on Ubuntu 22.04 LTS and I used: ``` sudo apt install pipenv ``` but I get an error: ``` FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.local/share/virtualenvs/hello-JDpq8NmY/bin/python' ``` I tried to update pip with: ``` curl -sS https://bootstrap.pypa.io/get-pip....
2022/04/25
[ "https://Stackoverflow.com/questions/71998895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12009223/" ]
Finally, I have caught the issue. You are editing in admin panel and I was sharing code for front end. Please try below steps for admin: Step 1 - file classes/Address.php ``` 'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 255], ``` Change this to **isAnything**...
Thanks for sharing the files. I have resolved the case. You need to modify the classes/form/CustomerAddressForm.php line 229 ``` $isValid &= $this->validateField('lastname', 'isName', $this->translator->trans( 'Invalid name', [], 'Shop.Forms.Errors' )); ``` Change to: ``...
71,998,895
I'm trying to setup Pipenv on Ubuntu 22.04 LTS and I used: ``` sudo apt install pipenv ``` but I get an error: ``` FileNotFoundError: [Errno 2] No such file or directory: '/home/foo/.local/share/virtualenvs/hello-JDpq8NmY/bin/python' ``` I tried to update pip with: ``` curl -sS https://bootstrap.pypa.io/get-pip....
2022/04/25
[ "https://Stackoverflow.com/questions/71998895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12009223/" ]
Finally, I have caught the issue. You are editing in admin panel and I was sharing code for front end. Please try below steps for admin: Step 1 - file classes/Address.php ``` 'lastname' => ['type' => self::TYPE_STRING, 'validate' => 'isAnything', 'required' => true, 'size' => 255], ``` Change this to **isAnything**...
I want to do this good with override. I have an issue with override this class. I have created module to override but it is not working. There is a way to override this without editing core files? ``` services: _defaults: public: true form.type.customer_address: class: 'Playdev\PrestaShopBundl...
2,014,767
I've got a python function that should loop through a tuple of coordinates and print their contents: ``` def do(coordList): for element in coordList: print element y=((5,5),(4,4)) x=((5,5)) ``` When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through ...
2010/01/06
[ "https://Stackoverflow.com/questions/2014767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211791/" ]
Use a trailing comma for singleton tuples. ``` x = ((5, 5),) ```
``` x=((5,5),) ``` (*x*) is an expression (*x*,) is a singleton tuple.
2,014,767
I've got a python function that should loop through a tuple of coordinates and print their contents: ``` def do(coordList): for element in coordList: print element y=((5,5),(4,4)) x=((5,5)) ``` When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through ...
2010/01/06
[ "https://Stackoverflow.com/questions/2014767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211791/" ]
Use a trailing comma for singleton tuples. ``` x = ((5, 5),) ```
This is an old and infuriating quirk of python syntax. You have to include a trailing comma to make Python see a tuple: ``` x = ((5,5),) ```
2,014,767
I've got a python function that should loop through a tuple of coordinates and print their contents: ``` def do(coordList): for element in coordList: print element y=((5,5),(4,4)) x=((5,5)) ``` When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through ...
2010/01/06
[ "https://Stackoverflow.com/questions/2014767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211791/" ]
Use a trailing comma for singleton tuples. ``` x = ((5, 5),) ```
You need to add a comma after your first tuple. `((5,5),)` should work.
2,014,767
I've got a python function that should loop through a tuple of coordinates and print their contents: ``` def do(coordList): for element in coordList: print element y=((5,5),(4,4)) x=((5,5)) ``` When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through ...
2010/01/06
[ "https://Stackoverflow.com/questions/2014767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211791/" ]
Use a trailing comma for singleton tuples. ``` x = ((5, 5),) ```
Simply add a comma: ``` x=((5,5),) ```
2,014,767
I've got a python function that should loop through a tuple of coordinates and print their contents: ``` def do(coordList): for element in coordList: print element y=((5,5),(4,4)) x=((5,5)) ``` When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through ...
2010/01/06
[ "https://Stackoverflow.com/questions/2014767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211791/" ]
``` x=((5,5),) ``` (*x*) is an expression (*x*,) is a singleton tuple.
This is an old and infuriating quirk of python syntax. You have to include a trailing comma to make Python see a tuple: ``` x = ((5,5),) ```
2,014,767
I've got a python function that should loop through a tuple of coordinates and print their contents: ``` def do(coordList): for element in coordList: print element y=((5,5),(4,4)) x=((5,5)) ``` When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through ...
2010/01/06
[ "https://Stackoverflow.com/questions/2014767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211791/" ]
``` x=((5,5),) ``` (*x*) is an expression (*x*,) is a singleton tuple.
You need to add a comma after your first tuple. `((5,5),)` should work.
2,014,767
I've got a python function that should loop through a tuple of coordinates and print their contents: ``` def do(coordList): for element in coordList: print element y=((5,5),(4,4)) x=((5,5)) ``` When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through ...
2010/01/06
[ "https://Stackoverflow.com/questions/2014767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211791/" ]
``` x=((5,5),) ``` (*x*) is an expression (*x*,) is a singleton tuple.
Simply add a comma: ``` x=((5,5),) ```
13,276,847
I'm trying to add commas to floats for display to end users of my application on GAE. The numbers come from json and are part of a 10 item query with 2 times each (aka 20 numbers per page view). For eg. ``` "total_reach": 276160.0, "total_reach": 500160.0 ``` I'm using the python GAE SDK 1.7.3 template system and s...
2012/11/07
[ "https://Stackoverflow.com/questions/13276847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1807085/" ]
``` ids = $("tr.selectON td[id]").map(function() { return this.id; }).get(); ``` Documentations : **To get elements with `id` attribute** <http://api.jquery.com/attribute-contains-prefix-selector/> **To filter id attribute** <http://api.jquery.com/map/> **To convert result into array** <http://api.jquery.com/get/...
You can make it simpler, cant speak to the JQuery performance though: ``` ids =[] $('tr.selectON td[id^=""]').each( function() { ids.push( this.id ) }); ``` "this" in the function is already a dom object, so you have direct access to its id.
49,561,543
I'm interested in getting a mapping of country codes to international phone number prefixes, like so: ``` {'US': '+1', 'GB': '+44', 'DE': '+49', ...} ``` One library that probably contains this information is [`python-phonenumbers`](https://github.com/daviddrysdale/python-phonenumbers). However, after a quick perusa...
2018/03/29
[ "https://Stackoverflow.com/questions/49561543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
You can get the mapping you want using [`pycountry`](https://pypi.python.org/pypi/pycountry) and [`phonenumbers`](https://pypi.python.org/pypi/phonenumbers), along with a simple dictionary comprehension: ``` import phonenumbers as pn import pycountry dct = {c.alpha_2: pn.country_code_for_region(c.alpha_2) for c in py...
I have just found a python library that must be perfect for your problem. It's called PhoneISO3166. This is the github link: [GitHub phoneiso3166](https://github.com/onlinecity/phone-iso3166/)
47,271,662
I would like to compute an RBF or "Gaussian" kernel for a data matrix `X` with `n` rows and `d` columns. The resulting square kernel matrix is given by: ``` K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2) ``` `var` and `gamma` are scalars. What is the fastest way to do this in python?
2017/11/13
[ "https://Stackoverflow.com/questions/47271662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475712/" ]
I am going to present four different methods for computing such a kernel, followed by a comparison of their run-time. Using pure numpy ================ Here, I use the fact that `||x-y||^2 = ||x||^2 + ||y||^2 - 2 * x^T * y`. ```py import numpy as np X_norm = np.sum(X ** 2, axis = -1) K = var * np.exp(-gamma * (X_no...
In the case that you are evaluating X against a high number of gammas, it is useful to save the negative pairwise distances matrix using the tricks done by @Callidior and @Divakar. ``` from numpy import exp, matmul, power, einsum, dot from scipy.linalg.blas import sgemm from numexpr import evaluate def pdist2(X): ...
47,271,662
I would like to compute an RBF or "Gaussian" kernel for a data matrix `X` with `n` rows and `d` columns. The resulting square kernel matrix is given by: ``` K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2) ``` `var` and `gamma` are scalars. What is the fastest way to do this in python?
2017/11/13
[ "https://Stackoverflow.com/questions/47271662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475712/" ]
I am going to present four different methods for computing such a kernel, followed by a comparison of their run-time. Using pure numpy ================ Here, I use the fact that `||x-y||^2 = ||x||^2 + ||y||^2 - 2 * x^T * y`. ```py import numpy as np X_norm = np.sum(X ** 2, axis = -1) K = var * np.exp(-gamma * (X_no...
The NumPy solution with a given X, Y and gamma would be: ``` import numpy as np def rbf_kernel(X, Y, gamma): X_norm = np.sum(X ** 2, axis=-1) Y_norm = np.sum(Y ** 2, axis=-1) K = np.exp(-gamma * (X_norm[:, None] + Y_norm[None, :] - 2 * np.dot(X, Y.T))) return K ```
47,271,662
I would like to compute an RBF or "Gaussian" kernel for a data matrix `X` with `n` rows and `d` columns. The resulting square kernel matrix is given by: ``` K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2) ``` `var` and `gamma` are scalars. What is the fastest way to do this in python?
2017/11/13
[ "https://Stackoverflow.com/questions/47271662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475712/" ]
Well you are doing a lot of optimizations in your [`answer post`](https://stackoverflow.com/a/47271663/3293881). I would like to add few more (mostly tweaks). I would build upon the winner from the answer post, which seems to be `numexpr` based on. ### Tweak #1 First off, `np.sum(X ** 2, axis = -1)` could be optimize...
In the case that you are evaluating X against a high number of gammas, it is useful to save the negative pairwise distances matrix using the tricks done by @Callidior and @Divakar. ``` from numpy import exp, matmul, power, einsum, dot from scipy.linalg.blas import sgemm from numexpr import evaluate def pdist2(X): ...
47,271,662
I would like to compute an RBF or "Gaussian" kernel for a data matrix `X` with `n` rows and `d` columns. The resulting square kernel matrix is given by: ``` K[i,j] = var * exp(-gamma * ||X[i] - X[j]||^2) ``` `var` and `gamma` are scalars. What is the fastest way to do this in python?
2017/11/13
[ "https://Stackoverflow.com/questions/47271662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475712/" ]
Well you are doing a lot of optimizations in your [`answer post`](https://stackoverflow.com/a/47271663/3293881). I would like to add few more (mostly tweaks). I would build upon the winner from the answer post, which seems to be `numexpr` based on. ### Tweak #1 First off, `np.sum(X ** 2, axis = -1)` could be optimize...
The NumPy solution with a given X, Y and gamma would be: ``` import numpy as np def rbf_kernel(X, Y, gamma): X_norm = np.sum(X ** 2, axis=-1) Y_norm = np.sum(Y ** 2, axis=-1) K = np.exp(-gamma * (X_norm[:, None] + Y_norm[None, :] - 2 * np.dot(X, Y.T))) return K ```
17,890,896
I have 15 lines in a log file and i want to read the 4th and 10 th line for example through python and display them on output saying this string is found : ``` abc def aaa aaa aasd dsfsfs dssfsd sdfsds sfdsf ssddfs sdsf f dsf s d ``` please suggest through code how to achieve this in python . just to elaborate more...
2013/07/26
[ "https://Stackoverflow.com/questions/17890896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2615729/" ]
Here you go (untested): ``` - (int)getRank:(NSString *passedString) { if([passedString isEqualToString:@"randomcard"]){ return YES; } else { return NO; } } ``` I suggest you learn Objective-C first. This is a very basic question.
To begin, NSString (the iOS implementation of String) goes something like this: ``` NSString str = @"Some STR"; ``` or ``` NSString = [NSString initWithFormat:@"Hello %@", "Hi there"]]; ```
17,890,896
I have 15 lines in a log file and i want to read the 4th and 10 th line for example through python and display them on output saying this string is found : ``` abc def aaa aaa aasd dsfsfs dssfsd sdfsds sfdsf ssddfs sdsf f dsf s d ``` please suggest through code how to achieve this in python . just to elaborate more...
2013/07/26
[ "https://Stackoverflow.com/questions/17890896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2615729/" ]
``` + (int)getRank:(NSString *)passedString { return [passedString isEqualToString:@"randomcard"] ? 1 : 0; } ``` I use the "+" symbol because you had it defined as "static" in your Java code and the equivalent in Objective-C are class methods. So, if you call in Java: `int rank = Class.getRank("some string");` ...
To begin, NSString (the iOS implementation of String) goes something like this: ``` NSString str = @"Some STR"; ``` or ``` NSString = [NSString initWithFormat:@"Hello %@", "Hi there"]]; ```
17,890,896
I have 15 lines in a log file and i want to read the 4th and 10 th line for example through python and display them on output saying this string is found : ``` abc def aaa aaa aasd dsfsfs dssfsd sdfsds sfdsf ssddfs sdsf f dsf s d ``` please suggest through code how to achieve this in python . just to elaborate more...
2013/07/26
[ "https://Stackoverflow.com/questions/17890896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2615729/" ]
Here you go (untested): ``` - (int)getRank:(NSString *passedString) { if([passedString isEqualToString:@"randomcard"]){ return YES; } else { return NO; } } ``` I suggest you learn Objective-C first. This is a very basic question.
``` + (int)getRank:(NSString *)passedString { return [passedString isEqualToString:@"randomcard"] ? 1 : 0; } ``` I use the "+" symbol because you had it defined as "static" in your Java code and the equivalent in Objective-C are class methods. So, if you call in Java: `int rank = Class.getRank("some string");` ...
67,241,815
I tried writing a simple merge and sort function in python and got stuck after getting the following error- ``` List out of range. ``` I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below- ``` def merge(lst1, lst2): # Gets two sorted lists and returns one m...
2021/04/24
[ "https://Stackoverflow.com/questions/67241815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15753999/" ]
Your problem is the while condition: ``` while i < len1 or j < len2: ``` it should be `and` - if either of the conditoins are not true, you simple append the remainder of the non-empty list to your result and you are done. Your current code still enters the while-body and checks `if lst1[i] < lst2[j]:` if one of th...
Here are the values for i, j just before that `if` condition- ``` 0 0 0 1 1 1 1 2 2 2 3 2 4 2 4 3 5 3 ``` When any of the lists is traversed till the end, it throws `index out of range error`. **Solution-** Instead of using `or` condition, use `and` condition and append the remaining list elements at the end of th...
67,241,815
I tried writing a simple merge and sort function in python and got stuck after getting the following error- ``` List out of range. ``` I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below- ``` def merge(lst1, lst2): # Gets two sorted lists and returns one m...
2021/04/24
[ "https://Stackoverflow.com/questions/67241815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15753999/" ]
Your problem is the while condition: ``` while i < len1 or j < len2: ``` it should be `and` - if either of the conditoins are not true, you simple append the remainder of the non-empty list to your result and you are done. Your current code still enters the while-body and checks `if lst1[i] < lst2[j]:` if one of th...
As suggested by other techies you can modify and run the program but you are simply increasing the time complexity of your program which you could have done in two lines. * Just extend the list1 elements like ``` list1.extend(list2) ``` * once the elements are into the list1 ``` print(set(sorted(list1))) ```
67,241,815
I tried writing a simple merge and sort function in python and got stuck after getting the following error- ``` List out of range. ``` I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below- ``` def merge(lst1, lst2): # Gets two sorted lists and returns one m...
2021/04/24
[ "https://Stackoverflow.com/questions/67241815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15753999/" ]
Your problem is the while condition: ``` while i < len1 or j < len2: ``` it should be `and` - if either of the conditoins are not true, you simple append the remainder of the non-empty list to your result and you are done. Your current code still enters the while-body and checks `if lst1[i] < lst2[j]:` if one of th...
First of all, Your logic is wrong! You are picking the lower numbers and putting them into the list. but what about the biggest number of all? You will be stuck there! Because you will never pick the last one! I changed the logic. Instead of counting up the iterators, I removed the picked ones! and when one list got e...
67,241,815
I tried writing a simple merge and sort function in python and got stuck after getting the following error- ``` List out of range. ``` I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below- ``` def merge(lst1, lst2): # Gets two sorted lists and returns one m...
2021/04/24
[ "https://Stackoverflow.com/questions/67241815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15753999/" ]
As suggested by other techies you can modify and run the program but you are simply increasing the time complexity of your program which you could have done in two lines. * Just extend the list1 elements like ``` list1.extend(list2) ``` * once the elements are into the list1 ``` print(set(sorted(list1))) ```
Here are the values for i, j just before that `if` condition- ``` 0 0 0 1 1 1 1 2 2 2 3 2 4 2 4 3 5 3 ``` When any of the lists is traversed till the end, it throws `index out of range error`. **Solution-** Instead of using `or` condition, use `and` condition and append the remaining list elements at the end of th...
67,241,815
I tried writing a simple merge and sort function in python and got stuck after getting the following error- ``` List out of range. ``` I would appreciate if you could help me fix it and figure out how to avoid it. I have added the code below- ``` def merge(lst1, lst2): # Gets two sorted lists and returns one m...
2021/04/24
[ "https://Stackoverflow.com/questions/67241815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15753999/" ]
First of all, Your logic is wrong! You are picking the lower numbers and putting them into the list. but what about the biggest number of all? You will be stuck there! Because you will never pick the last one! I changed the logic. Instead of counting up the iterators, I removed the picked ones! and when one list got e...
Here are the values for i, j just before that `if` condition- ``` 0 0 0 1 1 1 1 2 2 2 3 2 4 2 4 3 5 3 ``` When any of the lists is traversed till the end, it throws `index out of range error`. **Solution-** Instead of using `or` condition, use `and` condition and append the remaining list elements at the end of th...
43,753,657
I am a beginner in python and I am using an older version of anaconda which has the 3.5.2 version of python, because I would like to use tensorflow with it. I have some outdated packages that I would like to update with "conda update all". Is there a way to do this without updating python from 3.5 to 3.6, which is inco...
2017/05/03
[ "https://Stackoverflow.com/questions/43753657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7955849/" ]
You can either update them all manually `conda update yourpackage` ...or you could update them all `conda update --all`, and then downgrade python again with `conda install python=3.5.2`.
Another simple method: `conda update --all python=3.5.2` Replace the python version with your currently installed version. This will update all packages, and since the target version for `python` is already installed, it will not be updated. This also works with multiple packages: `conda update all python=3.5.2 spyder...
43,753,657
I am a beginner in python and I am using an older version of anaconda which has the 3.5.2 version of python, because I would like to use tensorflow with it. I have some outdated packages that I would like to update with "conda update all". Is there a way to do this without updating python from 3.5 to 3.6, which is inco...
2017/05/03
[ "https://Stackoverflow.com/questions/43753657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7955849/" ]
Short Answer ============ ```sh conda update --all --dry-run 2>/dev/null | grep -Fe '-->' | cut -d' ' -f3 | grep -ve 'python' | xargs conda update ``` --- Long Answer =========== Step 1: Dry run to check packages to be updated ----------------------------------------------- **Command** ```sh cond...
Another simple method: `conda update --all python=3.5.2` Replace the python version with your currently installed version. This will update all packages, and since the target version for `python` is already installed, it will not be updated. This also works with multiple packages: `conda update all python=3.5.2 spyder...
33,582,766
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code: ``` Process finished with exit code -1073741515 (0xC0000135) ``` I don't get any other results - not even from "print" commands at the beginning of the file. I have...
2015/11/07
[ "https://Stackoverflow.com/questions/33582766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3909896/" ]
I encountered the same error when running .py in PyCharm on Windows. Inspired by <https://thenewboston.com/forum/topic.php?id=10088>, I uninstalled and reinstalled Python. When reinstalling, I checked the `ADD PYTHON TO THE PATH` Option. After recreating the virtual environment in PyCharm, the error was gone. **Update...
I encountered this error in my code as well, in my case the problem was sharing `pickle` which produced in Unix machine one a Windows one.
33,582,766
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code: ``` Process finished with exit code -1073741515 (0xC0000135) ``` I don't get any other results - not even from "print" commands at the beginning of the file. I have...
2015/11/07
[ "https://Stackoverflow.com/questions/33582766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3909896/" ]
I encountered the same error when running .py in PyCharm on Windows. Inspired by <https://thenewboston.com/forum/topic.php?id=10088>, I uninstalled and reinstalled Python. When reinstalling, I checked the `ADD PYTHON TO THE PATH` Option. After recreating the virtual environment in PyCharm, the error was gone. **Update...
\*\*I faced the same situation and the malfunction stems from trying to run both terminal processor and graphical user interfaces. When I clicked the button program stopped running \*\* Solution: I disabled terminal inputs and work with graphics. For example: if you do this ``` entry1=Entry(root,width=10).pack() vari...
33,582,766
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code: ``` Process finished with exit code -1073741515 (0xC0000135) ``` I don't get any other results - not even from "print" commands at the beginning of the file. I have...
2015/11/07
[ "https://Stackoverflow.com/questions/33582766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3909896/" ]
reinstall python – you don't have python33.dll in c:\WINDOWS\system32\ Maybe you have different python versions – look at folders in root of c: If yes, then point to your version of python.exe in pyCharm > Settings > Project Interpreter
I solved it by disabling "**PyQt compatible**" checkbox in the Settings under **Build, Execution, Deployment --> Python Debugger**. After that, it should debug properly.
33,582,766
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code: ``` Process finished with exit code -1073741515 (0xC0000135) ``` I don't get any other results - not even from "print" commands at the beginning of the file. I have...
2015/11/07
[ "https://Stackoverflow.com/questions/33582766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3909896/" ]
reinstall python – you don't have python33.dll in c:\WINDOWS\system32\ Maybe you have different python versions – look at folders in root of c: If yes, then point to your version of python.exe in pyCharm > Settings > Project Interpreter
I got this error in PyCharm after upgrading pyarrow to the most recent version -- 0.16 --- using pip, running the same code I had ran before this update which used pandas read\_parquet specifying the engine="pyarrow" triggering use of this library. After uninstalling and installing the previous version with > > pip ...
33,582,766
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code: ``` Process finished with exit code -1073741515 (0xC0000135) ``` I don't get any other results - not even from "print" commands at the beginning of the file. I have...
2015/11/07
[ "https://Stackoverflow.com/questions/33582766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3909896/" ]
I encountered the same error when running .py in PyCharm on Windows. Inspired by <https://thenewboston.com/forum/topic.php?id=10088>, I uninstalled and reinstalled Python. When reinstalling, I checked the `ADD PYTHON TO THE PATH` Option. After recreating the virtual environment in PyCharm, the error was gone. **Update...
Here is caused it and solution: The computer had two physical processors. The code uses Numba for parallel computations. Upon disabling and re-enabling hyperthreading this issue started. To solve it clear **pycache** folder and run the program.
33,582,766
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code: ``` Process finished with exit code -1073741515 (0xC0000135) ``` I don't get any other results - not even from "print" commands at the beginning of the file. I have...
2015/11/07
[ "https://Stackoverflow.com/questions/33582766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3909896/" ]
reinstall python – you don't have python33.dll in c:\WINDOWS\system32\ Maybe you have different python versions – look at folders in root of c: If yes, then point to your version of python.exe in pyCharm > Settings > Project Interpreter
\*\*I faced the same situation and the malfunction stems from trying to run both terminal processor and graphical user interfaces. When I clicked the button program stopped running \*\* Solution: I disabled terminal inputs and work with graphics. For example: if you do this ``` entry1=Entry(root,width=10).pack() vari...
33,582,766
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code: ``` Process finished with exit code -1073741515 (0xC0000135) ``` I don't get any other results - not even from "print" commands at the beginning of the file. I have...
2015/11/07
[ "https://Stackoverflow.com/questions/33582766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3909896/" ]
I encountered this error in my code as well, in my case the problem was sharing `pickle` which produced in Unix machine one a Windows one.
If you're trying create a .svm use dlib probably the problem is in .xml, some image that you use is cause the problem. Try to create a new .xml putting out a image(any image) or remove that your .xml and test, try this even you find out the image problem. For exemple, the image "treinamento3.jpg" was the problem. I re...
33,582,766
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code: ``` Process finished with exit code -1073741515 (0xC0000135) ``` I don't get any other results - not even from "print" commands at the beginning of the file. I have...
2015/11/07
[ "https://Stackoverflow.com/questions/33582766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3909896/" ]
I got this error in PyCharm after upgrading pyarrow to the most recent version -- 0.16 --- using pip, running the same code I had ran before this update which used pandas read\_parquet specifying the engine="pyarrow" triggering use of this library. After uninstalling and installing the previous version with > > pip ...
Here is caused it and solution: The computer had two physical processors. The code uses Numba for parallel computations. Upon disabling and re-enabling hyperthreading this issue started. To solve it clear **pycache** folder and run the program.
33,582,766
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code: ``` Process finished with exit code -1073741515 (0xC0000135) ``` I don't get any other results - not even from "print" commands at the beginning of the file. I have...
2015/11/07
[ "https://Stackoverflow.com/questions/33582766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3909896/" ]
reinstall python – you don't have python33.dll in c:\WINDOWS\system32\ Maybe you have different python versions – look at folders in root of c: If yes, then point to your version of python.exe in pyCharm > Settings > Project Interpreter
I encountered this error in my code as well, in my case the problem was sharing `pickle` which produced in Unix machine one a Windows one.
33,582,766
I'm running a python script and it used to work (it even does on my other laptop right now) but not on my current computer - I just get the error code: ``` Process finished with exit code -1073741515 (0xC0000135) ``` I don't get any other results - not even from "print" commands at the beginning of the file. I have...
2015/11/07
[ "https://Stackoverflow.com/questions/33582766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3909896/" ]
The error seems to be related to issues in native code (e.g. C/C++) and might be related to issues in loading some dll file. To know which file, the Windows "Event Viewer" is your friend. The "Event Viewer" -> "Windows Logs" -> "Application" feed usually shows one or more rows for each crashed application and one of t...
Here is caused it and solution: The computer had two physical processors. The code uses Numba for parallel computations. Upon disabling and re-enabling hyperthreading this issue started. To solve it clear **pycache** folder and run the program.
12,737,121
This bit is being troublesome.... ``` #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //1 NSString *urlString = @"http://zaphod_beeblebrox.pythonanywhere.com/"; //2 NSURL *url = [NSURL URLWithString:urlString]; //3 NSURLRequest *...
2012/10/04
[ "https://Stackoverflow.com/questions/12737121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1718637/" ]
You asked this same question before, which [I answered](https://stackoverflow.com/a/12720171/1271826). I repeat the relevant portions of that answer below. If there's something that didn't make sense, just leave a comment below. --- I'm guessing you're trying to load a html page in a `UIWebView`? You obviously need a...
' I am trying to use a uiwebview to bring up a web app. If you know of any better way, please let me know!' ``` [theWebView loadRequest:[NSURLRequest requestWithURL:theURL]]; ```
12,737,121
This bit is being troublesome.... ``` #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //1 NSString *urlString = @"http://zaphod_beeblebrox.pythonanywhere.com/"; //2 NSURL *url = [NSURL URLWithString:urlString]; //3 NSURLRequest *...
2012/10/04
[ "https://Stackoverflow.com/questions/12737121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1718637/" ]
You asked this same question before, which [I answered](https://stackoverflow.com/a/12720171/1271826). I repeat the relevant portions of that answer below. If there's something that didn't make sense, just leave a comment below. --- I'm guessing you're trying to load a html page in a `UIWebView`? You obviously need a...
You have 3 different errors. First "(UIWebView)" doesn't mean anything, and secondly, if you had a statement there that did mean something it would need a semicolon after it. Thirdly, there should be a semicolon after NSLog(@"Error: %@", error). It would be better to put some of the code on separate lines for readabili...
27,949,520
how can I do this: in python, how can I do a loop or an if statment, that to get in the loop/ the if statment, you need a function to be called. I mean something like this: ``` if function() *is called*: print('function() is called') ``` thanks
2015/01/14
[ "https://Stackoverflow.com/questions/27949520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4454553/" ]
You should use booleans to handle that: ``` def function(): function.has_been_called = True pass function.has_been_called = False #Actual Code!: if function.has_been_called: print('function()is called') ``` The boolean will now store whether or not the fucntion has been called.
Use a decorator to wrap the function, so that any time the function is called, you get a print, without having to alter your original function ``` def is_called(func): def wrap(): func() print func, "is called" return wrap @is_called def function(): pass if function(): pass #do ``` would print 'fu...
58,932,201
I moved my Gem5 simulations from my system to a server. My system does not have HDF5 libraries, but the server has, and I am met with this error: > > > ``` > /usr/local/lib/python2.7/config/libpython2.7.a(posixmodule.o): In function `posix_tmpnam': > /space/src/Python-2.7/./Modules/posixmodule.c:7275: warning: the ...
2019/11/19
[ "https://Stackoverflow.com/questions/58932201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6346849/" ]
I don't know the root cause of this issue, some one who is working on Gem5 could possibly answer that. But as a workaround, since I have no admin access to the server ,and even then removing a library just for the sake of one build doesn't feel right, I edited the SConstruct file in gem5/, where the environment variab...
In case you run on older system like Debian 10 or Ubuntu 16.04, the errors are due to the fact that the `hdf5` library path is not in default system library path. I solved it by manually (brutally) linking gem5 ... The link flags added are: `-L/usr/lib/x86_64-linux-gnu/hdf5/serial/ -lhdf5_cpp -lhdf5` ```sh g++ -o /ge...
58,932,201
I moved my Gem5 simulations from my system to a server. My system does not have HDF5 libraries, but the server has, and I am met with this error: > > > ``` > /usr/local/lib/python2.7/config/libpython2.7.a(posixmodule.o): In function `posix_tmpnam': > /space/src/Python-2.7/./Modules/posixmodule.c:7275: warning: the ...
2019/11/19
[ "https://Stackoverflow.com/questions/58932201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6346849/" ]
After the resolution of: <https://askubuntu.com/questions/1187343/installation-of-gem5-on-ubuntu-19-10-on-my-laptop-i5-cpu-m520-64bit> in gem5 b383997d4a9c642dd4356bfc4554ac7ae183ae62 (March 2020) the Ubuntu 19.10 (GCC 9) build is working for me: ``` scons -j `nproc` build/ARM/gem5.opt ``` If you find any further bu...
In case you run on older system like Debian 10 or Ubuntu 16.04, the errors are due to the fact that the `hdf5` library path is not in default system library path. I solved it by manually (brutally) linking gem5 ... The link flags added are: `-L/usr/lib/x86_64-linux-gnu/hdf5/serial/ -lhdf5_cpp -lhdf5` ```sh g++ -o /ge...
63,056,197
I'm writing some python code where I need to use generators inside recursive functions. Here is some code I wrote to mimic what I am trying to do. This is attempt 1. ``` def f(): def f2(i): if i > 0: yield i f2(i - 1) yield f2(10) for x in f(): for y in x: print(y)...
2020/07/23
[ "https://Stackoverflow.com/questions/63056197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5927758/" ]
You can think of `yield from` as a for loop which yields every item: ``` for i in f(10): yield i ``` is the same as `yield from f(10)`. In other words, it *yields* the items *from* the given iteratable which in this case is another generator.
`yield from g()` will recurse inside a new generator `g` yielding from each `yield` statement at that generator so ``` def g1(): yield from g2() def g2() for i in range(10): yield i * 2 ``` You can think as if `yield from` in g1 was unrolling `g2` inside of it, expanding to something like this ```...
10,989,297
I have the following PHP code, and for the life of me I can't think of a simple & elegant way to implement around the empty() function in python to check if the index is defined in a list. ``` $counter = 0; $a = array(); for ($i=0;$i<100;$i++){ $i = ($i > 4) ? 0 : $i; if empty($a[$i]){ $a[$i]=array(); } $a...
2012/06/12
[ "https://Stackoverflow.com/questions/10989297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342553/" ]
PHP Arrays and Python lists are not equivalent. PHP Arrays are actually [associative containers](http://php.net/manual/en/language.types.array.php): > > An array in PHP is actually an ordered map. A map is a type that > associates values to keys. This type is optimized for several > different uses; it can be treate...
In the event you were trying to do it with a list, you would have to actually set that index to none, otherwise the element wouldn't be there you'd possibly be trying to check an index past the end of the list. ``` >>> i = [None] >>> i [None] >>> i = [None, None] >>> i [None, None] >>> i[1] is None True ```
10,989,297
I have the following PHP code, and for the life of me I can't think of a simple & elegant way to implement around the empty() function in python to check if the index is defined in a list. ``` $counter = 0; $a = array(); for ($i=0;$i<100;$i++){ $i = ($i > 4) ? 0 : $i; if empty($a[$i]){ $a[$i]=array(); } $a...
2012/06/12
[ "https://Stackoverflow.com/questions/10989297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342553/" ]
PHP Arrays and Python lists are not equivalent. PHP Arrays are actually [associative containers](http://php.net/manual/en/language.types.array.php): > > An array in PHP is actually an ordered map. A map is a type that > associates values to keys. This type is optimized for several > different uses; it can be treate...
``` # variable may not exsists if (variable in vars() or variable in globals()) and variable != "" and variable == False: pass ```
14,049,983
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
2012/12/27
[ "https://Stackoverflow.com/questions/14049983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529981/" ]
If you start an XPath expression with `//`, it begins searching from the root of document. To search relative to a particular element, you should prepend the expression with `.` instead: ``` element2 = driver.find_element_by_xpath("//div[@title='div2']") element2.find_element_by_xpath(".//p[@class='test']").text ```
***Find The Child of any Elements*** ``` parent = browser.find_element(by=By.XPATH,value='value of XPATH of Parents') child=parent.find_elements(by=By.TAG_NAME,value='value of child path') ```
14,049,983
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
2012/12/27
[ "https://Stackoverflow.com/questions/14049983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529981/" ]
If you start an XPath expression with `//`, it begins searching from the root of document. To search relative to a particular element, you should prepend the expression with `.` instead: ``` element2 = driver.find_element_by_xpath("//div[@title='div2']") element2.find_element_by_xpath(".//p[@class='test']").text ```
This is how you search for element or tag in CSS subclass and I believe that it works for multilevel situation as well: Sample HTML: ```html <li class="meta-item"> <span class="label">Posted:</span> <time class="value" datetime="2019-03-22T09:46:24+01:00" pubdate="pubdate">22.03.2019 u 09:46</time> </li> ``` Th...
14,049,983
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
2012/12/27
[ "https://Stackoverflow.com/questions/14049983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529981/" ]
Use the following: ``` element2 = driver.find_element_by_cssselector("css=div[title='div2']") element2.find_element_by_cssselector("p[@class='test']").text ``` Please let me know if you have any problems.
***Find The Child of any Elements*** ``` parent = browser.find_element(by=By.XPATH,value='value of XPATH of Parents') child=parent.find_elements(by=By.TAG_NAME,value='value of child path') ```
14,049,983
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
2012/12/27
[ "https://Stackoverflow.com/questions/14049983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529981/" ]
Use the following: ``` element2 = driver.find_element_by_cssselector("css=div[title='div2']") element2.find_element_by_cssselector("p[@class='test']").text ``` Please let me know if you have any problems.
This is how you search for element or tag in CSS subclass and I believe that it works for multilevel situation as well: Sample HTML: ```html <li class="meta-item"> <span class="label">Posted:</span> <time class="value" datetime="2019-03-22T09:46:24+01:00" pubdate="pubdate">22.03.2019 u 09:46</time> </li> ``` Th...
14,049,983
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
2012/12/27
[ "https://Stackoverflow.com/questions/14049983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529981/" ]
If you start an XPath expression with `//`, it begins searching from the root of document. To search relative to a particular element, you should prepend the expression with `.` instead: ``` element2 = driver.find_element_by_xpath("//div[@title='div2']") element2.find_element_by_xpath(".//p[@class='test']").text ```
Use the following: ``` element2 = driver.find_element_by_cssselector("css=div[title='div2']") element2.find_element_by_cssselector("p[@class='test']").text ``` Please let me know if you have any problems.
14,049,983
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
2012/12/27
[ "https://Stackoverflow.com/questions/14049983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529981/" ]
This is how you search for element or tag in CSS subclass and I believe that it works for multilevel situation as well: Sample HTML: ```html <li class="meta-item"> <span class="label">Posted:</span> <time class="value" datetime="2019-03-22T09:46:24+01:00" pubdate="pubdate">22.03.2019 u 09:46</time> </li> ``` Th...
***Find The Child of any Elements*** ``` parent = browser.find_element(by=By.XPATH,value='value of XPATH of Parents') child=parent.find_elements(by=By.TAG_NAME,value='value of child path') ```
14,049,983
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
2012/12/27
[ "https://Stackoverflow.com/questions/14049983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529981/" ]
If you start an XPath expression with `//`, it begins searching from the root of document. To search relative to a particular element, you should prepend the expression with `.` instead: ``` element2 = driver.find_element_by_xpath("//div[@title='div2']") element2.find_element_by_xpath(".//p[@class='test']").text ```
Chrome Webdriver : ``` element = driver.find_element_by_id("ParentElement") localElement = element.find_element_by_id("ChildElement") print(localElement.text) ```
14,049,983
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
2012/12/27
[ "https://Stackoverflow.com/questions/14049983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529981/" ]
Use the following: ``` element2 = driver.find_element_by_cssselector("css=div[title='div2']") element2.find_element_by_cssselector("p[@class='test']").text ``` Please let me know if you have any problems.
I guess,we need use method "By" from webdriver.common.by when use "driver.find\_element". So...the code must be: ``` from selenium import webdriver driver = webdriver.Firefox() from selenium.webdriver.common.by import By element2 = driver.find_element(By.XPATH, "//div[@title='div2']") element2.find_element(By.XPATH...
14,049,983
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
2012/12/27
[ "https://Stackoverflow.com/questions/14049983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529981/" ]
I guess,we need use method "By" from webdriver.common.by when use "driver.find\_element". So...the code must be: ``` from selenium import webdriver driver = webdriver.Firefox() from selenium.webdriver.common.by import By element2 = driver.find_element(By.XPATH, "//div[@title='div2']") element2.find_element(By.XPATH...
Chrome Webdriver : ``` element = driver.find_element_by_id("ParentElement") localElement = element.find_element_by_id("ChildElement") print(localElement.text) ```
14,049,983
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
2012/12/27
[ "https://Stackoverflow.com/questions/14049983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1529981/" ]
This is how you search for element or tag in CSS subclass and I believe that it works for multilevel situation as well: Sample HTML: ```html <li class="meta-item"> <span class="label">Posted:</span> <time class="value" datetime="2019-03-22T09:46:24+01:00" pubdate="pubdate">22.03.2019 u 09:46</time> </li> ``` Th...
Chrome Webdriver : ``` element = driver.find_element_by_id("ParentElement") localElement = element.find_element_by_id("ChildElement") print(localElement.text) ```
37,371,992
I am trying to split the integers in a series by forward slash by using `rsplit` function of python but it does not work. Original Data ============= ``` date 1/30/2015 1/30/2015 1/30/2015 1/30/2015 1/30/2015 1/30/2015 1/30/2015 1/30/2015 1/30/2015 1/30/2015 ``` expected Data ============= I want to split by '/' ...
2016/05/22
[ "https://Stackoverflow.com/questions/37371992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5157772/" ]
You can use the `str` accessor to use string methods on the series: ``` df["date"].str.rsplit("/") ``` Or to have them in different columns: ``` df["date"].str.rsplit("/", expand = True) ``` With a series, it might be better to work on datetime data: ``` import pandas as pd pd.to_datetime(df["date"]).dt.year Out...
IMO it would be more useful to just convert the string to a `datetime` using [`to_datetime`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html) so you can perform arithmetic operations on it and if you want the year or any other date/time component you can use the vectorised [`dt`](http://pa...
72,542,852
I'm trying to make a discord bot that can read dates from a txt file on my device. ---------------------------------------------------------------------------------- I've read the documentation and looked over similar posts, but I keep running into the same error. Just starting to learn python so please excuse any obv...
2022/06/08
[ "https://Stackoverflow.com/questions/72542852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19296877/" ]
So it seems like I completely mashed up python and nodejs on accident. Not quite sure what I was thinking but that was the issue. --- Simple answer β€” don't mix nodejs and Python.
First of all you should avoid to redefine "list" as this is python keyword. Second, the command is correct and the "open" keyword is built in in native python. So it should work. This exact line works in my python environment (even when overwriting "list"). When you look at the end of the lines of the error message yo...
64,726,961
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given: ``` x= "a sequence of words" x.split(" ",1) ``` I would like to get the string "a"
2020/11/07
[ "https://Stackoverflow.com/questions/64726961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
After the split a list is returned, so use indexing to get the first element: ``` x= "a sequence of words" print(x.split(" ",1)[0]) ```
The most "pythonic" method is an opinion. However any method like split which returns a list you can simply index the list at 0 to get the first item. `a = x.split(" ", 1)[0]`
64,726,961
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given: ``` x= "a sequence of words" x.split(" ",1) ``` I would like to get the string "a"
2020/11/07
[ "https://Stackoverflow.com/questions/64726961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
After the split a list is returned, so use indexing to get the first element: ``` x= "a sequence of words" print(x.split(" ",1)[0]) ```
You can use the first index Example: ```py x.split(" ",1)[0] ```
64,726,961
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given: ``` x= "a sequence of words" x.split(" ",1) ``` I would like to get the string "a"
2020/11/07
[ "https://Stackoverflow.com/questions/64726961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
After the split a list is returned, so use indexing to get the first element: ``` x= "a sequence of words" print(x.split(" ",1)[0]) ```
Wouldn’t this work as well? ``` x.split()[0] ```
64,726,961
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given: ``` x= "a sequence of words" x.split(" ",1) ``` I would like to get the string "a"
2020/11/07
[ "https://Stackoverflow.com/questions/64726961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
Do you mean? where 0 is the index ``` x = "a sequence of words" print(x[0]) ```
The most "pythonic" method is an opinion. However any method like split which returns a list you can simply index the list at 0 to get the first item. `a = x.split(" ", 1)[0]`
64,726,961
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given: ``` x= "a sequence of words" x.split(" ",1) ``` I would like to get the string "a"
2020/11/07
[ "https://Stackoverflow.com/questions/64726961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
Do you mean? where 0 is the index ``` x = "a sequence of words" print(x[0]) ```
You can use the first index Example: ```py x.split(" ",1)[0] ```
64,726,961
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given: ``` x= "a sequence of words" x.split(" ",1) ``` I would like to get the string "a"
2020/11/07
[ "https://Stackoverflow.com/questions/64726961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
Do you mean? where 0 is the index ``` x = "a sequence of words" print(x[0]) ```
Wouldn’t this work as well? ``` x.split()[0] ```
64,726,961
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given: ``` x= "a sequence of words" x.split(" ",1) ``` I would like to get the string "a"
2020/11/07
[ "https://Stackoverflow.com/questions/64726961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
Let's use the variable x you stated, and input the first character from x into another variable y: ``` x = "a sequence of words" y = x[0] ``` If you print y, you'll get the output 'a'. This is because the characters in a string can be indexed just like the items in a list. 0 is the first index, 1 is the second, and ...
The most "pythonic" method is an opinion. However any method like split which returns a list you can simply index the list at 0 to get the first item. `a = x.split(" ", 1)[0]`
64,726,961
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given: ``` x= "a sequence of words" x.split(" ",1) ``` I would like to get the string "a"
2020/11/07
[ "https://Stackoverflow.com/questions/64726961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
Let's use the variable x you stated, and input the first character from x into another variable y: ``` x = "a sequence of words" y = x[0] ``` If you print y, you'll get the output 'a'. This is because the characters in a string can be indexed just like the items in a list. 0 is the first index, 1 is the second, and ...
You can use the first index Example: ```py x.split(" ",1)[0] ```
64,726,961
given a function, like split(" ",1) whats the most pythonic way to take the first element of its output only, for example given: ``` x= "a sequence of words" x.split(" ",1) ``` I would like to get the string "a"
2020/11/07
[ "https://Stackoverflow.com/questions/64726961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792022/" ]
Let's use the variable x you stated, and input the first character from x into another variable y: ``` x = "a sequence of words" y = x[0] ``` If you print y, you'll get the output 'a'. This is because the characters in a string can be indexed just like the items in a list. 0 is the first index, 1 is the second, and ...
Wouldn’t this work as well? ``` x.split()[0] ```
58,638,534
I am very new to python 3(and python in general), and I have decided to try to make a cypher and decypher in my own way as a personal project. The cypher works by generating a random number and multiplying the letters number value by it. It adds all of these multiplied values into a list and then adding the random numb...
2019/10/31
[ "https://Stackoverflow.com/questions/58638534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12301586/" ]
When you use `list` function, it converts the string to `['[', '1', '9', '7', '6', ',', ' ', '1', '9', '9', '5', ',', ' ', '1', '9', ']']` Use instead: ```py dlist = eval(input('Text to be Decyphered:')) ``` `eval` function will convert it to an actual list. You can cross check it: ```py >>>print(type(eval('[1976,...
Try json on your input: ``` import json data = json.loads(the_string) ```
58,638,534
I am very new to python 3(and python in general), and I have decided to try to make a cypher and decypher in my own way as a personal project. The cypher works by generating a random number and multiplying the letters number value by it. It adds all of these multiplied values into a list and then adding the random numb...
2019/10/31
[ "https://Stackoverflow.com/questions/58638534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12301586/" ]
When you use `list` function, it converts the string to `['[', '1', '9', '7', '6', ',', ' ', '1', '9', '9', '5', ',', ' ', '1', '9', ']']` Use instead: ```py dlist = eval(input('Text to be Decyphered:')) ``` `eval` function will convert it to an actual list. You can cross check it: ```py >>>print(type(eval('[1976,...
You have a few problems on your code: 1. randrange(0, 100) -> if you get 0 then your result will all be 0 and won't work 2. Characters are Integers, Multiplication and division you will not always get an integer back so you man need to handle rounding 3. Your input to cypher is a String but the input of decypher is a ...
58,638,534
I am very new to python 3(and python in general), and I have decided to try to make a cypher and decypher in my own way as a personal project. The cypher works by generating a random number and multiplying the letters number value by it. It adds all of these multiplied values into a list and then adding the random numb...
2019/10/31
[ "https://Stackoverflow.com/questions/58638534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12301586/" ]
You have a few problems on your code: 1. randrange(0, 100) -> if you get 0 then your result will all be 0 and won't work 2. Characters are Integers, Multiplication and division you will not always get an integer back so you man need to handle rounding 3. Your input to cypher is a String but the input of decypher is a ...
Try json on your input: ``` import json data = json.loads(the_string) ```
48,957,624
I am very to new to python and trying to translate a bunch of keywords using google API. I have an excel file with 3000 keywords which are mix of english, spanish, german etc. Trying to translate everything to English. However, every time I run my code, I get error at different values. Sometimes, my code give error a...
2018/02/23
[ "https://Stackoverflow.com/questions/48957624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5695920/" ]
Normally this error is due to the character limit of 15K in Googletrans API. JSONDecodeError: Expecting value: line 1 column 1 (char 0) Consider reducing the number of characters.
Which line of your code gives you this error? Look at error trace Let's start with your iterators: it is declared as `i`, but then you use `j`. Then check length of your request. It shouldn't be longer than 5k symbols according to [JSONDecodeError using Google Translate API with Python3](https://stackoverflow.com/qu...
62,719,063
Using beautiful soup and python, I have undertaken some webscraping of the shown website to isolate: the rank, company name and revenue. I would like to show, in an html table that I am rendering using flask and jinja2, the results of the top ten companies in the table, however, the code I have written is just display...
2020/07/03
[ "https://Stackoverflow.com/questions/62719063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5074035/" ]
``` rank=data[0][0] name=data[0][1] revenue=data[0][2] ``` You're setting the rank, name and revenue from a single element (first element of data) I suggest that you try getting changing rank, name and revenue in your html to `{{element[0]}}` and so on, to access the respective data from each element you loop on
Thank you to @mmfallacy above who suggested this answer that I am just fleshing out. It works, but will accept the answer above as he suggested it. Here it is for reference: ``` {% for element in data %} <tr> <th scope="row"></th> <td>{{element[0]}}</td> <td>{{element[1]}}</td> <td>{{eleme...
68,603,298
i am following the django instructions to build a web application hello i have done everthing after the document but this happens Page not found (404) Request Method: GET Request URL: <http://127.0.0.1:8000/hello> Using the URLconf defined in PythonWeb.urls, Django tried these URL patterns, in this order: admin/ The c...
2021/07/31
[ "https://Stackoverflow.com/questions/68603298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16567727/" ]
You have made a silly mistake in `settings.py` file: Remove `/` after `hello`. ``` INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello', ] ```
I tried your code and it worked for me. I did two edits which are: **settings.py:** ```py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello.apps.HelloCo...
39,489,089
This is more or less a follow up question to [Two dimensional color ramp (256x256 matrix) interpolated from 4 corner colors](https://stackoverflow.com/questions/39485178/two-dimensional-color-ramp-256x256-matrix-interpolated-from-4-corner-colors?noredirect=1#comment66289716_39485178) that was profoundly answered by jad...
2016/09/14
[ "https://Stackoverflow.com/questions/39489089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1230358/" ]
First some questions to better clarify your problem: * what kind of interpolation you want: linear/cubic/other ? * What are the points constrains? for example will there be alway just single region encapsulated by these control points or there could be also points inside? For the simple linear interpolation and arbit...
I'm here again (a bit late, sorry,I just found the question) with a fairly short solution using `griddata` from `scipy.interpolate`. That function is meant to do precisely what you want : interpolate values on a grid from just a few points. The issues being the following : with that you won't be able to use fancy weigh...
21,582,358
Trying to find how to execute ipdb (or pdb) commands such as `disable`. Calling the `h` command on `disable` says > > disable bpnumber [bpnumber ...] > Disables the breakpoints given as a space separated list of > bp numbers. > > > So how whould I get those bp numbers? was looking through the list of commands...
2014/02/05
[ "https://Stackoverflow.com/questions/21582358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1037251/" ]
Use the `break` command. Don't add any line numbers and it will list all instead of adding them.
> > info breakpoints > > > or just > > info b > > > lists all breakpoints.
5,214,814
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this: ``` 104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n ``` and so on. How can I use python to write all these numbers to a file in one col...
2011/03/07
[ "https://Stackoverflow.com/questions/5214814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647475/" ]
``` "\n".join("104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n".split()) ```
Replace input\_filename and output\_filename with appropriate values. ``` f = open('input_filename','r') nums = f.read().split() f.close() f = open('output_filename', 'w') f.write('\n'.join(nums)) f.close() ``` [Edit] Reworked example that doesn't load the whole file into memory. It is now very similar to Chinmay Ka...
5,214,814
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this: ``` 104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n ``` and so on. How can I use python to write all these numbers to a file in one col...
2011/03/07
[ "https://Stackoverflow.com/questions/5214814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647475/" ]
The easiest way to do this is probably to use `sed`. But if you must use Python, you need to replace all tab characters with newlines. Try something like this: ``` with open('input_file', 'rb') as infile: with open('output_file', 'wb') as outfile: for line in infile: outfile.write(line.replace(...
Replace input\_filename and output\_filename with appropriate values. ``` f = open('input_filename','r') nums = f.read().split() f.close() f = open('output_filename', 'w') f.write('\n'.join(nums)) f.close() ``` [Edit] Reworked example that doesn't load the whole file into memory. It is now very similar to Chinmay Ka...
5,214,814
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this: ``` 104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n ``` and so on. How can I use python to write all these numbers to a file in one col...
2011/03/07
[ "https://Stackoverflow.com/questions/5214814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647475/" ]
The easiest way to do this is probably to use `sed`. But if you must use Python, you need to replace all tab characters with newlines. Try something like this: ``` with open('input_file', 'rb') as infile: with open('output_file', 'wb') as outfile: for line in infile: outfile.write(line.replace(...
``` "\n".join("104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n".split()) ```
5,214,814
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this: ``` 104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n ``` and so on. How can I use python to write all these numbers to a file in one col...
2011/03/07
[ "https://Stackoverflow.com/questions/5214814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647475/" ]
``` "\n".join("104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n".split()) ```
There are multiple ways of tackling this problem. You could use `string.split` and `string.join`, but that seems inefficient, since you'd be converting a string into a tuple and back into a string. Using regex, we replace one or more whitespace characters with a newline. The metacharacter `\s` represents any whitespa...
5,214,814
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this: ``` 104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n ``` and so on. How can I use python to write all these numbers to a file in one col...
2011/03/07
[ "https://Stackoverflow.com/questions/5214814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647475/" ]
``` "\n".join("104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n".split()) ```
If your file is small, you can use `file.readlines()` to read all the lines into memory: ``` with open('input.txt', 'r') as fin: for row in [l.split() for l in fin.readlines()]: for col in row: print col ``` If the file is very large, read the lines into memory one at a time (I like to use a ...
5,214,814
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this: ``` 104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n ``` and so on. How can I use python to write all these numbers to a file in one col...
2011/03/07
[ "https://Stackoverflow.com/questions/5214814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647475/" ]
The easiest way to do this is probably to use `sed`. But if you must use Python, you need to replace all tab characters with newlines. Try something like this: ``` with open('input_file', 'rb') as infile: with open('output_file', 'wb') as outfile: for line in infile: outfile.write(line.replace(...
There are multiple ways of tackling this problem. You could use `string.split` and `string.join`, but that seems inefficient, since you'd be converting a string into a tuple and back into a string. Using regex, we replace one or more whitespace characters with a newline. The metacharacter `\s` represents any whitespa...
5,214,814
I have a bunch of numbers that are tab-delimited with new line characters that looks something like this: ``` 104 109 105 110 126 119 97 103\n 114 129 119 130 122 106 117 128\n ``` and so on. How can I use python to write all these numbers to a file in one col...
2011/03/07
[ "https://Stackoverflow.com/questions/5214814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647475/" ]
The easiest way to do this is probably to use `sed`. But if you must use Python, you need to replace all tab characters with newlines. Try something like this: ``` with open('input_file', 'rb') as infile: with open('output_file', 'wb') as outfile: for line in infile: outfile.write(line.replace(...
If your file is small, you can use `file.readlines()` to read all the lines into memory: ``` with open('input.txt', 'r') as fin: for row in [l.split() for l in fin.readlines()]: for col in row: print col ``` If the file is very large, read the lines into memory one at a time (I like to use a ...
40,443,759
I am trying to count the word fizz using python. However it is giving me an error. ``` def fizz_count(x): count =0 for item in x : if item== "fizz": count=count+1 return count item= ["fizz","cat", "fizz", "Dog", "fizz"] example= fizz_count(item) print example ``` i checked with indentation but sti...
2016/11/05
[ "https://Stackoverflow.com/questions/40443759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4186243/" ]
Your indentation seems to be incorrect, and you should not have the first `return count` (why would you return `count` as soon as you define it??). ``` def fizz_count(x): count = 0 for item in x: if item == "fizz": count += 1 # equivalent to count = count + 1 return count item = ["fiz...
Well i am new to python world. What i learned is return statement should be some thing like this. Example one :- ``` def split_train_test(data, test_ratio): shuffled_indices = np.random.permutation(len(data)) test_set_size = int(len(data) * test_ratio) test_indices = shuffled_indices[:test_set_size] t...
40,443,759
I am trying to count the word fizz using python. However it is giving me an error. ``` def fizz_count(x): count =0 for item in x : if item== "fizz": count=count+1 return count item= ["fizz","cat", "fizz", "Dog", "fizz"] example= fizz_count(item) print example ``` i checked with indentation but sti...
2016/11/05
[ "https://Stackoverflow.com/questions/40443759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4186243/" ]
Please try the following code: remove `return count` right after `count = 0` There are also a few indentation changes. ``` def fizz_count(x): count = 0 for item in x: if item== "fizz": count=count+1 return count item = ["fizz","cat", "fizz", "Dog", "fizz"] example = fizz_count(item)...
Well i am new to python world. What i learned is return statement should be some thing like this. Example one :- ``` def split_train_test(data, test_ratio): shuffled_indices = np.random.permutation(len(data)) test_set_size = int(len(data) * test_ratio) test_indices = shuffled_indices[:test_set_size] t...
40,443,759
I am trying to count the word fizz using python. However it is giving me an error. ``` def fizz_count(x): count =0 for item in x : if item== "fizz": count=count+1 return count item= ["fizz","cat", "fizz", "Dog", "fizz"] example= fizz_count(item) print example ``` i checked with indentation but sti...
2016/11/05
[ "https://Stackoverflow.com/questions/40443759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4186243/" ]
the problem is the identation in your line return Try with this: ``` def fizz_count(x): count =0 for item in x : if item == "fizz": count += 1 return count ```
Well i am new to python world. What i learned is return statement should be some thing like this. Example one :- ``` def split_train_test(data, test_ratio): shuffled_indices = np.random.permutation(len(data)) test_set_size = int(len(data) * test_ratio) test_indices = shuffled_indices[:test_set_size] t...
40,443,759
I am trying to count the word fizz using python. However it is giving me an error. ``` def fizz_count(x): count =0 for item in x : if item== "fizz": count=count+1 return count item= ["fizz","cat", "fizz", "Dog", "fizz"] example= fizz_count(item) print example ``` i checked with indentation but sti...
2016/11/05
[ "https://Stackoverflow.com/questions/40443759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4186243/" ]
You do not need the first 'return' statement in your code. It works as follows, with indentation and spacing fixed: ``` def fizz_count(x): count = 0 for item in x: if item == "fizz": count = count + 1 return count item= ["fizz","cat", "fizz", "Dog", "fizz"] example = fizz_count(item) ...
Well i am new to python world. What i learned is return statement should be some thing like this. Example one :- ``` def split_train_test(data, test_ratio): shuffled_indices = np.random.permutation(len(data)) test_set_size = int(len(data) * test_ratio) test_indices = shuffled_indices[:test_set_size] t...
8,437,964
I was wondering if we can print like row-wise in python. Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise ``` print x # currently gives # 3 # 4 #.. and so on ``` and i am looking something like ...
2011/12/08
[ "https://Stackoverflow.com/questions/8437964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902885/" ]
In Python2: ``` data = [3, 4] for x in data: print x, # notice the comma at the end of the line ``` or in Python3: ``` for x in data: print(x, end=' ') ``` prints ``` 3 4 ```
Just add a `,` at the end of the item(s) you're printing. ``` print(x,) # 3 4 ``` Or in Python 2: ``` print x, # 3 4 ```
8,437,964
I was wondering if we can print like row-wise in python. Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise ``` print x # currently gives # 3 # 4 #.. and so on ``` and i am looking something like ...
2011/12/08
[ "https://Stackoverflow.com/questions/8437964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902885/" ]
``` my_list = ['keyboard', 'mouse', 'led', 'monitor', 'headphones', 'dvd'] for i in xrange(0, len(my_list), 4): print '\t'.join(my_list[i:i+4]) ```
For python 2: ``` for x in num: print x, ``` For python 3: ``` for x in num: print(x, end = ' ') ```
8,437,964
I was wondering if we can print like row-wise in python. Basically I have a loop which might go on million times and I am printing out some strategic counts in that loop.. so it would be really cool if I can print like row-wise ``` print x # currently gives # 3 # 4 #.. and so on ``` and i am looking something like ...
2011/12/08
[ "https://Stackoverflow.com/questions/8437964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902885/" ]
If you add comma at the end it should work for you. ``` >>> def test(): ... print 1, ... print 2, ... >>> test() 1 2 ```
Python 3: ``` l = [3.14, 'string', ('tuple', 'of', 'items')] print(', '.join(map(repr, l))) ``` Output: > > > ``` > 3.14, 'string', ('tuple', 'of', 'items') > > ``` > >