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 |
|---|---|---|---|---|---|---|
5,898,555 | I'm playing with the [pyflakes plugin for vim](https://github.com/kevinw/pyflakes-vim) and now when I open a python file I get the error messages in the screenshot [here](http://dl.dropbox.com/u/6114719/Screenshot.png)
Any ideas how to fix this?
Thanks in advance... | 2011/05/05 | [
"https://Stackoverflow.com/questions/5898555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91748/"
] | Could be an issue with the version of Python you're running under vs. what the package you're using is looking for. A quick google for "Module getChildNodes python" got me to the page for [Python compiler package](http://docs.python.org/library/compiler.html) which has one of those nice little "Deprecated" messages on ... | This is a bug in pyflakes and we cannot help you with this here.
Try filing an issue on [their git repository](https://github.com/kevinw/pyflakes-vim/issues). | 15,494 |
16,794,663 | In python I'm trying to grab multiple inputs from string using regular expression; however, I'm having trouble. For the string:
```
inputs = 12 1 345 543 2
```
I tried using:
```
match = re.match(r'\s*inputs\s*=(\s*\d+)+',string)
```
However, this only returns the value `'2'`. I'm trying to capture all ... | 2013/05/28 | [
"https://Stackoverflow.com/questions/16794663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877334/"
] | You could try something like:
`re.findall("\d+", your_string)`. | You should look at this answer: <https://stackoverflow.com/a/4651893/1129561>
In short:
>
> In Python, this isn’t possible with a single regular expression: each capture of a group overrides the last capture of that same group (in .NET, this would actually be possible since the engine distinguishes between captures... | 15,500 |
35,469,118 | I have been using my Raspberry Pi 2 to do some motion detection using a USB webcam and the motion package and am incredibly frustrated.
**Can someone explain to me how the on\_motion\_detected method is supposed to work??????**
The idea is that when the camera detects motion, a script is executed. The script just ech... | 2016/02/17 | [
"https://Stackoverflow.com/questions/35469118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4851753/"
] | Ypu have to remove ; which stands for commenting the line
; on\_motion\_detected python /home/pi/Desktop/Python/script.py
but
```
on_motion_detected python /home/pi/Desktop/Python/script.py
``` | Check that you have specified the process id properly in motion.conf:
**process\_id\_file /var/run/motion/motion.pid**
Once you have checked that, change the following settings to arbitrarily low values e.g.
**threshold 1**
**noise\_level 1** | 15,505 |
63,400,324 | I am relatively new to python and pandas. I am trying to replicate a battleship game. My goal is to locate the row and column that has 1 and storage that location as the Battleship location. I created a CSV file and it looks like this
```
col0,col1,col2,col3,col4,col5
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,1,0,0,0,0
0,... | 2020/08/13 | [
"https://Stackoverflow.com/questions/63400324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11763345/"
] | You really don't need to loop, you can use [`numpy.where`](https://numpy.org/doc/stable/reference/generated/numpy.where.html):
```
import pandas as pd
import numpy as np
df = pd.read_csv('/content/pandas_tutorial/My Drive/pandas/myBattleshipmap.csv',)
r, c = np.where(df.astype(bool))
print(r.tolist())
print(df.colum... | Use `where` to turn all values that are not 1 to `NaN`, then stack will leave you with a MultiIndex Series, whose index gives you the (row\_label, col\_label) tuples of everything that was 1.
```
df.where(df.eq(1)).stack().index
#MultiIndex([(3, 'col1')],
# )
```
---
If you don't want the column names, pe... | 15,513 |
47,145,930 | I read the Susan Fowler's book "production ready microservices" and in two places (until now) I found
* (page 26) "Avoid Versioning Microservices and Endpoints",
* "versioning microservices can easily become an organizational nightmare" (page 27),
* In microservice ecosystems, the versioning of microservices is disco... | 2017/11/06 | [
"https://Stackoverflow.com/questions/47145930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526119/"
] | Are you sure that she was not talking about incorporating the version into the **name** of the service or into the **name** of the endpoint?
Service called OrderProcessing\_2\_4\_1 with a versioned endpoint of get\_order\_2\_4\_1 is a very bad idea. OrderProcessing\_2\_4 with a versioned endpoint of get\_order\_2\_4 is... | The author of the book is correct in that it is difficult to update the version of an API, especially if it is popular. This is because you will have to either hunt down all the users of the older version and have them upgrade or you will have to support two versions of your software in production at the same time.
B... | 15,514 |
12,054,772 | I'm new to python (learning for 2 weeks only) and there's something I really can't even try (I have been googling for an hour and coulndn't find any).
`file1` and `file2` are both CSV files.
I've got a function that looks like:
```
def save(file1, file2):
```
it is for `file2` to have the same content as `file1`.... | 2012/08/21 | [
"https://Stackoverflow.com/questions/12054772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1614184/"
] | Python has a standard module [`shutil`](https://docs.python.org/2/library/shutil.html) which is useful for these sorts of things.
If you need to write the code to do it yourself, simply open two files (the input and the output). Loop over the file object, Reading lines from the input file and write them into the outpu... | If you simply want to copy a file you can do this:
```
def save(file1, file2):
with open(file1, 'rb') as infile:
with open(file2, 'wb') as outfile:
outfile.write(infile.read())
```
this copies the file with name `file1` to the file with name `file2`. It really doesn't matter what the content ... | 15,515 |
38,709,118 | I'm trying to validate a certificate with a CA bundle file. The original Bash command takes two file arguments like this;
```
openssl verify -CAfile ca-ssl.ca cert-ssl.crt
```
I'm trying to figure out how to run the above command in python subprocess whilst having ca-ssl.ca and cert-ssl.crt as variable strings (as o... | 2016/08/01 | [
"https://Stackoverflow.com/questions/38709118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1165419/"
] | Bash process substitution `<(...)` in the end is supplying a file path as an argument to `openssl`.
You will need to make a helper function to create this functionality since Python doesn't have any operators that allow you to inline pipe data into a file and present its path:
```
import subprocess
def validate_ca(c... | If you want to use process substitution, you will *have* to use `shell=True`. This is unavoidable. The `<(...)` process substitution syntax is bash syntax; you simply must call bash into service to parse and execute such code.
Additionally, you have to ensure that `bash` is invoked, as opposed to `sh`. On some systems... | 15,516 |
62,811,729 | mistakenly first i installed python 3.6 then install pip,then i install python 3.8 after that i checked the pip version its shows me.
```
pip 20.1.1 from /usr/local/lib/python3.6/dist-packages/pip (python 3.6)
```
Can i change to
```
pip 20.1.1 from /usr/local/lib/python3.8/dist-packages/pip (python 3.8)
``` | 2020/07/09 | [
"https://Stackoverflow.com/questions/62811729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820094/"
] | I believe you can do that if you simply remove `col2` from your select and group by. Because `col2` will no longer be returned, you should also remove the having statement. I think it should look something like this:
```sql
select
c.col1,
count(1)
from
table_1 a,
table_2 b,
table_3 c
where
a.ke... | use sum() and only group by for the col1
```
select c.col1, sum(a.col2) as total
from table_1 a,table_2 b.table_3 c
where a.key =b.key and b.no = c.no
group by c.col1;
```
**Output---**
```
c.col1 total
aa1 10
aa2 5
``` | 15,517 |
19,737,844 | I know that the Jinja2 library allows me to pass datastore models from my python code to html and access this data from inside the html code as shown [in this example](https://developers.google.com/appengine/docs/python/gettingstartedpython27/templates) . However Jinja2 isn't compatible with javascript and I want to ac... | 2013/11/02 | [
"https://Stackoverflow.com/questions/19737844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2559007/"
] | You should create a python controller which serves JSON formatted data, which any Javascript library (especially jQuery) can consume from. Then, setup the Jinja2 template to contain some Javascript which calls, loads and displays said data. | It has nothing to do with compatibility. Jinja is server side templating. You can use javascript for client side coding.
Using Jinja you can create HTML, which can be accessed by javascript like normal HTML.
To send datastore entities to your client you can use Jinja to pass a Python list or use a json webservice. | 15,520 |
66,412,526 | I am quite new to python and I have a table of occupancy that looks like this:
```
| room | free| date | place
| room_1 | 0 | 2021-01-13| Boston|
|room_2 |1| 2021-02-14| Boston|
|room_2|0|2021-02-15|Boston|
```
...
How can I calculate how often a room was free within a timeframe of a month and a week for ea... | 2021/02/28 | [
"https://Stackoverflow.com/questions/66412526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10094012/"
] | Hopefully there aren't many holes in the Unity documentation, but when you do find one you can often find sample code in the [Unity Quickstarts](https://github.com/firebase/quickstart-unity) (as these are also used to validate changes to the Unity SDK).
From [`UIHandler.cs`](https://github.com/firebase/quickstart-unit... | <https://firebase.google.com/docs/auth/ios/game-center> This might answer your question. You may have to implement this feature in XCode when you export the project from unity | 15,527 |
52,459,081 | Good morning everyone!
I am new to programming and am learning python. I am trying to create a function that converts each individual char in string into each corresponding individuals ints and displays them one after another. The first error it generates is "c is not defined".
```
c=''
def encode(secret_message):
... | 2018/09/22 | [
"https://Stackoverflow.com/questions/52459081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10401403/"
] | It was very difficult to understand your code, but as you asked for logic to improve your understanding, so sharing psuedocode, which you could refer to correct your code accordingly.
```
Node delete (index i, Node n) // pass index and head reference node and return head
if (n==null) // if node is null
return... | after struggling i managed to solve the problem, here is the answer, but i am still not sure about the complexity whether it's O(n) or O(log n).
```
public void delete(int index){
//check if the index is valid
if((index<0)||(index>length())){
System.out.println("Array out of bound!");
... | 15,529 |
54,021,168 | I am using flask and python3 to upload a video on server. The result is saved in format(filename)+result.jpg , where filename is the videoname
This image result was visible on browser with url /video\_feed before appending result.jpg with string
How can I now access the url to see result.jpg
```
@app.route('/video_... | 2019/01/03 | [
"https://Stackoverflow.com/questions/54021168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9781290/"
] | Using a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions):
```
return [x for x in xs if f(x) > 0]
```
Without using a list comprehension:
```
return filter(lambda x: f(x) > 0, xs)
```
Since you said it should return a list:
```
return list(filter(lambda x: f(x) > 0,... | Two solutions are possible using recursion, which do not use looping or comprehensions - which implement the iteration protocol internally.
**Method 1:**
```py
lst = list()
def foo(index):
if index < 0 or index >= len(xs):
return
if f(xs[index]) > 0:
lst.append(xs[index])
# print xs[i... | 15,531 |
17,866,724 | I have a long python script that uses print statements often, I was wondering if it was possible to add some code that would log all of the print statements into a text file or something like that. I still want all of the print statements to go to the command line as the user gets prompted throughout the program. If po... | 2013/07/25 | [
"https://Stackoverflow.com/questions/17866724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1464660/"
] | You can add this to your script:
```
import sys
sys.stdout = open('logfile', 'w')
```
This will make the print statements write to `logfile`.
If you want the option of printing to `stdout` and a file, you can try this:
```
class Tee(object):
def __init__(self, *files):
self.files = files
def write(... | Here is a program that does what you describe:
```
#! /usr/bin/python3
class Tee:
def write(self, *args, **kwargs):
self.out1.write(*args, **kwargs)
self.out2.write(*args, **kwargs)
def __init__(self, out1, out2):
self.out1 = out1
self.out2 = out2
import sys
sys.stdout = Tee(o... | 15,532 |
54,246,133 | I am an experienced programmer in ruby, python and javascript (specifically back-end node.js), I have worked in java, perl and c++, and I've used lisp and haskell academically, but I'm brand new to Scala and trying to learn some conventions.
I have a function that accepts a function as a parameter, similar to how a so... | 2019/01/18 | [
"https://Stackoverflow.com/questions/54246133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5158185/"
] | Since Scala has explicit function types, I'd say that if you need to pass a function to your function, use the function type, i.e. your option B. They are explicitly there for this purpose.
It is not exactly clear what do you mean by saying that you "have never seen that before in scala", BTW. A lot of standard librar... | Another option is not to define anything and keep the function type explicit:
```
def apply(x: Int, y: Int => Int): Int = y(x)
```
This makes the code more readable by making it clear which arguments are data objects and which are function objects. (Purists will say that there is no distinction in a functional langu... | 15,541 |
1,644,856 | For testing purposes I have this shell script
```
#!/bin/bash
echo $$
find / >/dev/null 2>&1
```
Running this from an interactive terminal, ctrl+c will terminate bash, and the find command.
```
$ ./test-k.sh
13227
<Ctrl+C>
$ ps -ef |grep find
$
```
Running it in the background, and killing the shell only will orp... | 2009/10/29 | [
"https://Stackoverflow.com/questions/1644856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126769/"
] | Send a signal to the group.
So instead of `kill 13231` do:
```
kill -- -13231
```
If you're starting from python then have a look at:
<http://www.pixelbeat.org/libs/subProcess.py>
which shows how to mimic the shell in starting
and killing a group | @Patrick's answer almost did the trick, but it doesn't work if the *parent* process of your *current* shell is in the same group (it kills the parent too).
I found this to be better:
`trap 'pkill -P $$' EXIT`
See [here](https://unix.stackexchange.com/a/124148) for more info. | 15,542 |
22,415,345 | I have a unicode string in python code:
```
name = u'Mayte_Martín'
```
I would like to use it with a SPARQL query, which meant that I should encode the string using 'utf-8' and use urllib.quote\_plus or requests.quote on it. However, both these quote functions behave strangely as can be seen when used with and witho... | 2014/03/14 | [
"https://Stackoverflow.com/questions/22415345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/464476/"
] | I'm answering my own question, so that it may help others who face the same issue.
This particular issue arises when you make the following import in the current workspace before executing anything else.
```
from __future__ import unicode_literals
```
This has somehow turned out to be incompatible with the followin... | ```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import urllib
name = u'Mayte_Martín'
print urllib.quote_plus(name.encode('utf-8'), safe=':/')
```
works without problem for me (Py 2.7.9, Debian)
(I don't know the answer, but I cannot make comments with regard to reputation) | 15,552 |
6,488,345 | I have tried both terminate() and kill() but both have failed to stop a subprocess I start in my python code.
Is there any other way?
On Windows with Python 2.7
I have also tried the following with no results...
```
os.kill(p.pid, signal.SIGTERM)
```
and
```
import ctypes
PROCESS_TERMINATE = 1
handle = ctypes.wi... | 2011/06/27 | [
"https://Stackoverflow.com/questions/6488345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/775302/"
] | >
> Unhandled exception type FileNotFoundException myclass.java /myproject/src/mypackage
>
>
>
This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exceptio... | This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exception. Like so:
```
public static void main(String[] args) throws IOException{
}
``` | 15,555 |
16,696,225 | How to instantiated a class if its name is given as a string variable (i.e. dynamically instantiate object of the class). Or alternatively, how does the following PHP 5.3+ code
```
<?php
namespace Foo;
class Bar {};
$classname = 'Foo\Bar';
$bar = new $classname();
```
can be spelled in python?
**Also see**
[Doe... | 2013/05/22 | [
"https://Stackoverflow.com/questions/16696225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/544463/"
] | What I would do is move the call to `get_int` into the condition of the while loop:
```
int main(void)
{
int integers;
printf("Enter some integers. Enter 0 to end.\n");
while ((integers = get_int()) != 0)
{
printf("%d is a number\n", integers);
}
return(0);
} // end main
```
The pro... | You are correct to suspect that you need to retool the `while` loop. Did you try something like this?
```
for (;;)
{
integers = get_int();
if (integers == 0) break;
printf("%d is a number\n", integers);
}
```
Also, your `get_int` would be better written with `fgets` (or `getline` if available) and ... | 15,565 |
39,734,278 | Is it possible to receive google drive push notifications if coded on aws lambda via api gateway?
Google drive requires the webhook address to be verified so is it possible to verify api gateway endpoint?
Here are the possible ways of verifying the endpoint:
1) Upload a file and test via /file and the rest are bel... | 2016/09/27 | [
"https://Stackoverflow.com/questions/39734278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2005490/"
] | @Atihska, it seems you have setup this API:
```
https://x8f3******.execute-api.us-east-1.amazonaws.com/prod/google-endpointverification
```
From what I understand, Google Drive's HTML tag verification method will try to verify the metadata in the **home page**. As per Google, the home page here is:
```
https://x8f3... | I don't know for sure how the registration process works for verifying the webhook address, but it is certainly possible to configure the webhook itself in API Gateway.
API Gateway supports [custom domain names](http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html "custom domain name... | 15,570 |
17,050,377 | I'm following the tutorial "Think Python" and I'm supposed to install the package called swampy. I'm running python 2.7.3 although I also have python 3 installed. I extracted the package and placed it in site-packages:
C:\Python27\Lib\site-packages\swampy-2.1.1
C:\Python31\Lib\site-packages\swampy-2.1.1
But wh... | 2013/06/11 | [
"https://Stackoverflow.com/questions/17050377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2475605/"
] | >
> I extracted the package and placed it in site-packages:
>
>
>
No, that's the wrong way of "installing" a package. Python packages come with a `setup.py` script that should be used to install them. Simply do:
```
python setup.py install
```
And the module will be installed correctly in the site-packages of t... | If anyone else is having trouble with this on Windows, I just added my sites-package directory to my PATH variable and it worked like any normal module import.
```
C:\Python34\Lib\site-packages
```
Hope it helps. | 15,579 |
70,393,570 | I am trying to solve the question in which I am asked to use property method to count the number of times the circles are created . Below is the code for the same.
```
import os
import sys
#Add Circle class implementation below
class Circle:
counter = 0
def __init__(self,radius):
self.radius = radius
... | 2021/12/17 | [
"https://Stackoverflow.com/questions/70393570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10254216/"
] | A small calculation may help:
```
...
WHERE
([user_id] = 1) AND
([year] * 100 + [week_number]) BETWEEN 202152 AND 202205
```
or
```
...
WHERE
([user_id] = 1) AND
(202152 <= [year] * 100 + [week_number]) AND
([year] * 100 + [week_number] <= 202205)
``` | You could...use variables:
```
DECLARE @myUser int = 1,
@startYear int = 2021,
@endYear int = 2022,
@startWeek int = 5,
@endWeek INT = 13;
SELECT *
FROM [db].[dbo].[table]
WHERE [user_id] = @myUser
AND (
(@startYear = [year] AND @startWeek = [week_number] AND @sta... | 15,580 |
46,032,570 | I have a Django REST backend, and it has a `/users` endpoint where I can add new users through `POST` method from frontend.
`/users` endpoint url:
`http://192.168.201.211:8024/users/`
In this endpoint I can view all users information and add new user, so I must avoid others entry it except Administrator. I create a ... | 2017/09/04 | [
"https://Stackoverflow.com/questions/46032570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2803344/"
] | From the docs:
You have to download and install the ARCore Services.
>
> You must use a supported, physical device. ARCore does not support virtual devices such as the Android Emulator. To prepare your device:
>
>
> Enable developer options
>
> Enable USB debugging
>
> Download the [ARCore Service](https:/... | I think you need to Install Tango core.
<https://play.google.com/store/apps/details?id=com.google.tango&hl=zh_TW> | 15,581 |
9,319,767 | I have a color photo of apple, how can I show only its outline (inside white, background black) with python/PIL? | 2012/02/16 | [
"https://Stackoverflow.com/questions/9319767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212200/"
] | Something like this should work.
```
from PIL import Image, ImageFilter
image = Image.open('your_image.png')
image = image.filter(ImageFilter.FIND_EDGES)
image.save('new_name.png')
```
If that doesn't give you the result you are looking for then you try implementing either Prewitt edge detection, Sobel edge detect... | If your object and background have fairly well contrast
```
from PIL import Image
image = Image.open(your_image_file)
mask=image.convert("L")
th=150 # the value has to be adjusted for an image of interest
mask = mask.point(lambda i: i < th and 255)
mask.save(file_where_to_save_result)
```
if higher contrast is in o... | 15,582 |
51,434,996 | I have the following code:
```
#!/usr/bin/python2.7
import json, re, sys
x = json.loads('''{"status":{"code":"200","msg":"ok","stackTrace":null},"dbTimeCost":11,"totalTimeCost":12,"hasmore":false,"count":5,"result":[{"_type":"Compute","_oid":"555e262fe4b059c7fbd6af72","label":"lvs3b01c-ea7c.stratus.lvs.ebay.com"},{"_t... | 2018/07/20 | [
"https://Stackoverflow.com/questions/51434996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7005590/"
] | just change your code which is used to print the label
```
print x['result'][4]['label'] # here you are just printing the 4th label only
```
to
```
print [i["label"] for i in x['result']]
``` | Using a list comprehension to get all label
**Ex:**
```
import json, re, sys
x = json.loads('''{"status":{"code":"200","msg":"ok","stackTrace":null},"dbTimeCost":11,"totalTimeCost":12,"hasmore":false,"count":5,"result":[{"_type":"Compute","_oid":"555e262fe4b059c7fbd6af72","label":"lvs3b01c-ea7c.stratus.lvs.ebay.com"}... | 15,585 |
47,422,284 | How can I elegantly do it in `go`?
In python I could use attribute like this:
```
def function():
function.counter += 1
function.counter = 0
```
Does `go` have the same opportunity? | 2017/11/21 | [
"https://Stackoverflow.com/questions/47422284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5537840/"
] | For example,
`count.go`:
```
package main
import (
"fmt"
"sync"
"time"
)
type Count struct {
mx *sync.Mutex
count int64
}
func NewCount() *Count {
return &Count{mx: new(sync.Mutex), count: 0}
}
func (c *Count) Incr() {
c.mx.Lock()
c.count++
c.mx.Unlock()
}
func (c *Count) C... | ```
var doThingCounter = 0
func DoThing() {
// Do the thing...
doThingCounter++
}
``` | 15,587 |
65,398,433 | **Problem description:** I want to create a program that can update one whole row (or cells in this row within given range) in one single line (i.e. one single API request).
This is what've seen in the **documentation**, that was related to my problem:
```py
# Updates A2 and A3 with values 42 and 43
# Note that updat... | 2020/12/21 | [
"https://Stackoverflow.com/questions/65398433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13682294/"
] | The error indicates that the data you are trying to write has more rows than the rows in the range. Each list inside your list represent single row of data in the spreadsheet.
In your example:
```
[['068222bb-c251-47ad-8c2a-e7ad7bad2f60'], ['urlLink'], ['100'], ['250'], ['20'], [''], [' ,'], ['0']]
```
It represent... | Hi you may try the following:
```
def gs_writer(sheet_name,dataframe,sheet_url,boolean,row,col):
import gspread
from gspread_dataframe import get_as_dataframe, set_with_dataframe
import google.oauth2
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.... | 15,589 |
42,214,228 | In numpy and tensorflow it's possible to add matrices (or tensors) of different dimensionality if the shape of smaller matrix is a suffix of bigger matrix. This is an example:
```
x = np.ndarray(shape=(10, 7, 5), dtype = float)
y = np.ndarray(shape=(7, 5), dtype = float)
```
For these two matrices operation `x+y` is... | 2017/02/13 | [
"https://Stackoverflow.com/questions/42214228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/766551/"
] | In NumPy, you could extend `y` to `3D` and then add -
```
x + y[:,None,:]
```
Haven't dealt with `tensorflow` really, but looking into its docs, it seems, we could use [`tf.expand_dims`](https://www.tensorflow.org/api_docs/python/array_ops/shapes_and_shaping#expand_dims) -
```
x + tf.expand_dims(y, 1)
```
The ext... | As correctly pointed out in the accepted answer the solution is to expand dimensions using available construct.
The point is to understand how numpy is doing the broadcasting of matrices in case of adding matrices if their dimensions don't match. The rule is that two matrices must have exactly the same dimensions with... | 15,590 |
16,918,063 | We're running into a problem (which is described <http://wiki.python.org/moin/UnicodeDecodeError>) -- read the second paragraph '...Paradoxically...'.
Specifically, we're trying to up-convert a string to unicode and we are receiving a UnicodeDecodeError.
Example:
```
>>> unicode('\xab')
Traceback (most recent... | 2013/06/04 | [
"https://Stackoverflow.com/questions/16918063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/590028/"
] | I think you're confusing Unicode strings and Unicode encodings (like UTF-8).
`os.walk(".")` returns the filenames (and directory names etc.) as strings that are *encoded* in the current codepage. It will silently *remove* characters that are not present in your current codepage ([see this question for a striking examp... | ```
'\xab'
```
Is a **byte**, number 171.
```
u'\xab'
```
Is a **character**, U+00AB Left-pointing double angle quotation mark («).
`u'\xab'` is a short-hand way of saying `u'\u00ab'`. It's not the same (not even the same datatype) as the byte `'\xab'`; it would probably have been clearer to always use the `\u` s... | 15,591 |
17,627,193 | I'm on a fresh Virtualbox install of CentOS 6.4.
After installing zsh 5.0.2 from source using `./configure --prefix=/usr && make && make install` and setting it as the shell with `chsh -s /usr/bin/zsh`, everything is good.
Then some time after, after installing python it seems, it starts acting strange.
1. Happens ... | 2013/07/13 | [
"https://Stackoverflow.com/questions/17627193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340947/"
] | OK , I suggest you try
export TERM=xterm
in your .zshrc configuration
the Changing into Zsh caused the bug. | **sigh** I knew I solved this before.
It's too damn easy to forget things.
The solution is to compile and apply the proper terminfo data with `tic`, as I have a custom config with my terminal clients, `xterm-256color-italic`, that confuses zsh.
There appear to be other ways to configure this stuff too; I basically... | 15,595 |
58,777,374 | I was recently studying someone's code and a portion of code given below
```
class Node:
def __init__(self, height=0, elem=None):
self.elem = elem
self.next = [None] * height
```
What does it mean by `[None] * height` in the above code
I know what does `*` operator (as multiplication and unpacking) and `Non... | 2019/11/09 | [
"https://Stackoverflow.com/questions/58777374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8401374/"
] | It means a list of `None`s with a `height` number of elements. e.g., for `height = 3`, it is this list:
```
[None, None, None]
``` | ```
>>> [None] * 5
[None, None, None, None, None]
```
Gives you a list of size `height` in your case | 15,598 |
55,233,846 | I'm trying to send HTTP post rest API call to the flask server. I'm able to do it in postman but How can I call it using python requests module?
payloads are key-project value-daynight and key-file value-
postman request is as shown in the image
[postman](https://i.stack.imgur.com/i8ZMT.png)
when I tried I ended up g... | 2019/03/19 | [
"https://Stackoverflow.com/questions/55233846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10865641/"
] | Just recently ran into this. One thing to look out for is to ensure nodeIntegration is set to true when creating your renderer windows.
```
mainWindow = new electron.BrowserWindow({
width: width,
height: height,
webPreferences: {
nodeIntegration: true
}
});
``` | AFAIU the recommended way is to use `contextBridge` module (in the `preload.js` script). It allows you to keep the context isolation enabled but safely expose your APIs to the context the website is running in.
<https://www.electronjs.org/docs/latest/tutorial/context-isolation>
Following this way, I also found that i... | 15,600 |
1,054,380 | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, an... | 2009/06/28 | [
"https://Stackoverflow.com/questions/1054380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/90025/"
] | Unless you are planning on writing the interfaces yourself, you are going to require some library, since as other posters have pointed out, you need to access low-level key press events managed by the desktop environment.
On Windows, the [PyHook](http://pypi.python.org/pypi/pyHook/1.4/) library would give you the func... | Depending on what statistics you want to collect, maybe you do not have to write this yourself; the program [Workrave](http://www.workrave.org/) is a program to remind you to take small breaks and does so by monitoring keyboard and mouse activity. It keeps statistics of this activity which you probably could use (unles... | 15,602 |
14,001,578 | What's the correct way to specify a hg dependency in `tox.ini`. e.g.
```
[testenv]
deps =
hg+https://code.google.com/p/python-progressbar/
```
Unfortunately this does not work, and the following is spewed out:
```
ERROR: invocation failed, logfile: /Users/brad/project/.tox/py33-dj/log/py33-dj-1.log
ERROR: actio... | 2012/12/22 | [
"https://Stackoverflow.com/questions/14001578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/253686/"
] | It's possible to specify the mercurial dependency in two ways within `deps = …`:
* `-ehg+https://code.google.com/p/python-progressbar/#egg=progressbar` (no space)
* `hg+https://code.google.com/p/python-progressbar/`
tox treats each line in `deps` as a single argument to `pip install` (whitespace included).
pip supp... | typically this is a artifact of a broken mercurial installation that refers to env python
in virtualenv for python 3 the env python is simply the worst thing to work with | 15,607 |
50,617,233 | I have a dataset (Product\_ID,date\_time, Sold) which has products sold on various dates. The dates are not consistent and are given for 9 months with random 13 days or more from a month. I have to segregate the data in a such a way that the for each product how many products were sold on 1-3 given days, 4-7 given days... | 2018/05/31 | [
"https://Stackoverflow.com/questions/50617233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9846590/"
] | You can first convert dates to dtetimes and get days by [`dt.day`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.day.html):
```
df['DATE_LOCATION'] = pd.to_datetime(df['DATE_LOCATION'], dayfirst=True)
days = df['DATE_LOCATION'].dt.day
```
Then binning by [`cut`](http://pandas.pydata.org/pand... | Assume your dataframe named df.
```
df["DATE_LOCATION"] = pd.to_datetime(df.DATE_LOCATION)
df["DAY"] = df.DATE_LOCATION.dt.day
def flag(x):
if 1<=x<=3:
return '1-3'
elif 4<=x<=7:
return '4-7'
elif 8<=x<=15:
return '8-15'
else:
return '>16' # maybe you mean '>=16'.
df["... | 15,608 |
1,062,562 | I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing t... | 2009/06/30 | [
"https://Stackoverflow.com/questions/1062562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80480/"
] | Use a thread ([longer example here](http://www.wellho.net/solutions/python-python-threads-a-first-example.html)):
```
from threading import Thread
class WindowThread(Thread):
def run(self):
callCppFunctionHere()
WindowThread().start()
``` | QApplication::exec() starts the main loop of the application and will only return after the application quits. If you want to run code after the application has been started, you should resort to Qt's event handling mechanism.
From <http://doc.trolltech.com/4.5/qapplication.html#exec> :
>
> To make your application ... | 15,609 |
32,867,501 | I have a python program that takes a .txt file with a list of information. Then the program proceeds to number every line, then remove all returns. Now I want to add returns to the lines that are numbered without double spacing so I can continue to edit the file. Here is my program.
```
import sys
from time import sle... | 2015/09/30 | [
"https://Stackoverflow.com/questions/32867501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5391570/"
] | You can inject the `$location` service if you are using html5 mode.
Because you are using URLs without a base root (such as a ! or a #), you need to explicitly add a `<base>` tag that defines the "root" of your application OR you can configure `$locationProvider` to not require a base tag.
HTML:
```
<head>
<base h... | You can use `$location.search()`.
```
var parameters = $location.search();
console.log(parameters);
-> object{
foo: foovalue,
bar: barvalue
}
```
SO these values will be accessible with `parameters.foo` and `parameters.bar` | 15,612 |
18,823,139 | I am new to selenium, I have a script that uploads a file to a server.
In the ide version sort of speak it uploads the file, but when I export test case as python 2 /unittest / webdriver it doesn't upload it..
It doesn't give me any errors, just doesn't upload it...
The python script is:
```
driver.find_element_by_... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18823139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782827/"
] | Your code work perfectly for me (I test it with Firefox, Chrome driver)
One thing I supect is excessive backslash(`\`) escape.
Try following:
```
driver.find_element_by_id("start-upload-button-single").click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('inpu... | If I run the following lines from the IDE it works just fine, it uploads the file.
```
Command | Target | Value
_____________________________________________________________
open | /upload |
click | id=start-upload-button-single |
type | css=inp... | 15,613 |
16,504,990 | How is it possible I am getting a permission denied using the below? I am using python 2.7 and ubuntu 12.04
Below is my mapper.py file
```
import sys
import json
for line in sys.stdin:
line = json.loads(line)
key = "%s:%s" % (line['user_key'],line['item_key'])
value = 1
sys.stdout.write('%s\t%s\n' % ... | 2013/05/12 | [
"https://Stackoverflow.com/questions/16504990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203556/"
] | Your `mapper.py` file needs to be executable (on some executable partition) so `chmod a+x mapper.py`
The underlying [execve(2)](http://man7.org/linux/man-pages/man2/execve.2.html) syscall is failing with
```
EACCES Execute permission is denied for the file or a script or ELF
interpreter.
EACCES The ... | you can add 'python' to the command, like so
```
cat /home/ubuntu/workspace/logging/data.txt | python /home/ubuntu/workspace/logging/mapper.py
``` | 15,622 |
65,647,986 | I am trying to interface a micropython board with python on my computer using serial read and write, however I can't find a way to read usb serial data in micropython that is non-blocking.
Basicly I want to call the input function without requiring an input to move on. (something like <https://github.com/adafruit/circ... | 2021/01/09 | [
"https://Stackoverflow.com/questions/65647986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13016068/"
] | Instead of typing xlsx, type xlsx like this:
```
import xlsxwriter
import pandas as pd
from pandas import DataFrame
path = ('mypath.xlsx')
xl = pd.ExcelFile(path)
print(xl.sheet_names)
```
It'll work. | The module name is xlsxwriter not xlxswriter, so replace that line with:
```
import xlsxwriter
``` | 15,623 |
26,856,793 | I am trying to load as a pandas dataframe a file that has Chinese characters in its name.
I've tried:
```
df=pd.read_excel("url/某物2008.xls")
```
and
```
import sys
df=pd.read_excel("url/某物2008.xls", encoding=sys.getfilesystemencoding())
```
But the response is something like: "no such file or directory "url/\xa1... | 2014/11/11 | [
"https://Stackoverflow.com/questions/26856793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2827060/"
] | ```
df=pd.read_excel(u"url/某物2008.xls", encoding=sys.getfilesystemencoding())
```
may work... but you may have to declare an encoding type at the top of the file | try this for unicode conversion:
`df=pd.read_excel(u"url/某物2008.xls", encoding='utf-8')` | 15,624 |
11,204,053 | I have two classes for example:
```
class Parent(object):
def hello(self):
print 'Hello world'
def goodbye(self):
print 'Goodbye world'
class Child(Parent):
pass
```
class Child must inherit only hello() method from Parent and and there should be no mention of goodbye().
Is it possible... | 2012/06/26 | [
"https://Stackoverflow.com/questions/11204053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438882/"
] | ```
class Child(Parent):
def __getattribute__(self, attr):
if attr == 'goodbye':
raise AttributeError()
return super(Child, self).__getattribute__(attr)
``` | This Python example shows how to design classes to achieve child class inheritance:
```
class HelloParent(object):
def hello(self):
print 'Hello world'
class Parent(HelloParent):
def goodbye(self):
print 'Goodbye world'
class Child(HelloParent):
pass
``` | 15,625 |
67,350,490 | I am trying to make a simple flask app using putty but it is not working
here is my hello.py file:
```
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World'
```
command I am running in putty (when in the file directory of hello.py)
pip install flask
python -c "impo... | 2021/05/01 | [
"https://Stackoverflow.com/questions/67350490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12333529/"
] | I used my terminal on my window machine instead of putty which is a remote machine | Check your wlan0 inet adress by typing ifconfig in bash and use it, also try to add the following code in your flask app:
```
if __name__ == '__main__':
app.run(debug=True, port=5000, host='wlan0 IP Add')
```
Run the application by typing >>sudo python3 hello.py
Did this work? | 15,628 |
8,408,970 | >
> **Possible Duplicate:**
>
> [Not getting exact result in python with the values leading zero. Please tell me what is going on there](https://stackoverflow.com/questions/3067409/not-getting-exact-result-in-python-with-the-values-leading-zero-please-tell-me)
>
>
>
I want to create dictionary which value begi... | 2011/12/07 | [
"https://Stackoverflow.com/questions/8408970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/613985/"
] | The leading zero is telling Python to interpret it as an octal number. | When you write 0123456, it gets interpreted as base-8, which is 42798 decimal | 15,629 |
41,782,396 | I am trying to deploy a [sample app](https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/flexible/django_cloudsql) to the Google App Engine Flexible Environment based on [this](https://cloud.google.com/python/django/flexible-environment) tutorial. The deployment works, however, the applicat... | 2017/01/21 | [
"https://Stackoverflow.com/questions/41782396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373359/"
] | `setf` returns the original flag value, so you can simply store that then put it back when you're done.
The same is true of `precision`.
So:
```
// Change flags & precision (storing original values)
const auto original_flags = std::cout.setf(std::ios::fixed | std::ios::showpoint);
const auto original_precision =... | You can use flags() method to save and restore all flags or unsetf() the one returned by setf
```
std::ios::fmtflags oldFlags( cout.flags() );
cout.setf(std::ios::fixed);
cout.setf(std::ios::showpoint);
std::streamsize oldPrecision(cout.precision(2));
// output whatever you should.
cout.flags( oldFlags );
co... | 15,635 |
68,403,642 | I need to share well described data and want to do this in a modern way that avoids managing bureaucratic documentation no one will read. Fields require some description or note (eg. "values don't include ABC because XYZ") which I'd like to associate to columns that'll be saved with `pd.to_<whatever>()`, but I don't kn... | 2021/07/16 | [
"https://Stackoverflow.com/questions/68403642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4107349/"
] | Would the following rough sketch be something you could live with:
**Step 1**: Create json structure out of `df` like you did
```
df.to_json('temp.json', orient='table', indent=4, index=False)
```
**Step 2**: Add the column description to the so produced json-file as you already did (could be done easily in a struc... | I didn't see that there will be such an option but I think you can just add a description inside of each variable:
```
schema = {'first':{'Variable':'x',"description": "example string","value": 2},"second":{"Variable":"y","description": "example string","value": 3}}
```
It creates a table:
```
... | 15,638 |
53,340,120 | I would like to install the package : newsapi in Python
I run the command
```
pip3 install newsapi-python
```
The package was succefully installed. But I import him in Anaconda :
```
from newsapi import NewsApiClient
>> ModuleNotFoundError: No module named 'newsapi'
```
I would like to know how to solve this ki... | 2018/11/16 | [
"https://Stackoverflow.com/questions/53340120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10651723/"
] | I think the issue is you aren't importing vue-router into your app. Only into router.js and then you don't import all of router.js into your app, only the createRouter function. Try this:
```
//routes.js
import Home from "../components/Home/Home.vue";
import About from "../components/About.vue";
import FallBackPage f... | To change route
```
this.$router.push({ path: '/' })
this.$router.push({ name: 'Home' })
```
//main.js
```
import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import { routes } from "./router/router";
Vue.use(VueRouter);
export function createApp() {
const router = new VueRo... | 15,639 |
51,605,651 | I'm looking to find the max run of consecutive zeros in a DataFrame with the result grouped by user. I'm interested in running the RLE on usage.
### sample input:
user--day--usage
A-----1------0
A-----2------0
A-----3------1
B-----1------0
B-----2------1
B-----3------0
### Desired output
user--... | 2018/07/31 | [
"https://Stackoverflow.com/questions/51605651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10158469/"
] | Use [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) with [`size`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html) by columns `user`, `usage` and helper `Series` for consecutive values first:
```
print (df)
user day usage
... | I think the following does what you are looking for, where the `consecutive_zero` function is an adaptation of the top answer [here](https://codereview.stackexchange.com/questions/138550/count-consecutive-ones-in-a-binary-list).
Hope this helps!
```
import pandas as pd
from itertools import groupby
df = pd.DataFrame... | 15,640 |
69,339,582 | I would like to compute the **hash of the contents (sequence of *bits*)** of a file (whose length could be any number of bits, and so not necessarily a multiple of the *trendy* eight) and send that file to a friend along with the hash-value. My friend should be able to compute the same hash from the file contents. I wa... | 2021/09/26 | [
"https://Stackoverflow.com/questions/69339582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8341274/"
] | First of all, the `hash()` function in Python is not the same as **cryptographic hash functions** in general. Here're the differences:
### `hash()`
>
> A hash is an fixed sized integer that identifies a particular value. Each value needs to have its own hash, so for the same value you will get the same hash even if ... | I arrived at `sha256hexdigestFromFile`, an alternative to @Lincoln Yan 's `calculateSHA256Hash`, after reviewing the [standard](http://dx.doi.org/10.6028/NIST.FIPS.180-4) for SHA-256.
This is also a response to my comment about `2048`.
```
def sha256hexdigestFromFile(filePath, blocks = 1):
'''Return as a str the ... | 15,643 |
51,797,321 | I am beginning to program in python. I want to delete elements from array based on the list of index values that I have. Here is my code
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
del_list = [0, 4, 11]
desired output = [45, 55, 6, 37, 656, 78, 8, 99, 9]
```
Here is what I have done
```
x = [12, 45, 55,... | 2018/08/11 | [
"https://Stackoverflow.com/questions/51797321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10211342/"
] | This question already has an answer here. [How to delete elements from a list using a list of indexes?](https://stackoverflow.com/questions/38647439/how-to-delete-elements-from-a-list-using-a-list-of-indexes).
BTW this will do for you
```
x = [12, 45, 55, 6, 34, 37, 656, 78, 8, 99, 9, 4]
index_list = [0, 4, 11]
val... | You can sort the `del_list` list in descending order and then use the `list.pop()` method to delete specified indexes:
```
for i in sorted(del_list, reverse=True):
x.pop(i)
```
so that `x` would become:
```
[45, 55, 6, 37, 656, 78, 8, 99, 9]
``` | 15,644 |
53,501,778 | I have installed `mysql connector` , which already has a built in sql adapter, i also don't need to install `mysqlclient` as i have mysql connector. But when i start python manage.py migrate, it is asking me to download mysqlclient. But i can not install `mysqlclient`. Can anyone help me how to fix the problem. Thanks
... | 2018/11/27 | [
"https://Stackoverflow.com/questions/53501778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Maybe you need to install mysql-connector-c connector and after:
```
pip install mysqlclient==1.3.13
``` | [There are two backends](https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-db-api-drivers) for using MySQL with python
* mysqlclient - recommended by the docs, but can be tricky to install on Windows
* mysql connector - doesn't always support the latest Django version.
First you need to decide which backend ... | 15,646 |
13,578,923 | Can anybody figure out how the python code below works and give me a possible way to port it to Objective-C (iOS) to work in my own project?
`month_id = calendar.timegm(datetime(year, month, 1, hour, 0, 0).timetuple()) * 1000`
Thanks a ton! | 2012/11/27 | [
"https://Stackoverflow.com/questions/13578923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/981575/"
] | calendar.timegm converts the given time to time in seconds since epoch of 1970. More information at <http://docs.python.org/3/library/calendar.html?highlight=calendar.timegm#calendar.timegm> | open a python interpreter, then enter this:
```
>>> import calendar
>>> from datetime import datetime
```
then input your line of code, and you should be able to get a pretty good idea. | 15,647 |
40,514,205 | I am developing a slack bot with plugins using entry points. I want to dynamically add a plugin during runtime.
I have a project with this structure:
```
+ ~/my_project_dir/
+ my_projects_python_code/
+ plugins/
- plugin1.py
- plugin2.py
- ...
- pluginN.py
- setup.py
- ... | 2016/11/09 | [
"https://Stackoverflow.com/questions/40514205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1496918/"
] | I needed to do something similar to load a dummy plugin for test purposes. This differs slightly from your use-case in that I was specifically trying to avoid needing to define the entry points in the package (as it is just test code).
I found I could dynamically insert entries into the pkg\_resources data structures ... | It's more than at least 5 years, since the time when I first asked myself almost the same question, and your question now is an impulse to finally find it out.
For me it was as well interesting, if one can add entry points from the same directory as the script without installation of a package. Though I always knew th... | 15,648 |
51,004,898 | I'm trying to programmatically retrieve ASIN numbers for over 500+ books.
example: Product Catch-22 by Joseph Heller
Amazon URL: [https://www.amazon.com/Catch-22-Joseph-Heller/dp/3866155239](https://rads.stackoverflow.com/amzn/click/com/3866155239)
I can get the product numbers manually by searching for each product ... | 2018/06/23 | [
"https://Stackoverflow.com/questions/51004898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9751133/"
] | <https://isbndb.com/> charges for the API :(
so...
Went the Google Web Scrape Route
```
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as soup
import requests
import time
def get_amazon_link(book_title):
url = 'https://www.google.com/search?q=amazon+novel+'+book_title
print(url)
ur... | According to Amazon's customer service page:
<https://www.amazon.co.uk/gp/help/customer/display.html?nodeId=898182>
>
> ASIN stands for Amazon Standard Identification Number. Almost every
> product on our site has its own ASIN, a unique code we use to identify
> it. For books, the ASIN is the same as the ISBN numb... | 15,650 |
17,260,003 | This question is in python:
```
battleships = [['0','p','0','s'],
['0','p','0','s'],
['p','p','0','s'],
['0','0','0','0']]
def fun(a,b,bships):
c = len(bships)
return bships[c-b][a-1]
print(fun(1,1,battleships))
print(fun(1,2,battleships))
```
first print gives... | 2013/06/23 | [
"https://Stackoverflow.com/questions/17260003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2266115/"
] | Indexing starts at `0`. So battleships contains items at indexes `0`, `1`, `2`, `3`.
First `len(bships)` gets the length of the list of lists `battleships`, which is 4.
`bships[c-b][a-1]` accesses items in a list through their index value. So with your first call to the function:
```
print(fun(1,1,battleships))
```... | You can work it out easily by replacing the calculations with the actual values:
In the first call, you are indexing:
```
bships[c-b][a-1] == bships[4-1][1-1] == bships[3][0]
```
Counting from 0, that's the last row, `['0','0','0','0']`, first element, `'0'`.
The second call evaluates to:
```
bships[c-b][a-1] == ... | 15,651 |
56,434,745 | I'm trying to load MySQL JDBC driver from a python app. I'm not invoking 'bin/pyspark' or 'spark-submit' program; instead I have a Python script in which I'm initializing 'SparkContext' and 'SparkSession' objects.
I understand that we can pass '--jars' option when invoking 'pyspark', but how do I load and specify jdbc ... | 2019/06/03 | [
"https://Stackoverflow.com/questions/56434745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1208108/"
] | I think you want do something like this
```py
from pyspark.sql import SparkSession
# Creates spark session with JDBC JAR
spark = SparkSession.builder \
.appName('stack_overflow') \
.config('spark.jars', '/path/to/mysql/jdbc/connector') \
.getOrCreate()
# Creates your DataFrame with spark session with JDB... | Answer is to create SparkContext like this:
```py
spark_conf = SparkConf().set("spark.jars", "/my/path/mysql_jdbc_driver.jar")
sc = SparkContext(conf=spark_conf)
```
This will load mysql driver into classpath. | 15,656 |
5,835,043 | I'm trying to use the ipy.vim script to set up a small python dev environment, but I'm running into a connection problem. When I type ipy\_vimserver.setup("demo") I get this error:
```
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_in... | 2011/04/29 | [
"https://Stackoverflow.com/questions/5835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/731470/"
] | I found it ! Thank you Anders
```
function UnixToDateTime(USec: Longint): TDateTime;
const
// Sets UnixStartDate to TDateTime of 01/01/1970
UnixStartDate: TDateTime = 25569.0;
begin
Result := (USec / 86400) + UnixStartDate;
end;
``` | That is the [unix timestamp](http://en.wikipedia.org/wiki/Unix_time) for Fri, 29 Apr 2011 11:42:31 GMT.
**Edit**
According to [IBS](http://ibs.sourceforge.net/documentation.html#introduction), it uses postgresql as its backend database. You should be able to convert it using [to\_timestamp](http://www.postgresql.org/... | 15,657 |
39,190,714 | Sorry if this has already been answered using terminology I don't know to search for.
I have one project:
```
project1/
class1.py
class2.py
```
Where `class2` imports some things from `class1`, but each has its own `if __name__ == '__main__'` that uses their respective classes I run frequently. But then, I ... | 2016/08/28 | [
"https://Stackoverflow.com/questions/39190714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191812/"
] | EDIT 2: Added code to class2.py to attach the parent directory to the PYTHONPATH to comply with how Python3 module imports work.
```
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
```
Removed relative import of Class1.
Folder structure:
```
project2
- class3.py
- project1
... | You could run `class2.py` from inside the `project2` folder, i.e. with the current working directory set to the `project2` folder:
```
user@host:.../project2$ python project1/class2.py
```
On windows that would look like this:
```
C:\...project2> python project1/class2.py
```
Alternatively you could modify the py... | 15,658 |
63,994,247 | I'm new to Docker. I'm trying to create a dockerfile which basically sets kubectl (Kubernetes client), helm 3 and Python 3.7. I used:
```
FROM python:3.7-alpine
COPY ./ /usr/src/app/
WORKDIR /usr/src/app
```
Now I'm trying to figure out how to add `kubectl` and `helm`. What would be the best way to install those two... | 2020/09/21 | [
"https://Stackoverflow.com/questions/63994247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9808098/"
] | Working Dockerfile. This will install the latest and stable versions of `kubectl` and `helm-3`
```
FROM python:3.7-alpine
COPY ./ /usr/src/app/
WORKDIR /usr/src/app
RUN apk add curl openssl bash --no-cache
RUN curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/... | Python should be available from a python base image I guess.
My take would be s.th like
```
ENV K8S_VERSION=v1.18.X
ENV HELM_VERSION=v3.X.Y
ENV HELM_FILENAME=helm-${HELM_VERSION}-linux-amd64.tar.gz
```
and then in the Dockerfile
```
RUN curl -L https://storage.googleapis.com/kubernetes-release/release/${K8S_VERSION... | 15,659 |
61,856,478 | I'm developing a python script to deploy an Azure Function App. For this reason I can't use another Python version to make this easier.
In azure portal I get this error:
[Azure Function app pyarrow module not found](https://i.stack.imgur.com/QM50w.png)
When I try to install it via VS Code with pip I get this error: [... | 2020/05/17 | [
"https://Stackoverflow.com/questions/61856478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13562280/"
] | As you use `conda` as the package manager, you should also use it to install `pyarrow` and `arrow-cpp` using it. In your above output VSCode uses `pip` for the package management. You should consider reporting this as a bug to VSCode. Your current environment is detected as `venv` and not as `conda` environment as you ... | Thank you for your answer.
In fact, I think I can't change the environment because this `venv` is actually the environment used by Azure Functions. Is there any way I can use `conda` installed packages in the azure function | 15,660 |
36,465,337 | I am using a Dymo USB scale with PyUSB and everything is really great apart from the scale's automatic shutdown after three minutes. I would like to keep it running as long as my python program is running. Is there any way to do this using python?
I am new to PyUSB and have followed this tutorial successfully so far: ... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36465337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4083055/"
] | As Ignacio said, there doesn't seem to be any computing way to do this. We eventually managed to stop the automatic shutdown by wiring a timer directly to the button which changes the units mode from grams to ounces. "Pressing" this every few seconds prevents the shutdown, and a little bit of extra coding allows for re... | Here is a hardware description to open/modify and code to toggle the scale button of DYMO (to avoid auto-shutdown)
<https://learn.adafruit.com/data-logging-iot-weight-scale/code-walkthrough> | 15,661 |
16,114,358 | is there a way to trace all the calls made by a web page when loading it? Say for example I went in a video watching site, I would like to trace all the GET calls recursively until I find an mp4/flv file. I know a way to do that would be to follow the URLs recursively, but this solution is not always suitable and quite... | 2013/04/19 | [
"https://Stackoverflow.com/questions/16114358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2300843/"
] | The following code may be what you are looking for. The object should flash for the total amount of `time` changing its color after `intervalTime`
```
using UnityEngine;
using System.Collections;
public class FlashingObject : MonoBehaviour {
private Material mat;
private Color[] colors = {Color.yellow, Color... | The answer above is great, but it does not stop flashing, because it takes far too long for the float to reach 5f.
The trick is to set the first parameter in the **Flash** function to something smaller, like 1f, instead of 5f. Take this script, and attach it to any game object. It will flash between yellow and red for... | 15,662 |
64,354,599 | What is the best way to create software client (service) that installs and then runs in the background. When you turn on the device (where the service is installed), this service will automatically send network availability information of device to web server. On web server will be only state of devices on network. (on... | 2020/10/14 | [
"https://Stackoverflow.com/questions/64354599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14449220/"
] | Use
```
(?m)^<hr>\r?\nBitmap:[\s\S]*?(?=^<hr>$|\Z)
```
See [proof](https://regex101.com/r/i64K0W/4).
**Explanation**
```
--------------------------------------------------------------------------------
(?m) set flags for this block (with ^ and $
matching start and e... | This works: `<hr>\nBitmap:.*\n(?:.*\n){1,2}`
See: <https://regex101.com/r/i64K0W/3>
The problem in your regex was the `*`, which is greedy. | 15,663 |
60,907,340 | Try to open file that exists with visual Studio Code 1.43.2
This is the py file:
```
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
```
This is the result:
```
PS C:\Users\Osori> & C:/Python/Python38-32/python.exe "c:/Users/Osori/Desktop/python_work/9_files and excepti... | 2020/03/28 | [
"https://Stackoverflow.com/questions/60907340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13143836/"
] | Below is for BigQuery Standard SQL
```
#standardSQL
SELECT *,
COUNTIF(New_Session_Flag = 1) OVER(PARTITION BY Fullvisitorid ORDER BY Visitid) Rank_Session_Order
FROM `project.dataset.table`
``` | The answer by Mikhail Berlyant using a conditional window count is corret and works. I am answering because I find that a window sum is even simpler (and possibly more efficient on a large dataset):
```
select
t.*,
sum(new_session_flag) over(partition by fullvisitorid order by visid_id) rank_session_order
from... | 15,664 |
53,042,453 | I'm currently working on a Mac with Mojave. I have successfully installed python 3.7 with brew
```
brew install python3
```
But I have tried several methods to install pip for python 3.7 (installing with get-pip.py, easy\_install pip, etc.), which had worked for installing pip in the python 2.7 folder, but not i... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53042453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10573864/"
] | If you want to ensure pip installed for python 3.7, try something like this:
```
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.7 get-pip.py
``` | Maybe you're using an older version of Brew?
In that case run
brew postinstall python3 | 15,665 |
40,219,946 | I have a large data set (millions of rows) in memory, in the form of **numpy arrays** and **dictionaries**.
Once this data is constructed I want to store them into files;
so, later I can load these files into memory quickly, without reconstructing this data from the scratch once again.
**np.save** and **np.load** f... | 2016/10/24 | [
"https://Stackoverflow.com/questions/40219946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2101900/"
] | It's a structured array. Use `d2.item()` to retrieve the actual dict object first:
```
import numpy as np
d1={'key1':[5,10], 'key2':[50,100]}
np.save("d1.npy", d1)
d2=np.load("d1.npy")
print d1.get('key1')
print d2.item().get('key2')
```
result:
```
[5, 10]
[50, 100]
``` | [pickle](https://docs.python.org/3/library/pickle.html) module can be used. Example code:
```
from six.moves import cPickle as pickle #for performance
from __future__ import print_function
import numpy as np
def save_dict(di_, filename_):
with open(filename_, 'wb') as f:
pickle.dump(di_, f)
def load_dict... | 15,673 |
44,696,676 | Once I have installed miniconda, I am permanently inside the root miniconda environment eg:
```
luc@montblanc:~$ conda info --envs
# conda environments:
#
bunnies /home/luc/miniconda3/envs/bunnies
expose /home/luc/miniconda3/envs/expose
testano /home/luc/miniconda3/e... | 2017/06/22 | [
"https://Stackoverflow.com/questions/44696676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4803860/"
] | See your .bashrc file. Miniconda adds their paths and change the default, find this file and then change or add the path you want, or remove the anaconda/miniconda path.
In your .bashrc (probably ~/.bashrc) you will see something like:
```
# added by Miniconda3 4.3.14 installer
export PATH="/path/to/miniconda3/bin:$P... | Here is a way to do this on the fly without editing one's init files:
```
(base) ➜ ~ which python
/home/xxx/anaconda3/bin/python
(base) ➜ ~ echo $PATH
/home/xxx/anaconda3/bin:/home/xxx/anaconda3/condabin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bi... | 15,674 |
2,032,677 | How does this import work, what file does it use?
```
import _functools
```
In python 2.5:
```
import _functools
print _functools.__file__
```
Gives:
```
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object... | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234322/"
] | C-coded modules can be built-in (lacking `__file__`) or live in a `.so` or `.pyd` dynamic library (which their `__file__` will indicate) -- that's an implementation detail that you should not care about.
If you want to understand how a Python-callable, C-coded function works by studying code, learning to **read** C is... | please be more clear when asking questions next time. I assume you want this
```
>>> import _functools
>>> _functools.__file__
'/usr/lib/python2.6/lib-dynload/_functools.so'
``` | 15,677 |
9,916,367 | I have a dll named ExpensiveAndLargeObfuscatedFoo.dll.
Lets says it defines a type named ExpensiveAndLargeObfuscatedFooSubClass.
It's been compiled for .NET.
Are there any tools (free, paid, whatever) that will generate c# or vb class files that will do nothing but wrap around *everything* defined in this expensive d... | 2012/03/28 | [
"https://Stackoverflow.com/questions/9916367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/346272/"
] | [ReSharper](http://www.jetbrains.com/resharper/) can do much of the work for you.
You will need to declare a basic class:
```
namespace easytoread {
public class SubClass {
private ExpensiveAndLargeObfuscatedFoo.SubClass _originalSubClass;
}
}
```
Then, choose ReSharper > Edit > Generate Code (Alt+I... | 1. If you have access to the source code, rename and fix in the source
code.
2. If you don't have access (and you can do it legally) use some
tool like Reflector or [dotPeek](http://www.jetbrains.com/decompiler/) to get the source code and then,
goto to the first point. | 15,681 |
40,254,007 | I am looking for a way to store multiple values for each key (just like we can in python using dictionary) using Go.
Is there a way this can be achieved in Go? | 2016/10/26 | [
"https://Stackoverflow.com/questions/40254007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3902984/"
] | Based on your response in comments I would suggest something like the following using a struct (though if you are only interested in a single value like `name` for each item in your slice then you could just use a `map[int][]string{}`
```
type Thing struct {
name string
age int
}
myMap := map[int][]Thing{}
... | In go, the key/value collection is called a `map`. You create it with `myMap := map[keyType]valType{}`
Usually something like `mapA := map[string]int{}`. If you want to store multiple values per key, perhaps something like:
`mapB := map[string][]string{}` where each element is itself a slice of strings. You can then ... | 15,684 |
61,496,129 | I need to run selenium-side-runner in docker.I wrote in the dockerfile to install Google Chrome and googledrive. But when the code is executed, the error is as follows:
```
WebDriverError: unknown error: Chrome failed to start: exited abnormally.
(unknown error: DevToolsActivePort file doesn't exist)
(The process s... | 2020/04/29 | [
"https://Stackoverflow.com/questions/61496129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13054579/"
] | A hack
======
Instead of installing a browser by hand, I would recommend using already available images like <https://github.com/SeleniumHQ/docker-selenium>.
A solution (recommended)
========================
From an architectural point of view, each Docker container should have only one purpose. In your case, the co... | You could use [this project](https://github.com/nixel2007/docker-selenium-side-runner), put your .side files in side directory and run `docker-composer up` | 15,685 |
40,314,960 | I have a csv file with columns id, name, address, phone. I want to read each row such that I store the data in two variables, `key` and `data`, where data contains name, address and phone. I want to do this because I want to append another column country in each row in a new csv. Can anyone help me with the code in pyt... | 2016/10/29 | [
"https://Stackoverflow.com/questions/40314960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2433565/"
] | `key, *data = row` is Python 3 syntax. For Python 2 you can do this:
```
key, data = row[0], row[1:]
``` | You can try the code below. I have put two option one is to make a list for each row, and other is comma separated. Based on the usage you can use either one.
```
import csv
dict = {}
reader = csv.reader(open('info.csv', 'r'))
for row in reader:
data = []
print row
key,data = row[0],row[1:]
dict[key] ... | 15,686 |
38,290,965 | I am a beginner in Python.
I use Python 2.7 with ElementTree to parse XML files.
I have a big XML file (~700 MB), which contains multiple root instances, for example:
```
<?xml version="1.0" ?> <foo> <bar> <sometag> Mehdi </sometag> <someothertag> blahblahblah </someothertag> . . . </bar> </foo>
<?xml version="1.0"... | 2016/07/10 | [
"https://Stackoverflow.com/questions/38290965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4811059/"
] | You can try [this](https://jsfiddle.net/loginshivam/jq4c4wg7/2/)
```
<input value="0" id="id">
```
give a id to input field
on button click call a function
```
<button onclick="myFunction()">Add +10</button>
<script>
function myFunction() {
document.getElementById("id").value = parseInt(document.get... | You can use a click counter like [this](https://stackoverflow.com/questions/22402777/html-javascript-button-click-counter)
and edit it replacing `+= 1` with `+= 10`.
Here my code,
```js
var input = document.getElementById("valor"),
button = document.getElementById("buttonvalue");
var clicks = 0;
button.ad... | 15,687 |
61,679,525 | **Is it possible to have a variable that is defined in a python file be passed through to a html file in the same directory and used in a 'script' tag?**
Synopsis:
Im producing a flask website that pulls data from a database and uses it to create a line chart in chartjs. Flask uses jijna to manage templates. The data... | 2020/05/08 | [
"https://Stackoverflow.com/questions/61679525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13486528/"
] | For beginners who try to put Flask and ChartJS together, a common approach seems to be to write Jinja code which uses loops to output Javascript, or manually uses Jinja expressions within the JS. This can quick become a maintenence nightmare.
Here's my approach which lets you define the data you want charted in Python... | You can use the same jinja templating feature to access your Variable in js too.
Maybe if you want strings you should enclose them like this `"{{variable}}"` | 15,689 |
19,351,060 | What is the most pythonic way to iterate a dictionary and conditionally execute a method on values.
e.g.
```
if dict_key is "some_key":
method_1(dict_keys_value)
else
method_2(dict_keys_value)
```
It can't be a dict comprehension because I am not trying to create a dictionary from the result. It is just itera... | 2013/10/13 | [
"https://Stackoverflow.com/questions/19351060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462455/"
] | What you have is perfectly fine, and you can iterate with something like:
```
for key, value in my_dict.items(): # use `iteritems()` in Python 2.x
if key == "some_key": # use `==`, not `is`
method_1(value)
else:
method_2(value)
```
See: [`dict.items()`](http://docs.python.org/3/library/stdt... | Why not create a dict with lambda functions?
```
methods = {
'method1': lambda val: val+1,
'method2': lambda val: val+2,
}
for key, val in dict.iteritems():
methods[key](val)
``` | 15,690 |
25,884,534 | Can anyone tell me how to define a json data type to a particular field in models.
I have tried this
```
from django.db import models
import jsonfield
class Test(models.Model):
data = jsonfield.JSONField()
```
but when I say `python manage.py sqlall xyz`
its taking the data field as text
```
BEGIN;
CREATE TAB... | 2014/09/17 | [
"https://Stackoverflow.com/questions/25884534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323440/"
] | In the background [JSONField actually is a TextField](https://github.com/dmkoch/django-jsonfield/blob/master/jsonfield/fields.py#L154), so that output from sqlall is not a problem, that's the expected behavior.
Further, I recreated your model and it worked just fine, both when entering the value as a string and as a p... | A JSONField data type has been added to Django for certain databases to improve handling of JSON. More info is available in this post: [Django 1.9 - JSONField in Models](https://stackoverflow.com/questions/37007109/django-1-9-jsonfield-in-models) | 15,693 |
38,043,683 | I'm writing a git pre-commit hook, but it requires user input and hooks don't run in an interactive terminal. With Python I could do something like this to get access to user input:
```
#!/usr/bin/python
import sys
# This is required because git hooks are run in non-interactive
# mode. You aren't technically suppose... | 2016/06/26 | [
"https://Stackoverflow.com/questions/38043683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13973/"
] | You may try:
```
STDIN.reopen("/dev/tty")
``` | This seems to work:
```
file = File.open("/dev/tty")
line = file.gets
p line
```
You can't reassign STDIN and we don't have a reassignable global variable for it. I don't know much about this, maybe reopen and dup can be used for that. But otherwise you can use that `file` instead of `STDIN` in your program, I guess... | 15,698 |
50,982,990 | I'm designing an Application where username will be an `AutoIntegerField` and unique.
Here's my model.
```
class ModelA(models.Model):
username = models.BigAutoField(primary_key=True, db_index=False)
user_id = models.UUIDField(default=uuid.uuid4, unique=True,
editable=False)
``... | 2018/06/22 | [
"https://Stackoverflow.com/questions/50982990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1162512/"
] | I think the issue is that you still have an old index on your `username` field that clashes with the new type. The `db_index=False` argument has no effect because `primary_key=True` always generates an index.
You might be able to solve this by removing `primary_key=True`, creating a migration, and then re-adding it an... | in my case I was connecting django to postgres at localhost pgadmin
first deleted all the migrations except default one and also in the pycache
then just run python manage.py makemigrations and python manage.py migrate in your terminal | 15,701 |
716,386 | I was trying to hack up a tool to visualize shaders for my game and I figured I would try using python and cocoa. I have ran into a brick wall of sorts though. Maybe its my somewhat poor understand of objective c but I can not seem to get this code for a view I was trying to write working:
```
from objc import YES, NO... | 2009/04/04 | [
"https://Stackoverflow.com/questions/716386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84805/"
] | Depending on what's happening elsewhere in your app, your instance might actually be getting copied.
In this case, implement the `copyWithZone` method to ensure that the new copy gets the renderer as well. (Caveat, while I am a Python developer, and an Objective-C cocoa developer, I haven't used PyObjC myself, so I c... | Even if they weren't serialized, the \_\_init\_\_-constructor of python isn't supported by the ObjectiveC-bridge. So one needs to overload e.g. initWithFrame: for self-created Views. | 15,702 |
23,894,545 | I would like to use ArangoDB in Django, but I don't know which of the following options is better: using the [ArangoDB Python driver](http://blog.klymyshyn.com/2013/02/arangodb-driver-for-python.html) or building a new API with Foxx. I think that the ArangoDB Python driver is not based on Foxx and I don't know the pros... | 2014/05/27 | [
"https://Stackoverflow.com/questions/23894545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1960092/"
] | Better option for your case is to use ArangoDB Python driver.
Here is couple of reasons:
* easy-to-start - just install driver and move on with development
* some similarity to Django ORM API
* have some documentation
* all your business logic will be in place and in Python which should be great advantage
And here i... | I made a python ArangoDB driver (<https://github.com/saeschdivara/ArangoPy>)
and I created on top of that kind of a bridge for Django (<https://github.com/saeschdivara/ArangoDjango>). So you can use kind of an orm for ArangoDB and still use the Django Restframework to create your API. | 15,703 |
4,205,697 | My goal is to use to make it easy for non-programmers to execute a Python script with fairly complex options, on a single local machine that I have access to. I'd like to use the browser (specifically Safari on OS X) as a poor man's GUI. A short script would process the form data and then send it on to the main program... | 2010/11/17 | [
"https://Stackoverflow.com/questions/4205697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215679/"
] | Use an [AOP framework](http://www.postsharp.com) for this, to inject code when a certain method is hit. You can also do this native via the .NET framework with a [ContextBoundObject](http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx); which is probably what they've used in the framework. | You are thinking about this wrong. It's not that the attribute has a changing value, it's that its interpretation by the code that uses the attribute is based on runtime state. In the example you gave, it is probably the case that the code which checks for that attribute also does the checking of Thread.CurrentPrincipl... | 15,704 |
62,528,247 | I've updated the initial script with a modified version of Bryan-Oakley's [answer](https://stackoverflow.com/a/6789351/10364425). It now has 2 canvas, 1 with the draggable rectangle, and 1 with the plot. I would like the rectangle to be dragged along the x-axis on the plot if that is possible?
```
import tkinter as tk... | 2020/06/23 | [
"https://Stackoverflow.com/questions/62528247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13796693/"
] | The issue with your code is that you create two canvases, one for the matplotlib figure and one for the draggable rectangle while you want both on the same.
To solve this, I merged the current code of the question with the one before the edit, so the whole matplotlib figure is now embedded in the Tkinter window. The k... | I'm not sure how to do it with tkinter or pyQt but I know how to make something like this with PyGame which is another GUI solution for python. I hope this example helps you:
```
import pygame
SCREEN_WIDTH = 430
SCREEN_HEIGHT = 410
WHITE = (255, 255, 255)
RED = (255, 0, 0)
FPS = 30
pygame.init()
screen = py... | 15,706 |
29,826,430 | I want to extract a variable named `value` that is set in a second, arbitrarily chosen, python script.
The process works when do it manually in pyhton's interactive mode, but when I run the main script from the command line, `value` is not imported.
The main script's input arguments are already successfully forwarded... | 2015/04/23 | [
"https://Stackoverflow.com/questions/29826430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1809463/"
] | In my case I am using Handlebars for mandrill templates and I have solved this by sending HTML to the template `<br/>` instead of `\n` by replacing `\n` in my string with `<br/>` something like: `.Description.Replace("\n", "<br/>");`
And then on the mandrill template I put the variable inside {{{ variable }}} instead ... | If you want to send more complex content, be it html, or variables with break lines and whatnot, you can first render the template and then send the message, instead of directly using `send-template`.
Render the template with a call to [`templates.render`](https://mandrillapp.com/api/docs/templates.JSON.html#method=re... | 15,707 |
57,561,119 | Using python 3, I'm trying to append a sheet from an existing excel file to another excel file.
I have conditional formats in this excel file so I can't just use pandas.
```
from openpyxl import load_workbook
final_wb = load_workbook("my_final_workbook_with_lots_of_sheets.xlsx")
new_wb = load_workbook("workbook_wit... | 2019/08/19 | [
"https://Stackoverflow.com/questions/57561119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193105/"
] | So another approach, without color ranges.
A couple of things are not going right in your code I think. First, you are drawing the contours on `thresh_binary`, but that already has the outer lines of the other cells as well - the lines you are trying to get rid off. I think that is why you use `opening`(?) while in th... | Actually, in your code the 'box' is a legitimate extra contour. And you draw all contours on the final image, so that includes the 'box'. This could cause issues if any of the other colored cells are fully in the image.
A better approach is to separate out the color you want. The code below creates a binary mask that ... | 15,708 |
27,829,575 | I have a python script that calls a system program and reads the output from a file `out.txt`, acts on that output, and loops. However, it doesn't work, and a close investigation showed that the python script just opens `out.txt` once and then keeps on reading from that old copy. How can I make the python script reread... | 2015/01/07 | [
"https://Stackoverflow.com/questions/27829575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154996/"
] | You need to flush `foo` so that the external program can see its latest changes. When you write to a file, the data is buffered in the local process and sent to the system in larger blocks. This is done because updating the system file is relatively expensive. In your case, you need to force a flush of the data so that... | You take your file\_var and end the loop with file\_var.close().
```
for ... :
ga_file = open(out.txt, 'r')
... do stuff
ga_file.close()
```
Demo of an implementation below (as simple as possible, this is all of the Jython code needed)...
```
__author__ = ''
import time
var = 'false'
while var == 'fals... | 15,709 |
74,448,363 | I am trying to find out if a hex color is "blue". This might be a very subjective thing when comparing different (lighter/ darker) shades of blue or close to blue colors but in my case it does not have to be very precise. I just want to determine if a color is blue or not.
The more generalized question would be, is th... | 2022/11/15 | [
"https://Stackoverflow.com/questions/74448363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4644897/"
] | This is a somewhat complicated question, see more discussion here: <https://graphicdesign.stackexchange.com/questions/92984/how-can-i-tell-basic-color-a-hex-code-is-closest-to>
I don't know of any library or implementation that already exists for this. If you really need this functionality though and don't need it to ... | I mean you could do:
```
hex = input()
if hex == '#0000FF':
print('Blue')
else:
print('Not blue')
```
If that is what you are looking for. | 15,712 |
64,532,869 | I'm very new to java but i have decent experience with c++ and python. So, I'm doing a question in which im required to implement an airplane booking system, which does the following -
1.initialize all seats to not occupied(false)
2.ask for input(eco or first class)
3.check if seat is not occupied
4.if seat is not ... | 2020/10/26 | [
"https://Stackoverflow.com/questions/64532869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7617688/"
] | As Java calls methods by value,
Your problem about static is you are passing the value of `current_seat` to the `book_seat` method, so changing the value doesn't affect that variable after returning from the method.
To solve it just call the method and do not pass your static vars. It's static, so you have access it ... | 1. Checking Inout stream
Not sure wether your question is related to "static" variables or more related to "How to handle Input Stream?".
Regarding:
>
> if I press 1 it should book in first class but the program does not await for my input and proceeds to else statement instead.
>
>
>
You should think about "fl... | 15,713 |
2,284,666 | I've been able to do this through the django environment shell, but hasn't worked on my actual site. Here is my model:
```
class ShoeReview(models.Model):
def __unicode__(self):
return self.title
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
... | 2010/02/17 | [
"https://Stackoverflow.com/questions/2284666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200916/"
] | ```
ariake = Shoe.objects.get(pk=1)
# get the OwnerReviews
ariake.ownerreview_set.all()
# or the ShoeReviews
akiake.shoereview_set.all()
```
Or if you really want to use the OwnerReview class directly
```
OwnerReview.objects.filter(shoe=ariaki)
```
A question for you. Did you mean to use OnoToOneField(Shoe) and n... | The reason why you're getting an empty QuerySet is because on your ShoeReview model, your filter argument is wrong:
>
> `owner_reviews = OwnerReview.objects.filter(Shoe__name=Shoe)`
>
>
>
Change to this:
>
> `owner_reviews = OwnerReview.objects.filter(Shoe=Shoe) #without __name`
> or you can do like this also:... | 15,715 |
37,209,213 | I am working on a project with some friends and we're facing a bit of a problem with our implementation of `picamera`.
We're trying to import `cv2` and `picamera` at the start of the program (working with Python 3) and so far importing `cv2` works just fine.
When we're trying to import picamera it tells us this: `Impo... | 2016/05/13 | [
"https://Stackoverflow.com/questions/37209213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6140273/"
] | I know this was posted a while ago, but for those who are experiencing the same issue, try this:
```
pip install "picamera[array]"
```
According to [piimagesearch.com](http://www.pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/ "pyimagesearch.com") it's necessary to install the ... | This should might help
```
sudo pip3 install picamera
```
I ran this on my desktop and something installed so it should work
if pip isn't installed you may have to run
```
sudo apt-get install python3-pip
```
sources:
[How to install pip with Python 3?](https://stackoverflow.com/questions/6587507/how-to-instal... | 15,716 |
57,524,198 | You won´t be able to run the script, sadly I don´t know why.
It's about EOL but I'm not that much into python so I need your help,
I´ve tried different stuff and didn't work. Also, my friend that actually is into phyton tried and failed.
this is just a menu code for running multiple antiviruses whenever I want to chec... | 2019/08/16 | [
"https://Stackoverflow.com/questions/57524198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11935868/"
] | You are using backslash characters '\' in your paths. While this is OK on the command line, it is (mostly) not correct in source code. The backslash character is used as escape character to change the meaning of the following character. In your case the trailing apostroph is escaped so that the path string is not close... | You are missing a single quote at the end of the line:
```
if choice == "1":
print("Checking Files ... (The process wont take long !")
os.chdir 'C:\Users\alexa\Desktop\Core_Files\Projects\S1mpl3 Antivirus\Check\Files\File_Check.vbs\ **<---here**
menu()
``` | 15,717 |
65,273,118 | I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I w... | 2020/12/13 | [
"https://Stackoverflow.com/questions/65273118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372142/"
] | I see that your GPU has **[compute capability 5.0](https://developer.nvidia.com/cuda-gpus)** which is OK, TensorFlow should like it. Thus I assume something went wrong during the environment setup. Please try creating a new environment using:
```
conda create --name tf_gpu tensorflow-gpu
```
Then install all other ... | Using `conda` to install TensorFlow is always a better way to manage the multi versions of TensorFlow itself as well as CUDA and CUDNN. I recently create a new conda environment and prepare to install the newest TensorFlow too. I also encountered the issue you mentioned. I checked the dependency list from `conda instal... | 15,719 |
74,365,103 | I have a small code created in python and from an api I would like to go through all the
`code = url.json()["data"][0]["name"]`
But I do not know how to do it
this is my little code:
```
import requests
swf = input("write: ")
url = requests.get(f"https://apihabbo.com/api/furnis?hotel=es&name={swf}")
code = url.js... | 2022/11/08 | [
"https://Stackoverflow.com/questions/74365103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20452313/"
] | `data['data'][0]['code']` is not a list. The list is `data['data']`, you need to loop over that.
```
for d in data['data']:
print(d['code'])
``` | You have to iterate through the list of received data points.
```
response = requests.get("https://apihabbo.com/api/furnis?hotel=es&name=Gorro%20con%20Pomp%C3%B3n")
data = response.json()
for i in data['data']:
print("{}".format(i['code']))
``` | 15,729 |
61,235,115 | **Mac OS**: when I try to run anything involving pip, I get
```
-bash: pip: command not found
```
This happened after I accidentally deleted the pip Unix file in `usr/local/bin` while trying to solve a different problem with pip. At this point, I've pretty much given up on solving the problem manually.
>
> Is ther... | 2020/04/15 | [
"https://Stackoverflow.com/questions/61235115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13322285/"
] | In recent python versions pip is as module rather than as individual script. Try:
```
python -m pip
``` | solution was surprisingly simple: deleted everything python related from my computer:
1. deleted `Python` App in `Applications` Folder
2. deleted all python and pip related files in `usr/local/bin`
3. deleted the `Python.framework` folder in `Libraray/Frameworks`
4. searched for and deleted all folders named `python`
... | 15,730 |
11,616,003 | I install virtualenv with command `sudo /usr/bin/pip-2.6 install virtualenv`
And it says
```
Requirement already satisfied (use --upgrade to upgrade):
virtualenv in /usr/local/lib/python2.6/dist-packages
Cleaning up...
```
Why pip from /usr/bin looks to /usr/local/lib?
I need to install virtualenv scripts direct... | 2012/07/23 | [
"https://Stackoverflow.com/questions/11616003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429873/"
] | Starting with iOS 6, you MUST set the audio session category to 'playback' before creating the UIWebView. This is all you have to do. It is not necessary to make the session active.
This should be used for html video as well, because if you don't configure the session, your video will be muted when the ringer switch i... | This plugin will make your app ignore the mute switch. It's basically the same code that's in the other answers but it's nicely wrapped into a plugin so that you don't have to do any manual objective c edits.
<https://github.com/EddyVerbruggen/cordova-plugin-backgroundaudio>
Run this command to add it to your project... | 15,731 |
15,616,139 | I am python beginner struggling to create and save a list containing tuples from csv file in python.
The code I got for now is:
```
def load_file(filename):
fp = open(filename, 'Ur')
data_list = []
for line in fp:
data_list.append(line.strip().split(','))
fp.close()
return data_list
```
... | 2013/03/25 | [
"https://Stackoverflow.com/questions/15616139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2207588/"
] | `split` returns a list, if you want a tuple, convert it to a tuple:
```
data_list.append(tuple(line.strip().split(',')))
```
Please use the `csv` module. | First question: why is a list of lists bad? In the sense of "duck-typing", this should be fine, so maybe you think about it again.
If you really need a list of tuples - only small changes are needed.
Change the line
```
data_list.append(line.strip().split(','))
```
to
```
data_list.append(tuple(l... | 15,737 |
21,352,457 | I'm trying to create a program that will launch livestreamer.exe with flags (-example), but cannot figure out how to do so.
When using the built in "run" function with windows, I type this:
`livestreamer.exe twitch.tv/streamer best`
And here is my python code so far:
```
import os
streamer=input("Streamer (full na... | 2014/01/25 | [
"https://Stackoverflow.com/questions/21352457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2925095/"
] | ```
arr = [["food", "eggs"],["beverage", "milk"],["desert", "cake"]]
arr.inject([]) do |hash, (v1, v2)|
hash << { category: v1, item: v2 }
end
```
I used [`inject`](http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-inject) to keep the code concise.
Next time you may want to show what you have tried in the q... | ```
hash = arr.each_with_object({}){|elem, hsh|hsh[elem[0]] = elem[1]}
``` | 15,740 |
47,810,110 | I have a text file which has 30 multiple choice questions in the following pattern
1. question one goes here ?
A. Option 1
B. Option 2
C. Option 3
D. Option 4
and so on to 30
Number of options is variable; there are minimum two and maximum six options.
I want to practice these questions in a interface like html... | 2017/12/14 | [
"https://Stackoverflow.com/questions/47810110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3986321/"
] | You just need to change your JS to:
```
$(document).ready(function(){
$('section').mouseenter(function(){
var id = $(this).attr('id');
$('a').removeClass('colorAdded');
$("a[href='#"+id+"']").addClass('colorAdded');
});
});
```
It was an issue with not including quotations in selectin... | I'm actually don't know why your codepen example is not working, I didn't look into your code carefully, but I tried to create simple code like bellow and it worked.
the thing you probably should care about is how you import JQuery into your page.
`<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery... | 15,745 |
17,957,651 | For those who need to know, I'm running a 64 bit Ubuntu 12.04, and trying to run the problematic script using a pip-installed python3.2
For a project I was writing I wanted to display an image in a tkinter window. To do this I installed Pillow via pip and installed tkinter for python 3 like so:
```
pip-3.2 install pi... | 2013/07/30 | [
"https://Stackoverflow.com/questions/17957651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1543167/"
] | So after posting an issue on [GitHub](https://github.com/python-imaging/Pillow/issues/322#issuecomment-23053260 "GitHub") I was told I was missing some libraries.
Specifically I needed to
`sudo apt-get install tk8.5-dev tcl8.5-dev`
and then
`pip install -I pillow`
to rebuild pillow. This worked on my raspberry p... | I don't have the rep to comment, so I'll answer instead
I too was getting the error `can't from PIL import _imagingtk`
using python3 on Linux Mint 17
when trying to do a `tk_im = ImageTk(im)`
First I installed the tk8.6-dev and tcl8.6-dev as suggested above
Then I tried the `pip3 --upgrade route`, which didn't fix t... | 15,746 |
414,896 | I'm trying to determine what is the fastest way to read in large text files with many rows, do some processing, and write them to a new file. In C#/.net, it appears StreamReader is a seemingly quick way of doing this but when I try to use for this file (reading line by line), it goes about 1/3 the speed of python's I/O... | 2009/01/05 | [
"https://Stackoverflow.com/questions/414896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] | Do you have a code sample of what your doing, or the format of the file you are reading?
Another good question would be how much of the stream are you keeping in memory at a time? | A general note:
1. High performance streaming isn't complicated. You usually have to modify the logic that uses the streamed data; **that's** complicated.
Actually, that's it. | 15,749 |
55,459,783 | I am currently trying to code Uno in python for my Computer science principles class in school and I created a definition to draw cards from the deck into the player's hand and whenever I run the code I keep getting this error. I was just wondering how to fix it because I have tried a couple of things and have gotten n... | 2019/04/01 | [
"https://Stackoverflow.com/questions/55459783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11293669/"
] | Lists in Python are mutable. So when you manipulate a list (even within the scope of a function) it will reflect everywhere that list is referenced.
```
x = x.insert(0,draw)
z = z.remove(draw)
```
These lines of code are assigning the return of the method calls on the list. Both of these method calls don't return an... | The problem comes from these two lines, because remove does not return the list :
```
x = x.insert(0, draw)
z = z.remove(draw)
```
`insert` and `remove` do not return anything. Do not reassign `x` and `z` and it should work:
```
x.insert(0, draw)
z.remove(draw)
```
In addition, you should return `z` to save the r... | 15,759 |
64,657,061 | I'm trying to create a simple python calculator to calculate dose of a medication.
For a sample weighing 60kg. The dose should be (60\*15) divide by 80.
The supposed output should be 11.25 vials.
However, Im getting 7.575757575757576e+27. Please help me out to diagnose the problem here. Thanks
Here is the sample cod... | 2020/11/03 | [
"https://Stackoverflow.com/questions/64657061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11362617/"
] | You're multiplying the string
Try this:
```
print ('Number of vial is ' + str(int(ptWeight)*15 / 80)+ ' vials.')
``` | You are multiplying as a sting. Try this instead
```
print('Hello Doctor!')
print('What is your name?')
myName= input()
print('It is good to meet you, ' 'Dr.' +myName)
print('What is the weight of patient?') # Patient weight
ptWeight = int(input())
vitals = round(int((ptWeight)*15) / 80,2)
print ('Number of vial i... | 15,760 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.