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 |
|---|---|---|---|---|---|---|
56,026,352 | I created a Django (v. 2.1.5) model called Metric that has itself as an embed model, as you can see below:
```py
from djongo import models
class Metric(models.Model):
_id = models.ObjectIdField()
...
dependencies = models.ArrayModelField(
model_container='Metric',
blank=True,
)
def... | 2019/05/07 | [
"https://Stackoverflow.com/questions/56026352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11465606/"
] | You can create this filter:
```
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.htt... | This [sample](https://github.com/spring-cloud-samples/sample-gateway-oauth2login) shows how to set up Spring Cloud Gateway with Spring Security OAuth2. | 2,706 |
34,841,822 | I have coded a Python Script for Twitter Automation using Tweepy. Now, when i run on my own Linux Machine as `python file.py` The file runs successfully and it keeps on running because i have specified repeated Tasks inside the Script and I also don't want to stop the script either. But as it is on my Local Machine, th... | 2016/01/17 | [
"https://Stackoverflow.com/questions/34841822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5676841/"
] | I have installed it from github with the command `bower install git@github.com:angular/angular.git`:
```
$ bower install git@github.com:angular/angular.git
bower angular#* not-cached git@github.com:angular/angular.git#*
bower angular#* resolve git@github.com:angular/angular.git#*
bower angu... | I advise you not to use Bower. Bower is used to get your packages in your project folder, that's it.
Try to look up JSPM (<http://jspm.io>). It does a lot more than getting packages in your project. It takes care of ES6 to ES5. And loads all your packages in one time using SystemJS in your browser with just a couple l... | 2,707 |
23,952,821 | I am making a dabian binary package for local use. `dpkg-buildpackage -rfakeroot` is failed due to below error.
```
find /home/dwft78/project/CoreScanner/cscore-1.0/lib -name "libcs*" -type f -exec cp -f {} /home/dwft78/project/CoreScanner/cscore-1.0/debian/cscore/opt/motorola-scanner//bin \;
find /home/dwft78/project... | 2014/05/30 | [
"https://Stackoverflow.com/questions/23952821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458841/"
] | Something like that could just do the trick:
```
#!/usr/bin/make -f
export DH_COMPAT=5 # though I don't know what for...
%:
dh $@
override_dh_shlibdeps:
dh_shlibdeps -l$(shell pwd)/lib/Linux/$(DEB_BUILD_GNU_CPU)
```
**Edit**
I just remembered there was an option to dh\_shlibdeps which even [got attention... | how about just exporting `LD_LIBRARY_PATH` in `debian/rules`?
```
#!/usr/bin/make -f
export LD_LIBRARY_PATH=$(shell pwd)/lib/Linux/$(DEB_BUILD_GNU_CPU)
%:
dh $@
```
note
----
i'm using `$(DEB_BUILD_GNU_CPU)` here to calculate the value of *x86\_64*.
this might give the correct result (it will return *i38... | 2,709 |
21,500,062 | Hi I'm new in programming and in python and I have an assignment that I can't complete. I have to write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns. I have used this code so far:
```
num... | 2014/02/01 | [
"https://Stackoverflow.com/questions/21500062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3260697/"
] | ```
col=0 #add this line
while count < int(numprimes):
if primetest(potentialprime) == True:
print "%5d"%potentialprime, #and this line
col += 1 #and this block
if col==5: #
print "\n" #
col=0 #
count += 1
potentialp... | Add a variable for the number of the current column `currentCol` initialized to 0 and change the line `print potentialprime` to the following 5 lines:
```
print str(potentialprime).ljust(5),
currentCol += 1
if currentCol==5:
print ""
currentCol=0
```
Take notice of the call to [`ljust`](http://docs.python.or... | 2,710 |
52,967,071 | I'm trying to do django api.
In models.py
```
class Receipt(models.Model):
id=models.AutoField(primary_key=True)
name=models.CharField(max_length=100)
created_at = models.DateTimeField(default=datetime.datetime.now(),null=True,blank=True)
updated_at = models.DateTimeField(auto_now=True,editable=False)... | 2018/10/24 | [
"https://Stackoverflow.com/questions/52967071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10455023/"
] | The error as you could see in traceback is in you form `ReceiptForm`. `DateTimeField` with `auto_now` are `editable=False` and `blank=True` automatically, therefore could not be included in a form unless it's readonly. You could remove `auto_now` and use a custom save method to set `updated_at`.
See these questions fo... | What you're trying to achieve?
[`auto_now`](https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.DateField.auto_now) is to set field value for *every save*. You can't override this.
[`auto_now_add`](https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.DateField.auto_now_add) ... | 2,713 |
61,045,138 | I have following test.bat file:
```
:begin
@echo off
python -c "from datetime import datetime;import sys;sys.stdout.write(datetime.strptime('20200220', '%Y%m%d').replace(day = 1).strftime('%Y%m%d'))"
```
When I run it from cmd, I get:
```
ValueError: time data '20200220' does not match format 'mYd'
```
Please ig... | 2020/04/05 | [
"https://Stackoverflow.com/questions/61045138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9005202/"
] | Not sure why but you need to escape the `%`. This works.
```
...
python -c "from datetime import datetime;import sys;sys.stdout.write(datetime.strptime('20200220', '%%Y%%m%%d').replace(day = 1).strftime('%%Y%%m%%d'))"
``` | See the message of error:
```
ValueError: time data '20200220' does not match format 'mYd'
```
2020 is a year 02 month and 20 the day and you try to parse with **mYd**, you need parse with **Ymd**. Set correctly position of the date format. | 2,714 |
62,471,080 | I am trying to rank a large dataset using python. I do not want duplicates and rather than using the 'first' method, I would instead like it to look at another column and rank it based on that value.
It should only look at the second column if the rank in the first column has duplicates.
```
Name CountA CountB
Al... | 2020/06/19 | [
"https://Stackoverflow.com/questions/62471080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1824972/"
] | Maybe use sort and pull out the index:
```
import pandas as pd
df = pd.DataFrame({'Name':['A','B','C','D'],'CountA':[15,20,20,45],'CountB':[3,52,31,43]})
df['rank'] = df.sort_values(['CountA','CountB'],ascending=False).index + 1
Name CountA CountB rank
0 A 15 3 4
1 B 20 52 2
... | You can take the counts of the values in CountA and then filter the DataFrame rows based on the count of CountA being greater than 1. Where the count is greater than 1, take CountB, otherwise CountA.
```
df = pd.DataFrame([[15,3],[20,52],[20,31],[45,43]],columns=['CountA','CountB'])
colAcount = df['CountA'].value_cou... | 2,715 |
61,385,291 | I'm working on Express with NodeJS to build some custom APIs.
I've successfully build some APIs.
Using GET, i'm able to retrieve the data.
Here's my index.js file with all the code.
```
const express = require('express');
const app = express();
//Create user data.
const userData = [
{
id : 673630,
... | 2020/04/23 | [
"https://Stackoverflow.com/questions/61385291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12785631/"
] | In order to send POST data upon request, you have to pass the data through the request body. To do that, you have to install a Node.js body parsing middleware called [body-parser](https://www.npmjs.com/package/body-parser). Please read this to get an idea about how to configure this on your app.
Then you have to add t... | It would be something like this assuming your passing json in the post request:
Your request body would be like this:
```
{
"id": "1",
"firstName": "First Name",
"lastName": "Last Name"
}
```
```
app.post('/api/employees', function(req, res) {
if(req.body) {
userData.push(req.body)
}
else {
... | 2,716 |
14,095,023 | I created a custom paster command as described in <http://pythonpaste.org/script/developer.html#what-do-commands-look-like>. In my setup.py I have defined the entry point like this:
```
entry_points={
'paste.global_paster_command' : [
'xxx_new = xxxconf.main:NewXxx'
]
}
```
I'm inside an activated virtualenv... | 2012/12/30 | [
"https://Stackoverflow.com/questions/14095023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/110963/"
] | You are doing something wrong, it should work. This is the minimal working example, you can test it with your virtualenv:
`blah/setup.py`:
```
from setuptools import setup, find_packages
setup(name='blah',
version='0.1',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_pac... | You should install your paster\_script in the active virtualenv. Then you can use it anywhere. | 2,721 |
51,601,502 | I'd like to create a TensorFlow's dataset out of my images using Dataset API. These images are organized in a complex hierarchy but at the end, there are always two directories "False" and "Genuine". I wrote this piece of code
```
import tensorflow as tf
from tensorflow.data import Dataset
import os
def enumerate_all... | 2018/07/30 | [
"https://Stackoverflow.com/questions/51601502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4671908/"
] | Counterexample
==============
Using the assumptions below about the statement of the problem (times are effectively given as values such as .06 for 60 milliseconds), if we convert .06 to `float` and add it 1800 times, the computed result is 107.99884796142578125. This differs from the mathematical result, 108.000, by ... | ### As much as possible, reduce the errors caused by floating point calculations
Since you've already described measuring your individual timings in milliseconds, it's far better if you accumulate those timings using integer values before you finally divide them:
```
std::milliseconds duration{};
for(Timing const& ti... | 2,722 |
58,088,175 | This is similar to [this question](https://stackoverflow.com/questions/45221014/python-exif-cant-find-date-taken-information-but-exists-when-viewer-through-wi), except that the solution there doesn't work for me.
Viewing a HEIC file in Windows Explorer, I can see several dates. The one that matches what I know is the ... | 2019/09/24 | [
"https://Stackoverflow.com/questions/58088175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123047/"
] | It's a HEIC file issue - it's not supported apparently, some difficulties around licensing I think. | While doing it with `mdls`, it's better (performance-wise) to give it a whole bunch of filenames separated by space at once.
I tested with 1000 files: works fine, 20 times performance gain. | 2,725 |
24,456,735 | I could successfully rum a simple program to check whether the number is prime or not in C. The code looks like this
```
void isPrime(int n)
{
int a=0,i;
for(i=1;i<=n;i++)
{
if(n%i==0)
a++;
}
if(a==2)
{
printf("\n%d is prime",n);
}
else
{
printf("\n%d is not ... | 2014/06/27 | [
"https://Stackoverflow.com/questions/24456735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2947110/"
] | Why don't you add some `print` statements so you can see where the code fails? Adding some prints should be your first reflex when debugging.
```
def isPrime(n):
a=0
for x in range(1,n):
print('x,a', x,a)
if n%x==0:
print('incrementing a...')
a=a+1
print('a after loo... | The issue you have is that the last value produced `range(start, stop)` is `stop-1`; see [the docs](https://docs.python.org/2/library/functions.html#range). Thus, `isPrime` should have the following `for` loop:
```
for x in range(1, n+1):
```
This will faithfully replicate the C code, and produce the correct output.... | 2,727 |
1,459,590 | if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:
```
os.listdir("\\\\remotehost\\share")
```
However, if I attempt to list the network drives/directories available on the remot... | 2009/09/22 | [
"https://Stackoverflow.com/questions/1459590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300745/"
] | May be [pysmb](http://miketeo.net/wp/index.php/projects/pysmb) can help | Sorry. I'm not able to try this as I'm not in a PC.
Have you tried:
```
os.listdir("\\\\remotehost\\")
``` | 2,730 |
73,279,102 | I have the following sentence:
```
text="The weather is extremely severe in England"
```
I want to perform a custom `Name Entity Recognition (NER)` procedure
First a normal `NER` procedure will output `England` with a `GPE` label
```
pip install spacy
!python -m spacy download en_core_web_lg
import spacy
nlp = s... | 2022/08/08 | [
"https://Stackoverflow.com/questions/73279102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17465901/"
] | Indeed it looks like NER do not allow overlapping, and that is your problem, your second part of the code tries to create a ner containing another ner, hence, it fails.
see in:
<https://github.com/explosion/spaCy/discussions/10885>
and therefore spacy has spans categorization.
I did not find yet the way to character... | Why do you need the new hash in the string store? Due to the underscore? Thx | 2,739 |
2,407,872 | I have a problem, which is not easily described. I'm writing a web application that makes strong usage of jQuery and AJAX calls. Now I don't have a lot of experience in Javascript archicture, but I realize that my program has not a good structure. I think I have too many identifiers referring to the same (at least more... | 2010/03/09 | [
"https://Stackoverflow.com/questions/2407872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49628/"
] | You could use a global registry:
```
window.WidgetRegistry = {};
window.WidgetRegistry['foowidget'] = new Widget('#myID');
```
and when AJAX calls return, they can get the widget like this:
```
var widgetID = data.widgetID;
if (widgetID in window.WidgetRegistry) {
var widget = window.WidgetRegistry[widgetID];
}... | I'm not sure I've fully understood your question, but I'll try to point some ideas.
In my opinion, you should make base widget class, which contains common functionality for widgets.
Let's use for example AppName.Widgets.base(). One of the instance variables is \_events, which is object that stores events as keys and... | 2,740 |
38,302,028 | Using pip from a (python 3.5) script, how can i upgrade a package i previously installed via the command line (using `pip install`)?
Something like
```
import pip
pip.install("mysuperawesomepackage", upgrade=True)
``` | 2016/07/11 | [
"https://Stackoverflow.com/questions/38302028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113623/"
] | I think you should link in either 2 stylesheets, one for portrait and one for landscape OR define your styles with media queries using orientation
In the following example i have included both, but either will do.
e.g.
```html
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" media="all and (orientation... | Try to give every thing in percentage in some exceptional cases like font size etc you can use EM or PX. | 2,745 |
57,596,488 | I am trying to access JSON using urllib.request.urlopen. It works fine when I use urllib2 in python2, but not urllib.request.urlopen.
```
URL = 'https://api.exchangeratesapi.io/latest'
f = urllib.request.urlopen(URL)
```
```
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.... | 2019/08/21 | [
"https://Stackoverflow.com/questions/57596488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11958437/"
] | This is what I used and it worked:
```
from urllib.request import urlopen
URL = 'https://api.exchangeratesapi.io/latest'
f = urlopen(URL)
```
I hope this works for you! | you can try to disable the ssl verification
```
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
``` | 2,746 |
54,685,134 | I am using Keras to create a deep learning model. When I creating a VGG16 model, the model is created but I get the following warning.
```
vgg16_model = VGG16()
```
why this warning happens and how can I resolve this?
```
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_... | 2019/02/14 | [
"https://Stackoverflow.com/questions/54685134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10594993/"
] | It looks like there's an open git issue to clean this up in the keras code:
<https://github.com/tensorflow/minigo/issues/740>
You should be safe to ignore the warning, I don't believe you can change it without modifying the TF repo. You can disable warnings as [mentioned here](https://stackoverflow.com/questions/486... | So , the method `colocate_with` is a context manager to make sure that the operation or tensor you're about to create will be placed on the same device the reference operation is on. But, your warning says that it will be deprecated and that this will from now on be handled automatically. From the next version of tenso... | 2,748 |
39,693,115 | I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate:
```
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
```
I need to extract the hours from each line (in this case 09) and then find the most common hours the emails ... | 2016/09/26 | [
"https://Stackoverflow.com/questions/39693115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6879638/"
] | Ok, first off, you should probably use a `with` `as` statement, it just simplifies things and makes sure you don't mess up. So
`fh = open('poem.txt', 'r')`
becomes
`with open('poem.txt','r') as file:`
and since you're just concerned with words, you might as well use a built-in from the start:
```
words = file.... | What you need to do is to keep a list of all the longest words you've seen so far and keep the longest length. So for example, if the longest word so far has the length 5, you will have a list of all words with 5 characters in it. As soon as you see a word with 6 or more characters, you will clear that list and only pu... | 2,751 |
13,228,939 | Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging.
is there any standard convention people follow or is it... | 2012/11/05 | [
"https://Stackoverflow.com/questions/13228939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1475962/"
] | Implement function [`__str__`](http://docs.python.org/3/reference/datamodel.html#object.__str__) in the class for the object you are printing.
If you are printing objects for a class that you can't alter then it is fairly straightforward to provide your own `print` function, since you are using Python 3.
Edit: Usual... | The standard way to print custom info about an object (class instance) is to use `__str__` method:
```
class A:
var = 1
def __str__(self):
return 'Accessing from print function, var = {0}'.format(self.var)
```
In this method you can display any info you want
```
a = A()
print(a)
>>> Accessing from ... | 2,754 |
68,929,023 | I have to do this in python so instead of writing these many lines - any other way ?
```
insert into table_a (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_b (col1,col2,col3) select col1,col2,col3 from temp;
insert into table_c (col1,col2,col3) select col1,col2,col3 from temp;
insert into table... | 2021/08/25 | [
"https://Stackoverflow.com/questions/68929023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16257885/"
] | If you only need it to go until a specific letter, you can just use a string with as many letters as you need and then loop through them. [Thanks to Michael for pointing it out]
```
letters = "abcdefgh"
for letter in letters:
print(f"insert into table_{letter} (col1,col2,col3) select col1,col2,col3 from temp;")
... | Put the table names in a `list`, then iterate on it and build the query with it
```
tables = ['table_a', 'table_b', 'table_c']
for table in tables:
query = f"insert into {table} (col1,col2,col3) select col1,col2,col3 from temp;"
``` | 2,760 |
12,084,445 | Is it possible to change the getter for a python property after it has been created?
```
class A:
_lookup_str = 'hi'
@property
def thing():
value = some_dictionary[_lookup_str]
# overwrite self.thing so that it is just value, not a special getter
return value
```
The idea is that ... | 2012/08/23 | [
"https://Stackoverflow.com/questions/12084445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257712/"
] | Werkzeug has a [`cached_property` decorator](http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property) that does exactly what you want. It just replaces the `__dict__` entry for the function after the first function call with the output of the first call.
Here's the code (from [werkzeug.utils on github](ht... | The answer, as indicated by Jeff Tratner, is to overwrite the property object found in the `__dict__` of the python object. Werkzeug's cached\_property seems overcomplicated to me. The following (much simpler) code works for me:
```
def cached_property(f):
@property
def g(self, *args, **kwargs):
print ... | 2,761 |
17,300,638 | I am trying to get Node.js to build on Windows. The process completes, seemingly okay, but does not generate node.lib.
Checking what was output it seems there is an issue right at the start (I disappeared off to get a coffee why I didn't see it at first) when trying to build.
```
Project files generated.
Setting env... | 2013/06/25 | [
"https://Stackoverflow.com/questions/17300638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
] | You can save the previous position of the marble like this:
```
CGRect previousPosition = marbleFrame.frame;
```
And in the next iteration, if the marble collides the wall, set its frame to that.
Other solution would be checking from which side is colliding (top, left, right or down), that's easy comparing the inte... | First of all, collision detection is not a easy thing to get working correctly, so you may want to look into some external libraries, such as ObjectiveChipmunk or Box2d.
That being said, there are a few things you could put into that else statement. The general way to go about it would be to "move the object back" so... | 2,764 |
62,885,473 | ```
import numpy as np
import pandas as pd
df = pd.read_csv('Salaries.csv',engine='python')
print( df[ df['JobTitle'].value_counts()==1 ] )
```
I'm trying to get the row if the Job in JobTitle appears once.
However, I keep getting this error:
pandas.core.indexing.IndexingError: Unalignable boolean Series provided ... | 2020/07/13 | [
"https://Stackoverflow.com/questions/62885473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13758656/"
] | Another solution using `transform`:
```
df[df.groupby('JobTitle')['JobTitle'].transform('count').eq(1)]
``` | You can do it in a single line of code combining the index values of `value_counts()` where the series is equal to 1:
```
df[df['A'].isin((df['A'].value_counts() == 1).replace({False:np.nan}).dropna().index)]
```
Perhaps a bit better and easier to understand, in two lines of code:
```
values = df['A'].value_counts(... | 2,765 |
7,666,269 | I want to know if a constructor in Java returns something. I know there is no return value like '5' or "Hello World." But if we are assigning a variable to it:
```
People person = new People();
```
Then wouldn't it logically make sense for the object or ID to be returned? Is the reference in memory where the object ... | 2011/10/05 | [
"https://Stackoverflow.com/questions/7666269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629599/"
] | In Java you only have primitives and references to objects as types for fields, parameters and local variables. A reference is a bit like an ID, except it can change as any moment without you needing to know when this has happened.
A reference is closer to the concept of a pointer or object index. ie. it refers to a m... | constructor is not "normal" method. And you must use operator `new` with constructor and then you will have reference to the object, so this is pointer (id) to the place in memory.
[here is some explanation](http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html)
>
> Constructor declarations look l... | 2,766 |
20,435,615 | I am trying to build a list with the following format:
(t,dt,array)
Where t is time -float-, dt is also a float an array is an array of ints that represents the state of my system. I want to have elements ordered in an array by the first element, that is t. So my take on it is to use the heap structure provided by Py... | 2013/12/06 | [
"https://Stackoverflow.com/questions/20435615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3053450/"
] | ```
(0,0,np.random.randint(0,2,Nsize))
```
The first two elements there aren't `t` or `dt`. They're both 0. As such, the tuple comparison tries to compare the arrays in the 3rd slot and finds that that doesn't produce a meaningful boolean result. Did you mean to have something meaningful in the first two slots? | As far as where the error comes from:
```
>>> a = (0, 0, np.random.randint(0, 2, 3))
>>> a
(0, 0, array([0, 0, 1]))
>>> b = (0, 0, np.random.randint(0, 2, 3))
>>> a
(0, 0, array([0, 0, 1]))
>>> a == b
```
The reason for this is that numpy overrides comparison operators in a non-standard way. Rather than returning a ... | 2,775 |
18,026,306 | I am trying to create a python class based on this class. I am trying to have it return the person’s wages for the week (including time and a half for any overtime. I need to place this method following the def getPhoneNo(self): method and before the `def __str__(self):` method because I am trying to use this method in... | 2013/08/02 | [
"https://Stackoverflow.com/questions/18026306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2631037/"
] | Is the `__str__` function looking alright? I mean stringRep is changed several times and the last version is returned.
I think the body of the function should look like this:
```
stringRep = "First Name: " + self.firstName + "\n" +\
"Last Name: " + self.lastName + "\n" +\
"Phone Number... | I see two issues in the example you posted:
* The getWeeksPay function needs to be indented so that it is interpreted as a PersonWorker class method versus a normal function.
* You have some funky characters at the end of the return statement in the **str** method.
I updated your code snippet with an example of what ... | 2,778 |
38,466,796 | I just made a heap class in python and am still working in Tree traversal. When I invoked `inoder function`, I got error said `None is not in the list`. In my three traversal functions, they all need `left` and `right` function. I assume that the problem is in these two functions, but I don't know how to fix it.
```
c... | 2016/07/19 | [
"https://Stackoverflow.com/questions/38466796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6338377/"
] | You don't actually need to use the ID directly; you can just sample row numbers, and then directly index the data.frame with those:
```
# How many rows in the data.frame?
n <- nrow(mtcars)
# Sample them
mtcars[sample(x = n, size = n, replace = TRUE), ]
```
If you pass in the same integer twice, you get that row tw... | I use the 'matches' function from the grr package for this.
```
Indices <- unlist(matches(b.idx, data_xy$ID, list=TRUE))
b.data <- data_xy[Indices, ]
``` | 2,779 |
65,284,837 | I have this pyspark script in Azure databricks notebook:
```
import argparse
from pyspark.sql.types import StructType
from pyspark.sql.types import StringType
spark.conf.set(
"fs.azure.account.key.gcdmchndev01c.dfs.core.chinacloudapi.cn",
"<storag account key>"
)
inputfile = "abfss://... | 2020/12/14 | [
"https://Stackoverflow.com/questions/65284837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/759352/"
] | tl;dr
=====
```java
java.time.Duration.ofMillis( m ).toDaysPart()
```
Avoid legacy date-time types
============================
You are using terrible date-time classes that were supplanted years ago by the modern *java.time* classes. Never use `Calendar`, `GregorianCalendar`, `java.util.Date`, and such.
`java.tim... | Use java.time also when you need javax.xml.datatype.Duration
------------------------------------------------------------
>
> I am explicitly asking for javax.xml.datatype. It is not in my hand to
> choose another datatype.
>
>
>
The conversion from `java.time.Duration` to a `javax.xml.datatype.Duration` fulfilli... | 2,780 |
43,770,008 | I need to run a large build script (bash commands) on a python script. I receive it as a large string and each line is splitted by a \n. So, I need to execute each line separately.
At first, I tried to use [subprocess.Popen()](https://docs.python.org/2.7/library/subprocess.html) to execute them. But the problem is: af... | 2017/05/03 | [
"https://Stackoverflow.com/questions/43770008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3061426/"
] | What you want is definitely a little weird, but it's possible using pipes.
```
from subprocess import PIPE, Popen
p = Popen(['bash'], stdin=PIPE, stdout=PIPE)
p.stdin.write('echo hello world\n')
print(p.stdout.readline())
# Check a return code
p.stdin.write('echo $?\n')
if p.stdout.readline().strip() ⩵ '0':
print... | when calling a shell, the os starts a new process unless you have a shell interpreter in python all the way.
the only possibility to do it in the same process is simulating all steps with python directly.
the better way is to accept the limit, call an external process yourself and wait for the script to terminate con... | 2,781 |
66,399,560 | I have encountered some value error when input txt file into python.
the txt file called "htwt.txt", and contain the below data:
```
Ht Wt
169.6 71.2
166.8 58.2
157.1 56
181.1 64.5
158.4 53
165.6 52.4
166.7 56.8
156.5 49.2
168.1 55.6
165.3 77.8
```
When I typed the below code, and value errors are occurre... | 2021/02/27 | [
"https://Stackoverflow.com/questions/66399560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14620006/"
] | Pandas `read_csv` is enough
```
import pandas as pd
import os
os.chdir("/Users/James/Desktop/data/")
df1 = pd.read_csv("htwt.txt",sep=' ')
```
Output:
```
>>> df1
Ht Wt
0 169.6 71.2
1 166.8 58.2
2 157.1 56.0
3 181.1 64.5
4 158.4 53.0
5 165.6 52.4
6 166.7 56.8
7 156.5 49.2
8 168.1 55.6
9 ... | The first row in your text file has alphanumeric characters: "Ht Wt".
These characters cannot be converted to a floating point number.
Remove the first row and you should be fine. | 2,782 |
45,138,223 | i have some sort of processes :
```
subprocess.Popen(['python2.7 script1.py')],shell=True)
subprocess.Popen(['python2.7 script2.py')],shell=True)
subprocess.Popen(['python2.7 script3.py')],shell=True)
subprocess.Popen(['python2.7 script4.py')],shell=True)
```
i want to each one starts after the previous process comp... | 2017/07/17 | [
"https://Stackoverflow.com/questions/45138223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5121002/"
] | In my app the issue was caused by the templateUrl path being relative-to-code instead of absolute (relative-to-project).
I had added the `module.component(...)` part along with the UpgradeComponent in one go, since the ngJS component was originally routed to directly. When I did so, I used the ng4 usual way of writing... | I faced the same issue while upgrading from angularJs 1.7 to Angular 9. To fix the issue i changed **`template`** to **`templateUrl`** in the angularJS component file. | 2,786 |
31,318,739 | I try to install flask-bcrypt via pip, but it raisis me this error:
```
error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat)
```
I am currently running `Visual Studio 2015 RC` with `Python 3` on `Windows 10`.
Any ideas how to solve this error?
**Edit:**
I tried to follow diffrent solutions a... | 2015/07/09 | [
"https://Stackoverflow.com/questions/31318739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5023926/"
] | Apparently the problem can be solved by installing py-bcrypt first. A win32 installer is available from the first comment to this reddit post:
<http://www.reddit.com/r/flask/comments/15q5xj/anyone_have_a_working_version_of_flaskbcrypt_for/> | Here is another option, you need to setup Wheel package before you can import bcrypt
```
pip install wheel
```
```
pip install bcrypt
```
```
from flask_bcrypt import Bcrypt
``` | 2,787 |
15,077,627 | TL;DR: I want a locals() that looks in a containing scope.
Hi, all.
I'm teaching a course on Python programming to some chemist friends, and I want to be sure I really understand scope.
Consider:
```
def a():
x = 1
def b():
print(locals())
print(globals())
b()
```
Locals prints an emp... | 2013/02/25 | [
"https://Stackoverflow.com/questions/15077627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1911697/"
] | What is happening in your code is that when python see's the `x=3` line in your `b()` method, it is recreating `x` with a scope within the `b` function instead of using the `x` with it's scope in the `a` function.
because your code then goes:
```
a = x+2
x = 3
```
it is saying that you need to define the in... | The statement `print(locals())` refers to nearest enclosing scope, that is the `def b():` function. When calling `b()`, you will print the locals to this b function, and definition of x is outside the scope.
```
def a():
x = 1
def b():
print(locals())
print(globals())
b()
print(locals(... | 2,788 |
52,736,009 | I have improved [my first Python program](https://stackoverflow.com/questions/51300358/python-hiding-json-empty-key-values-in-the-print-statement/51302419?noredirect=1) using f-strings instead of print:
```
....
js = json.loads(data)
# here is an excerpt of my code:
def publi(type):
if type == 'ART':
ret... | 2018/10/10 | [
"https://Stackoverflow.com/questions/52736009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10069047/"
] | You can use a conditional expression in an f-string as well:
```
return f"{nom} {'(%s)' % dat if dat else ''}. {tit}. {jou}. {'Pubmed: ' + pbm if pbm else ''}"
```
or you can simply use the `and` operator:
```
return f"{nom} {dat and '(%s)' % dat}. {tit}. {jou}. {pbm and 'Pubmed: ' + pbm}"
``` | An easy but slightly fugly workaround is to have the formatting decorations in the string.
```
try:
pbm = ". Pubmed: " + art['pubmedId_s']
except (KeyError, NameError):
pbm = ""
...
print(f"{nom} ({dat}). {tit}. {jou}{pbm}")
``` | 2,791 |
11,188,619 | I have a string built from a few segments, which are not separated, but not overlap. This looks like that:
```
<python><regex><split>
```
I would like to split in into:
```
<python>, <regex>, <split>
```
I'm looking for the most efficient way to do that, and in the same time with as little code as possible. I cou... | 2012/06/25 | [
"https://Stackoverflow.com/questions/11188619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531954/"
] | Try [re.findall](http://docs.python.org/library/re.html#re.findall):
```
import re
your_string = '<python><regex><split>'
parts = re.findall(r'<.+?>', your_string)
print parts # ['<python>', '<regex>', '<split>']
``` | If your input data is really that simple, you can just use the `.replace()` method that's built into strings.
```
>>> '<python><regex><split>'.replace('><', '>, <')
'<python>, <regex>, <split>'
```
If it's more complex, you should give a better example of input/expected output. | 2,792 |
58,257,125 | I have a form with an `<input type="file">`, and I'm getting an error when I try to save the uploaded image. The image is uploaded via POST XMLHttpRequest. I have no idea why this is happening.
views.py:
```
import datetime
from django.shortcuts import render
from .models import TemporaryImage
def upload_file(requ... | 2019/10/06 | [
"https://Stackoverflow.com/questions/58257125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8629753/"
] | You're only uploading a single file; you shouldn't be iterating over the file key.
```
def upload_file(request):
key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}'
file = request.FILES.get('file')
if file:
img = TemporaryImage(image=file, key=key)
img.save()
``` | i guess you have too try to save your image this way:
```
from django.core.files.base import ContentFile
...
def upload_file(request):
key = f'{request.user}-{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}'
file = request.FILES.get('file')
if file :
img = TemporaryImage.objects.create(key=key)
... | 2,795 |
1,312,524 | I'm attempting to build a webpage that loads depending on the input provided. I'm having some trouble wrapping my head around event handling in javascript, basically. Coming from python, if I wanted to wait for a specific keyboard input before moving on to the next object to display, I would create a *while* loop and p... | 2009/08/21 | [
"https://Stackoverflow.com/questions/1312524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160854/"
] | For easier implementation of event handling I recommend you to use a library such as [Prototype](http://www.prototypejs.org/api/event) or [Jquery](http://docs.jquery.com/Events) (Note that both links take you to their respective Event handling documentation.
In order to use them you have to keep in mind 3 things:
* W... | you could attach an event listener to the window object like this
```
window.captureEvents(Event.KEYPRESS);
window.onkeypress = output;
function output(event) {
alert("you pressed" + event.which);
}
``` | 2,796 |
41,596,143 | I am trying to find an elegant way to calculate a bivariate normal CDF with python where one upper bound of the CDF is a function of two variables, of which one is a variable of the bivariate normal density (integral variable).
Example:
```
from scipy import integrate
import numpy as np
# First define f(x, y) as the... | 2017/01/11 | [
"https://Stackoverflow.com/questions/41596143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3023486/"
] | Although it's slow this approach seems to work.
The first few lines, up to 'this should produce 1', are a sanity check. I wanted to verify that my approach would correctly calculate the volume under the density. It does.
I use a variance-covariance matrix to get the desired correlation of 0.4 and avoid writing my own... | I had to write an option model that was using a bivariate distribution in Python. However, I did not find a prebuilt function that was fast - some seem to be using the random scipy generator to emulate it with the multivariate function. BUT... if you really dig deep and see what the other financial packages are using, ... | 2,806 |
47,784,693 | I am not able to handle to pass optional parameters in python `**kwargs`
```
def ExecuteyourQuery(self, queryStatement, *args, **kwargs):
if self.cursorOBJ is not None:
resultOBJ = self.cursorOBJ.execute(queryStatement, *args,**kwargs)
self.resultsVal = resultOBJ.fetchall()
```
---
The below stateme... | 2017/12/13 | [
"https://Stackoverflow.com/questions/47784693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4949381/"
] | When using args as the last parameter of your function, you can pass any number of **arguments** after the formal arguments, when existing. Args is a [tuple](https://www.tutorialspoint.com/python/python_tuples.htm).
```
def my_method(farg, *args):
print('FARG: ', farg)
print('ARGS: ', args)
my_method('Formal Argu... | another way to do this is by setting a default value for a parameter
```
def method(one, two, three=3):
print(one)
print(two)
if three != 3: # don't have to use it like this but it is a default value
print(three)
```
this set a default value if the parameter is not filled
if it is filled it will over... | 2,807 |
28,750,643 | okay, im a new guy at all this, just randomly picked it up with my neighbor and we are both stuck at this. We have been following this tutorial([here](http://www.swaroopch.com/notes/python/#intro)) and have made it to 6.6 in the tutorial. I have searched the forums looking for a way to get passed my problem but all the... | 2015/02/26 | [
"https://Stackoverflow.com/questions/28750643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4611612/"
] | First of all, Python shell differs from system shell (cmd.exe). You try to run `python script.py` in Python interpreter instead of `cmd.exe`.
Open `cmd.exe` and type in `python script.py` to solve this. It'll run fine if it doesn't contain any errors. `cd c:\\` doesn't work due to the same reason.
First `quit()` or... | You are in the python interpreter which is an interactive shell. You can consider it "scratch paper" to test out or try different things.
To run your script :
quit()
in the command prompt run python.exe hello.py ( on windows.. on \*nix just python) | 2,808 |
74,158,560 | I am going through JavaScript course on freecodecamp and I came across this ['Steamroller' challenge](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller). Coming from python I really like one-liner solutions so I managed to write one for this challe... | 2022/10/21 | [
"https://Stackoverflow.com/questions/74158560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14625103/"
] | Quote from [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat#description):
>
> Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; **for arrays ..., e... | So others answer your question, but here are simplified code
```js
const steamrollArray1 = arr => Array.isArray(arr) ? [].concat(...arr.map(steamrollArray1)) : arr;
const steamrollArray2 = arr => Array.isArray(arr) ? arr.flat(Infinity) : arr;
console.log(
steamrollArray1([1, [2], [3, [[4]]]])
); // returns [1, 2, ... | 2,809 |
48,946,036 | I'm getting started with docker compose and have been working through the simple demo flask application. The thing is, I'm running this from inside of an organization that intercepts all communication in such a way that SSL errors are thrown right and left. They provide us with three root certificates we need to instal... | 2018/02/23 | [
"https://Stackoverflow.com/questions/48946036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3929175/"
] | This isn't really a docker-specific question: you are asking, in effect, "how do I install certificate authorities under Linux"? The answer is going to be the same regardless of whether you are running your ssl client inside or outside of a container.
Your Python image is based on alpine, and alpine uses the "ca-certi... | In my case, Host machine's MTU is 1450, and Docker's MTU is 1500.
Which causes docker set MSS to 1460, and then TLS "server hello" packet got bigger than 1450 bytes, so the Host machine discard it.
To see if it's your case too, run ifconfig on both you Docker container and your host machine. If Host's MTU is less tha... | 2,811 |
32,866,578 | I am trying to bastardise Django and Django REST Framework into a single module so see if it can work. So far, I have the following code:
```
###############################################################################
# SETTINGS
###############################################################################
import... | 2015/09/30 | [
"https://Stackoverflow.com/questions/32866578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you are using `docker run` to start your container, you have the `--add-host=""` argument which takes a hostname and an IP that get written to the container's `/etc/hosts`.
Your startup command would look like this:
```
docker run -d --add-host="domain-a.dev:192.168.0.10" [...]
```
Replace `192.168.0.10` with ... | I basically worked around this now by using <http://xip.io/>
By using urls like `sub.127.0.0.1.xip.io` I can connect to my local machine. My app only has to know that `127.0.0.1.xip.io` is treated as the "top level domain", and `sub` is the domain name without tld. (In a Ruby on Rails app this can be done by adjusting... | 2,816 |
69,920,403 | There is an HTML page that I would like to find the elements of two input types and press one button to log in with the help of selenium along with python3.
The problem is that I can't seem to find a way of doing this correctly.
The two texts and the button are in a form without an id or some tag, also I'm new on this... | 2021/11/10 | [
"https://Stackoverflow.com/questions/69920403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1089615/"
] | I just changed your code from `presence_of_element_located` expected conditions to `presence_of_element_located`, corrected the locators and make some more things clearer. I hope now this should work.
```py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by... | To click on the link *`Login to start working`*, next key in the credentials and finally to click on the *Submit* button you can use the following [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):
```
driver.get("http://example.com/")
We... | 2,817 |
34,126,957 | I'm trying to install Pygame for python 3.5 32bit. I have learned that I can open the `.whl` files provided on the site by using the `pip` command. The problem is I've tried multiple ways doing this but with constant error.
```
python -m pip install pygame-1.9.2a0-cp35-none-win32.whl
'python' is not recognized as an ... | 2015/12/07 | [
"https://Stackoverflow.com/questions/34126957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5481774/"
] | It would be helpful if your filtered the result set from the database by the customer's name, for example...
```
DefaultListModel dlm = new DefaultListModel();
try (PreparedStatement st = con.prepareStatement("select songpick from customer where customername=?")) {
String customerName = (String)jComboBox1.getSelec... | You need to have a `WHERE` clause and set the value that you want to get from
E.g. `SELECT songpick FROM customer WHERE <columnName> = ?` and set the value of the that you need before the `executeQuery` statement with `st.setString(1, "Foo");` | 2,819 |
72,207,311 | ```
#!/bin/bash
data_dir=./all
for file_name in "$data_dir"/*
do
echo "$file_name"
python process.py "$file_name"
done
```
For example, this script processes the files sequentially in a directory in a 'for' loop. Is it possible to start multiple process.py instances to process... | 2022/05/11 | [
"https://Stackoverflow.com/questions/72207311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3943868/"
] | It's better to use [os.listdir](https://docs.python.org/3/library/os.html#os.listdir) and [subprocess.Popen](https://stackoverflow.com/a/7224186/5707560) to start new processes. | With **GNU Parallel**, like this:
```
parallel python process.py {} ::: all/*
```
It will run N jobs in parallel, where N is the number of CPU cores you have, or you can specify `-j4` to run on just 4, for example.
Many, many options for:
* logging,
* splitting/chunking inputs,
* tagging/separating output,
* stagg... | 2,820 |
17,694,780 | I'm a front-end dev struggling along with Django. I have the basics pretty much down but I've hit at wall at the following point.
I have a site running locally and also on a dev machine. Locally I've added an extra class model to an already existing app, registered it in the relevant admin.py and checked it in the set... | 2013/07/17 | [
"https://Stackoverflow.com/questions/17694780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321623/"
] | I figured out the problem. Turns out the login I was using to get into the admin didn't have superuser privileges. So I made a new one with:
```
python manage.py createsuperuser
```
After logging in with the new username and password I could see all my new shiny tables! | Are you sure touching `.wsgi` file does restart your app?
It looks like it doesn't.
Make sure the app is restarted. Find the evidence touching `.wsgi` file restarts the app maybe.
Since you don't provide any insight about how the dev server runs the apps, we won't be able to help you any further. | 2,822 |
54,172,462 | I'm new to ML and Colab. Trying to play around with the project at <https://github.com/tkarras/progressive_growing_of_gans> but having a hard time getting it running in Colab.
When I run the import\_example.py script from the project, I get immediate errors relating to Tensorflow not loading. So I tried stepping back ... | 2019/01/13 | [
"https://Stackoverflow.com/questions/54172462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1958417/"
] | Even I was facing the same issue. Later I realized I forgot to enable **GPU** in notebook settings.
I enabled it and installed **TensorFlow-GPU** (GPU version).
You can find notebook settings in **Edit** > **Notebook Settings**.
[Here's the screenshot](https://i.stack.imgur.com/Sr7Hr.jpg) | You just have to read the error carefully:
>
> NOTE: If your import is failing due to a missing package, you can
> manually install dependencies using either !pip or !apt.
>
>
>
Try running:
```
!pip install tensorflow
```
inside notebook, and then rerun the cell with the import. | 2,823 |
24,253,977 | I am trying to remove non repeating characters from a list in python. e.g list = [1,1,2,3,3,3,5,6] should return [1,1,3,3].
My initial attempt was:
```
def tester(data):
for x in data:
if data.count(x) == 1:
data.remove(x)
return data
```
This will work for some inputs, but for [1,2,3,4,5... | 2014/06/17 | [
"https://Stackoverflow.com/questions/24253977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3636636/"
] | ```
l=[1,1,2,3,3,3,5,6]
[x for x in l if l.count(x) > 1]
[1, 1, 3, 3, 3]
```
Adds elements that appear at least twice in your list.
In your own code you need to change the line `for x in data` to `for x in data[:]:`
Using `data[:]` you are iterating over a `copy` of original list. | Another linear solution.
```
>>> data = [1, 1, 2, 3, 3, 3, 5, 6]
>>> D = dict.fromkeys(data, 0)
>>> for item in data:
... D[item] += 1
...
>>> [item for item in data if D[item] > 1]
[1, 1, 3, 3, 3]
``` | 2,828 |
45,062,219 | Is there a simpler way possible to just add numbers which are regarded as strings but also integer by python? It doesn't let me add it, maybe because of the way I converted the integer to string and then a list?
I have done this so far:
```
function_menu()
print()
numbers = str(number)
lists = []
lists.extend(numbers... | 2017/07/12 | [
"https://Stackoverflow.com/questions/45062219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8295906/"
] | You could remove `0`s from the list. If the list becomes empty, return `0`, the product otherwise:
```
>>> no_zeroes = [value for value in values if value > 0]
>>> no_zeroes
[1.0, 3.4]
>>> reduce(lambda x, y : y*x, no_zeroes) if no_zeroes else 0
3.4
```
Note that from a mathematical point of view, the product of an ... | if you use numpy arrays you can filter out the zero values:
```
import numpy as np
vals = np.array([0.0, 0.0, 0.0, 0.0])
no_zeros = vals[vals>0]
if no_zeros:
print( np.prod(no_zeros))
else:
print(0.0)
``` | 2,838 |
37,622,153 | I would like to compute all (different) intersections of a collection of finite sets of integers (here implemented as a list of lists) in python (to avoid confusion, a formal definition is at the end of the question):
```
> A = [[0,1,2,3],[0,1,4],[1,2,4],[2,3,4],[0,3,4]]
> all_intersections(A) # desired output
[[], [0... | 2016/06/03 | [
"https://Stackoverflow.com/questions/37622153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442181/"
] | Here is a recursive solution. It is almost instantaneous on your test example:
```
def allIntersections(frozenSets):
if len(frozenSets) == 0:
return []
else:
head = frozenSets[0]
tail = frozenSets[1:]
tailIntersections = allIntersections(tail)
newIntersections = [head]
... | Iterative solution that takes about 3.5 ms on my machine for your large test input:
```
from itertools import starmap, product
from operator import and_
def all_intersections(sets):
# Convert to set of frozensets for uniquification/type correctness
last = new = sets = set(map(frozenset, sets))
# Keep goin... | 2,846 |
61,657,685 | First project from work and got stuck with this tedious error on Ubuntu.
Currently using node -v 13.8.0, installed python 2.7.17, GCC 7.5.0
also checked node-gyp npm page and installed all python and gcc dependencies.
here is my package.json file
```
"dependencies": {
"apn": "^2.1.5",
"async": "^1.5.2",
... | 2020/05/07 | [
"https://Stackoverflow.com/questions/61657685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11847762/"
] | The problem you have is the **time** package which is outdated <https://www.npmjs.com/package/time>.
There are some different solutions depending on why are you using that package, you could use a different library/package to handle dates and time, but you will probably need to refactor some code.
Try removing this d... | This works for me
```
npm install -g npm-check-updates
npm-check-updates -u
npm install
``` | 2,847 |
11,067,697 | I'm building a calendar-based web app, and am in great need of a javascript Date library-- something similar to python's [dateutil](http://labix.org/python-dateutil). I came across [DateJs](http://www.datejs.com/). The functionality looks great. My only hesitance is that the repo hasn't been touched since early 2008. U... | 2012/06/16 | [
"https://Stackoverflow.com/questions/11067697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/652693/"
] | I'd like to recommend [momentjs](http://momentjs.com/) - a very lightweight, yet surprisingly capable Date JS library. ) | DateJS works wonders for us. I am not really concerned that development seems to have stalled as it is pretty complete as-is. | 2,848 |
1,314,717 | In python, I can construct my [optparse](http://docs.python.org/library/optparse.html) instance such that it will automatically filter out the options and non-option/flags into two different buckets:
```
(options, args) = parser.parse_args()
```
With boost::program\_options, how do I retrieve a list of tokens which ... | 2009/08/22 | [
"https://Stackoverflow.com/questions/1314717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20712/"
] | IIRC, you have to use a combination of [`positional_options_description`](http://www.boost.org/doc/libs/1_39_0/doc/html/program_options/overview.html#id2892937) and [*hidden options*](http://www.boost.org/doc/libs/1_39_0/doc/html/program_options/howto.html#id2893967). The idea is to (1) add a normal option and give it ... | Here is an example:
```
namespace po = boost::program_options;
po::positional_options_description m_positional;
po::options_description m_cmdLine;
po::variables_map m_variables;
m_cmdLine.add_options()
(/*stuff*/)
("input", po::value<vector<string> >()->composing(), "")
;
m_positional.add("input", -1);
po... | 2,851 |
59,801,340 | I have been attempting to make a small python program to monitor and return ping results from different servers. I have reached a point where pinging each device in the sequence has become inefficient and lacks performance. I want to continuously ping each one of my targets at the same time on my python.
What would th... | 2020/01/18 | [
"https://Stackoverflow.com/questions/59801340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12737497/"
] | First of all you can't have many id's with the same value in a one html page. Cause it will result an error in the future while your doing a lot of code to it. Please change your btnedt to a class not an id. then change your script like this.
```
<script>
$(document).ready(function () {
$(document).on('cl... | Use class instead of multiple IDs
=================================
>
> Share your modal code
>
>
>
```
var mem_butn = "<td><input type=\"button\" class=\"btnedt\" value=\"Edit\" /></td>";
```
```
<script>
$(document).ready(function () {
$('body').on('click', '.btnedt', function() {
$... | 2,852 |
61,005,152 | Here I am using `fft` function of `numpy` to plot the fft of PCM wave generated from a 10000Hz sine wave. But the amplitude of the plot I am getting is wrong.
The frequency is coming correct using `fftfreq` function which I am printing in the console itself. My python code is here.
```
import numpy as np
import matpl... | 2020/04/03 | [
"https://Stackoverflow.com/questions/61005152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12673488/"
] | After a long home work I could able to find my issue. As I mentioned in the **Updating the work:** the reason was with the number of samples which I took was wrong.
I changed the two lines in the code
```
n_sa = 8 * int(freq_in_hertz)
t_fft = np.linspace(0, 1, n_sa)
```
to
```
n_sa = y.size //number of samples di... | I'm not sure exactly what you are trying to do, but my suspicion is that the Sine\_10000Hz.bin file isn't what you think it is.
Is it possible it contains more than one channel (left & right)?
Is it realy signed 16 bit integers?
It's not hard to create a 10kHz sine wave in 16 bit integers in numpy.
```py
import num... | 2,853 |
64,924,830 | Is it possible to write an API with Python so you can connect a physical ON and OFF switch via USB to a PC and when user presses the switch to ON or OFF, the python program detects it and send a signal to a web app and shows ON or OFF message on the website?
I am sorry if what I am asking its not clear enough! | 2020/11/20 | [
"https://Stackoverflow.com/questions/64924830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12487489/"
] | You can simply use `std::optional`:
```
String(const std::optional<int> &min_len, const std::optional<int> &max_len,
const std::optional<std::string> &pattern);
Type *type = new String(5, {}, std::nullptr); // last 2 parameters are omitted.
```
For C++14 you can use similar constructs that exist in other op... | Have you tried to use an [std::optional](https://en.cppreference.com/w/cpp/utility/optional) (since C++17)?
I know you mentioned the need to use C++14 compatible code, but there is a [boost::optional](https://www.boost.org/doc/libs/1_65_1/libs/optional/doc/html/index.html) available. | 2,855 |
8,210,344 | I get the following error
ImportError: No module named numeric if I have the following import
```
from numeric import *
```
in my python source code. How do I get this running on my Windows box against a python 2.7.x compiler? | 2011/11/21 | [
"https://Stackoverflow.com/questions/8210344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004443/"
] | You will probably need to install this module: <http://numpy.scipy.org/>
There are binaries for windows too, so installation should be easy.
Josh | There is no common module called `numeric`. Are you sure you don't mean `import numpy`? | 2,860 |
4,227,503 | I would like to establish a good naming scheme for physical/mathematical quantities used in my simulation code. Consider the following example:
```
from math import *
class GaussianBeamIntensity(object):
"""
Optical intensity profile of a Gaussian laser beam.
"""
def __init__(self, intensity_at_waist... | 2010/11/19 | [
"https://Stackoverflow.com/questions/4227503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335609/"
] | I think you've already found the good balance. Expressive names are important, so I totally agree with the use of *wavelenght* instead of lambda as a class attribute. This way the interface remains clear and expressive.
In a long formula, though, lambda\_ is good choice as shorthand notation, because this is a commonl... | Use Python3 and you can use the actual symbol λ for a variable name.
I look forward to writing code like:
```
from math import pi as π
sphere_volume = lambda r : 4/3 * π * r**3
``` | 2,862 |
53,545,656 | I know there are many post related to dictionary operations but I could not find the solution for my special case.
I have list of dictinoary (repeated dictionary keys with similar or different values) and I have to create a new dictionary from this list.
Eg:
```
a = [{u'a': 1}, {u'a': 2}, {u'a': 1}, {u'b': 2}, {u'b': ... | 2018/11/29 | [
"https://Stackoverflow.com/questions/53545656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2565385/"
] | You can sort the list `a` so that the like keys are groups and the largest values are last. Then add the values so that last value is the value left in the dict:
```
>>> a = [{u'a': 1}, {u'a': 2}, {u'a': 1}, {u'b': 2}, {u'b': 1}, {u'c': 1}, {u'c': 1}]
>>> {k:v for k,v in (x.items()[0] for x in sorted(a))}
{u'a': 2, u'... | You could do:
```
a = [{u'a': 1}, {u'a': 2}, {u'a': 1}, {u'b': 2}, {u'b': 1}, {u'c': 1}, {u'c': 1}]
result = {}
for di in a:
for key, value in di.items():
result[key] = max(value, result.get(key, value))
print(result)
```
**Output**
```
{'a': 2, 'c': 1, 'b': 2}
``` | 2,863 |
67,268,013 | I have been trying to draw a networkx multidigraph with multiple self-loops on nodes using matplotlib for quite a few days now but nothing works.
After multiple tests, I narrowed the problem to Networkx with Matplotlib.
I executed the following tutorial <https://networkx.org/documentation/latest/auto_examples/drawing/p... | 2021/04/26 | [
"https://Stackoverflow.com/questions/67268013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6099112/"
] | any time GoogleFinance() reutrns a historical array, you need to INDEX() it to get just the single answer.
It's almost always the second row and second column of the array that you want.
So:
```
=INDEX(Goooglefinance(.... ), 2, 2)
``` | I've tested your function and the error ***Function MULTIPLY parameter 2 expects number values. But 'Date' is a text and cannot be coerced to a number*** is due to this part `E2*GOOGLEFINANCE("Currency:"&F2&$G$1,"price", H2)` in your IFS function.
The return value of the `GOOGLEFINANCE("Currency:"&F2&$G$1,"price", H2)... | 2,866 |
51,263,370 | I am trying to implement k-nearest neighbor algorithm with the dataset which I have preprocessed. I imported the data as pandas dataframe and then converted it into numpy array but the following error is occuring-
```
File "/home/user/Documents/Mooc_implementation.py", line 8, in <module>
x = num_data[:,:10]
F... | 2018/07/10 | [
"https://Stackoverflow.com/questions/51263370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9355642/"
] | you use `.` instead of `->` because of this declaration of parameters:
`int ball_room(ball *b, int i, int n)`
`b` is expected to be pointer to data with type `ball`, so you can access it in various ways:
1. array way: e.g. `b[5].somefield = 15` - you use dot here, because if `b` is of type `ball *`, it means that `... | In C/C++ an array devolves into the address of it's first member. So when you pass the array to `ball_room` what actually gets passed is `&ball[0]`.
Now inside `ball_room` the reverse happens. `b` is a pointer to ball. But here you use it as an array `b[j]`. So it un-devolves back into an array of structs. So what `b[... | 2,867 |
58,411,930 | After all of web searching and coming up of no answer to this, I thought of asking this question on this platform. I had an application container which i try to connect with mine database container but due to reasons unaware mine application is not able to connect.
I am providing all the relevant information required f... | 2019/10/16 | [
"https://Stackoverflow.com/questions/58411930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182512/"
] | in my case
i changed
```
mysql://root:root@localhost:3307/db
```
to
```
mysql://root:root@Gateway ip:3307/test_db
```
the Gateway ip you can find it in
```
docker network ls
docker network inspect
``` | Change 'HOST': 'db' to 'HOST': '**localhost**' in settings.py file. Because you map the default MySQL port from container to MySQL default port in your main host. | 2,876 |
29,678,324 | I'm just learning python so be gentle. I want to read a file and that to be one function and then have another function work on what the previous function "read". I am having trouble passing the result on one function to another. Here is what I have no far:
I want to call read\_file more than once and to be able to pa... | 2015/04/16 | [
"https://Stackoverflow.com/questions/29678324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4797120/"
] | Here is your modified code (comments in uppercase for easier finding, not rudeness):
```
def read_file():
user_input = raw_input("please put date needed in x.xx form: ")
path = r'C:\\Users\\CP\\documents\\' + user_input
allFiles = glob.glob(path + '/*.csv')
frame = pd.DataFrame()
list = []
for ... | If you are trying to pass frame from one function to the other, you need to declare it outside the scope of the function. Otherwise we need more information about what you are trying to accomplish.
```
frame = None
def read_file():
user_input = raw_input("please put date needed in x.xx form: ")
path = r'C:\\Us... | 2,877 |
51,171,741 | I am using Python for the first time to create a simple JSON parser. However, when printing the JSON data to the console, it includes many extra brackets and other symbols that are unwanted. I am also running Python 2.7.10.
```
import json
from urllib2 import urlopen
response = urlopen("https://finance.yahoo.com/webs... | 2018/07/04 | [
"https://Stackoverflow.com/questions/51171741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6131554/"
] | I think you are actually printing a tuple with python 2 `print` syntax and the `u` character is a unicode flag ([What exactly do "u" and "r" string flags do, and what are raw string literals?](https://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-and-what-are-raw-string-literals)).
Also i... | Convert name and price to string
`print(str(name), str(price))`
or
use
`name = str(item['resource']['fields']['name'])` | 2,878 |
70,423,743 | I'm new in python and programming in general. I have this project to create a simple library to add new authors and upload books. I must also display the uploaded book details(total words, most common words, different words, etc.) when I open the book. Now to do this I know that I first must open the uploaded book in r... | 2021/12/20 | [
"https://Stackoverflow.com/questions/70423743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17725025/"
] | ```
<v-btn
class="mr-4"
:loading="saveLoading == index"
@click="submit(item, index)"
>
data: () => ({
valid: true,
saveLoading: -1,
})
submit (formItem, index) {
this.saveLoading = index
console.log(formItem)
// POST the formItem and make the saveLoading false in async then(),... | If you are generating the forms from the api response, mean that in some way you are attaching the response to the Vue Data property. If so, you could easily enrich the objects of the array (the forms object) to have a isLoading property. So the result will be something like:
```
API RESPONSE
[
{
form_name: ... | 2,879 |
37,143,664 | Just trying to pull some lat/lon info from EXIF data on a bunch of photos, but code is throwing a `KeyError` even though that key is used (successfully) later on to print specific coordinates.
Dictionary in question is "`tags`" - `'GPS GPSLatitude'` and `'GPS GPSLongitude'` are both keys in `tags.keys()`; I've triple... | 2016/05/10 | [
"https://Stackoverflow.com/questions/37143664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5957741/"
] | `GPS GPSLatitude` and `GPS GPSLongitude` may not be present in all tag dicts.
Instead of accessing keys as `tags['GPS GPSLatitude']` & `tags['GPS GPSLongitude']` , you can also access these as `tags.get('GPS GPSLatitude')` & `tags.get('GPS GPSLongitude')` This wil return `None` instead of throwing error, where you can... | I think @BryanOakley has the right idea. If the key isn't in the dict, it isn't there. (Those fields are optional, and some files might not have the data.) So you can use the `dict.get(key, default=None)` approach, and replace the Key Error with a default value.
```
jpegs = [file for file in os.listdir(path) if file.e... | 2,881 |
58,673,628 | I have been leaning python and programming for not so long. So you may find my question silly.
I am reviewing generator and try to generate 'yes', 'no' infinitely just to understand the concept.
I have tried this code but having "yes" each time
```
def yes_or_no():
answer = ["yes","no"]
i=0
while True:
... | 2019/11/02 | [
"https://Stackoverflow.com/questions/58673628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12308317/"
] | `yes_no()` produces the generator; you want to call `next` on the same generator each time, rather than printing the same first element over and over.
```
c = yes_no()
print(next(c))
print(next(c))
# etc.
```
That said, there's no need for a separate counter; just yield `yes`, then yield `no`, then repeat.
```
def... | You need to initialize the generator and then call `next` on the initialized generator object:
```
c = yes_or_no()
```
Now you need to call `next` on `c`:
```
print(next(c))
print(next(c))
```
---
In your current code `c=next(yes_or_no())`:
* `yes_or_no()` will initialize the generator and calling `next` on it ... | 2,882 |
19,351,065 | I'm trying to get a deeper understanding of how Python works, and I've been looking at the grammar shown at <http://docs.python.org/3.3/reference/grammar.html>.
I notice it says you would have to change parsermodule.c also, but truthfully I'm just not following what's going on here.
I understand that a grammar is a s... | 2013/10/13 | [
"https://Stackoverflow.com/questions/19351065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029146/"
] | That is basically an [EBNF](http://en.wikipedia.org/wiki/EBNF) (Extended Backus–Naur Form) specification. | When you write a program in a language, the very first thing your interpreter/compiler must do in order to go from a sequence of characters to actual action is to translate that sequence of characters in a higher complexity structure. To do so, first it chunks up your program in a sequence of tokens expressing what eac... | 2,884 |
53,515,926 | I have data stored in a parquet files and hive table partitioned by year, month, day. Thus, each parquet file is stored in `/table_name/year/month/day/` folder.
I want to read in data for only some of the partitions. I have list of paths to individual partitions as follows:
```py
paths_to_files = ['hdfs://data/table_... | 2018/11/28 | [
"https://Stackoverflow.com/questions/53515926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7064628/"
] | Reading the direct file paths to the parent directory of the year partitions should be enough for a dataframe to determine there's partitions under it. However, it wouldn't know what to name the partitions without the directory structure `/year=2018/month=10`, for example.
Therefore, if you have Hive, then going via ... | Your data isn't stored in a way optimal for parquet so you'd have to load files one by one and add the dates
Alternatively, you can move the files to a directory structure fit for parquet
( e.g. .../table/year=2018/month=10/day=29/file.parquet)
then you can read the parent directory (table) and filter on year, month, ... | 2,889 |
12,568,689 | I am new to python (2nd) day and working on a problem that asks me to Write a program that reads ASCII files (asks for file name as input), checks if it has more than
two words and prints out the two first words of the file on screen.
Its a little vague but I am going to assume the file is all str, deliminiated by sp... | 2012/09/24 | [
"https://Stackoverflow.com/questions/12568689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1690243/"
] | That code should be written as:
```
if len(words) > 2:
print 'There are more than two words'
firsttow = words[:2]
print firstrow
elif len(words) <2:
print 'There are under 2 words, no words will be shown'
```
Note the indentation, and the use of `elif` (which means "else if"). | ```
with codecs.open(name, encoding='utf-8') as f:
words=[] #define words here
for line in f:
line = line.lstrip(BOM)
words.extend(line.split()) #append words from each line to words
if len(words) > 2:
print 'There are more than two words'
firsttow = words[:2]
... | 2,890 |
5,093,153 | I'm wondering how to go about implementing a macro recorder for a python gui (probably PyQt, but ideally agnostic). Something much like in Excel but instead of getting VB macros, it would create python code. Previously I made something for Tkinter where all callbacks pass through a single class that logged actions. Unf... | 2011/02/23 | [
"https://Stackoverflow.com/questions/5093153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/98967/"
] | Thinking in high level, this is what I'd do:
Develop a decorator function, with which I'd decorate every event-handling functions.
This decorator functions would take note of thee function called, and its parameters (and possibly returning values) in a unified data-structure - taking care, on this data structure, to ... | An example of what you're looking for is in [mayavi2](http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/application.html#automatic-script-generation). For your purposes, mayavi2's "script record" functionality will generate a Python script that can then be trivially modified for other cases. I hear... | 2,891 |
2,032,706 | i have been trying to running some pinax code inside pydev eclipse
i keep on having this error
Error: Can't import Pinax. Make sure you are in a virtual environment that has Pinax installed or create one with pinax-boot.py.
my question is how do i run pinax inside eclipse using django built in server
i am python n... | 2010/01/09 | [
"https://Stackoverflow.com/questions/2032706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/81850/"
] | How about
```
map.connect ':user/:repo/commit/:sha', :action => :index
```
Or use `map.resource` instead of `map.connect` if you need a RESTful route.
In the controller, the URL information can be retrieved from params, for example `params[:user]` returns the username. | You can name your routes as you like, and specify which controllers and actions you'd like to use them with.
For example, you might have:
```
map.connect ':user/:repo/commit/:sha', :controller => 'transactions', :action => 'commit'
```
This would send the request to the 'commit' method in 'transactions' controller.... | 2,893 |
7,321,113 | I'm using Cairo/RSVG based solution for rasterizing SVG to PNG. It's already beeb described on StackOverflow in [Convert SVG to PNG in Python](https://stackoverflow.com/questions/6589358/convert-svg-to-png-in-python).
However, this solution doesn't seem to work with custom fonts.
I've found [this page describing embe... | 2011/09/06 | [
"https://Stackoverflow.com/questions/7321113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/60711/"
] | I have spent a week researching this very issue and concluded that the best way to handle server-side rendering/rasterizing of SVG with custom fonts is to install those fonts on the server. The tools I tried (rsvg, imagemagick, phantomjs, qtwebkit...) could not handle web fonts and svg fonts.
Google has [several hundr... | You can try to use [inkscape](http://www.inkscape.org), perhaps this gives you better results:
```
inkscape inputfile.svg --export-png=exportfile.png
```
Running this from python is described here: [Calling an external command in Python](https://stackoverflow.com/questions/89228/how-to-call-external-command-in-pyth... | 2,896 |
66,977,521 | I want to run arbitrary "code" in an argument like an anonymous function in Python.
How to do this in one single line?
Lambdas seems that does not work since they only take one expression.
```
def call_func(callback):
callback()
def f():
pkg_set_status(package_name, status)
print('ok')
call_func(f)
```
... | 2021/04/06 | [
"https://Stackoverflow.com/questions/66977521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3274630/"
] | The structure defined by myList with the `<ol>` elements is never actually added to the document. If you concatenate the `<ol>`, then the `<li>` entries, then `</ol>` all to wrapper.innerHTML then it should work.
For example something like...
```
var myList = "<ol>";
for (var i = 0; i < properties.length; i++) {
... | If you would check your structure in dev tools you would see there was no `ol` element in finale result.
So you can create it:
```
var myList = document.createElement("ol");
```
Then fill it with `li`:
```
myList.innerHTML
```
And then insert it:
```
idk.insertAdjacentElement("afterbegin", myList);
```
```j... | 2,899 |
46,966,690 | I have data like this:
```
0,tcp,http,SF,181,5450,0.11,0.00,0.00,0.00,,normal.
0,tcp,http,SF,239,486,0.05,0.00,0.00,0.00,normal.
0,tcp,http,SF,235,1337,0.03,0.00,0.00,0.00,normal.
0,tcp,http,SF,219,1337,0.03,0.00,0.00,0.00,normal.
```
The original data was stored in txt. I used list to store them in python. But the ... | 2017/10/27 | [
"https://Stackoverflow.com/questions/46966690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7428504/"
] | When accessing data or methods from within the vue object, use `this.thing`. In your case, that would be `this.strSlug(this.shop.name)`. | Does not work even with 'this.' because that function has not been defined at the time data is being initialized. I think you have to do it in the created() life-cycle hook. | 2,902 |
61,605,694 | I'm implementing a two-link acrobot simulation using pydrake and would like to enforce joint limits to prevent the lower link from colliding with the upper link. I've added the joint limits to the URDF and am parsing this URDF to generate an acrobot multibodyplant object. I've used functions to successfully verify that... | 2020/05/05 | [
"https://Stackoverflow.com/questions/61605694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13471747/"
] | I just tried to reproduce, and was also surprised that it doesn't appear to work.
Here is a runnable reproduction that violates the joint lower limit at the elbow, which is set to 0.0.
It also prints out the limit from the joint, confirming that the parsing worked.
<https://www.dropbox.com/s/2m12ws0g88t5uei/joint_l... | >
> ...but my simulation is not responding to those limits
>
>
>
what do you mean exactly?.
First, you should know that our joint limits are "soft", meaning that they are not constraints but more like stiff springs. `MultibodyPlant` computes the stiffness of these springs automatically for you to ensure the stab... | 2,904 |
57,221,919 | I try to install `docker-ce` on `redhat 8` but it failed
first, I try
```
# systemctl enable docker
Failed to enable unit: Unit file docker.service does not exist.
```
So, I want to install `docker-ce` for the daemon
```
# yum install yum-utils
# yum-config-manager --add-repo https://download.docker.com/linux/cen... | 2019/07/26 | [
"https://Stackoverflow.com/questions/57221919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11841974/"
] | yum install docker-ce --no-best worked for me
( Installed: docker-ce-3:18.09.1-3.el7.x86\_64 and Skipped: docker-ce-3:19.03.1-3.el7.x86\_64) | My guess, due to a missing subscription you cannot download packages from repositories the docker-ce package needs. So first register for a development account with redhat, then subscribe your host using the subscription Manager (remember, no production usage allowed then) and then retry the installation.
Edit: Here ar... | 2,906 |
28,299,754 | ```
a = [(24, 13), (23, 13), (22, 13), (21, 13), (20, 13),
(19, 13), (19, 14), (19, 15), (18, 15), (17, 15),
(16, 15), (15, 15), (14, 15), (13, 15), (13, 14),
(13, 13), (13, 12), (13, 11), (13, 10), (12, 10),
(11, 10), (10, 10), (9, 10), (8, 10), (7, 10),
(7, 9), (7, 8), (7, 7), (7, 6), (7, 5),... | 2015/02/03 | [
"https://Stackoverflow.com/questions/28299754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4296482/"
] | Probably not the prettiest solution, but the straightforward way would be this:
```
a = [(24, 13), (23, 13), (22, 13), (21, 13), (20, 13),
(19, 13), (19, 14), (19, 15), (18, 15), (17, 15),
(16, 15), (15, 15), (14, 15), (13, 15), (13, 14),
(13, 13), (13, 12), (13, 11), (13, 10), (12, 10),
(11, 10), ... | you can convert the tuples to numpy array, and check if after two legs, you moved in both axis.
```
arr = np.array(a)
((np.abs(arr[2:] - arr[:-2])>0).sum(axis=1)==2).sum()
``` | 2,911 |
71,040,681 | I have a Rancher Deskop(dockerd) on M1 MacOS and when I am trying to build below dockerfile I am getting an error such as below. Here is the command how I am trying to build the image `docker build -t te-grafana-dashboards-toolchain --no-cache .`
I tried to change the platforms but nonae of them worked for me. I am a ... | 2022/02/08 | [
"https://Stackoverflow.com/questions/71040681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12530530/"
] | Incidentally, in case it's helpful to another who lands here, I have the same issue on an M1 Max MacBook Pro laptop attempting to do a `docker build` from a company repo that should be a pretty well traveled path, but I might be the only one (it's a small company) that has an ARM64 M1 "Apple Silicon" Mac. ***However I ... | this resolved my issue.
```
FROM ubuntu:focal
RUN apt update; apt install -y curl jq build-essential python3.8 python3-pip docker-compose jsonnet bison mercurial
RUN ln -s /usr/bin/python3.8 /usr/bin/python
RUN curl -OL https://golang.org/dl/go1.17.linux-arm64.tar.gz; mkdir /etc/golang; tar -xvzf go1.17.linux-arm64.ta... | 2,913 |
10,851,121 | I am trying to use python to extract certain information from html code.
for example:
```
<a href="#tips">Visit the Useful Tips Section</a>
and I would like to get result : Visit the Useful Tips Section
<div id="menu" style="background-color:#FFD700;height:200px;width:100px;float:left;">
<b>Menu</b><br />
HTML<br />... | 2012/06/01 | [
"https://Stackoverflow.com/questions/10851121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1401233/"
] | You should use a proper HTML parsing library, such as the [HTMLParser](http://docs.python.org/library/htmlparser.html) module. | ```
string = '<a href="#tips">Visit the Useful Tips Section</a>'
re.findall('<[^>]*>(.*)<[^>]*>', string) //return 'Visit the Useful Tips Section'
``` | 2,922 |
2,509,927 | i have some python code(some functions) and i want to implement this in bigger matlab program!how can i do this?any help will be useful.... | 2010/03/24 | [
"https://Stackoverflow.com/questions/2509927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275695/"
] | You can use the [system](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/system.html) command to execute the Python code externally. To link it in more "natively" I think you'll have to go through C. That is, embed your Python code in C code and then expose it with a DLL to Matlab.
P.S. On windows you can al... | There is a library called [PyMat](http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html). It allows to call python code from matlab. | 2,930 |
39,136,134 | **cat test.py**
```
from importlib import import_module
bar = import_module('bar', package='project')
```
**ls project/**
```
__init__.py
__init__.pyc
bar.py
bar.pyc
```
**python test.py**
```
Traceback (most recent call last):
File "test.py", line 5, in <module>
bar = import_module('bar', package='pro... | 2016/08/25 | [
"https://Stackoverflow.com/questions/39136134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1252307/"
] | It needs a dot in front of bar .. :-(
```
bar = import_module('.bar', package='project')
``` | The documentation for [import\_lib](https://docs.python.org/2/library/importlib.html) says that
>
> If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import\_module('..mod', 'pkg.subpkg') will impo... | 2,935 |
43,600,114 | Im using python 3.4 and I am trying to make a recursive guessing game. The game should take a min value and a max value and have a "magic" number. The game is going to generate a random number in between the range of x and y. Then ask the user to insert y for yes l for too low, and h for too high. if it is yes 'congrat... | 2017/04/25 | [
"https://Stackoverflow.com/questions/43600114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7916637/"
] | This can be done with a simple function using four `if` statements to avoid adding out-of-bounds values:
```
#include <stdio.h>
#define BOARD_SZ 10
int sum_neighborhood(int, int, int [][BOARD_SZ], int, int);
int main(void)
{
int board[BOARD_SZ][BOARD_SZ] = { { 1, 0, 0, 1, 1, 1, 1, 1, 0, 1 },
... | ```
int add(const int **arr, size_t nrows, size_t ncols)
{
int sum = 0;
for (size_t i = 0; i < nrows; ++i)
for (size_t j = 0; j < ncols; ++j)
sum += arr[i][j];
return sum;
}
```
Use a pair of nested loops to walk the rows and columns. | 2,936 |
11,463,749 | I visited <http://www.sublimetext.com> today and was intrigued by the screencast animation the website has on its opening page. It looks like a mashup between video and slideshow. I've seen them at other modern websites as well, but I assumed it was some HTML5 video tag trickery. But when I looked at the source of subl... | 2012/07/13 | [
"https://Stackoverflow.com/questions/11463749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174527/"
] | Jon Skinner, the creator of Sublime Text wrote about the process [on his website](http://www.sublimetext.com/~jps/animated_gifs_the_hard_way.html)
He also published the encoder he wrote [on GitHub](https://github.com/sublimehq/anim_encoder) | look at one of their images and you'll understand how it works:
<http://www.sublimetext.com/anim/command_palette_packed.png>
they just cutting and inserting appropriate portions of image into the appropriate positions of canvas element, but if your question is how to make such image, I don't have an idea.
I guess wit... | 2,938 |
52,678,981 | I'm new to programing on python and working with scrapy. I am facing an error with the web crawling. I have used similar help pages on this site and even followed a tutorial from beginning to end to no avail, any help will be appreciated.
Error says: Spider error processing http://quotes.toscrape.com/> (referer: None)... | 2018/10/06 | [
"https://Stackoverflow.com/questions/52678981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10465578/"
] | The problem is your command prompt uses [cp437](https://en.wikipedia.org/wiki/Code_page_437) character set, which doesn't support some characters that you have just scraped (for example, “ and ”)
I don't think it is possible to print that characters to windows shell (maybe new PowerShells support it, I don't know). Yo... | I change a little my code and its work the way expected here is updated code:
```
#-*- coding: utf-8 -*-
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
allowed_domains = ["quotes.toscrape.com"]
start_urls = (
'http://quotes.toscrape.com/',
)
def parse(self, response):
... | 2,939 |
356,138 | I'm having a very peculiar problem in my Python FastCGI code - sys.stdout has a file descriptor of '-1', so I can't write to it.
I'm checking this at the first line of my program, so I know it's not any of my code changing it.
I've tried `sys.stdout = os.fdopen(1, 'w')`, but anything written there won't get to my brow... | 2008/12/10 | [
"https://Stackoverflow.com/questions/356138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44992/"
] | Forgive me if this is a dumb question, but I notice this line in your config file:
>
> Arguments=-u C:\app\app\_wsgi.py
>
>
>
Are you running a WSGI application or a FastCGI app? There *is* a difference. In WSGI, writing to stdout isn't a good idea. Your program should have an application object that can be calle... | On windows, it's possible to launch a proces without a valid stdin and stdout. For example, if you execute a python script with pythonw.exe, the stdout is invdalid and if you insist on writing to it, it will block after 140 characters or something.
Writing to another destination than stdout looks like the safest solut... | 2,940 |
41,231,316 | I've been trying to write this reduce method and I can't find a nice way to do it in java. I managed in python but it makes use of lots of python stuff and porting that to java seems like a real pain. Is there a more java way to do it?
Here's some test code, that should show what I mean if the title wasn't clear.
My ... | 2016/12/19 | [
"https://Stackoverflow.com/questions/41231316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4058774/"
] | Not sure about "nice", but it works:
```
public static <T> T[] reduce(T[] duplicated)
{
int len = duplicated.length;
for (int i = 1; i <= len / 2; i++) {
if (len % i == 0) {
if (checkFactors(i, duplicated)) {
return Arrays.copyOf(duplicated, i);
}
}
}... | So you want to test if an array is a smaller array repeated - now if, by your definition, `bigArray.length % smallArray.length != 0` means that it is NOT the smaller array repeated, I can give you a solution. In other words: If the smaller array doesn't fit inside the bigger array an even number of times, does that mea... | 2,946 |
46,028,830 | I've been fooling around with `__slots__` and searching about them a little, but I'm still confused about some specifics:
I'm aware that `__slots__` generates some kind of descriptors:
```py
>>> class C:
... __slots__ = ('x',)
...
>>> C.x
<member 'x' of 'C' objects>
>>> C.x.__get__
<method-wrapper '__get__' of ... | 2017/09/04 | [
"https://Stackoverflow.com/questions/46028830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7770274/"
] | >
> Where are actually storerd the values (since there is no dict) ? I was thinking it's something implemented in C and not directly accessible with Python code.
>
>
>
Memory is allocated for the `PyObject *` pointers directly in the object itself. You can see the handling in [`Objects/typeobject.c`](https://githu... | looking at your overall outlook, I've been working on performative solutions for custom setters on member descriptors for some time now, and this is the best I've come up with so far:
(tested with Anaconda 2.3.0 (Python 3.4.3) on wine, and Python 3.5.2 on linux)
**Note: This solution does not attempt to be pythonic... | 2,948 |
65,767,823 | I am new to using terminal in Mac. When I type any python3 command it only checks the users folder on my PC, HOW can I change the directory to open a folder in the users section and check for the .py file there? | 2021/01/18 | [
"https://Stackoverflow.com/questions/65767823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15026906/"
] | Access the desired path using `cd` command
```
cd path/to/access
```
Then you can run the python command to run the scripts. | If you know the name of the folder in which you want to check, you can change the current python directory using: `os.chdir`
<https://docs.python.org/3/library/os.html#os.chdir>
In that case it doesn't matter from where you're running your python script. | 2,949 |
62,292,262 | I am making a simple program in Python and I want from one file import a class that I made in another class. My code is the following:
```
#file cPoint.py
import math
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def printC(self):
print ("(",self.x,",",self.y,")")
```
and my... | 2020/06/09 | [
"https://Stackoverflow.com/questions/62292262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1960266/"
] | Create another row above your column title with the following formula. This will isolate the number, which can then be sorted according to its numerical value (tested, see screenshot below):
```
=LEFT(RIGHT(A3;LEN(A3)-16);LEN(A3)-21)
```
[](https://... | Try putting a zero in front of the single digits. Pad with more zeros if you have higher numbers.
56g\_flux\_data39(01)1992, 56g\_flux\_data39(02)1992, 56g\_flux\_data39(03)1992, all the way to 56g\_flux\_data39(11)1992 | 2,952 |
61,169,193 | I have a python code that prints Arabic text on vscode terminal, the output in the terminal appears in "unreadable" format.
code:
```
print('مرحبا')
```
output:
```
مرحبا
```
How can I solve this issue? | 2020/04/12 | [
"https://Stackoverflow.com/questions/61169193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3261292/"
] | to have a `String` variable formatted as {"Head1","Head2","Head3";1,2,3;4,5,6;7,8,9}, you can do as follows
```
Dim sValue As String, r As Range
For Each r In ThisWorkbook.Names("MyRange").RefersToRange.Rows
sValue = sValue & Join(Application.Transpose(Application.Transpose(r.Value)), ",") & ";"
Ne... | I think you are looking for
```
sValue = ThisWorkbook.Names("MyRange"),name
```
to find all names on Activesheet:
```
Sub test_names()
Dim wsName As String
wsName = ActiveSheet.Name
Dim nameRange As Variant
For Each nameRange In ThisWorkbook.Names
Set rngName = Range(nameRange)
wsP... | 2,953 |
16,569,784 | I'm using a *private* view in my Django project for an AJAX request.
```python
def HereIsSomeJSON(request, label):
if not request.method == "POST":
raise PermissionDenied
# Here is the job of my AJAX, basically feeding a JSON
json = {...}
return HttpResponse(json, "application/json")
```
Usi... | 2013/05/15 | [
"https://Stackoverflow.com/questions/16569784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1824222/"
] | Your approach of requiring POST for your ajax views is basically OK, and there is an [existing decorator](https://docs.djangoproject.com/en/dev/topics/http/decorators/) to handle it:
```
from django.views.decorators.http import require_POST
@require_POST
def my_view(request):
# I can assume now that only POST req... | As [@armonge](https://stackoverflow.com/users/407762/armonge) said, just checking for POST method doesn't do any protection. Suppose you need some checks, that user is registered and maybe have some permissions or needed properties. For this purpose, such decorator can be used (probably needs to be customized):
```
de... | 2,954 |
5,523,279 | it seems that I have some trouble understanding the semantics of the SUID bit, perhaps someone can help me clarify the situation.
My understanding of the semantic of the SUID bit are as follows:
When I set the SUID bit with a file, then the file will be executed as the owner of the file and not as the caller of the fi... | 2011/04/02 | [
"https://Stackoverflow.com/questions/5523279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/350403/"
] | Setting the SUID bit on a \*.py file does not help in any way here since the script is executed by the Python interpreter which must be set SUID in this case. Using 'sudo' is your better friend here. | Setting SUID does not work for scripts, because the kernel sees the #! (shebang - magic number 0x23 0x21 - man magic) and drops the privileges before calling the interpreter /usr/bin/python with the script as input. A way around is setting the python interpreter SUID root and add functionality to change privileges to t... | 2,956 |
55,683,072 | Actually, i'm very new to python and working on some image problem statement. Stuck in a problem and not able to get out of this.
I have data frame like:
```
Image RGB max_1 max_2 max_3
file1 [[224,43,234][22,5,224][234,254,220]] 234 224 254
file2 [[22,143,113][221,12... | 2019/04/15 | [
"https://Stackoverflow.com/questions/55683072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7721819/"
] | You can do something like this perhaps:
```
file1 = [[224,43,234],[22,5,224],[234,254,220]]
for idx, inner_list in enumerate(file1):
print('max_'+str(idx+1)+' : '+str(max(inner_list)))
``` | You said you have a data frame, so I assume it's a `pandas` `DataFrame` object.
In which case, you can use list comprehension to take the max from each sub-list in the list, and assign each element to a new column (this loop isn't elegant but will work):
```
df['max_colors'] = df['RGB'].apply(lambda x: [np.max(color)... | 2,959 |
59,333,904 | (I'm very new to both python and stackoverflow.)
```
def A():
def B():
print("I'm B")
A.B = B
A()
A.B()
```
output:
```
"I'm B"
```
This works well. What I want is to put that in a class like this(doesn't work. I just tried..)
```
class Student:
def A(self):
def B():
prin... | 2019/12/14 | [
"https://Stackoverflow.com/questions/59333904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386013/"
] | You don't need to reference *self* because the inner function *B* is defined there. It should be like this:
```
class Student:
def A(self):
def B():
print("I'm B")
B()
``` | I never use classes, but could you do it this way?
```
class A:
def __call__(self): // so you can call it like a function
def B():
print("i am B")
B()
call_A = A() // make the class callable
call_A() ... | 2,969 |
21,175,923 | The problem I am tackle with is to find the first occurrence node in its inorder traversal in a BST.
The code I have is given below
```
def Inorder_search_recursive(node,key):
if not node:
return None
InOrder_search_recursive(node.lChild)
if node.value==key:
return node
InOrder_search_... | 2014/01/17 | [
"https://Stackoverflow.com/questions/21175923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1824922/"
] | When you call yourself recursively, like this:
```
InOrder_search_recursive(node.lChild)
```
That's just a normal function call, like any other. It just calls the function and gets back a result. It doesn't automatically `return` the value from that function, or do anything else.
So, you do the left-subtree search,... | Since your problem is `to find the first occurrence node in its inorder traversal`, you should 1) traverse the tree in-order and 2) stop when you find the first occurrence.
```
def search(node, key):
if node is None:
return None
# Search the left subtree and return early if key is found
n = search(... | 2,972 |
24,488,891 | I have a django app and trying to set it up with gunicorn first and later with supervisor and nginx.
The app is running with the normal django command perfectly like `python manage.py runserver`
I installed the gunicorn using pip like `pip install gunicorn` and django version is `1.5.3`
when i run the below command ... | 2014/06/30 | [
"https://Stackoverflow.com/questions/24488891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1342109/"
] | You didn't show a full output. It probably looks like
```
$ gunicorn elcarweb.wsgi
[2015-10-27 21:01:47 +0000] [5429] [INFO] Starting gunicorn 19.2.1
[2015-10-27 21:01:47 +0000] [5429] [INFO] Listening at: http://127.0.0.1:8000 (5429)
[2015-10-27 21:01:47 +0000] [5429] [INFO] Using worker: sync
[2015-10-27 21:01:47 +0... | For anyone facing the same issue, the problem is usually something in django itself.
Activate your venv and run ./manage.py runserver
This will usually give you a more detailed error message. | 2,974 |
2,337,216 | Besides wrapping all your code in `try` `except`, is there any way of achieving the same thing as running your script like `python -mpdb script`? I'd like to be able to see what went wrong when an exception gets raised. | 2010/02/25 | [
"https://Stackoverflow.com/questions/2337216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31610/"
] | If you do not want to modify the source then yOu could run it from [ipython](http://ipython.scipy.org/moin/) - an enhanced interactive python shell.
e.g. run ipython then execute `%pdb on` to enable post-mortem debugging. `%run scriptname` will then run the script and automatically enter the debugger on any uncaught e... | `import pdb; pdb.set_trace()`
Source: <http://docs.python.org/library/pdb.html> | 2,984 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.