qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
62,374,607
I have a list 2,3,4,3,5,9,4,5,6 I want to iterate over the list until I get the first highest number that is followed by a lower number. Then to iterate over the rest of the number until I get the lowest number followed by a higher number. Then the next highest highest number that is followed by a lower number.And so o...
2020/06/14
[ "https://Stackoverflow.com/questions/62374607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13744765/" ]
you need to add the new user ONLY after you have checked all of them. instead you have it in the middle of your for loop, so it's going to add it over and over. try this: ``` var doesExistFlag = false; for (let i = 0; i < this.users.length; i++) { if (this.users[i].user == this.adminId) { doesExistFlag = true...
`id` is the name of the field ...which is never being compared to. `adminId` probably should be `userId`, for the sake of readability. While frankly speaking, just sort it on the server-side already.
13,264
58,031,373
I have a queue of 500 processes that I want to run through a python script, I want to run every N processes in parallel. What my python script does so far: It runs N processes in parallel, waits for all of them to terminate, then runs the next N files. What I need to do: When one of the N processes is finished, anoth...
2019/09/20
[ "https://Stackoverflow.com/questions/58031373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11597586/" ]
Advanced PDF Template is not yet supported in SuiteBundle.
Update: I noticed that when I create a new advanced template by customizing a standard one, I can see the new template in the bundle creation process. If I start from a "saved search", I don't... It is weird, ins't it?
13,267
60,740,554
I try to implement Apache Airflow with the CeleryExecutor. For the database I use Postgres, for the celery message queue I use Redis. When using LocalExecutor everything works fine, but when I set the CeleryExecutor in the airflow.cfg and want to set the Postgres database as the result\_backend ``` result_backend = po...
2020/03/18
[ "https://Stackoverflow.com/questions/60740554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4296244/" ]
You need to add the `db+` prefix to the database connection string: ```py f"db+postgresql+psycopg2://{user}:{password}@{host}/{database}" ``` This is also mentioned in the docs: <https://docs.celeryproject.org/en/stable/userguide/configuration.html#database-url-examples>
You need to add the `db+` prefix to the database connection string: ``` result_backend = db+postgresql://airflow_user:*******@localhost/airflow ```
13,268
5,556,360
I'm having a problem getting matplotlib to work in ubuntu 10.10. First I install the matplotlib using apt-get, and later I found that the version is 0.99 and some examples on the official site just won't work. Then I download the 1.01 version and install it without uninstalling the 0.99 version. To make the situation ...
2011/04/05
[ "https://Stackoverflow.com/questions/5556360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/693500/" ]
Ben Gamari has [packaged](https://launchpad.net/~bgamari/+archive/matplotlib-unofficial) matplotlib 1.0 for Ubuntu.
Try installing it with `pip`: ``` sudo apt-get install python-pip sudo pip install matplotlib ``` I just tested this and it should install matplotlib 1.0.1.
13,269
45,803,713
Presently we have a big-data cluster built using Cloudera-Virtual machines. By default the Python version on the VM is 2.7. For one of my programs I need Python 3.6. My team is very skeptical about 2 installations and afraid of breaking existing cluster/VM. I was planning to follow this article and install 2 versions ...
2017/08/21
[ "https://Stackoverflow.com/questions/45803713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864598/" ]
It seems that [`miniconda`](https://conda.io/miniconda.html) is what you need. using it you can manage multiple python environments with different versions of python. **to install miniconda3 just run:** ----------------------------------- ``` # this will download & install miniconda3 on your home dir wget https://rep...
ShmulikA's suggestion is pretty good. Here I'd like to add another one - I use Python 2.7.x, but for few prototypes, I had to go with Python 3.x. For this I used the **`pyenv`** utility. Once installed, all you have to do is: ``` pyenv install 3.x.x ``` Can list all the available Python variants: ``` pyenv versio...
13,271
66,588,659
I have a variable that saves the user's input. If the user inputs a list, e.g `["oranges","apples","pears"]` python seems to take this as a string, and print every character, instead of every word, that the code would print if fruit was simply a list. How do I the code to do this? Here is what I've tried... ``` fruit ...
2021/03/11
[ "https://Stackoverflow.com/questions/66588659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
python takes inputs as one huge string so instead of that being a list it is just a string like that looks like this ```py '["oranges","apples","pears"]' ``` turning this into a list will just look like ```py ['[', '"', 'o', 'r', 'a', 'n', 'g', 'e', 's', '"', ',', '"', 'a', 'p', 'p', 'l', 'e', 's', '"', ',', '"', '...
You will have to split word is list by comma. ``` fruit = list(fruit.split(",")) fruit = input("What is you favourite fruit?") fruit = fruit.split(",") for i in fruit: print(i) ```
13,272
62,616,736
I've been using the Fermipy conda environment on Python 2.7.14 64-bit on macOS Catalina 10.15.5 and overnight received the error "r.start is not a function" when trying to connect to the Jyputer server through Vscode (if I try on Jupyter Notebook/Lab the server instantly dies). I had a bunch of clutter on my system so ...
2020/06/27
[ "https://Stackoverflow.com/questions/62616736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13820618/" ]
As answered here, <https://github.com/microsoft/vscode-python/issues/12355#issuecomment-652515770> VSCode changed how it launches jupyter kernels, and the new method is incompatible with python 2.7. Add this line to your VSCode settings.json file and restart. ``` "python.experiments.optOutFrom": ["LocalZMQKernel - e...
I got the same message. (r.start is not a function.) I had an old uninstalled version of anaconda on the computer which had left behind a folder containing its python version. Jupyter was supposed to be running from new venv after setting both python and jupyter path in vscode. I fully deleted remaining files from old ...
13,273
72,285,267
I have a below dictionary defined with IP address of the application for the respective region. Region is user input variable, based on the input i need to procees the IP in rest of my script. ``` app_list=["puppet","dns","ntp"] dns={'apac':["172.118.162.93","172.118.144.93"],'euro':["172.118.76.93","172.118.204.93",...
2022/05/18
[ "https://Stackoverflow.com/questions/72285267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3619226/" ]
``` # use a nested dict comprehension # use enumerate for the index of the list items and add it to the key using f-string {key: {f"{k}.{i}": e for k, v in val.items() for i, e in enumerate(v)} for key, val in my_dict.items()} {'Ka': {'Ka.0': '0.80', 'Ka.1': '0.1', 'Ba.0': '0.50', 'Ba.1': '1.1', 'FC.0':...
``` from collections import defaultdict new = defaultdict(dict) for k, values in d.items(): for sub_key, values in values.items(): for value in values: existing_key_count = sum(1 for existing_key in new[k].keys() if existing_key.startswith(sub_key)) new_key = f"{sub_key}.{existing_ke...
13,274
45,732,286
I am working with protein sequences. My goal is to create a convolutional network which will predict three angles for each amino acid in the protein. I'm having trouble debugging a TFLearn DNN model that requires a reshape operation. The input data describes (currently) 25 proteins of varying lengths. To use Tensors I...
2017/08/17
[ "https://Stackoverflow.com/questions/45732286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9376487/" ]
There is a new plugin (since a year), called [chartjs-plugin-piechart-outlabels](https://www.npmjs.com/package/chartjs-plugin-piechart-outlabels) Just import the source `<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-piechart-outlabels"></script>` and use it with the outlabeledPie type ``` var randomS...
The real problem lies with the overlapping of the labels when the slices are small.You can use [PieceLabel.js](https://emn178.github.io/Chart.PieceLabel.js/samples/demo/) which solves the issue of overlapping labels by hiding it . You mentioned that you **cannot hide labels** so use legends, which will display names of...
13,276
58,523,431
`driver.getWindowHandles()` returns Set so, if we want to choose window by index, we have to wrap Set into ArrayList: ``` var tabsList = new ArrayList<>(driver.getWindowHandles()); var nextTab = tabsList.get(1); driver.switchTo().window(nextTab); ``` in python we can access windows by index immediately: ``` next_wi...
2019/10/23
[ "https://Stackoverflow.com/questions/58523431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11705114/" ]
Window Handles -------------- In a discussion, regarding [window-handles](/questions/tagged/window-handles "show questions tagged 'window-handles'") Simon (creator of WebDriver) clearly mentioned that: > > While the datatype used for storing the list of handles may be ordered by insertion, the order in which the Web...
One comment - take into account the order of Set is not fixed, so it will return you a random window by the usage above.
13,281
53,372,966
While executing the following python script using cloud-composer, I get `*** Task instance did not exist in the DB` under the `gcs2bq` task Log in Airflow Code: ``` import datetime import os import csv import pandas as pd import pip from airflow import models #from airflow.contrib.operators import dataproc_operator fr...
2018/11/19
[ "https://Stackoverflow.com/questions/53372966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6039925/" ]
I have stumbled on this issue also. What helped for me was to do this line: ``` spark.sql("SET spark.sql.hive.manageFilesourcePartitions=False") ``` and then use `spark.sql(query)` instead of using dataframe. I do not know what happens under the hood, but this solved my problem. Although it might be too late for ...
I know the topic is quite old but: 1. I've received same error but the actual source problem was hidden much deeper in logs. If you facing same problem as me, go to the end of your stack trace and you might find actual reason for job to be failing. In my case: a. `org.apache.spark.sql.hive.client.Shim_v0_13.getPar...
13,284
70,339,321
The decision variable of my optimization problem (which I am aiming at keeping linear) is a placement binary vector, where the value in each position is either 0 or 1 (two different possible locations of item i). One component of the objective function is this: [![XOR](https://i.stack.imgur.com/SFvgz.png)](https://i....
2021/12/13
[ "https://Stackoverflow.com/questions/70339321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11422437/" ]
My notation is: `xprev[i]` is the previous solution and `x[i]` is the current one. I assume `xprev[i]` is a binary constant and `x[i]` is a binary variable. Then we can write ``` sum(i, |xprev[i]-x[i]|) =sum(i|xprev[i]=0, x[i]) + sum(i|xprev[i]=1, 1-x[i]) =sum(i, x[i]*(1-xprev[i]) + (1-x[i])*xprev[i]) ``...
**UPDATE**: If what you need to replace is a XOR gate, then you could use a combination of other gates, which are linear, to replace it. Here are some of them <https://en.wikipedia.org/wiki/XOR_gate#Alternatives>. Example: `A XOR B = (A OR B) AND (NOT A + NOT B)`. When A and B are binary, that should translate mathema...
13,285
65,493,246
I am using python through a secure shell. When I use pydot and graphviz package, it shows error [Errno 2] dot not found in path. I searched so many solutions. People suggest 'sudo apt install graphviz' or 'sudo apt-get install graphviz'. But when I use 'sudo', it shows 'username is not in the sudoers file.This incident...
2020/12/29
[ "https://Stackoverflow.com/questions/65493246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14644632/" ]
You can use `_source` to limit what's retrieved: ``` POST indexname/_search { "_source": "scores.a/*" } ``` Alternatively, you could employ `script_fields` which do exactly the same but offer playroom for value modification too: ``` POST indexname/_search { "script_fields": { "scores_prefixed_with_a": { ...
Use [`.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) - [`.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) on [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Ob...
13,286
10,234,575
I first installed pymongo using easy\_install, that didn't work so I tried with pip and it is still failing. This is fine in the terminal: ``` Macintosh:etc me$ python Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 14:13:39) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "licen...
2012/04/19
[ "https://Stackoverflow.com/questions/10234575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4533572/" ]
Found it! Required a path append before importing of the pymongo module ``` sys.path.append('/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages') import pymongo ``` Would ideally like to find a way to append this to the pythonpath permanently, but this works for now!
I'm not sure why the last message says "Successfully installed pymongo" but it obviously failed due to the fact that you don't have gcc installed on your system. You need to do the following: RHEL/Centos: sudo yum install gcc python-devel Debian/Ubuntu: sudo apt-get install gcc python-dev Then try and install pymongo...
13,287
1,941,894
I'm trying to get virtualenv to work on my machine. I'm using python2.6, and after installing pip, and using pip to install virtualenv, running "virtualenv --no-site-packages cyclesg" results in the following: ``` New python executable in cyclesg/bin/python Installing setuptools.... Complete output from command /hom...
2009/12/21
[ "https://Stackoverflow.com/questions/1941894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/236267/" ]
Are you on mandriva? In order to support multilib (mixing x86/x86\_64) Mandriva messes up your python installation. They patched python, which breaks virtualenv; instead of fixing python, they then proceeded to patch virtualenv. This is useless if you are using your own virtualenv installed from pip. Here is the bug:...
Are you on a linux based system? It looks like virtualenv is trying to build a new python exectable but can't find the files to do that. Try installing the `python-dev` package.
13,288
65,465,114
I am new to python programming. Following the AWS learning path: <https://aws.amazon.com/getting-started/hands-on/build-train-deploy-machine-learning-model-sagemaker/?trk=el_a134p000003yWILAA2&trkCampaign=DS_SageMaker_Tutorial&sc_channel=el&sc_campaign=Data_Scientist_Hands-on_Tutorial&sc_outcome=Product_Marketing&sc_g...
2020/12/27
[ "https://Stackoverflow.com/questions/65465114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2601359/" ]
If you just remove it then the prediction will work. Therefore, recommend removing this code line. xgb\_predictor.content\_type = 'text/csv'
Removing xgb\_predictor.content\_type = 'text/csv' will work. But best way is that you first check the attributes of the object: ``` xgb_predictor.__dict__.keys() ``` This way, you will know that which attributes can be set.
13,289
63,767,925
I'm really new to programming (two days old), so excuse my python dumbness. I've recently run into a problem with adding up to numbers from a list. I've managed to come up with this program: ``` list_nums = ["17", "3"] num1 = list_nums[0] num2 = list_nums[1] ...
2020/09/06
[ "https://Stackoverflow.com/questions/63767925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14231446/" ]
`"17"` and `"3"`These are string, if you remove double-quotes from them, they become integers `17` and `3`. So if you want to add 2 numbers, they have to be `integer` or `float` in Python. Just remove double-quotes in list: `list_nums = [17, 3]`
Your `num1` and `num2` variables contain string values `'17'` and `'3'`. Operator `+` for strings works as a concatenation, e.g. `'17' + '3' == '173'`. If you need to get 20 out of it, you need to work with numeric types, like integers. For that, you either need to remove quotes from your 17 and 3 literals: ``` list_n...
13,290
40,851,872
Can I get python to print the source code for `__builtins__` directly? OR (more preferably): What is the pathname of the source code for `__builtins__`? --- I at least know the following things: * `__builtins__` is a module, by typing `type(__builtins__)`. * I have tried the best-answer-suggestions to a more gene...
2016/11/28
[ "https://Stackoverflow.com/questions/40851872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The `__builtin__` module is implemented in [`Python/bltinmodule.c`](https://github.com/python/cpython/blob/2.7/Python/bltinmodule.c), a rather unusual location for a rather unusual module.
I can't try it right now, but python default ide is able to open core modules easily (I tried with math and some more) <https://docs.python.org/2/library/idle.html> On menus. Open module.
13,291
8,275,793
I have managed to write some simple scripts in python for android using sl4a. I can also create shortcuts on my home screen for them. But the icon chosen for this is always the python sl4a icon. Can I change this so different scripts have different icons?
2011/11/26
[ "https://Stackoverflow.com/questions/8275793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1024495/" ]
You can change it if you build the .APK file from your computer and pick the icon there. You develop the Python SL4A application and you pick the logo in the /res/drawable folder.
I guess it depends on your launcher. With ADW launcher, you can do a long press on your shortcut from your home screen and then select the icon you want to use by pressing the icon button. For other launchers I've no idea.
13,292
51,952,761
In tkinter, when a button has the focus, you can press the space bar to execute the command associated with that button. I'm trying to make pressing the Enter key do the same thing. I'm certain I've done this in the past, but I can't find the code, and what I'm doing now isn't working. I'm using python 3.6.1 on a Mac. ...
2018/08/21
[ "https://Stackoverflow.com/questions/51952761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908293/" ]
The only thing your Ajax is sending is this.refs.search.value - not the name "search" / not url encoded / not multi-part encoded. Indeed, you seem to have invented your own encoding system. Try: ``` xhr.open('get','//localhost:80/ReactStudy/travelReduxApp/public/server/search.php?search=' + value,true); ``` in Ajax...
``` <?php header('Access-Control-Allow-Origin:* '); /*shows warning without isset*/ /*$form = $_GET["search"]; echo $form;*/ /*with isset shows not found*/ if(isset($_POST["search"])){ $form = $_GET["search"]; echo $form; }else{ echo "not found";`ghd` } ?> ```
13,294
37,357,896
I am using sublime to automatically word-wrap python code-lines that go beyond 79 Characters as the Pep-8 defines. Initially i was doing return to not go beyond the limit. The only downside with that is that anyone else not having the word-wrap active wouldn't have the limitation. So should i strive forward of actual...
2016/05/21
[ "https://Stackoverflow.com/questions/37357896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1767754/" ]
PEP8 wants you to perform an actual word wrap. The point of PEP8’s stylistic rules is that the file looks the same in every editor, so you cannot rely on editor visualizations to satisfy PEP8. This also makes you choose the point where to break deliberately. For example, Sublime will do a pretty basic job in wrapping ...
In-file word wrapping would let your code conform to Pep-8 most consistently, even if other programmers are looking at your code using different coding environments. That seems to me to be the best solution to keeping to the standard, particularly if you are expecting that others will, at some point, be looking at your...
13,295
43,630,195
`A = [[[1,2,3],[4]],[[1,4],[2,3]]]` Here I want to find lists in A which sum of all sublists in list not grater than 5. Which the result should be `[[1,4],[2,3]]` I tried a long time to solve this problem in python. But I still can't figure out the right solution, which I stuck at loop out multiple loops. My code as...
2017/04/26
[ "https://Stackoverflow.com/questions/43630195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5702561/" ]
A simple solution which you can think of would be like this - ``` A = [[[1,2,3],[4]],[[1,4],[2,3]]] r = [] # this will be our result for list in A: # Iterate through each item in A f = True # This is a flag we set for a favorable sublist for item in list: # Here we iterate through each list in the su...
This should work for your problem: ``` >>> for alist in A: ... if max(sum(sublist) for sublist in alist) <= 5: ... print(alist) ... [[1, 4], [2, 3]] ```
13,296
54,093,050
I'm following this code example from a [python course](https://www.python-course.eu/python3_properties.php): ``` class P: def __init__(self,x): self.x = x @property def x(self): return self.__x @x.setter def x(self, x): if x < 0: self.__x = 0 elif x > ...
2019/01/08
[ "https://Stackoverflow.com/questions/54093050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3128156/" ]
Your setter method should be like below: ``` @M_inv.setter def M_inv(self): M = self.var * np.eye(self.W.shape[1]) + np.matmul(self.W.T, self.W) self.__M_inv = np.linalg.inv(M) ``` The decorator `@M_inv.setter` and the function `def M_inv(self):` name should be same
The example is wrong. EDIT: Example was using a setter in `__init__` on purpose. Getters and setters, even though they act like properties, are just methods that access a private attribute. That attribute **must exist**. In the example, `self.__x` is never created. Here is my suggested use : ``` class PCAModel(obje...
13,301
58,798,388
I feel silly having to ask this question, but my memory evades me of better alternatives. Two appraoches that spring to mind: First: ``` def f1(v): return sum(2**i for i,va in enumerate(v) if va) >>> f1([True, False, True]) 5 ``` Second: ``` def f2(v): return int('0b' + "".join(str(int(va)) for va in v),2...
2019/11/11
[ "https://Stackoverflow.com/questions/58798388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1186019/" ]
Using booleans in arithmetic operations (also lambda functions) is very pythonic: ``` lst = [True, False, True] func = lambda x: sum(2 ** num * i for num, i in enumerate(x)) print(func(lst)) # 5 ```
This is another hacky way I came up with: ``` def f1(v): return int(''.join(str(int(b)) for b in v), 2) ``` Example: ``` >>> def f1(v): ... return int(''.join(str(int(b)) for b in v), 2) ... >>> f1([True, False, True]) 5 >>> ``` Another identical example using `map` (more readable in my view): ``` def f1...
13,302
54,757,300
I have an existing python array instantiated with zeros. How do I iterate through and change the values? I can't iterate through and change elements of a Python array? ``` num_list = [1,2,3,3,4,5,] mu = np.mean(num_list) sigma = np.std(num_list) std_array = np.zeros(len(num_list)) for i in std_array: temp_nu...
2019/02/19
[ "https://Stackoverflow.com/questions/54757300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7671993/" ]
In your code you are iterating over the elements of the `numpy.array` `std_array`, but then using these elements as indices to dereference `std_array`. An easy solution would be the following. ``` num_arr = np.array(num_list) for i,element in enumerate(num_arr): temp_num = (element-mu)/sigma std_array[i]=temp_...
You `i` is an element from `std_array`, which is `float`. `Numpy` is therefore complaining that you are trying slicing with `float` where: > > only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) > and integer or boolean arrays are valid indices > > > If you don't have to use `for`, then `numpy`...
13,311
32,200,565
I`ve got this exception when using returnvalue in function ``` @inlineCallbacks def my_func(id): yield somefunc(id) @inlineCallbacks def somefunc(id): somevar = yield func(id) returnValue(somevar) returnValue(somevar) File "/usr/lib64/python2.7/site-packages/twisted/internet/defer.py", line 1105, in retur...
2015/08/25
[ "https://Stackoverflow.com/questions/32200565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4349456/" ]
Just download and install [wp-pagenavi](https://wordpress.org/plugins/wp-pagenavi/) plugin and then use: ``` if(method_exists('wp_pagenavi')){ wp_pagenavi(array('query' => $query)); } ``` Pass your query object in wp\_pagenavi method argument.
i guess, you are seeking a numbered pagination for custom query, than try this article [Kvcodes](http://www.kvcodes.com/2015/08/how-to-add-numeric-pagination-in-your-wordpress-theme-without-plugin/). here is the code. ``` function kvcodes_pagination_fn($pages = '', $range = 2){ $showitems = ($range * 2)+1; ...
13,312
59,723,005
For my report, I'm creating a special color plot in jupyter notebook. There are two parameters, `x` and `y`. ``` import numpy as np x = np.arange(-1,1,0.1) y = np.arange(1,11,1) ``` with which I compute a third quantity. Here is an example to demonstrate the concept: ``` values = [] for i in range(len(y)) : z ...
2020/01/13
[ "https://Stackoverflow.com/questions/59723005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A known (reasonably) numerically-stable version of the geometric mean is: ```py import torch def gmean(input_x, dim): log_x = torch.log(input_x) return torch.exp(torch.mean(log_x, dim=dim)) x = torch.Tensor([2.0] * 1000).requires_grad_(True) print(gmean(x, dim=0)) # tensor(2.0000, grad_fn=<ExpBackward>) ```...
torch.prod() helps: ``` import torch x = torch.FloatTensor(3).uniform_().requires_grad_(True) print(x) y = x.prod() ** (1.0/x.shape[0]) print(y) y.backward() print(x.grad) # tensor([0.5692, 0.7495, 0.1702], requires_grad=True) # tensor(0.4172, grad_fn=<PowBackward0>) # tensor([0.2443, 0.1856, 0.8169]) ``` EDIT: ?w...
13,313
5,268,391
Is it possible to pipe numpy data (from one python script ) into the other? suppose that `script1.py` looks like this: `x = np.zeros(3, dtype={'names':['col1', 'col2'], 'formats':['i4','f4']})` `print x` Suppose that from the linux command, I run the following: `python script1.py | script2.py` Will `script2.py` g...
2011/03/11
[ "https://Stackoverflow.com/questions/5268391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/540009/" ]
No, data is passed through a pipe as text. You'll need to serialize the data in `script1.py` before writing, and deserialize it in `script2.py` after reading.
Check out the `save` and `load` functions. I don't think they would object to being passed a pipe instead of a file.
13,314
26,373,356
I am not sure why I am getting an error that game is not defined: ``` #!/usr/bin/python # global variables wins = 0 losses = 0 draws = 0 games = 0 # Welcome and get name of human player print 'Welcome to Rock Paper Scissors!!' human = raw_input('What is your name?') print 'Hello ',human # start game game() def gam...
2014/10/15
[ "https://Stackoverflow.com/questions/26373356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4147288/" ]
You have to define the function `game` before you can call it. ``` def game(): ... game() ```
Okay, I spent some time tinkering with this today and now have the following: ``` import random import string # global variables global wins wins = 0 global losses losses = 0 global draws draws = 0 global games games = 0 # Welcome and get name of human player print 'Welcome to Rock Paper Scissors!!' human = raw_input...
13,317
53,350,132
I'm trying to understand how to pull a specific item from the code below. ``` var snake = [[{x : 20, y : 30}],[{x : 40, y: 50}]]; ``` Coming from python I found this to be useful when dealing with for loops to have all my objects in an array within an array. Say for instance I want to pull the first `x:` value from...
2018/11/17
[ "https://Stackoverflow.com/questions/53350132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10444342/" ]
You are deleting a large number of rows. That is the problem. There is lots of overhead in deletions. If you are deleting a significant number of rows in a table -- and significant might only be a few percent -- then it is often faster to recreate the table: ``` select b.* into temp_b -- actually, I wouldn't use a t...
Your query looks fine to me. Your problem seems to be that you have a very large amount of data and need ways to optimize performance. What you can do is materialize your subquery, and make sure max\_id is indexed, for example by making it a primary key. So create a temporary table `Max_B`, and store the results of ...
13,319
51,869,152
Supposing that a have this dict with the keys and some range: ``` d = {"x": (0, 2), "y": (2, 4)} ``` I need to create dicts using the range above, I will get: ``` >>> keys = [k for k,v in d.items()] >>> >>> def newDict(keys,array): ... return dict(zip(keys,array)) ... >>> for i in range(0,2): ... for j in...
2018/08/16
[ "https://Stackoverflow.com/questions/51869152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2452792/" ]
This is known behavior that came about a few versions ago (I think 2016). This `#{style}` interpolation is not supported in attributes: > > Caution > > > Previous versions of Pug/Jade supported an interpolation syntax such > as: > > > a(href="/#{url}") Link This syntax is no longer supported. > Alternatives ar...
There is an easy way to do that, write directly the variable, without using quotes, brackets, $, !, or #, like this: ``` a(href=originalUrl) !{originalURL} ``` The result of this is a link with the text in originalURL Example: if originalUrl = 'www.google.es' ``` a(href='www.google.es') www.google.es ``` finally...
13,320
58,928,062
``` import pandas as pd from sqlalchemy import create_engine host='user@127.0.0.1' port=10000 schema ='result' table='new_table' engine = create_engine(f'hive://{host}:{port}/{schema}') conn=engine.connect() engine.execute('CREATE TABLE ' + table + ' (year int, GDP_rate int, GDP string)') data = { 'year': [2017, 2018...
2019/11/19
[ "https://Stackoverflow.com/questions/58928062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12300690/" ]
Kindly add method='multi' for batch insert df.to\_sql("table\_name", con = engine,index=False,method='multi')
A likely pyhive bug. See <https://github.com/dropbox/PyHive/issues/250>. The problem happens when inserting multiple rows.
13,321
48,524,013
So i'm starting to use Django but i had some problems trying to run my server. I have two versions of python installed. So in my mysite package i tried to run `python manage.py runserver` but i got this error: ``` Unhandled exception in thread started by <function wrapper at 0x058E1430> Traceback (most recent call ...
2018/01/30
[ "https://Stackoverflow.com/questions/48524013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9217311/" ]
Not sure what django version you are currently using but if you are working with Django 2.0 then python2 wouldn't work ( Cause Django2.0 support only Python 3.4+) So in your case if you are in Django2.0 (assuming you already have installed latest version of python in your machine) then you should run following command...
Have you tried to upgrade django with pip or pip3? ``` pip install --upgrade django --user ```
13,322
29,858,752
I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/> After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael...
2015/04/24
[ "https://Stackoverflow.com/questions/29858752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4474430/" ]
*For Linux and OSX* **Step 1: Download chromedriver** ``` # You can find more recent/older versions at http://chromedriver.storage.googleapis.com/ # Also make sure to pick the right driver, based on your Operating System wget http://chromedriver.storage.googleapis.com/81.0.4044.69/chromedriver_mac64.zip ``` For deb...
Had this issue with Mac Mojave running Robot test framework and Chrome 77. This solved the problem. Kudos @Navarasu for pointing me to the right track. ``` $ pip install webdriver-manager --user # install webdriver-manager lib for python $ python # open python prompt ``` Next, in python prompt: ``` from selenium im...
13,324
52,566,756
I tried to draw a decision tree in Jupyter Notebook this way. ``` mglearn.plots.plot_animal_tree() ``` But I didn't make it in the right way and got the following error message. ``` --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most ...
2018/09/29
[ "https://Stackoverflow.com/questions/52566756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5574794/" ]
in Anaconda install * python-graphviz * pydot This will fix your problem
In case if your operation system is **Ubuntu** I recommend to try command: ``` sudo apt-get install -y graphviz libgraphviz-dev ```
13,334
58,838,759
I have multiple csv files containing item and invoicing data (proprietary and edifact files). They look roughly like this: ``` 0001;12345;Item1 0002;12345;EUR;1.99 0003;12345;EUR;1.99 ``` The always start with 0001 but do not necessarily have more than one row. How do I group them efficiently? Currently I read them...
2019/11/13
[ "https://Stackoverflow.com/questions/58838759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11766755/" ]
With my knowledge of EDIFACT-style files, they're basically hierarchical, with some row code (`0001` here) acting as a "start-of-group" symbol. So yeah – something like this is a fast, Pythonic way to group by that symbol. (`input_file` can just as well be a disk file, but for the sake of a self-contained example, it'...
If the files have the same columns, it would be interesting to read it in dataframes, and append to each one this thing. `df1= pd.read_csv(Path+File1, sep=';') df2= pd.read_csv(Path+File2, sep=';') df2.append(df1, ignore_index = True, sort=False).` Afterward, you can just sort by the first column that contains...
13,343
52,676,660
I am totally new to Jupyter Notebook. Currently, I am using the notebook with R and it is working well. Now, I tried to use it with Python and I receive the following error. > > [I 09:00:52.947 NotebookApp] KernelRestarter: restarting kernel (4/5), > new random ports > > > Traceback (most recent call last): > >...
2018/10/06
[ "https://Stackoverflow.com/questions/52676660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10464893/" ]
> > ipython` 7.0.1 has requirement prompt-toolkit<2.1.0,>=2.0.0, but you'll have prompt-toolkit 1.0.15 which is incompatible > > > <https://github.com/jupyter/jupyter_console/issues/158> > > > Upgrading `prompt-toolkit` will fix the problem. ``` pip install --upgrade prompt-toolkit ```
It's more stable to create a kernel with an Anaconda virtualenv. Follow these steps. 1. Execute Anaconda prompt. 2. Type `conda create --name $ENVIRONMENT_NAME R -y` 3. Type `conda activate $ENVIRONMENT_NAME` 4. Type `python -m ipykernel install` 5. Type `ipython kernel install --user --name $ENVIRONMENT_NAME` Then,...
13,344
2,623,524
As asked and answered in [this post](https://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[1...
2010/04/12
[ "https://Stackoverflow.com/questions/2623524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I would use code like ``` path = "/Users/smcho/Desktop/bracket/[10,20]" replacements = {"[": "[[]", "]": "[]]"} new_path = "".join(replacements.get(c, c) for c in path) ```
``` import re path2 = re.sub(r'(\[|\])', r'[\1]', path1) ```
13,353
41,186,818
The [uuid4()](https://docs.python.org/2/library/uuid.html#uuid.uuid4) function of Python's module `uuid` generates a random UUID, and seems to generate a different one every time: ``` In [1]: import uuid In [2]: uuid.uuid4() Out[2]: UUID('f6c9ad6c-eea0-4049-a7c5-56253bc3e9c0') In [3]: uuid.uuid4() Out[3]: UUID('2fc1...
2016/12/16
[ "https://Stackoverflow.com/questions/41186818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995862/" ]
[Faker](https://github.com/joke2k/faker "Faker") makes this easy ``` >>> from faker import Faker >>> f1 = Faker() >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec741188ebb >>> print(f1.uuid4()) a41f020c-2d4d-333f-f1d3-979f1043fae0 >>> f1.seed(4321) >>> print(f1.uuid4()) cc733c92-6853-15f6-0e49-bec74...
Simple solution based on the answer of @user10229295, with a comment about the seed. The Edit queue was full, so I opened a new answer: ``` import hashlib import uuid seed = 'Type your seed_string here' #Read comment below m = hashlib.md5() m.update(seed.encode('utf-8')) new_uuid = uuid.UUID(m.hexdigest()) ``` **C...
13,363
14,946,639
Say I have the following code: ``` if request.POST: id = request.POST.get('id') # block of code to use variable id do_work(id) do_other_work(id) ``` is there a shortcut (one line of code) that will test if it's request.POST for the conditional block and also assign variable id for the conditional block t...
2013/02/18
[ "https://Stackoverflow.com/questions/14946639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342553/" ]
No, you can't assign anything in an `if` test expression. If you didn't have the rest of the `if` block, ``` id = request.POST and request.POST.get('id') ``` would work. It doesn't make much sense, to do it, though, because `id = request.POST.get('id')` works just fine with empty `request.POST`. Please remember ...
I like this: ``` id = request.POST.get('id', False) if id is not False: # do something ```
13,373
66,534,294
I am using python 3.7 and have intalled IPython I am using ipython shell in django like ``` python manage.py shell_plus ``` and then ``` [1]: %load_ext autoreload [2]: %autoreload 2 ``` and then i am doing ``` [1]: from boiler.tasks import add [2]: add(1,2) "testing" ``` `change add function` ``` def add(x,y...
2021/03/08
[ "https://Stackoverflow.com/questions/66534294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2897115/" ]
> > Will this cause issues on the memory side? > > > Which side of what, and which side of it is the memory side? It may use more memory than necessary. > > What happens to that extra memory? > > > It remains unused. > > Does it have to be manually freed or is there a way to do it automatically? > > > ...
For your purposes, the memory allocator doesn't know, nor does it really care about how much memory you actually use in a block you malloc. The key here is to never use *more* memory than you malloc. The extra memory just sits there, available for your use if you want it. Note that allocating 10 bytes vs 4 bytes won't...
13,374
26,953,153
Beginner python coder here, keep things simple, please. So, I need this code below to scramble two letters without scrambling the first or last letters. Everything seems to work right up until the `scrambler()` function. ``` from random import randint def wordScramble(string): stringArray = string.split() fo...
2014/11/16
[ "https://Stackoverflow.com/questions/26953153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257122/" ]
If the labels 0, 100, 200 belong to one axis and the texts "Day One", ... to the other one you can set the colors of the labels of the first axis to transparent like this ``` axis.TextColor = OxyColors.Transparent; ``` Hope this helps.
If XAML use this ``` <oxy:Plot.Axes> <oxy:LinearAxis Position="Left" TextColor = OxyColors.Transparent/> </oxy:Plot.Axes> ``` If code ``` // Create a plot model PlotModel = new PlotModel { Title = "Updating by task running on the UI thread" }; // Add the axes, note that MinimumPadding and AbsoluteMinimum shoul...
13,375
18,782,584
How can I perform post processing on my SQL3 database via python? The following code doesn't work, but what I am trying to do is first create a new database if not exists already, then insert some data, and finally execute the query and close the connection. But I what to do so separately, so as to add additional funct...
2013/09/13
[ "https://Stackoverflow.com/questions/18782584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2295350/" ]
It would seem that FB has made some changes to its redirection script, when it detects a Windows Phone webbrowser control. What the C# SDK does, is generate the login page as "<http://www.facebook.com>....". When you open this URL on the webbrowser control, it gets redirected to "<http://m.facebook.com>..." which dis...
In my project I just listened for the WebView's navigated event. If it happens, it means that user did something on the login page (i.e. pressed login button). Then I parsed the uri of the page you mentioned which should contain OAuth callback url, if it is correct and the result is success I redirect manually to the c...
13,376
809,859
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard. Can anyone point to documentatio...
2009/05/01
[ "https://Stackoverflow.com/questions/809859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85271/" ]
[Four spaces and no hard tabs](https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#whitespace-1), if you're a Pythonista.
``` 2 space 4 busy coder 3 space for heavy if statement using script kiddies 4 space for those who make real money pressing space 4 times 8 space for the man in ties and suit who doesn't need to code ```
13,378
32,309,177
How do we do a DNS query, expecially MX query, in Python by not installing any third party libs. I want to query the MX record about a domain, however, it seems that `socket.getaddrinfo` can only query the A record. I have tried this: ``` python -c "import socket; print socket.getaddrinfo('baidu.com', 25, socket.AF_...
2015/08/31
[ "https://Stackoverflow.com/questions/32309177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1889327/" ]
Here's some rough low-level code for making a dns request using just the standard library if anyone's interested. ``` import secrets import socket # https://datatracker.ietf.org/doc/html/rfc1035 # https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#table-dns-parameters-4 def dns_request(name, qtype=...
First Install dnspython ``` import dns.resolver answers = dns.resolver.query('dnspython.org', 'MX') for rdata in answers: print 'Host', rdata.exchange, 'has preference', rdata.preference ```
13,388
38,414,650
I've recently found this page: [Making PyObject\_HEAD conform to standard C](https://www.python.org/dev/peps/pep-3123/) and I'm curious about this paragraph: > > Standard C has one specific exception to its aliasing rules precisely designed to support the case of Python: a value of a struct type may also be access...
2016/07/16
[ "https://Stackoverflow.com/questions/38414650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5960237/" ]
Your interpretation1 is correct, but the code isn't. The pointer `i` already points to the object, and thus to the first element, so you only need to cast it to the correct type: ``` int* n = ( int* )i; ``` then you simply dereference it: ``` *n = 345; ``` Or in one step: ``` *( int* )i = 345; ``` --- 1 (Quo...
You have a few issues, but this works for me: ``` #include <malloc.h> #include <stdio.h> struct with_int { int a; char b; }; int main(void) { struct with_int *i = (struct with_int *)malloc(sizeof(struct with_int)); i->a = 5; *(int *)i = 8; printf("%d\n", i->a); } ``` Output is: 8
13,389
65,521,446
When typing a word in a dash input I would like to get autosuggestions, an example of what I mean is this CLI app I made in the past. [![enter image description here](https://i.stack.imgur.com/SPzmM.png)](https://i.stack.imgur.com/SPzmM.png) a link to the documentation: <https://python-prompt-toolkit.readthedocs.io/e...
2020/12/31
[ "https://Stackoverflow.com/questions/65521446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14008858/" ]
`:` is missing after the third `while` statement, also `except` and `print` statements have the same indentation level. You can use `try-except` without additional `while` loop, check if the input number is less then `11` and append the input the the list and if not break the while loop. ***Example***: ``` while Tru...
flows answered your question appropriately. Because I think you would like to ask for pairs of name and grade, I modified your program a little. ``` def student_data(): student_list = [] while True: # Ask for the name of the student student_name = input("Please enter the student name, press ...
13,392
67,655,396
I'm trying to migrate my custom user model and I run makemigrations command to make migrations for new models. But when I run migrate command it throws this error : > > conn = \_connect(dsn, connection\_factory=connection\_factory, > \*\*kwasync) django.db.utils.OperationalError > > > **Trace back:** ``` (ve...
2021/05/23
[ "https://Stackoverflow.com/questions/67655396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14472949/" ]
> > I'm trying to understand Linux OS library dependencies to effectively run python 3.9 and imported pip packages to work. > > > Your questions may have pretty broad answers and depend on a bunch of input factors you haven't mentioned. > > Is there a requirement for GCC to be installed for pip modules with c ex...
Python depends on compilers and a lot of other tools if you're going to compile the source (from the repository). This is from the offical repository, telling you what you need to compile it from source, [check it out](https://devguide.python.org/setup/#install-dependencies). > > **1.4. Install dependencies** > This ...
13,393
51,346,677
``` ERROR: build step 1 "gcr.io/gae-runtimes/nodejs8_app_builder:nodejs8_20180618_RC02" failed: exit status 1 ERROR Finished Step #1 - "builder" Step #1 - "builder": Permission denied for "be8392bdf4a2c92301391a124a5b72078453db3c15fcfc71f923e3c63d1bd8ea" from request "/v2/PROJECT_ID/app-engine-build-cache/node-cache/m...
2018/07/15
[ "https://Stackoverflow.com/questions/51346677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8025518/" ]
> > ### Troubleshooting > > > If you find 403 (access denied) errors in your build logs, try the following steps: > > > Disable the Cloud Build API and re-enable it. Doing so should give your service account access to your project again. > > > Fixed an issue for me.
It shows in the 1st few lines of the log that image couldnt be pulled from registry due to unauthorized user credentials accessing the registry. Did you check the credentials? If you have a token based login, check if the token is not expired.
13,394
45,417,077
I've got a module called `core`, which contains a number of python files. If I do: ``` from core.curve import Curve ``` Does `__init__.py` get called? Can I move import statements that apply to all core files into `__init__.py` to save repeating myself? What **should** go into `__init__.py`?
2017/07/31
[ "https://Stackoverflow.com/questions/45417077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222151/" ]
> > Is \_\_init\_\_.py run everytime I import anything from that module? > > > According to [docs](https://docs.python.org/2/tutorial/modules.html#importing-from-a-package) in most cases **yes**, it is.
You can add all your functions that you want to use in your directory ``` - core - __init__.py ``` in this `__init__.py` add your class and function references like ``` from .curve import Curve from .some import SomethingElse ``` and where you want to User your class just refer it like ``` from core import Cu...
13,397
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.
13,400
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" ```
13,402
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 'test.jpg=@test.jpg'. 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
13,403
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] --------------------------------------...
13,404
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<>(); ```
13,413
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...
13,423
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`.
13,424
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...
13,425
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 ...
13,428
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...
13,429
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....
13,430
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) ...
13,440
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" ...
13,441
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...
13,444
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...
13,445
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) ```
13,448
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
13,453
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...
13,455
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...
13,457
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,458
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 ```
13,459
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...
13,460
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))...
13,461
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...
13,463
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...
13,466
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...
13,475
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',...
13,477
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...
13,478
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...
13,481
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...
13,483
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() ```
13,484
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...
13,493
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] ```
13,498
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)) ```
13,499
50,653,208
What I want to achieve is simple, in R I can do things like `paste0("https\\",1:10,"whatever",11:20)`, how to do such in Python? I found some things [here](https://stackoverflow.com/questions/28046408/equivalent-of-rs-paste-command-for-vector-of-numbers-in-python), but only allow for : `paste0("https\\",1:10)`. Any...
2018/06/02
[ "https://Stackoverflow.com/questions/50653208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6113825/" ]
**@Jason**, I will suggest you to use any of these following 2 ways to do this task. ✓ By creating a list of texts using **list comprehension** and **zip()** function. > > **Note:** To print `\` on screen, use escape sequence `\\`. See [List of escape sequences and their use](https://msdn.microsoft.com/en-us/library...
**Based on the link you provided,** this should work: ``` ["https://" + str(i) + "whatever" + str(i) for i in xrange(1,11)] ``` Gives the following output: ``` ['https://1whatever1', 'https://2whatever2', 'https://3whatever3', 'https://4whatever4', 'https://5whatever5', 'https://6whatever6', 'https://7whatever7',...
13,500
29,219,814
Im kinda new to python, im trying to the basic task of splitting string data from a file using a double backslash (\\) delimiter. Its failing, so far: ``` from tkinter import filedialog import string import os #remove previous finalhostlist try: os.remove("finalhostlist.txt") except E...
2015/03/23
[ "https://Stackoverflow.com/questions/29219814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3014488/" ]
write expects a string and you have passed it a list, if you want the contents written use `str.join`. ``` rawhostlist.write("\n".join(line.split("\\"))) ``` You also don't need to call close when you use `with`, it closes your file automatically and you actually never call close anyway as you are missing parens `ra...
if you want them written on separate lines: ``` for sub in line.split("\\"):rawhostlist.write(sub) ```
13,501
20,369,642
I'm trying to get the keyboard code of a character pressed in python. For this, I need to see if a keypad number is pressed. *This is not what I'm looking for*: ``` import tty, sys tty.setcbreak(sys.stdin) def main(): tty.setcbreak(sys.stdin) while True: c = ord(sys.stdin.read(1)) if c == or...
2013/12/04
[ "https://Stackoverflow.com/questions/20369642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1224926/" ]
As synthesizerpatel said, I need to go to a lower level. Using pyusb: ``` import usb.core, usb.util, usb.control dev = usb.core.find(idVendor=0x045e, idProduct=0x0780) try: if dev is None: raise ValueError('device not found') cfg = dev.get_active_configuration() interface_number = cfg[(0,0)].b...
To get raw keyboard input from Python you need to snoop at a lower level than reading stdin. For OSX check this answer: [OS X - Python Keylogger - letters in double](https://stackoverflow.com/questions/13806829/os-x-python-keylogger-letters-in-double) For Windows, this might work: <http://www.daniweb.com/software-d...
13,504
54,229,785
How to check whether a folder exists in google drive with name using python? I have tried with the following code: ``` import requests import json access_token = 'token' url = 'https://www.googleapis.com/drive/v3/files' headers = { 'Authorization': 'Bearer' + access_token } response = requests.get(url, headers=h...
2019/01/17
[ "https://Stackoverflow.com/questions/54229785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10506357/" ]
* You want to know whether a folder is existing in Google Drive using the folder name. * You want to achieve it using the access token and `requests.get()`. If my understanding is correct, how about this modification? Please think of this as just one of several answers. ### Modification points: * You can search the ...
You may see this [sample code](https://gist.github.com/jmlrt/f524e1a45205a0b9f169eb713a223330) on how to check if destination folder exists and return its ID. ``` def get_folder_id(drive, parent_folder_id, folder_name): """ Check if destination folder exists and return it's ID """ # Auto-iterate ...
13,507
43,223,017
I am attempting to understand the excellent Code given as a guide by Andrej Karpathy: <https://gist.github.com/karpathy/d4dee566867f8291f086> I am new to python, still learning! I am doing the best I can to understand the following code from the link: ``` # perform parameter update with Adagrad for param, dparam, me...
2017/04/05
[ "https://Stackoverflow.com/questions/43223017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183804/" ]
Write a simple for loop with zip will help you learn a lot. for example: ``` for a, b, c in zip([1,2,3], [4,5,6], [7,8,9]): print a print b print c print "/" ``` This function will print: 1 4 7 / 2 5 8 / 3 6 7 So that the zip function just put those three lis...
Python treats the variables merely as *labels* or name tags. Since you have zipped those inside a `list` of lists, it doesn't matter where they are, as long as you address them by their name / label correctly. Kindly note, this may not work for immutable types like `int` or `str`, etc. Refer to this answer for more exp...
13,508
73,425,359
I am running Ubuntu 22.04 with xorg. I need to find a way to compile microbit python code locally to a firmware hex file. Firstly, I followed the guide here <https://microbit-micropython.readthedocs.io/en/latest/devguide/flashfirmware.html>. After a lot of debugging, I got to this point: <https://pastebin.com/MGShD31N...
2022/08/20
[ "https://Stackoverflow.com/questions/73425359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12625930/" ]
Mu and the uflash command are able to retrieve your Python code from .hex files. Using uflash you can do the following for example: ``` uflash my_script.py ``` I think that you want is somehow possible to do, but its harder than just using their web python editor: <https://python.microbit.org/v/2>
**Working Ubuntu 22.04 host CLI setup with Carlos Atencio's Docker to build your own firmware** After trying to setup the toolchain for a while, I finally decided to Google for a Docker image with the toolchain, and found <https://github.com/carlosperate/docker-microbit-toolchain> [at this commit](https://github.com/c...
13,516
9,725,737
> > **Possible Duplicate:** > > [Tool to convert python indentation from spaces to tabs?](https://stackoverflow.com/questions/338767/tool-to-convert-python-indentation-from-spaces-to-tabs) > > > I have a number of python files (>1000) that need to be reformatted so indentation is done only with tabs (yes, i kn...
2012/03/15
[ "https://Stackoverflow.com/questions/9725737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69882/" ]
I would suggest using this [Reindent](http://pypi.python.org/pypi/Reindent/0.1.0) script on PyPI to convert all of your horribly inconsistent files to a consistent PEP-8 (4-space indents) version. At this point try one more time to convince whoever decided on tabs that the company coding standard is stupid and PEP-8 s...
How about ``` find . -type f -iname \*.py -print0 | xargs -0 sed -i 's/^ /\t/' ``` This command finds all .py files below the current directory and replaces every four consecutive spaces it finds inside of them with a tab. Just noticed Spacedman's comment. This approach will not handle spaces at the beginning of...
13,519
37,817,559
I've packaged a [this simple flask app](https://github.com/SimplyAhmazing/pyinstaller-tut) using PyInstaller but my OSX executable fails to run and shows the following executable, ``` Error loading Python lib '/Users/ahmed/Code/play/py-install-tut/dist/myscript.app/Contents/MacOS/Python': dlopen(/Users/ahmed/Code/play...
2016/06/14
[ "https://Stackoverflow.com/questions/37817559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/772401/" ]
The minimum deployment target with Xcode 8 is iOS 8. To support target the iOS SDK 7.x and below, use Xcode 7. If you try to use a deployment target of iOS 7.x or below, Xcode will suggest you change your target to iOS 8: [![Xcode Warning](https://i.stack.imgur.com/LGe5e.png)](https://i.stack.imgur.com/LGe5e.png)
Apple has changed so much since iOS 7 until now. The easiest way of not having to deal with backward compatibility is to make the old OS's obsolete. ~~So you have 2 choices. You can leave the setting as is and deal with the warning message,~~ or you can change the setting and not support iOS 7 or lower any longer. Ther...
13,520
67,117,219
i am new to coding and python and i was wondering how to create a regex that will match all ip addresses that start with 192.168.1.xxx I have been looking online and have not yet been able to find a match. Here is some some sample data that i am trying to match them from. ``` /index.html HTTP/1.1" 404 208 "-" "Mozill...
2021/04/15
[ "https://Stackoverflow.com/questions/67117219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12920080/" ]
Here you go. Also, checkout <https://regexr.com/> `^192\.168\.1\.[0-9]{1,3}$`
I think here its best to use a combination of `regex` to grab any valid IP address from your data, row by row. Then use `ipaddress` to check if the address sits within the network you're looking for. This will provide much more flexibility in the case you need to check different networks, instead of rewriting the `reg...
13,526
16,024,041
I'm having issues sending unicode to SQL Server via pymssql: ``` In [1]: import pymssql conn = pymssql.connect(host='hostname', user='me', password='password', database='db') cursor = conn.cursor() In [2]: s = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' In [3]: s...
2013/04/15
[ "https://Stackoverflow.com/questions/16024041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599229/" ]
Ended up using pypyodbc instead. Needed some assistance to [connect](https://stackoverflow.com/questions/16024956/connecting-to-sql-server-with-pypyodbc), then used the [doc recipe](https://code.google.com/p/pypyodbc/wiki/A_HelloWorld_sample_to_access_mssql_with_python) for executing statements: ``` import pypyodbc co...
Here is something which worked for me: ``` # -*- coding: utf-8 -*- import pymssql conn = pymssql.connect(host='hostname', user='me', password='password', database='db') cursor = conn.cursor() s = u'Monsieur le Curé of the «Notre-Dame-de-Grâce» neighborhood' cursor.execute("INSERT INTO MyTable(col1) VALUES(%s)", s.en...
13,528
40,700,192
The Virt-Manager is capable of modifying network interfaces of running domains, for example changing the connected network. I want to script this in python with the libvirt-API. ``` import libvirt conn = libvirt.open('qemu:///system') deb = conn.lookupByName('Testdebian') xml = deb.XMLDesc() xml = replace('old-netwo...
2016/11/20
[ "https://Stackoverflow.com/questions/40700192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6204346/" ]
This is very easy in [c++17](/questions/tagged/c%2b%2b17 "show questions tagged 'c++17'"). ``` template<class Tuple> decltype(auto) sum_components(Tuple const& tuple) { auto sum_them = [](auto const&... e)->decltype(auto) { return (e+...); }; return std::apply( sum_them, tuple ); }; ``` or `(...+e)` for th...
With C++1z it's pretty simple with [fold expressions](http://en.cppreference.com/w/cpp/language/fold). First, forward the tuple to an `_impl` function and provide it with index sequence to access all tuple elements, then sum: ``` template<typename T, size_t... Is> auto sum_components_impl(T const& t, std::index_sequen...
13,531
43,628,733
I wrote this code to display contents of a list in grid form . It works fine for the alphabet list . But when i try to run it with a randomly generated list it gives an list index out of range error . Here is the full code: import random ``` #barebones 2d shell grid generator ''' Following list is a place holder...
2017/04/26
[ "https://Stackoverflow.com/questions/43628733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5698361/" ]
I suggest you use the function '.load' rather than '.csv', something like this: ``` data = sc.read.load(path_to_file, format='com.databricks.spark.csv', header='true', inferSchema='true').cache() ``` Of you course you can add more options. Then you can si...
It would be good if you can provide some sample data next time. How should we know how your csv looks like. Concerning your question, it looks like that your csv column is not a decimal all the time. InferSchema takes the first row and assign a datatype, in your case, it is a [DecimalType](http://spark.apache.org/docs/...
13,532
48,761,673
I want to solve a case where i know what all will be contents of the string output.. but i am not sure about the order of the contents inside the output.. say, the expected contents of my output are `['this','output','can','be','jumbled','in','any','order']`.. and the output can be `'this can in any order jumbled out...
2018/02/13
[ "https://Stackoverflow.com/questions/48761673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7534349/" ]
Use [`contains(where:)`](https://developer.apple.com/documentation/swift/sequence/2905153-contains) on the dictionary values: ``` // Enable button if at least one value is not nil: button.isEnabled = dict.values.contains(where: { $0 != nil }) ``` Or ``` // Enable button if no value is nil: button.isEnabled = !dict....
You can use [`filter`](https://developer.apple.com/documentation/swift/sequence/2905694-filter) to check if any value is nil in a dictionary. ``` button.isEnabled = dict.filter { $1 == nil }.isEmpty ```
13,535
53,140,438
How to create cumulative sum (new\_supply)in dataframe python from demand column from table ``` item Date supply demand A 2018-01-01 0 10 A 2018-01-02 0 15 A 2018-01-03 100 30 A 2018-01-04 0 10 A 2018-01-05 0 40 A 2018-01-06 50 50 A 2018-01-07...
2018/11/04
[ "https://Stackoverflow.com/questions/53140438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10603056/" ]
Make the python file executable chmod +x Test.py
Why do you have to include the logic inside a class? note = 10 if note >= 10: print("yes") else: print("NO") Just this will do, remove the class
13,540
3,885,846
I'd like to call a .py file from within python. It is in the same directory. Effectivly, I would like the same behavior as calling python foo.py from the command line without using any of the command line tools. How should I do this?
2010/10/07
[ "https://Stackoverflow.com/questions/3885846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450054/" ]
It's not quite clear (at least to me) what you mean by using "none of the command-line tools". To run a program in a subprocess, one usually uses the `subprocess` module. However, if both the calling and the callee are python scripts, there is another alternative, which is to use the `multiprocessing` module. For e...
``` execfile('foo.py') ``` See also: * [Further reading on execfile](http://docs.python.org/library/functions.html#execfile)
13,542
61,270,154
I used to have my app on Heroku and the way it worked there was that I had 2 buildpacks. One for NodeJS and one for Python. Heroku ran `npm run build` and then Django served the files from the `build` folder. I use Code Pipeline on AWS to deploy a new version of my app every time there is a new push on my GitHub repos...
2020/04/17
[ "https://Stackoverflow.com/questions/61270154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11804213/" ]
So I figured out one solution that worked for me. Since I want to create the build version of my app on the server the way Heroku does it with the NodeJS buildpack, I had to create a command that installs node like this: ``` container_commands: 01_install_node: command: "curl -sL https://rpm.nodesource.com/setu...
I don't know exactly Python but I guess you can adapt for you case. Elastic Beanstalk for Node.js platform use by default `app.js`, then `server.js`, and then `npm start` (in that order) to start your application. You can change this behavior with **configuration files**. Below the steps to accomplish with Node.js: ...
13,544