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
2,046,912
I am seeing some weird behavior while parsing shared paths (shared paths on server, e.g. \storage\Builds) I am reading text file which contains directory paths which I want to process further. In order to do so I do as below: ``` def toWin(path): return path.replace("\\", "\\\\") for line in open(fileName): ...
2010/01/12
[ "https://Stackoverflow.com/questions/2046912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62056/" ]
This may not be your actual issue, but your UNC paths are actually not correct - they should start with a double backslash, but internally only use a single backslash as a divider. I'm not sure why the same thing would be working within the shell. **Update:** I suspect that what's happening is that in the shell, your...
Have to convert input to forward slash (unix-style) for os.\* modules to parse correctly. changed code as below ``` def toUnix(path): return path.replace("\\", "/") ``` Now all modules parse correctly.
2,046,912
I am seeing some weird behavior while parsing shared paths (shared paths on server, e.g. \storage\Builds) I am reading text file which contains directory paths which I want to process further. In order to do so I do as below: ``` def toWin(path): return path.replace("\\", "\\\\") for line in open(fileName): ...
2010/01/12
[ "https://Stackoverflow.com/questions/2046912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62056/" ]
There is simply no reason to "convert". Backslashes are only interpreted when they are contained in string literals in your code, not when you read them programmatically from a file. Therefore, you should disable your conversion function and things will probably work.
Have to convert input to forward slash (unix-style) for os.\* modules to parse correctly. changed code as below ``` def toUnix(path): return path.replace("\\", "/") ``` Now all modules parse correctly.
31,620,161
I am trying to run a python script using nrpe to monitor rabbitmq. Inside the script is a command 'sudo rabbiqmqctl list\_queues' which gives me a message count on each queue. However this is resulting in nagios giving htis message: ``` CRITICAL - Command '['sudo', 'rabbitmqctl', 'list_queues']' returned non-zero exi...
2015/07/24
[ "https://Stackoverflow.com/questions/31620161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/811220/" ]
The "non-zero exit code" error is often associated with `requiretty` being applied to all users by default in your sudoers file. Disabling "requiretty" in your sudoers file for the user that runs the check is safe, and may potentially fix the issue. E.g. (assuming nagios/nrpe are the users) @ /etc/sudoers ``` Defa...
I guess what Mr @EE1213 mentions is right. If you have the permission to see /var/log/secure, the log probably contains error messages regarding sudoers. Like: ``` "sorry, you must have a tty to run sudo" ```
24,494,437
I am using the Facebook Ads API and am wondering about Ad Image creation. This page, <https://developers.facebook.com/docs/reference/ads-api/adimage/#create>, makes it look pretty simple, except I'm not sure what's going on with the '[email protected]'. What is the @ for and how does it work? I currently make the po...
2014/06/30
[ "https://Stackoverflow.com/questions/24494437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3391108/" ]
First if you want to upload an Image on Facebook Ads API you can't give a URL you will have to provide the real path for it. in many cases you can use 'image\_url' directly & give the URL of the image, but in some cases you will need to upload the image to facebook and use the HASH provided by it. PHP/cURL implement...
The @ feature is to upload a file. It is supported by curl and PHP for example. So if you add a https link it is not strange that it doesn't work
10,925,410
In a single character string when I try to fetch second character python fails quite verbosely which is correct and expected behavior. ``` print 'a'[1] ``` However when I try to fetch an invalid sub sequence range, it fails silently. ``` print 'a'[1:] ``` What is the reason for the difference in behavior?
2012/06/07
[ "https://Stackoverflow.com/questions/10925410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137587/" ]
actually `slicing` never generates any `error` in case of `strings` and `lists`: **for eg.** ``` >>> s='abc' >>> s[-1000:1000] 'abc' ``` works fine. On the other hand, while accesing `Indexes` that are not defined will always raise an `IndexError` in both `strings` and `lists`: ``` >>> s[4] Traceback (most recent...
The semantics differ: ``` print 'a'[1] ``` tries to index into a non-existent (ie invalid) index/location, which *is* an error. ``` print 'a'[1:] ``` simply returns, based on the specified range, an empty string (`''`), which is *not* an error. I.e., ``` In [175]: 'a'[1] --------------------------------------...
10,925,410
In a single character string when I try to fetch second character python fails quite verbosely which is correct and expected behavior. ``` print 'a'[1] ``` However when I try to fetch an invalid sub sequence range, it fails silently. ``` print 'a'[1:] ``` What is the reason for the difference in behavior?
2012/06/07
[ "https://Stackoverflow.com/questions/10925410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137587/" ]
This makes more sense when you look at how mutable slicing on a list behaves: ``` >>> a = list(range(10)) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[10] = 2 Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> a[10] = 2 IndexError: list assignment index out of range >>> a[10:] = [1, 2, 3] ...
The semantics differ: ``` print 'a'[1] ``` tries to index into a non-existent (ie invalid) index/location, which *is* an error. ``` print 'a'[1:] ``` simply returns, based on the specified range, an empty string (`''`), which is *not* an error. I.e., ``` In [175]: 'a'[1] --------------------------------------...
10,925,410
In a single character string when I try to fetch second character python fails quite verbosely which is correct and expected behavior. ``` print 'a'[1] ``` However when I try to fetch an invalid sub sequence range, it fails silently. ``` print 'a'[1:] ``` What is the reason for the difference in behavior?
2012/06/07
[ "https://Stackoverflow.com/questions/10925410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137587/" ]
The semantics differ: ``` print 'a'[1] ``` tries to index into a non-existent (ie invalid) index/location, which *is* an error. ``` print 'a'[1:] ``` simply returns, based on the specified range, an empty string (`''`), which is *not* an error. I.e., ``` In [175]: 'a'[1] --------------------------------------...
It can be thought of this way: When you use `a[1]`, it is assumed that you exactly know what you want to access (in this case - second element in a string). Since `a[1]` does not exist python raises an exception. However, range operator `a[1:]` is implemented with the semantics that one may not know the exact range o...
10,925,410
In a single character string when I try to fetch second character python fails quite verbosely which is correct and expected behavior. ``` print 'a'[1] ``` However when I try to fetch an invalid sub sequence range, it fails silently. ``` print 'a'[1:] ``` What is the reason for the difference in behavior?
2012/06/07
[ "https://Stackoverflow.com/questions/10925410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137587/" ]
actually `slicing` never generates any `error` in case of `strings` and `lists`: **for eg.** ``` >>> s='abc' >>> s[-1000:1000] 'abc' ``` works fine. On the other hand, while accesing `Indexes` that are not defined will always raise an `IndexError` in both `strings` and `lists`: ``` >>> s[4] Traceback (most recent...
A slicing operation is different from an index operation. An index returns an element, and a slice returns a range, even an empty range or an empty string. An array with a single element has two "boundaries" where indexing pointers can be: 0 and 1. You can slice like `'a'[0:1]` and you`ll get the string (or range in a...
10,925,410
In a single character string when I try to fetch second character python fails quite verbosely which is correct and expected behavior. ``` print 'a'[1] ``` However when I try to fetch an invalid sub sequence range, it fails silently. ``` print 'a'[1:] ``` What is the reason for the difference in behavior?
2012/06/07
[ "https://Stackoverflow.com/questions/10925410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137587/" ]
actually `slicing` never generates any `error` in case of `strings` and `lists`: **for eg.** ``` >>> s='abc' >>> s[-1000:1000] 'abc' ``` works fine. On the other hand, while accesing `Indexes` that are not defined will always raise an `IndexError` in both `strings` and `lists`: ``` >>> s[4] Traceback (most recent...
This makes more sense when you look at how mutable slicing on a list behaves: ``` >>> a = list(range(10)) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[10] = 2 Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> a[10] = 2 IndexError: list assignment index out of range >>> a[10:] = [1, 2, 3] ...
10,925,410
In a single character string when I try to fetch second character python fails quite verbosely which is correct and expected behavior. ``` print 'a'[1] ``` However when I try to fetch an invalid sub sequence range, it fails silently. ``` print 'a'[1:] ``` What is the reason for the difference in behavior?
2012/06/07
[ "https://Stackoverflow.com/questions/10925410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137587/" ]
actually `slicing` never generates any `error` in case of `strings` and `lists`: **for eg.** ``` >>> s='abc' >>> s[-1000:1000] 'abc' ``` works fine. On the other hand, while accesing `Indexes` that are not defined will always raise an `IndexError` in both `strings` and `lists`: ``` >>> s[4] Traceback (most recent...
It can be thought of this way: When you use `a[1]`, it is assumed that you exactly know what you want to access (in this case - second element in a string). Since `a[1]` does not exist python raises an exception. However, range operator `a[1:]` is implemented with the semantics that one may not know the exact range o...
10,925,410
In a single character string when I try to fetch second character python fails quite verbosely which is correct and expected behavior. ``` print 'a'[1] ``` However when I try to fetch an invalid sub sequence range, it fails silently. ``` print 'a'[1:] ``` What is the reason for the difference in behavior?
2012/06/07
[ "https://Stackoverflow.com/questions/10925410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137587/" ]
This makes more sense when you look at how mutable slicing on a list behaves: ``` >>> a = list(range(10)) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[10] = 2 Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> a[10] = 2 IndexError: list assignment index out of range >>> a[10:] = [1, 2, 3] ...
A slicing operation is different from an index operation. An index returns an element, and a slice returns a range, even an empty range or an empty string. An array with a single element has two "boundaries" where indexing pointers can be: 0 and 1. You can slice like `'a'[0:1]` and you`ll get the string (or range in a...
10,925,410
In a single character string when I try to fetch second character python fails quite verbosely which is correct and expected behavior. ``` print 'a'[1] ``` However when I try to fetch an invalid sub sequence range, it fails silently. ``` print 'a'[1:] ``` What is the reason for the difference in behavior?
2012/06/07
[ "https://Stackoverflow.com/questions/10925410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137587/" ]
A slicing operation is different from an index operation. An index returns an element, and a slice returns a range, even an empty range or an empty string. An array with a single element has two "boundaries" where indexing pointers can be: 0 and 1. You can slice like `'a'[0:1]` and you`ll get the string (or range in a...
It can be thought of this way: When you use `a[1]`, it is assumed that you exactly know what you want to access (in this case - second element in a string). Since `a[1]` does not exist python raises an exception. However, range operator `a[1:]` is implemented with the semantics that one may not know the exact range o...
10,925,410
In a single character string when I try to fetch second character python fails quite verbosely which is correct and expected behavior. ``` print 'a'[1] ``` However when I try to fetch an invalid sub sequence range, it fails silently. ``` print 'a'[1:] ``` What is the reason for the difference in behavior?
2012/06/07
[ "https://Stackoverflow.com/questions/10925410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1137587/" ]
This makes more sense when you look at how mutable slicing on a list behaves: ``` >>> a = list(range(10)) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a[10] = 2 Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> a[10] = 2 IndexError: list assignment index out of range >>> a[10:] = [1, 2, 3] ...
It can be thought of this way: When you use `a[1]`, it is assumed that you exactly know what you want to access (in this case - second element in a string). Since `a[1]` does not exist python raises an exception. However, range operator `a[1:]` is implemented with the semantics that one may not know the exact range o...
55,441,517
I am following the official [docker get started guide](https://docs.docker.com/get-started/part2/). Instead of using a python image, I would like to setup a mongodb instance. I decided on a tag, and found the relevant [Dockerfile](https://github.com/docker-library/mongo/blob/89f19dc16431025c00a4709e0da6d751cf94830f/4.0...
2019/03/31
[ "https://Stackoverflow.com/questions/55441517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
It seems the only thing I had to add was `<import type="android.view.View" />` in the data tags...
You have to define variable as ObservableField below : ``` public final ObservableField<String> name = new ObservableField<>(); public final ObservableField<String> family = new ObservableField<>(); ```
55,441,517
I am following the official [docker get started guide](https://docs.docker.com/get-started/part2/). Instead of using a python image, I would like to setup a mongodb instance. I decided on a tag, and found the relevant [Dockerfile](https://github.com/docker-library/mongo/blob/89f19dc16431025c00a4709e0da6d751cf94830f/4.0...
2019/03/31
[ "https://Stackoverflow.com/questions/55441517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
It seems the only thing I had to add was `<import type="android.view.View" />` in the data tags...
The issue for me was , there were multiple qualifier layout's for example I had one for Night Mode and the base file, I was only making changes in the base file but not in other qualifier resource file, once I made the changes in all qualifiers, it worked for me.
55,441,517
I am following the official [docker get started guide](https://docs.docker.com/get-started/part2/). Instead of using a python image, I would like to setup a mongodb instance. I decided on a tag, and found the relevant [Dockerfile](https://github.com/docker-library/mongo/blob/89f19dc16431025c00a4709e0da6d751cf94830f/4.0...
2019/03/31
[ "https://Stackoverflow.com/questions/55441517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
It seems the only thing I had to add was `<import type="android.view.View" />` in the data tags...
I had a `BindingAdapter` tag that was present in an *unreachable* module.
55,441,517
I am following the official [docker get started guide](https://docs.docker.com/get-started/part2/). Instead of using a python image, I would like to setup a mongodb instance. I decided on a tag, and found the relevant [Dockerfile](https://github.com/docker-library/mongo/blob/89f19dc16431025c00a4709e0da6d751cf94830f/4.0...
2019/03/31
[ "https://Stackoverflow.com/questions/55441517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
It seems the only thing I had to add was `<import type="android.view.View" />` in the data tags...
I had the same error show up but it was because my `android:text="@={...}"` was outside the editText.
55,441,517
I am following the official [docker get started guide](https://docs.docker.com/get-started/part2/). Instead of using a python image, I would like to setup a mongodb instance. I decided on a tag, and found the relevant [Dockerfile](https://github.com/docker-library/mongo/blob/89f19dc16431025c00a4709e0da6d751cf94830f/4.0...
2019/03/31
[ "https://Stackoverflow.com/questions/55441517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
If you use two-ways databinding (`@={myBindingValue}`, with the **'='** sign instead of `@{myBindingValue}`) sometimes, you'll have this unusefull generic error because the value you are trying to bind is declared as immutable => **val** instead of **var** in Kotlin in your data class. **Exemple :** ``` data class Us...
You have to define variable as ObservableField below : ``` public final ObservableField<String> name = new ObservableField<>(); public final ObservableField<String> family = new ObservableField<>(); ```
55,441,517
I am following the official [docker get started guide](https://docs.docker.com/get-started/part2/). Instead of using a python image, I would like to setup a mongodb instance. I decided on a tag, and found the relevant [Dockerfile](https://github.com/docker-library/mongo/blob/89f19dc16431025c00a4709e0da6d751cf94830f/4.0...
2019/03/31
[ "https://Stackoverflow.com/questions/55441517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
It seems the only thing I had to add was `<import type="android.view.View" />` in the data tags...
In your xml code inside textView tag, for android:text attribute you have used @{viewmodel}. It just refers your shopViewModel class, you must target the text variable inside that class. Then the gen. class file errors will vanish. > > bindingImpl errors are mostly generated for invalid > assignment for XML-text or ...
55,441,517
I am following the official [docker get started guide](https://docs.docker.com/get-started/part2/). Instead of using a python image, I would like to setup a mongodb instance. I decided on a tag, and found the relevant [Dockerfile](https://github.com/docker-library/mongo/blob/89f19dc16431025c00a4709e0da6d751cf94830f/4.0...
2019/03/31
[ "https://Stackoverflow.com/questions/55441517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
In your xml code inside textView tag, for android:text attribute you have used @{viewmodel}. It just refers your shopViewModel class, you must target the text variable inside that class. Then the gen. class file errors will vanish. > > bindingImpl errors are mostly generated for invalid > assignment for XML-text or ...
I had the same error show up but it was because my `android:text="@={...}"` was outside the editText.
55,441,517
I am following the official [docker get started guide](https://docs.docker.com/get-started/part2/). Instead of using a python image, I would like to setup a mongodb instance. I decided on a tag, and found the relevant [Dockerfile](https://github.com/docker-library/mongo/blob/89f19dc16431025c00a4709e0da6d751cf94830f/4.0...
2019/03/31
[ "https://Stackoverflow.com/questions/55441517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
In your xml code inside textView tag, for android:text attribute you have used @{viewmodel}. It just refers your shopViewModel class, you must target the text variable inside that class. Then the gen. class file errors will vanish. > > bindingImpl errors are mostly generated for invalid > assignment for XML-text or ...
The issue for me was , there were multiple qualifier layout's for example I had one for Night Mode and the base file, I was only making changes in the base file but not in other qualifier resource file, once I made the changes in all qualifiers, it worked for me.
55,441,517
I am following the official [docker get started guide](https://docs.docker.com/get-started/part2/). Instead of using a python image, I would like to setup a mongodb instance. I decided on a tag, and found the relevant [Dockerfile](https://github.com/docker-library/mongo/blob/89f19dc16431025c00a4709e0da6d751cf94830f/4.0...
2019/03/31
[ "https://Stackoverflow.com/questions/55441517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
If you use two-ways databinding (`@={myBindingValue}`, with the **'='** sign instead of `@{myBindingValue}`) sometimes, you'll have this unusefull generic error because the value you are trying to bind is declared as immutable => **val** instead of **var** in Kotlin in your data class. **Exemple :** ``` data class Us...
The issue for me was , there were multiple qualifier layout's for example I had one for Night Mode and the base file, I was only making changes in the base file but not in other qualifier resource file, once I made the changes in all qualifiers, it worked for me.
55,441,517
I am following the official [docker get started guide](https://docs.docker.com/get-started/part2/). Instead of using a python image, I would like to setup a mongodb instance. I decided on a tag, and found the relevant [Dockerfile](https://github.com/docker-library/mongo/blob/89f19dc16431025c00a4709e0da6d751cf94830f/4.0...
2019/03/31
[ "https://Stackoverflow.com/questions/55441517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4341439/" ]
It seems the only thing I had to add was `<import type="android.view.View" />` in the data tags...
If you use two-ways databinding (`@={myBindingValue}`, with the **'='** sign instead of `@{myBindingValue}`) sometimes, you'll have this unusefull generic error because the value you are trying to bind is declared as immutable => **val** instead of **var** in Kotlin in your data class. **Exemple :** ``` data class Us...
72,671,082
very new to VBA. Suppose I have a 6 by 2 array with values shown on right, and I have an empty 2 by 3 array (excluding the header). My goal is to get the array on the left looks as how it is shown. ``` (Header) 1 2 3 1 a a c e 1 b ...
2022/06/18
[ "https://Stackoverflow.com/questions/72671082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19365488/" ]
Populate Array With Values From Another Array --------------------------------------------- * It is always a nested loop, but in Python, it is obviously 'under the hood' i.e. not seen to the end-user. They have integrated this possibility (written some code) into the language. * The following is a simplified version o...
**Alternative avoiding loops** For the *sake of the art* and in order to *approximate* your requirement to find a way replicating Python's code ``` array[:, 0] = [a, b] ``` in VBA without nested loops, you could try the following function combining several column value inputs (via a ParamArray) returning a comb...
74,478,463
I am developing deployment via DBX to Azure Databricks. In this regard I need a data job written in SQL to happen everyday. The job is located in the file `data.sql`. I know how to do it with a python file. Here I would do the following: ``` build: python: "pip" environments: default: workflows: - name:...
2022/11/17
[ "https://Stackoverflow.com/questions/74478463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13219123/" ]
There are various ways to do that. (1) One of the most simplest is to add a SQL query in the Databricks SQL lens, and then reference this query via `sql_task` as described [here](https://dbx.readthedocs.io/en/latest/reference/deployment/?h=sql_task#configuring-complex-deployments). (2) If you want to have a Python pr...
I found a simple workaround (although might not be the prettiest) to simply change the `data.sql` to a python file and run the queries using spark. This way I could use the same `spark_python_task`.
59,989,572
I'm working with a database called `international_education` from the `world_bank_intl_education` dataset of `bigquery-public-data`. ``` FIELDS country_name country_code indicator_name indicator_code value year ``` My aim is to plot a line graph with countries who have had the bigg...
2020/01/30
[ "https://Stackoverflow.com/questions/59989572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4459665/" ]
You don't need the CTE and you don't need the window frame definitions. So this should be equivalent: ``` SELECT country_name, year, value, (first_value(value) OVER (PARTITION BY country_name ORDER BY YEAR DESC) - first_value(value) OVER (PARTITION BY country_name ORDER BY YEAR) ) as total_range ...
If I understand correctly what you are trying to calculate, I wrote a query that do everything in BigQuery without the need to do anything in pandas. This query returns all the rows for each country that rank top 3 or bottom 3 in change in Population growth. ``` WITH differences AS ( SELECT country_name, year, v...
59,989,572
I'm working with a database called `international_education` from the `world_bank_intl_education` dataset of `bigquery-public-data`. ``` FIELDS country_name country_code indicator_name indicator_code value year ``` My aim is to plot a line graph with countries who have had the bigg...
2020/01/30
[ "https://Stackoverflow.com/questions/59989572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4459665/" ]
> > thought there might have been a quicker way to write this query as seemed a bit long winded > > > I think below is the least verbose version (BigQuery Standard SQL) ``` #standardSQL SELECT country_name, year, (LAST_VALUE(value) OVER(win) - FIRST_VALUE(value) OVER(win)) AS total_range, value FROM...
If I understand correctly what you are trying to calculate, I wrote a query that do everything in BigQuery without the need to do anything in pandas. This query returns all the rows for each country that rank top 3 or bottom 3 in change in Population growth. ``` WITH differences AS ( SELECT country_name, year, v...
59,989,572
I'm working with a database called `international_education` from the `world_bank_intl_education` dataset of `bigquery-public-data`. ``` FIELDS country_name country_code indicator_name indicator_code value year ``` My aim is to plot a line graph with countries who have had the bigg...
2020/01/30
[ "https://Stackoverflow.com/questions/59989572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4459665/" ]
You don't need the CTE and you don't need the window frame definitions. So this should be equivalent: ``` SELECT country_name, year, value, (first_value(value) OVER (PARTITION BY country_name ORDER BY YEAR DESC) - first_value(value) OVER (PARTITION BY country_name ORDER BY YEAR) ) as total_range ...
> > thought there might have been a quicker way to write this query as seemed a bit long winded > > > I think below is the least verbose version (BigQuery Standard SQL) ``` #standardSQL SELECT country_name, year, (LAST_VALUE(value) OVER(win) - FIRST_VALUE(value) OVER(win)) AS total_range, value FROM...
29,833,789
I am learning python, I get this error: ``` getattr(args, args.tool)(args) AttributeError: 'Namespace' object has no attribute 'cat' ``` If I execute my script like this: ``` myscript.py -t cat ``` What i want is print ``` Run cat here ``` Here is my full code: ``` #!/usr/bin/python import sys, argparse parse...
2015/04/23
[ "https://Stackoverflow.com/questions/29833789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358977/" ]
EvenLisle's answer gives the correct idea, but you can easily generalize it by using `arg.tools` as the key to `globals()`. Moreover, to simplify validation, you can use the `choices` argument of `add_argument` so that you know the possible values of `args.tool`. If someone provides an argument other than dog, cat, or ...
This: ``` def cat(args): print 'Run cat here' if "cat" in globals(): globals()["cat"]("arg") ``` will print "Run cat here". You should consider making a habit of having your function definitions at the top of your file. Otherwise, the above snippet would not have worked, as your function `cat` would not yet be ...
41,531,571
I am working on a GUI in python 3.5 with PyQt5 for a small chat bot. The problem i have is that the pre-processing, post-processing and brain are taking too much time to give back the answer for the user provided input. The GUI is very simple and looks like this: <http://prntscr.com/dsxa39> it loads very fast without ...
2017/01/08
[ "https://Stackoverflow.com/questions/41531571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5956553/" ]
Slow functions, such as `sleep`, will always block unless they are running asynchronously in another thread. If you want to avoid threads a workaround is to break up the slow function. In your case it might look like: ``` for _ in range(20): sleep(1) self.app.processEvents() ``` where `self.app` is a refere...
``` import sys from PyQt5 import QtCore, QtGui from PyQt5.QtWidgets import QMainWindow, QGridLayout, QLabel, QApplication, QWidget, QTextBrowser, QTextEdit, \ QPushButton, QAction, QLineEdit, QMessageBox from PyQt5.QtGui import QPalette, QIcon, QColor, QFont from PyQt5.QtCore import pyqtSlot, Qt import threading i...
39,501,277
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta ([Python pandas calculate rolling stock beta using rolling ...
2016/09/14
[ "https://Stackoverflow.com/questions/39501277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6107994/" ]
While efficient subdivision of the input data set into rolling windows is important to the optimization of the overall calculations, the performance of the beta calculation itself can also be significantly improved. The following optimizes only the subdivision of the data set into rolling windows: ``` def numpy_betas...
Created a simple python package [finance-calculator](https://finance-calculator.readthedocs.io/en/latest/usage.html) based on numpy and pandas to calculate financial ratios including beta. I am using the simple formula ([as per investopedia](https://www.investopedia.com/ask/answers/070615/what-formula-calculating-beta....
39,501,277
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta ([Python pandas calculate rolling stock beta using rolling ...
2016/09/14
[ "https://Stackoverflow.com/questions/39501277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6107994/" ]
***Generate Random Stock Data*** 20 Years of Monthly Data for 4,000 Stocks ``` dates = pd.date_range('1995-12-31', periods=480, freq='M', name='Date') stoks = pd.Index(['s{:04d}'.format(i) for i in range(4000)]) df = pd.DataFrame(np.random.rand(480, 4000), dates, stoks) ``` --- ``` df.iloc[:5, :5] ``` [![enter...
Further optimizing on @piRSquared's implementation for both speed and memory. the code is also simplified for clarity. ``` from numpy import nan, ndarray, ones_like, vstack, random from numpy.lib.stride_tricks import as_strided from numpy.linalg import pinv from pandas import DataFrame, date_range def calc_beta(s: n...
39,501,277
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta ([Python pandas calculate rolling stock beta using rolling ...
2016/09/14
[ "https://Stackoverflow.com/questions/39501277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6107994/" ]
Using a generator to improve memory efficiency ***Simulated data*** ``` m, n = 480, 10000 dates = pd.date_range('1995-12-31', periods=m, freq='M', name='Date') stocks = pd.Index(['s{:04d}'.format(i) for i in range(n)]) df = pd.DataFrame(np.random.rand(m, n), dates, stocks) market = pd.Series(np.random.rand(m), dates...
Created a simple python package [finance-calculator](https://finance-calculator.readthedocs.io/en/latest/usage.html) based on numpy and pandas to calculate financial ratios including beta. I am using the simple formula ([as per investopedia](https://www.investopedia.com/ask/answers/070615/what-formula-calculating-beta....
39,501,277
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta ([Python pandas calculate rolling stock beta using rolling ...
2016/09/14
[ "https://Stackoverflow.com/questions/39501277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6107994/" ]
Using a generator to improve memory efficiency ***Simulated data*** ``` m, n = 480, 10000 dates = pd.date_range('1995-12-31', periods=m, freq='M', name='Date') stocks = pd.Index(['s{:04d}'.format(i) for i in range(n)]) df = pd.DataFrame(np.random.rand(m, n), dates, stocks) market = pd.Series(np.random.rand(m), dates...
but these would be blockish when you require beta calculations across the dates(m) for multiple stocks(n) resulting (m x n) number of calculations. Some relief could be taken by running each date or stock on multiple cores, but then you will end up having huge hardware. The major time requirement for the solutions av...
39,501,277
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta ([Python pandas calculate rolling stock beta using rolling ...
2016/09/14
[ "https://Stackoverflow.com/questions/39501277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6107994/" ]
While efficient subdivision of the input data set into rolling windows is important to the optimization of the overall calculations, the performance of the beta calculation itself can also be significantly improved. The following optimizes only the subdivision of the data set into rolling windows: ``` def numpy_betas...
**HERE'S THE SIMPLEST AND FASTEST SOLUTION** The accepted answer was too slow for what I needed and the I didn't understand the math behind the solutions asserted as faster. They also gave different answers, though in fairness I probably just messed it up. I don't think you need to make a custom rolling function to c...
39,501,277
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta ([Python pandas calculate rolling stock beta using rolling ...
2016/09/14
[ "https://Stackoverflow.com/questions/39501277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6107994/" ]
Using a generator to improve memory efficiency ***Simulated data*** ``` m, n = 480, 10000 dates = pd.date_range('1995-12-31', periods=m, freq='M', name='Date') stocks = pd.Index(['s{:04d}'.format(i) for i in range(n)]) df = pd.DataFrame(np.random.rand(m, n), dates, stocks) market = pd.Series(np.random.rand(m), dates...
**HERE'S THE SIMPLEST AND FASTEST SOLUTION** The accepted answer was too slow for what I needed and the I didn't understand the math behind the solutions asserted as faster. They also gave different answers, though in fairness I probably just messed it up. I don't think you need to make a custom rolling function to c...
39,501,277
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta ([Python pandas calculate rolling stock beta using rolling ...
2016/09/14
[ "https://Stackoverflow.com/questions/39501277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6107994/" ]
Using a generator to improve memory efficiency ***Simulated data*** ``` m, n = 480, 10000 dates = pd.date_range('1995-12-31', periods=m, freq='M', name='Date') stocks = pd.Index(['s{:04d}'.format(i) for i in range(n)]) df = pd.DataFrame(np.random.rand(m, n), dates, stocks) market = pd.Series(np.random.rand(m), dates...
While efficient subdivision of the input data set into rolling windows is important to the optimization of the overall calculations, the performance of the beta calculation itself can also be significantly improved. The following optimizes only the subdivision of the data set into rolling windows: ``` def numpy_betas...
39,501,277
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta ([Python pandas calculate rolling stock beta using rolling ...
2016/09/14
[ "https://Stackoverflow.com/questions/39501277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6107994/" ]
While efficient subdivision of the input data set into rolling windows is important to the optimization of the overall calculations, the performance of the beta calculation itself can also be significantly improved. The following optimizes only the subdivision of the data set into rolling windows: ``` def numpy_betas...
but these would be blockish when you require beta calculations across the dates(m) for multiple stocks(n) resulting (m x n) number of calculations. Some relief could be taken by running each date or stock on multiple cores, but then you will end up having huge hardware. The major time requirement for the solutions av...
39,501,277
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta ([Python pandas calculate rolling stock beta using rolling ...
2016/09/14
[ "https://Stackoverflow.com/questions/39501277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6107994/" ]
**HERE'S THE SIMPLEST AND FASTEST SOLUTION** The accepted answer was too slow for what I needed and the I didn't understand the math behind the solutions asserted as faster. They also gave different answers, though in fairness I probably just messed it up. I don't think you need to make a custom rolling function to c...
but these would be blockish when you require beta calculations across the dates(m) for multiple stocks(n) resulting (m x n) number of calculations. Some relief could be taken by running each date or stock on multiple cores, but then you will end up having huge hardware. The major time requirement for the solutions av...
39,501,277
I have many (4000+) CSVs of stock data (Date, Open, High, Low, Close) which I import into individual Pandas dataframes to perform analysis. I am new to python and want to calculate a rolling 12month beta for each stock, I found a post to calculate rolling beta ([Python pandas calculate rolling stock beta using rolling ...
2016/09/14
[ "https://Stackoverflow.com/questions/39501277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6107994/" ]
**HERE'S THE SIMPLEST AND FASTEST SOLUTION** The accepted answer was too slow for what I needed and the I didn't understand the math behind the solutions asserted as faster. They also gave different answers, though in fairness I probably just messed it up. I don't think you need to make a custom rolling function to c...
Created a simple python package [finance-calculator](https://finance-calculator.readthedocs.io/en/latest/usage.html) based on numpy and pandas to calculate financial ratios including beta. I am using the simple formula ([as per investopedia](https://www.investopedia.com/ask/answers/070615/what-formula-calculating-beta....
35,257,550
I want to migrate from sqlite3 to MySQL in Django. First I used below command: ``` python manage.py dumpdata > datadump.json ``` then I changed the settings of my Django application and configured it with my new MySQL database. Finally, I used the following command: ``` python manage.py loaddata datadump.json ```...
2016/02/07
[ "https://Stackoverflow.com/questions/35257550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5214998/" ]
You have consistency error in your data, django\_admin\_log table refers to auth\_user which does not exist. sqlite does not enforce foreign key constraints, but mysql does. You need to fix data and then you can import it into mysql.
I had to move my database from a postgres to a MySql-Database. This worked for me: Export (old machine): ``` python manage.py dumpdata --natural --all --indent=2 --exclude=sessions --format=xml > dump.xml ``` Import (new machine): (note that for older versions of Django you'll need **syncdb** instead of migrate) ...
44,481,386
I have a python script which is used to remove noise from background of image. When I am calling this script from terminal it is working fine without any error. I am calling that script as below from terminal: ``` /usr/bin/python noise.py 1.png 100 ``` But When I tried to calling it from PHP using apache it is givin...
2017/06/11
[ "https://Stackoverflow.com/questions/44481386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3198113/" ]
Use this as a drawable ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape"> <stroke android:width="2dp" android:color="@android:color/transparent" /> <padding android:left="2dp" android:top="2dp" ...
``` You can also make the android:background="@null" and remove android:cropToPadding="false" <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" ...
44,481,386
I have a python script which is used to remove noise from background of image. When I am calling this script from terminal it is working fine without any error. I am calling that script as below from terminal: ``` /usr/bin/python noise.py 1.png 100 ``` But When I tried to calling it from PHP using apache it is givin...
2017/06/11
[ "https://Stackoverflow.com/questions/44481386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3198113/" ]
Use this as a drawable ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape"> <stroke android:width="2dp" android:color="@android:color/transparent" /> <padding android:left="2dp" android:top="2dp" ...
An Example to insert in all ImageButtons,remove the extra padding statement which will not apply to you ``` <ImageButton android:id="@+id/imageButton4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/imageButton6" android:layout_centerHorizontal...
44,481,386
I have a python script which is used to remove noise from background of image. When I am calling this script from terminal it is working fine without any error. I am calling that script as below from terminal: ``` /usr/bin/python noise.py 1.png 100 ``` But When I tried to calling it from PHP using apache it is givin...
2017/06/11
[ "https://Stackoverflow.com/questions/44481386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3198113/" ]
Use this as a drawable ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape"> <stroke android:width="2dp" android:color="@android:color/transparent" /> <padding android:left="2dp" android:top="2dp" ...
btn\_border XML in res/drawable ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <solid android:color="#85d1fa" /> <stroke android:width="2.2dp" android:color="#ffffff" /> </shape> ``` ImageButton on your Layout XML ...
55,939,474
I am trying to deploy the lambda function along with the `serverless.yml` file to AWS, but it throw below error The following is the function defined in the YAML file ``` functions: s3-thumbnail-generator: handler:handler.s3_thumbnail_generator events: - s3: bucket: ${self:custom.bucket} eve...
2019/05/01
[ "https://Stackoverflow.com/questions/55939474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11040619/" ]
The problem is that there is no value indicator (`:`) at the end of the line: ``` handler:handler.s3_thumbnail_generator ``` so the parser continues to try and gather a multi-line plain scalar by adding `events` followed by a value indicator. But a multi-line plain scalar cannot be a key in YAML. It is unclear what...
If it is your original file there is a syntax error in your YAML file. I added a note under the line of possible error: ``` functions: s3-thumbnail-generator: handler:handler.s3_thumbnail_generator events: - s3: bucket: ${self:custom.bucket} event: s3.ObjectCreated:* rules: - su...
11,743,378
I'm trying to talk to `supervisor` over xmlrpc. Based on [`supervisorctl`](https://github.com/Supervisor/supervisor/blob/master/supervisor/supervisorctl.py) (especially [this line](https://github.com/Supervisor/supervisor/blob/master/supervisor/options.py#L1512)), I have the following, which seems like it should work, ...
2012/07/31
[ "https://Stackoverflow.com/questions/11743378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21640/" ]
Your code looks substantially correct. I'm running Supervisor 3.0 with Python 2.7, and given the following: ``` import supervisor.xmlrpc import xmlrpclib p = xmlrpclib.ServerProxy('http://127.0.0.1', transport=supervisor.xmlrpc.SupervisorTransport( None, None, 'unix:///home/lars/lib/su...
I don't use the ServerProxy from xmlrpclib, I use the Server class instead and I don't have to define any transports or paths to sockets. Not sure if your purposes require that, but here's a thin client I use fairly frequently. It's pretty much straight out of the docs. ``` python -c "import xmlrpclib;\ supervisor_cli...
11,743,378
I'm trying to talk to `supervisor` over xmlrpc. Based on [`supervisorctl`](https://github.com/Supervisor/supervisor/blob/master/supervisor/supervisorctl.py) (especially [this line](https://github.com/Supervisor/supervisor/blob/master/supervisor/options.py#L1512)), I have the following, which seems like it should work, ...
2012/07/31
[ "https://Stackoverflow.com/questions/11743378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21640/" ]
Your code looks substantially correct. I'm running Supervisor 3.0 with Python 2.7, and given the following: ``` import supervisor.xmlrpc import xmlrpclib p = xmlrpclib.ServerProxy('http://127.0.0.1', transport=supervisor.xmlrpc.SupervisorTransport( None, None, 'unix:///home/lars/lib/su...
I faced the same issue; the problem was simple; `supervisord` was not running! First: ``` supervisord ``` And then: ``` supervisorctl start all ``` **Done!** :) > > If you've set nodaemon to true, you must keep the process runing in another tab of your terminal. > > >
11,743,378
I'm trying to talk to `supervisor` over xmlrpc. Based on [`supervisorctl`](https://github.com/Supervisor/supervisor/blob/master/supervisor/supervisorctl.py) (especially [this line](https://github.com/Supervisor/supervisor/blob/master/supervisor/options.py#L1512)), I have the following, which seems like it should work, ...
2012/07/31
[ "https://Stackoverflow.com/questions/11743378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21640/" ]
I don't use the ServerProxy from xmlrpclib, I use the Server class instead and I don't have to define any transports or paths to sockets. Not sure if your purposes require that, but here's a thin client I use fairly frequently. It's pretty much straight out of the docs. ``` python -c "import xmlrpclib;\ supervisor_cli...
I faced the same issue; the problem was simple; `supervisord` was not running! First: ``` supervisord ``` And then: ``` supervisorctl start all ``` **Done!** :) > > If you've set nodaemon to true, you must keep the process runing in another tab of your terminal. > > >
26,476,939
What's a concise python way to say ``` if <none of the elements of this array are None>: # do a bunch of stuff once ```
2014/10/21
[ "https://Stackoverflow.com/questions/26476939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/554807/" ]
The [`all`](https://docs.python.org/2/library/functions.html#all) builtin is nice for this. Given an iterable, it returns `True` if all elements of the iterable evaluate to `True`. ``` if all(x is not None for x in array): # your code ```
You could use all ``` all(i is not None for i in l) ```
26,476,939
What's a concise python way to say ``` if <none of the elements of this array are None>: # do a bunch of stuff once ```
2014/10/21
[ "https://Stackoverflow.com/questions/26476939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/554807/" ]
Why not simply, ``` None not in lst ```
The [`all`](https://docs.python.org/2/library/functions.html#all) builtin is nice for this. Given an iterable, it returns `True` if all elements of the iterable evaluate to `True`. ``` if all(x is not None for x in array): # your code ```
26,476,939
What's a concise python way to say ``` if <none of the elements of this array are None>: # do a bunch of stuff once ```
2014/10/21
[ "https://Stackoverflow.com/questions/26476939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/554807/" ]
Why not simply, ``` None not in lst ```
You could use all ``` all(i is not None for i in l) ```
26,476,939
What's a concise python way to say ``` if <none of the elements of this array are None>: # do a bunch of stuff once ```
2014/10/21
[ "https://Stackoverflow.com/questions/26476939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/554807/" ]
Of course in this case, [Jared's answer](https://stackoverflow.com/a/26476967/908494) is obviously the shortest, and also the most readable. And it has other advantages (like automatically becoming O(1) or O(log N) if you switch from a list to a set or a SortedSet). But there will be cases where that doesn't work, and ...
You could use all ``` all(i is not None for i in l) ```
26,476,939
What's a concise python way to say ``` if <none of the elements of this array are None>: # do a bunch of stuff once ```
2014/10/21
[ "https://Stackoverflow.com/questions/26476939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/554807/" ]
Why not simply, ``` None not in lst ```
Of course in this case, [Jared's answer](https://stackoverflow.com/a/26476967/908494) is obviously the shortest, and also the most readable. And it has other advantages (like automatically becoming O(1) or O(log N) if you switch from a list to a set or a SortedSet). But there will be cases where that doesn't work, and ...
59,888,355
I am having issues with having Conda install the library at this link: <https://github.com/ozgur/python-firebase> I am running: `conda install python-firebase` This is the response I get: ``` Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen solve. Re...
2020/01/23
[ "https://Stackoverflow.com/questions/59888355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11964771/" ]
You have to run this ``` conda install -c auto python-firebase ``` Take a look at [this](https://anaconda.org/auto/python-firebase)
Try doing `conda install -c auto python-firebase` Check <https://anaconda.org/auto/python-firebase> for further information
59,888,355
I am having issues with having Conda install the library at this link: <https://github.com/ozgur/python-firebase> I am running: `conda install python-firebase` This is the response I get: ``` Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen solve. Re...
2020/01/23
[ "https://Stackoverflow.com/questions/59888355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11964771/" ]
Checking <https://anaconda.org/search?q=firebase> you can see that there is only one entry that has `win64` listed on the right side. Since you are running on windows, you need to select that one and then enter the correct installation command: ``` conda install -c nayyaung python-firebase ``` (Note that the channel...
Try doing `conda install -c auto python-firebase` Check <https://anaconda.org/auto/python-firebase> for further information
14,321,679
I'm a new to programming and I chose python as my first language because its easy. But I'm confused here with this code: ``` option = 1 while option != 0: print "/n/n/n************MENU************" #Make a menu print "1. Add numbers" print "2. Find perimeter and area of a rectangle" print "0. Forget i...
2013/01/14
[ "https://Stackoverflow.com/questions/14321679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1977722/" ]
If you didn't create the variable `option` at the start of the program, the line ``` while option != 0: ``` would break, because no `option` variable would yet exist. As for how to change its value, notice that it is changed every time the line: ``` option = input("Please make a selection: ") ``` happens- that ...
Python requires variables to be declared before they can be used. In this case, a decision is being made whether `option` is set to `1` or `2` (so we set it to one of those values, ordinarily we could just as easily set it to `0` or an empty string). While some languages are less stringent on variable declaration (PHP...
14,321,679
I'm a new to programming and I chose python as my first language because its easy. But I'm confused here with this code: ``` option = 1 while option != 0: print "/n/n/n************MENU************" #Make a menu print "1. Add numbers" print "2. Find perimeter and area of a rectangle" print "0. Forget i...
2013/01/14
[ "https://Stackoverflow.com/questions/14321679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1977722/" ]
So that the while statement below it doesn't try to check a non-existent name. It doesn't *have* to be assigned `1`, it just happens to be the first non-zero natural number.
Python requires variables to be declared before they can be used. In this case, a decision is being made whether `option` is set to `1` or `2` (so we set it to one of those values, ordinarily we could just as easily set it to `0` or an empty string). While some languages are less stringent on variable declaration (PHP...
59,951,747
i tried the example project of the Flask-MQTT (<https://github.com/stlehmann/Flask-MQTT>) with my local mosquitto broker. But unfortunatly it is not working. Subscription and publish are not forwared correctly. so i've added some logger messages: ``` def handle_connect(client, userdata, flags, rc): print("CLIENT CONNE...
2020/01/28
[ "https://Stackoverflow.com/questions/59951747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5409884/" ]
The reason this is failing is in the mosquitto logs. ``` 1580163250: New connection from 127.0.0.1 on port 1883. 1580163250: Client flask_mqtt already connected, closing old connection. 1580163250: New client connected from 127.0.0.1 as flask_mqtt (p2, c1, k30). 1580163250: No will message specified. 1580163250: Sendi...
thanks for your fast reply! this helped me a lot and fixes the problem: The code is ``` """ A small Test application to show how to use Flask-MQTT. """ import eventlet import json from flask import Flask, render_template from flask_mqtt import Mqtt from flask_socketio import SocketIO from flask_bootstrap import Bo...
53,932,357
When installing packages with sudo apt-get install or building libraries from source inside a python virtual environment (I am not talking about pip install), does doing it inside a python virtual environment isolate the applications being installed? I mean do they exist only inside the python virtual environment?
2018/12/26
[ "https://Stackoverflow.com/questions/53932357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2651062/" ]
Things that a virtual environment gives you an isolated version of: * You get a separate `PATH` entry, so unqualified command-line references to `python`, `pip`, etc., will refer to the selected Python distribution. This can be convenient if you have many copies of Python installed on the system (common on developer w...
As per the comment by @deceze, virtual environments have no influence over `apt` operations. When building from source, any compiled binaries will be linked to the python binaries of that environment. So if your virtualenv python version varies from the system version, and you use the system python (path problems usua...
13,728,325
I'm trying to use Z3 from its python interface, but I would prefer not to do a system-wide install (i.e. sudo make install). I tried doing a local install with a --prefix, but the Makefile is hard-coded to install into the system's python directory. Best case, I would like run z3 directly from the build directly, in ...
2012/12/05
[ "https://Stackoverflow.com/questions/13728325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1406686/" ]
Yes, you can do it by including the build directory in your `LD_LIBRARY_PATH` and `PYTHONPATH` environment variables.
If you don't care about the python interface, edit the `build/Makefile` and comment out or delete the following lines in the `install` target: ``` @cp libz3$(SO_EXT) /usr/lib/python2.7/dist-packages/libz3$(SO_EXT) @cp z3*.pyc /usr/lib/python2.7/dist-packages ```
40,222,971
The answer presented here: [How to work with surrogate pairs in Python?](https://stackoverflow.com/questions/38147259/how-to-work-with-surrogate-pairs-in-python) tells you how to convert a surrogate pair, such as `'\ud83d\ude4f'` into a single non-BMP unicode character (the answer being `"\ud83d\ude4f".encode('utf-16',...
2016/10/24
[ "https://Stackoverflow.com/questions/40222971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6555884/" ]
You'll have to manually replace each non-BMP point with the surrogate pair. You could do this with a regular expression: ``` import re _nonbmp = re.compile(r'[\U00010000-\U0010FFFF]') def _surrogatepair(match): char = match.group() assert ord(char) > 0xffff encoded = char.encode('utf-16-le') return (...
It's a little complex, but here's a one-liner to convert a single character: ``` >>> emoji = '\U0001f64f' >>> ''.join(chr(x) for x in struct.unpack('>2H', emoji.encode('utf-16be'))) '\ud83d\ude4f' ``` To convert a mix of characters requires surrounding that expression with another: ``` >>> emoji_str = 'Here is a no...
52,264,354
I have the following dataframe: ``` Sentence 0 Cat is a big lion 1 Dogs are descendants of wolf 2 Elephants are pachyderm 3 Pachyderm animals include rhino, Elephants and hippopotamus ``` I need to create a python code which looks at the words in sentence above and calculates the sum of scores for each b...
2018/09/10
[ "https://Stackoverflow.com/questions/52264354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9244542/" ]
As a first effort, you can try a `split` and `map`-based approach, and then compute the score using `groupby`. ``` v = df1['Sentence'].str.split(r'[\s.!?,]+', expand=True).stack().str.lower() df1['Value'] = ( v.map(df2.set_index('Name')['Score']) .sum(level=0) .fillna(0, downcast='infer')) ``` ``` df1 ...
### `nltk` You may need to download stuff ``` import nltk nltk.download('punkt') ``` Then set up stemming and tokenizing ``` from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenize ps = PorterStemmer() ``` Create a handy dictionary ``` m = dict(zip(map(ps.stem, scores.Name), scores.Score))...
52,264,354
I have the following dataframe: ``` Sentence 0 Cat is a big lion 1 Dogs are descendants of wolf 2 Elephants are pachyderm 3 Pachyderm animals include rhino, Elephants and hippopotamus ``` I need to create a python code which looks at the words in sentence above and calculates the sum of scores for each b...
2018/09/10
[ "https://Stackoverflow.com/questions/52264354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9244542/" ]
As a first effort, you can try a `split` and `map`-based approach, and then compute the score using `groupby`. ``` v = df1['Sentence'].str.split(r'[\s.!?,]+', expand=True).stack().str.lower() df1['Value'] = ( v.map(df2.set_index('Name')['Score']) .sum(level=0) .fillna(0, downcast='infer')) ``` ``` df1 ...
Trying to using `findall` with `re` `re.I` ``` df.Sentence.str.findall(df1.Name.str.cat(sep='|'),flags=re.I).\ map(lambda x : sum([df1.loc[df1.Name==str.lower(y),'Score' ].values for y in x])[0]) Out[49]: 0 4 1 4 2 5 3 14 Name: Sentence, dtype: int64 ```
22,590,892
I have a python list of string tuples of the form: `lst = [('xxx', 'yyy'), ...etc]`. The list has around `8154741` tuples. I used a profiler and it says that the list takes around 500 MB in memory. Then I wrote all tuples in the list into a text file and it took around 72MB on disk size. I have three questions: * Wh...
2014/03/23
[ "https://Stackoverflow.com/questions/22590892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2464658/" ]
you have `8154741` tuples, that means your list, assuming 8 byte pointers, already contains `62 MB` of pointers to tuples. Assuming each tuple contains two ascii strings in python2, thats another `124 MB` of pointers for each tuple. Then you still have the overhead for the tuple and string objects, each object has a re...
Python objects can take much more memory than the raw data in them. This is because to achieve the features of Python's advanced and superfast data structures, you have to create some intermediate and temporary objects. Read more [here](http://deeplearning.net/software/theano/tutorial/python-memory-management.html). W...
22,590,892
I have a python list of string tuples of the form: `lst = [('xxx', 'yyy'), ...etc]`. The list has around `8154741` tuples. I used a profiler and it says that the list takes around 500 MB in memory. Then I wrote all tuples in the list into a text file and it took around 72MB on disk size. I have three questions: * Wh...
2014/03/23
[ "https://Stackoverflow.com/questions/22590892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2464658/" ]
Python objects can take much more memory than the raw data in them. This is because to achieve the features of Python's advanced and superfast data structures, you have to create some intermediate and temporary objects. Read more [here](http://deeplearning.net/software/theano/tutorial/python-memory-management.html). W...
Well are the strings mostly shared or unique? What is the significance of the tuples: bag-of-words or skip-gram representation? If so, one good library for vector representations of words is [word2vec](https://code.google.com/p/word2vec/) and here's a good [article on optimizing word2vec's performance](http://radimreh...
22,590,892
I have a python list of string tuples of the form: `lst = [('xxx', 'yyy'), ...etc]`. The list has around `8154741` tuples. I used a profiler and it says that the list takes around 500 MB in memory. Then I wrote all tuples in the list into a text file and it took around 72MB on disk size. I have three questions: * Wh...
2014/03/23
[ "https://Stackoverflow.com/questions/22590892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2464658/" ]
you have `8154741` tuples, that means your list, assuming 8 byte pointers, already contains `62 MB` of pointers to tuples. Assuming each tuple contains two ascii strings in python2, thats another `124 MB` of pointers for each tuple. Then you still have the overhead for the tuple and string objects, each object has a re...
Well are the strings mostly shared or unique? What is the significance of the tuples: bag-of-words or skip-gram representation? If so, one good library for vector representations of words is [word2vec](https://code.google.com/p/word2vec/) and here's a good [article on optimizing word2vec's performance](http://radimreh...
14,088,294
I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please? ``` #!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import Sim...
2012/12/30
[ "https://Stackoverflow.com/questions/14088294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1937459/" ]
Check [this](http://pymotw.com/2/BaseHTTPServer/index.html#module-BaseHTTPServer) post from Doug Hellmann's blog. ``` from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn import threading class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_r...
I have developed a PIP Utility called [ComplexHTTPServer](https://github.com/vickysam/ComplexHTTPServer) that is a multi-threaded version of SimpleHTTPServer. To install it, all you need to do is: ``` pip install ComplexHTTPServer ``` Using it is as simple as: ``` python -m ComplexHTTPServer [PORT] ``` (By defau...
14,088,294
I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please? ``` #!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import Sim...
2012/12/30
[ "https://Stackoverflow.com/questions/14088294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1937459/" ]
Check [this](http://pymotw.com/2/BaseHTTPServer/index.html#module-BaseHTTPServer) post from Doug Hellmann's blog. ``` from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn import threading class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_r...
It's amazing how many votes these solutions that break streaming are getting. If streaming might be needed down the road, then `ThreadingMixIn` and gunicorn are no good because they just collect up the response and write it as a unit at the end (which actually does nothing if your stream is infinite). Your basic appro...
14,088,294
I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please? ``` #!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import Sim...
2012/12/30
[ "https://Stackoverflow.com/questions/14088294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1937459/" ]
Check [this](http://pymotw.com/2/BaseHTTPServer/index.html#module-BaseHTTPServer) post from Doug Hellmann's blog. ``` from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn import threading class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_r...
In python3, you can use the code below (https or http): ``` from http.server import HTTPServer, BaseHTTPRequestHandler from socketserver import ThreadingMixIn import threading USE_HTTPS = True class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() ...
14,088,294
I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please? ``` #!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import Sim...
2012/12/30
[ "https://Stackoverflow.com/questions/14088294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1937459/" ]
Check [this](http://pymotw.com/2/BaseHTTPServer/index.html#module-BaseHTTPServer) post from Doug Hellmann's blog. ``` from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from SocketServer import ThreadingMixIn import threading class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_r...
A multithreaded https server in python3.7 ``` from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn import threading import ssl hostName = "localhost" serverPort = 8080 class MyServer(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) s...
14,088,294
I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please? ``` #!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import Sim...
2012/12/30
[ "https://Stackoverflow.com/questions/14088294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1937459/" ]
I have developed a PIP Utility called [ComplexHTTPServer](https://github.com/vickysam/ComplexHTTPServer) that is a multi-threaded version of SimpleHTTPServer. To install it, all you need to do is: ``` pip install ComplexHTTPServer ``` Using it is as simple as: ``` python -m ComplexHTTPServer [PORT] ``` (By defau...
It's amazing how many votes these solutions that break streaming are getting. If streaming might be needed down the road, then `ThreadingMixIn` and gunicorn are no good because they just collect up the response and write it as a unit at the end (which actually does nothing if your stream is infinite). Your basic appro...
14,088,294
I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please? ``` #!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import Sim...
2012/12/30
[ "https://Stackoverflow.com/questions/14088294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1937459/" ]
I have developed a PIP Utility called [ComplexHTTPServer](https://github.com/vickysam/ComplexHTTPServer) that is a multi-threaded version of SimpleHTTPServer. To install it, all you need to do is: ``` pip install ComplexHTTPServer ``` Using it is as simple as: ``` python -m ComplexHTTPServer [PORT] ``` (By defau...
A multithreaded https server in python3.7 ``` from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn import threading import ssl hostName = "localhost" serverPort = 8080 class MyServer(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) s...
14,088,294
I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please? ``` #!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import Sim...
2012/12/30
[ "https://Stackoverflow.com/questions/14088294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1937459/" ]
In python3, you can use the code below (https or http): ``` from http.server import HTTPServer, BaseHTTPRequestHandler from socketserver import ThreadingMixIn import threading USE_HTTPS = True class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() ...
It's amazing how many votes these solutions that break streaming are getting. If streaming might be needed down the road, then `ThreadingMixIn` and gunicorn are no good because they just collect up the response and write it as a unit at the end (which actually does nothing if your stream is infinite). Your basic appro...
14,088,294
I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please? ``` #!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import Sim...
2012/12/30
[ "https://Stackoverflow.com/questions/14088294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1937459/" ]
It's amazing how many votes these solutions that break streaming are getting. If streaming might be needed down the road, then `ThreadingMixIn` and gunicorn are no good because they just collect up the response and write it as a unit at the end (which actually does nothing if your stream is infinite). Your basic appro...
A multithreaded https server in python3.7 ``` from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn import threading import ssl hostName = "localhost" serverPort = 8080 class MyServer(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) s...
14,088,294
I'm trying to create multithreaded web server in python, but it only responds to one request at a time and I can't figure out why. Can you help me, please? ``` #!/usr/bin/env python2 # -*- coding: utf-8 -*- from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer from SimpleHTTPServer import Sim...
2012/12/30
[ "https://Stackoverflow.com/questions/14088294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1937459/" ]
In python3, you can use the code below (https or http): ``` from http.server import HTTPServer, BaseHTTPRequestHandler from socketserver import ThreadingMixIn import threading USE_HTTPS = True class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() ...
A multithreaded https server in python3.7 ``` from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn import threading import ssl hostName = "localhost" serverPort = 8080 class MyServer(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) s...
51,106,340
I am trying to create an application in appengine that searches for a list of keys and then I use this list to delete these records from the datastore, this service has to be a generic service so I could not use a model just search by the name of kind, it is possible to do this through appengine features? Below my cod...
2018/06/29
[ "https://Stackoverflow.com/questions/51106340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8484943/" ]
The problem was found on the line where fetch\_page is set. Removing this line ``` query.fetch_page(DEFAULT_PAGE_SIZE) ``` for this ``` keys = query.fetch(limit=_DEFAULT_LIMIT, keys_only=True) ```
To run a datastore query without a model class available in the environment, you can use the [`google.appengine.api.datastore.Query`](https://cloud.google.com/appengine/docs/standard/python/refdocs/google.appengine.api.datastore#google.appengine.api.datastore.Query) class from the low-level [datastore API](https://clou...
51,106,340
I am trying to create an application in appengine that searches for a list of keys and then I use this list to delete these records from the datastore, this service has to be a generic service so I could not use a model just search by the name of kind, it is possible to do this through appengine features? Below my cod...
2018/06/29
[ "https://Stackoverflow.com/questions/51106340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8484943/" ]
The problem was found on the line where fetch\_page is set. Removing this line ``` query.fetch_page(DEFAULT_PAGE_SIZE) ``` for this ``` keys = query.fetch(limit=_DEFAULT_LIMIT, keys_only=True) ```
If the goal is simply to wipe entities regardless of their kind then you have some options besides specifying the kinds/models yourself. * you could obtain the list of all kinds from your models file and iterate through them, see [How to delete all the entries from google datastore?](https://stackoverflow.com/question...
26,529,791
this is the first time I am trying to code in python and I am implementing the Apriori algorithm. I have generated till 2-itemsets and below is the function I have to generate 2-Itemsets by combining the keys of the 1-itemset. How do I go about making this function generic? I mean, by passing the keys of a dictionary...
2014/10/23
[ "https://Stackoverflow.com/questions/26529791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4077331/" ]
I assume that, given your field, you can benefit very much from the study of python's [itertools](https://docs.python.org/3/library/itertools.html) library. In your use case you can directly use the itertools `combinations` or wrap it in a helper function ``` from itertools import combinations def ord_comb(l,n): ...
This? ``` In [12]: [(x, y) for x in keys for y in keys if y>x] Out[12]: [('382', '723'), ('382', '458'), ('382', '390'), ('458', '723'), ('298', '382'), ('298', '723'), ('298', '458'), ('298', '390'), ('390', '723'), ('390', '458'), ('248', '382'), ('248', '723'), ('248', '458'), ('248', '298'), ('248',...
35,799,809
I am playing around with `unicode` in python. So there is a simple script: ``` # -*- coding: cp1251 -*- print 'юникод'.decode('cp1251') print unicode('юникод', 'cp1251') print unicode('юникод', 'utf-8') ``` In cmd I've switched encoding to `Active code page: 1251`. And there is the output: ``` СЋРЅРёРєРѕРґ СЋРЅР...
2016/03/04
[ "https://Stackoverflow.com/questions/35799809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3990145/" ]
I think I can understand what happened to you. The last line gave me the hint, that your *trash codepoints* confirmed. You try to display cp1251 characters but your editor is configured to use utf8. The `# -*- coding: cp1251 -*-` is only used by the Python interpretor to convert characters from source python files th...
Just use the following, but **ensure** you save the source code in the declared encoding. It can be *any* encoding that supports the characters you want to print. The terminal can be in a different encoding, as long as it *also* supports the characters you want to print: ``` #coding:utf8 print u'юникод' ``` The adva...
35,799,809
I am playing around with `unicode` in python. So there is a simple script: ``` # -*- coding: cp1251 -*- print 'юникод'.decode('cp1251') print unicode('юникод', 'cp1251') print unicode('юникод', 'utf-8') ``` In cmd I've switched encoding to `Active code page: 1251`. And there is the output: ``` СЋРЅРёРєРѕРґ СЋРЅР...
2016/03/04
[ "https://Stackoverflow.com/questions/35799809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3990145/" ]
I think I can understand what happened to you. The last line gave me the hint, that your *trash codepoints* confirmed. You try to display cp1251 characters but your editor is configured to use utf8. The `# -*- coding: cp1251 -*-` is only used by the Python interpretor to convert characters from source python files th...
Your issue is that the encoding declaration is wrong: your editor uses `utf-8` character encoding to save the source code. **Use `# -*- coding: utf-8 -*-` to fix it.** ``` >>> u'юникод' u'\u044e\u043d\u0438\u043a\u043e\u0434' >>> u'юникод'.encode('utf-8') '\xd1\x8e\xd0\xbd\xd0\xb8\xd0\xba\xd0\xbe\xd0\xb4' >>> print _....
35,799,809
I am playing around with `unicode` in python. So there is a simple script: ``` # -*- coding: cp1251 -*- print 'юникод'.decode('cp1251') print unicode('юникод', 'cp1251') print unicode('юникод', 'utf-8') ``` In cmd I've switched encoding to `Active code page: 1251`. And there is the output: ``` СЋРЅРёРєРѕРґ СЋРЅР...
2016/03/04
[ "https://Stackoverflow.com/questions/35799809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3990145/" ]
Your issue is that the encoding declaration is wrong: your editor uses `utf-8` character encoding to save the source code. **Use `# -*- coding: utf-8 -*-` to fix it.** ``` >>> u'юникод' u'\u044e\u043d\u0438\u043a\u043e\u0434' >>> u'юникод'.encode('utf-8') '\xd1\x8e\xd0\xbd\xd0\xb8\xd0\xba\xd0\xbe\xd0\xb4' >>> print _....
Just use the following, but **ensure** you save the source code in the declared encoding. It can be *any* encoding that supports the characters you want to print. The terminal can be in a different encoding, as long as it *also* supports the characters you want to print: ``` #coding:utf8 print u'юникод' ``` The adva...
58,959,226
I am trying to install a package which needs `psycopg2` as a dependency, so I installed `psycopg2-binary` using `pip install psycopg2-binary` but when I try to `pip install django-tenant-schemas` I get this error: ``` In file included from psycopg/psycopgmodule.c:27:0: ./psycopg/psycopg.h:34:10: fatal error: Python.h:...
2019/11/20
[ "https://Stackoverflow.com/questions/58959226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10796680/" ]
This takes a whole 1 line fewer. Whether it's cleaner or easier to understand is up to you .... ``` int sides[3]; for (int i=0; i < 3; i++) { cout << "Enter side " << i+1 << endl; cin >> sides[i]; } ``` It's good to write short code where it makes it clearer, so do keep considering how you can do that. Making it...
To make the code more maintainable and readable: 1) Use more meaningful variable names, or if you would name them consecutively, use an array e.g. `int numbers[3]` 2) Similarly, when you are taking prompts like this, consider having the prompts in a parallel array for the questions, or if they are the same prompt u...
58,959,226
I am trying to install a package which needs `psycopg2` as a dependency, so I installed `psycopg2-binary` using `pip install psycopg2-binary` but when I try to `pip install django-tenant-schemas` I get this error: ``` In file included from psycopg/psycopgmodule.c:27:0: ./psycopg/psycopg.h:34:10: fatal error: Python.h:...
2019/11/20
[ "https://Stackoverflow.com/questions/58959226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10796680/" ]
If you really want to shorten your project and make it more "clean" you can do it this way. ``` #include <iostream> int main() { std::string str = "string"; std::cin >> str; return 0; } ``` Like you wanted to write `cout` and `cin` in a single line, you could write like that, but I think it's not "clean" to w...
To make the code more maintainable and readable: 1) Use more meaningful variable names, or if you would name them consecutively, use an array e.g. `int numbers[3]` 2) Similarly, when you are taking prompts like this, consider having the prompts in a parallel array for the questions, or if they are the same prompt u...
61,643,039
When I run the cv.Canny edge detector on drawings, it detects hundreds of little edges densely packed in the shaded areas. How can I get it to stop doing that, while still detecting lighter features like eyes and nose? I tried blurring too. Here's an example, compared with an [online photo tool](https://online.rapidre...
2020/05/06
[ "https://Stackoverflow.com/questions/61643039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12346436/" ]
Here is one way to do that in Python/OpenCV. **Morphologic edge out is the absolute difference between a mask and the dilated mask** * Read the input * Convert to gray * Threshold (as mask) * Dilate the thresholded image * Compute the absolute difference * Invert its polarity as the edge image * Save the result Inpu...
I was successfully able to make `cv.Canny` give satisfactory results by changing the kernel dimension from (11, 11) to (0, 0), allowing the kernel to be dynamically determined by sigma. By doing this and tuning sigma, I got pretty good results. Also, `cv.imshow` distorts images, so when I was using it to test, the resu...
38,451,831
I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it? ``` %pyspark import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ``` And here is the error I've got ``` Traceback (most recent cal...
2016/07/19
[ "https://Stackoverflow.com/questions/38451831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151388/" ]
The following works for me with Spark & Python 3: ``` %pyspark import matplotlib import io # If you use the use() function, this must be done before importing matplotlib.pyplot. Calling use() after pyplot has been imported will have no effect. # see: http://matplotlib.org/faq/usage_faq.html#what-is-a-backend matplot...
As per @eddies suggestion, I tried and this is what worked for me on Zeppelin 0.6.1 python 2.7 ``` %python import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.figure() plt.plot([1,2,3,4]) plt.ylabel('some numbers') z.show(plt, width='500px') plt.close() ```
38,451,831
I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it? ``` %pyspark import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ``` And here is the error I've got ``` Traceback (most recent cal...
2016/07/19
[ "https://Stackoverflow.com/questions/38451831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151388/" ]
The following works for me with Spark & Python 3: ``` %pyspark import matplotlib import io # If you use the use() function, this must be done before importing matplotlib.pyplot. Calling use() after pyplot has been imported will have no effect. # see: http://matplotlib.org/faq/usage_faq.html#what-is-a-backend matplot...
Note that as of Zeppelin 0.7.3, matplotlib integration is much more seamless, so the methods described here are no longer necessary. <https://zeppelin.apache.org/docs/latest/interpreter/python.html#matplotlib-integration>
38,451,831
I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it? ``` %pyspark import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ``` And here is the error I've got ``` Traceback (most recent cal...
2016/07/19
[ "https://Stackoverflow.com/questions/38451831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151388/" ]
The following works for me with Spark & Python 3: ``` %pyspark import matplotlib import io # If you use the use() function, this must be done before importing matplotlib.pyplot. Calling use() after pyplot has been imported will have no effect. # see: http://matplotlib.org/faq/usage_faq.html#what-is-a-backend matplot...
Change this: ``` import matplotlib matplotlib.use('Agg') ``` with ``` import matplotlib.pyplot as plt; plt.rcdefaults() plt.switch_backend('agg') ``` Complete code example Spark 2.2.0 + python3(anaconda3.5): ``` %spark.pyspark import matplotlib.pyplot as plt; plt.rcdefaults() plt.switch_backend('agg') import nu...
38,451,831
I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it? ``` %pyspark import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ``` And here is the error I've got ``` Traceback (most recent cal...
2016/07/19
[ "https://Stackoverflow.com/questions/38451831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151388/" ]
The following works for me with Spark & Python 3: ``` %pyspark import matplotlib import io # If you use the use() function, this must be done before importing matplotlib.pyplot. Calling use() after pyplot has been imported will have no effect. # see: http://matplotlib.org/faq/usage_faq.html#what-is-a-backend matplot...
I would suggest you to use IPython/IPySpark interpreter in zeppelin 0.8.0 which will be released soon. The matplotlib integration in ipython is almost the same as jupyter. There's one tutorial <https://www.zepl.com/viewer/notebooks/bm90ZTovL3pqZmZkdS9lN2Q3ODNiODRkNjA0ZjVjODM1OWZlMWExZjM4OTk3Zi9ub3RlLmpzb24>
38,451,831
I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it? ``` %pyspark import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ``` And here is the error I've got ``` Traceback (most recent cal...
2016/07/19
[ "https://Stackoverflow.com/questions/38451831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151388/" ]
Note that as of Zeppelin 0.7.3, matplotlib integration is much more seamless, so the methods described here are no longer necessary. <https://zeppelin.apache.org/docs/latest/interpreter/python.html#matplotlib-integration>
As per @eddies suggestion, I tried and this is what worked for me on Zeppelin 0.6.1 python 2.7 ``` %python import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.figure() plt.plot([1,2,3,4]) plt.ylabel('some numbers') z.show(plt, width='500px') plt.close() ```
38,451,831
I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it? ``` %pyspark import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ``` And here is the error I've got ``` Traceback (most recent cal...
2016/07/19
[ "https://Stackoverflow.com/questions/38451831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151388/" ]
As per @eddies suggestion, I tried and this is what worked for me on Zeppelin 0.6.1 python 2.7 ``` %python import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.figure() plt.plot([1,2,3,4]) plt.ylabel('some numbers') z.show(plt, width='500px') plt.close() ```
I would suggest you to use IPython/IPySpark interpreter in zeppelin 0.8.0 which will be released soon. The matplotlib integration in ipython is almost the same as jupyter. There's one tutorial <https://www.zepl.com/viewer/notebooks/bm90ZTovL3pqZmZkdS9lN2Q3ODNiODRkNjA0ZjVjODM1OWZlMWExZjM4OTk3Zi9ub3RlLmpzb24>
38,451,831
I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it? ``` %pyspark import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ``` And here is the error I've got ``` Traceback (most recent cal...
2016/07/19
[ "https://Stackoverflow.com/questions/38451831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151388/" ]
Note that as of Zeppelin 0.7.3, matplotlib integration is much more seamless, so the methods described here are no longer necessary. <https://zeppelin.apache.org/docs/latest/interpreter/python.html#matplotlib-integration>
Change this: ``` import matplotlib matplotlib.use('Agg') ``` with ``` import matplotlib.pyplot as plt; plt.rcdefaults() plt.switch_backend('agg') ``` Complete code example Spark 2.2.0 + python3(anaconda3.5): ``` %spark.pyspark import matplotlib.pyplot as plt; plt.rcdefaults() plt.switch_backend('agg') import nu...
38,451,831
I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it? ``` %pyspark import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ``` And here is the error I've got ``` Traceback (most recent cal...
2016/07/19
[ "https://Stackoverflow.com/questions/38451831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151388/" ]
Note that as of Zeppelin 0.7.3, matplotlib integration is much more seamless, so the methods described here are no longer necessary. <https://zeppelin.apache.org/docs/latest/interpreter/python.html#matplotlib-integration>
I would suggest you to use IPython/IPySpark interpreter in zeppelin 0.8.0 which will be released soon. The matplotlib integration in ipython is almost the same as jupyter. There's one tutorial <https://www.zepl.com/viewer/notebooks/bm90ZTovL3pqZmZkdS9lN2Q3ODNiODRkNjA0ZjVjODM1OWZlMWExZjM4OTk3Zi9ub3RlLmpzb24>
38,451,831
I am using Zeppelin and matplotlib to visualize some data. I try them but fail with the error below. Could you give me some guidance how to fix it? ``` %pyspark import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ``` And here is the error I've got ``` Traceback (most recent cal...
2016/07/19
[ "https://Stackoverflow.com/questions/38451831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151388/" ]
Change this: ``` import matplotlib matplotlib.use('Agg') ``` with ``` import matplotlib.pyplot as plt; plt.rcdefaults() plt.switch_backend('agg') ``` Complete code example Spark 2.2.0 + python3(anaconda3.5): ``` %spark.pyspark import matplotlib.pyplot as plt; plt.rcdefaults() plt.switch_backend('agg') import nu...
I would suggest you to use IPython/IPySpark interpreter in zeppelin 0.8.0 which will be released soon. The matplotlib integration in ipython is almost the same as jupyter. There's one tutorial <https://www.zepl.com/viewer/notebooks/bm90ZTovL3pqZmZkdS9lN2Q3ODNiODRkNjA0ZjVjODM1OWZlMWExZjM4OTk3Zi9ub3RlLmpzb24>
8,510,615
I have ubuntu 11.10. I apt-get installed pypy from this launchpad repository: <https://launchpad.net/~pypy> the computer already has python on it, and python has its own pip. How can I install pip for pypy and how can I use it differently from that of python?
2011/12/14
[ "https://Stackoverflow.com/questions/8510615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1098562/" ]
To keep a separate installation, you might want to create a [virtualenv](http://pypi.python.org/pypi/virtualenv) for PyPy. Within the virtualenv, you can then just run `pip install whatever` and it will install it for PyPy. When you create a virtualenv, it automatically installs pip for you. Otherwise, you will need t...
The problem with `pip` installing from the `pypy` (at least when installing `pypy` via `apt-get`) is that it is installed into the system path: ``` $ whereis pip pip: /usr/local/bin/pip /usr/bin/pip ``` So after such install, `pypy pip` is executed by default (/usr/local/bin/pip) instead of the `python pip` (/usr/bi...
8,510,615
I have ubuntu 11.10. I apt-get installed pypy from this launchpad repository: <https://launchpad.net/~pypy> the computer already has python on it, and python has its own pip. How can I install pip for pypy and how can I use it differently from that of python?
2011/12/14
[ "https://Stackoverflow.com/questions/8510615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1098562/" ]
To keep a separate installation, you might want to create a [virtualenv](http://pypi.python.org/pypi/virtualenv) for PyPy. Within the virtualenv, you can then just run `pip install whatever` and it will install it for PyPy. When you create a virtualenv, it automatically installs pip for you. Otherwise, you will need t...
if you want to use pip with pypy: ``` pypy -m pip install [package] ``` pip is included with pypy so just target pip with the -m flag
8,510,615
I have ubuntu 11.10. I apt-get installed pypy from this launchpad repository: <https://launchpad.net/~pypy> the computer already has python on it, and python has its own pip. How can I install pip for pypy and how can I use it differently from that of python?
2011/12/14
[ "https://Stackoverflow.com/questions/8510615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1098562/" ]
Quoting (with minor changes) from here the [pypy website](http://doc.pypy.org/en/latest/install.html): > > If you want to install 3rd party libraries, the most convenient way is > to install pip: > > > > ``` > $ curl -O https://bootstrap.pypa.io/get-pip.py > $ ./pypy-2.1/bin/pypy get-pip.py > $ ./pypy-2.1/bin/pip...
The problem with `pip` installing from the `pypy` (at least when installing `pypy` via `apt-get`) is that it is installed into the system path: ``` $ whereis pip pip: /usr/local/bin/pip /usr/bin/pip ``` So after such install, `pypy pip` is executed by default (/usr/local/bin/pip) instead of the `python pip` (/usr/bi...
8,510,615
I have ubuntu 11.10. I apt-get installed pypy from this launchpad repository: <https://launchpad.net/~pypy> the computer already has python on it, and python has its own pip. How can I install pip for pypy and how can I use it differently from that of python?
2011/12/14
[ "https://Stackoverflow.com/questions/8510615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1098562/" ]
Quoting (with minor changes) from here the [pypy website](http://doc.pypy.org/en/latest/install.html): > > If you want to install 3rd party libraries, the most convenient way is > to install pip: > > > > ``` > $ curl -O https://bootstrap.pypa.io/get-pip.py > $ ./pypy-2.1/bin/pypy get-pip.py > $ ./pypy-2.1/bin/pip...
if you want to use pip with pypy: ``` pypy -m pip install [package] ``` pip is included with pypy so just target pip with the -m flag
8,510,615
I have ubuntu 11.10. I apt-get installed pypy from this launchpad repository: <https://launchpad.net/~pypy> the computer already has python on it, and python has its own pip. How can I install pip for pypy and how can I use it differently from that of python?
2011/12/14
[ "https://Stackoverflow.com/questions/8510615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1098562/" ]
if you want to use pip with pypy: ``` pypy -m pip install [package] ``` pip is included with pypy so just target pip with the -m flag
The problem with `pip` installing from the `pypy` (at least when installing `pypy` via `apt-get`) is that it is installed into the system path: ``` $ whereis pip pip: /usr/local/bin/pip /usr/bin/pip ``` So after such install, `pypy pip` is executed by default (/usr/local/bin/pip) instead of the `python pip` (/usr/bi...
63,191,779
I've created previously a python script that creates an author index. To spare you the details, (since extracting text from a pdf was pretty hard) I created a minimal reproducible example. My current status is I get a new line for each author and a comma separated list of the pages on which the author appears. Howev...
2020/07/31
[ "https://Stackoverflow.com/questions/63191779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7318488/" ]
`str.split` returns lists of strings. So `lambda x: sorted(x)` still sort by strings, not integers. You can try: ``` df['Pages'] = (df.Pages.str.split(',') .explode().astype(int) .sort_values() .groupby(level=0).agg(list) ) ``` Output: ``` Autor Pages 0 Author2 [20] 1 ...
If you want to use your existing approach, ``` df.Pages = ( df.Pages.str.split(",") .apply(lambda x: sorted(x, key=lambda x: int(x))) ) ``` --- ``` Autor Pages 0 Author2 [20] 1 Autor1 [1, 15] 2 Bertha Musterfrau [17] 3 Max Mustermann [5, 13] ```
53,796,705
why so in python 3.6.1 with simple code like: ``` print(f'\xe4') ``` Result: ``` Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> print(f'\xe4') File "<pyshell#13>", line 1, in <lambda> print = lambda text, end='\n', file=sys.stdout: print(text, end=end, file=file) File "<py...
2018/12/15
[ "https://Stackoverflow.com/questions/53796705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10540454/" ]
So let's recap: you have overridden the built-in `print` function with this: ``` print = lambda text, end='\n', file=sys.stdout: print(text, end=end, file=file) ``` Which is the same as ``` def print(text, end='\n', file=sys.stdout): print(text, end=end, file=file) ``` As you can see, this function calls its...
Works for me as well. But maybe it'll work for you with: ``` print(chr(0xe4)) ```