qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
9,353,457
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently. How do you pass variables to and from functions properly. In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not wo...
2012/02/19
[ "https://Stackoverflow.com/questions/9353457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1191626/" ]
I think this is what you want to do: ``` a = "foo" def func_1(): b = "bar" print a,b return b # Took out parenthasis returned_b = func_1() # Added variable to hold the returned "b" print returned_b ``` It looks like you are just learning to code in general. Your issues look to be with understanding how comp...
I think you mean, how do I access values that I return from a function. Say you have a function: ``` def func_1(): b = 1 return b ``` If you want the return value from that function, set some variable equal to it, like so: ``` someVariable = func_1() #func_1 executes it's code, and returns the value contai...
9,353,457
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently. How do you pass variables to and from functions properly. In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not wo...
2012/02/19
[ "https://Stackoverflow.com/questions/9353457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1191626/" ]
I think this is what you want to do: ``` a = "foo" def func_1(): b = "bar" print a,b return b # Took out parenthasis returned_b = func_1() # Added variable to hold the returned "b" print returned_b ``` It looks like you are just learning to code in general. Your issues look to be with understanding how comp...
The `b` inside `func_1()` is local to the function and not available outside of the function. You need to *assign* the returned value of the function `func_1()` to a variable name in the main body. ``` b = func_1() print b ```
9,353,457
As I muddle my way through trying to learn how to code (in python) I've hit the same problem I hit frequently. How do you pass variables to and from functions properly. In this example, I want to create a new variable inside the function process, but I don't know how to get it back properly (this method does not wo...
2012/02/19
[ "https://Stackoverflow.com/questions/9353457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1191626/" ]
I think this is what you want to do: ``` a = "foo" def func_1(): b = "bar" print a,b return b # Took out parenthasis returned_b = func_1() # Added variable to hold the returned "b" print returned_b ``` It looks like you are just learning to code in general. Your issues look to be with understanding how comp...
You've returned it, but not assigned it to anything: ``` def func_1(): b = "bar" a = 2 return a, b a, b = func_1() print b ```
60,445,837
i have an api end point where i am uploading data to using python. end point accepts ``` putHeaders = { 'Authorization': user, 'Content-Type': 'application/octet-stream' } ``` My current code is doing this .Save a dictionary as csv file .Encode csv to utf8 ``` dataFile = open(fileData['name'], 'r').r...
2020/02/28
[ "https://Stackoverflow.com/questions/60445837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10004110/" ]
Here's a [working example](https://stackblitz.com/edit/react-ts-w55wqg). You have to install the `@types/faker` package also for getting type definitions. ``` import React, { Component } from 'react'; import { render } from 'react-dom'; import Hello from './Hello'; import './style.css'; import faker from 'faker'; i...
I had the same issue and tried the above suggested solution without success. What worked for me, was changing the following line in `tsconfig.json`: `//"module": "esnext", "module": "commonjs",` Or, pass it at the command-line: `ts-node -O '{"module": "commonjs"}' ./server/generate.ts > ./server/database.json` Expl...
2,754,753
I use pylons in my job, but I'm new to django. I'm making an rss filtering application, and so I'd like to have two backend processes that run on a schedule: one to crawl rss feeds for each user, and another to determine relevance of individual posts relative to users' past preferences. In pylons, I'd just write paster...
2010/05/02
[ "https://Stackoverflow.com/questions/2754753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303931/" ]
Yes, this is actually how I run my cron backup scripts. You just need to load your virtualenv if you're using virtual environments and your project settings. I hope you can follow this, but after the line `# manage.py shell` you can write your code just as if you were in `manage.py shell` You can import your virtuale...
Sounds like you need some twod.wsgi in your life: <http://packages.python.org/twod.wsgi/>
2,754,753
I use pylons in my job, but I'm new to django. I'm making an rss filtering application, and so I'd like to have two backend processes that run on a schedule: one to crawl rss feeds for each user, and another to determine relevance of individual posts relative to users' past preferences. In pylons, I'd just write paster...
2010/05/02
[ "https://Stackoverflow.com/questions/2754753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303931/" ]
I think that's what [Custom Management Commands](http://docs.djangoproject.com/en/dev/howto/custom-management-commands/) are there for.
Sounds like you need some twod.wsgi in your life: <http://packages.python.org/twod.wsgi/>
5,482,546
so I have a list with a whole bunch of tuples ``` j = [('jHKT', 'Dlwp Dfbd Gwlgfwqs (1kkk)', 53.0), ('jHKT', 'jbdbjf Bwvbly (1kk1)', 35.0), ('jHKT', 'Tfstzfy (2006)', 9.0), ('jHKT', 'fjznfnt Dwjbzn (1kk1)', 25.0), ('jHKT', 'Vznbsq sfnkz (1k8k)', 4.0), ('jHKT', 'fxzt, Clwwny! (2005)', 8.0), ('jHKT', "Dwfs Thzs jfbn W...
2011/03/30
[ "https://Stackoverflow.com/questions/5482546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
I think your code works correctly and you see the first part of the list, where key is realy 0.0. You just sort the list in ascending order :-)
It's probably worth comparing the sorted and unsorted lists to see if the sort is actually changing data. You could try something as simple as: ``` print sum(e[2] for e in j) j = sorted(j, key=lambda e : e[2]) print sum(e[2] for e in j) ```
5,482,546
so I have a list with a whole bunch of tuples ``` j = [('jHKT', 'Dlwp Dfbd Gwlgfwqs (1kkk)', 53.0), ('jHKT', 'jbdbjf Bwvbly (1kk1)', 35.0), ('jHKT', 'Tfstzfy (2006)', 9.0), ('jHKT', 'fjznfnt Dwjbzn (1kk1)', 25.0), ('jHKT', 'Vznbsq sfnkz (1k8k)', 4.0), ('jHKT', 'fxzt, Clwwny! (2005)', 8.0), ('jHKT', "Dwfs Thzs jfbn W...
2011/03/30
[ "https://Stackoverflow.com/questions/5482546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
i too think its ok[in quick glance] .. check this link .. it's about various sorting techniques in python <http://wiki.python.org/moin/HowTo/Sorting/>
It's probably worth comparing the sorted and unsorted lists to see if the sort is actually changing data. You could try something as simple as: ``` print sum(e[2] for e in j) j = sorted(j, key=lambda e : e[2]) print sum(e[2] for e in j) ```
5,482,546
so I have a list with a whole bunch of tuples ``` j = [('jHKT', 'Dlwp Dfbd Gwlgfwqs (1kkk)', 53.0), ('jHKT', 'jbdbjf Bwvbly (1kk1)', 35.0), ('jHKT', 'Tfstzfy (2006)', 9.0), ('jHKT', 'fjznfnt Dwjbzn (1kk1)', 25.0), ('jHKT', 'Vznbsq sfnkz (1k8k)', 4.0), ('jHKT', 'fxzt, Clwwny! (2005)', 8.0), ('jHKT', "Dwfs Thzs jfbn W...
2011/03/30
[ "https://Stackoverflow.com/questions/5482546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380714/" ]
As others said, the code is perfectly fine. You should try to isolate the situation and try to find out where exactly the issue happened. * Does it happen in a simple script which only contains the list assignment and the sort operation? * Do other list operations work? Try slicing, iterating over it, or sorting witho...
It's probably worth comparing the sorted and unsorted lists to see if the sort is actually changing data. You could try something as simple as: ``` print sum(e[2] for e in j) j = sorted(j, key=lambda e : e[2]) print sum(e[2] for e in j) ```
70,541,783
I'm python user learning R. Frequently, I need to check if columns of a dataframe contain NaN(s). In python, I can simply do ``` import pandas as pd df = pd.DataFrame({'colA': [1, 2, None, 3], 'colB': ['A', 'B', 'C', 'D']}) df.isna().any() ``` giving me ``` colA True colB False dtype: ...
2021/12/31
[ "https://Stackoverflow.com/questions/70541783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2743931/" ]
The best waty to check if columns have NAs is to apply a loop to the columns with a function to check whether there is `any(is.na)`. ``` lapply(df, function(x) any(is.na(x))) $colA [1] TRUE $colB [1] FALSE ``` I can see you load the tidyverse yet did not use it in your example. If we want to do this within the tid...
The easiest way would be: ``` df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) is.na(df) ``` **Output:** ``` colA colB [1,] FALSE FALSE [2,] FALSE FALSE [3,] TRUE FALSE [4,] FALSE FALSE ``` **Update**, if you only want to see the rows containing NA: ``` > df[rowSums(is.na(df)) > 0,] ...
70,541,783
I'm python user learning R. Frequently, I need to check if columns of a dataframe contain NaN(s). In python, I can simply do ``` import pandas as pd df = pd.DataFrame({'colA': [1, 2, None, 3], 'colB': ['A', 'B', 'C', 'D']}) df.isna().any() ``` giving me ``` colA True colB False dtype: ...
2021/12/31
[ "https://Stackoverflow.com/questions/70541783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2743931/" ]
You can use anyNA: Checks for NA in a vector ``` df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) sapply(df, anyNA) colA colB TRUE FALSE ``` Edit ---- [jay.sf](https://stackoverflow.com/questions/70541783/the-simplest-way-to-check-for-nans-in-columns-r/70541887#comment124698260_70541887) is ...
The easiest way would be: ``` df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) is.na(df) ``` **Output:** ``` colA colB [1,] FALSE FALSE [2,] FALSE FALSE [3,] TRUE FALSE [4,] FALSE FALSE ``` **Update**, if you only want to see the rows containing NA: ``` > df[rowSums(is.na(df)) > 0,] ...
70,541,783
I'm python user learning R. Frequently, I need to check if columns of a dataframe contain NaN(s). In python, I can simply do ``` import pandas as pd df = pd.DataFrame({'colA': [1, 2, None, 3], 'colB': ['A', 'B', 'C', 'D']}) df.isna().any() ``` giving me ``` colA True colB False dtype: ...
2021/12/31
[ "https://Stackoverflow.com/questions/70541783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2743931/" ]
You can use anyNA: Checks for NA in a vector ``` df = data.frame(colA = c(1, 2, NA, 3), colB = c('A', 'B', 'C', 'D')) sapply(df, anyNA) colA colB TRUE FALSE ``` Edit ---- [jay.sf](https://stackoverflow.com/questions/70541783/the-simplest-way-to-check-for-nans-in-columns-r/70541887#comment124698260_70541887) is ...
The best waty to check if columns have NAs is to apply a loop to the columns with a function to check whether there is `any(is.na)`. ``` lapply(df, function(x) any(is.na(x))) $colA [1] TRUE $colB [1] FALSE ``` I can see you load the tidyverse yet did not use it in your example. If we want to do this within the tid...
67,126,748
I have a problem with my python(python3.8.5) project! I have two docker containers. One is used for the frontend(container2) using flask. There I have a website where I can send requests(package requests) to the second container(backend). In the backend(container1) I have to create a zip file containing multiple file. ...
2021/04/16
[ "https://Stackoverflow.com/questions/67126748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15661344/" ]
A probably incomplete solution, that does what you describe. Depending on other concerns (like file size) this might not be what you really want, but it works. As an example I have 2 flask servers: flask1 (backend) and flask2 (frontend): flask1: ``` from flask import Flask, send_file, request app = Flask(__name__) ...
You could proxy the request from frontend. I assume you use something like react. So if you add a line like: ``` "proxy": "http://backend-container:8080" ``` to your package.json, frontend should proxy to the backend. Now you can send requests like http://front-end/api/hello and it will hit the backend. Not sure if ...
71,451,635
This is my first question in here. Question is mostly about Python but a little bit about writing crypto trading bot. I need to calculate some indicators about trading like Bollinger Bands, RSI or etc in my bot. Indicators are calculated from candlesticks data in trading. And candlesticks data updated in their time pe...
2022/03/12
[ "https://Stackoverflow.com/questions/71451635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It's not quite obvious from your description what `CandlestickUpdater` is for. It looks like its purpose is to notify `TradeControl` that time has come to update `candlestick_data`, whereas updating logic itself is in the `TradeControl.update_candlestick` method. So basically `CandlestickUpdater` is a timer. There are...
> > **Q :** *" ... should (I) use mutex-like structures to guard against conditions like race condition "... ?* > > > **A :** Given the facts, how the Python Interpreter works ( since ever & most probably forever, as Guido von Rossum has expressed himself ) with all its threads, distributing ***"a permission to ...
70,648,020
[![enter image description here](https://i.stack.imgur.com/dbDhf.png)](https://i.stack.imgur.com/dbDhf.png) I configured python 3.6 in JetBrains initially but uninstalled it today since it reached end-of-life. I installed version 3.10 but I keep getting the error that "Python 3.1 has reached end of date." Clicking on...
2022/01/10
[ "https://Stackoverflow.com/questions/70648020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13706804/" ]
We can do this with only one function, `Array.find()`. We can do this by checking if it is equal to the `Remove invalid product` inside the function. See the example below. ```js const responses = [{ "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid prod...
You can do it using `array.find()`. Try this code it's help you ! ``` function App() { const responses = [ { "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid product" } ]; return ( <div> checkResponses : {res...
70,648,020
[![enter image description here](https://i.stack.imgur.com/dbDhf.png)](https://i.stack.imgur.com/dbDhf.png) I configured python 3.6 in JetBrains initially but uninstalled it today since it reached end-of-life. I installed version 3.10 but I keep getting the error that "Python 3.1 has reached end of date." Clicking on...
2022/01/10
[ "https://Stackoverflow.com/questions/70648020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13706804/" ]
You can do it using `array.find()`. Try this code it's help you ! ``` function App() { const responses = [ { "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid product" } ]; return ( <div> checkResponses : {res...
**strong text** ``` const responses = [ { "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid product" } ]; console.log(responses.find(variable => variable?.hasOwnProperty('status'))?.status); ```
70,648,020
[![enter image description here](https://i.stack.imgur.com/dbDhf.png)](https://i.stack.imgur.com/dbDhf.png) I configured python 3.6 in JetBrains initially but uninstalled it today since it reached end-of-life. I installed version 3.10 but I keep getting the error that "Python 3.1 has reached end of date." Clicking on...
2022/01/10
[ "https://Stackoverflow.com/questions/70648020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13706804/" ]
We can do this with only one function, `Array.find()`. We can do this by checking if it is equal to the `Remove invalid product` inside the function. See the example below. ```js const responses = [{ "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid prod...
**strong text** ``` const responses = [ { "productName": "Required" }, null, { "status": "Remove invalid product" }, { "status": "Remove invalid product" } ]; console.log(responses.find(variable => variable?.hasOwnProperty('status'))?.status); ```
12,491,731
I am using tkMessageBox.showinfo ([info at tutorialspoint](http://www.tutorialspoint.com/python/tk_messagebox.htm)) to popup warnings in my program. The problem happens only when the warning is called with a second TopLevel window (apart from the main one) on screen: in this case the warning remains hidden behind the ...
2012/09/19
[ "https://Stackoverflow.com/questions/12491731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538256/" ]
I think the message box is only ever guaranteed to be above its parent. If you create a second toplevel and you want a messagebox to be on top of that second window, make that second window the parent of the messagebox. ``` tl2 = tk.Toplevel(...) ... tkMessageBox.showinfo("Say Hello", "Hello World", parent=tl2) ```
I do not see the issue that you describe. The code I wrote below is just about the minimum needed to create a window which creates a second window. The second window creates an info box using the `showinfo` method. I wonder whether you have something besides this. (Note that I made the windows somewhat large in order t...
57,672,921
For clarity, i was looking for a way to compile multiple regex at once. For simplicity, let's say that every expression should be in the format `(.*) something (.*)`. There will be no more than 60 expressions to be tested. As seen [here](https://stackoverflow.com/questions/42136040/how-to-combine-multiple-regex-into-s...
2019/08/27
[ "https://Stackoverflow.com/questions/57672921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2243607/" ]
There are various issues with your example: 1. You are using a *capturing* group, so it gets the index `1` that you'd expect to reference the first group of the inner regexes. Use a non-capturing group `(?:%s|%s|%s|%s)` instead. 2. Group indexes increase even inside `|`. So`(?:(a)|(b)|(c))` you'd get: ``` >>> re.matc...
Giacomo answered the question. However, I also suggest: 1) put the "compile" before the loop, 2) gather non empty groups in a list, 3) think about using (.+) instead of (.\*) in re1,re2,etc. ``` rex= re.compile("%s|%s|%s|%s" % (re1, re2, re3, re4)) for sentence in sentences: match = rex.search(sentence...
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
Sorry for the very late response; I just stumbled onto this page. In case anyone visits this page in the future, the python module gmpy2 is designed to work with very large inputs, and includes among other things an integer square root function. Example: ``` >>> import gmpy2 >>> gmpy2.isqrt((10**100+1)**2) mpz(100000...
One option would be to use the `decimal` module, and do it in sufficiently-precise floats: ``` import decimal def isqrt(n): nd = decimal.Decimal(n) with decimal.localcontext() as ctx: ctx.prec = n.bit_length() i = int(nd.sqrt()) if i**2 != n: raise ValueError('input was not a perfe...
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
Python's default `math` library has an integer square root function: > > ### [`math.isqrt(n)`](https://docs.python.org/3/library/math.html#math.isqrt) > > > Return the integer square root of the nonnegative integer *n*. This is the floor of the exact square root of *n*, or equivalently the greatest integer a such t...
Your function fails for large inputs: ``` In [26]: isqrt((10**100+1)**2) ValueError: input was not a perfect square ``` There is a [recipe on the ActiveState site](http://code.activestate.com/recipes/577821-integer-square-root-function/) which should hopefully be more reliable since it uses integer maths only. It i...
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
Seems like you could check like this: ``` if int(math.sqrt(n))**2 == n: print n, 'is a perfect square' ``` Update: As you pointed out the above fails for large values of `n`. For those the following looks promising, which is an adaptation of the example C code, by Martin Guy @ UKC, June 1985, for the relatively...
Inspired by all answers, decided to implement in pure C++ several best methods from these answers. As everybody knows C++ is always faster than Python. To glue C++ and Python I used [Cython](https://cython.org/). It allows to make out of C++ a Python module and then call C++ functions directly from Python functions. ...
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
Sorry for the very late response; I just stumbled onto this page. In case anyone visits this page in the future, the python module gmpy2 is designed to work with very large inputs, and includes among other things an integer square root function. Example: ``` >>> import gmpy2 >>> gmpy2.isqrt((10**100+1)**2) mpz(100000...
Floats cannot be precisely represented on computers. You can test for a desired proximity setting epsilon to a small value within the accuracy of python's floats. ``` def isqrt(n): epsilon = .00000000001 i = int(n**.5 + 0.5) if abs(i**2 - n) < epsilon: return i raise ValueError('input was not a...
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
Here's a very straightforward implementation: ``` def i_sqrt(n): i = n.bit_length() >> 1 # i = floor( (1 + floor(log_2(n))) / 2 ) m = 1 << i # m = 2^i # # Fact: (2^(i + 1))^2 > n, so m has at least as many bits # as the floor of the square root of n. # # Proof: (2^(i+1))^2 = 2^(2i + ...
Floats cannot be precisely represented on computers. You can test for a desired proximity setting epsilon to a small value within the accuracy of python's floats. ``` def isqrt(n): epsilon = .00000000001 i = int(n**.5 + 0.5) if abs(i**2 - n) < epsilon: return i raise ValueError('input was not a...
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
***Note:** There is now [`math.isqrt`](https://docs.python.org/3/library/math.html#math.isqrt) in stdlib, available since Python 3.8.* Newton's method works perfectly well on integers: ```python def isqrt(n): x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x ```...
**Long-hand square root algorithm** It turns out that there is an algorithm for computing square roots that you can compute by hand, something like long-division. Each iteration of the algorithm produces exactly one digit of the resulting square root while consuming two digits of the number whose square root you seek....
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
One option would be to use the `decimal` module, and do it in sufficiently-precise floats: ``` import decimal def isqrt(n): nd = decimal.Decimal(n) with decimal.localcontext() as ctx: ctx.prec = n.bit_length() i = int(nd.sqrt()) if i**2 != n: raise ValueError('input was not a perfe...
The script below extracts integer square roots. It uses no divisions, only bitshifts, so it is quite fast. It uses [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method) on the inverse square root, a technique made famous by *Quake III Arena* as mentioned in the Wikipedia article, [Fast inverse square root]...
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
**Long-hand square root algorithm** It turns out that there is an algorithm for computing square roots that you can compute by hand, something like long-division. Each iteration of the algorithm produces exactly one digit of the resulting square root while consuming two digits of the number whose square root you seek....
Your function fails for large inputs: ``` In [26]: isqrt((10**100+1)**2) ValueError: input was not a perfect square ``` There is a [recipe on the ActiveState site](http://code.activestate.com/recipes/577821-integer-square-root-function/) which should hopefully be more reliable since it uses integer maths only. It i...
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
**Update:** [Python 3.8 has a `math.isqrt` function](https://docs.python.org/3/library/math.html#math.isqrt) in the standard library! I benchmarked every (correct) function here on both small (0…222) and large (250001) inputs. The clear winners in both cases are [`gmpy2.isqrt` suggested by mathmandan](https://stackove...
Your function fails for large inputs: ``` In [26]: isqrt((10**100+1)**2) ValueError: input was not a perfect square ``` There is a [recipe on the ActiveState site](http://code.activestate.com/recipes/577821-integer-square-root-function/) which should hopefully be more reliable since it uses integer maths only. It i...
15,390,807
Is there an integer square root somewhere in python, or in standard libraries? I want it to be exact (i.e. return an integer), and bark if there's no solution. At the moment I rolled my own naive one: ``` def isqrt(n): i = int(math.sqrt(n) + 0.5) if i**2 == n: return i raise ValueError('input was...
2013/03/13
[ "https://Stackoverflow.com/questions/15390807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
***Note:** There is now [`math.isqrt`](https://docs.python.org/3/library/math.html#math.isqrt) in stdlib, available since Python 3.8.* Newton's method works perfectly well on integers: ```python def isqrt(n): x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x ```...
Seems like you could check like this: ``` if int(math.sqrt(n))**2 == n: print n, 'is a perfect square' ``` Update: As you pointed out the above fails for large values of `n`. For those the following looks promising, which is an adaptation of the example C code, by Martin Guy @ UKC, June 1985, for the relatively...
72,394,305
I used this command: `python manage.py runserver 0:8080` After I logined the system I can reach rest API pages, but can't reach other pages. Although I send a request, the command output does not log. ``` Quit the server with CONTROL-C. ```
2022/05/26
[ "https://Stackoverflow.com/questions/72394305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15506634/" ]
You *can* actually convert from a string holding a base-16 number to a numeric value in plain Sqlite, but it's kind of ugly, using a [recursive CTE](https://sqlite.org/lang_with.html#recursive_common_table_expressions): ```sql WITH RECURSIVE hexnumbers(hexstr) AS (VALUES ('0x123'), ('0x4'), ('0x7f')), parse_hex(nu...
SQLite doesn't convert from hex to dec, you need to write such a function yourself. An example can be found in the [SQLite Forum](https://sqlite.org/forum/info/79dc039e21c6a1ea): ``` /* ** Function UNHEX(arg) -> blob ** ** Decodes the arg which must be an even number of hexidecimal characters into a blob and returns t...
32,215,510
I am quite new to use Frame of Tkinter in Python. I discovered Frame from the following [post](https://stackoverflow.com/questions/32198849/set-the-correct-tkinter-widgets-position-in-python) When i run the GUI the Check box are not in the same line. [![enter image description here](https://i.stack.imgur.com/jB3jB.p...
2015/08/25
[ "https://Stackoverflow.com/questions/32215510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493192/" ]
Answers to your Questions Bryan Oakley gave you. Here is some code so you can imagine what he is talking about: ``` from __future__ import division from Tkinter import * import tkFileDialog import tkMessageBox from ttk import Separator class MainWindow(Frame): def __init__(self): Frame.__init__(self) ...
1. Yes, it is possible to use `grid` In any frame you wish 2. Yes, it is possible to place "Camera white balance" and "average white balance" in the same row. 3. The reason the code runs forever without displaying anything is because you are using both grid (for the separator) and pack (for the frames). They both have ...
35,114,144
My Celery task raises a custom exception `NonTransientProcessingError`, which is then caught by `AsyncResult.get()`. Tasks.py: ``` class NonTransientProcessingError(Exception): pass @shared_task() def throw_exception(): raise NonTransientProcessingError('Error raised by POC model for test purposes') ``` In ...
2016/01/31
[ "https://Stackoverflow.com/questions/35114144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308967/" ]
``` import celery from celery import shared_task class NonTransientProcessingError(Exception): pass class CeleryTask(celery.Task): def on_failure(self, exc, task_id, args, kwargs, einfo): if isinstance(exc, NonTransientProcessingError): """ deal with NonTransientProcessingErro...
It might be a bit late, but I have a solution to solve this issue. Not sure if it is the best one, but it solved my problem at least. I had the same issue. I wanted to catch the exception produced in the celery task, but the result was of the class `celery.backends.base.CustomException`. The solution is in the followi...
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_i...
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
you can use: ``` public String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } private String capitalize(String s) { if (s == null ||...
In order to get android device name you have to add only a single line of code: ``` android.os.Build.MODEL; ``` Found here:[getting-android-device-name](http://developer.android.com/reference/android/os/Build.html)
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_i...
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
you can use: ``` public String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } private String capitalize(String s) { if (s == null ||...
you can also get it via bluetoothAdapter see [this](https://stackoverflow.com/a/23729614/4260932) ``` public String getPhoneName() { BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter(); String deviceName = myDevice.getName(); return deviceName; } ```
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_i...
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
you can use: ``` public String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } private String capitalize(String s) { if (s == null ||...
Download csv from here: <https://support.google.com/googleplay/answer/1727131?hl=en> > > See if your device works with Google Play by checking the list below. > When you download the PDF file, devices are ordered alphabetically > (A-Z) by manufacturer name. > > > Then import this file into your database. Quer...
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_i...
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
In order to get android device name you have to add only a single line of code: ``` android.os.Build.MODEL; ``` Found here:[getting-android-device-name](http://developer.android.com/reference/android/os/Build.html)
you can also get it via bluetoothAdapter see [this](https://stackoverflow.com/a/23729614/4260932) ``` public String getPhoneName() { BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter(); String deviceName = myDevice.getName(); return deviceName; } ```
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_i...
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
In order to get android device name you have to add only a single line of code: ``` android.os.Build.MODEL; ``` Found here:[getting-android-device-name](http://developer.android.com/reference/android/os/Build.html)
Download csv from here: <https://support.google.com/googleplay/answer/1727131?hl=en> > > See if your device works with Google Play by checking the list below. > When you download the PDF file, devices are ordered alphabetically > (A-Z) by manufacturer name. > > > Then import this file into your database. Quer...
20,839,308
I am using python sklearn library for doing classification of data. Following is the code I have implemented. I just want to ask, is this correct way of classifying? I mean can following code potentially remove all the biases? And, is it 10-k fold cross validation? ``` cv = cross_validation.ShuffleSplit(n_samples, n_i...
2013/12/30
[ "https://Stackoverflow.com/questions/20839308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2632729/" ]
Download csv from here: <https://support.google.com/googleplay/answer/1727131?hl=en> > > See if your device works with Google Play by checking the list below. > When you download the PDF file, devices are ordered alphabetically > (A-Z) by manufacturer name. > > > Then import this file into your database. Quer...
you can also get it via bluetoothAdapter see [this](https://stackoverflow.com/a/23729614/4260932) ``` public String getPhoneName() { BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter(); String deviceName = myDevice.getName(); return deviceName; } ```
34,074,840
I am doing a small python script to perform a wget call, however I am encountering an issue when I am replacing the string that contains the url/ip address and that it will be given to my "wget" string ``` import os import sys usr = sys.argv[1] pswd = sys.argv[2] ipAddr = sys.argv[3] wget = "wget http://{IPaddress...
2015/12/03
[ "https://Stackoverflow.com/questions/34074840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1757475/" ]
You aren't assigning the result of the `format` call to anything - you're just throwing it away. Try this instead: ``` wget = "wget http://{IPaddress}" wget = wget.format(IPaddress=ipAddr) print "The command wget is %s" %wget os.system(wget) ``` Alternatively, this seems a bit cleaner: ``` wget = "wget http://{I...
You need to actually format your `wget` string like this. ``` import os import sys usr = sys.argv[1] pswd = sys.argv[2] ipAddr = sys.argv[3] wget = "wget http://{IPaddress}".format(IPaddress=ipAddr) print "The command wget is %s" % wget os.system(wget) ``` `.format()` does not modify the string in place, it ret...
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ...
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In JupyterNotebook cell, Simply you can use: ``` %%html <style type='text/css'> .CodeMirror{ font-size: 17px; </style> ```
I would also suggest that you explore the options offered by the [**jupyter themer**](https://github.com/transcranial/jupyter-themer). For more modest interface changes you may be satisfied with running the syntax: ``` jupyter-themer [-c COLOR, --color COLOR] [-l LAYOUT, --layout LAYOUT] ...
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ...
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In JupyterNotebook cell, Simply you can use: ``` %%html <style type='text/css'> .CodeMirror{ font-size: 17px; </style> ```
In addition to the suggestion by Konrad here, I'd like to suggest [jupyter themes](https://github.com/dunovank/jupyter-themes), which seems to have more options, such as line-height, font size, cell width etc. Command line usage: ``` jt [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT] [-nfs NBFONTSIZE]...
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ...
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In JupyterNotebook cell, Simply you can use: ``` %%html <style type='text/css'> .CodeMirror{ font-size: 17px; </style> ```
For chrome users, This is very simple. Just install the desired font in your OS. Then open the said browser, Go to Settings -> Appearance -> Customize font. Go to fixed width font and from drop down list select the desired font. Note: This might also change the fonts at some other places depending on the web pages t...
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ...
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In addition to the suggestion by Konrad here, I'd like to suggest [jupyter themes](https://github.com/dunovank/jupyter-themes), which seems to have more options, such as line-height, font size, cell width etc. Command line usage: ``` jt [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT] [-nfs NBFONTSIZE]...
There is a much easier way to do without adding the CSS files and all the other methods suggested. But you have to do it every time you start the Jupiter notebook. Go to inspect in your browser and click on the element selection icon and then click on the box. And at the bottom of the page, you will be seeing the styl...
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ...
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
You can hover to `.ipython` folder (i.e. you can type `$ ipython locate` in your terminal/bash OR `CMD.exe Prompt` from your Anaconda Navigator to see where is your ipython is located) Then, in `.ipython`, you will see `profile_default` directory which is the default one. This directory will have `static/custom/custom...
In addition to the suggestion by Konrad here, I'd like to suggest [jupyter themes](https://github.com/dunovank/jupyter-themes), which seems to have more options, such as line-height, font size, cell width etc. Command line usage: ``` jt [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT] [-nfs NBFONTSIZE]...
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ...
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
I would also suggest that you explore the options offered by the [**jupyter themer**](https://github.com/transcranial/jupyter-themer). For more modest interface changes you may be satisfied with running the syntax: ``` jupyter-themer [-c COLOR, --color COLOR] [-l LAYOUT, --layout LAYOUT] ...
There is a much easier way to do without adding the CSS files and all the other methods suggested. But you have to do it every time you start the Jupiter notebook. Go to inspect in your browser and click on the element selection icon and then click on the box. And at the bottom of the page, you will be seeing the styl...
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ...
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In your notebook (simple approach). Add new cell with following code ``` %%html <style type='text/css'> .CodeMirror{ font-size: 12px; } div.output_area pre { font-size: 12px; } </style> ```
For chrome users, This is very simple. Just install the desired font in your OS. Then open the said browser, Go to Settings -> Appearance -> Customize font. Go to fixed width font and from drop down list select the desired font. Note: This might also change the fonts at some other places depending on the web pages t...
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ...
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
I would also suggest that you explore the options offered by the [**jupyter themer**](https://github.com/transcranial/jupyter-themer). For more modest interface changes you may be satisfied with running the syntax: ``` jupyter-themer [-c COLOR, --color COLOR] [-l LAYOUT, --layout LAYOUT] ...
For chrome users, This is very simple. Just install the desired font in your OS. Then open the said browser, Go to Settings -> Appearance -> Customize font. Go to fixed width font and from drop down list select the desired font. Note: This might also change the fonts at some other places depending on the web pages t...
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ...
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
In addition to the suggestion by Konrad here, I'd like to suggest [jupyter themes](https://github.com/dunovank/jupyter-themes), which seems to have more options, such as line-height, font size, cell width etc. Command line usage: ``` jt [-h] [-l] [-t THEME] [-f MONOFONT] [-fs MONOSIZE] [-nf NBFONT] [-nfs NBFONTSIZE]...
For chrome users, This is very simple. Just install the desired font in your OS. Then open the said browser, Go to Settings -> Appearance -> Customize font. Go to fixed width font and from drop down list select the desired font. Note: This might also change the fonts at some other places depending on the web pages t...
22,386,359
I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not change to browser). Specifically, what has to be put in the css file and which css file should be used? I am on a Windows ...
2014/03/13
[ "https://Stackoverflow.com/questions/22386359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318479/" ]
The new location of the theme file is: `~/.jupyter/custom/custom.css`
In your notebook (simple approach). Add new cell with following code ``` %%html <style type='text/css'> .CodeMirror{ font-size: 12px; } div.output_area pre { font-size: 12px; } </style> ```
19,254,178
essentially I am writing something based off of python and I would like to, in python, be able to get the result of a javascript function. Lets say `function.js` has a bunch of functions inside it If I have some python code, in it I would like to be able to do something like the following: ``` val = some_js_function...
2013/10/08
[ "https://Stackoverflow.com/questions/19254178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2127988/" ]
My best theory is that this is a possible consequence of dropping and re-creating a table with the same name (<https://issues.apache.org/jira/browse/CASSANDRA-5905>). We are targeting a fix for 2.1 (<https://issues.apache.org/jira/browse/CASSANDRA-5202>); in the meantime, prefer TRUNCATE over drop/recreate.
Although its very late and you must have solve this issue as well. For others having similar problem, try this ``` sudo bash -c 'rm -rf /var/lib/cassandra/data/system/*' ``` Remember, its only for development purposes. **THIS COMMAND WILL DELETE ALL YOUR DATA.**
51,136,741
I'm trying to deploy a simple python app to Google Container Engine: I have created a cluster then run `kubectl create -f deployment.yaml` It has been created a deployment pod on my cluster. After that i have created a service as: `kubectl create -f deployment.yaml` > > Here's my Yaml configurations: > > > **pod.y...
2018/07/02
[ "https://Stackoverflow.com/questions/51136741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644562/" ]
> > The HashedPassword + Salt is stored in a column > > > That is probably the root problem. You don't need to provide or handle a Salt. See [this answer](http://%20stackoverflow.com/a/17758221/9695604). You should not need a `GetSalt()` method. You can't simply concatenate 2 base64 strings, the decoder doesn...
The Base64 format stores 6 bits per character. Which, as bytes are 8 bits, sometimes some padding is needed at the end. One or two `=` characters are appended. `=` is not otherwise used. If you concatenate two Base64 strings at the join there maybe some padding. Putting padding in the middle of a Base64 string is not ...
52,648,383
I am trying to perform a MultiOutput Regression using ElasticNet and Random Forests as follows: ```python from sklearn.ensemble import RandomForestRegressor from sklearn.multioutput import MultiOutputRegressor from sklearn.linear_model import ElasticNet X_train, X_test, y_train, y_test = train_test_split(X_features, ...
2018/10/04
[ "https://Stackoverflow.com/questions/52648383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10456915/" ]
MultiOutputRegressor itself doesn't have these attributes - you need to access the underlying estimators first using the `estimators_` attribute (which, although not mentioned in the [docs](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputRegressor.html), it exists indeed - see the docs f...
``` regr_multi_Enet.estimators_[0].coef_ ``` To get the coefficients of the first estimator etc.
26,292,909
this is my first post here! My goal is to duplicate the payload of a unidirectional TCP stream and send this payload to multiple endpoints concurrently. I have a working prototype written in Python, however I am new to Python, and to Socket programming. Ideally the solution is capable of running in both Windows and \*...
2014/10/10
[ "https://Stackoverflow.com/questions/26292909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4128004/" ]
The problem is caused by missing or conflicting dependencies: 1. Add hadoop-auth to your classpath 2. If the problem still arises, remove hadoop-core from your classpath. It is conflicting with hadoop-auth. This will solve the problem.
Finally i found an answer for this. 1. Copy the PlatformName class from hadoop-auth and custom compile it locally. package org.apache.hadoop.util; public class PlatformName { ``` private static final String platformName = System.getProperty("os.name") + "-" + System.getProperty("os.arch") + "-" + System.getPro...
4,178,440
Any Java tutorial that resembles Mark Pilgrim's approach for [DiveIntoPython](http://www.diveintopython.net/)?
2010/11/14
[ "https://Stackoverflow.com/questions/4178440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/313127/" ]
What about the official Java Tutorial? I found it pretty helpful to get started with the language.
I haven't read Dive Into Python but I do know that Bruce Eckels Thinking In Java is an excellent book and well worth a look. Be warned though - it's monster size and not easy to carry around!
4,178,440
Any Java tutorial that resembles Mark Pilgrim's approach for [DiveIntoPython](http://www.diveintopython.net/)?
2010/11/14
[ "https://Stackoverflow.com/questions/4178440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/313127/" ]
I haven't read Dive Into Python but I do know that Bruce Eckels Thinking In Java is an excellent book and well worth a look. Be warned though - it's monster size and not easy to carry around!
I don't think there is anything like *Dive into Python* in the Java world. The Java language doesn't lend itself to the model of 'Check out what we can do with these 15 lines of code!' Best approach would be to dive in yourself, pick a project, and use the tutorial and the docs. Many people will recommend Eckel's *Thi...
4,178,440
Any Java tutorial that resembles Mark Pilgrim's approach for [DiveIntoPython](http://www.diveintopython.net/)?
2010/11/14
[ "https://Stackoverflow.com/questions/4178440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/313127/" ]
What about the official Java Tutorial? I found it pretty helpful to get started with the language.
I don't think there is anything like *Dive into Python* in the Java world. The Java language doesn't lend itself to the model of 'Check out what we can do with these 15 lines of code!' Best approach would be to dive in yourself, pick a project, and use the tutorial and the docs. Many people will recommend Eckel's *Thi...
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ...
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I found [this](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) while searching for Aspect Oriented Programming for python. I agree with other posters that such concerns shouldn't be mixed with core logic. In essence,points where you want to put logging might not always be arbitary, may be concepts like ...
I would use the standard [`logging`](http://docs.python.org/library/logging.html) module that's been part of the standard library since Python 2.3. That way, there is a good chance that people looking at your code will already know how the `logging` module works. And if they have to learn then at least it's well-docum...
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ...
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I think there is a point where you must draw a line and make a compromise. I see no way to completely decouple logging from the system because you have to send those messages somewhere and in a way that someone understands. I would go with the default logging module, because... it's the default module. It's well docum...
I would use the standard [`logging`](http://docs.python.org/library/logging.html) module that's been part of the standard library since Python 2.3. That way, there is a good chance that people looking at your code will already know how the `logging` module works. And if they have to learn then at least it's well-docum...
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ...
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I often use DTrace for this. On OS X, python and ruby are both already set up with DTrace hooks. On other platforms, you'd probably have to do this yourself. But being able to attach debug traces to a running process is, well, awesome. However, for library code (let's say you're writing an http client library), the be...
I think the simplest solution is the best here. This depends on language, but just use a very short, globally accessible identifier - in PHP I use a custom function `trace($msg)` - and then just implement and re-implement that code as you see fit for the particular project or phase. The automatic, in-compiler version ...
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ...
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
Another option would be to write the code without logging and then apply some transform to insert the appropriate logging statements before executing the code. The actual techniques to do this would be highly dependant on the language, but would be pretty similar to the process of writing a debugger. It probably isn't...
In response to your edit about information production/consumption: That's a valid concern for the general case, but logging is not the general case. In particular, you should not be relying on logging output from one part of your program to affect the execution of another part. That would indeed tightly couple the cons...
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ...
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I found [this](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) while searching for Aspect Oriented Programming for python. I agree with other posters that such concerns shouldn't be mixed with core logic. In essence,points where you want to put logging might not always be arbitary, may be concepts like ...
I think the simplest solution is the best here. This depends on language, but just use a very short, globally accessible identifier - in PHP I use a custom function `trace($msg)` - and then just implement and re-implement that code as you see fit for the particular project or phase. The automatic, in-compiler version ...
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ...
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I think there is a point where you must draw a line and make a compromise. I see no way to completely decouple logging from the system because you have to send those messages somewhere and in a way that someone understands. I would go with the default logging module, because... it's the default module. It's well docum...
There should be tooling to allow boilerplate log messages a la "entering method A with parameters (1,2,3)", "returning from method B with value X, took 10 ms" to be automatically (and selectively) generated (controlled at run or deploy time). Writing that stuff by hand is just too boring/repetitive/error-prone. Not su...
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ...
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I found [this](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) while searching for Aspect Oriented Programming for python. I agree with other posters that such concerns shouldn't be mixed with core logic. In essence,points where you want to put logging might not always be arbitary, may be concepts like ...
There should be tooling to allow boilerplate log messages a la "entering method A with parameters (1,2,3)", "returning from method B with value X, took 10 ms" to be automatically (and selectively) generated (controlled at run or deploy time). Writing that stuff by hand is just too boring/repetitive/error-prone. Not su...
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ...
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I think there is a point where you must draw a line and make a compromise. I see no way to completely decouple logging from the system because you have to send those messages somewhere and in a way that someone understands. I would go with the default logging module, because... it's the default module. It's well docum...
I think the simplest solution is the best here. This depends on language, but just use a very short, globally accessible identifier - in PHP I use a custom function `trace($msg)` - and then just implement and re-implement that code as you see fit for the particular project or phase. The automatic, in-compiler version ...
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ...
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I found [this](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) while searching for Aspect Oriented Programming for python. I agree with other posters that such concerns shouldn't be mixed with core logic. In essence,points where you want to put logging might not always be arbitary, may be concepts like ...
In response to your edit about information production/consumption: That's a valid concern for the general case, but logging is not the general case. In particular, you should not be relying on logging output from one part of your program to affect the execution of another part. That would indeed tightly couple the cons...
741,063
I always had doubts when it comes to designing proper report of execution. Say you have the following (stupid, to be simple) case. I will use python. ``` def doStuff(): doStep1() doStep2() doStep3() ``` Now, suppose you want to give a report of the various steps, if something goes wrong etc. Not really ...
2009/04/12
[ "https://Stackoverflow.com/questions/741063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I think the best solution for a library is one along the lines of adding e.g. ``` Log.Write(...) ``` where the behavior of Log is picked up from the ambient environment (e.g. app.config or an environment variable). (I also think this is a problem that's been approached and solved many times, and while there are a ...
I would use the standard [`logging`](http://docs.python.org/library/logging.html) module that's been part of the standard library since Python 2.3. That way, there is a good chance that people looking at your code will already know how the `logging` module works. And if they have to learn then at least it's well-docum...
44,274,464
I've got a program that reads strings with special characters (used in spanish) from a file. I then use chdir to change to a directory which its name is the string. For example in a file called "names.txt" I got the following ``` Tableta Música . . etc ``` That file is encoded in utf-8 so that I read it from pyt...
2017/05/31
[ "https://Stackoverflow.com/questions/44274464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7586576/" ]
Your file "names.txt" has a Byte-Order Mask (BOM). To remove it, open the file with the following decoder: ``` f = open("names.txt", encoding="utf-8-sig") ``` As a side note, it is safer to strip a file name: `names[0].strip()` instead of `names[0][:-1]`.
The beginning of your file has the unicode BOM. Skip first character when reading your file or open it with `utf-8-sig` encoding.
66,801,663
I have several database tables that I use in Django. Now I want to design everything around the database not in the Django ORM but in the rational style of my MySQL database. This includes multiple tables for different information. I have made a drawing of what I mean. I want the `createsuperuser` command to query once...
2021/03/25
[ "https://Stackoverflow.com/questions/66801663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14375016/" ]
<https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/#module-django.core.management> You can create django custom commands which will looks like: python manage.py createsuperuser2 (or similar name) ``` class Command(BaseCommand): def handle(self, *args, **options): username = input("us...
Just setup `REQUIRED_FIELDS` inside your User class. If you don't have custom user class, create `class User(AbstractUser)` but dont forget to set `AUTH_USER_MODEL = "users.User"` in `settings.py` ``` REQUIRED_FIELDS = ["country","city","street"] ```
1,738,494
I'm having a tough time getting the logging on Appengine working. the statement ``` import logging ``` is flagged as an unrecognized import in my PyDev Appengine project. I suspected that this was just an Eclipse issue, so I tried calling ``` logging.debug("My debug statement") ``` which does not print anything...
2009/11/15
[ "https://Stackoverflow.com/questions/1738494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211584/" ]
The problem is most likely with the setup of the dev\_appserver. Try running it with the -d flag to turn on debugging.
I have experience only with the Java App Engine, but there they set things up to only log WARN and ERROR. Try using one of those and see if you start getting output! I'm sure there are ways to loosen the filter, but I wouldn't know how to do it in Python.
1,738,494
I'm having a tough time getting the logging on Appengine working. the statement ``` import logging ``` is flagged as an unrecognized import in my PyDev Appengine project. I suspected that this was just an Eclipse issue, so I tried calling ``` logging.debug("My debug statement") ``` which does not print anything...
2009/11/15
[ "https://Stackoverflow.com/questions/1738494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211584/" ]
I have experience only with the Java App Engine, but there they set things up to only log WARN and ERROR. Try using one of those and see if you start getting output! I'm sure there are ways to loosen the filter, but I wouldn't know how to do it in Python.
Use the command option `--log_level` ``` $ dev_appserver.py --host 127.0.0.1 --log_level=debug . ```
1,738,494
I'm having a tough time getting the logging on Appengine working. the statement ``` import logging ``` is flagged as an unrecognized import in my PyDev Appengine project. I suspected that this was just an Eclipse issue, so I tried calling ``` logging.debug("My debug statement") ``` which does not print anything...
2009/11/15
[ "https://Stackoverflow.com/questions/1738494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211584/" ]
The problem is most likely with the setup of the dev\_appserver. Try running it with the -d flag to turn on debugging.
Use the command option `--log_level` ``` $ dev_appserver.py --host 127.0.0.1 --log_level=debug . ```
50,546,740
I am using python 3.6.4 and pandas 0.23.0. I have referenced pandas 0.23.0 documentation for constructor and append. It does not mention anything about non-existent values. I didn't find any similar example. Consider following code: ``` import pandas as pd months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", ...
2018/05/26
[ "https://Stackoverflow.com/questions/50546740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4446712/" ]
I agree with RafaelC that padding your list for 2018 data with NaNs for missing values is the best way to do this. You can use `np.nan` from Numpy (which you will already have installed since you have Pandas) to generate NaNs. ``` import pandas as pd import numpy as np months = ["Jan", "Feb", "Mar", "Apr", "May", "Ju...
You can add a row using `pd.DataFrame.loc` via a series. So you only need to convert your array into a `pd.Series` object before adding a row: ``` df.loc[index_yrs[2]] = pd.Series(r2018, index=df.columns[:len(r2018)]) print(df) Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2016 26.0 ...
67,407,000
I have the below `string` as input: ``` 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' ``` I wrote function which convert it to `di...
2021/05/05
[ "https://Stackoverflow.com/questions/67407000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14976099/" ]
Your approach is good, except for a couple weird things: * You aren't creating a *JSON* anything, so to avoid any confusion I suggest you don't name your returned dictionary `json_data` or your function `str_2_json`. JSON, or **J**ava**S**cript **O**bject **N**otation is just that -- a standard of denoting an object a...
``` import json json_data = json.loads(string) ```
67,407,000
I have the below `string` as input: ``` 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' ``` I wrote function which convert it to `di...
2021/05/05
[ "https://Stackoverflow.com/questions/67407000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14976099/" ]
Assuming these fields cannot contain internal commas, you can use `re.split` to both split and remove surrounding whitespace. It looks like you have different types of fields that should be handled differently. I've added a guess at a schema handler based on field names that can serve as a template for converting the v...
``` import json json_data = json.loads(string) ```
67,407,000
I have the below `string` as input: ``` 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' ``` I wrote function which convert it to `di...
2021/05/05
[ "https://Stackoverflow.com/questions/67407000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14976099/" ]
You can do this with regex ``` import re def parseString(s): dict(re.findall('(?:(\S+) ([^,]+)(?:, )?)', s)) sample = "name SP1, status Offline, size 4764771 MB, free 2406182 MB, path /dev/sdb, log 230 MB, port 5660, guid a48134c00cda2c37005b30b0e40e3ed6, clusterUuid -8650609094877646407--116798096584060989, dis...
``` import json json_data = json.loads(string) ```
67,407,000
I have the below `string` as input: ``` 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' ``` I wrote function which convert it to `di...
2021/05/05
[ "https://Stackoverflow.com/questions/67407000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14976099/" ]
Your approach is good, except for a couple weird things: * You aren't creating a *JSON* anything, so to avoid any confusion I suggest you don't name your returned dictionary `json_data` or your function `str_2_json`. JSON, or **J**ava**S**cript **O**bject **N**otation is just that -- a standard of denoting an object a...
Assuming these fields cannot contain internal commas, you can use `re.split` to both split and remove surrounding whitespace. It looks like you have different types of fields that should be handled differently. I've added a guess at a schema handler based on field names that can serve as a template for converting the v...
67,407,000
I have the below `string` as input: ``` 'name SP2, status Online, size 4764771 MB, free 2576353 MB, path /dev/sde, log 210 MB, port 5660, guid 7478a0141b7b9b0d005b30b0e60f3c4d, clusterUuid -8650609094877646407--116798096584060989, disks /dev/sde /dev/sdf /dev/sdg, dare 0' ``` I wrote function which convert it to `di...
2021/05/05
[ "https://Stackoverflow.com/questions/67407000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14976099/" ]
You can do this with regex ``` import re def parseString(s): dict(re.findall('(?:(\S+) ([^,]+)(?:, )?)', s)) sample = "name SP1, status Offline, size 4764771 MB, free 2406182 MB, path /dev/sdb, log 230 MB, port 5660, guid a48134c00cda2c37005b30b0e40e3ed6, clusterUuid -8650609094877646407--116798096584060989, dis...
Assuming these fields cannot contain internal commas, you can use `re.split` to both split and remove surrounding whitespace. It looks like you have different types of fields that should be handled differently. I've added a guess at a schema handler based on field names that can serve as a template for converting the v...
55,120,078
Is there any way to add new records in the file with each field occupying specific size using python? As shown in below picture, there are together 8 columns `[column number:column bytes] ->[1:20,2:10,3:10,4:39, 6:2, 7:7,8:7]` each of different size. For example if first column value is of 20 bytes "ABBSBABBSBT ", this...
2019/03/12
[ "https://Stackoverflow.com/questions/55120078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11056039/" ]
When you use `ParseExact`, your string and format should match *exactly*. The proper format is: `ddd, d MMM yyyy hh:mm:ss zzz` (or `HH` which depends on your hour format) After you parse it, you need to use `ToString` to format it with `yyyy-MM-dd'T'hh:mm:ss` format (or `HH` which depends you want [12-hour clock](htt...
You need to specify the format that the input data has (the second parameter of `DateTime.ParseExact`). In your case, the data you provide has the format `ddd, d MMM yyyy hh:mm:ss zzz`. Also, in the last line, where you print the result you have to format it. So, this is how you have to do it: ``` string dataa = "Mon...
61,396,228
How can I convert small float values such as *1.942890293094024e-15* or *2.8665157186802404e-07* to binary values in Python? I tried [GeeksforGeek's solution](https://www.geeksforgeeks.org/python-program-to-convert-floating-to-binary/), however, it does not work for values this small (I get this error: **ValueError: i...
2020/04/23
[ "https://Stackoverflow.com/questions/61396228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281273/" ]
After some consultation, I found a good [piece of code](https://trinket.io/python3/8934ea47a2) that solves my problem. I just had to apply some little tweaks on it (making it a function, removing automatic input requests etc.). Huge thanks to @kartoon!
One problem I see is with `str(number).split(".")`. I've added a simple hack before that: `number = "{:30f}".format(number)` so that there is no `e` in number. Though, I'm not sure if the result is correct.
14,582,773
my problem is how to best release memory the response of an asynchrones url fetch needs on appengine. Here is what I basically do in python: ``` rpcs = [] for event in event_list: url = 'http://someurl.com' rpc = urlfetch.create_rpc() rpc.callback = create_callback(rpc) urlfetch.make_fetch_call(rpc, u...
2013/01/29
[ "https://Stackoverflow.com/questions/14582773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471612/" ]
Wrong approach: Put these urls into a (put)-queue, increase its rate to the desired value (defaut: 5/sec), and let each task handle one url-fetch (or a group hereof). Please note that theres a safety limit of 3000 url-fetch-api-calls / minute (and one url-fetch might use more than one api-call)
Use the task queue for urlfetch as well, fan out and avoid exhausting memory, register named tasks and provide the event\_list cursor to next task. You might want to fetch+process in such a scenario instead of registering new task for every process, especially if process also includes datastore writes. I also find ndb...
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[...
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1, len(list1), 2): list1[i] +=1 print(list1) ``` using i%2 seems not very efficient
Try this: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1,len(list1),2): list1[i] += 1 ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[...
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
[`numpy`](http://www.numpy.org/) allows you to use `+=` operation with slices too: ``` In [15]: import numpy as np In [16]: l = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) In [17]: l[1::2] += 1 In [18]: l Out[18]: array([ 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]) ```
``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1, len(list1), 2): list1[i] +=1 print(list1) ``` using i%2 seems not very efficient
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[...
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
[`numpy`](http://www.numpy.org/) allows you to use `+=` operation with slices too: ``` In [15]: import numpy as np In [16]: l = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) In [17]: l[1::2] += 1 In [18]: l Out[18]: array([ 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]) ```
``` a = [i for i in range(1,11)] #a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = [a[i]+1 if i%2==1 else a[i] for i in range(len(a))] #b = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[...
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1, len(list1), 2): list1[i] +=1 print(list1) ``` using i%2 seems not very efficient
``` a = [i for i in range(1,11)] #a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = [a[i]+1 if i%2==1 else a[i] for i in range(len(a))] #b = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[...
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
Use [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) and a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) ``` >>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [v+1 if i%2!=0 else v for i,v in enumerate(list1)] [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``...
``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1, len(list1), 2): list1[i] +=1 print(list1) ``` using i%2 seems not very efficient
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[...
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1, len(list1), 2): list1[i] +=1 print(list1) ``` using i%2 seems not very efficient
You can create an iterator representing the delta (`itertools.cycle([0, 1])` and then add its elements to your existing list. ``` >>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [a + b for a,b in zip(list1, itertools.cycle([0,1]))] [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] >>> ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[...
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
You could use `slicing` with a list comprehension as follows: ``` In [26]: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [27]: list1[1::2] = [x+1 for x in list1[1::2]] In [28]: list1 Out[28]: [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ```
[`numpy`](http://www.numpy.org/) allows you to use `+=` operation with slices too: ``` In [15]: import numpy as np In [16]: l = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) In [17]: l[1::2] += 1 In [18]: l Out[18]: array([ 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]) ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[...
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
Use [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) and a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) ``` >>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [v+1 if i%2!=0 else v for i,v in enumerate(list1)] [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``...
Try this: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1,len(list1),2): list1[i] += 1 ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[...
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
You could use `slicing` with a list comprehension as follows: ``` In [26]: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [27]: list1[1::2] = [x+1 for x in list1[1::2]] In [28]: list1 Out[28]: [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ```
You can create an iterator representing the delta (`itertools.cycle([0, 1])` and then add its elements to your existing list. ``` >>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [a + b for a,b in zip(list1, itertools.cycle([0,1]))] [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] >>> ```
36,011,478
What's the most pythonic way of performing an arithmetic operation on every nth value in a list? For example, if I start with list1: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I would like to add 1 to every second item, which would give: ``` list2 = [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] ``` I've tried: ``` list1[...
2016/03/15
[ "https://Stackoverflow.com/questions/36011478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6052660/" ]
[`numpy`](http://www.numpy.org/) allows you to use `+=` operation with slices too: ``` In [15]: import numpy as np In [16]: l = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) In [17]: l[1::2] += 1 In [18]: l Out[18]: array([ 1, 3, 3, 5, 5, 7, 7, 9, 9, 11]) ```
Try this: ``` list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(1,len(list1),2): list1[i] += 1 ```
19,378,869
``` Error occurred during initialization of VM. Could not reserve enough space for object heap. Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit. ``` The bat file has the following command: ``` java -cp stanford-corenlp-3.2.0.jar;stanford-corenlp-3.2.0-models...
2013/10/15
[ "https://Stackoverflow.com/questions/19378869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2120596/" ]
I've recently had this issue. I'm running a Django application, which is served by uWSGI. I'm actually running uWSGI processes with as-limit argument set to 512MB. After digging around this, I've discovered that every process which the application runs using subprocess, will keep same OS limits as uWSGI processes. Aft...
Try setting the heap size explicitly: see [Could not reserve enough space for object heap](https://stackoverflow.com/questions/4401396/could-not-reserve-enough-space-for-object-heap) This setting can be also be affected by environment variables - you should print the variables in the batch file (I think the `set` comm...
71,586,428
I want to find a concise way to sample n consecutive elements with stride m from a numpy array. The simplest case is with sampling 1 element with stride 2, which means getting every other element in a list, which can be done like this: ``` >>> a = np.arange(10) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> a[::2] ar...
2022/03/23
[ "https://Stackoverflow.com/questions/71586428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9079872/" ]
If `a` is long enough you could reshape, slice, and ravel ``` a.reshape(-1,3)[:,:2].ravel() ``` But `a` has to be (9,) or (12,). And the result will still be a copy. The suggested: ``` np.lib.stride_tricks.as_strided(a, (4,2), (8*3, 8)).ravel()[:-1] ``` is also a copy. The `as_strided` part is a view, but `ravel...
This code might be useful, I tested it on the example in the question (n=2, m=3) ``` import numpy as np def get_slice(arr, n, m): b = np.array([]) for i in range(0, len(arr), m): b = np.concatenate((b, arr[i:i + n])) return b sliced_arr = get_slice(np.arange(10), n=2, m=3) print(sliced_arr) ``` ...
63,348,785
I'm new and trying to follow this tutorial: <https://www.youtube.com/watch?v=_uQrJ0TkZlc> from 05:00:00 I follow him just like he doing, then at 05:05:04 when he run the server it's work fine for him, but for me is not. This is exactly my steps.... After Install django like this: ``` pip install django ``` I writ...
2020/08/10
[ "https://Stackoverflow.com/questions/63348785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14068193/" ]
The 2nd approach doesn't require you to have recording rules for every possible interval over which you'd like an average rate, saving resources.
The `avg_over_time(rate(metric_total[5m])[$__interval:])` calculates average of average rates. This isn't a good metric, since [average of averages doesn't equal to average](https://math.stackexchange.com/questions/95909/why-is-an-average-of-an-average-usually-incorrect). So the better approach would be to calculate `r...
22,204,801
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). e.g. ``` ./program A # output FALSE ./program AA # output FALSE ./program AAA # output FALSE ./program AAAA # output FALSE ./program AAAAA # output FALSE ./program AAA...
2014/03/05
[ "https://Stackoverflow.com/questions/22204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219368/" ]
You could try something like this (see [docs](http://docs.python.org/2/library/subprocess.html#subprocess.call)): ``` import subprocess args = "" while True: args += "A" result = subprocess.call(["./program", "{args}".format(args=args)]) if result == 'TRUE': break ``` The `subprocess` module...
**file.py** ``` import os count=10 input="A" for i in range(0, count): input_args=input_args+input_args os.popen("./program "+input_args) ``` running **file.py** would execute **./program** 10 times with increasing `A` input
22,204,801
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). e.g. ``` ./program A # output FALSE ./program AA # output FALSE ./program AAA # output FALSE ./program AAAA # output FALSE ./program AAAAA # output FALSE ./program AAA...
2014/03/05
[ "https://Stackoverflow.com/questions/22204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219368/" ]
You can use [subprocess.check\_output](http://docs.python.org/3/library/subprocess.html#subprocess.check_output): ``` import subprocess strlen = 0 while True: strlen += 1 if subprocess.check_output(['./program', 'A'*strlen]) == 'TRUE': break ```
**file.py** ``` import os count=10 input="A" for i in range(0, count): input_args=input_args+input_args os.popen("./program "+input_args) ``` running **file.py** would execute **./program** 10 times with increasing `A` input
22,204,801
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). e.g. ``` ./program A # output FALSE ./program AA # output FALSE ./program AAA # output FALSE ./program AAAA # output FALSE ./program AAAAA # output FALSE ./program AAA...
2014/03/05
[ "https://Stackoverflow.com/questions/22204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219368/" ]
You could try something like this (see [docs](http://docs.python.org/2/library/subprocess.html#subprocess.call)): ``` import subprocess args = "" while True: args += "A" result = subprocess.call(["./program", "{args}".format(args=args)]) if result == 'TRUE': break ``` The `subprocess` module...
You can use [subprocess.check\_output](http://docs.python.org/3/library/subprocess.html#subprocess.check_output): ``` import subprocess strlen = 0 while True: strlen += 1 if subprocess.check_output(['./program', 'A'*strlen]) == 'TRUE': break ```
22,204,801
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). e.g. ``` ./program A # output FALSE ./program AA # output FALSE ./program AAA # output FALSE ./program AAAA # output FALSE ./program AAAAA # output FALSE ./program AAA...
2014/03/05
[ "https://Stackoverflow.com/questions/22204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219368/" ]
You could try something like this (see [docs](http://docs.python.org/2/library/subprocess.html#subprocess.call)): ``` import subprocess args = "" while True: args += "A" result = subprocess.call(["./program", "{args}".format(args=args)]) if result == 'TRUE': break ``` The `subprocess` module...
Use `commands`. Here is the documentation `http://docs.python.org/2/library/commands.html` 1. `commands.getstatusoutput` returns a stdout output from your C program. So, if your program prints something, use that. (In fact, it returns a tuple (0, out) for stdout). 2. `commands.getstatus` returns boolean status from pr...
22,204,801
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). e.g. ``` ./program A # output FALSE ./program AA # output FALSE ./program AAA # output FALSE ./program AAAA # output FALSE ./program AAAAA # output FALSE ./program AAA...
2014/03/05
[ "https://Stackoverflow.com/questions/22204801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219368/" ]
You can use [subprocess.check\_output](http://docs.python.org/3/library/subprocess.html#subprocess.check_output): ``` import subprocess strlen = 0 while True: strlen += 1 if subprocess.check_output(['./program', 'A'*strlen]) == 'TRUE': break ```
Use `commands`. Here is the documentation `http://docs.python.org/2/library/commands.html` 1. `commands.getstatusoutput` returns a stdout output from your C program. So, if your program prints something, use that. (In fact, it returns a tuple (0, out) for stdout). 2. `commands.getstatus` returns boolean status from pr...
48,783,650
I have a python list l.The first few elements of the list looks like below ``` [751883787] [751026090] [752575831] [751031278] [751032392] [751027358] [751052118] ``` I want to convert this list to pandas.core.series.Series with 2 leading 0.My final outcome will look like ``` 00751883787 00751026090 00752575831 007...
2018/02/14
[ "https://Stackoverflow.com/questions/48783650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9300211/" ]
you can try: ``` list=[121,123,125,145] series='00'+pd.Series(list).astype(str) print(series) ``` output: ``` 0 00121 1 00123 2 00125 3 00145 dtype: object ```
This is one way. ``` from itertools import chain; concat = chain.from_iterable import pandas as pd lst = [[751883787], [751026090], [752575831], [751031278]] pd.DataFrame({'a': pd.Series([str(i).zfill(11) for i in concat(lst)])}) a 0 00751883787 1 00751026090 2 00752575831 3 00...
48,783,650
I have a python list l.The first few elements of the list looks like below ``` [751883787] [751026090] [752575831] [751031278] [751032392] [751027358] [751052118] ``` I want to convert this list to pandas.core.series.Series with 2 leading 0.My final outcome will look like ``` 00751883787 00751026090 00752575831 007...
2018/02/14
[ "https://Stackoverflow.com/questions/48783650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9300211/" ]
you can try: ``` list=[121,123,125,145] series='00'+pd.Series(list).astype(str) print(series) ``` output: ``` 0 00121 1 00123 2 00125 3 00145 dtype: object ```
First use `DataFrame` constructor with columns, then cast to `string` and last add `0` by [`Series.str.zfill`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.zfill.html) if nested `list`s: ``` lst = [[751883787], [751026090], [752575831], [751031278], [751032392], ...