qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
48,266,643 | I have the 2d list mainlist
```
mainlist = [['John','Doe',True],['Mary','Jane',False],['James','Smith',False]]
slist1 = ['John', 'Doe']
slist2 = ['John', 'Smith']
slist3 = ['Doe', 'John']
slist4 = ['John', True]
```
How to determine if a sublist of a sublist exists in a list where if slist1 is tested against mainlis... | 2018/01/15 | [
"https://Stackoverflow.com/questions/48266643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8573372/"
] | You could take an array with references to the wanted arrays and as index for the array for pusing the remainder value of the actual index and the length of the temporary array.
```js
var array = ['fruit', 'vegetables', 'sugars', 'bread', 'fruit', 'vegetables', 'sugars', 'bread'],
fruits = [], // final array... | Not super elegant but it will do the job..
```js
var a =
['bread_1','fruit_1','vegetable_1','sugars_1',
'bread_2','fruit_2','vegetable_2','sugars_2',
'bread_3','fruit_3','vegetable_3','sugars_3'];
var i=0;
a = a.reduce(function(ac, va, id, ar){
if(i==ac.length) i=0;
ac[i].push(va);
i++;
retur... | 12,466 |
34,898,525 | I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows:
```
date1 = "2014-10-10" # input start date
date2 = "2016-01-07" # input end date
month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34898525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3480116/"
] | With pandas, you can have a one liner like this:
```
import pandas as pd
date1 = "2014-10-10" # input start date
date2 = "2016-01-07" # input end date
month_list = [i.strftime("%b-%y") for i in pd.date_range(start=date1, end=date2, freq='MS')]
``` | Here is my solution with a simple list comprehension which uses `range` to know where months must start and end
```
from datetime import datetime as dt
sd = dt.strptime('2014-10-10', "%Y-%m-%d")
ed = dt.strptime('2016-01-07', "%Y-%m-%d")
lst = [dt.strptime('%2.2d-%2.2d' % (y, m), '%Y-%m').strftime('%b-%y') \
... | 12,468 |
58,872,437 | I launched `Jupyter Notebook`, created a new notebook in `python`, imported the necessary `libraries` and tried to access a `.xlsx` file on the desktop with this `code`:
`haber = pd.read_csv('filename.xlsx')`
but error keeps popping up. Want a reliable way of accessing this file on my desktop without incurring any e... | 2019/11/15 | [
"https://Stackoverflow.com/questions/58872437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11003573/"
] | If you open the developer console, you'll see there's an error in one of the templates (DishDetailComponent.html@75:9):
[](https://i.stack.imgur.com/iH8LI.png)
As you can see, it complains about there's no `dividerColor` property i... | I found a changes log here: <https://www.reddit.com/r/Angular2/comments/86ta8k/angular_material_600beta5_changelog/> and replaced all `dividerColor`s with `color` in my project and it worked!
Thanks for @Fel's help. | 12,478 |
49,488,989 | I'm looking into the Twitter Search API, and apparently, it has a count parameter that determines "The number of tweets to return per page, up to a maximum of 100." What does "per page" mean, if I'm for example running a python script like this:
```
import twitter #python-twitter package
api = twitter.Api(consumer_key... | 2018/03/26 | [
"https://Stackoverflow.com/questions/49488989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128156/"
] | Tweepy has a `Cursor` object that works like this:
```
for tweet in tweepy.Cursor(api.search, q="#myHashtag&geocode=59.347937,18.072433,5km", lang='en', tweet_mode='extended').items():
# handle tweets here
```
You can find more info in the [Tweepy Cursor docs](http://tweepy.readthedocs.io/en/v3.5.0/cursor_tutori... | With [TwitterAPI](https://github.com/geduldig/TwitterAPI) you would access pages this way:
```
pager = TwitterPager(api,
'search/tweets',
{'q':'#myHashtag', 'geocode':'59.347937,18.072433,5km'})
for item in pager.get_iterator():
print(item['text'] if 'text' in item else ... | 12,479 |
50,195,029 | today I have encountered a strange problem where python ide would not scale the font correctly on my 1920\*1080 screen. So i fixed it. Kinda
I knew that there was an option in windows where one could toggle the "Override high DPI scaling behavior". Problem is that this tab is only available for application e.g ".exe".... | 2018/05/05 | [
"https://Stackoverflow.com/questions/50195029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4102180/"
] | This is what I was looking for: sort -t ';' -k 2,2 < some-csv.log
Big thanks to @dmadic | If your input.txt is something like:
```
Any
ANA
Bill
BOB
Ana
```
and you want your output to be:
```
Ana
Any
Bill
ANA
BOB
```
then, maybe your could try something like:
```
grep -E "[a-z]+" input.txt | sort > lower.txt
grep -wE "[A-Z]+" input.txt | sort > upper.txt
cat lower.txt upper.txt
``` | 12,480 |
4,011,705 | I've tried lots of solution that posted on the net, they don't work.
```
>>> import _imaging
>>> _imaging.__file__
'C:\\python26\\lib\\site-packages\\PIL\\_imaging.pyd'
>>>
```
So the system can find the \_imaging but still can't use truetype font
```
from PIL import Image, ImageDraw, ImageFilter, ImageFont
im = I... | 2010/10/25 | [
"https://Stackoverflow.com/questions/4011705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483144/"
] | The following worked for me on Ubuntu 14.04.1 64 bit:
```
sudo apt-get install libfreetype6-dev
```
Then, in the virtualenv:
```
pip uninstall pillow
pip install --no-cache-dir pillow
``` | Worked for Ubuntu 12.10:
```
sudo pip uninstall PIL
sudo apt-get install libfreetype6-dev
sudo apt-get install python-imaging
``` | 12,482 |
10,059,497 | Code is much more precise than English; Here's what I'd like to do:
```
import sys
fileName = sys.argv[1]
className = sys.argv[2]
# open py file here and import the class
# ???
# Instantiante new object of type "className"
a = eval(className + "()") # I don't know if this is the way to do that.
# I "know" that cla... | 2012/04/08 | [
"https://Stackoverflow.com/questions/10059497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569302/"
] | Use [`importlib.import_module`](http://localhost/pythondocs/library/importlib.html#importlib.import_module) and the built in function [`getattr`](http://localhost/pythondocs/library/functions.html#getattr). No need for `eval`.
```
import sys
import importlib
module_name = sys.argv[1]
class_name = sys.argv[2]
module ... | As aaronasterling mentions, you can take advantage of the import machinery if the file in question happens to be on the python path (somewhere under the directories listed in `sys.path`), but if that's not the case, use the built in [`exec()`](http://docs.python.org/dev/library/functions.html#exec) function:
```
fileV... | 12,492 |
6,095,818 | Just curious to know is there any document utility available in PHP which can perform something like docutils in python ?
A libary which can be very user friendly in terms of converting restructured text into HTML ? | 2011/05/23 | [
"https://Stackoverflow.com/questions/6095818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239670/"
] | phpDocumentor is quite outdated. Have a look at [DocBlox (Github Repository)](https://github.com/mvriel/Docblox) or [DocBlox-project.org](http://www.docblox-project.org/)
edit:
docblox merged with phpdocumentor and they now maintain phpdocumentor 2.
links that take you directly to the project:
[phpdoc.org](http://www.... | Try [phpDocumentor](http://www.phpdoc.org/). | 12,493 |
9,966,250 | I am trying to understand eval(), but am not having much luck.
I am writing my own math library and am trying to include integration into the library. I need help getting python to recognize the function as a series of variables, constants, and operators. I was told that eval would do the trick but how would i go abou... | 2012/04/01 | [
"https://Stackoverflow.com/questions/9966250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044726/"
] | The documentation for [`eval()`](http://docs.python.org/library/functions.html#eval) is pretty clear in my view and gives a reasonable example of what you need.
Basically you want to hold an expression to be evaluated in a string:
```
>>> f = 'x**2 + 2*x'
```
Then you can define a value for `x`:
```
>>> x = 3
```... | Perhaps you might be thinking of the 'eval' mode of the abstract syntax tree module which allows you to constuct a syntax tree for a single expression.
For example the code below will take an expression in a string and modify it such that 'x\*\*2+3\*x\*\* 4+2' changes to 'x\*\*3+3\*x\*\* 5+2'. (Note that this is not t... | 12,494 |
46,207,299 | On Windows when I execute:
c:\python35\scripts\tensorboard --logdir=C:\Users\Kevin\Documents\dev\Deadpool\Tensorflow-SegNet\logs
and I web browse to <http://localhost:6006> the first time I am redirected to <http://localhost:6006/[[_traceDataUrl]]> and I get the command prompt messages:
```
W0913 14:32:25.401402 Rel... | 2017/09/13 | [
"https://Stackoverflow.com/questions/46207299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1637126/"
] | i'am having the exact same error. Maybe it is because of [this](https://github.com/tensorflow/tensorflow/issues/7856) issue. So try to Change the env-variable to --logdir=foo:C:\Users\Kevin\Documents\dev\Deadpool\Tensorflow-SegNet\logs.
Hope it helps. | Could it be that you try to access the webpage with IE? Apparently IE is not supported by Tensorboard yet(<https://github.com/tensorflow/tensorflow/issues/9372>). Maybe use another Browser. | 12,495 |
7,093,121 | Recently, reading Python ["Functional Programming HOWTO"](http://docs.python.org/howto/functional.html), I came across a mentioned there `test_generators.py` standard module, where I found the following generator:
```
# conjoin is a simple backtracking generator, named in honor of Icon's
# "conjunction" control struct... | 2011/08/17 | [
"https://Stackoverflow.com/questions/7093121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/862380/"
] | This seems to work, and it's still lazy:
```
def conjoin(gs):
return [()] if not gs else (
(val,) + suffix for val in gs[0]() for suffix in conjoin(gs[1:])
)
def range3():
return range(3)
print list(conjoin([range3, range3]))
```
Output:
```
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2,... | `simple_conjoin` uses the same basic building blocks -- loops, conditions, and `yield` -- as the building blocks of the `itertools` recipes. It also treats functions as data, a hallmark of functional programming.
>
> Of course this is most useful when the
> iterators have side-effects, so that which values *can* be ... | 12,497 |
11,915,432 | Why raise UnicodeDecodeError?
I try to deploy my django app using apache
to copy static files, typing
```
$python manage.py collectstatic
```
and I got error message like below.
```
You have requested to collect static files at the destination
location as specified in your settings.
This will overwrite existing fi... | 2012/08/11 | [
"https://Stackoverflow.com/questions/11915432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1559347/"
] | Looks like one or more paths to your static files that are going to be copied contains non ASCII characters.
It has nothing to do with the path to the desctination directory.
**One way to find out would be** to put
```
try:
print path
except:
pass
try:
print entry
except:
pass
```
just before lin... | I had the same error when I used **django-pipeline** inside docker container. It turned out that for some reason the system used POSIX locale. I used the solution proposed here and exported locale setting in system shell:
```
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
```
You can check that afterwards your lo... | 12,498 |
46,564,730 | I am trying to read a table from a Google spanner database, and write it to a text file to do a backup, using google dataflow with the python sdk.
I have written the following script:
```
from __future__ import absolute_import
import argparse
import itertools
import logging
import re
import time
import datetime ... | 2017/10/04 | [
"https://Stackoverflow.com/questions/46564730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6837292/"
] | Google currently added support of Backup Spanner with Dataflow, you can choose related template when creating DataFlow job.
For more: <https://cloud.google.com/blog/products/gcp/cloud-spanner-adds-import-export-functionality-to-ease-data-movement> | I have reworked my code following the suggestion to simply use a ParDo, instead of using the BoundedSource class. As a reference, here is my solution; I am sure there are many ways to improve on it, and I would be happy to to hear opinions.
In particular I am surprised that I have to a create a dummy PColl when startin... | 12,499 |
63,415,954 | why the result of C++ and python bitwise shift operator are diffrernt?
python
```
>>> 1<<20
1048576
```
C++
```
cout <<1<<20;
120
``` | 2020/08/14 | [
"https://Stackoverflow.com/questions/63415954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13966865/"
] | The result differes because of the operator associativity in C++.
```
std::cout << 1 << 20;
```
is the same as
```
(std::cout << 1) << 20;
```
because `operator <<` is left-associative. What you intend to do is
```
std::cout << (1 << 20);
``` | cout overloads the '<<' operator to print the values. So when you are doing
```
cout <<1<<20;
```
It actually prints 1 and 20 and doesnt do any shifting
```
int shifted = 1 << 20;
cout << shifted;
```
This should return the same output as python's
simpler way is to do
```
cout << (1 <<20);
``` | 12,500 |
69,592,525 | I refer to [Python : Using the map function](https://stackoverflow.com/questions/18087544/python-using-the-map-function) It says "map returns a specific type of generator in Python 3 that is not a list (but rather a 'map object', as you can see). " That is my understanding too. Generator object do not contain the value... | 2021/10/16 | [
"https://Stackoverflow.com/questions/69592525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15670527/"
] | `del` doesn't remove the tuple from memory, it just removes the variable.
The `map` object has its own reference to the tuple -- it's a class instance variable variable.
Garbage collection doesn't remove a the tuple from memory until all references to it are destroyed. This will happen when the generator reaches the ... | With `del t1` you delete the *variable*, not the object it references.
Before `del t1`:
[](https://i.stack.imgur.com/7EsXt.png)
After `del t1`:
[](https://i.stack.imgur.com/0xwMq.png)
So that's still all alive and well and f... | 12,501 |
69,141,448 | I have an error that I cannot resolve. here is the error I get when I authenticate with postman: **TypeError: Object of type ObjectId is not JSON serializable // Werkzeug Debugger**
**File "C:\Users\Amoungui\AppData\Local\Programs\Python\Python39\Lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of ty... | 2021/09/11 | [
"https://Stackoverflow.com/questions/69141448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12665256/"
] | Try to use `timestamps` in your schema after defining you fields.
```
const itemSchema = mongoose.Schema({
person_name: String,
person_position: String,
person_level: String,
},{timestamps:true});
var RecordItem = mongoose.model("recorditem", itemSchema);
``` | There are several ways to safe createdAt
1. timestamp : true in options
2. `createdAt: { type: Date, default: Date.now },`
3. itemSchema.pre('save', function(next) {
if (!this.createdAt) {
this.createdAt = new Date();
}
next();
}); | 12,502 |
68,168,293 | I am trying to retrieve data from SQL Server database using python but the system crash and display the below error:
>
> ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'where'. (156) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQ... | 2021/06/28 | [
"https://Stackoverflow.com/questions/68168293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5980666/"
] | You have not declared user variable. Either declare it as follows:
```
const user = firebase.auth().currentUser
```
Or directly pass it as param if you don't need user object anywhere else:
```
.doc(firebase.auth().currentUser.uid)
``` | You should initialize the user before using it.
```
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "####",
authDomain: "###.firebaseapp.com",
projectId: "#",
storageBucket: "#.appspot.com",
messagingSenderId: "#",
appId: "1:####"
};
// Initialize Firebase
fireb... | 12,503 |
33,050,100 | I am dealing with a simple csv file that contains three columns and three rows containing numeric data. The csv data file looks like the following:
```
Col1,Col2,Col3
1,2,3
2,2,3
3,2,3
4,2,3
```
I have hard time figuring out how to let my python program subtracts the average value of the first column "Col1" fro... | 2015/10/10 | [
"https://Stackoverflow.com/questions/33050100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1974919/"
] | Please show your html page from where you are sending post data. I think you should have to make an array of $\_POST variables then you can get all the records at php side and you can insert all three records in table.
Try this
Please check the below link where you can find your solution
[Inserting Multiple Rows with... | Create Model that holds all table columns.
```
class OrderModel extends BaseModel{
public $id;
// Fill here all columns
public function __construct($data) {
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
public function get_table_name() {
return "ordering";
}
}... | 12,504 |
41,841,828 | I would like to know if there is an else statement, like in python, that when attached to a **try-catch** structure, makes the block of code within it only executable if no exceptions were thrown/caught.
For instance:
```
try {
//code here
} catch(...) {
//exception handling here
} ELSE {
//this should ex... | 2017/01/25 | [
"https://Stackoverflow.com/questions/41841828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7408143/"
] | The concept of an `else` for a `try` block doesn't exist in c++. It can be emulated with the use of a flag:
```
{
bool exception_caught = true;
try
{
// Try block, without the else code:
do_stuff_that_might_throw_an_exception();
exception_caught = false; // This needs to be the last... | Why not just put it at the end of the try block? | 12,505 |
59,694,929 | i am creating a project where react is not rendering anything on django localhost
index.html
```
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div id="App">
<!---all will be define in App.js-->
<h1>Index.html </h1>
</div>
</body>
{% load static%}
<s... | 2020/01/11 | [
"https://Stackoverflow.com/questions/59694929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11631248/"
] | Change this source code:
```
document.getElementById('app')
```
... to this:
```
document.getElementById('App')
``` | Its because your element has id of "App" but you are trying to hook react app on element 'app'. It's case sensitive. | 12,506 |
39,760,629 | UnitTests has a feature to capture `KeyboardInterrupt`, finishes a test and then report the results.
>
> **-c, --catch**
>
>
> *Control-C* during the test run waits for the current test to end and then reports all the results so far. A second *Control-C*
> raises the normal KeyboardInterrupt exception.
>
>
> See ... | 2016/09/29 | [
"https://Stackoverflow.com/questions/39760629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1603480/"
] | Your issue may lie in the execution ordering of your hook, such that pytest exits prior to your hook being executed. This could happen if an unhandled exception occurs in preexisting handling of the keyboard interrupt.
To ensure your hook executes sooner, use `tryfirst` or `hookwrapper` as described [here](https://doc... | Take a look at pytest's [hookspec](http://doc.pytest.org/en/latest/_modules/_pytest/hookspec.html).
They have a hook for keyword interrupt.
```
def pytest_keyboard_interrupt(excinfo):
""" called for keyboard interrupt. """
``` | 12,508 |
20,748,202 | It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted
However In python 2.7 it returns `ValueError: malformed string` when running this example:
```
>>> ast.literal_eval("4 + 9")
`... | 2013/12/23 | [
"https://Stackoverflow.com/questions/20748202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2425215/"
] | The reason this doesn’t work on Python 2 lies in its implementation of `literal_eval`. The original implementation only performed number evaluation for additions and subtractions when the righth operand was a complex number. This is syntactically necessary for complex numbers to be expressed as a literal.
This [was ch... | Use the source, luke!
[`http://hg.python.org/cpython/file/2.7/Lib/ast.py#l40`](http://hg.python.org/cpython/file/2.7/Lib/ast.py#l40)
[`http://hg.python.org/cpython/file/3.2/Lib/ast.py#l39`](http://hg.python.org/cpython/file/3.2/Lib/ast.py#l39)
You will find your answer in there. Specifically, the 2.7 version has the... | 12,509 |
61,385,841 | I have specific question. I have lego EV3 and i installed Micropython. But i want import turtle, tkinter and other modules and they aren't in micropython. But time module working.Do someone know what modules are in ev3 micropython? Thanks for answer. | 2020/04/23 | [
"https://Stackoverflow.com/questions/61385841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13045504/"
] | To add bearer token in retrofit, you have to create a class that implements `Interceptor`
```
public class TokenInterceptor implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
//rewrite the request to add bearer token
Request newRequest=chain.request(... | these three class will be your final setup for all types of call
>
> for first call(Login) you do not need to pass token and after login pass jwt as bearer token to authenticate after authentication do not need to pass
>
>
>
```
public class ApiUtils {
private static final String BASE_URL="https://abcd.abcd.com/... | 12,518 |
38,775,586 | The following python code:
```
# user profile information
args = {
'access_token':access_token,
'fields':'id,name',
}
print 'ACCESSED', urllib.urlopen('https://graph.facebook.com/me', urllib.urlencode(args)).read()
```
Prints the following:
*ACCESSED {"success":true}*
The token is valid, no error, ... | 2016/08/04 | [
"https://Stackoverflow.com/questions/38775586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1507649/"
] | Turns out urllib.urlopen will send the data as a POST when the data parameter is provided. Facebook Graph API works using GET not POST. Change the call to trick the function into calling just a URL ( no data ):
```
print 'ACCESSED', urllib.urlopen('https://graph.facebook.com/me/?' + urllib.urlencode(args)).read()
```... | You have to add a `/` to the URL to get `https://graph.facebook.com/me/` instead of `https://graph.facebook.com/me`.
```
# user profile information
args = {
'access_token':access_token,
'fields':'id,name'
}
print 'ACCESSED', urllib.urlopen('https://graph.facebook.com/me/', urllib.urlencode(args)).read()
```
... | 12,519 |
73,009,209 | I have a pandas datafrme with a text column and was wondering how can I count the number of line breaks.This is how it's done in excel and would like to now how I can achieve this in python:
[How To Count Number Of Lines (Line Breaks) In A Cell In Excel?](https://www.extendoffice.com/documents/excel/4785-excel-count-n... | 2022/07/17 | [
"https://Stackoverflow.com/questions/73009209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7297511/"
] | Your approach is slow because you loop over the rows and use intermediate copies.
You should be able to use boolean indexing for direct swapping:
```
mask = final['HomeAway'].eq(0)
final.loc[mask, 4:124], final.loc[mask, 124:] = final.loc[mask, 124:], final.loc[mask, 4:124]
``` | The Data on which you are working is unknown and I have tried to replicate your problem with duplicate data. Change the variables and the indexing values while using it in your project
**CODE**
```
import pandas as pd
import numpy as np
data = pd.DataFrame({"HomeAway": [1, 1, 0, 0, 1],
"Value1":... | 12,520 |
7,733,200 | I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out
main urls.py file - the admin works fine
```
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.au... | 2011/10/11 | [
"https://Stackoverflow.com/questions/7733200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/225600/"
] | ```
from django.contrib import admin,include
admin.autodiscover()
urlpatterns = patterns('',
(r'^pnasser/',include('pnasser.urls')),
(r'^admin/',include(admin.site.urls)),
(r'^',include('pnasser.urls')),
)
```
maybe you missed "include" in the first line | ```
Using the URLconf defined in mysite.urls, Django tried these
URL patterns, in this order:
```
This error message should list all possible URLs, including the 'expanded' urls from your pnasser app. Since you're only getting the URLs from your main urls.py, it suggests you haven't properly enabled the `pnasser` app... | 12,521 |
56,093,339 | I'm currently trying to write a script that does a specific action on a certain day. So for example, if today is the 6/30/2019 and in my dataframe there is a 6/30/2019 entry, xyz proceeds to happen. However, I am having troubles comparing the date from a dataframe to a DateTime date. Here's how I created the dataframe
... | 2019/05/11 | [
"https://Stackoverflow.com/questions/56093339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11486279/"
] | ```
import datetime
import pandas as pd
da = str(datetime.datetime.now().date())
# converting the column to datetime, you can check the dtype of the column by doing
# df['event_date'].dtypes
df['event_date'] = pd.to_datetime(df['event_date'])
# generate a df with rows where there is a match
df_co = df.loc[df['eve... | ```
import pandas as pd
import time
# keep only y,m,d, and throw out the rest:
now = (time.strftime("%Y/%m/%d"))
# the column in the dataframe needs to be converted to datetime first.
df['event_date'] = pd.to_datetime(df['event_date'])
# to return indices
df[df['event_date']==now].index.values
# if you want to lo... | 12,531 |
44,089,727 | i have a weekly report that i need to do, i chooseed to create it with openpyxl python module, and send it via mail,
when i open the received mail (outlook), the cells with formulas appears as empty,
but when downloading the file and open it, the data appears,
OS fedora 20. parts of the code :
```
# imported ... | 2017/05/20 | [
"https://Stackoverflow.com/questions/44089727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6424190/"
] | Unfortunately not.
There is no language support for what you want.
Let me be specific about what you want just so that you understand what I answered.
Your question is basically this: Given that I have *two* instances of an object, and I have properties in this object that have a private setter, is there any languag... | That won't work. If `Pos` is a property with a private setter (as it is) the only way they could change it would be by calling a public method from within `otherPlayer`. Something like `otherPlayer.SetPos(new Vector2(34,151))`, where `SetPos()` is:
```
public void SetPos(Vector2 NewPos)
{ Pos = NewPos; }
``` | 12,532 |
32,496,664 | **What is the pythonic way to set a maximum length paramter?**
Let's say I want to restrict a list of strings to a certain maximum size:
```
>>> x = ['foo', 'bar', 'a', 'rushmoreorless', 'kilimangogo']
>>> maxlen = 3
>>> [i for i in x if len(i) <= maxlen]
['foo', 'bar', 'a']
```
And I want to functionalize it and a... | 2015/09/10 | [
"https://Stackoverflow.com/questions/32496664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | >
> Let's say I want to restrict a list of strings to a certain maximum
> size:
>
>
> And I want to functionalize it and allow different maxlen but if no
> maxlen is given, it should return the full list:
>
>
> And I want to set the maxlen to the max length of element in alist
>
>
>
To address all these requ... | How about the following approach, this avoids the need to use `max`:
```
def filter_length(a_list, max_length=None):
if max_length == 0:
return []
elif max_length:
return [i for i in x if len(i) <= max_length]
else:
return a_list
x = ['foo', 'bar', 'a', 'rushmoreorless', 'kilimango... | 12,535 |
28,894,756 | I have installed python 2.7, numpy 1.9.0, scipy 0.15.1 and scikit-learn 0.15.2.
Now when I do the following in python:
```
train_set = ("The sky is blue.", "The sun is bright.")
test_set = ("The sun in the sky is bright.",
"We can see the shining sun, the bright sun.")
from sklearn.feature_extraction.text import Cou... | 2015/03/06 | [
"https://Stackoverflow.com/questions/28894756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4193051/"
] | You are missing an underscore, try this way:
```
from sklearn.feature_extraction.text import CountVectorizer
train_set = ("The sky is blue.", "The sun is bright.")
test_set = ("The sun in the sky is bright.",
"We can see the shining sun, the bright sun.")
vectorizer = CountVectorizer(stop_words='english')
docum... | Try using the `vectorizer.get_feature_names()` method. It gives the column names in the order it appears in the `document_term_matrix`.
```
from sklearn.feature_extraction.text import CountVectorizer
train_set = ("The sky is blue.", "The sun is bright.")
test_set = ("The sun in the sky is bright.",
"We can see th... | 12,538 |
48,671,331 | Am implementing a sign up using python & mysql.
Am getting the error no module named flask.ext.mysql and research implies that i should install flask first. They say it's very simple, you simply type
pip install flask-mysql
but where do i type this? In mysql command line for my database or in the python app? | 2018/02/07 | [
"https://Stackoverflow.com/questions/48671331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8857901/"
] | Pip is used from the command line. If you are on a Linux/Mac machine, type it from the Terminal. Make sure you actually have Pip.
If you don't, use this command (on the Terminal) on linux:
```
sudo apt-get install pip
```
If you are on a Mac, use (in the Terminal):
```
/usr/bin/ruby -e "$(curl -fsSL https://raw.gi... | You should be able to type it in the command line for your operating system (ie. CMD/bash/terminal) as long as you have pip installed and the executable location is in your PATH. | 12,539 |
41,708,881 | I used pip today for the first time in a while and I got the helpful message
>
> You are using pip version 8.1.1, however version 9.0.1 is available.
> You should consider upgrading via the 'pip install --upgrade pip' command.
>
>
>
So, I went ahead and
```
pip install --upgrade pip
```
but things did not go... | 2017/01/17 | [
"https://Stackoverflow.com/questions/41708881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3704831/"
] | You can reinstall `pip` with `conda`:
```
conda install pip
```
Looks like you need to have root rights:
```
sudo conda install pip
``` | You can use curl to reinstall pip via the Python Packaging Authority website:
```
curl https://bootstrap.pypa.io/get-pip.py | python
``` | 12,540 |
66,963,342 | How can I change the output of the `models.ForeignKey` field in my below custom field?
Custom field:
```py
class BetterForeignKey(models.ForeignKey):
def to_python(self, value):
print('to_python', value)
return {
'id': value.id,
'name_fa': value.name_fa,
'name_... | 2021/04/06 | [
"https://Stackoverflow.com/questions/66963342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7431943/"
] | None of the above worked for me, but turns out the solution was quite simple...
All I was doing wrong was not explicitly including "null" as the parameter in the useRef initialization (it expects null, not undefined).
Also you CANNOT use "HTMLElement" as your ref type, you have to be more specific, so for me it was "H... | The same stands for the `<svg>` elements:
```
const ref = useRef<SVGSVGElement>(null)
...
<svg ref={ref} />
``` | 12,543 |
14,160,686 | I'm writing a python (3.2+) plugin library and I want to create a function which will create some variables automatically handled from config files.
The use case is as follows (class variable):
```
class X:
option(y=0)
def __init__(self):
pass
```
(instance variable):
```
class Y:
def __init__(... | 2013/01/04 | [
"https://Stackoverflow.com/questions/14160686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889902/"
] | You cannot get a reference to the class, because the class has yet to be created. Your parent frame points a temporary function, whose `locals()` when it completes will be used as the class body.
As such, all you need to do is add your variables to the parent frame locals, and these will be added to the class when cla... | It seems to me that a metaclass would be suitable here:
**python2.x syntax**
```
def class_maker(name,bases,dict_):
dict_['y']=0
return type(name,bases,dict_)
class X(object):
__metaclass__ = class_maker
def __init__(self):
pass
print X.y
foo = X()
print foo.y
```
**python3.x syntax**
It ... | 12,553 |
8,301,962 | I am trying to rewrite the code described [here](http://opencv.itseez.com/doc/tutorials/features2d/feature_homography/feature_homography.html#feature-homography). using the python API for Opencv.
The step 3 of the code has this lines:
```
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match( des... | 2011/11/28 | [
"https://Stackoverflow.com/questions/8301962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053925/"
] | Looking in the examples provided by OpenCV 2.3.1 under the python2 folder, I found an implementation of a flann based match function which doesn't rely on the FlanBasedMatcher object.
Here is the code:
```
FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing
flann_params = dict(algorithm = FLANN_INDEX_KDTREE,
... | Pythonic FlannBasedMatcher is already available in OpenCV trunk, but if I remember correctly, it was added after 2.3.1 release.
Here is OpenCV sample using FlannBasedMatcher: <http://code.opencv.org/projects/opencv/repository/revisions/master/entry/samples/python2/feature_homography.py> | 12,554 |
31,483,448 | I have a python script which I want to start using a rc(8) script in FreeBSD. The python script uses the `#!/usr/bin/env python2` pattern for portability purposes. (Different \*nix's put interpreter binaries in different locations on the filesystem).
The FreeBSD rc scripts will not work with this.
Here is a script th... | 2015/07/17 | [
"https://Stackoverflow.com/questions/31483448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1183499/"
] | *Self answered my question, but I'm hoping someone else will give a better answer for posterity*
The reason why env(1) does not work is because it expects an environment in the first place, but rc scripts run before the environment is set up. Hence it fails. It seems that the popular env shebang pattern is actually an... | The command interpreter warning is generated by the `_find_processes()` function in `/usr/src/etc/rc.subr`.
The reason that it does that is because a service written in an interpreted language is found in `ps` output by the *name of the interpreter*. | 12,557 |
6,648,394 | I have a project and I want to use python but the server is only Windows Server 2000 can it run on this system? | 2011/07/11 | [
"https://Stackoverflow.com/questions/6648394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1347816/"
] | If you are using windows 2000 then it's possible that python 3.2 is not your best alternative.
A couple of months ago there was an interesting thread in the python-dev mailing list[1] about dropping win2k support (there are some annoying bugs for this platform).
[1] <http://mail.python.org/pipermail/python-dev/2010-M... | You can use [Micro Python](https://micropython.org/) for DOS. It has Python 3.4 syntax. | 12,558 |
5,189,483 | If my question is unclear there is a great explainaion of what I'm attempting to do here under the section, "Method 2: The British Method": <http://www.gradeamathhelp.com/how-to-factor-polynomials.html>
My current program simply inputted all 3 A,B, and C variables and then assigned A\*C to D
I then took the negative ... | 2011/03/04 | [
"https://Stackoverflow.com/questions/5189483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your code isn't working because you need "END" commands every time you use a "THEN" command. END is also used to close off "REPEAT", "FOR", and "WHILE" loops. Why does it need "END" for an "IF,THEN" type command? Because "IF,THEN" equates to:
```
If X+Y=B and X*Y=D (
```
In typical scripting
The "END" is like an... | Download available at: <http://www.ticalc.org/pub/83/basic/math/algebra/> | 12,559 |
16,847,597 | I am new to python and programming, so apologies in advance. I know of remove(), append(), len(), and rand.rang (or whatever it is), and I believe I would need those tools, but it's not clear to me *how* to code it.
What I would like to do is, while looping or otherwise accessing List\_A, randomly select an index with... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16847597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2058922/"
] | If you don't care about the order of the input list, I'd shuffle it, then remove `n` items from that list, adding those to the other list:
```
from random import shuffle
def remove_percentage(list_a, percentage):
shuffle(list_a)
count = int(len(list_a) * percentage)
if not count: return [] # edge case, n... | If you can find a random index `i` of some element in `listA`, then you can easily move it from A to B using:
```
listB.append(listA.pop(i))
``` | 12,561 |
62,999,056 | This python 3 code does exactly what I want
```py
from pathlib import Path
def minify(src_dir:Path, dest_dir:Path, n: int):
"""Write first n lines of each file f in src_dir to dest_dir/f"""
dest_dir.mkdir(exist_ok=True)
for path in src_dir.iterdir():
new = [x.rstrip() for x in list(path.open().read... | 2020/07/20 | [
"https://Stackoverflow.com/questions/62999056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4381942/"
] | Looks like you are using Bootstrap. Currently, your left nav is initially set to `position: fixed`, I recommend using `position: relative` to your left nav initially so that positioning your `nav` elements can be **relative to the height of the background image**. Using Bootstrap, this solution wraps the left nav & the... | You should be able to have that working with just CSS and no javascript using `position: sticky` attribute.
Make both elements `position: sticky`, the top nav should have a `top: 0` property and the side nav should have a `top: x` property where `x` is the height of the top nav.
That should be enough and you should b... | 12,564 |
58,525,753 | I'm trying to use Ansible with ssh for interact with Windows machines
i have successfully install OpenSSH on a Windows machine that mean i can connect from linux to windows with:
```
ssh username@ipAdresse
```
i've tried using a lot of version of ansible (2.6, 2.7.12, 2.7.14, 2.8.5 and 2.8.6) and i always test if ... | 2019/10/23 | [
"https://Stackoverflow.com/questions/58525753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11431519/"
] | Ok solved, the problem was
```
ansible_ssh_pass=*****
```
the correct syntax is
```
ansible_password=*****
``` | To use SSH as the connection to a Windows host (starting from Ansible 2.8), set the following variables in the inventory:
* ansible\_connection=ssh
* **ansible\_shell\_type**=cmd/powershell (Set either cmd or powershell not both)
Finally, the inventory file:
```
[windows]
192.***.***.***
[all:vars]
ansible_connecti... | 12,569 |
68,590,820 | I want to use the face recognition module of python in a project but when I am trying to install it using the command "pip install face\_recognition" or "pip install face-recognition", it is showing an error and is not installing. This is the screenshot of the error:[:
wait_time = between(5,... | 2020/05/23 | [
"https://Stackoverflow.com/questions/61969924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5825106/"
] | **If it crash on iOS :**
Check if you have updated your Info.plist file. You must have the key «Privacy - Contacts Usage Description» with a sentence in value.
Follow the documentation : <https://github.com/morenoh149/react-native-contacts#ios-2>
**If it crash on Android :**
Check if you have updated your Android... | ```
//Try it
const addContact = () => {
PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.WRITE_CONTACTS,
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
])
Contacts.getAll().then(contacts => {
// console.log('hello',contacts);
setMblContacts(contacts);
})
}
`... | 12,571 |
30,897,442 | I had a working project with django 1.7, and now I moved it to django 1.8.
I can do `syncdb` and run the app with sqlite, but when I switch to postgres, it fails to do **syncdb**:
```
Creating tables...
Creating table x
Creating table y
Running deferred SQL...
Traceback (most recent call last):
File "m... | 2015/06/17 | [
"https://Stackoverflow.com/questions/30897442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896222/"
] | I didn't like the idea of commenting/uncommenting code, so I tried a different approach: I migrated "manually" some apps, and then run `django-admin.py migrate` for the remaining ones. After deleting all the `*.pyc` files, my sequence of commands was:
```
$ django-admin.py migrate auth
$ django-admin.py migrate conten... | I had this issues with a `forms.ChoiceForm` queryset. I was able to switch to using [`forms.ModelChoiceForm`](https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield) which are lazily evaluated and this fixed the problem for me. | 12,572 |
2,066,049 | I'm trying to write a POS-style application for a [Sheevaplug](http://en.wikipedia.org/wiki/SheevaPlug) that does the following:
1. Captures input from a card reader (as I understand, most mag card readers emulate keyboard input, so basically I'm looking to capture that)
2. Doesn't require X
3. Runs in the background ... | 2010/01/14 | [
"https://Stackoverflow.com/questions/2066049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231670/"
] | Section 5 of the Linux kernel [input documentation](http://www.kernel.org/doc/Documentation/input/input.txt) describes what each of the values in the event interface means. | the format is explained in the [kernel documentation](http://www.mjmwired.net/kernel/Documentation/input/) in section *5. Event Interface*. | 12,582 |
6,495,688 | There are lots of [good](https://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script) [reasons](https://stackoverflow.com/questions/1352922/why-is-usr-bin-env-python-supposedly-more-correct-than-just-usr-bin-pyth) to use #! /usr/bin/env. Bottom line: It makes ... | 2011/06/27 | [
"https://Stackoverflow.com/questions/6495688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730070/"
] | *"kill-ability" on the command line* can by addressed portably and reliably using the PID of the backgrounded process obtained from shell `$!` variable.
```
$ ./bintest.py & bg_pid=$! ; echo bg_pid=$bg_pid ; ps && kill $bg_pid
[1] 2993
bg_pid=2993
PID TTY TIME CMD
2410 pts/0 00:00:00 bash
2993 pts/0 ... | I don't think you can rely on the `killall` using the script name to work all the time. On Mac OS X I get the following output from `ps` after running both scripts:
```
2108 ttys004 0:00.04 /usr/local/bin/python /Users/adam/bin/bintest.py
2133 ttys004 0:00.03 python /Users/adam/bin/envtest.py
```
and running... | 12,583 |
56,594,272 | I found a code for text classification in tensorflow and when I try to run this code: <https://www.tensorflow.org/beta/tutorials/keras/feature_columns> I get an error.
I used the dataset from here: <https://www.kaggle.com/kazanova/sentiment140>
```
Traceback (most recent call last):
File "text_clas.py", line 35, in... | 2019/06/14 | [
"https://Stackoverflow.com/questions/56594272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You are saving or deleting a customer from the table, but the `dataSource` is using the data that you have already fetched from the database. It cannot get the updated data unless you manually do it.
While saving a new customer, you'll have to make the `getUser()` request again ( or push the customer object in the `r... | Akash's approach is correct. In addition to his approach you should use [afterClosed()](https://material.angular.io/components/dialog/api#MatDialogRef) method to link MatDialog to current component and get notified when the dialog is closed. After the dialog is closed, just fetch users again.
```js
ngOnInit() {
... | 12,586 |
33,546,935 | I have a list of lists, with integer values in each list, that represent dates over an 8 year period.
```
dates = [[2014, 11, 14], [2014, 11, 13], ....., [2013, 12, 01].....]
```
I need to compare these dates so that I can find an average cost per month, with other data stored in the file. So i need to figure o... | 2015/11/05 | [
"https://Stackoverflow.com/questions/33546935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5522009/"
] | You can use a dictionary to preserve the year and month as the key and the relative days in a list as value, then you can do any progress on your items which are categorized by the year and month.
```
>>> dates = [['2014', '11', '14'], ['2014', '10', '13'], ['2014', '10', '01'], ['2014', '12', '01'], ['2013', '12', '0... | If you want to iterate thought you dates array, and do an action every time the month changes you could use this method:
```
dates = [[2014, 11, 14], [2014, 11, 13], [2013, 12, 1]]
old_m = ""
for year, month, day in dates:
if old_m != month:
# calculate average here
old_m = month
``` | 12,587 |
51,941,175 | I am trying to read a txt file(kept in another location) in python, but getting error.
--------------------------------------------------------------------------------------
>
> FileNotFoundError
>
> in ()
> ----> 1 employeeFile=open("C:/Users/xxxxxxxx/Desktop/python/files/employee.txt","r")
> 2 print(employee... | 2018/08/21 | [
"https://Stackoverflow.com/questions/51941175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6487702/"
] | I'm guessing you copy and pasted from a Windows property pane, switching backslashes to forward slashes manually. Problem is, the properties dialog shoves a Unicode LEFT-TO-RIGHT EMBEDDING character into the path so the display is consistent, even in locales with right-to-left languages (e.g. Arabic, Hebrew).
You can ... | As your error message suggests, there's a weird character between the colon and the forward slash (`C:[some character]/`). Other than that the code is fine.
```py
employeeFile = open("C:/Users/xxxxxxxx/Desktop/python/files/employee.txt", "r")
```
You can copy paste this code and use it. | 12,588 |
19,623,386 | Hi: I want to do a sound waves simulation that include wave propagation, absorbing and reflection in 3D space.
I do some searches and I found [this question](https://stackoverflow.com/questions/4956331/wave-simulation-with-python) in stackoverflow but it talk about electromagnetic waves not sound waves.
I know i can ... | 2013/10/27 | [
"https://Stackoverflow.com/questions/19623386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/553460/"
] | Hope this can give you some inputs...
As far as i know, in EM simulations obstacles (and thus terrain) are not considered at all. With sound you have to consider reflection, diffraction, etc
there are different standards to calculate the noise originated from different sources (I'll list the europe ones, the one i kno... | An easy way to do this is use the SoundPlan software. Multiple sound propagation methods such as ISO9613-2, CONCAWE and Nord2000 are implemented. It has basic 3D visualization with sound pressure level contours. | 12,589 |
46,309,161 | I am having issues reading data from a bucket hosted by Google.
I have a bucket containing ~1000 files I need to access, held at (for example)
gs://my-bucket/data
Using gsutil from the command line or other of Google's Python API clients I can access the data in the bucket, however importing these APIs is not suppor... | 2017/09/19 | [
"https://Stackoverflow.com/questions/46309161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8598909/"
] | If you just want to read data into memory, then [this answer](https://stackoverflow.com/a/42799952/1399222) has the details you need, namely, to use the [file\_io](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/lib/io/file_io.py) module.
That said, you might want to consider using built-in read... | For what its worth. I also had problems reading files, in particular binary files from google cloud storage inside a datalab notebook. The first way I managed to do it was by copying files using gs-utils to my local filesystem and using tensorflow to read the files normally. This is demonstrated here after the file cop... | 12,590 |
56,567,013 | We are fairly new to Django. We we have an app and a model. We'd like to add an 'Category' object to our model. We did that, and then ran 'python manage.py makemigrations'.
We then deploy our code to a server running the older code, and run 'python manage.py migrate'. This throws 2 pages of exceptions, finishing with ... | 2019/06/12 | [
"https://Stackoverflow.com/questions/56567013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11638068/"
] | I believe you skipped some migration in the server, so now you are missing some tables (I have been in that situation. Ensure **migrations** directories are on your **.gitignore**. You CAN NOT check in migrations files, you have to run `makemigrations` on the server). This can be solved by tracing back up to the point ... | Remember to run `python manage.py makemigrations` if you made changes to the `models.py` then run `python manage.py makemigrations`
Both commands **must** be run on the same server with the same database | 12,591 |
10,654,707 | I download python2.6.6 source form <http://www.python.org/getit/releases/2.6.6/>
After that I run these commands
./configure
make
I tried to import zlib but it says no module named zlib. How can install zlib module for it
After I tried installing python2.6.8 I got same error no zlib.
While installing it I got below e... | 2012/05/18 | [
"https://Stackoverflow.com/questions/10654707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813102/"
] | I tried following which helped me with some of these modules.
You have to edit setup.py.
Find the following lines in setup.py:
```
lib_dirs = self.compiler.library_dirs + [
'/lib64', '/usr/lib64',
'/lib', '/usr/lib',
]
```
**For 64 bit**
Add `/usr/lib/x86_64-linux-gnu`:
```
lib_dirs = self.compiler.... | I wrote a note for myself addressing your problem, might be helpful: [`python installation`](http://cheater.nemoden.com/python-installation/).
Do you really need `bsddb` and `sunaudiodev` modules? You might not want to since both are deprecated since python 2.6 | 12,592 |
41,971,623 | Is it possible to have a python script pause when you hold a button down and then start when you release that button? (I have the button connected to GPIO pins on my Raspberry Pi) | 2017/02/01 | [
"https://Stackoverflow.com/questions/41971623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070269/"
] | **Yes.** The AWS account that is currently controlling your domain name with Route 53 must be used, but it can be pointed to anything on the Internet.
Steps:
* In the AWS account with the "other" EC2 instance, create an **Elastic IP Address** and assign it to the EC2 instance. This will ensure that its IP address doe... | Once you have set the nameserver for your domain to point to Route53, you no longer need to control the subdomains from bigrock services. Just add them to your Route53 dashboard, and they'll be reflected live. | 12,597 |
50,628,893 | I am doing a final project in a python course and I have done a program using phantomjs that run like a background process in windows.
Therefore, after creating my project, I used pyinstaller --noconsole --onefile to my file in order to hide his console but even tough I did it, I still get a console popup - phantomjs.... | 2018/05/31 | [
"https://Stackoverflow.com/questions/50628893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9581412/"
] | No need to rename the .dat to .csv. Instead you can use a regex that matches two or more spaces as a column separator.
Try use `sep` parameter:
```
pd.read_csv('http://users.stat.ufl.edu/~winner/data/clinton1.dat',
header=None, sep='\s\s+', engine='python')
```
Output:
```
0 1 2 ... | You can use a regular expression as a separator. In your specific case, all the delimiters are more than one space whereas the spaces in the names are just single spaces.
```
import pandas as pd
clinton = pd.read_csv("clinton1.csv", sep='\s{2,}', header=None, engine='python')
``` | 12,598 |
20,269,507 | I'm a novice in python and also in py.test. I'm searching a way to run multiple tests on multiple items and cannot find it. I'm sure it's quite simple when you know how to do it.
I have simplified what I'm trying to do to make it simple to understand.
If I have a Test class who defines a serie of tests like this one... | 2013/11/28 | [
"https://Stackoverflow.com/questions/20269507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269921/"
] | Add the sorting clause to the most outer query | For paging with a "window", you can do something like this:
```
select e.*
from ( select e.*
, row_number()
over
(order by uur_id) ive$idx$
from bubs_uren_v e
where ( uur_id = :w1 )
) e
where ive$idx$ between (:start_index + 1) and (:star... | 12,599 |
63,191,480 | I wrote a small code with python. But this part of the code doesn't work when game focused on and it doesnt respond back.
`pyautogui.moveRel(-2, 4)`
Also this part works when my cursor appear in menu or etc. too. But when i switched into game (when my cursor disappear and crosshair appeared) it doesn't work (doesn't ... | 2020/07/31 | [
"https://Stackoverflow.com/questions/63191480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14027997/"
] | I tried this code below:
`import win32con`
`import win32api`
`win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, int(10), int(10), 0, 0)`
And it worked in game. I think it relative with win32con. Anyway i got it. | This is how PyAutoGui works:
```
0,0 X increases -->
+---------------------------+
| | Y increases
| | |
| 1920 x 1080 screen | |
| | V
| |
| |
+-------------------... | 12,600 |
22,049,248 | I would like to develop an app engine application that directly stream data into a BigQuery table.
According to Google's documentation there is a simple way to stream data into bigquery:
* <http://googlecloudplatform.blogspot.co.il/2013/09/google-bigquery-goes-real-time-with-streaming-inserts-time-based-queries-and-... | 2014/02/26 | [
"https://Stackoverflow.com/questions/22049248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2558486/"
] | Minimal working (as long as you fill in the right ids for your project) example:
```
import httplib2
from apiclient import discovery
from oauth2client import appengine
_SCOPE = 'https://www.googleapis.com/auth/bigquery'
# Change the following 3 values:
PROJECT_ID = 'your_project'
DATASET_ID = 'your_dataset'
TABLE_ID... | Here is a working code example from an appengine app that streams records to a BigQuery table. It is open source at code.google.com:
<http://code.google.com/p/bigquery-e2e/source/browse/sensors/cloud/src/main.py#124>
To find out where the bigquery object comes from, see
<http://code.google.com/p/bigquery-e2e/source/b... | 12,602 |
39,771,024 | I made a module and moved it to `/root/Downloads/Python-3.5.2/Lib/site-packages`.
When I run bash command `python3` in this folder to start the ide and import the module it works. However if I run `python3` in any other directory (e.g. `/root/Documents/Python`) it says
```none
ImportError: No module named 'exampleMod... | 2016/09/29 | [
"https://Stackoverflow.com/questions/39771024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6726467/"
] | Instead of moving the module I would suggest you add the location of the module to the `PYTHONPATH` environment variable. If this is set then the python interpreter will know where to look for your module.
e.g. on Linux
```sh
export PYTHONPATH=$PYTHONPATH:<insert module location here>
``` | **If you are a window user and you are getting import issues from site-packages
then you can add the path of your site-packages to env variable**
[](https://i.stack.imgur.com/fmK0h.png)
C:\Users\hp\AppData\Local\Programs\Python\Python310\Lib\site-pac... | 12,603 |
8,121,886 | I'm sure this has been answered somewhere, because it's a very basic question - I can not, however, for the life of me, find the answer on the web. I feel like a complete idiot, but I have to ask so, here goes:
I'm writing a python code that will produce a list of all page addresses on a domain. This is done using sel... | 2011/11/14 | [
"https://Stackoverflow.com/questions/8121886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1020693/"
] | I'm familiar with python's api of selenium
but you probably can receive link using `get_attribute(attributename)` method. So it should be something like:
```
linkstr = ""
for link in Listlinker:
linkstr = link.get_attribute("href")
if linkstr in Domenesider:
pass
elif str(HovedDomene) in linkstr:
Domen... | >
> I've been checking up on your tip to not use time.sleep(10) as a page load wait. From reading different posts itseems to me that waiting for page loading is redundant with selenium 2. Se for example link The reason being that selenium 2 has a implicit wait for load function. Just thought I'd mention it to you, sin... | 12,605 |
52,131,675 | I have list of list of integers as shown below:
```
flst = [[19],
[21, 31],
[22],
[23],
[9, 25],
[26],
[27, 29],
[28],
[27, 29],
[2, 8, 30],
[21, 31],
[5, 11, 32],
[33]]
```
I want to get the list of integers in increasing order as shown below:
```
out = [19, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32,... | 2018/09/01 | [
"https://Stackoverflow.com/questions/52131675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6017391/"
] | Sure, you can pass field names as arguments and use `[arg]` accessors as you already do with `[key]`:
```js
function populateClinicRoomSelect(object, valueField, labelField) {
var selectArray = [];
var options = [];
for(var key in object) {
if(object.hasOwnProperty(key)) {
options = {
val... | You mean like this?
```js
function populateClinicRoomSelect(object, value, label) {
value = value || "id"; // defaults value to id
label = label || "RoomName"; // defaults label to RoomName
var selectArray = [];
var options = [];
for(var key in object) {
if(object.hasOwnProperty(key))... | 12,606 |
44,456,572 | Am getting the following error - Missing required dependencies ['numpy']
Standalone and via Django, without Apache2 integration - the code work likes charm, however things start to fall when used with Apache2. It refuses to import pandas or numpy giving one error after another.
I am using Apache2, libapache2-mod-wsgi-... | 2017/06/09 | [
"https://Stackoverflow.com/questions/44456572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1759084/"
] | In your class fields
```
private Handler progressHandler = new Handler();
private Runnable progressRunnable = new Runnable() {
@Override
public void run() {
progressDialog.setProgress(progressValue);
progressHandler.postDelayed(this, 1000);
}
};
```
When the time ... | do something lik this
```
new Thread(new Runnable() {
public void run() {
while (prStatus < 100) {
prStatus += 1;
handler.post(new Runnable() {
public void run() {
pb_2.setProgress(prStatus);
}
... | 12,607 |
17,056,796 | I'm trying to send an ascii command over tcp/ip but python (i think) add a header to he string.
if I do a `s.send(bytes('RV\n ', 'ascii'))` I get an eRV rather than RV when I inspect the command going out. Any ideas?
[Previous post](https://stackoverflow.com/questions/16968253/python-3-tcp-ip-ascii-command). | 2013/06/12 | [
"https://Stackoverflow.com/questions/17056796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2460673/"
] | If you want to stay away from SQL you can try with [EntityFramework.Extended](http://weblogs.asp.net/pwelter34/archive/2011/11/29/entity-framework-batch-update-and-future-queries.aspx).
Provides support for writing LINQ like batch delete/update queries. I only tried it once, it worked nice, but not sure if i would us... | There are two ways I can think of right off hand to achieve what you are seeking.
1) create a stored procedure and call it from your entity model.
2) Send the raw command text to the db, see this [microsoft article](http://msdn.microsoft.com/en-us/data/jj592907.aspx) | 12,608 |
17,420,528 | I am following the book "how to think like a computer scientist" to learn python
and am having some problems understanding the classes and object chapter.
An exercise there says to write a function named moveRect that takes a Rectangle and 2 parameters named dx& dy. It should change the location of the rectangle by ad... | 2013/07/02 | [
"https://Stackoverflow.com/questions/17420528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297440/"
] | In your first example, you passed the *class* as an argument instead of the *instance* you created. Because there is no `self.x` in the class `Rectangle`, the error was raised.
You could just put the function in the class:
```
class Rectangle:
def __init__(self, x, y, width, height):
self.x = x
se... | Frob instances, not types.
```
moveRect(rect, dx, dy)
``` | 12,609 |
30,460,461 | I have this in my project urlconf `photocheck.urls`:
```
urlpatterns = patterns('',
url(r'^admin/docs/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^rest/', include('core.urls')),
url(r'^shotmaker/', include('shotmaker.urls')),
url(r'^report/', incl... | 2015/05/26 | [
"https://Stackoverflow.com/questions/30460461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4057053/"
] | Use [`reverse_lazy()`](https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse-lazy) instead of `reverse()`. | I got same error and solved but only `reverse_lazy()` is not enough, use `reverse_lazy()` like `reverse_lazy('app_name:url_name')`. | 12,613 |
20,338,064 | I am trying to execute a command on a file such as chmod in a python script. How can I get the file name from command line to the script? I want to execute the script like so ./addExecute.py blah
Where blah is the name of some file. The code I have is this:
```
#!/usr/bin/python
import sys
import os
file = sys.argv[1... | 2013/12/02 | [
"https://Stackoverflow.com/questions/20338064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3058993/"
] | ```
os.system("chmod 700 file")
^^^^--- literal string, looking for a file named "file"
```
You probably want
```
os.system("chmod 700 " + file)
^^^^^^---concatenate your variable named "file"
``` | It could be something like
```
os.system("chmod 700 %s" % file)
``` | 12,614 |
69,963,185 | I am trying to convert excel database into python.
I have a trading data which I need to import into the system in xml format.
my code is following:
```
df = pd.read_excel("C:/Users/junag/Documents/XML/Portfolio2.xlsx", sheet_name="Sheet1", dtype=object)
root = ET.Element('trading-data')
root.set('xmlns:xsi', 'http:/... | 2021/11/14 | [
"https://Stackoverflow.com/questions/69963185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17410005/"
] | If you are creating a binding then the property must be notifiable, that is, have an associated signal and emit it when it changes:
```py
class Manager(QObject):
processResult = Signal(bool)
df_changed = Signal()
def __init__(self):
QObject.__init__(self)
self.ds = "loading .."
@Slot(... | you should set Row value after setting property, like this:
```
tbModel.setRow(1,
{
param_name: "number of classes",
value: backend.paramDs
}
)
```
tbModel is id of your Table View's Model | 12,619 |
39,533,766 | I'm having a little problem with a modal in django.
I have a link which calls an id and the id is a modal. However, the modal isn't opening. I'm pretty sure that this is happening because the link is inside a "automatic" form, but I'm new in django and python so I have no idea.
The code is:
```
{% block body %}
... | 2016/09/16 | [
"https://Stackoverflow.com/questions/39533766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5516104/"
] | Change your `<a>` tag to the following:
```
<a class="btn btn-info btn-block btn-password" href="#"
data-toggle="modal" data-target="#change-password">Alterar senha</a>
```
At least this is how I do it in my Django templates. As I think **@souldeux** was trying to say, you need to use the `data-target` attribute... | ```
<a class="btn btn-info btn-block btn-password" href="#change-password" data-toggle="modal">Alterar senha</a>
```
You need a `data-target` attribute in addition to your `data-toggle`. <http://getbootstrap.com/javascript/#live-demo> | 12,620 |
6,403,757 | I tried installing pycurl via pip. it didn't work and instead it gives me this error.
```
running install
running build
running build_py
running build_ext
building 'pycurl' extension
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv
-Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arc... | 2011/06/19 | [
"https://Stackoverflow.com/questions/6403757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200412/"
] | I got it working using this
```
sudo env ARCHFLAGS="-arch x86_64" pip install pycurl
``` | if you are on linux with apt-get:
```
lnx#> apt-get search pycurl
```
To install:
```
lnx#> sudo apt-get install python-pycurl
```
if on linux with yum:
```
lnx#> yum search pycurl
I get this on my comp:
python-pycurl.x86_64 : A Python interface to libcurl
```
To install i've did:
`lnx#> sudo yum install ... | 12,622 |
33,442,411 | In one of our homework problems, we need to write a class in python called Gate which contains the drawing and function of many different gates in a circuit. It describes as follows:
```
in1 = Gate("input")
out1 = Gate("output")
not1 = Gate("not")
```
Here `in1`, `out1`, `not1` are all instances of this class. What... | 2015/10/30 | [
"https://Stackoverflow.com/questions/33442411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5508199/"
] | Create a wrapper function around `fun` to select an element of the array. For example, the following will integrate the first element of the array.
```
from scipy.integrate import quad
# The function you want to integrate
def fun(x, a):
return np.asarray([a * x, a * x * x])
# The wrapper function
def wrapper(x, ... | Your function returns an array, `integrate.quad` needs a float to integrate. So you want to give it a function that returns one of the elements from your array instead of the function itself. You can do that via a quick `lambda`:
```
def integrate(a, index=0)
return quad(lambda x,y: fun(x, y)[index], 0, 1, args=a... | 12,623 |
38,668,389 | Im in need of help outputting the json key with python. I tried to output the name "carl".
Python code :
```
from json import loads
import json,urllib2
class yomamma:
def __init__(self):
url = urlopen('http://localhost/name.php').read()
name = loads(url)
print "Hello" (name)
```
Php code (fo... | 2016/07/29 | [
"https://Stackoverflow.com/questions/38668389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6580871/"
] | I'll just assume the PHP code works correctly, I don't know PHP very well.
On the client, I recommend using [`requests`](http://docs.python-requests.org/en/master/) (installable through `pip install requests`):
```
import requests
r = requests.get('http://localhost/name.php')
data = r.json()
print data['person_one']... | try this:
```
import json
person_data = json.loads(url)
print "Hello {}".format(person_data["person_one"])
``` | 12,624 |
31,346,790 | I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
```
import os, zipfile
fo... | 2015/07/10 | [
"https://Stackoverflow.com/questions/31346790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688131/"
] | Below is the code that worked for me:
```
import os, zipfile
dir_name = 'C:\\SomeDirectory'
extension = ".zip"
os.chdir(dir_name) # change directory from working dir to dir with files
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
... | You need to construct a `ZipFile` object with the filename, and *then* extract it:
```
zipfile.ZipFile.extract(item)
```
is wrong.
```
zipfile.ZipFile(item).extractall()
```
will extract all files from the zip file with the name contained in `item`.
I think you should more closely read the documentation... | 12,625 |
55,355,567 | I am writing code to read data from a CSV file to a pandas dataframe and to get the unique values and concatenate them as a string. The problem is that one of the columns contains the values `True` and `False`. So while concatenating the values I am getting the error
>
>
> ```
> sequence item 0: expected str insta... | 2019/03/26 | [
"https://Stackoverflow.com/questions/55355567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584680/"
] | Python 3 does not preform implicit casts. You will need to explicitly cast your booleans to strings.
This can be done easily with [`map` builtin function](https://docs.python.org/3/library/functions.html?highlight=builtin%20filter#map) which applies a function on each item of an iterable and returns the result:
```
s... | Use `.astype(str)`
**Ex:**
```
df[i].unique().astype(str).tolist()
``` | 12,634 |
54,880,349 | I have installed Python 3.7 64-bit on my 64-bit OS. I have also Installed mysql-installer-community-8.0.15.0 plus I installed MySQL connector using this code `python -m pip install mysql-connector` and still when I try to import mysql.connector. I get this error.
>
> "C:\Users\Basir
> Payenda\PycharmProjects\newprj\... | 2019/02/26 | [
"https://Stackoverflow.com/questions/54880349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11080590/"
] | You are doing
```
throw new InvalidTestScore("Invalid Test Score");
```
so you have to declare that your method is actually going to throw this exception
```
public static void inTestScore(int[] arr) throws InvalidTestScore
``` | You must declare that your method may throw this exception:
```
public static void inTestScore(int[] arr) throws InvalidTestScore {
...
}
```
This allows the compiler to force any method that calls your method to either catch this exception, or declare that it may throw it. | 12,635 |
63,710,044 | I am trying to use Serverless Framework to deploy a Python Fast API WebApp.
Is is related to issue:
<https://github.com/jordaneremieff/mangum/issues/126>
When I deploy it using serverless, sls depoy and Invoke the function I am getting the following error:
```
[ERROR] KeyError: 'requestContext'
Traceback (most recen... | 2020/09/02 | [
"https://Stackoverflow.com/questions/63710044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694699/"
] | The issue lies within the `mangum` adapter expecting input similar to the `event` content specified by [AWS API Gateway shown here](https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html). You'll see that there's a `requestResponse` dictionary there that the Mangum adapter seems to strictly require to fu... | You need to provide at least the **minimal** `Event data`, like in the example below,
when you invoke a FastAPI-based lambda function (for example via AWS console Lambda -> Test Event):
```
{
"resource": "/",
"path": "/api/v1/test/",
"httpMethod": "GET",
"requestContext": {
},
"multiValueQueryStringParamet... | 12,636 |
24,478,623 | I trying to setup virtualenvwrapper in GitBash (Windows 7). I write the next lines:
`1 $ export WORKON_HOME=$HOME/.virtualenvs
2 $ export MSYS_HOME=/c/msys/1.0
3 $ source /usr/local/bin/virtualenvwrapper.sh`
And the last line give me an error:
`source /usr/local/bin/virtualenvwrapper.sh
sh.exe: /usr/local/bin/virtu... | 2014/06/29 | [
"https://Stackoverflow.com/questions/24478623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I believe it has something to do with the "image" input.
have you considered using a button element instead?
```
<button type="submit" name="someName" value="someValue"><img src="someImage.png" alt="SomeAlternateText"></button>
``` | Try this :-
```
<form action="dologin.php" method="post">
<input type="text" name="email" class="form-control" placeholder="Username">
<input type="password" name="password" class="form-control" placeholder="Password">
<input type="image" src="img/login.png" type="submit" alt="Login">
</form>
```
And in dologi... | 12,637 |
38,316,477 | so i'm trying to convert a bash script, that i wrote, into python, that i'm learning, and the python equivalent of the bash whois just can't give me the answer that i need.
this is what i have in bash-
```
whois 'ip address' | grep -i abuse | \
grep -o [[:alnum:]]*\@[[:alnum:]]*\.[[:alpha:]]* | sort -u
```
and... | 2016/07/11 | [
"https://Stackoverflow.com/questions/38316477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6576450/"
] | This should do what you are looking for. It works correctly in the snippet.
```js
window.onload = onPageLoad();
function onPageLoad() {
document.getElementById("1403317").checked = true;
}
```
```html
<input type="checkbox" id="1403317">
``` | try this one maybe ?
```
$(document).ready(function() {
$('#1403317').attr('checked', true)
};
``` | 12,638 |
49,771,589 | I just made the transition from Spyder to VScode for my python endeavours. Is there a way to run individual lines of code? That's how I used to do my on-the-spot debugging, but I can't find an option for it in VScode and really don't want to keep setting and removing breakpoints.
Thanks. | 2018/04/11 | [
"https://Stackoverflow.com/questions/49771589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4482349/"
] | If you highlight some code, you can right-click or run the command, `Run Selection/Line in Python Terminal`.
We are also planning on [implementing Ctrl-Enter](https://github.com/Microsoft/vscode-python/issues/1349) to do the same thing and looking at [Ctr-Enter executing the current line](https://github.com/Microsoft/... | One way you can do it is through the Integrated Terminal. Here is the guide to open/use it: <https://code.visualstudio.com/docs/editor/integrated-terminal>
After that, type `python3` or `python` since it is depending on what version you are using. Then, copy and paste the fraction of code you want to run into the term... | 12,639 |
61,394,928 | I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks. | 2020/04/23 | [
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] | This also works well:
```
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.replace(/\s*$/, '')
... | First, install prompt-sync: `npm i prompt-sync`
Then in your JavaScript file:
```
const ps = require("prompt-sync");
const prompt = ps();
let name = prompt("What is your name? ");
console.log("Hello, ", name);
```
That's it.
You can improve this by adding `{sigint: true}` when initialising ps. With this configurat... | 12,647 |
46,776,264 | My application requirement is to use our LDAP directory to authenticate a User based on their network login. I setup the LDAP correctly using ldap3 in my system.py. I'm able to bind to a user and identify credentials in python, not using Django. Which authentication backend would I set Django up to use to make my login... | 2017/10/16 | [
"https://Stackoverflow.com/questions/46776264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8570299/"
] | This is a broad question and I am not sure your experience with Django so without more information I would suggest trying [this](https://github.com/etianen/django-python3-ldap) or [this](http://fle.github.io/combine-ldap-and-classical-authentication-in-django.html) | I am running Python 3 and have used the excellent `django-python3-ldap` package with both OpenLDAP and Active Directory from Django 1.6 through 2.0. You can find it here:
<https://github.com/etianen/django-python3-ldap>
It is a well maintained package that we've been able to use as we upgrade Django from version to v... | 12,657 |
49,352,889 | I installed `fiona` as follows:
```
conda install -c conda-forge fiona
```
It installed without any errors. When I try to import `fiona`, I get the following error:
Traceback (most recent call last):
```
File "<stdin>", line 1, in <module>
File "/home/name/anaconda3/lib/python3.6/site-packages/fiona/__init__.p... | 2018/03/18 | [
"https://Stackoverflow.com/questions/49352889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9400561/"
] | I guess this problem comes from conflicts with stuff already installed in the Anaconda distribution. My inelegant workaround is:
```
conda install -c conda-forge geopandas
conda remove geopandas fiona
pip install geopandas fiona
``` | Because I did not want to uninstall geopandas, I solved the issue by upgrading fiona via pip
```
pip install --upgrade fiona
``` | 12,658 |
56,378,783 | I'm doing a supposedly simple python challenge a friend gave me involving an elevator and the logic behind its movements. Everything was going well and good until I got to the point where I had to write how to determine if the elevator could move hit a called floor en route to its next queued floor.
```py
def floorCom... | 2019/05/30 | [
"https://Stackoverflow.com/questions/56378783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10760049/"
] | I think your problem lies in the use of a for loop in conjunction with the queue.remove() function. It seems like the `for x in queue:` operator runs into problems when you edit the list while it runs. I would recommend using `while queue:` instead and setting x to the first element.
```
while queue:
x = ... | The reason for it to skip floor 6, is because of removing the data from the list, which is being iterated.
```
l=[3,6,9,10,14]
for i in l:
print(i)
```
Output:
3
6
9
10
14
```
for i in l:
print(i)
l.remove(i)
```
output:
3
9
14 | 12,659 |
69,869,854 | Can I get the `__doc__` string of the main script?
Here is the starting script, which would be run from command line: `python a.py`
module a.py
```py
import b
b.func()
```
module b.py
```py
def func():
???.__doc__
```
How can I get the calling module, as an object?
I am not asking about how to get the file... | 2021/11/07 | [
"https://Stackoverflow.com/questions/69869854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84196/"
] | a.py
```
"""
Foo bar
"""
import b
if __name__ == '__main__':
b.show_your_docs()
```
b.py
```
def show_your_docs():
name = caller_name(1)
print(__import__(name).__doc__)
```
Where caller\_name is code from this [gist](https://gist.github.com/techtonik/2151727#gistcomment-2333747)
The weakness of this... | This is the full solution from @MatthewMartin 's accepted answer:
```
def show_your_docs():
name = caller_name(1)
print(__import__(name).__doc__)
def caller_docstring(level=1):
name = caller_name(level)
return __import__(name).__doc__
def caller_name(skip=2):
def stack_(frame):
... | 12,662 |
18,587,208 | can any one tell me how to simulate touch on Image Button using android view client python | 2013/09/03 | [
"https://Stackoverflow.com/questions/18587208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2741623/"
] | Replace
```
android:src="res/drawable-hdpi/capture.PNG"
```
with
```
android:src="@drawable/capture"
```
Hope it helps. | change
```
android:src="res/drawable-hdpi/capture.PNG"
```
with
```
android:src="@drawable/capture"
``` | 12,663 |
28,180,511 | I wrote a simple triple quote print statement. See below. For the OVER lineart, it gets truncated into two different lines (when you copy paste this into the interpreter.) But, if I insert a space or any at the end of each of the lines, then it prints fine. Any idea why this behavior in python.
I am inclined to think ... | 2015/01/27 | [
"https://Stackoverflow.com/questions/28180511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4500493/"
] | You have `\` backslash escapes in your string, one each on the last two lines as well as on the first line spelling *over*, all three part of the letter *R*. These signal to Python that you wanted to *ignore* the newline right after it.
Either use a space right after each `\` backslash at the end of a line, *double* t... | The problem is with `\` at the end of line so you need to escape them. For that i use another backslash.
```
print(
"""
_____ ____ __ __ ______
/ ____| / _ | / | /| | ____|
| | / / | | / /| /| | | |___
| | _ / /__| | ... | 12,667 |
54,914,306 | This code fails when it runs:
```
import datetime
import subprocess
startdate = datetime.datetime(2010,4,9)
for i in range(1):
startdate += datetime.timedelta(days=1)
enddate = datetime.datetime(2010,4,10)
for i in range(1):
enddate += datetime.timedelta(days=1)
subprocess.call("sudo mam-list-usag... | 2019/02/27 | [
"https://Stackoverflow.com/questions/54914306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11035382/"
] | When possible, pass a *list* containing your command name and its arguments.
```
subprocess.call(["sudo", "mam-list-usagerecords",
"-s", str(startdate),
"-e", str(enddate),
"--format", "csv",
"--full"])
```
This avoids the need to even know how the ... | When I first started using some of the subprocess methods I ran into some of the same issues.
Try running your code like this:
```
import datetime
import subprocess
import shlex
startdate = datetime.datetime(2010, 4, 9) + datetime.timedelta(days=1)
enddate = datetime.datetime(2010, 4, 10) + datetime.timedelta(days=1... | 12,668 |
34,999,726 | Imagine I have an initializer with optional parameter
```
def __init__(self, seed = ...):
```
Now if parameter is not specified I want to provide a default value. But the seed is hard to calculate, so I have a class method that suggests the seed based on some class variables
```
MyClass.seedFrom(...)
```
Now how ... | 2016/01/25 | [
"https://Stackoverflow.com/questions/34999726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982238/"
] | In case you only need to call `seedFrom` once, you can do so when `__init__` is defined.
```
class MyClass:
# Defining seedFrom as a function outside
# the class is also an option. Defining it
# as a class method is not, since you still
# have the problem of not having a class to
# pass as the fir... | If you must do this in the **init** and want the seed method to be on the class, then you can make it a class method, eg as follows:
```
class SomeClass(object):
defaultSeed = 255
@classmethod
def seedFrom(cls, seed):
pass # some seed
def __init__(self, seed=None):
self.seedFrom(seed... | 12,669 |
4,011,526 | I am a nurse and I know python but I am not an expert, just used it to process DNA sequences
We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format... | 2010/10/25 | [
"https://Stackoverflow.com/questions/4011526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485991/"
] | This uses [dateutil](http://labix.org/python-dateutil) to parse the date (e.g. '11/11/2010 - 09:00am'), and [parsedatetime](http://code.google.com/p/parsedatetime/) to parse the relative time (e.g. '4 hours later'):
```
import dateutil.parser as dparser
import parsedatetime.parsedatetime as pdt
import parsedatetime.pa... | Here are some possible way you can solve this -
1. **Using Regular Expressions** - Define them according to the patterns in your text. Match the expressions, extract pattern and you repeat for all records. This approach needs good understanding of the format in which the data is & of course regular expressions :)
2. ... | 12,670 |
49,100,167 | So I'm optimizing a game playing bot and have run out of optimizations in pure python. Currently, most of the time is spent translating one game state into the next game state for the alpha-beta search. The current thinking is that I could speed this up by writing the state-transition code in C. My problem comes from t... | 2018/03/04 | [
"https://Stackoverflow.com/questions/49100167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/409106/"
] | This is not the expected behaviour. Components that do not change should not re-execute the mounted hook.
I would search for the problem someplace in the top of the vue component hierarchy, because it sounds like some other piece of code might force the re-rendering of the hierarchy. | When router's path changes, components will mount again,if you want to mount component only one time, you can try the Vue's build-in component **keep-alive**, it will only trigger its activated hook and deactivated hook.And you can do something in these two hooks.
**The html:**
```
<div id="app">
<router-link t... | 12,676 |
74,009,340 | My question is similar to this([Python sum on keys for List of Dictionaries](https://stackoverflow.com/questions/8584504/python-sum-on-keys-for-list-of-dictionaries)), but need to sum up the values based on two or more key-value elements.
I have a list of dictionaries as following:
```
list_to_sum=
[{'Name': '... | 2022/10/10 | [
"https://Stackoverflow.com/questions/74009340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20188249/"
] | You could create a [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter).Then you can simply add the values as the appear using the tuple as `(Name, City)` as the key:
```
from collections import Counter
list_to_sum=[
{'Name': 'A', 'City': 'W','amt':100},
{'Name': 'B'... | ```
list_to_sum = [{'Name': 'A', 'City': 'W', 'amt': 100},
{'Name': 'B', 'City': 'A', 'amt': 200},
{'Name': 'A', 'City': 'W', 'amt': 300},
{'Name': 'C', 'City': 'X', 'amt': 400},
{'Name': 'C', 'City': 'X', 'amt': 500},
{'Name': 'A', 'City': 'W',... | 12,677 |
50,692,816 | I am getting the following SSL issue when running pip install:
```
python -m pip install zeep
Collecting zeep
Retrying (Retry(total=4, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'SSLError(SSLError("bad handshake:
Error([('SSL routines', 'ssl3_get_server_certificate', 'certific... | 2018/06/05 | [
"https://Stackoverflow.com/questions/50692816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1045057/"
] | I was able to resolve the issue by using the following:
```
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --index-url=https://pypi.org/simple/ zeep
``` | If using windows then make sure the below three paths are added in Windows environment variable :
1. ....\Anaconda\Library\bin
2. ....\Anaconda\Scripts
3. ....\Anaconda
If not using Anaconda then in place of Anaconda the path where python is installed. | 12,679 |
64,251,311 | First post so be gentle please.
I have a bash script running on a Linux server which does a daily sftp download of an Excel file. The file is moved to a Windows share.
An additional requirement has arisen in that i'd like to add the number of rows to the filename which is also timestamped so different each day. Ideall... | 2020/10/07 | [
"https://Stackoverflow.com/questions/64251311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14409634/"
] | Assuming we put your python into a separate script file, something like:
```py
# count_script.py
import sys
import pandas as pd
excel_file = pd.ExcelFile(sys.argv[1])
df = excel_file.parse('mysheet')
print(df[['code']].count().at(0))
```
We could then easily call that script from within the bash script that invoked... | You can pass command-line arguments to python programs, by invoking them as such:
```
python3 script.py argument1 argument2 ... argumentn
```
They can then be accessed within the script using `sys.argv`. You must `import sys` before using it. `sys.argv[0]` is the name of the python script, and the rest are the addit... | 12,680 |
7,518,067 | I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt... | 2011/09/22 | [
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] | Use **shutil.copy2** instead of **shutil.copyfile**
```
import shutil
shutil.copy2('/src/dir/file.ext','/dst/dir/newname.ext') # file copy to another file
shutil.copy2('/src/file.ext', '/dst/dir') # file copy to diff directory
``` | well the questionis old, for new viewer of Python 3.6
use
```
shutil.copyfile( "D:\Out\myfile.txt", "D:\In" )
```
instead of
```
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
```
`r` argument is passed for reading file not for copying | 12,681 |
41,857,659 | My python code works correctly in the below example. My code combines a directory of CSV files and matches the headers. However, I want to take it a step further - how do I add a column that appends the filename of the CSV that was used?
```
import pandas as pd
import glob
globbed_files = glob.glob("*.csv") #creates ... | 2017/01/25 | [
"https://Stackoverflow.com/questions/41857659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067066/"
] | This should work:
```
import os
for csv in globbed_files:
frame = pd.read_csv(csv)
frame['filename'] = os.path.basename(csv)
data.append(frame)
```
`frame['filename']` creates a new column named `filename` and `os.path.basename()` turns a path like `/a/d/c.txt` into the filename `c.txt`. | Mike's answer above works perfectly. In case any googlers run into the following error:
```
>>> TypeError: cannot concatenate object of type "<type 'str'>";
only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid
```
It's possibly because the separator is not correct. I was using a custom csv fil... | 12,691 |
34,971,363 | I am heavily using python threading, and my many use-cases require that I would log separate task executions under different logger names.
A typical code example would be:
```
def task(logger=logger):
global_logger.info('Task executing')
for item in [subtask(x) for x in range(100000)]:
# While debuggi... | 2016/01/24 | [
"https://Stackoverflow.com/questions/34971363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1055356/"
] | Because loggers inherit their parent's level if not explicitly set, you could just do e.g.
```
root_name = global_logger.name
logging.getLogger(root_name + '.main.task').setLevel(logging.INFO)
```
and that would mean that all child loggers inherit that level, unless a level were explicitly set for one of them.
Note... | I was having the same issue suppressing the output from the `BAC0` library. I tried changing the parent logger and that did not update the children (Python 3.9)
This answer is based on the accepted answer in this post: [How to list all existing loggers using python.logging module](https://stackoverflow.com/questions/5... | 12,693 |
35,204,703 | one script starts automatically when my raspberry is booted up, within this script there is motion sensor, if detected, it starts a subproces camera.py (recording a video, then converts the video and emails)
within the main script that starts u on booting up, there is another if statement, if button pressed then stop ... | 2016/02/04 | [
"https://Stackoverflow.com/questions/35204703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5794219/"
] | Use `pkill`:
```
$ sudo pkill -f camera.py
``` | If you make camera.py executable, put it on your $PATH and make line 1 of the script `#!/usr/bin/python`, then execute camera.py without the python command in front of it, your `"sudo killall camera.py"` command should work. | 12,694 |
40,866,883 | I use python 3.4 , pyQt5 and Qt designer (Winpython distribution). I like the idea of making guis by designer and importing them in python with setupUi. I'm able to show MainWindows and QDialogs. However, now I would like to set my MainWindow, always on top and with the close button only. I know this can be done by set... | 2016/11/29 | [
"https://Stackoverflow.com/questions/40866883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491532/"
] | Every call of `setWindowFlags` will completely override the current settings, so you need to set all the flags at once. Also, you must include the `CustomizeWindowHint` flag, otherwise all the other hints will be ignored. The following will probably work on Windows:
```
self.setWindowFlags(
QtCore.Qt.Windo... | I would propose a different solution, because it keeps the existing flags. Reason to do this, is to NOT mingle with UI-specific presets (like that a dialog has not by default a "maximize" or "minimize" button).
```
self.setWindowFlags(self.windowFlags() # reuse initial flags
& ~QtCore.Qt.WindowContextHelpButtonHin... | 12,697 |
47,689,456 | I was trying to connect oracle database using python like below.
```
import cx_Oracle
conn = cx_Oracle.connect('user/password@host:port/database')
```
I've faced an error when connecting oracle.
DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No ... | 2017/12/07 | [
"https://Stackoverflow.com/questions/47689456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176741/"
] | That error indicates that you are missing a 64-bit Oracle client installation or it hasn't been configured correctly. Take a look at the link mentioned in the error message. It will give instructions on how to perform the Oracle client installation and configuration.
[Update on behalf of Anthony: his latest cx\_Oracle... | This seems a problem with version 6.X.This problem didnot appeared in 5.X.But for my case a little workaround worked.I installed in my physical machine and only thing that i need to do was a pc reboot or reopen the terminal as i have added in the path of environment variables.You can try to install in physical machine ... | 12,698 |
53,649,039 | I have a Databricks notebook setup that works as the following;
* pyspark connection details to Blob storage account
* Read file through spark dataframe
* convert to pandas Df
* data modelling on pandas Df
* convert to spark Df
* write to blob storage in single file
My problem is, that you can not name the file outpu... | 2018/12/06 | [
"https://Stackoverflow.com/questions/53649039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6050134/"
] | >
> I know the compiler is supposed to generate an error for templates that are erroneous for any template parameter even if not instantiated.
>
>
>
That is not the case, though. If no instantiation can be generated for a template, then the program is ill-formed, **no diagnostic required**(1). So the program is il... | While it's largely a quality of implementation issue, `-Werror` can indeed (and does) interfere with SFINAE. Here is a more involved example to test it:
```
#include <type_traits>
template <typename T>
constexpr bool foo() {
if (false) {
T a;
}
return false;
}
template<typename T, typename = void... | 12,703 |
40,476,046 | i'm actually an amateur python programmer and am trying to use the django framework for an android app backend. everything is okay but my problem is actually how to pass the image in the Filefield to JSON. i have tried using SerializerMethodField as described in the rest framework documentation but didn't work. sorry i... | 2016/11/07 | [
"https://Stackoverflow.com/questions/40476046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6214350/"
] | If you want to check if two files are equal, you can check the exit code of `diff -q` (or `cmp`). This is faster since it doesn't require finding the exact differences:
```
if diff -q file1 file2 > /dev/null
then
echo "The files are equal"
else
echo "The files are different or inaccessible"
fi
```
All Unix tools... | You can use the logic pipe:
For one command:
```
diff -q file1 file2 > /dev/null && echo "The files are equal"
```
Or more commands:
```
diff -q file1 file2 > /dev/null && {
echo "The files are equal"; echo "Other command"
echo "More other command"
}
``` | 12,704 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.