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
13,391,444
I'm trying to use [PySide](http://qt-project.org/wiki/PySideDocumentation) so I did a `brew install pyside pyside-tools`. However, I get the following error: ``` >>> from PySide.QtGui import QApplication Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: dlopen(/Library/Python/2.7/si...
2012/11/15
[ "https://Stackoverflow.com/questions/13391444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384964/" ]
I was getting the same error, and I'm using Python installed via Homebrew. I found two PySide libraries in /Library/Python/2.7/site-packages/ . Moving them out of the way, and re-building/installing PySide through Homebrew worked.
I tried the import you gave - I am using same system environment. It worked fine. try: brew update and re-install.
13,391,444
I'm trying to use [PySide](http://qt-project.org/wiki/PySideDocumentation) so I did a `brew install pyside pyside-tools`. However, I get the following error: ``` >>> from PySide.QtGui import QApplication Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: dlopen(/Library/Python/2.7/si...
2012/11/15
[ "https://Stackoverflow.com/questions/13391444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384964/" ]
I was getting the same error, and I'm using Python installed via Homebrew. I found two PySide libraries in /Library/Python/2.7/site-packages/ . Moving them out of the way, and re-building/installing PySide through Homebrew worked.
Got the same error when running `ipython qtconsole` which will import PySide to provide a Qt console. Finally I thought there might be something wrong after PySide's installation. So I run `pyside_postinstall.py -install` manually which should be automatically run after PySide is installed, and this fixed my problem. ...
61,698,002
From python in a nutshell, > > Where C is a class, the statement `x=C(23)` is equivalent to: > > > > ``` > x = C.__new__(C, 23) > if isinstance(x, C): type(x).__init__(x, 23) > > ``` > > From my understanding `object.__new__` creates a new, uninitialized instance of the class it receives as its first argumen...
2020/05/09
[ "https://Stackoverflow.com/questions/61698002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13432122/" ]
> > Isn't it obvious that `__new__` will return a object of type C. > > > Not at all. The following is valid: ``` >>> class C: ... def __new__(cls): ... return "not a C" ... def __init__(self): ... print("Never called") ... >>> C() 'not a C' ``` When you override `__new__`, you will *probably* retur...
[isinstance(a, b)](https://docs.python.org/3/library/functions.html#isinstance) is used to check if a is instance of b. Not sure why you checking it after creation. Magical methods can be redefined. Although in normal cases isinstance() is needed to check dynamic data.
44,718,204
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition. ``` log file name - my_app_20170622.log log file entries within time - 00:00:01 to 23:59:59 ``` On next day I want to create a new log file with next day's date - ``` log file name - my_app_20...
2017/06/23
[ "https://Stackoverflow.com/questions/44718204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6102259/" ]
You have to create a `TimedRotatingFileHandler`: ``` from logging.handlers import TimedRotatingFileHandler logname = "my_app.log" handler = TimedRotatingFileHandler(logname, when="midnight", interval=1) handler.suffix = "%Y%m%d" logger.addHandler(handler) ``` This piece of code will create a `my_app.log` but the log...
I suggest you take a look at `logging.handlers.TimedRotatingFileHandler`. I think it's what you're looking for.
44,718,204
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition. ``` log file name - my_app_20170622.log log file entries within time - 00:00:01 to 23:59:59 ``` On next day I want to create a new log file with next day's date - ``` log file name - my_app_20...
2017/06/23
[ "https://Stackoverflow.com/questions/44718204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6102259/" ]
Finally, I got the correct answer and I want to share this answer. Basically, need to create a [TimedRotatingFileHandler](https://docs.python.org/2.4/lib/node349.html) like below - ``` log_format = "%(asctime)s - %(levelname)s - %(message)s" log_level = 10 handler = TimedRotatingFileHandler("my_app.log", when="midnig...
I suggest you take a look at `logging.handlers.TimedRotatingFileHandler`. I think it's what you're looking for.
44,718,204
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition. ``` log file name - my_app_20170622.log log file entries within time - 00:00:01 to 23:59:59 ``` On next day I want to create a new log file with next day's date - ``` log file name - my_app_20...
2017/06/23
[ "https://Stackoverflow.com/questions/44718204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6102259/" ]
### [RotatingFileHandler](https://docs.python.org/2.4/lib/node348.html) ```py class RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]]) ``` Returns a new instance of the `RotatingFileHandler` *class*. The specified file is opened and used as the stream for logging. If mode is not specified, `a` is use...
I suggest you take a look at `logging.handlers.TimedRotatingFileHandler`. I think it's what you're looking for.
44,718,204
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition. ``` log file name - my_app_20170622.log log file entries within time - 00:00:01 to 23:59:59 ``` On next day I want to create a new log file with next day's date - ``` log file name - my_app_20...
2017/06/23
[ "https://Stackoverflow.com/questions/44718204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6102259/" ]
[TimedRotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) can be used for this purpose. Please refer the below code. ``` from logging.config import dictConfig import logging dictConfig({ 'version': 1, 'formatters': { 'standard': { ...
I suggest you take a look at `logging.handlers.TimedRotatingFileHandler`. I think it's what you're looking for.
44,718,204
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition. ``` log file name - my_app_20170622.log log file entries within time - 00:00:01 to 23:59:59 ``` On next day I want to create a new log file with next day's date - ``` log file name - my_app_20...
2017/06/23
[ "https://Stackoverflow.com/questions/44718204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6102259/" ]
You have to create a `TimedRotatingFileHandler`: ``` from logging.handlers import TimedRotatingFileHandler logname = "my_app.log" handler = TimedRotatingFileHandler(logname, when="midnight", interval=1) handler.suffix = "%Y%m%d" logger.addHandler(handler) ``` This piece of code will create a `my_app.log` but the log...
Finally, I got the correct answer and I want to share this answer. Basically, need to create a [TimedRotatingFileHandler](https://docs.python.org/2.4/lib/node349.html) like below - ``` log_format = "%(asctime)s - %(levelname)s - %(message)s" log_level = 10 handler = TimedRotatingFileHandler("my_app.log", when="midnig...
44,718,204
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition. ``` log file name - my_app_20170622.log log file entries within time - 00:00:01 to 23:59:59 ``` On next day I want to create a new log file with next day's date - ``` log file name - my_app_20...
2017/06/23
[ "https://Stackoverflow.com/questions/44718204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6102259/" ]
You have to create a `TimedRotatingFileHandler`: ``` from logging.handlers import TimedRotatingFileHandler logname = "my_app.log" handler = TimedRotatingFileHandler(logname, when="midnight", interval=1) handler.suffix = "%Y%m%d" logger.addHandler(handler) ``` This piece of code will create a `my_app.log` but the log...
### [RotatingFileHandler](https://docs.python.org/2.4/lib/node348.html) ```py class RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]]) ``` Returns a new instance of the `RotatingFileHandler` *class*. The specified file is opened and used as the stream for logging. If mode is not specified, `a` is use...
44,718,204
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition. ``` log file name - my_app_20170622.log log file entries within time - 00:00:01 to 23:59:59 ``` On next day I want to create a new log file with next day's date - ``` log file name - my_app_20...
2017/06/23
[ "https://Stackoverflow.com/questions/44718204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6102259/" ]
You have to create a `TimedRotatingFileHandler`: ``` from logging.handlers import TimedRotatingFileHandler logname = "my_app.log" handler = TimedRotatingFileHandler(logname, when="midnight", interval=1) handler.suffix = "%Y%m%d" logger.addHandler(handler) ``` This piece of code will create a `my_app.log` but the log...
[TimedRotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) can be used for this purpose. Please refer the below code. ``` from logging.config import dictConfig import logging dictConfig({ 'version': 1, 'formatters': { 'standard': { ...
44,718,204
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition. ``` log file name - my_app_20170622.log log file entries within time - 00:00:01 to 23:59:59 ``` On next day I want to create a new log file with next day's date - ``` log file name - my_app_20...
2017/06/23
[ "https://Stackoverflow.com/questions/44718204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6102259/" ]
Finally, I got the correct answer and I want to share this answer. Basically, need to create a [TimedRotatingFileHandler](https://docs.python.org/2.4/lib/node349.html) like below - ``` log_format = "%(asctime)s - %(levelname)s - %(message)s" log_level = 10 handler = TimedRotatingFileHandler("my_app.log", when="midnig...
[TimedRotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) can be used for this purpose. Please refer the below code. ``` from logging.config import dictConfig import logging dictConfig({ 'version': 1, 'formatters': { 'standard': { ...
44,718,204
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition. ``` log file name - my_app_20170622.log log file entries within time - 00:00:01 to 23:59:59 ``` On next day I want to create a new log file with next day's date - ``` log file name - my_app_20...
2017/06/23
[ "https://Stackoverflow.com/questions/44718204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6102259/" ]
### [RotatingFileHandler](https://docs.python.org/2.4/lib/node348.html) ```py class RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]]) ``` Returns a new instance of the `RotatingFileHandler` *class*. The specified file is opened and used as the stream for logging. If mode is not specified, `a` is use...
[TimedRotatingFileHandler](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) can be used for this purpose. Please refer the below code. ``` from logging.config import dictConfig import logging dictConfig({ 'version': 1, 'formatters': { 'standard': { ...
60,949,588
I have a python script that does some GUI test on a chromium application. Sometimes this application does not load up correctly and for this reason the GUI test will not pass, but a simple restart of this application can fix the problem. What I currently have is something like this: ``` def test(): ...do some set...
2020/03/31
[ "https://Stackoverflow.com/questions/60949588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12200507/" ]
In OpenCV, the given threshold options (e.g. cv.THRESH\_BINARY or cv.THRESH\_BINARY\_INV) are actually constant integer values. You are trying to use strings instead of these integer values. That is the reason why you get the Type Error. If you want to apply all these different thresholds in a loop, one option is to cr...
This might be related: [OpenCV Thresholding example](https://docs.opencv.org/master/d7/d4d/tutorial_py_thresholding.html) First off, there is no need to use `range`, you can simply do `for flag in titles:` and pass `flag`. Have you checked if your image is loaded correctly? Are you sure that your flag is repsonsible f...
60,949,588
I have a python script that does some GUI test on a chromium application. Sometimes this application does not load up correctly and for this reason the GUI test will not pass, but a simple restart of this application can fix the problem. What I currently have is something like this: ``` def test(): ...do some set...
2020/03/31
[ "https://Stackoverflow.com/questions/60949588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12200507/" ]
In OpenCV, the given threshold options (e.g. cv.THRESH\_BINARY or cv.THRESH\_BINARY\_INV) are actually constant integer values. You are trying to use strings instead of these integer values. That is the reason why you get the Type Error. If you want to apply all these different thresholds in a loop, one option is to cr...
You code is not working because the type of the flags is `int` and not `string`. You can print the type: `print(type(cv.THRESH_BINARY))`. The result is `<class 'int'>`. You may create a list of `int`s: ``` th_flags = [cv.THRESH_BINARY, cv.THRESH_BINARY_INV, cv.THRESH_TRUNC, cv.THRESH_TOZERO, cv.THRESH_TOZERO_I...
29,959,550
I'm trying to fetch forms for floorplans for individual property's. I can check that the object exists in the database, but when I try to create a form with an instance of it I receive this error: ``` Traceback: File "/Users/balrog911/Desktop/mvp/mvp_1/lib/python2.7/site-packages/django/core/handlers/base.py" in get_r...
2015/04/30
[ "https://Stackoverflow.com/questions/29959550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4847831/" ]
``` NSString *n = [NSString stringWithFormat:@"%@",@"http://somedomain.com/api/x?q={\"order_by\":[{\"field\":\"t\",\"direction\":\"desc\"}]}"]; NSURL *url = [NSURL URLWithString:[n stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSLog(@"%@",url); ```
The proper way to compose a URL from strings is to use [NSURLComponents](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLComponents_class/index.html) helper class. The reason for this seemingly elaborate approach is that each component of a URL (see [RFC 3986](https://www.rfc-editor.org...
58,472,090
I am trying to load a pickle object in R, using the following process found online. First, I create a Python file called: "pickle\_reader.py": ```py import pandas as pd def read_pickle_file(file): pickle_data = pd.read_pickle(file) return pickle_data ``` Then, I run the following R code: ``` install.packag...
2019/10/20
[ "https://Stackoverflow.com/questions/58472090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898786/" ]
If you want to insert a python package into a different environment, which in this case is R, you must search how to install python packages in R. In this case, looking at the [CRAN webpage](https://cran.r-project.org/web/packages/reticulate/vignettes/python_packages.html) you can see that in order to install pandas in...
Make sure that pandas installed. I suggest using conda environment. I read the pickle applying below steps: * Create conda environment and install necessary packages. * Then in R, you can set the right python (which is python in your conda env) ``` Sys.setenv(RETICULATE_PYTHON = "~/anaconda3/envs/your_env/bin/pyt...
58,472,090
I am trying to load a pickle object in R, using the following process found online. First, I create a Python file called: "pickle\_reader.py": ```py import pandas as pd def read_pickle_file(file): pickle_data = pd.read_pickle(file) return pickle_data ``` Then, I run the following R code: ``` install.packag...
2019/10/20
[ "https://Stackoverflow.com/questions/58472090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898786/" ]
I find this to be a much more straight forward method than making a new `.py` file. In an R code chunk do: ``` library(reticulate) pd <- import("pandas") x <- pd$read_pickle("file.pickle") ```
If you want to insert a python package into a different environment, which in this case is R, you must search how to install python packages in R. In this case, looking at the [CRAN webpage](https://cran.r-project.org/web/packages/reticulate/vignettes/python_packages.html) you can see that in order to install pandas in...
58,472,090
I am trying to load a pickle object in R, using the following process found online. First, I create a Python file called: "pickle\_reader.py": ```py import pandas as pd def read_pickle_file(file): pickle_data = pd.read_pickle(file) return pickle_data ``` Then, I run the following R code: ``` install.packag...
2019/10/20
[ "https://Stackoverflow.com/questions/58472090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898786/" ]
I find this to be a much more straight forward method than making a new `.py` file. In an R code chunk do: ``` library(reticulate) pd <- import("pandas") x <- pd$read_pickle("file.pickle") ```
Make sure that pandas installed. I suggest using conda environment. I read the pickle applying below steps: * Create conda environment and install necessary packages. * Then in R, you can set the right python (which is python in your conda env) ``` Sys.setenv(RETICULATE_PYTHON = "~/anaconda3/envs/your_env/bin/pyt...
19,427,685
i have problems with the array indexes in python. at function readfile it crashes and prints: **"list index out of range"** ``` inputarr = [] def readfile(filename): lines = readlines(filename) with open(filename, 'r') as f: i = 0 j= 0 k = 0 for line in f: li...
2013/10/17
[ "https://Stackoverflow.com/questions/19427685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2890530/" ]
I added the javafx runtime separately to the pom as below and it worked: ``` <dependency> <groupId>javafx</groupId> <artifactId>jfxrt</artifactId> <version>${javafx.min.version}</version> <scope>system</scope> <systemPath>${java.home}\lib\jfxrt.jar</systemPath> </depend...
From [*What is JavaFX?*](http://docs.oracle.com/javafx/2/overview/jfxpub-overview.htm#A1095238): > > JavaFX 2.2 and later releases are fully integrated with the Java SE 7 Runtime Environment (JRE) and the Java Development Kit (JDK). > > > This means you should be able to just use the `javafx.*` packages without a...
19,427,685
i have problems with the array indexes in python. at function readfile it crashes and prints: **"list index out of range"** ``` inputarr = [] def readfile(filename): lines = readlines(filename) with open(filename, 'r') as f: i = 0 j= 0 k = 0 for line in f: li...
2013/10/17
[ "https://Stackoverflow.com/questions/19427685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2890530/" ]
I added the javafx runtime separately to the pom as below and it worked: ``` <dependency> <groupId>javafx</groupId> <artifactId>jfxrt</artifactId> <version>${javafx.min.version}</version> <scope>system</scope> <systemPath>${java.home}\lib\jfxrt.jar</systemPath> </depend...
JavaFX in Java7 is not on any classpath - you need to adjust your project classpath or use a tool like e(fx)clipse which manages that for you. In Java8 it is on the extension classpath!
53,961,912
Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially t...
2018/12/28
[ "https://Stackoverflow.com/questions/53961912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5096832/" ]
You're not adequately representing the one-to-many relationship between products and sellers. Your product table has the seller\_id and the seller\_price, but if one product is sold by many sellers, it cannot. Instead of duplicating product entries so the same product can have multiple sellers, what you need is a tabl...
This is a Data Warehouse question. I would recommend putting prices on a Fact as measures and having only attributes on the Dimensions. Dimensions: * Product * Seller * Manufacturer Fact (Columns): * List item * Seller Price * List item * MRSP * Product ID * Seller ID * Manufacturer ID * Timestamp
53,961,912
Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially t...
2018/12/28
[ "https://Stackoverflow.com/questions/53961912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5096832/" ]
Since you have a case of many-to-many then your structure would use a link table. You’ll have tables `seller`, `product` and `link_seller_product`. The last table has a link to the `seller` table via id as well as the `product` table via id. This table therefore can also have any information that is dependent on the se...
You're not adequately representing the one-to-many relationship between products and sellers. Your product table has the seller\_id and the seller\_price, but if one product is sold by many sellers, it cannot. Instead of duplicating product entries so the same product can have multiple sellers, what you need is a tabl...
53,961,912
Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially t...
2018/12/28
[ "https://Stackoverflow.com/questions/53961912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5096832/" ]
Since you have a case of many-to-many then your structure would use a link table. You’ll have tables `seller`, `product` and `link_seller_product`. The last table has a link to the `seller` table via id as well as the `product` table via id. This table therefore can also have any information that is dependent on the se...
This is a Data Warehouse question. I would recommend putting prices on a Fact as measures and having only attributes on the Dimensions. Dimensions: * Product * Seller * Manufacturer Fact (Columns): * List item * Seller Price * List item * MRSP * Product ID * Seller ID * Manufacturer ID * Timestamp
8,584,377
G'Day, I have a number of Django projects and a number of other Python projects as git repositories. I have pre-commit hook that runs Pylint on my code before allowing me to commit it - this hook doesn't know whether the project is a Django application or a vanilla Python project. For all my Django projects, I have...
2011/12/21
[ "https://Stackoverflow.com/questions/8584377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47825/" ]
Take a look at init\_hook in pylint configuration file. ``` init-hook=import sys; sys.path.insert(0, 'my_django_project/apps'); ``` You will obviously need a configuration file per Django application, and run pylint as, e.g. ``` pylint --rcfile=pylint.conf my_django_project ```
Maybe this doesn't fully answer your question, but I suggest to use [django-lint](http://chris-lamb.co.uk/projects/django-lint/), to avoid warnings like: ``` F: 4: Unable to import 'myapp.views' E: 15: MyClass.my_function: Class 'MyClass' has no 'objects' member E: 77: MyClass.__unicode__: Instance of 'MyClass' has n...
8,584,377
G'Day, I have a number of Django projects and a number of other Python projects as git repositories. I have pre-commit hook that runs Pylint on my code before allowing me to commit it - this hook doesn't know whether the project is a Django application or a vanilla Python project. For all my Django projects, I have...
2011/12/21
[ "https://Stackoverflow.com/questions/8584377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47825/" ]
Take a look at init\_hook in pylint configuration file. ``` init-hook=import sys; sys.path.insert(0, 'my_django_project/apps'); ``` You will obviously need a configuration file per Django application, and run pylint as, e.g. ``` pylint --rcfile=pylint.conf my_django_project ```
Adding to Koterpillar's great answer, you can also configure your pre-commit hook to change the current directory to `my_django_project` and run pylint from there.
61,986,195
I have this python code that predicts the trade calls with the Bollinger band values and the Close Price. ```html from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score lr1 = LogisticRegression() x = df[['Lower_Band','Upp...
2020/05/24
[ "https://Stackoverflow.com/questions/61986195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9471113/" ]
As described by KolaB, you should use the `random_state` parameter of `train_test_split` to make results reproducible. But actually, you mentioned that your results vary between 0.3 and 0.8 in accuracy score. This is a strong indicator that your results depend on a particular random choice for the test set. I would, th...
Your problem is most probably in `train_test_split`. You are not initialising the random state that ensures you get reproducible results. Try changing the line with this function to: ``` x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3, random_state=1) ``` Also see scikit learn documentation on the [...
26,450,336
I have this python code. And whenever i start the webbserver and go to the website i don't get the message " test ", just internal server error. How come? what am i doing wrong. Whenever i go to the website its a GET request right, so it should go into domain() function and give me the text " test " ``` @app.route("/...
2014/10/19
[ "https://Stackoverflow.com/questions/26450336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4153021/" ]
I am also new to Android Reversing , and I have spent some time searching for simple understanding of Smali code and found this : note class structure is L; ========================== ``` Lcom/breakapp/dd/mymod/Processor;->l:I ``` original java file name ======================= ``` .source "example.java" ``` the...
You may want to read the dalvik bytecode doc's since they are more detailed then the documentation you can find about smali. Anyway, I am also in the process of learning smali so, probably, I can't give you the best answer but maybe this will help. Let's start by looking at what iput does: > > iput vx,vy, field\_id >...
61,442,421
I am using the combination of **request** and **beautifulsoup** to develop a web-scraping program in python. Unfortunately, I got 403 problem (even using **header**). Here my code: ``` from bs4 import BeautifulSoup from requests import get headers_m = ({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWe...
2020/04/26
[ "https://Stackoverflow.com/questions/61442421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13378861/" ]
This is not general python question. The site blocks such straightforward attempts of **scraping**, you need to find a set of headers (specific for this site) that will pass validation. Regards,
Simply use `Chrome` as `User-Agent`. ``` from bs4 import BeautifulSoup BeautifulSoup(requests.get("https://...", headers={"User-Agent": "Chrome"}).content, 'html.parser') ```
66,254,984
I have a list of dicts in python which look like these: ```py [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}] ``` I want to sort them by day of week such that the result is ```py [{'day' : 'Monday' , 'workers' : ['Kelly']}, {'day' : 'Wednesday' , 'workers' : ...
2021/02/18
[ "https://Stackoverflow.com/questions/66254984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6415973/" ]
Use a lambda function that extracts the weekday name from the dictionary and then returns the index as in your linked question. ``` weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"] list_of_dicts = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}] list_of_dic...
The same basic approach that the example you link to uses will work for your list of dictionaries case. The trick is, you need to extract the day value from the dictionaries within the list to make it work. A `lambda` expression used for the `key` parameter is one way to do that. Example: ``` day_order = ["Monday", "...
66,254,984
I have a list of dicts in python which look like these: ```py [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}] ``` I want to sort them by day of week such that the result is ```py [{'day' : 'Monday' , 'workers' : ['Kelly']}, {'day' : 'Wednesday' , 'workers' : ...
2021/02/18
[ "https://Stackoverflow.com/questions/66254984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6415973/" ]
The same basic approach that the example you link to uses will work for your list of dictionaries case. The trick is, you need to extract the day value from the dictionaries within the list to make it work. A `lambda` expression used for the `key` parameter is one way to do that. Example: ``` day_order = ["Monday", "...
To sort a dictionary by a key `"key"`, you can do: ```py sorted(dicts, key=lambda d: d["key"]) ``` Merging this with the answer from the [question you linked](https://stackoverflow.com/q/13844158/14160477): ```py m = ["Monday", "Tuesday", ...] print(sorted(dicts, key=lambda d: m.index(d["day"]))) ```
66,254,984
I have a list of dicts in python which look like these: ```py [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}] ``` I want to sort them by day of week such that the result is ```py [{'day' : 'Monday' , 'workers' : ['Kelly']}, {'day' : 'Wednesday' , 'workers' : ...
2021/02/18
[ "https://Stackoverflow.com/questions/66254984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6415973/" ]
The same basic approach that the example you link to uses will work for your list of dictionaries case. The trick is, you need to extract the day value from the dictionaries within the list to make it work. A `lambda` expression used for the `key` parameter is one way to do that. Example: ``` day_order = ["Monday", "...
Here it is: ``` lst = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}, {'day' : 'Friday' , 'workers' : ['Nelly']}] m = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] result = sorted(lst, key= lambda x: m.index(x['day'])) print(result) #[{'d...
66,254,984
I have a list of dicts in python which look like these: ```py [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}] ``` I want to sort them by day of week such that the result is ```py [{'day' : 'Monday' , 'workers' : ['Kelly']}, {'day' : 'Wednesday' , 'workers' : ...
2021/02/18
[ "https://Stackoverflow.com/questions/66254984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6415973/" ]
Use a lambda function that extracts the weekday name from the dictionary and then returns the index as in your linked question. ``` weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"] list_of_dicts = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}] list_of_dic...
To sort a dictionary by a key `"key"`, you can do: ```py sorted(dicts, key=lambda d: d["key"]) ``` Merging this with the answer from the [question you linked](https://stackoverflow.com/q/13844158/14160477): ```py m = ["Monday", "Tuesday", ...] print(sorted(dicts, key=lambda d: m.index(d["day"]))) ```
66,254,984
I have a list of dicts in python which look like these: ```py [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}] ``` I want to sort them by day of week such that the result is ```py [{'day' : 'Monday' , 'workers' : ['Kelly']}, {'day' : 'Wednesday' , 'workers' : ...
2021/02/18
[ "https://Stackoverflow.com/questions/66254984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6415973/" ]
Use a lambda function that extracts the weekday name from the dictionary and then returns the index as in your linked question. ``` weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"] list_of_dicts = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}] list_of_dic...
Here it is: ``` lst = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}, {'day' : 'Friday' , 'workers' : ['Nelly']}] m = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] result = sorted(lst, key= lambda x: m.index(x['day'])) print(result) #[{'d...
66,254,984
I have a list of dicts in python which look like these: ```py [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}] ``` I want to sort them by day of week such that the result is ```py [{'day' : 'Monday' , 'workers' : ['Kelly']}, {'day' : 'Wednesday' , 'workers' : ...
2021/02/18
[ "https://Stackoverflow.com/questions/66254984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6415973/" ]
To sort a dictionary by a key `"key"`, you can do: ```py sorted(dicts, key=lambda d: d["key"]) ``` Merging this with the answer from the [question you linked](https://stackoverflow.com/q/13844158/14160477): ```py m = ["Monday", "Tuesday", ...] print(sorted(dicts, key=lambda d: m.index(d["day"]))) ```
Here it is: ``` lst = [{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} , {'day' : 'Monday' , 'workers' : ['Kelly']}, {'day' : 'Friday' , 'workers' : ['Nelly']}] m = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] result = sorted(lst, key= lambda x: m.index(x['day'])) print(result) #[{'d...
12,343,261
OK, so I went on <http://wiki.vg/Protocol>, but I don't understand how to send the packets through a socket to a Minecraft server. I would like to know if it is possible, and if it is how, to send Minecraft packets through a Python socket to a Minecraft server, as if the socket was the Minecraft client. I want to see i...
2012/09/09
[ "https://Stackoverflow.com/questions/12343261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1983840/" ]
Well I'd start with [this](https://gist.github.com/1209061) which sends a packet. It's linked to from the same page you mention. Then adjust the packet ID and the data you add to the stream.
No, as a Minecraft server is nothing but a host listening to a TCP socket. You're better off looking for a Python TCP/sockets tutorial in general, or a Minecraft client/bot library.
59,416,899
We use ndb datastore in our current python 2.7 standard environment. We migrating this application to python 3.7 standard environment with firestore (native mode). We use pagination on ndb datastore and construct our query using fetch. ``` query_results , next_curs, more_flag = query_structure.fetch_page(10) ``` T...
2019/12/19
[ "https://Stackoverflow.com/questions/59416899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3647998/" ]
There is no direct equivalent in Firestore pagination. What you can do instead is fetch one more document than the N documents that the page requires, then use the presence of the N+1 document to determine if there is "more". You would omit the N+1 document from the displayed page, then start the next page at that N+1 ...
I build a custom firestore API not long ago to fetch records with pagination. You can take a look at the [repository](https://github.com/vwt-digital/firestore-api). This is the story of the learning cycle I went through: My first attempt was to use limit and offset, this seemed to work like a charm, but then I walked ...
1,668,223
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system). Firstly I import a sc...
2009/11/03
[ "https://Stackoverflow.com/questions/1668223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200816/" ]
i think [this post](http://mail.python.org/pipermail/tutor/2006-August/048596.html) should help you edit: to secure the availability of this information (in case the link dies or something similar) i will include the original message from the [tutor mailing list](http://mail.python.org/mailman/listinfo/tutor) here: -...
Suggestion: Import your modules dynamically using `__import__` E.g. ``` module_list = ['os', 'decimal', 'random'] for module in module_list: x = __import__(module) print 'name: %s - module_obj: %s' % (x.__name__, x) ``` Will produce: ``` name: os - module_obj: <module 'os' from '/usr/lib64/python2.4/os.pyc...
1,668,223
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system). Firstly I import a sc...
2009/11/03
[ "https://Stackoverflow.com/questions/1668223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200816/" ]
i think [this post](http://mail.python.org/pipermail/tutor/2006-August/048596.html) should help you edit: to secure the availability of this information (in case the link dies or something similar) i will include the original message from the [tutor mailing list](http://mail.python.org/mailman/listinfo/tutor) here: -...
I know this post has been out of date but I just encountered this issue and was struggling against it for the past few days. Now I came with a conclusion that can perfectly solve this issue. Please see the sample code below: ``` try: theMod = sys.modules['ModNeedToBeDel'] except: theMod = None if theMod: ...
1,668,223
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system). Firstly I import a sc...
2009/11/03
[ "https://Stackoverflow.com/questions/1668223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200816/" ]
i think [this post](http://mail.python.org/pipermail/tutor/2006-August/048596.html) should help you edit: to secure the availability of this information (in case the link dies or something similar) i will include the original message from the [tutor mailing list](http://mail.python.org/mailman/listinfo/tutor) here: -...
I recently found this post <https://www.geeksforgeeks.org/reloading-modules-python/> and so for Python 3.4 or later use ``` import importlib importlib.reload(module) ```
1,668,223
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system). Firstly I import a sc...
2009/11/03
[ "https://Stackoverflow.com/questions/1668223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200816/" ]
Suggestion: Import your modules dynamically using `__import__` E.g. ``` module_list = ['os', 'decimal', 'random'] for module in module_list: x = __import__(module) print 'name: %s - module_obj: %s' % (x.__name__, x) ``` Will produce: ``` name: os - module_obj: <module 'os' from '/usr/lib64/python2.4/os.pyc...
I know this post has been out of date but I just encountered this issue and was struggling against it for the past few days. Now I came with a conclusion that can perfectly solve this issue. Please see the sample code below: ``` try: theMod = sys.modules['ModNeedToBeDel'] except: theMod = None if theMod: ...
1,668,223
I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system). Firstly I import a sc...
2009/11/03
[ "https://Stackoverflow.com/questions/1668223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200816/" ]
I recently found this post <https://www.geeksforgeeks.org/reloading-modules-python/> and so for Python 3.4 or later use ``` import importlib importlib.reload(module) ```
I know this post has been out of date but I just encountered this issue and was struggling against it for the past few days. Now I came with a conclusion that can perfectly solve this issue. Please see the sample code below: ``` try: theMod = sys.modules['ModNeedToBeDel'] except: theMod = None if theMod: ...
55,767,411
I have an potentially infinite python 'while' loop that I would like to keep running even after the main script/process execution has been completed. Furthermore, I would like to be able to later kill this loop from a unix CLI if needed (ie. kill -SIGTERM PID), so will need the pid of the loop as well. How would I acco...
2019/04/19
[ "https://Stackoverflow.com/questions/55767411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1998671/" ]
In python, parent processes attempt to kill all their daemonic child processes when they exit. However, you can use `os.fork()` to create a completely new process: ``` import os pid = os.fork() if pid: #parent print("Parent!") else: #child print("Child!") ```
`Popen` returns an object which has the `pid`. According to the [doc](https://docs.python.org/3/library/subprocess.html#subprocess.Popen) > > Popen.pid > The process ID of the child process. > > > Note that if you set the shell argument to True, this is the process ID of the spawned shell. > > > You would need...
10,649,623
I have a web app that uses google app engine .In ubuntu ,I start the app engine using ``` ./dev_appserver.py /home/me/dev/mycode ``` In the mycode folder ,I have app.yml and the python files of the web app.In the web app code,I have used logging to write values of some variables like ``` import logging LOG_FILENAM...
2012/05/18
[ "https://Stackoverflow.com/questions/10649623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1291096/" ]
Did you read this <https://developers.google.com/appengine/articles/logging> as I understand you must not declare your own log file
I have the same environment (Ubuntu, python, gae) and ran into similar issues with logging. You can't log to local file as stated here: <https://developers.google.com/appengine/docs/python/overview> > > "The sandbox ensures that apps can only perform actions that do not interfere with the performance and scalability...
6,069,690
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value: ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ``` When I execute the code I get: `NameError: name ...
2011/05/20
[ "https://Stackoverflow.com/questions/6069690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760797/" ]
Wrong indentation, it should be this instead, otherwise you're exiting the function. ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ```
The indentation of the final line makes it execute in the context of the class and not `__init__`. Indent it one more time to make your program work.
6,069,690
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value: ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ``` When I execute the code I get: `NameError: name ...
2011/05/20
[ "https://Stackoverflow.com/questions/6069690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760797/" ]
Wrong indentation, it should be this instead, otherwise you're exiting the function. ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ```
I'd try ``` class foo(): def __init__(self,bar=None): self.bar = bar self.is_set = (bar is None) ``` Then inside the class ``` ... def spam(self, eggs, ham): if self.is_set: print("Camelot!") else: ... ``` Have you read [the doc's tutorial's entry about classes](http://docs.python.org/tu...
6,069,690
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value: ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ``` When I execute the code I get: `NameError: name ...
2011/05/20
[ "https://Stackoverflow.com/questions/6069690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760797/" ]
Wrong indentation, it should be this instead, otherwise you're exiting the function. ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ```
In your code, `isSet` is a *class* attribute, as opposed to an *instance* attribute. Therefore in the class body you need to define it before referencing it in the `print` statement. Outside the class and in its methods, you must prefix it with the class name and a dot, i.e. `Foo.` in this case. Note that the code in `...
6,069,690
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value: ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ``` When I execute the code I get: `NameError: name ...
2011/05/20
[ "https://Stackoverflow.com/questions/6069690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760797/" ]
It depends on what you are trying to do. You probably want `isSet` to be a member of `foo`: ``` class foo(): def __init__(self,bar=None): self.bar=bar self.isSet=True if bar is None: self.isSet=False f = foo() print f.isSet ```
The indentation of the final line makes it execute in the context of the class and not `__init__`. Indent it one more time to make your program work.
6,069,690
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value: ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ``` When I execute the code I get: `NameError: name ...
2011/05/20
[ "https://Stackoverflow.com/questions/6069690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760797/" ]
It depends on what you are trying to do. You probably want `isSet` to be a member of `foo`: ``` class foo(): def __init__(self,bar=None): self.bar=bar self.isSet=True if bar is None: self.isSet=False f = foo() print f.isSet ```
I'd try ``` class foo(): def __init__(self,bar=None): self.bar = bar self.is_set = (bar is None) ``` Then inside the class ``` ... def spam(self, eggs, ham): if self.is_set: print("Camelot!") else: ... ``` Have you read [the doc's tutorial's entry about classes](http://docs.python.org/tu...
6,069,690
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value: ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ``` When I execute the code I get: `NameError: name ...
2011/05/20
[ "https://Stackoverflow.com/questions/6069690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760797/" ]
It depends on what you are trying to do. You probably want `isSet` to be a member of `foo`: ``` class foo(): def __init__(self,bar=None): self.bar=bar self.isSet=True if bar is None: self.isSet=False f = foo() print f.isSet ```
In your code, `isSet` is a *class* attribute, as opposed to an *instance* attribute. Therefore in the class body you need to define it before referencing it in the `print` statement. Outside the class and in its methods, you must prefix it with the class name and a dot, i.e. `Foo.` in this case. Note that the code in `...
6,069,690
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value: ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ``` When I execute the code I get: `NameError: name ...
2011/05/20
[ "https://Stackoverflow.com/questions/6069690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760797/" ]
I'd try ``` class foo(): def __init__(self,bar=None): self.bar = bar self.is_set = (bar is None) ``` Then inside the class ``` ... def spam(self, eggs, ham): if self.is_set: print("Camelot!") else: ... ``` Have you read [the doc's tutorial's entry about classes](http://docs.python.org/tu...
The indentation of the final line makes it execute in the context of the class and not `__init__`. Indent it one more time to make your program work.
6,069,690
I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value: ``` class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet ``` When I execute the code I get: `NameError: name ...
2011/05/20
[ "https://Stackoverflow.com/questions/6069690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760797/" ]
In your code, `isSet` is a *class* attribute, as opposed to an *instance* attribute. Therefore in the class body you need to define it before referencing it in the `print` statement. Outside the class and in its methods, you must prefix it with the class name and a dot, i.e. `Foo.` in this case. Note that the code in `...
The indentation of the final line makes it execute in the context of the class and not `__init__`. Indent it one more time to make your program work.
37,906,459
I have a text file. The guts of it look like this/ all of it looks like this (has been edited. This was also not what it initially looked like) ``` (0, 16, 0) (0, 17, 0) (0, 18, 0) (0, 19, 0) (0, 20, 0) (0, 21, 0) (0, 22, 0) (0, 22, 1) (0, 22, 2) (0, 23, 0) (0, 23, 4) (0, 24, 0) (0, 25, 0) (0, 25, 1) (0...
2016/06/19
[ "https://Stackoverflow.com/questions/37906459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6306510/" ]
As @TimPietzcker suggested and trusting the file to only have these fixed representations of integers in comma separated triplets, surrounded by parentheses, a simple parser in one go (OP's question also had a greed "read" of file into memors): ``` #! /usr/bin/env python from __future__ import print_function infile =...
Only need small modification.You can try this. ``` om_set = set(eval(open('abc.txt').read())) ``` **Result** ``` {(0, 19, 0), (0, 20, 0), (0, 21, 1), (0, 22, 0), (0, 24, 3), (0, 27, 0), (0, 29, 2), (0, 35, 2)} ``` **Edit** Here is the working of code in in `IPython` prompt. ``` In [1]: file_ = open('abc....
59,538,746
A use case of the `super()` builtin in python is to call an overridden method. Here is a simple example of using `super()` to call `Parent` class's `echo` function: ```py class Parent(): def echo(self): print("in Parent") class Child(Parent): def echo(self): super().echo() print("in Ch...
2019/12/31
[ "https://Stackoverflow.com/questions/59538746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3411556/" ]
If you don't pass the arguments, Python 3 makes an effort to provide them for you. It's a little kludgy, but it *usually* works. Essentially, it just assumes the first parameter to your method is `self` (the second argument to `super`), and when the class definition completes, it provides a virtual closure scope for an...
In Python 3, `super()` with zero arguments is already the shortcut for `super(__class__, self)`. See [PEP3135](https://www.python.org/dev/peps/pep-3135/) for complete explanation. This is not the case for Python 2, so I guess that most code examples you found were actually written for Python 2 (or Python2+3 compatible...
65,784,777
I have a python script which pushes data to another system. If it cannot push data for whatever reason then it will exit with non-zero status code otherwise it will not. I am using my python script in my below shell script. ``` export NAME="${CI_COMMIT_REF_NAME//\//-}-1${CI_PIPELINE_IID}" for environment in dev stage...
2021/01/19
[ "https://Stackoverflow.com/questions/65784777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14431930/" ]
Use a conditional operator to set a variable. ``` failed=false for environment in dev stage; do FILE_NAME="${NAME}-${environment}.tgz"; python helper.py push ${environment} master "${FILE_NAME}" || failed=true python helper.py push ${environment} slave "${FILE_NAME}" || failed=true done if [ "$failed" = true ] t...
> > Basically somehow I need to store exit code of all the possible python line > > > Try this ``` declare -A result for env in dev stage; do FILE_NAME="$NAME-$env.tgz" python helper.py push "$env" master "$FILE_NAME"; result["$FILE_NAME"]=$? python helper.py push "$env" slave "$FILE_NAME"; result["$FILE_N...
44,771,837
I looked at some answers, including [this](https://stackoverflow.com/questions/37457277/remove-non-ascii-characters-from-csv-file-using-python) but none seem to answer my question. Here are some example lines from CSV: ``` _id category ObjectId(56266da778d34fdc048b470b) [{"group":"Home","id":"53cea0be763f4a6f4a8b459...
2017/06/27
[ "https://Stackoverflow.com/questions/44771837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1472743/" ]
As you open the input csv file in `rb` mode, I assume that you are using a Python2.x version. The good news is that you have no problem in the csv part because the csv reader will read plain bytes without trying to interpret them. But the `json` module will insist in decoding the text into unicode and by default uses u...
Most probably you have certain non-ascii characters in your csv content. ``` import re def remove_unicode(text): if not text: return text if isinstance(text, str): text = str(text.decode('ascii', 'ignore')) else: text = text.encode('ascii', 'ignore') remove_ctrl_chars_regex =...
36,222,454
Trying to solve a problem I asked earlier that couldn't be done with postgres sql query. So I moved on to trying to find another way to do it. Essentially - what I have directory lets call it **server** that has multiple CSV files in it with the UUID as the name of the csv. ``` localhost Server]$ tree . ├── 50333694...
2016/03/25
[ "https://Stackoverflow.com/questions/36222454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5992247/" ]
It sounds like you need something like this (untested): ``` mv server server.bk && mkdir server && awk -F, ' NR==FNR { map["server.bk/"$2".csv"]=$1; next } FNR==1 { close(out); out="server/"map[FILENAME]".csv"; print "date,"map[FILENAME] > out } { print > out } ' servers.csv server.bk/*.csv ``` At the end of running...
Here's something I threw together in Python: ``` import csv import os import sys # This is mostly for convenience. Python convention is that all caps # are "constants", but there's nothing that enforces that ...
36,222,454
Trying to solve a problem I asked earlier that couldn't be done with postgres sql query. So I moved on to trying to find another way to do it. Essentially - what I have directory lets call it **server** that has multiple CSV files in it with the UUID as the name of the csv. ``` localhost Server]$ tree . ├── 50333694...
2016/03/25
[ "https://Stackoverflow.com/questions/36222454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5992247/" ]
It sounds like you need something like this (untested): ``` mv server server.bk && mkdir server && awk -F, ' NR==FNR { map["server.bk/"$2".csv"]=$1; next } FNR==1 { close(out); out="server/"map[FILENAME]".csv"; print "date,"map[FILENAME] > out } { print > out } ' servers.csv server.bk/*.csv ``` At the end of running...
``` IFS=,; while read a b; do mv $b $a; sed -i "1i\date,$a" $a; done < servers.csv ``` p.s. caveat emptor, there is mv and inplace edit. test with a copy first.
41,237,314
I have a python function (**pyfunc**): ``` def pyfunc(x): ... return someString ``` I want to apply this function to every item in a mysql table column, something like: ``` UPDATE tbl SET mycol=pyfunc(mycol); ``` This update includes tens of millions of records. Is there an efficient way to do this? **No...
2016/12/20
[ "https://Stackoverflow.com/questions/41237314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7319653/" ]
Even simplier (but for php5.5 and php7): ``` $numery = array_column( $command->queryAll(), 'phone_number' ); ```
Use below loop to get desired result ``` $numery = $command->queryAll(); $number_arr = array(); foreach($numery as $number) { array_push($number_arr,$number['phone_number']); } print_r($number_arr); ```
72,274,548
When I run any kubectl command I get following WARNING: ``` W0517 14:33:54.147340 46871 gcp.go:120] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.25+; use gcloud instead. To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke ``` I ...
2022/05/17
[ "https://Stackoverflow.com/questions/72274548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1869399/" ]
I fixed this problem by adding the correct export in `.bashrc` ``` export USE_GKE_GCLOUD_AUTH_PLUGIN=True ``` After sourcing `.bashrc` with `. ~/.bashrc` and reloading cluster config with: ``` gcloud container clusters get-credentials clustername ``` the warning dissapeared: ``` user@laptop:/$ k get svc -A NAMES...
Got a similar issue, while connecting to a fresh Kubernetes cluster having a version `v1.22.10-gke.600` ``` gcloud container clusters get-credentials my-cluster --zone europe-west6-b --project project ``` and got the below error, as seems like now its become error for the newer version ``` Fetching cluster endpoint...
72,274,548
When I run any kubectl command I get following WARNING: ``` W0517 14:33:54.147340 46871 gcp.go:120] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.25+; use gcloud instead. To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke ``` I ...
2022/05/17
[ "https://Stackoverflow.com/questions/72274548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1869399/" ]
I fixed this problem by adding the correct export in `.bashrc` ``` export USE_GKE_GCLOUD_AUTH_PLUGIN=True ``` After sourcing `.bashrc` with `. ~/.bashrc` and reloading cluster config with: ``` gcloud container clusters get-credentials clustername ``` the warning dissapeared: ``` user@laptop:/$ k get svc -A NAMES...
You need to do the following things to avoid this warning message now and to avoid errors in the future. 1. Add the correct export in .bashrc. I am using .zshrc instead of .bashrc so added export in .zshrc ``` export USE_GKE_GCLOUD_AUTH_PLUGIN=True ``` 2. Reload .bashrc ``` source ~/.bashrc ``` 3. Update gcloud to...
56,335,217
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by : ``` import pymysql conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture') ``` then I download django frame and try to use it to connect mysql , what I do is : create a my.cnf file cont...
2019/05/28
[ "https://Stackoverflow.com/questions/56335217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031764/" ]
Yes, of course.You need to install 'mysqlclient' package or 'mysql-connector-python' package, with pip.
I guess you dont have `mysqlclient` python library installed in virtual environment. Since you are using Windows, you need to download and install `mysqlclient` python library from [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient)
56,335,217
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by : ``` import pymysql conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture') ``` then I download django frame and try to use it to connect mysql , what I do is : create a my.cnf file cont...
2019/05/28
[ "https://Stackoverflow.com/questions/56335217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031764/" ]
Yes, of course.You need to install 'mysqlclient' package or 'mysql-connector-python' package, with pip.
Yes you have to reinstall the mysql for django in the virtual environment again. For windows you can do:- pip install django mysqlclient
56,335,217
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by : ``` import pymysql conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture') ``` then I download django frame and try to use it to connect mysql , what I do is : create a my.cnf file cont...
2019/05/28
[ "https://Stackoverflow.com/questions/56335217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031764/" ]
Yes, of course.You need to install 'mysqlclient' package or 'mysql-connector-python' package, with pip.
Basically you need to put the following code on top of both `manage.py` and `wsgi.py` like this: ``` #!/usr/bin/env python import os import sys **import pymysql** **pymysql.install\_as\_MySQLdb()** # rest of the code ``` Also you need to ensure you have `pymysql` installed in your virtual environment. **FYI:** Usin...
56,335,217
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by : ``` import pymysql conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture') ``` then I download django frame and try to use it to connect mysql , what I do is : create a my.cnf file cont...
2019/05/28
[ "https://Stackoverflow.com/questions/56335217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031764/" ]
Yes, of course.You need to install 'mysqlclient' package or 'mysql-connector-python' package, with pip.
Both *PyMySQL* and *MySQLdb* are db connectors. I assume that your django framework by default searches for MySQLdb and throws exception because it couldn't find one. You can either install MySQLdb or follow @ruddra's answer on that. I would recommend you to go with @ruddra's answer incase of development machine. Beca...
56,335,217
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by : ``` import pymysql conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture') ``` then I download django frame and try to use it to connect mysql , what I do is : create a my.cnf file cont...
2019/05/28
[ "https://Stackoverflow.com/questions/56335217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031764/" ]
I guess you dont have `mysqlclient` python library installed in virtual environment. Since you are using Windows, you need to download and install `mysqlclient` python library from [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient)
Basically you need to put the following code on top of both `manage.py` and `wsgi.py` like this: ``` #!/usr/bin/env python import os import sys **import pymysql** **pymysql.install\_as\_MySQLdb()** # rest of the code ``` Also you need to ensure you have `pymysql` installed in your virtual environment. **FYI:** Usin...
56,335,217
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by : ``` import pymysql conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture') ``` then I download django frame and try to use it to connect mysql , what I do is : create a my.cnf file cont...
2019/05/28
[ "https://Stackoverflow.com/questions/56335217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031764/" ]
I guess you dont have `mysqlclient` python library installed in virtual environment. Since you are using Windows, you need to download and install `mysqlclient` python library from [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient)
Both *PyMySQL* and *MySQLdb* are db connectors. I assume that your django framework by default searches for MySQLdb and throws exception because it couldn't find one. You can either install MySQLdb or follow @ruddra's answer on that. I would recommend you to go with @ruddra's answer incase of development machine. Beca...
56,335,217
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by : ``` import pymysql conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture') ``` then I download django frame and try to use it to connect mysql , what I do is : create a my.cnf file cont...
2019/05/28
[ "https://Stackoverflow.com/questions/56335217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031764/" ]
Yes you have to reinstall the mysql for django in the virtual environment again. For windows you can do:- pip install django mysqlclient
Basically you need to put the following code on top of both `manage.py` and `wsgi.py` like this: ``` #!/usr/bin/env python import os import sys **import pymysql** **pymysql.install\_as\_MySQLdb()** # rest of the code ``` Also you need to ensure you have `pymysql` installed in your virtual environment. **FYI:** Usin...
56,335,217
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by : ``` import pymysql conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture') ``` then I download django frame and try to use it to connect mysql , what I do is : create a my.cnf file cont...
2019/05/28
[ "https://Stackoverflow.com/questions/56335217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031764/" ]
Yes you have to reinstall the mysql for django in the virtual environment again. For windows you can do:- pip install django mysqlclient
Both *PyMySQL* and *MySQLdb* are db connectors. I assume that your django framework by default searches for MySQLdb and throws exception because it couldn't find one. You can either install MySQLdb or follow @ruddra's answer on that. I would recommend you to go with @ruddra's answer incase of development machine. Beca...
36,188,632
this code works on the command line. ``` python -c 'import base64,sys; u,p=sys.argv[1:3]; print base64.encodestring("%s\x00%s\x00%s" % (u,u,p))' user pass ``` output is dXNlcgB1c2VyAHBhc3M= I am trying to get this to work in my script ``` test = base64.encodestring("{0}{0}{1}").format(acct_name,pw) print test `...
2016/03/23
[ "https://Stackoverflow.com/questions/36188632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3954080/" ]
You have a mistake in parenthesis. Instead of: ``` test = base64.encodestring("{0}{0}{1}").format(acct_name,pw) ``` (which first encodes "{0}{0}{1}" in base64 and **then** tries to substitute variables using `format`), you should have ``` test = base64.encodestring("{0}{0}{1}".format(acct_name,pw)) ``` (which fi...
Thanks SZYM i am all set. This is the code that gets it to work ``` test = base64.encodestring("{0}\x00{0}\x00{1}".format(acct_name,pw)) ``` Turns out the hex \x00 is needed so program getting the hash knows where username stops and password begins. -ALF
14,800,708
I am using the PyScripter integrated development environment and taking courses using Python 2.7. Why does `number = input("some input text")` immediately display the python input dialog when the program is ran? Wouldn't we have to execute it? Because really, it's just setting a variable to a python input. It never sa...
2013/02/10
[ "https://Stackoverflow.com/questions/14800708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2059278/" ]
Indeed `number` is variable and nothing more. See [documentation on input()](http://docs.python.org/release/3.2/library/functions.html#input).
python is just kind off a simple language, it does not need variable declaration for example. But it's better that it automatically asks your input instead that you have to write the code for starting the variable
69,633,739
I am pretty new to python, coming from Java and I want to update a variable in an initialized class This is my full code ``` import datetime import time import threading from tkinter import * from ibapi.client import EClient, TickAttribBidAsk from ibapi.wrapper import EWrapper, TickTypeEnum from ibapi.contract im...
2021/10/19
[ "https://Stackoverflow.com/questions/69633739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12496189/" ]
I played with tk a few years ago, this is how I structured my code. I make a tkinter window and connect to TWS from the tkinter class. ``` from tkinter import * import threading from ibapi import wrapper from ibapi.client import EClient from ibapi.utils import iswrapper #just for decorator from ibapi.common import * ...
It would probably help if you did something like this: ``` class TkinterClass: def __init__(self): self.ibkrConnection = Application() self.root = Tk() self.root.title("test") self.root.grid_columnconfigure((0, 1), weight=1) self.titleTicker = Label(root, text="TICKER", bg='...
56,697,108
I am trying to read a shapefile using geopandas, for which I used `gp.read_file` ``` import geopandas as gp fl="M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp" data=gp.read_file(fl) ``` I am getting the following error: `TypeError: invalid path: UnparsedPath(path='M:/rathore/vic_5km/L2_data/L2_data/...
2019/06/21
[ "https://Stackoverflow.com/questions/56697108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10705248/" ]
After so many tries, I have created an [issue](https://issuetracker.google.com/issues/135865377) on Google Issue Tracker under [component](https://issuetracker.google.com/issues?q=componentid:409906), also submitted the code sample to the team and they replied as: > > Your Worker is package protected, and hence we ca...
This seems something similar to what has already been reported on some devices from this OEM. Here's a similar bug on [WorkManager's issuetracker](https://issuetracker.google.com/113676489), there's not much that WorkManager can do in these cases. As commented in this bug: > > ...if a device manufacturer has decided...
56,697,108
I am trying to read a shapefile using geopandas, for which I used `gp.read_file` ``` import geopandas as gp fl="M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp" data=gp.read_file(fl) ``` I am getting the following error: `TypeError: invalid path: UnparsedPath(path='M:/rathore/vic_5km/L2_data/L2_data/...
2019/06/21
[ "https://Stackoverflow.com/questions/56697108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10705248/" ]
This seems something similar to what has already been reported on some devices from this OEM. Here's a similar bug on [WorkManager's issuetracker](https://issuetracker.google.com/113676489), there's not much that WorkManager can do in these cases. As commented in this bug: > > ...if a device manufacturer has decided...
On Oneplus devices turn off battery optimization. Go to phone setting --> battery--> bettery optimization --> search your app --> turn off batter optimization. Workmanager works properly. Compay's just mesh up with Android custom Os just to increase their battery back.
56,697,108
I am trying to read a shapefile using geopandas, for which I used `gp.read_file` ``` import geopandas as gp fl="M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp" data=gp.read_file(fl) ``` I am getting the following error: `TypeError: invalid path: UnparsedPath(path='M:/rathore/vic_5km/L2_data/L2_data/...
2019/06/21
[ "https://Stackoverflow.com/questions/56697108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10705248/" ]
After so many tries, I have created an [issue](https://issuetracker.google.com/issues/135865377) on Google Issue Tracker under [component](https://issuetracker.google.com/issues?q=componentid:409906), also submitted the code sample to the team and they replied as: > > Your Worker is package protected, and hence we ca...
On Oneplus devices turn off battery optimization. Go to phone setting --> battery--> bettery optimization --> search your app --> turn off batter optimization. Workmanager works properly. Compay's just mesh up with Android custom Os just to increase their battery back.
6,548,996
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :) I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class ...
2011/07/01
[ "https://Stackoverflow.com/questions/6548996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/824997/" ]
One solution would be to store current index and/or depth information and use it to traverse the nested list. But that seems like a solution that would do a lot of complicated forking -- testing for ends of lists, and so on. Instead, I came up with a compromise. Instead of flattening the list of lists, I created a gene...
Essentially I would base my own solution on recursion. I would extend the container class with the following: 1. `cursor_position` - Property that stores the index of the highlighted element (or the element that contains the element that contains the highlighted element, or any level of recursion beyond that). 2. `rep...
6,548,996
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :) I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class ...
2011/07/01
[ "https://Stackoverflow.com/questions/6548996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/824997/" ]
I'd let the cursor have a stack of the indices of the arrays. Examples: ``` [1, 2, 3, ['a', 'b', 'c'], 4 ] ``` If the cursor is at the 1 (at index 0), the cursor's position is [0]. It the cursor is at the 2 (at index 1), the cursor's position is [1]. If the cursor is at the 'a' (at index 3 at the outmost level an...
Essentially I would base my own solution on recursion. I would extend the container class with the following: 1. `cursor_position` - Property that stores the index of the highlighted element (or the element that contains the element that contains the highlighted element, or any level of recursion beyond that). 2. `rep...
6,548,996
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :) I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class ...
2011/07/01
[ "https://Stackoverflow.com/questions/6548996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/824997/" ]
One solution would be to store current index and/or depth information and use it to traverse the nested list. But that seems like a solution that would do a lot of complicated forking -- testing for ends of lists, and so on. Instead, I came up with a compromise. Instead of flattening the list of lists, I created a gene...
I'd let the cursor have a stack of the indices of the arrays. Examples: ``` [1, 2, 3, ['a', 'b', 'c'], 4 ] ``` If the cursor is at the 1 (at index 0), the cursor's position is [0]. It the cursor is at the 2 (at index 1), the cursor's position is [1]. If the cursor is at the 'a' (at index 3 at the outmost level an...
6,548,996
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :) I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class ...
2011/07/01
[ "https://Stackoverflow.com/questions/6548996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/824997/" ]
One solution would be to store current index and/or depth information and use it to traverse the nested list. But that seems like a solution that would do a lot of complicated forking -- testing for ends of lists, and so on. Instead, I came up with a compromise. Instead of flattening the list of lists, I created a gene...
While I like the idea of flattening the index list, that makes it impossible to modify the length of any sublist while iterating through the nested list. If this is not functionality you need, I would go with that. Otherwise I would also implement a pointer into the list as a tuple of indices, and rely on recursion. T...
6,548,996
Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :) I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class ...
2011/07/01
[ "https://Stackoverflow.com/questions/6548996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/824997/" ]
I'd let the cursor have a stack of the indices of the arrays. Examples: ``` [1, 2, 3, ['a', 'b', 'c'], 4 ] ``` If the cursor is at the 1 (at index 0), the cursor's position is [0]. It the cursor is at the 2 (at index 1), the cursor's position is [1]. If the cursor is at the 'a' (at index 3 at the outmost level an...
While I like the idea of flattening the index list, that makes it impossible to modify the length of any sublist while iterating through the nested list. If this is not functionality you need, I would go with that. Otherwise I would also implement a pointer into the list as a tuple of indices, and rely on recursion. T...
46,942,411
I'm analyzing revision histories, using `git-archive` to get the files at a particular revision (see <https://stackoverflow.com/a/40811494/1168342>). The approach works, but I'm trying to optimize for projects with many revisions. Much processing is wasted archiving (via tar) and back to a files in another directory ...
2017/10/25
[ "https://Stackoverflow.com/questions/46942411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1168342/" ]
Use: ``` mkdir <path> && GIT_INDEX_FILE=<path>/.git git --work-tree=<path> checkout <revision> -- . && rm <path>/.git ``` The `git checkout` step will overwrite the index, so to make this parallelize well, we can just point the index file into the target. There's one file name that's pretty sure to be safe: `.git`! ...
In JGit the `ArchiveCommand` implements what `git archive` does and also provides several archive file formats out of the box. However, the `ArchiveCommand` can be extended with custom archive formats. A custom format needs to implement the `Format` interface and register it with `ArchiveCommand::registerFormat`. Even...
4,234,823
I am trying to open a serial port with python. This is on Ubuntu. I import the openinterface.py and enter in this ``` ser = openinterface.CreateBot(com_port = "/dev/ttyUSB1", mode="full") ``` I get an error saying "unsupported operand types for -: 'str' and 'int'" I tried the same call with single quotes instead of ...
2010/11/20
[ "https://Stackoverflow.com/questions/4234823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/508530/" ]
According to [this page in Russian](http://rus-linux.net/lib.php?name=/MyLDP/hard/irobot/irobot.html), there's a bug with the `openinterface.py` file that tries to subtract one from the port argument. It suggests making this change (removing the `- 1` on line 803) with `sed`: ``` sed -ie "803s/ - 1//" openinterface.py...
This is what you want if you are using python 3: ``` import serial #import pyserial lib ser = serial.Serial("/dev/ttyS0", 9600) #specify your port and braudrate data = ser.read() #read byte from serial device print(data) #display the ...
44,777,408
I want to mock a method of a class and use `wraps`, so that it is actually called, but I can inspect the arguments passed to it. I have seen at several places ([here](https://stackoverflow.com/questions/25608107/python-mock-patching-a-method-without-obstructing-implementation) for example) that the usual way to do that...
2017/06/27
[ "https://Stackoverflow.com/questions/44777408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1264820/" ]
In short, you can't do this using `Mock` instances alone. `patch.object` creates `Mock`'s for the specified instance (Potato), i.e. it replaces `Potato.foo` with a single Mock the moment it is called. Therefore, there is no way to pass instances to the `Mock` as the mock is created before any instances are. To my kno...
Do you control creation of `Potato` instances, or at least have access to these instances after creating them? You should, else you'd not be able to check particular arg lists. If so, you can wrap methods of individual instances using ``` spud = dig_out_a_potato() with mock.patch.object(spud, "foo", wraps=spud.foo) a...
44,777,408
I want to mock a method of a class and use `wraps`, so that it is actually called, but I can inspect the arguments passed to it. I have seen at several places ([here](https://stackoverflow.com/questions/25608107/python-mock-patching-a-method-without-obstructing-implementation) for example) that the usual way to do that...
2017/06/27
[ "https://Stackoverflow.com/questions/44777408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1264820/" ]
In short, you can't do this using `Mock` instances alone. `patch.object` creates `Mock`'s for the specified instance (Potato), i.e. it replaces `Potato.foo` with a single Mock the moment it is called. Therefore, there is no way to pass instances to the `Mock` as the mock is created before any instances are. To my kno...
Your question looks identical to [python mock - patching a method without obstructing implementation](https://stackoverflow.com/questions/25608107) to me. <https://stackoverflow.com/a/72446739/9230828> implements what you want (except that it uses a with statement instead of a decorator). `wrap_object.py`: ``` # Copyr...
57,943,053
When EMR machine is trying to run a step that includes boto3 initialisation it sometimes get the following error: `ValueError: Invalid endpoint: https://s3..amazonaws.com` When I'm trying to set up a new machine it can suddenly work. Attached the full error: ``` self.client = boto3.client("s3") File "/usr/local/lib...
2019/09/15
[ "https://Stackoverflow.com/questions/57943053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6359988/" ]
It looks like you have an invalid region. [Check](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html) your ~/.aws/config
In my case, even though `~/.aws/config` had the region set, ``` $ cat ~/.aws/config [default] region = us-east-1 ``` the env var `AWS_REGION` was set to an empty string ``` $ env | grep -i aws AWS_REGION= ``` unset this env var and all was good again ``` $ unset AWS_REGION $ aws sts get-caller-identity --output...
57,943,053
When EMR machine is trying to run a step that includes boto3 initialisation it sometimes get the following error: `ValueError: Invalid endpoint: https://s3..amazonaws.com` When I'm trying to set up a new machine it can suddenly work. Attached the full error: ``` self.client = boto3.client("s3") File "/usr/local/lib...
2019/09/15
[ "https://Stackoverflow.com/questions/57943053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6359988/" ]
Set the region in your `~/.aws/credentials` or `~/.aws/config` files. You can set the region as an environment variable as well e.g. In `bash` ``` export AWS_REGION="eu-west-2" ``` or in `Powershell` ``` $Env:AWS_REGION="eu-west-2" ```
In my case, even though `~/.aws/config` had the region set, ``` $ cat ~/.aws/config [default] region = us-east-1 ``` the env var `AWS_REGION` was set to an empty string ``` $ env | grep -i aws AWS_REGION= ``` unset this env var and all was good again ``` $ unset AWS_REGION $ aws sts get-caller-identity --output...
28,572,764
I've been reading through the source for the cpython HTTP package for fun and profit, and noticed that in server.py they have the `__all__` variable set but also use a leading underscore for the function `_quote_html(html)`. Isn't this redundant? Don't both serve to limit what's imported by `from HTTP import *`? Why ...
2015/02/17
[ "https://Stackoverflow.com/questions/28572764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029146/" ]
Aside from the *"private-by-convention"* functions with `_leading_underscores`, there are: * Quite a few `import`ed names; * Four class names; * Three function names *without* leading underscores; * Two string *"constants"*; and * One local variable (`nobody`). If `__all__` wasn't defined to cover only the classes, a...
`__all__` indeed serves as a limit when doing `from HTTP import *`; prefixing `_` to the name of a function or method is a convention for informing the user that that item should be considered private and thus used at his/her own risk.
28,572,764
I've been reading through the source for the cpython HTTP package for fun and profit, and noticed that in server.py they have the `__all__` variable set but also use a leading underscore for the function `_quote_html(html)`. Isn't this redundant? Don't both serve to limit what's imported by `from HTTP import *`? Why ...
2015/02/17
[ "https://Stackoverflow.com/questions/28572764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029146/" ]
`__all__` indeed serves as a limit when doing `from HTTP import *`; prefixing `_` to the name of a function or method is a convention for informing the user that that item should be considered private and thus used at his/her own risk.
This is mostly a documentation thing, in a similar vein to comments. A leading underscore is a clearer indication to a person *reading the code* that particular functions or variables aren't part of the public API than having that person check each name against `__all__`. [PEP8](https://www.python.org/dev/peps/pep-0008...
28,572,764
I've been reading through the source for the cpython HTTP package for fun and profit, and noticed that in server.py they have the `__all__` variable set but also use a leading underscore for the function `_quote_html(html)`. Isn't this redundant? Don't both serve to limit what's imported by `from HTTP import *`? Why ...
2015/02/17
[ "https://Stackoverflow.com/questions/28572764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029146/" ]
Aside from the *"private-by-convention"* functions with `_leading_underscores`, there are: * Quite a few `import`ed names; * Four class names; * Three function names *without* leading underscores; * Two string *"constants"*; and * One local variable (`nobody`). If `__all__` wasn't defined to cover only the classes, a...
This is mostly a documentation thing, in a similar vein to comments. A leading underscore is a clearer indication to a person *reading the code* that particular functions or variables aren't part of the public API than having that person check each name against `__all__`. [PEP8](https://www.python.org/dev/peps/pep-0008...
13,993,617
I am currently using Python v2.6 and trying to merge words into a line. My code supposed to read data from a text file, in which I have two rows of data both of which are strings. Then, it takes the second row data every time, which are the words of sentences, those are separated by delimiter strings, such that: Insid...
2012/12/21
[ "https://Stackoverflow.com/questions/13993617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1839494/" ]
``` def foo(lines): output = [] for line in lines: words = line.split() if len(words) < 2: word = words[0] else: word = words[1] if word == '</S>+ESTag': yield ' '.join(output) output = [] elif word != '<S>+BSTag': ...
I think the problem is that the script isn't being executed (unless you just excluded the [shebang](http://docs.python.org/2/using/unix.html#miscellaneous) in the code you posted) Try this ``` cat file.txt | python script.py | less ```
47,177,112
I manually create PySpark DataFrame as follows: ``` acdata = sc.parallelize([ [('timestamp', 1506340019), ('pk', 111), ('product_pk', 123), ('country_id', 'FR'), ('channel', 'web')] ]) # Convert to tuple acdata_converted = acdata.map(lambda x: (x[0][1], x[1][1], x[2][1])) # Define schema acschema = StructType([ ...
2017/11/08
[ "https://Stackoverflow.com/questions/47177112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7316807/" ]
You need to map all 5 fields to match with the schema defined. ``` acdata_converted = acdata.map(lambda x: (x[0][1], x[1][1], x[2][1], x[3][1], x[4][1])) ```
I'd do it this way: ``` acdata = sc.parallelize([{'timestamp': 1506340019, 'pk': 111, 'product_pk': 123, 'country_id': 'FR', 'channel': 'web'}, {...}]) # Define schema acschema = StructType([ StructField("timestamp", LongType(), True), StructField("pk", LongType(), True), StructField("product_pk", LongTyp...
70,828,210
I have `Django` project and want to look the another db (not default db created by `Php Symfony`) Django can set up two DB in `settins.py` ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("...
2022/01/24
[ "https://Stackoverflow.com/questions/70828210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942868/" ]
You may be looking for the [`managed = false`](https://docs.djangoproject.com/en/4.0/ref/models/options/#django.db.models.Options.managed) meta setting on your models. That will cause Django not to try to manage those models (such as creating migrations for them). It's commonly used when working with externally managed...
I think what you need do is run ``` python manage.py migrate --database extern ```
70,828,210
I have `Django` project and want to look the another db (not default db created by `Php Symfony`) Django can set up two DB in `settins.py` ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("...
2022/01/24
[ "https://Stackoverflow.com/questions/70828210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942868/" ]
You may want to generate your models using ``` python manage.py inspectdb --database=extern > models.py ``` This will generate models corresponding to the tables in your database Check [this link](https://docs.djangoproject.com/en/4.0/howto/legacy-databases/) for more details about legacy databases (django docs)
I think what you need do is run ``` python manage.py migrate --database extern ```
70,828,210
I have `Django` project and want to look the another db (not default db created by `Php Symfony`) Django can set up two DB in `settins.py` ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("...
2022/01/24
[ "https://Stackoverflow.com/questions/70828210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942868/" ]
You may be looking for the [`managed = false`](https://docs.djangoproject.com/en/4.0/ref/models/options/#django.db.models.Options.managed) meta setting on your models. That will cause Django not to try to manage those models (such as creating migrations for them). It's commonly used when working with externally managed...
You may want to generate your models using ``` python manage.py inspectdb --database=extern > models.py ``` This will generate models corresponding to the tables in your database Check [this link](https://docs.djangoproject.com/en/4.0/howto/legacy-databases/) for more details about legacy databases (django docs)
43,433,406
I am trying to run app not written by me app. When I write `python manage.py makemigrations` I got: ``` Traceback (most recent call last): File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql,...
2017/04/16
[ "https://Stackoverflow.com/questions/43433406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2950593/" ]
I had the same issue while using **Python 3.6.5** and **Django==2.1.7** on **Mac OS 10.15.2**. I fixed it by manually creating the table `django_content_type` with the columns: `id, app_label, model` On running `python manage.py migrate` and the error appears, there should be a `*.sqlite3` file created on the path spe...
It seems like I was using python 3x And this app was written using python 2x
43,433,406
I am trying to run app not written by me app. When I write `python manage.py makemigrations` I got: ``` Traceback (most recent call last): File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql,...
2017/04/16
[ "https://Stackoverflow.com/questions/43433406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2950593/" ]
simply delete your db.sqlite3 file....and reagain run the command---> py manage.py migrate then, py manage.py makemigrations app\_name finally, py manage.py migrate... follow this process wish you will fixed your prblm
It seems like I was using python 3x And this app was written using python 2x
43,433,406
I am trying to run app not written by me app. When I write `python manage.py makemigrations` I got: ``` Traceback (most recent call last): File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql,...
2017/04/16
[ "https://Stackoverflow.com/questions/43433406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2950593/" ]
This issue can occur if you have code that uses contenttypes database information at import time rather than at runtime. For example, if you added code that runs at the module level or class level along the lines of: ``` TERM_CONTENT_TYPE = ContentType.objects.get_for_model(Term) ``` but you only added this *after* ...
It seems like I was using python 3x And this app was written using python 2x
20,492,625
I've written tests for my python code and want to check how much % is covered with tests, so I decided to use python coverage. But I have a problem launching it. I launch my tests with this bash command: ``` export PYTHONPATH=. && python files/test/tests.py ``` My python program is in "files" directory, and tests ar...
2013/12/10
[ "https://Stackoverflow.com/questions/20492625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2876296/" ]
The correct way to do this is to use an appropriate **coverage** plugin for the unit testing framework/runner you are using: Here are some combinations: * [pytest](http://pytest.org/latest/) + [pytest-cov](https://pypi.python.org/pypi/pytest-cov) * [nose](https://pypi.python.org/pypi/nose/1.3.0) + [nose-cov](https://...
``` coverage run files/test/tests.py ```
53,129,263
Depend on this tutorials [grpc basic](https://grpc.io/docs/tutorials/basic/python.html) I clone `https://github.com/grpc/grpc` to local, `cd example/python/helloworld` start server `python greeter_server.py` then start client `python greeter_client.py`, but get error ``` Traceback (most recent call last): File...
2018/11/03
[ "https://Stackoverflow.com/questions/53129263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6449456/" ]
1. I found I set a global http proxy `export http_proxy=http://127.0.0.1:1087`, I closed this proxy, then It was find. 2. update `greeter_client.py`, change `localhost` to `127.0.0.1`. It's find to me.
Could you try few options and share your feedback: **Option - 1** another port(except 50051) in [client](https://github.com/grpc/grpc/blob/master/examples/python/helloworld/greeter_client.py) and [server](https://github.com/grpc/grpc/blob/master/examples/python/helloworld/greeter_server.py#L36)? **Option-2** Try wi...
41,434,350
I work on a project and I want to download a csv file from a url. I did some research on the site but none of the solutions presented worked for me. The url offers you directly to download or open the file of the blow I do not know how to say a python to save the file (it would be nice if I could also rename it) But ...
2017/01/02
[ "https://Stackoverflow.com/questions/41434350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6435119/" ]
Try this. Change "folder" to a folder on your machine ``` import os import requests url='https://data.toulouse-metropole.fr/api/records/1.0/download/?dataset=dechets-menagers-et-assimiles-collectes' response = requests.get(url) with open(os.path.join("folder", "file"), 'wb') as f: f.write(response.content) ```
You can adapt an example from [the docs](https://docs.python.org/3/howto/urllib2.html) ``` import urllib.request url='https://data.toulouse-metropole.fr/api/records/1.0/download/?dataset=dechets-menagers-et-assimiles-collectes' with urllib.request.urlopen(url) as testfile, open('dataset.csv', 'w') as f: f.write(t...
35,780,768
I am getting this message when I try to install aws. Anyone have any ideas of what's going on? ``` Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/i...
2016/03/03
[ "https://Stackoverflow.com/questions/35780768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5505587/" ]
Pure virtual functions will never cause anything to fail during linking. Instead, pure virtual functions will cause a compilation error if you try to instantiate the object of an abstract type. Reminder - an abstract type is a type which has (directly or indirectly through inheritance) at least one pure virtual functi...
This may compile or build, if the solution has been previously built. This means that it is using old object code. Try to do a clean build of your solution, then rebuild it. Once your solution is cleaned. Then try to compile the inherited class. Another thing that may be of concern is that you have declared your inheri...