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 |
|---|---|---|---|---|---|---|
37,464,116 | I have found some ways to using python to build android app.But all of them need to install sl4a and pythonforandroid.
It is so complicated,so is there any way to package sl4a to my android app project,and once I install the apk,I needn't install sl4a any more. | 2016/05/26 | [
"https://Stackoverflow.com/questions/37464116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5867427/"
] | You can use Kivy at following link :
[Python for Android](https://github.com/kivy/python-for-android)
It will can help u have a look to the following topic :
[How can I integrate a Python code in the Android Java app?](https://www.quora.com/How-can-I-integrate-a-Python-code-in-the-Android-Java-app)
hope this help y... | You *can* do this. What it comes down to is packaging the Python interpreter (compiled by the NDK) in your app, and starting it via the standard NDK mechanisms. This is the same thing that e.g. Kivy does, but you'd be adding the code to your own app rather than (like Kivy) using a java bootstrap then letting the Python... | 11,754 |
21,717,995 | How can i set the python on my mac back to the default reference location? When I to do
```
sudo easy_install virtualenv
```
I get the following results
```
dyld: Library not loaded: @rpath/Python
Referenced from: /Users/a1ctesta/Library/Enthought/Canopy_64bit/User/bin/python
Reason: image not found
```
I do ... | 2014/02/12 | [
"https://Stackoverflow.com/questions/21717995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3221720/"
] | You probably need to modify your `$PATH` environment variable so that `/usr/bin` is before your custom path. To check if this is the issue, run the following command and see if `/usr/bin` is before or after your custom path
```
$ echo $PATH
```
The PATH environment variable is often set in `~/.bash_profile`, for exa... | I had the same issue. It was easiest to reinstall Canopy. From the Canopy preferences menu, Unset Canopy as your default Python. Then restart your computer. <https://support.enthought.com/hc/en-us/articles/204469700-Uninstalling-and-resetting-Canopy> | 11,755 |
73,409,909 | No matter what I install, it's either opencv-python, opencv-contrib-python or both at the same time, I keep getting the "No module named 'cv2'" error. I couldn't find an answer here. Some say that only opencv-python works, others say opencv-contrib-python works. I tried everything but nothing seems to work. I'm trying ... | 2022/08/18 | [
"https://Stackoverflow.com/questions/73409909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11672955/"
] | You need update your EAS to 0.60.0
npm install -g eas-cli
I had the same problem.
Work for me, friend | We fixed this issue by next steps
1: Upgrade your eas-cli running: `npm install -g eas-cli`
2: If you're publishing by first time your app, you need request access in to your App Store Connet, by this link,
<https://appstoreconnect.apple.com/access/api>
```
Select Users and Access, and then select the API Keys tab... | 11,759 |
66,937,068 | **Please help me fix my regex :).**
Summary: How can I make a repeating group (tags) match greedily even if it means a preceding optional group (a label) is empty.
For some reason, my regex is not acting as desired:
```
code: re.match("^foo(-.*?)?((?:-(?:a|b))*)$", "foo-a-b").groups()
output: ('-a', '-b')
expe... | 2021/04/04 | [
"https://Stackoverflow.com/questions/66937068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4089332/"
] | This boils down to stylistic preferences. I personally don't have qualms with having some of the attributes defined outside of `__init__(...)`, and so would opt for something like:
```
class TriangleData():
def __init__(self, contour_data: np.ndarray):
self.get_triangle_data(contour_data)
def get_tri... | There is a wide spectrum of approaches and libraries to eliminate redundancy of a plain `__init__()`. Please take a look at the [dataclasses](https://docs.python.org/3/library/dataclasses.html), [attrs](https://www.attrs.org/en/stable/), [NamedTuple](https://docs.python.org/3/library/typing.html#typing.NamedTuple) and ... | 11,762 |
1,038,907 | >
> **Possible Duplicate:**
>
> [Suggestions for a Cron like scheduler in Python?](https://stackoverflow.com/questions/373335/suggestions-for-a-cron-like-scheduler-in-python)
>
>
>
What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas [here](h... | 2009/06/24 | [
"https://Stackoverflow.com/questions/1038907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7581/"
] | There is a handy event scheduler that might do what you need. Here's a link to the documentation:
<http://docs.python.org/library/sched.html> | Many programmers try to avoid multi-threaded code, since it is highly bug-prone in imperative programming.
If you want to a scheduled task in a single-threaded environment, then you probably need some kind of "[Reactor](http://en.wikipedia.org/wiki/Reactor_pattern)". You may want to use a ready-made one like [Twisted]... | 11,765 |
48,075,739 | django version: 1.11, python version: 3.6.3
I found this stackoverflow question:
[Unit Testing a Django Form with a FileField](https://stackoverflow.com/questions/2473392/unit-testing-a-django-form-with-a-filefield)
and I like how there isn't an actual image/external file used for the unittest; however I tried these... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48075739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3329127/"
] | `image_data` should be dict, without providing key `{value}` will create set object. You need to define it like this `{key: value}`. Fix to this:
```
image_data = {
'image_field': InMemoryUploadedFile(im_io, None, 'random.jpg', 'image/jpeg', len(im_io.getvalue()), None)
}
``` | Without External File Code
```
from django.core.files.uploadedfile import SimpleUploadedFile
testfile = (
b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04'
b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02'
b'\x02\x4c\x01\x00\x3b')
avatar = SimpleUploadedFile('small.gif', testfile, ... | 11,772 |
3,319,788 | I am trying to retrieve data in a sybase data base from python and I was wondering which would be the best way to do it. I found this module but may be you have some other suggestions:
<http://python-sybase.sourceforge.net/>
Thanks | 2010/07/23 | [
"https://Stackoverflow.com/questions/3319788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400413/"
] | The sybase module you linked is by far the easiest way. You can get data like so:
```
import Sybase
db = Sybase.connect('server','name','pass','database')
c = db.cursor()
c.execute("sql statement")
list1 = c.fetchall()
print list1
```
You will have to use something like freetds to setup the interfaces for sybase, ... | you can also connect through [ODBC](http://tinyurl.com/255plm2). | 11,773 |
28,724,785 | I am currently working on a project that makes use of Python 3.2.3 and thought to do some tests of my code in IPython but it seems that IPython does not support the version of python I am using.
I get the following ImportError when trying to run Ipython on my Ubuntu machine.
```
ImportError: IPython requires Python v... | 2015/02/25 | [
"https://Stackoverflow.com/questions/28724785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3166105/"
] | You can find some discussion about dropping 2.6 and 3.2 support [here](https://github.com/ipython/ipython/pull/4002). One of the main reasons was that 3.2 does not support 2.x-style unicode strings - `u"I love IPython!"`, while 3.3 and above do. This change made it possible to support 2.7 and 3.3+ in a single codebase. | [Quickstart](http://ipython.org/ipython-doc/2/install/install.html):
IPython requires Python 2.7 or ≥ 3.3.
If you need to use Python 2.6 or 3.2, you can find IPython 1.0 [here](http://archive.ipython.org/release/).
PS:
The deadsnakes PPA has packages for old and new python versions:
```
sudo apt-get install python... | 11,775 |
68,081,171 | This is a problem of the missing number in python.
```
class Missing:
n = int(input())
arr = list(map(int,input().split(" ")))
def __init__(self,arr,n):
self.arr = arr
self.n = n
def MissingNumber(self):
self.res = self.n*(self.n+1)/2
self.sum_array = sum(self.arr)
... | 2021/06/22 | [
"https://Stackoverflow.com/questions/68081171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14643490/"
] | you need put the input outside class,and assign it when you create instance by `Obj = Missing(arr,n)`
code:
```
class Missing:
def __init__(self,arr,n):
self.arr = arr
self.n = n
def MissingNumber(self):
self.res = self.n*(self.n+1)/2
self.sum_array = sum(self.arr)
ret... | your constructor need two parameter. You need to assign it before it run.
you need to assign n and arr outside class object
```
class Missing:
def __init__(self,arr,n):
self.arr = arr
self.n = n
def MissingNumber(self):
self.res = self.n*(self.n+1)/2
self.sum_array = sum(self.... | 11,776 |
6,715,486 | So I am fairly new to python. But would like your help solving this minor issue I having removing similar duplicates out of a list.
So I have a list of urls: `myList = ['http://www.mywebsite.com/shoes', 'http://wwww.yourwebsite.com/', 'http://www.mywebsite.com/shoes/']`
I want to remove similar url's as you can see <... | 2011/07/16 | [
"https://Stackoverflow.com/questions/6715486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841342/"
] | If similarity for you is difference in '\' thab you can use sets[(read tutorial here)](http://docs.python.org/tutorial/datastructures.html#sets) [and here](http://docs.python.org/library/stdtypes.html?highlight=frozenset#set-types-set-frozenset) to remove duplicates from your list since:
>
> A set object is an unorde... | The issue may be that you haven't figured out exactly what it means for two URLs to be similar. We can't help you with that because only you know what your requirements are. Once you do figure that out, though, the rest is simple enough. There are two ways to do it:
* If your similarity relation is transitive - that i... | 11,777 |
15,848,156 | I use the package named python-snappy. This package requires [snappy](https://code.google.com/p/snappy/) library. So, I download and install snappy successfully by the following commands such as:
```
./configure
make
sudo make install
```
When I import snappy, I receive the errors:
```
from _snappy import CompressE... | 2013/04/06 | [
"https://Stackoverflow.com/questions/15848156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/875781/"
] | Traditionally you might have to run the `ldconfig` utility to update your */etc/ld.so.cache* (or equivalent as appropriate to your OS). Sometimes it might be necessary to add new entries (paths) to your */etc/ld.so.conf*.
Basically the shared object (so) loaders on many versions of Unix (and probably other Unix-like o... | You can install the [python-snappy](http://packages.ubuntu.com/precise/python-snappy) and [libsnappy1](http://packages.ubuntu.com/precise/libsnappy1) from the ubuntu repos:
```
$ sudo apt-get install libsnappy1 python-snappy
```
You should not have to download anything. | 11,779 |
59,412,006 | I am new to python and having a problem:
my task was `"Given a sentence, return a sentence with the words reversed"`
e.g. `Tea is hot --------> hot is Tea`
my code was:
```
def funct1 (x):
a,b,c = x.split()
return c + " "+ b + " "+ a
funct1 ("I am home")
```
It did solve the answer, but i have 2 questi... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59412006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12565719/"
] | Your code is heavily dependent on the assumption that the string will always contain **exactly** 2 spaces. The task description you provided does not say that this will always be the case.
This assumption can be eliminated by using `str.join` and `[::-1]` to reverse the list:
```
def funct1(x):
return ' '.join(x.... | A pythonic way to do this would be:
```
def reverse_words(sentence):
return " ".join(reversed(sentence.split()))
```
To answer the subquestions:
1. Yes, use [`str.join`](https://docs.python.org/3/library/stdtypes.html#str.join).
2. Yes, you can use a [slice](https://stackoverflow.com/questions/509211/understand... | 11,785 |
32,780,946 | I have this database layout
```
class Clinic(models.Model):
class Menu(models.Model):
...
menu = models.OneToOneField(Clinic, related_name='menu')
class Item(models.Model):
...
menu = models.ForeignKey('Menu')
```
and I would like to access my Menu model and the Items linked to that menu from my Cl... | 2015/09/25 | [
"https://Stackoverflow.com/questions/32780946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3282276/"
] | `clinic.menu.objects` is the `ModelManager` for the `Menu` model - note that it's an attribute of the `Menu` *class*, not of your `clinic.menu` instance. `ModelManager` classes are used to query the underlying table, and are not supposed to be called directly from instances (which wouldn't make much sense anyway), henc... | Try this:
```
Clinic.objects.get(pk=1).menu.item_set.all()
``` | 11,786 |
8,264,569 | I've got 32 SQLite (3.7.9) databases with 3 tables each that I'm trying to merge together using the idiom that I've found elsewhere (each db has the same schema):
```
attach db1.sqlite3 as toMerge;
insert into tbl1 select * from toMerge.tbl1;
insert into tbl2 select * from toMerge.tbl2;
insert into tbl3 select * from ... | 2011/11/25 | [
"https://Stackoverflow.com/questions/8264569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126321/"
] | You can do it somewhat with HTML5's new input types
See: <http://www.456bereastreet.com/archive/201004/html5_input_types/> | Using HTML5, kind of yes. Link: <http://thereforei.am/2011/07/01/css-selectors-for-html5-input-validation/> | 11,787 |
49,461,537 | Using pycharm community python3.6.2 Django 2.0.3
views.py
```
from django.http import HttpResponse
def hello_world(request):
return HttpResponse('Hello World')
```
urls.py
```
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', admin.si... | 2018/03/24 | [
"https://Stackoverflow.com/questions/49461537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9511012/"
] | The error is telling you that there is no variable such as `hello_world` defined. You need to change it to:
```
url(r'^$', views.hello_world)
```
Where `views` is the views module that you have imported at the top. | This line of code is wrong
```
url(r'^$', views, hello_world)
```
You just imported the `view` which is the file view.py. Now you need to call the function view, which it is going to be like:
```
url(r'^$', views.hello_world)
```
And you might think it is going to be useful to give that url a name so you can use ... | 11,790 |
36,937,305 | I am running a shell script in cygwin where I am using python robot framework, but in that environment it's not getting 'pybot' as command.
```
$ pybot --version
```
Result-
```
-bash: pybot: command not found
```
However in cmd prompt the above command is working fine.
PS- I have already set python interpreter... | 2016/04/29 | [
"https://Stackoverflow.com/questions/36937305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4637378/"
] | I have explored and get to know that, in Cygwin we need to specify the file type as well. So, if we say-
```
pybot.bat --version
```
this should work. | worked for me in cygwin:
Adjetterpc@Pompina
$ robot.bat --version
Robot Framework 3.0.4 (Python 2.7.13 on win32)
Adjetterpc@Pompina
$ pybot.bat --version
Robot Framework 3.0.4 (Python 2.7.13 on win32) | 11,791 |
62,023,199 | I have a little problem on making ecounter for fast food, the problems is at continuing order.
I don't know how to use True and False in python..
I choose three food as a beginner. It's end up failing..
So I tried to use True by copying other people code.
at first the code was success, but when i changed a little thing... | 2020/05/26 | [
"https://Stackoverflow.com/questions/62023199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13620217/"
] | Query is fairly self explanatory. I have added a should clause with a match on field c and no exists check on field c. Minimum\_should\_match is set as 1. A document which matches either of clause is returned i.e either it should not exist or should match the input string
```
{
"query": {
"bool": {
"must":... | Use filter and exist.
[exists](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html)
[filter](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html)
```
{
"query": {
"filtered": {
"filter": {
"bool": {
"must_no... | 11,792 |
48,886,423 | I have a address list as :
```
addr = ['100 NORTH MAIN ROAD',
'100 BROAD ROAD APT.',
'SAROJINI DEVI ROAD',
'BROAD AVENUE ROAD']
```
I need to do my replacement work in a following function:
```
def subst(pattern, replace_str, string):
```
by defining a pattern outside of this f... | 2018/02/20 | [
"https://Stackoverflow.com/questions/48886423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9385748/"
] | No need for regex, just use `replace`:
```
[x.replace('ROAD', 'RD') for x in addr]
```
If you only want to replace the `ROAD` as a word, no in the middle, use:
```
[re.sub(r'\bROAD\b', 'RD', x) for x in addr]
``` | Using `re`
```
import re
addr = ['100 NORTH MAIN ROAD',
'100 BROAD ROAD APT.',
'SAROJINI DEVI ROAD',
'BROAD AVENUE ROAD']
for i, v in enumerate(addr):
addr[i] = re.sub('ROAD', 'RD', v) #v.replace("ROAD", "RD")
print addr
```
**Output**:
```
['100 NORTH MAIN RD', '100 BRD R... | 11,793 |
70,332,822 | I am receiving an image as bytes that I would like to store using specifically with open command due to library restrictions. Therefore I am unable to use libs like opencv2 and PIL
```
mport numpy as np
import base64
import cv2
import io
from os.path import dirname, join
from com.chaquo.python import Python
def main(... | 2021/12/13 | [
"https://Stackoverflow.com/questions/70332822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As you wrote most Databricks clusters use 1.2.17 so it is different version and version affected by vulnerability is not used by Databricks.
Only one problem is when you install different version by yourself on the cluster. Even when you installed affected version you can mitigate the problem by setting Spark config i... | you get complete e2e update on this here : <https://databricks.com/blog/2021/12/13/log4j2-vulnerability-cve-2021-44228-research-and-assessment.html> | 11,796 |
13,788,114 | Given the following Python (from <http://norvig.com/sudoku.html>)
```
def cross(A, B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
cols = '123456789'
rows = 'ABCDEFGHI'
squares = cross(rows, cols)
```
This produces:
```
['A1', 'A2', 'A3', 'A4', 'A5', 'A6'... | 2012/12/09 | [
"https://Stackoverflow.com/questions/13788114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163625/"
] | Well it's shorter to just present the code than to explain:
```
#include <iostream> // std::wcout, std::endl
#include <string> // std::string
#include <utility> // std::begin, std::end
#include <vector>
using namespace std;
string sum( char const a, char const b ) { return string() + a + b;... | templatize for classes A and B. then make pairs `std::pair<A, B>` | 11,797 |
30,884,008 | I have files with code that is formatted for windows. when I try to run them on linux machine i have problem with file encodings. Can anybody suggest a solution for this
on Windows when I run I get -
```
This was return from redis
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python... | 2015/06/17 | [
"https://Stackoverflow.com/questions/30884008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4943862/"
] | Your selection list in the first condition of your `if` statement is the problem.
If `opt` happens to be `es`, for example, then
```
if opt == 'es':
opt = "ESP:"
```
will change that to `ESP:`.
```
if opt in ["es","la","en","ar","fr"] and extent == "begin":
```
can then never be `True` (when you're using `an... | **AND**
To become condition True by **AND Operator**, required **True** result from the **all conditions**.
**OR**
To become condition True by **OR Operator**, required **True** result from the any **one condition**.
**E.g.**
```
In [1]: True and True
Out[1]: True
In [2]: True and False
Out[2]: False
In [3]: Tru... | 11,803 |
17,559,257 | I am using the following code to send email from unix.
Code
```
#!/usr/bin/python
import os
def sendMail():
sendmail_location = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t" % sendmail_location, "w")
p.write("From: %s\n" % "myname@company.com")
p.write("To: %s\n" % "yourname@company.c... | 2013/07/09 | [
"https://Stackoverflow.com/questions/17559257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392233/"
] | Sendmail is an extremely simplistic program. It knows how to send a blob of text over smtp. If you want to have attachments, you're going to have to do the work of converting them into a blob of text and using (in your example) p.write() to add them into the message.
That's hard - but you can use the `email` module (p... | I normally use the following to send a file "file\_name.dat" as attachment:
```
uuencode file_name.dat file_name.dat | mail -s "Subject line" arnab.bhagabati@gmail.com
``` | 11,812 |
58,880,450 | How might I remove duplicate lines from a file and also the unique related to this duplicate?
**Example:**
Input file:
```
line 1 : Messi , 1
line 2 : Messi , 2
line 3 : CR7 , 2
```
I want the output file to be:
```
line 1 : CR7 , 2
```
Just ( " CR7 , 2 " I want to delete duplicate lines and also... | 2019/11/15 | [
"https://Stackoverflow.com/questions/58880450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12379359/"
] | Have you tried `Counter`?
This works for example:
```
import collections
a = [1, 1, 2]
out = [k for k, v in collections.Counter(a).items() if v == 1]
print(out)
```
Output: `[2]`
Or with a longer example:
```
import collections
a = [1, 1, 1, 2, 4, 4, 4, 5, 3]
out = [k for k, v in collections.Counter(a).items() ... | Given your input you can do something like this:
```
seen = {} # key maps to index
double_seen = set()
with open('input.txt') as f:
for line in f:
_, key = line.split(':')
key = key.strip()
if key not in seen: # Have not seen this yet?
seen[key] = line # Then add it to the dict... | 11,814 |
67,194,174 | I want to write a python code were the output will be something like this
[[1],[1,2],[1,2,3], … [1,2,3, … ]]
I have this code and has the similar output but the only difference is that it prints all the cases
for example
if I say that the range is 3 it prints
[[1], [1, 2], [1, 3], [1, 2, 3]]
and not
[[1], [1, 2], [1, 2... | 2021/04/21 | [
"https://Stackoverflow.com/questions/67194174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13300391/"
] | How about using `list comprehension`?
For example:
```
num = 3
print([[*range(1, i + 1)] for i in range(1, num + 1)])
```
Output:
```
[[1], [1, 2], [1, 2, 3]]
``` | You should not use a loop inside loops if you intend to add a single number at the end of it only.
```
def copyBase(lst):
return lst[:]
def sub_lists(l):
base = [1]
lists = []
for i in range(1, l+1):
lists += [copyBase(base),]
base += [i+1]
return lists
num=int(input("Please give... | 11,815 |
58,105,181 | I'm using databricks-connect on mac using pycharm but after I finished the configuration and tried to run `databricks-connect test`, I got the following error and have no idea what the problem is. I followed this documentation: <https://docs.databricks.com/user-guide/dev-tools/db-connect.html>
The error message is as ... | 2019/09/25 | [
"https://Stackoverflow.com/questions/58105181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6279751/"
] | Maybe your Java/Python version does not comply. Check your cluster, which Python version does it use (in my case it was 3.5).
And what's most important: check which JDK version do you have on your computer.
In my case, I've had the latest one, which was not supported by `databricks-connect`. It needs to run on JDK 8. | To ignore the RUNTIME version, export an environment variable that resolves:
export DEBUG\_IGNORE\_VERSION\_MISMATCH=1 | 11,819 |
25,331,758 | I am writing a script to start and background a process inside a vagrant machine. It seems like every time the script ends and the ssh session ends, the background process also ends.
Here's the command I am running:
`vagrant ssh -c "cd /vagrant/src; nohup python hello.py > hello.out > 2>&1 &"`
`hello.py` is actually... | 2014/08/15 | [
"https://Stackoverflow.com/questions/25331758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3667561/"
] | I faced the same problem when trying to run Django application as a daemon. I don't know why, but adding a "sleep 1" behind works for me.
```
vagrant ssh -c "nohup python manage.py runserver & sleep 1"
``` | Running nohup inside the ssh command did not work for me when running wireshark. This did:
```
nohup vagrant ssh -c "wireshark" &
``` | 11,821 |
46,901,975 | I am new to this whole python and the data mining.
Let's say I have a list of string called data
```
data[0] = ['I want to make everything lowercase']
data[1] = ['How Do I Do It']
data[2] = ['With A Large DataSet']
```
and so on. My len(data) gives 50000.
I have tried
```
{k.lower(): v for k, v in data.items()}
`... | 2017/10/24 | [
"https://Stackoverflow.com/questions/46901975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4160544/"
] | if your list *data* like this:
```
data = ['I want to make everything lowercase', '', '']
data = [k.lower() for k in data]
```
if your list *data* is a list of string list:
```
data = [['I want to make everything lowercase'], ['']]
data = [[k.lower()] for l in data for k in l]
```
the fact is that list don't has ... | You need a list comprehension, not a dict comprehension:
```
lowercase_data = [v.lower() for v in data]
``` | 11,822 |
65,332,466 | I get a [circular dependency error](https://stackoverflow.com/questions/40705237/django-db-migrations-exceptions-circulardependencyerror) that makes me have to comment out a field. Here is how my models are set up:
```
class Intake(models.Model):
# This field causes a bug on makemigrations. It must be commented wh... | 2020/12/16 | [
"https://Stackoverflow.com/questions/65332466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Ok OP let me do this again, you want to find all the rows which are "A" (base condition) and all the rows which are following a "A" row at some point, right ?
Then,
```
is_A = df["ID"] == "A"
not_A_follows_from_A = (df["ID"] != "A") &( df["ID"].shift() == "A")
candidates = df["ID"].loc[is_A | not_A_follows_from_A].un... | Let us try `drop_duplicates`, then `groupby` select the number of unique ID we would like to keep by `head`, and `merge`
```
out = df.merge(df[['Time','ID']].drop_duplicates().groupby('Time').head(2))
Time ID Val
0 1 A 2.0
1 1 A 5.0
2 1 B 2.5
3 1 B 2.0
4 2 A 1.0
5 2 A 6.0
6 ... | 11,823 |
18,451,694 | e.g. I defined an function which needs several input arguments, if some keyword arguments not being assigned, typically there be an TypeError message, but I want to change it, to output an NaN as the result, could it be done?
```
def myfunc( S0, K ,r....):
if S0 = NaN or .....:
```
How to do it?
Much appreciate... | 2013/08/26 | [
"https://Stackoverflow.com/questions/18451694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2525479/"
] | You can capture the TypeError and do whatever you want with it:
```
def myfunc(a):
try:
return a / 2.5 + 5
except TypeError:
return float('nan')
print myfunc('whatever')
```
[The Python Tutorial](http://docs.python.org/2/tutorial/errors.html) has an excellent chapter on this subject. | ```
def myfunc(S0 = None, K = None, r = None, ....):
if S0 is None or K is None or r is None:
return NaN
``` | 11,824 |
68,030,577 | I have obtained 3 lists/arrays in my python script and I am wondering why I am not able to multiply them to values successfully.
```
Array 1: [-0.01896408 -0.0191784 -0.01939271 ... 0.97766441 0.97745009
0.97723578]
Array 2: [ 1.21527999 1.21302709 1.21077419 ... -0.69821075 -0.70046365
-0.70271655]
Array 3: [... | 2021/06/18 | [
"https://Stackoverflow.com/questions/68030577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15233108/"
] | I can't comment so I have to post my comment like this:
As I understand it you try to multiply elements of the "pointsArray" with a scalar.
Have you tried printing
```
array1[i]
```
to see what it looks like? From the error I would guess that this is somehow not just a number, but the entire array. You could for ex... | dot is used for matrix multiplication.
Try this:
```
matrix1.dot(matrix2)
```
A bit more clarity:
If you want to use \*, convert both to numpy.matrix and then try. | 11,827 |
57,487,274 | I have a below API response. This is a very small subset which I am pasting here for reference. there can be 80+ columns on this.
```
[["name","age","children","city", "info"], ["Richard Walter", "35", ["Simon", "Grace"], {"mobile":"yes","house_owner":"no"}],
["Mary", "43", ["Phil", "Marshall", "Emily"], {"mobile":"y... | 2019/08/14 | [
"https://Stackoverflow.com/questions/57487274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11924956/"
] | There are times when using Python seems to be very effective, this might be one of those.
```
df['scores'].apply(lambda x: sum(float(i) if len(x) > 0 else np.nan for i in x.split(',')))
0 NaN
1 NaN
2 0.359982
3 0.359982
4 -0.000646
5 0.003793
6 0.856057
``` | You can just do `str.split`
```
df.scores.str.split(',',expand=True).astype(float).sum(1).mask(df.scores.isnull())
0 NaN
1 NaN
2 0.359982
3 0.359982
4 -0.000646
5 0.003793
6 0.856057
dtype: float64
``` | 11,830 |
48,176,802 | I'm very new to work with `xlsxwriter` in python. I have created a scraper in python and it is working flawlessly. However, when I try to write these data in an excel file using `xlsxwriter` I get stuck. What I have written so far can create an excel file and write the last populated data derived from the for loop. How... | 2018/01/09 | [
"https://Stackoverflow.com/questions/48176802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9189799/"
] | 1. Each time through the first `for` loop, you overwrite `data`, so only the last thing assigned survives. This could be addressed by moving your second `for` loop to be inside the first, so it gets called for each value of `data`.
2. If you want things to be in different columns, you need to use different values for `... | As Scott Hunter noted, your overwriting your data, which is stored just fine as a tuple in your data variable. However, it seems like your issue is in your for loop, where you're only adding to row within each block, which explains why your code is traveling only vertically in your spread sheet. Perhaps rearranging thi... | 11,833 |
61,715,377 | So I have a docker project, which is some kind of Python pytest that runs subprocess on an executable file as a blackbox test. I would like to build the container, and then run it each time by copying the executable file to a dedicated folder inside the container WORKDIR (e.g. exec/). But I am not sure how to do it.
... | 2020/05/10 | [
"https://Stackoverflow.com/questions/61715377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4930109/"
] | 'Week' in mysql has 2 inputs: date and week type. By default it's equal 0. That means week starts from sunday. Try this code:
```
SELECT IFNULL(SUM(rendeles_dbszam),0) as eladott_pizzak_szama FROM rendeles WHERE WEEK(rendeles_idopont) = WEEK(CURRENT_DATE(),1)
``` | You can use this little formula to get the Monday starting the week of any given DATE, DATETIME, or TIMESTAMP object.
```
FROM_DAYS(TO_DAYS(datestamp) -MOD(TO_DAYS(datestamp) -2, 7))
```
I like to use it in a stored function named `TRUNC_MONDAY(datestamp)` defined like this.
```
DELIMITER $$
DROP FUNCTION IF EXIST... | 11,834 |
40,920,564 | I am using two different `HTTP POST` utilities ([poster](https://addons.mozilla.org/en-US/firefox/addon/poster/) out of Firefox as well as `Python` [requests](http://docs.python-requests.org/en/master/) API) to post a simple `SPARQL` insert to `Virtuoso`.
My URL is: `http://localhost:8890/sparql`
My request parameter... | 2016/12/01 | [
"https://Stackoverflow.com/questions/40920564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1312080/"
] | I stopped by this question days ago trying to achieve the same with `curl`. Since it is a powerful (and far more convenient) alternative to browser extensions, here is the formulation that eventually proved successful:
```
curl -X POST \
-H "Content-Type:application/sparql-update" \
-H "Accept:text/html" \
... | There are many aspects to this "question" making it difficult to provide a simple answer, suitable to this site. This is one of the reasons I suggested the mailing list, which is better suited to conversational and/or multi-facet assistance.
* Have you tried using `curl` as most of our examples do?
* Looking at the [P... | 11,835 |
20,688,034 | Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env... | 2013/12/19 | [
"https://Stackoverflow.com/questions/20688034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3016020/"
] | Another symptom of this problem for me was if I went into the python console of my virtualenv and did `import ssl` it would error out. Turns out my virtualenv wasn't using the `brew` version of python, just the default install on my machine. No clue why the default install suddenly stopped working, but here's how I fix... | In many cases this is caused by an out of date virtualenv, here's a script to regenerate your virtualenv(s): <https://gist.github.com/WoLpH/fb98f7dc6ba6f05da2b8>
Simply copy it to a file (downloadable link above) and execute it like this: `zsh -e recreate_virtualenvs.sh <project_name>`
```
#!/bin/zsh -e
if [ ! -d "$... | 11,840 |
1,045,906 | I have worked with pyCurl in the past and have it working with my system default python install. However, I have a project that requires python to be more portable and I am using ActivePython-2.6.
I have had no problems installing any other modules so far, but am getting errors installing pyCurl.
The error:
```
Sea... | 2009/06/25 | [
"https://Stackoverflow.com/questions/1045906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124485/"
] | I couldn't find a curl-config to add to the path, which makes sense as it's not a module that can be called (as far as I can tell)
The answer ended up being a bit of a hack, but it works.
As I had pyCurl working in my native python2.6 install, I simply copied the curl and pycurl items from the native install into th... | It looks like `curl-config` isn't in your path. Try running it from the command line and adjust the `PATH` environment variable as needed so that Python can find it. | 11,850 |
11,696,691 | I have a Bash script (Bash 3.2, Mac OS X 10.8) that invokes multiple Python scripts in parallel in order to better utilize multiple cores. Each Python script takes a really long time to complete.
The problem is that if I hit Ctrl+C in the middle of the Bash script, the Python scripts do not actually get killed. How ca... | 2012/07/27 | [
"https://Stackoverflow.com/questions/11696691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1424877/"
] | You can't use this structure:
```
do
{
window.setTimeout(fadeIn,1000);
} while(done == false);
```
Because the code in the `setTimeout()` runs sometime LATER, your value of done will NEVER be changed and this loop will run forever. And, as long as it runs, the `setTimeout()` never gets to fire either (because ja... | Remember that javascript is single-threaded, so your setTimeout'et functions will not be called until it is finished running the current script. Which will never happen since you're in a loop that's never gonna end (untill you're out of memory from all those setTimeout's). Just call setTimeout once and let the function... | 11,855 |
19,489,132 | What is the proper way to pass values of string variables to Popen function in Python? I tried the below piece of code
```
var1 = 'hello'
var2 = 'universe'
p=Popen('/usr/bin/python /apps/sample.py ' + '"' + str(eval('var1')) + ' ' + '"' + str(eval('var2')), shell=True)
```
and in sample.py, below is the code
```
pr... | 2013/10/21 | [
"https://Stackoverflow.com/questions/19489132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2663585/"
] | This should work:
```
p = Popen('/usr/bin/python /apps/sample.py {} {}'.format(var1, var2), shell=True)
```
Learn about [string formatting](http://docs.python.org/2/library/string.html#format-examples) .
Second, passing arguments to scripts has its quirks: <http://docs.python.org/2/library/subprocess.html#subproces... | ```
var1 = 'hello'
var2 = 'universe'
p=Popen("/usr/bin/python /apps/sample.py %s %s"%(str(eval('var1')), str(eval('var2'))), shell=True)
```
Passing format specifier is nice way to do it. | 11,856 |
48,234,112 | I want to print all elements in this list in reversed order and every element in this list must be on a new line.
For example if the list is ['i', 'am', 'programming', 'with', 'python'] it should print out:
python
with
programming
am
i
What is the best way to do this?
```
def list():
words = []
while True:
... | 2018/01/12 | [
"https://Stackoverflow.com/questions/48234112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9160869/"
] | You don't need to convert to a data table for every step, it would be easier to query if you moved away from that.
```
var query =
from row in dt.AsEnumerable()
group new
{
premA = row.Field<decimal>("PREM_A"),
premB = row.Field<decimal>("PREM_B"),
} by row.Field<string>("ID").Trim() in... | Also:
```
var resultsDt = dt.AsEnumerable()
.GroupBy(row => row.Field<string>("ID"))
.Select(grp =>new {Id= grp.Key,
PREM_A= grp.Sum(r => r.Field<decimal>("PREM_A")),
PREM_B=grp.Sum(r... | 11,857 |
64,802,573 | I am trying to get the most basic of OpenAPI server to work as expected. It works as expected with auto-generated python-flask but not with aspnet where exceptions being raised on queries occurs.
What extra steps are required to get the aspnet server to respond correctly to queries?
The YAML is as below:
```
openapi... | 2020/11/12 | [
"https://Stackoverflow.com/questions/64802573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133232/"
] | You can set a **cookie** for detection users; for example, for the first, I visit your store, you set a cookie with **GUID** value for me, now when I order something, you use my GUID as an identifier to track my order. | add AllowAnonymous attribute to actions or controllers. Then user don't need to do log in.
```
[
[AllowAnonymous]
public class Orders: Controller
{
[AllowAnonymous]
public ActionResult PlaceOrder()
{
}
public ActionResult Get()
{
}
... | 11,858 |
325,463 | I've a python script that has to launch a shell command for every file in a dir:
```
import os
files = os.listdir(".")
for f in files:
os.execlp("myscript", "myscript", f)
```
This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python... | 2008/11/28 | [
"https://Stackoverflow.com/questions/325463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28582/"
] | >
> subprocess: The `subprocess` module
> allows you to spawn new processes,
> connect to their input/output/error
> pipes, and obtain their return codes.
>
>
>
<http://docs.python.org/library/subprocess.html>
Usage:
```
import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)... | use spawn
```
import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
``` | 11,859 |
46,138,803 | I'm trying the tutorial [Using Cloud Datastore with Python](https://cloud.google.com/python/getting-started/using-cloud-datastore), but when I run:
```
virtualenv -p python3 env
```
I got an error:
```
The path python3 (from --python=python3) does not exist
```
I checked the python version by running:
```
python... | 2017/09/10 | [
"https://Stackoverflow.com/questions/46138803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646732/"
] | After reading this [tutorial](https://cloud.google.com/python/setup), I found the workaround for my case:
```
virtualenv --python "C:\\Anaconda3\\python.exe" env
``` | If `python --V` is showing a version greater than 3, then why not try:
```
virtualenv -p python env
```
instead? The value of the `p` flag is simply referring to the version of python you're wanting to create the virtual environment with. In this case, `python` is greater than version 3. | 11,869 |
53,495,570 | I need to install `graph-tool` from source, so I add in my Dockerfile this:
```
FROM ubuntu:18.04
RUN git clone https://git.skewed.de/count0/graph-tool.git
RUN cd graph-tool && ./configure && make && make install
```
as it written [here](https://git.skewed.de/count0/graph-tool/wikis/Installation-instructions#manual... | 2018/11/27 | [
"https://Stackoverflow.com/questions/53495570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9098575/"
] | You need to run **autogen.sh** first, it will generate **configure** file
P.S. Make sure you install libtool
```
apt-get install libtool
``` | You have to install the prerequisites first.
```
RUN apt update && apt install -y --no-install-recommends \
make \
build-essential \
g++ \
....
```
Don't forget to clean up and remove temp/unnecessary files! | 11,875 |
19,768,456 | I stumbled upon a behaviour in python that I have a hard time understanding. This is the proof-of-concept code:
```
from functools import partial
if __name__ == '__main__':
sequence = ['foo', 'bar', 'spam']
loop_one = lambda seq: [lambda: el for el in seq]
no_op = lambda x: x
loop_two = lambda seq: [p... | 2013/11/04 | [
"https://Stackoverflow.com/questions/19768456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146792/"
] | Why don't you use JNA API `http://www.java2s.com/Code/Jar/j/Downloadjna351jar.htm` to load native library? Once you putted into your project classpath, you add this code
`NativeLibrary.addSearchPath("libtesseract302", "your native lib path");` make sure you have this libtesseract302.dll file, normally it is located at... | A few days ago I ran into the same error message when trying to load a C++ DLL with JNA. It turned out that the cause was a missing DLL that my DLL depended on.
In my case it was the MS Visual Studio 2012 redistributable, which I then downloaded and installed on the machine and the problem was gone. Try using **Depend... | 11,876 |
49,203,174 | i am trying to install Home Automatization (<https://home-assistant.io>) on my Synology. I've installed python via the synology packaging system, i've done basic setup (<https://home-assistant.io/docs/installation/synology/>) but when i try to run the daemon i see this in console:
*homeassistant requires Python '>=3.5... | 2018/03/09 | [
"https://Stackoverflow.com/questions/49203174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9469908/"
] | I faced exactly the same issue where I needed to keep previous user answers for a conversation. Take a look at [Handler](https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.handler.html]) documentation which is a base class for all handlers. It has parameter called pass\_user\_data. When set to True it pa... | I think the accepted solution is deprecated -
<https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.handler.html>
>
> pass\_user\_data and pass\_chat\_data determine whether a dict you can use to keep any data in will be sent to the callback function. Related to either the user or the chat that the upda... | 11,886 |
48,971,320 | This may be a very easy question but I'm new to python and I've searched the net however I couldn't solve the problem. I have a csv file which I need to search for a specific word in the columns of its first row. How can I do that? | 2018/02/25 | [
"https://Stackoverflow.com/questions/48971320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9201115/"
] | I used the default csv module of python to read a csv file line by line. Since you specified that we have to search only in the first row, that's why I used break-to stop execution after searching the first row of the csv. You can remove the break, to search throughout the csv. Hope this works.
```
import csv
a='abc' ... | ```
import csv
a='abc' #String that you want to search
with open("testing.csv") as f_obj:
reader = csv.reader(f_obj, delimiter=',')
for line in reader: #Iterates through the rows of your csv
print(line) #line here refers to a row in the csv
if a in str(line): #If the strin... | 11,887 |
819,396 | I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.
Is there a straightforward way to open up the files using the correct file encodi... | 2009/05/04 | [
"https://Stackoverflow.com/questions/819396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100758/"
] | Use the [chardet](http://chardet.feedparser.org/) library to detect the encoding. | You can check for the [BOM](http://en.wikipedia.org/wiki/Byte-order_mark "BOM") at the beginning of the file to check whether it's UTF.
Then [unicode.decode](http://docs.python.org/library/stdtypes.html#str.decode) accordingly (using one of the [standard encodings](http://docs.python.org/library/codecs.html#standard-e... | 11,888 |
63,141,133 | I'm new to python and webscraping.
I'm trying to extract the text from a list that starts with `"a href"`.
The whole list is in a variable named `team"`.
If I write `team[0].a.text` I get the first text.
But when I do `team[0:14].a.text` I get this response:
```
AttributeError: 'list' object has no attribute 'a'`
`... | 2020/07/28 | [
"https://Stackoverflow.com/questions/63141133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14011583/"
] | I hope this simple example helps you udnerstand on your errors more.
**If I say `qjogos = (int(qtjog_entry.get()))` at the main block, like:**
```
from tkinter import *
root = Tk()
def click():
pass
qtjog_entry = Entry(root)
qtjog_entry.pack()
qjogos = (int(qtjog_entry.get()))
b = Button(root,text='Click me'... | It looks like `self.qtjog_entry.get()` returns an empty string; you can't use `int()` on an empty string. Without having more context, it's hard to tell exactly what's wrong here. | 11,890 |
11,254,769 | Here is the story.
I have a bunch of stored procedures and all have their own argument types.
What I am looking to do is to create a bit of a type safety layer in python so I can make sure all values are of the correct type before hitting the database.
Of course I don't want to write up the whole schema again in ... | 2012/06/29 | [
"https://Stackoverflow.com/questions/11254769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/537925/"
] | If you want the Python type classes, like you might get from a `SQLALchemy` column object, you'll need to build and maintain your own mapping. `psycopg2` doesn't have one, even internally.
But if what you want is a way to get from an `oid` to a function that will convert raw values into Python instances, `psycopg2.ext... | The mapping of postgres types and python types is given [here](http://packages.python.org/psycopg2/usage.html). Does that help?
Edit:
When you read a record from a table, the postgres (or any database) driver will automatically map the record column types to Python types.
```
cur = con.cursor()
cur.execute("SELECT * ... | 11,891 |
34,538,890 | I have a question which is not really clear in python documentation (<https://docs.python.org/2/library/stdtypes.html#set.intersection>).
When using set.intersection the resulting set contains the objects from current set or from other? In the case that both objects have same value but are different objects in memory.... | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1936538/"
] | What objects are used varies, if the sets are the same size the intersecting elements from b, if b has more elements then the objects from a are returned:
```
i = "$foobar" * 100
j = "$foob" * 100
l = "$foobar" * 100
k = "$foob" * 100
print(id(i), id(j))
print(id(l), id(k))
a = {i, j}
b = {k, l, 3}
inter = a.intersec... | One thing you could do is instead use python dictionaries. Access is still O(1), elements are easy to access, and a simple loop such as follows can get the intersection feature:
```
res=[]
for item in dict1.keys():
if dict2.has_key(item):
res.append(item)
```
The advantage here is you have full control of wha... | 11,892 |
64,839,088 | I'm trying to use the OpenCV Stitcher class for putting two images together. I ran the simple example provided in the answer to this [question](https://stackoverflow.com/questions/34362922/how-to-use-opencv-stitcher-class-with-python) with the same koala images, but it returns `(1, None)` every time. I've tried this on... | 2020/11/14 | [
"https://Stackoverflow.com/questions/64839088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7129536/"
] | Try changing the default pano confidence threshold using `setPanoConfidenceThresh()`. By default it's 1.0, and apparently it results in the stitcher thinking that it has failed.
Here is the full example that works for me. I used that pair of koala images as well, and I am on opencv 4.2.0:
```
stitcher = cv2.Stitcher.... | Try rescaling the images to 0.6 and 0.6 , by using the resize. For some reason I got the result only at those values. | 11,893 |
64,938,027 | Can I indicate a specific dictionary shape/form for an argument to a function in python?
Like in typescript I'd indicate that the `info` argument should be an object with a string `name` and a number `age`:
```js
function parseInfo(info: {name: string, age: number}) { /* ... */ }
```
Is there a way to do this with ... | 2020/11/20 | [
"https://Stackoverflow.com/questions/64938027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6826164/"
] | In Python 3.8+ you could use the [alternative syntax](https://www.python.org/dev/peps/pep-0589/#alternative-syntax) to create a [TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict):
```
from typing import TypedDict
Info = TypedDict('Info', {'name': str, 'age': int})
def parse_info(info: Info):... | Perhaps you could do the following:
```
def assertTypes(obj, type_obj):
for t in type_obj:
if not(t in obj and type(obj[t]) == type_obj[t]):
return False
return True
def parseInfo(info):
if not assertTypes(info, {"name": str, "age": int}):
print("INVALID OBJECT FORMAT")
... | 11,894 |
22,328,160 | I am converting many obscure date formats from an old system. The dates are unpacked/processed as strings and converted into ISO 8601 format.
This particular function attempts to convert YYMMDD0F to YYYYMMDD -- function name says it all. Dates from the year 2000 make this messy and clearly this is not the most python... | 2014/03/11 | [
"https://Stackoverflow.com/questions/22328160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1645914/"
] | How about this one:
```
SELECT ID, Team, DPV, DPT, DPV-DPT AS Difference FROM e2teams
``` | Something like this?
```
SELECT
ID,
Team,
DPV,
DPT,
(DPV - DPT) as Difference
FROM
e2teams
```
You can find more information **[here](https://dev.mysql.com/doc/refman/5.0/en/arithmetic-functions.html)** | 11,895 |
12,444,942 | I'm doing an evolution experiment using python and pygame, however that is unimportant, it is one function that is not working and id like you to have a look at.
The error message I'm getting is float object is not callable. It says the problem is in line 205 which is calling the function from line 51.
I will post a... | 2012/09/16 | [
"https://Stackoverflow.com/questions/12444942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339482/"
] | Line 51:
```
def distance(self,listx,listy):
```
Line 55:
```
self.distance=(((self.x-self.tcentrex)**2) + ((self.y-self.tcentrey)**2))**0.5
```
You can't have `self.distance` be both a method and a variable and expect things to work properly.
When line 55 is executed (during the first time the `distance()` meth... | In line 55, within the `distance` method, you assign a float value to `self.distance`. So after you call `distance` once, the attribute `distance` on that object refers to a float, which is not callable. | 11,898 |
55,174,991 | Attempting to convert this EGCD equation into python.
```
egcd(a, b) = (1, 0), if b = 0
= (t, s - q * t), otherwise, where
q = a / b (note: integer division)
r = a mod b
(s, t) = egcd(b, r)
```
The test I used was egcd(5, 37) which should return (15,-2) but is returning (19.5, -5.135135135135135)
My code is:
```
... | 2019/03/15 | [
"https://Stackoverflow.com/questions/55174991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10687320/"
] | `a / b` in Python 3 is "true division" the result is non-truncating floating point division even when both operands are `int`s.
To fix, either use `//` instead (which is floor division):
```
q = a // b
```
or [use `divmod`](https://docs.python.org/3/library/functions.html#divmod) to perform both division and remain... | Change `q = a / b` for `q = a // b` | 11,899 |
8,117,249 | I think I might be repeating the question but I didn't find any of the answers suited to my requirement.
Pardon my ignorance.
I have a program running which continuously spits out some binary data from a server.It never stops until it's killed.
I want to wrap it in a python script to read the output and process it as... | 2011/11/14 | [
"https://Stackoverflow.com/questions/8117249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044911/"
] | Read with a length limit:
```
proc = subprocess.Popen(args, stdin=None, stdout=subprocess.PIPE, stderr=None)
while True:
chunk = proc.stdout.read(1024)
# chunk is <= 1024 bytes
```
---
This is the code from your comment, slightly modified. It works for me:
```
import subprocess
class container(object):
... | You could run the other program with its output directed to a file and then use Python's *f.readline()* to tail the file. | 11,900 |
54,469,599 | Here's the code, it's from <https://plot.ly/python/line-and-scatter/>
=====================================================================
```
import plotly.plotly as py
import plotly.graph_objs as go
# Create random data with numpy
import numpy as np
N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.ra... | 2019/01/31 | [
"https://Stackoverflow.com/questions/54469599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9493894/"
] | You can try this code:
```
Sub Sample()
' Define object variables
Dim listRange As Range
Dim cellValue As Range
' Define other variables
Dim itemsQuantity As Integer
Dim stringResult As String
Dim separator As String
Dim counter As Integer
' Define the range where the options are... | Column to Sentence
==================
Features
--------
* At least two cells of data in Range, or else "" is returned.
* Only first column of Range is processed (`Resize`).
Usage in Excel
--------------
[](https://i.stack.imgur.com/FnDPU.jpg)
The ... | 11,902 |
6,978,204 | I made a set of XMLRPC client-server programs in python and set up a little method for authenticating my clients. However, after coding pretty much the whole thing, I realized that once a client was authenticated, the flag I had set for it was global in my class i.e. as long as one client is authenticated, all clients ... | 2011/08/08 | [
"https://Stackoverflow.com/questions/6978204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400612/"
] | Something like this would work:
```
class SomeClass(object):
authenticated = {}
def authenticate(self, username, password):
#do something here
if authenticate(username, password):
# make unique token can probably be just a hash
# of the millisecond time and the username
... | You have to decide. If you really want to use one instance for all clients, you have to store the "authenticated" state somewhere else. I am not familiar with SimpleXMLRPCServer(), but if you could get the conection object somewhere, or at least its source address, you could establish a set() where all authenticated cl... | 11,904 |
70,102,585 | I'm [using Nikola](https://getnikola.com/), a static website generator, to build a website. I am automating its building through [Github Actions](https://github.com/getnikola/nikola-action). I also wanted to use [Pandoc](https://pandoc.org) to help convert my markdown to html, but I noted that Pandoc was not included i... | 2021/11/24 | [
"https://Stackoverflow.com/questions/70102585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17501797/"
] | `pandoc` is not a Python package. It is a separate and very powerful command line tool. `nikola` invokes the command line tool to do its work. You need to install it using the `sudo apt install pandoc` command line that they suggest. | I discovered that the system was unable to find Pandoc as the entirety of the project was run in a Docker container; I had previously installed Pandoc on the system itself and failed. I was able to solve the problem by modifying the [shell script](https://github.com/getnikola/nikola-action/blob/master/entrypoint.sh) to... | 11,905 |
25,851,090 | The results from the code below in Python 2.7 struck me as a contradiction. The `is` operator is supposed to work with object identity and so is `id`. But their results diverge when I'm looking at a user-defined method. Why is that?
```
py-mach >>class Hello(object):
... def hello():
... pass
...
py-mach >>Hello.h... | 2014/09/15 | [
"https://Stackoverflow.com/questions/25851090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1988435/"
] | The Python documentation for the [id function](https://docs.python.org/2/library/functions.html#id) states:
>
> Return the "identity" of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. **Two objects with non-overlapping lifetimes may h... | This is a "simple" consequence of how the memory allocator works. It is very similar to the case:
```
>>> id([]) == id([])
True
```
Basically python doesn't guarantee that ID's don't get reused -- it only guarantees that the id is unique *as long as the object is alive*. In this case, the first object being passed t... | 11,906 |
58,040,654 | I have this json dataset. From this dataset i only want "column\_names" keys and its values and "data" keys and its values.Each values of column\_names corresponds to values of data. How do i combine only these two keys in python for analysis
```
{"dataset":{"id":42635350,"dataset_code":"MSFT","column_names":
["Date",... | 2019/09/21 | [
"https://Stackoverflow.com/questions/58040654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10331731/"
] | ```
data = {
"dataset": {
"id":42635350,"dataset_code":"MSFT",
"column_names": ["Date","Open","High","Low","Close","Volume","Dividend","Split","Adj_Open","Adj_High","Adj_Low","Adj_Close","Adj_Volume"],
"frequency":"daily",
"type":"Time Series",
"data":[
["2017-12-28",85.9,85.93... | The following snippet should work for you
```py
import pandas as pd
df = pd.DataFrame(data['dataset']['data'],columns=data['dataset']['column_names'])
```
Check the following link to learn more
<https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html> | 11,907 |
21,585,730 | I want to launch a program from python, in this case abaqus (a finite element analysis software), using:
```
os.system('abaqus job=' + JobName + ' user=' + UELname + ' interactive')
```
After say 5 minutes running the program I want to execute a python script that monitors some output files generated by abaqus. If a... | 2014/02/05 | [
"https://Stackoverflow.com/questions/21585730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1262767/"
] | Did you try [subprocess](http://docs.python.org/2/library/subprocess.html) module? | Logic seems fine, i would suggest you to use [subprocess](http://docs.python.org/2/library/subprocess.html), instead of os.system. Since you are calling commands, you can run all these commands at once like this
```
cmdToRun = '\'abaqus job=\' + JobName + \' user=\' + UELname + \' interactive\' ; sleep 300; abaqus cae... | 11,909 |
749,680 | I tried using the Process class as always but that didn't work. All I am doing is trying to run a Python file like someone double clicked it.
Is it possible?
EDIT:
Sample code:
```
string pythonScript = @"C:\callme.py";
string workDir = System.IO.Path.GetDirectoryName ( pythonScript );
Process proc = new Process ... | 2009/04/14 | [
"https://Stackoverflow.com/questions/749680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51816/"
] | Here's my code for executing a python script from C#, with a redirected standard input and output ( I pass info in via the standard input), copied from an example on the web somewhere. Python location is hard coded as you can see, can refactor.
```
private static string CallPython(string script, string pyArgs, str... | [Process.Start](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx) should work. if it doesn't, would you post your code and the error you are getting? | 11,910 |
20,503,671 | Ok so I'm trying to run a C program from a python script. Currently I'm using a test C program:
```
#include <stdio.h>
int main() {
while (1) {
printf("2000\n");
sleep(1);
}
return 0;
}
```
To simulate the program that I will be using, which takes readings from a sensor constantly.
Then ... | 2013/12/10 | [
"https://Stackoverflow.com/questions/20503671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2836175/"
] | Your program isn't hung, it just runs very slowly. Your program is using buffered output; the `"2000\n"` data is not being written to stdout immediately, but will eventually make it. In your case, it might take `BUFSIZ/strlen("2000\n")` seconds (probably 1638 seconds) to complete.
After this line:
```
printf("2000\n... | See [readline docs](http://docs.python.org/2/library/io.html#io.TextIOBase.readline).
Your code:
```
process.stdout.readline
```
Is waiting for EOF or a newline.
I cannot tell what you are ultimately trying to do, but adding a newline to your printf, e.g., `printf("2000\n");`, should at least get you started. | 11,913 |
55,352,756 | From a user given input of job description, i need to extract the keywords or phrases, using python and its libraries. I am open for suggestions and guidance from the community of what libraries work best and if in case, its simple, please guide through.
Example of user input:
`user_input = "i want a full stack deve... | 2019/03/26 | [
"https://Stackoverflow.com/questions/55352756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10486777/"
] | Well, a good keywords set is a good method. But, the key is how to build it. There are many way to do it.
Firstly, the simplest one is searching open keywords set in the web. It's depend on your luck and your knowledge. Your keywords (likes "python, java, machine learing") are common tags in Stackoverflow, Recruitment... | Well, i answered my own question. Thanks anyways for those who replied.
```
keys = ['python', 'full stack developer','java','machine learning']
keywords = []
for i in range(len(keys)):
word = keys[i]
if word in keys:
keywords.append(word)
else:
continue
print(keywords)
```
Output was as ... | 11,916 |
55,373,000 | I wanted to import `train_test_split` to split my dataset into a test dataset and a training dataset but an import error has occurred.
I tried all of these but none of them worked:
```
conda upgrade scikit-learn
pip uninstall scipy
pip3 install scipy
pip uninstall sklearn
pip uninstall scikit-learn
pip install sklea... | 2019/03/27 | [
"https://Stackoverflow.com/questions/55373000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11264930/"
] | `train_test_split` isn't in `preprocessing`, it is in `model_selection` and `cross_validation`, so you meant:
```
from sklearn.model_selection import train_test_split
```
Or:
```
from sklearn.cross_validation import train_test_split
``` | test\_train\_split is not present in preprocessing.
It is present in model\_selection module so try.
```
from sklearn.model_selection import train_test_split
```
it will work. | 11,917 |
46,210,757 | Assume I have a python dictionary with 2 keys.
```
dic = {0:'Hi!', 1:'Hello!'}
```
What I want to do is to extend this dictionary by duplicating itself, but change the key value.
For example, if I have a code
```
dic = {0:'Hi!', 1:'Hello'}
multiplier = 3
def DictionaryExtend(number_of_multiplier, dictionary):
... | 2017/09/14 | [
"https://Stackoverflow.com/questions/46210757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3794041/"
] | It's not immediately clear why you might want to do this. If the keys are always consecutive integers then you probably just want a list.
Anyway, here's a snippet:
```
def dictExtender(multiplier, d):
return dict(zip(range(multiplier * len(d)), list(d.values()) * multiplier))
``` | I don't think you need to use inheritance to achieve that. It's also unclear what the keys should be in the resulting dictionary.
If the keys are always consecutive integers, then why not use a list?
```
origin = ['Hi', 'Hello']
extended = origin * 3
extended
>> ['Hi', 'Hello', 'Hi', 'Hello', 'Hi', 'Hello']
extended... | 11,918 |
40,914,325 | I'm beginner to python and I would like to start with automation.
Below is the task I'm trying to do.
```
ssh -p 2024 root@10.54.3.32
root@10.54.3.32's password:
```
I try to ssh to a particular machine and its prompting for password. But I have no clue how to give the input to this console. I have tried this
```... | 2016/12/01 | [
"https://Stackoverflow.com/questions/40914325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3275349/"
] | I have implemented through pexpect. You may need to `pip install pexpect` before you run the code:
```
import pexpect
from pexpect import pxssh
accessDenied = None
unreachable = None
username = 'someuser'
ipaddress = 'mymachine'
password = 'somepassword'
command = 'ls -al'
try:
ssh = pexpect.spawn('ssh %s@%s' % (... | I have implemented through paramiko. You may need to `pip install paramiko` before you run the code:
```
import paramiko
username = 'root'
password = 'calvin'
host = '192.168.0.1'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=str(username), password=st... | 11,923 |
42,207,798 | When I using lxml library in python to get data on a html page (Youtube video title), It not return text correctly It return a text Like this "à·à·à¶½à¶±à·à¶§à¶ºà¶±à"
Here my code,
```
page = requests.get("https://www.youtube.com/watch?v=MZMapfEg5g8")
source = html.fromstring(page.content)
links = source.xpath('//li... | 2017/02/13 | [
"https://Stackoverflow.com/questions/42207798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6440193/"
] | Because your `on` clause is `1 = 0` nothing matches, so all rows are inserted.
Changing your `on` clause to `a = b` will yield your expected results of `2,4,5,1,3`.
rextester for `on a = b`: <http://rextester.com/OPLL86727>
It might be helpful to be more explicit with aliasing your source and target:
```
declare @t... | You are matching on 1=0 which will always fire the insert. You should use On Source.a = @t2.b | 11,924 |
55,877,915 | I am trying to gather weather data from an API and then store that Data in a Database for use later.
I have been able to access the data and print it out using a for loop, but I would like to assign each iteration of that for loop to a variable to be stored in a different location in a database.
How would I be able t... | 2019/04/27 | [
"https://Stackoverflow.com/questions/55877915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6908101/"
] | IMO you need some sort of dynamic length data structure to which you can append the data inside a `for` loop and then access it using `index`.
Therefore, you can create a `list` and then append all the values of `for` lop into it as shown below:
```
list = []
for i in dailyTHigh:
list.append(i['temperatureHig... | IMO you can use a stack data structure and store the data in the FILO (First In Last Out) form. This way, you can also manage data in more efficient way, even it get's bigger in size (in future) | 11,925 |
38,326,357 | **following is my code in python for the scraping and output efforts**
```
html = urlopen("http://www.imdb.com/news/top")
wineReviews = BeautifulSoup(html)
lines = []
for headLine in imdbNews.findAll("h2"):
#headLine.encode('ascii', 'ignore')
imdb_news = headLine.get_text()
lines.append(imdb_news)
... | 2016/07/12 | [
"https://Stackoverflow.com/questions/38326357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6578757/"
] | To avoid reflection, you can use a generic method:
```
public void DoSomething(MyClass a) => MakeSomeStaff(a, () => { /* Do method body */ });
private void MakeSomeStaff<T>(T item, Action action) where T: class
{
if (item == null)
throw new Exception();
action();
}
``` | **EDIT: Had an idea that abuses operator overloading, original answer at the bottom:**
Use operator overloading to throw on null
```
public struct Some<T> where T : class {
public T Value { get; }
public Some(T value)
{
if (ReferenceEquals(value, null))
throw new Exception();
V... | 11,928 |
25,824,417 | Before Django 1.7 I used to define a per-project `fixtures` directory in the settings:
```
FIXTURE_DIRS = ('myproject/fixtures',)
```
and use that to place my `initial_data.json` fixture storing the default **groups** essential for the whole project. This has been working well for me as I could keep the design clean... | 2014/09/13 | [
"https://Stackoverflow.com/questions/25824417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2263517/"
] | If you absolutely want to use fixtures, just use `RunPython`and `call_command` in your data migrations.
```
from django.db import migrations
from django.core.management import call_command
def add_data(apps, schema_editor):
call_command('loaddata', 'thefixture.json')
def remove_data(apps, schema_editor):
cal... | I recommend using factories instead of fixtures, they are a mess and difficult to maintain, better to use FactoryBoy with Django. | 11,929 |
28,250,578 | how to set proper document root for vagrant. Now it takes docroot from the wrong place. I'm trying to run laravel project, so it has to be not /var/www/project but /vae/www/project/public...
My YAML file:
```
---
vagrantfile-local:
vm:
box: puphpet/debian75-x64
box_url: puphpet/debian75-x64
... | 2015/01/31 | [
"https://Stackoverflow.com/questions/28250578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470912/"
] | I can see you have:
`vhosts:
495wa1uc3p0z:
servername: projectx.dev
serveraliases:
- www.projectx.dev
docroot: /var/www/projectx/public
port: '80'
setenv:
- 'APP_ENV dev'
directories:
8yngfatheg7u:
provider: directory
path: /var/www/projectx/public
options:
- Indexes
- FollowSymlinks
- MultiViews
allo... | It was right that I needed to run "vagran provision" after modifications, but another thing that config should look like this
```
vhosts:
495wa1uc3p0z:
servername: projectx.dev
docroot: /var/www/projectx/public
port: '80'
setenv:
- 'APP_ENV dev'
... | 11,930 |
57,417,939 | I am currently running a python script in a batch file. In the python, I have some print function to monitor the running code. The printed information then will be shown in the command window. In the meantime, I also want to save all these print-out text to a log-file, so I can track them in the long run.
Currently, t... | 2019/08/08 | [
"https://Stackoverflow.com/questions/57417939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11730027/"
] | For a better solution in the long run, consider the built in [logging module](https://docs.python.org/3/library/logging.html). You can give multiple destinations, such as stdout and files, log rotation, formatting, and importance levels.
Example:
```py
import logging
logging.basicConfig(filename='log_file', filemode... | Just make a function
```
def print_and_log(text):
print(text)
with open("logfile.txt", "a") as logfile:
logfile.write(text+"\n")
```
Then wherever you need to print, use this function and it will also log. | 11,931 |
47,979,852 | I just do this:
```
t = Variable(torch.randn(5))
t =t.cuda()
print(t)
```
but it takes 5 to 10 minitues,everytime.
I used cuda samples to test bandwidth, it's fine.
Then I used pdb to find which takes the most time.
I find in `/anaconda3/lib/python3.6/site-packages/torch/cuda/__init__`:
```
def _lazy_new(cls, *args... | 2017/12/26 | [
"https://Stackoverflow.com/questions/47979852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9141892/"
] | There’s a cuda version mismatch between the cuda my pytorch was compiled with the cuda I'm running.I divided the official installation commond
>
> conda install pytorch torchvision cuda90 -c pytorch
>
>
>
into two section:
>
> conda install -c soumith magma-cuda90
>
>
> conda install pytorch torchvision -c so... | Try doing it this way:
```
torch.cuda.synchronize()
t = Variable(torch.randn(5))
t =t.cuda()
print(t)
```
Then, it should be *blazing fast* depending on your GPU memory, at least on every *re-run* it should be. | 11,932 |
45,468,073 | I have successfully installed Pandas through Anaconda in PyCharm. Unfortunately when I run Import Pandas this is what I get as the output:
```
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
"/Users/PycharmProjects/Security upload/Security
upload.py"
Traceback (most recent call last):
File "/U... | 2017/08/02 | [
"https://Stackoverflow.com/questions/45468073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7678127/"
] | According to [here](https://github.com/opencobra/cobrapy/issues/490) and [here](https://github.com/awslabs/aws-shell/issues/161), you need to fix your dateutil package.
```
pip uninstall python-dateutil
pip install python-dateutil --upgrade
```
Maybe this:
```
sudo pip uninstall python-dateutil
sudo pip install pyt... | Was facing the same issue and started installing jupyter and got few errors
reinstalling ipython worked for me
```
sudo -H pip install --ignore-installed -U ipython
```
I also needed to reinstall pyzmq
```
sudo -H pip install --ignore-installed -U pyzmq
```
after this I re-ran import pandas in ipython and it wo... | 11,933 |
66,996,203 | I am trying to flip the lat long in a exported csv but am having a hard time getting python to recognize the rows to reorder them. Need the below data to read W#### N#####, W#### N#### so that QGIS's WKT layer import will work correctly later after I finish the formatting for WKT using Linestring().
```
Example Data:
... | 2021/04/08 | [
"https://Stackoverflow.com/questions/66996203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15578731/"
] | -For the `Access Key ID` you can find in `IAM` user management
-The `Secret Access Key` is the private SSH key you have created/you can create to log into your account, you would register the public key on IAM and keep the secret key to use the aws cli
-You can find the `Region` in the information for the bucket that... | * For region -> just check your upper right of the console you can choose any one, the default region when you access a resource from the AWS Management Console is US East (Ohio) (us-east-2).
* For Bucket `s3 -> navigation pane ->buckets -> search your buckets if not then create one in a specific region`. If you want a... | 11,934 |
3,211,031 | ```
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
fo.read(3)
fo.close()
file_open("file_ro.py")
```
I expect above program to return first 3 bytes from file . But it returns nothing. When I ran these in interactive python command prompt - I get expected output! | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246365/"
] | `fo.read()` *returns* the data that was read and you never assign it to anything. You are talking about 'output', but your code isn't supposed to output anything. Are you trying to print those three bytes? In that case you are looking for something like
```
f = open('file_ro.py', 'r')
print f.read(3)
```
You are get... | ```
import sys
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
read_data=fo.read(3)
fo.close()
print read_data
file_open("file.py")
``` | 11,935 |
60,827,864 | I am trying to have a master dag which will create further dags based on my need.
I have the following python file inside the *dags\_folder* in *airflow.cfg*.
This code creates the master dag in database. This master dag should read a text file and should create dags for each line in the text file. But the dags created... | 2020/03/24 | [
"https://Stackoverflow.com/questions/60827864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3211801/"
] | You have 2 options:
1. **Use SubDagOperator**: [Example DAG](https://github.com/apache/airflow/blob/1.10.9/airflow/operators/subdag_operator.py). Use it if your Schedule Interval can be the same.
2. **Write a Python DAG File**: From you master DAG, create Python files in your AIRFLOW\_HOME containing DAGs. You can use... | Have a look at the TriggerDagRunOperator:
<https://airflow.apache.org/docs/stable/_api/airflow/operators/dagrun_operator/index.html>
Example usage:
<https://github.com/apache/airflow/blob/master/airflow/example_dags/example_trigger_controller_dag.py> | 11,938 |
52,345,911 | I'm working on a python(3.6) project in which I need to clone a GitHub repo which will have the directory structure as:
```
|parent_DIR
|--sub_DIR
|file1....
|file2....
|--sub_DIR2
|file1...
```
Now I need to get the following info:
```
1. Parent directory name
2. How many subdirectories are
3. names of... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52345911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644562/"
] | You can try your pop-over viewController's modalPresentationStyle to either `.overCurrentContext` or `.overFullScreen`.
>
> case overCurrentContext:
>
>
>
> >
> > A presentation style where the content is displayed over another view controller’s content.
> >
> >
> >
>
>
>
This means it will present the nex... | You need to set your new view controller's
```
modalPresentationStyle = .overCurrentContext
```
Do this when you initialise your view controller, or in the storyboard. | 11,939 |
37,888,565 | I'm having an issue with ctypes. I think my type conversion is correct and the error isn't making sense to me.
Error on line " arg - ct.c\_char\_p(logfilepath) "
TypeError: bytes or integer address expected instead of str instance
I tried in both python 3.5 and 3.4.
function i'm calling:
```
stream_initialize('stre... | 2016/06/17 | [
"https://Stackoverflow.com/questions/37888565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5344673/"
] | `c_char_p` takes `bytes` object so you have to convert your `string` to `bytes` first:
```
ct.c_char_p(logfilepath.encode('utf-8'))
```
Another solution is using the `c_wchar_p` type which takes a `string`. | *For completeness' sake*:
It is also possible to call it as `stream_initialize(b'stream_log.txt')`. Note the `b` in front of the string, which causes it to be interpreted as a `bytes` object. | 11,940 |
42,441,687 | I use `pyspark.sql.functions.udf` to define a UDF that uses a class imported from a .py module written by me.
```
from czech_simple_stemmer import CzechSimpleStemmer #this is my class in my module
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
...some code here...
def clean_one_raw_doc... | 2017/02/24 | [
"https://Stackoverflow.com/questions/42441687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4985473/"
] | SparkContext.addPyFile("my\_module.py") will do it. | from the spark-submit [documentation](http://spark.apache.org/docs/2.0.1/submitting-applications.html)
>
> For Python, you can use the --py-files argument of spark-submit to add
> .py, .zip or .egg files to be distributed with your application. If
> you depend on multiple Python files we recommend packaging them i... | 11,941 |
47,944,185 | It's my first post, I hope it will be well done.
I'm trying to run the following ZipLine Algo with local AAPL data :
```
import pandas as pd
from collections import OrderedDict
import pytz
from zipline.api import order, symbol, record, order_target
from zipline.algorithm import TradingAlgorithm
data = OrderedDict()... | 2017/12/22 | [
"https://Stackoverflow.com/questions/47944185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9131416/"
] | Only reference and workaround I found regarding this issue is [here](https://github.com/pydata/pandas-datareader/issues/394):
```py
from pandas_datareader.google.daily import GoogleDailyReader
@property
def url(self):
return 'http://finance.google.com/finance/historical'
GoogleDailyReader.url = url
``` | do:
```
pip install fix_yahoo_finance
```
then modify the file: zipline/lib/pythonx.x/site-packages/zipline/data/benchmarks.py
add the following two statements to the file:
```
import fix_yahoo_finance as yf
yf.pdr_override ()
```
then change following instruction:
```
data = pd_reader.DataReader (symbol, 'Goog... | 11,942 |
56,057,132 | I define some func here, it will change all user defined attribtutes into upper case
```
def up(name, parent, attr):
user_defined_attr = ((k, v) for k, v in attr.items() if not k.startswith('_'))
up_attr = {k.upper(): v for k,v in user_defined_attr}
return type(name, parent, up_attr)
```
For example:
``... | 2019/05/09 | [
"https://Stackoverflow.com/questions/56057132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5245972/"
] | Okay, seems like this behaviour cannot be avoided, so you should parse dates manually. But the way to parse it is pretty simple.
If we are parsing date in ISO 8601 format, the mask of date string looks like this:
```
<yyyy>-<mm>-<dd>T<hh>:<mm>:<ss>(.<ms>)?(Z|(+|-)<hh>:<mm>)?
```
1. Getting date and time separately
... | This might be the case when all browsers follow their own standards for encoding date formats (but I am not sure on this part). Anyways a simple fix for this is to apply the `toISOString` method.
```js
const today = new Date();
console.log(today.toISOString());
``` | 11,943 |
19,202,921 | Here is my input:
```
>>> from decimal import Decimal
>>> Decimal('114.3')
Decimal('114.3')
>>> Decimal(114.3)
Decimal('114.2999999999999971578290569595992565155029296875')
```
I thought those two instances of Decimal have to be equal but Decimal with float arg seems to loose precision. Why is this? My python versio... | 2013/10/05 | [
"https://Stackoverflow.com/questions/19202921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699931/"
] | The second line is giving you the exact decimal value of the binary floating-point number which approximates 114.3. This is almost all about binary floating point, not much about Decimal. See [the docs](http://docs.python.org/2/tutorial/floatingpoint.html) for details.
Later: if using Python 3, see [these docs](http:/... | When you do `Decimal(114.3)`, you are creating a regular float object and then passing it to Decimal. The accuracy is lost due to binary floating-point imprecision when the float 114.3 is created, before Decimal ever gets to see it. There's no way to get that accuracy back. That's why Decimal accepts string representat... | 11,944 |
16,739,894 | I've found [this Library](https://github.com/pythonforfacebook/facebook-sdk/) it seems it is the official one, then [found this](https://stackoverflow.com/questions/10488913/how-to-obtain-a-user-access-token-in-python), but everytime i find an answer the half of it are links to [Facebook API Documentation](https://deve... | 2013/05/24 | [
"https://Stackoverflow.com/questions/16739894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861487/"
] | Javascript and PHP can be used as web development languages. You need a web front end for the user to grant permission so that you can obtain the access token.
Rephrased: **You cannot obtain the access token programmatically, there must be manual user interaction**
In Python it will involve setting up a web server, f... | here is a Gist i tried to make using `Tornado` since the answer uses `web.py`
<https://gist.github.com/abdelouahabb/5647185> | 11,945 |
54,958,169 | I have the three following dataframes:
```
df_A = pd.DataFrame( {'id_A': [1, 1, 1, 1, 2, 2, 3, 3],
'Animal_A': ['cat','dog','fish','bird','cat','fish','bird','cat' ]})
df_B = pd.DataFrame( {'id_B': [1, 2, 2, 3, 4, 4, 5],
'Animal_B': ['dog','cat','fish','dog','fish','cat','cat... | 2019/03/02 | [
"https://Stackoverflow.com/questions/54958169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11139882/"
] | Not sure if it is faster or more pythonic, but it avoids the for loop :)
```
import pandas as pd
df_A = pd.DataFrame( {'id_A': [1, 1, 1, 1, 2, 2, 3, 3],
'Animal_A': ['cat','dog','fish','bird','cat','fish','bird','cat' ]})
df_B = pd.DataFrame( {'id_B': [1, 2, 2, 3, 4, 4, 5],
... | You can try the below:
```
df_A.merge(df_B, left_on = ['Animal_A'], right_on = ['Animal_B'] ).groupby(['id_A' ,'id_B']).count().reset_index().merge(df_P).drop('Animal_B', axis = 1).rename(columns = {'Animal_A': 'count'})
``` | 11,948 |
42,282,577 | I have this HTML
```html
<div class="callout callout-accordion" style="background-image: url("/images/expand.png");">
<span class="edit" data-pk="bandwidth_bar">Bandwidth Settings</span>
<span class="telnet-arrow"></span>
</div>
```
I'm trying to select **span** with text = `Bandwidth Settings`, an... | 2017/02/16 | [
"https://Stackoverflow.com/questions/42282577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480164/"
] | One way would be to use `find_element_by_xpath(xpath)` like this:
```
if driver.find_element_by_xpath("//span[contains(.,'Bandwidth Settings')]") is None:
print "Not found"
else:
print "Found"
...
```
For an exact match (as you asked for in your comment), use `"//span[text()='Bandwidth Settings']"`
On your... | The code that you need to use:
```
from selenium.common.exceptions import NoSuchElementException
try:
span = driver.find_element_by_xpath('//span[text()="Bandwidth Settings"]')
print "Found"
except NoSuchElementException:
print "Not found"
```
If you need to select the parent `div` element:
```
div = s... | 11,949 |
24,857,779 | I used os.rename() method to rename the directory in my python script. This script called automatically by the scheduler every day. Sometimes the os.rename() function returns the error,
```
[Error 5] Access is denied
```
But all other times its working fine.
Code,
```
try:
if(os.path.exists(Downloaded_Path)):
... | 2014/07/21 | [
"https://Stackoverflow.com/questions/24857779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553605/"
] | The error means that the user account that the scheduler uses to run the program does not have permissions to rename that directory.
One common reason for the fact that it sometimes works and sometimes does not is that the program creates some of the directories it needs to rename but not others.
* The directories c... | This will also fail if the host names are not "network qualified" the same way.
```
>>> os.renames(r'\\host.domain.com\joan\rocks', r'\\host\joan\jett\rocks')
WindowsError: [Error 5] Access is denied
>>> os.renames(r'\\host\joan\rocks', r'\\host\joan\jett\rocks')
>>>
>>> os.renames(r'\\host.domain.com\joan\rocks', r... | 11,951 |
36,428,178 | Even with the most basic of code, my .txt file is coming out empty, and I can't understand why. I'm running this subroutine in `python 3` to gather information from the user. When I open the .txt file in both notepad and N++, I get an empty file.
Here's my code :
```
def Setup():
fw = open('AutoLoader.txt', 'a')
... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36428178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Try replacing fw.close with fw.close() | It's working on python 3.4
```
def Setup():
fw = open('AutoLoader3.4.txt', 'a+')
x = True
while x == True:
print("Enter new location to enter")
new_entry = str(input('Start with \'web\' if it\'s a web page\n'))
fw.write(new_entry)
y = input('New Data? Y/N\n')
if y == 'N' or y == 'n':
... | 11,957 |
26,506,642 | if d is a dict, python docs provide us with this method:
```
dict.get = get(...)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
```
Another famous pattern is:
```
try:
D[k]:
except:
d
```
But in my benchmarks (done with timeit), i have found that the following approach is the best:
```
... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26506642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3599101/"
] | Looks like the `D[k] if k in D else d` pattern is about twice faster than .get, at least for some usages.
.get
```
$ python -m timeit -s 'D={}; k=xrange(0,100000)' 'D.get(k)'
10000000 loops, best of 3: 0.0934 usec per loop
```
if/else
```
$ python -m timeit -s 'D={}; k=xrange(0,100000)' 'D[k] if k in D else None'
... | Maybe you should give `pypy` a try and compile that on your embedded system. `if-then-else` and `get` have similar results. Some benchmarks:
PyPy:
```
$ pypy3 -m timeit -s 'd={}; k=0' 'd[k] if k in d else None'
1000000000 loops, best of 3: 0.0008 usec per loop
$ pypy3 -m timeit -s 'd={}; k=0' 'd.get(k)' ... | 11,960 |
37,033,709 | I know that it's often [best practice](https://softwareengineering.stackexchange.com/questions/213935/why-use-classes-when-programming-a-tkinter-gui-in-python) to write Tkinter GUI code using object-oriented programming (OOP), but I'm trying to keep things simple because I'm new to Python.
I have written the following... | 2016/05/04 | [
"https://Stackoverflow.com/questions/37033709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6030297/"
] | `MyLabel` is local to `main()` so the way you can not access it that way from `ChangeLabelText()`.
If you do not want to change the design of your program, then you will need to change the definition of `ChangeLabelText()` like what follows:
```
def ChangeLabelText(m):
m.config(text = 'You pressed the button!')
... | *but I'm trying to keep things simple because I'm new to Python* Hopefully this helps in understanding that classes are the simple way, otherwise you have to jump through hoops and manually keep track of many variables. Also, the Python Style Guide suggests that CamelCase is used for class names and lower\_case\_with\_... | 11,961 |
39,026,120 | I have a python string that I need to remove parentheses. The standard way is to use `text = re.sub(r'\([^)]*\)', '', text)`, so the content within the parentheses will be removed.
However, I just found a string that looks like `(Data with in (Boo) And good luck)`. With the regex I use, it will still have `And good lu... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294529/"
] | With the re module (replace the innermost parenthesis until there's no more replacement to do):
```
import re
s = r'Sainte Anne -(Data with in (Boo) And good luck) Charenton'
nb_rep = 1
while (nb_rep):
(s, nb_rep) = re.subn(r'\([^()]*\)', '', s)
print(s)
```
With the [regex module](https://pypi.python.org/py... | First I split the line into tokens that do not contain the parenthesis, for later on joining them into a new line:
```
line = "(Data with in (Boo) And good luck)"
new_line = "".join(re.split(r'(?:[()])',line))
print ( new_line )
# 'Data with in Boo And good luck'
``` | 11,964 |
3,433,806 | I was reading on web2py framework for a hobby project of mine I am doing. I learned how to program in Python when I was younger so I do have a grasp on it. Right now I am more of a PHP dev but kindda loathe it.
I just have this doubt that pops in: Is there a way to use "Vanilla" python on the backend? I mean Vanilla l... | 2010/08/08 | [
"https://Stackoverflow.com/questions/3433806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399621/"
] | There is no reason to do that :) but if you insist you can write on top of [WSGI](http://wsgi.org/wsgi/)
I suggest that you can try a micro-framework such as web.py if u like it Vanilla style | without a framework, you use WSGI. to do this, you write a function `application` like so:
```
def application(environment, start_response):
start_response("200 OK", [('Content-Type', 'text/plain')])
return "hello world"
```
`environment` contains cgi variables and other stuff. Normally what happens is appli... | 11,973 |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | I was facing the same issue and even customizing the log\_dir option using datetime didn't work. Check this page: <https://github.com/tensorflow/tensorboard/issues/2819> which helped me. I just added the 'profile\_batch = 100000000' in this callback as:
TensorBoard(log\_dir=log\_dir, .., profile\_batch = 100000000) | I faced with issue becuase of mixed slashes in tensorboard logdir (on Windows).
This happened when I used:
```
logdir_path = os.path.join(r'D:something\models', 'model1')
```
Solved using:
```
logdir_path = os.path.normpath(os.path.join(r'D:something\models', 'model1'))
callbacks = [tf.keras.callbacks.TensorBoard(... | 11,975 |
58,320,969 | I’m working on the below script on my MacbookAir and I’m unclear where this syntax error comes from and tried searching on google why it breaks at the = sign in the print function.
I understood there are different functions to print and tried many of them. But am unclear if I’m using the correct Python version (both ... | 2019/10/10 | [
"https://Stackoverflow.com/questions/58320969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12194431/"
] | There's a few issues to fix here.
Firstly don't use `id` attributes in content which can be dynamically appended multiple times. You'll end up with duplicate ids which is invalid and will cause issues in your JS. Use common `class` attributes instead.
Secondly you can attach an event handler to all of the elements wi... | You need event delegation for this. Also it's not ideal to use an id with a fixed number for each of your operations. If your table has 1000 rows, you don't want to copy-paste your function 1000 times.
I created an example based on classes:
```js
$(document).ready(function() {
$(".btn-add").click(function() {
... | 11,985 |
14,109,915 | I am currently playing around with an example from the book Violent Python. You can see my implementation [here](https://github.com/igniteflow/violent-python/blob/master/pwd-crackers/unix-pwd-crack.py)
I am now trying to implement the same script in Go to compare performance, note I am completely new to Go. Opening t... | 2013/01/01 | [
"https://Stackoverflow.com/questions/14109915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/343223/"
] | `crypt` is very easy to wrap with cgo, eg
```
package main
import (
"fmt"
"unsafe"
)
// #cgo LDFLAGS: -lcrypt
// #define _GNU_SOURCE
// #include <crypt.h>
// #include <stdlib.h>
import "C"
// crypt wraps C library crypt_r
func crypt(key, salt string) string {
data := C.struct_crypt_data{}
ckey := C.... | E.g.
```
package main
import (
"crypto/des"
"fmt"
"log"
)
func main() {
b, err := des.NewCipher([]byte("abcdefgh"))
if err != nil {
log.Fatal(err)
}
msg := []byte("Hello!?!")
fmt.Printf("% 02x: %q\n", msg, msg)
b.Encrypt(msg, ms... | 11,987 |
21,892,080 | I'm using Python's [Watchdog](http://pythonhosted.org/watchdog/) to monitor a given directory for new files being created. When a file is created, some code runs that spawns a subprocess shell command to run different code to process this file. This should run for every new file that is created. I've tested this out wh... | 2014/02/19 | [
"https://Stackoverflow.com/questions/21892080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3329870/"
] | Here's what I ended up doing, which solved my problem. I used multiprocessing to start a separate watchdog monitoring process to watch for each file separately. Watchdog already queues up new files for me, which is fine for me.
As for point 2 above, I needed, e.g. a file2 to process before a file1, even though file1 ... | I'm not sure it would make much sense to do a thread per file. The [GIL](https://wiki.python.org/moin/GlobalInterpreterLock) will probably eliminate any advantage you'd see from doing that and might even impact performance pretty badly and lead to some unexpected behavior. I haven't personally found `watchdog` to be ve... | 11,990 |
25,663,543 | I'm trying to run celery worker in OS X (Mavericks). I activated virtual environment (python 3.4) and tried to start Celery with this argument:
```
celery worker --app=scheduling -linfo
```
Where `scheduling` is my celery app.
But I ended up with this error: `dbm.error: db type is dbm.gnu, but the module is not ava... | 2014/09/04 | [
"https://Stackoverflow.com/questions/25663543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493329/"
] | try this :-
```
var value=$(this).attr("href");
```
[Demo](http://jsfiddle.net/rmbvo9oh/2/) | In JavaScript, when you bind an event to an element, the `this` variable is being available (of course depending on the element and event). So, when you click an element and bind a function, within that function scope the clicked element is referenced as `this`. Writing `$(this)` you make a jQuery object out of it:
``... | 11,991 |
11,301,863 | I have a django FileField, which i use to store wav files on the Amazon s3 server. I have set up the celery task to read that file and convert it to mp3 and store it to another FileField. Problem i am facing is that i am unable to pass the input file to ffmpeg as the file is not the physical file on the hard disk drive... | 2012/07/02 | [
"https://Stackoverflow.com/questions/11301863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/867365/"
] | Use [`subprocess.Popen.communicate`](http://docs.python.org/library/subprocess.html?highlight=popen.communicate#subprocess.Popen.communicate) to pass the input to your subprocess:
```
command = ['ffmpeg', '-y', '-i', '-', output_file.name]
process = subprocess.Popen(command, stdin=subprocess.PIPE)
process.communicate(... | You need to create a pipe, pass the read end of the pipe to the subprocess, and dump the data into the write end. | 11,992 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.