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 |
|---|---|---|---|---|---|---|
66,530,908 | I am using `gcc10.2`, `c++20`.
I am studying c++ after 2 years of python.
In python we always did run-time check for input validity
```
def createRectangle(x, y, width, height): # just for example
for v in [x, y, width, height]:
if v < 0:
raise ValueError("Cant be negative")
# blahblahbla... | 2021/03/08 | [
"https://Stackoverflow.com/questions/66530908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8471995/"
] | ```
for (int v : {x, y, width, height})
if (v < 0)
throw std::runtime_error("Can't be negative");
```
Note that such loop copies each variable twice. If your variables are heavy to copy (e.g. containers), use pointers instead:
```
for (const int *v : {&x, &y, &width, &height})
if (*v < 0)
...... | In C++:
1. Use an appropriate type so validation (at the point you *use* the variables as opposed to setting them up from some input) is unnecessary, e.g. `unsigned` for a length. C++ is more strongly typed than Python, so you don't need large validation checks to make sure the correct type is passed to a function.
2.... | 5,146 |
55,351,647 | I'm a beginner of python and follow a book to practice.
In my book, the author uses this code
```
s, k = 0
```
but I get the error:
```none
Traceback (most recent call last): File "<stdin>", line 1, in
<module> TypeError: 'int' object is not iterable
```
I want to know what happened here. | 2019/03/26 | [
"https://Stackoverflow.com/questions/55351647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7290997/"
] | You are asking to initialize two variables `s` and `k` using a single int object `0`, which of course is not iterable.
The corrrect syntax being:
```
s, k = 0, 0
```
**Where**
```
s, k = 0, 1
```
Would assign `s = 0` and `k = 1`
>
> Notice the each `int` object on the right being initialized to the
> corresp... | ```
s = k = 0
```
OR
```
s, k = (0, 0)
```
depends on what u need | 5,147 |
41,377,820 | I downgraded Postgres.app from 9.6 to 9.5 by removing the Postgres.app desktop app. I updated the database by doing
(I downloaded Postgres by downloading Postgres.app Desktop app and I installed Django by doing pip install Django)
```
sudo /usr/libexec/locate.updatedb
```
And it looks like it is initiating database... | 2016/12/29 | [
"https://Stackoverflow.com/questions/41377820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427176/"
] | This solves the problem for me:
1. uninstall your psycopg2
pip uninstall psycopg2
2. then do this
pip --no-cache-dir install -U psycopg2 | I think that your problem is that the version of `psycopg2` that is currently installed references the C postgres library that was bundled with your previous install of postgres (`/Applications/Postgres.app/Contents/Versions/9.6/lib/libpq.5.dylib`).
Try uninstalling and reinstalling `psycopg2`.
```
pip uninstall psyc... | 5,149 |
55,454,182 | Read dates from user input in the form yyyy,mm,dd. Then find number of days between dates. Datetime wants integers and input needs to be converted from string to integer. Previous questions seem to involve time or a different OS and those suggestions do not seem to work with Anaconda and Win10. I tried those which seem... | 2019/04/01 | [
"https://Stackoverflow.com/questions/55454182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8491388/"
] | Use `.strptime()` to convert string date to date object and then calculate diff
**Ex:**
```
import datetime
InitialDate = "2019,02,10" #input("Enter the begin date as yyyy,mm,dd")
FinalDate = "2019,02,20" #input("Enter the end date as yyyy,mm,dd")
InitialDate = datetime.datetime.strptime(InitialDate, "%Y,%m,%d"... | from datetime import datetime
InitialDate = input("Enter the begin date as yyyy/mm/dd: ")
FinalDate = input("Enter the end date as yyyy/mm/dd: ")
InitialDate = datetime.strptime(InitialDate, '%Y/%m/%d')
FinalDate = datetime.strptime(FinalDate, '%Y/%m/%d')
difference = FinalDate - InitialDate
print(difference.days) | 5,150 |
47,794,007 | So time.sleep isnt working. i am on python 3.4.3 and i have not had this problem on my computer with 3.6.
This is my code:
```
import calendar
def ProfileCreation():
Name = input("Name: ")
print("LOADING...")
time.sleep(1)
Age = input("Age: ")
print("LOADING...")
time.sleep(1)
ProfileAns ... | 2017/12/13 | [
"https://Stackoverflow.com/questions/47794007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9035852/"
] | You might want to `import time` as at the moment `time.sleep(1)` isn't actually defined, just add the import to the top of your code and this should fix it. | Change it to following:
```
import calendar
import time
def ProfileCreation():
Name = input("Name: ")
print("LOADING...")
time.sleep(1)
Age = input("Age: ")
print("LOADING...")
time.sleep(1)
ProfileAns = input("This matches no profiles. Create profile? ")
if ProfileAns.lower == 'yes':
... | 5,152 |
44,707,384 | For my evaluation, I wanted to run a rolling 1000 window `OLS regression estimation` of the dataset found in this URL:
<https://drive.google.com/open?id=0B2Iv8dfU4fTUa3dPYW5tejA0bzg>
using the following `Python` script.
```
# /usr/bin/python -tt
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
... | 2017/06/22 | [
"https://Stackoverflow.com/questions/44707384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1731796/"
] | `pd.stats.ols.MovingOLS` was removed in Pandas version 0.20.0
<http://pandas-docs.github.io/pandas-docs-travis/whatsnew.html#whatsnew-0200-prior-deprecations>
<https://github.com/pandas-dev/pandas/pull/11898>
I can't find an 'off the shelf' solution for what should be such an obvious use case as rolling regressions.... | It was [deprecated](https://github.com/pandas-dev/pandas/pull/11898) in favor of statsmodels.
See here [examples how to use statsmodels rolling regression](https://www.statsmodels.org/dev/examples/notebooks/generated/rolling_ls.html). | 5,154 |
60,008,614 | I have two dictionaries:
```
members_singles = {'member3': ['PCP3'], 'member4': ['PCP1'], 'member11': ['PCP2'], 'member12':
['PCP3'], 'member14': ['PCP4'], 'member15': ['PCP4'], 'member16': ['PCP4'], 'members17': ['PCP3']}
providers = {
"PCP1" : 3,
"PCP2" : 4,
"PCP3" : 1,
"PCP4" : 2,
"PCP5" : 4,
}
```
I want to it... | 2020/01/31 | [
"https://Stackoverflow.com/questions/60008614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11069614/"
] | When the `providers` count reaches zero, your code adds the provider to the `to_remove_zero` list. But the count may go negative later on, which will add the same provider to the `pcps_in_negative` list. At that point, your code needs to back-track and remove it from the `to_remove_zero` list:
```
providers[provider] ... | This is probably because you are altering the list, while expecting the indices to remain consistent:
```
a = [1,2,3]
a[0]
# 1
a.pop()
# 3
a[0]
# 1
``` | 5,155 |
55,501,746 | **Below is the problem I am running into:**
*Linear Regression - Given 16 pairs of prices (as dependent variable) and
corresponding demands (as independent variable), use the linear regression tool to estimate the best fitting
linear line.*
```
Price Demand
127 3420
134 3400
136 3250
139 3410
140 3190
141 3250
148 28... | 2019/04/03 | [
"https://Stackoverflow.com/questions/55501746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11307363/"
] | I would rewrite this to be simpler and remove unnecessary looping:
```
$filenameOut = "out.html"
#get current working dir
$cwd = Get-ScriptDirectory #(Get-Location).path #PSScriptRoot #(Get-Item -Path ".").FullName
$filenamePathOut = Join-Path $cwd $filenameOut
$InitialAppointmentGenArr = Get-ChildItem -Path $temp
... | Well, let's start with what you are attempting to do, and why it isn't working. If you look at the file object for any of those files (`$file|get-member`), you see that the `FullName` property only has a `get` method, no `set` method, so you can't change that property. So you are never going to change that property wit... | 5,156 |
31,096,151 | I am parsing streaming hex data with python regex. I have the following packet structure that I am trying to extract from the stream of packets:
```
'\xaa\x01\xFF\x44'
```
* \xaa - start of packet
* \x01 - data length [value can vary from 00-FF]
* \xFF - data
* \x44 - end of packet
i want to use python regex to ind... | 2015/06/28 | [
"https://Stackoverflow.com/questions/31096151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2163865/"
] | I ended up doing something as follows:
```
self.packet_regex = \
re.compile('(\xaa)([\x04-\xFF]{1})([\x00-\xFF]{1})([\x10-\xFF]{1})([\x00-\xFF]*)([\x00-\xFF]{1})(\x44)')
match = self.packet_regex.search(self.buffer)
if match and match.groups():
groups = match.groups()
if (ord(groups[1]) - 4) == le... | This is pretty much a work around for what you have asked. Just have a look at it
```
import re
orig_str = '\xaa\x01\xFF\x44'
print orig_str
#converting original hex data into its representation form
st = repr(orig_str)
print st
#getting the representation form of regex and removing leading and trailing single quotes ... | 5,157 |
50,841,542 | I am little bit familiar with np.fromregex. I read the tutorials and tried to implement it to read a data file.
When the file is read using simple python list comprehension, it gives the desired result:
`[400, 401, 405, 408, 412, 414, 420, 423, 433]`.
But, when `np.fromregex` is is gives another format answer:
`[(400... | 2018/06/13 | [
"https://Stackoverflow.com/questions/50841542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Just choose the group and you'll get what you want:
```
dt = [('num', np.int32)]
x = np.fromregex(ifile, regexp, dt)
print(x['num'])
#[400 401 405 408 412 414 420 423 433]
``` | ```
import numpy as np
import cStringIO
import re
data = """
DMStack failed for: lsst_z1.0_400.fits
DMStack failed for: lsst_z1.0_401.fits
DMStack failed for: lsst_z1.0_405.fits
DMStack failed for: lsst_z1.0_408.fits
DMStack failed for: lsst_z1.0_412.fits
DMStack failed for: lsst_z1.0_414.fits
DMStack failed for: lsst... | 5,158 |
63,814,809 | Hi i need to make a project for school where people can insert a review but before the review is posted on twitter it is going to be placed in a database. before it is going to be posted in twitter a moderator needs to check every review to see if there are no swear words etc. i wanted to make a small code in python wh... | 2020/09/09 | [
"https://Stackoverflow.com/questions/63814809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Try this code. I am not clear on what you are trying to do in
`output_table()` data frame.
```
library(shiny)
library(shinyWidgets)
# ui object
ui <- fluidPage(
titlePanel(p("Spatial app", style = "color:#3474A7")),
sidebarLayout(
sidebarPanel(
uiOutput("inputp1"),
numericInput("num", label = ("va... | First of all, you'd need to include a `req` in your `reactive()`, since `input$num` is not available at the initializing od your example:
```r
dt<-reactive({input$button
req(input$num)
name<-c("John","Jack","Bill")
value1<-c(2,4,6)
dt<-data.frame(name,value1)
dt$value1<-dt$value1*isolate(input$num)... | 5,160 |
57,264,952 | very new to python and hope can get some help here. I'm trying to sum up the total from different lists in dictionary
```
{'1': [0, 2, 2, 0, 0], '2': [0, 1, 1, 0, 0], '3': [2, 4, 2, 0, 2]}
```
I have been trying to find a way to sum up the total as follow and append in a new list:
```
'1': [0, 2, 2, 0, 0]
'2': [0, ... | 2019/07/30 | [
"https://Stackoverflow.com/questions/57264952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7280296/"
] | Using `zip()` ([doc](https://docs.python.org/3/library/functions.html#zip)) function to transpose dictionary values and `sum()` to sum them inside list comprehension:
```
d = {'1': [0, 2, 2, 0, 0], '2': [0, 1, 1, 0, 0], '3': [2, 4, 2, 0, 2]}
out = [sum(i) for i in zip(*d.values())]
print(out)
```
Prints:
```
[2, 7... | You can do like this,
```
In [6]: list(map(sum,zip(*d.values())))
Out[6]: [2, 7, 5, 0, 2]
``` | 5,161 |
43,742,143 | I have a text file that contains data in json format
```
{"Header":
{
"name":"test"},
"params":{
"address":"myhouse"
}
}
```
I am trying to read it from a python file and convert it to json format. I have tried with both yaml and json libraries, and, with both libraries, it converts it to json format, but it also co... | 2017/05/02 | [
"https://Stackoverflow.com/questions/43742143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5193545/"
] | Do this:
```
import json
with open("file.json", "r") as f:
obj = json.load(f)
with open("file.json", "w") as f:
json.dump(obj, f, indent = 4[, ensure_ascii = False]) # if your string has some unicode characters, let ensure_ascii to be False.
``` | You can use `json.load` to load a json object from a file.
```
import json
with open("file.json", "r") as f:
obj = json.load(f)
```
The resulting json object delimits strings with `'` rather than `"`, but you can easily use a `replace` call at that point.
```
In [6]: obj
Out[6]: {'Header': {'name': 'test'}, 'pa... | 5,162 |
58,709,973 | * when running Python test from withing VS Code using CTRL+F5 I'm getting error message
*ImportError: attempted relative import with no known parent package*
[](https://i.stack.imgur.com/jb... | 2019/11/05 | [
"https://Stackoverflow.com/questions/58709973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93277/"
] | Do not use relative import.
Simply change it to
```
from solutions import helloWorldPackage as hw
```
**Update**
I initially tested this in PyCharm. PyCharm has a nice feature - it adds content root and source roots to PYTHONPATH (both options are configurable).
You can achieve the same effect in VS Code by adding... | >
> Setup a main module and its source packages paths
> =================================================
>
>
>
Solution found at:
* [https://k0nze.dev/posts/python-relative-imports-vscode/#:~:text=create%20a%20settings.json%20within%20.vscode](https://k0nze.dev/posts/python-relative-imports-vscode/#:%7E:text=cre... | 5,163 |
62,494,807 | I have the following python script
```
from bs4 import BeautifulSoup
import requests
home_dict = []
for year in range(2005, 2021):
if year == 2020:
for month in range(1, 6):
url = 'https://www.rebgv.org/market-watch/MLS-HPI-home-price-comparison.hpi.all.all.' + str(year) + '-' + str(month) + ... | 2020/06/21 | [
"https://Stackoverflow.com/questions/62494807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11303284/"
] | Perhaps try a `try` clause?
```
for year in range(2005, 2021):
month in range(1, 13):
try:
<your code>
except:
continue
``` | As scraping for 1 to 6 months is common for all the years. You can **scrape** those years first. And then if the year is not equal to 2020 you can **scrape** rest of the years | 5,171 |
67,790,430 | I have a big text file that has around 200K lines of records/lines.
But I need to extract only specific lines which Start with CLM. For example, if the file has 100K lines that start with CLM I should print all that 100K lines alone.
Can anyone help me to achieve this using python script? | 2021/06/01 | [
"https://Stackoverflow.com/questions/67790430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15924358/"
] | this would work:
```
df2[, colnames(df2) %in% colnames(df1)]
x3 x4 x7 x10 x12
1 IL_NA1A_P IL_NA3D_P PROD009_P PROD014_P PROD023A_P
```
You simply check which column-names of `df2` appear also in `df1` and select these columns from `df2`. | If all of `df1` column names are present in `df2` you can use -
```
df2[names(df1)]
# x3 x4 x7 x10 x12
#1 IL_NA1A_P IL_NA3D_P PROD009_P PROD014_P PROD023A_P
```
If only few of `df1` column names are present in `df2` you can either use -
```
df2[intersect(names(df2), names(df1))]
... | 5,174 |
6,652,492 | I have a Java project that utilizes Jython to interface with a Python module. With my configuration, the program runs fine, however, when I export the project to a JAR file, I get the following error:
```
Jar export finished with problems. See details for additional information.
Fat Jar Export: Could not find class-... | 2011/07/11 | [
"https://Stackoverflow.com/questions/6652492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/584676/"
] | This is not supported by Windows Installer. Elevation is usually handled by the application through its [manifest](http://msdn.microsoft.com/en-us/library/bb756929.aspx).
A solution is to create a wrapper (VBScript or EXE) which uses [ShellExecute](http://msdn.microsoft.com/en-us/library/bb762153%28VS.85%29.aspx) with... | Sorry for the confusion - I now understand what you are after.
There are indeed ways to set the shortcut flag but none that I know of straight in Visual Studio. I have found a number of functions written in C++ that set the SLDF\_RUNAS\_USER flag on a shortcut.
Some links to such functions include:
* <http://blogs.m... | 5,177 |
38,644,397 | I am trying to make a login system with python and mysql. I connected to the database, but when I try to insert values into a table, it fails. I'm not sure what's wrong. I am using python 3.5 and the PyMySQL module.
```
#!python3
import pymysql, sys, time
try:
print('Connecting.....')
time... | 2016/07/28 | [
"https://Stackoverflow.com/questions/38644397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6544457/"
] | It looks like the `get`/`getAs` methods mentioned in the example are just convenience wrappers for the `fetch` method. See <https://github.com/http4s/http4s/blob/a4b52b042338ab35d89d260e0bcb39ccec1f1947/client/src/main/scala/org/http4s/client/Client.scala#L116>
Use the `Request` constructor and pass `Method.POST` as t... | ```
import org.http4s.circe._
import org.http4s.dsl._
import io.circe.generic.auto._
case class Name(name: String)
implicit val nameDecoder: EntityDecoder[Name] = jsonOf[Name]
def routes: PartialFunction[Request, Task[Response]] = {
case req @ POST -> Root / "hello" =>
req.decode[Name] { name =>
... | 5,183 |
66,503,032 | Is there anyway that I could make the function below faster and more optimized with `pandas` or `numpy`, the function below adds the sum of `seq45` until the elements of it is equivalent or over 10000.The elements that is being added up to `seq45` are `3,7,11` in order. The reason why i want to increase the speed is to... | 2021/03/06 | [
"https://Stackoverflow.com/questions/66503032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15217016/"
] | You can input numbers using scanner class similar to the following code from w3schools:
```
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
... | put count++; after the last print statement | 5,186 |
62,929,576 | I would like to approximate bond yields in python. But the question arose which curve describes this better?
------------------------------------------------------------------------------------------------------------
```
import numpy as np
import matplotlib.pyplot as plt
x = [0.02, 0.22, 0.29, 0.38, 0.52, 0.55, 0.67... | 2020/07/16 | [
"https://Stackoverflow.com/questions/62929576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12412154/"
] | This may help you. I'm not sure but this works for me
### Signout Fuction
```dart
Future _signOut() async {
try {
return await auth.signOut();
} catch (e) {
print(e.toString());
return null;
}
}
```
### Function Usage
```dart
IconButton(
onPressed: () async {
await _auth.signO... | You need to have AuthWidgetBuilder as top-level widget (ideally above MaterialApp) so that the entire widget tree is rebuilt on sign-in / sign-out events.
You could make SplashScreen a child, and have some conditional logic to decide if you should present it.
By the way, if your splash screen doesn't contain any anim... | 5,188 |
61,645,140 | I am really struggling with this issue.
In the below, I take a domain like something.facebook.com and turn it into facebook.com using my UDF.
I get this error though:
```
UnicodeEncodeError: 'ascii' codec can't encode characters in position 64-65: ordinal not in range(128)
```
I've tried a few things to get around... | 2020/05/06 | [
"https://Stackoverflow.com/questions/61645140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9629771/"
] | This seems to solve it. Interestingly, the output is never 'unicode error'
```
def cleanup(domain):
try:
if domain is None or domain == '':
domain = 'empty'
return str(domain)
for tld in toplevel:
if tld in domain:
... | Try this one.
```
def cleanup(domain):
#Test the empt Entry
if domain is None or domain == '':
domain = 'empty'
return domain
listSub = domain.split('.')
result = listSub[1]
#get the part we need www.facebook.com > .facebook.com
for part in listSub[2:]:
result = result + '.' + par... | 5,189 |
13,365,876 | I am using python [tox](http://pypi.python.org/pypi/tox) to run python unittest for several versions of python, but these python interpreters are not all available on all machines or platforms where I'm running tox.
How can I configure tox so it will run tests only when python interpretors are available.
Example of `... | 2012/11/13 | [
"https://Stackoverflow.com/questions/13365876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/99834/"
] | As of Tox version 1.7.2, you can pass the `--skip-missing-interpreters` flag to achieve this behavior. You can also set `skip_missing_interpreters=true` in your `tox.ini` file. More info [here](http://tox.readthedocs.org/en/latest/config.html#confval-skip_missing_interpreters=BOOL).
```
[tox]
envlist =
py24, py25,... | tox will display an Error if an interpreter cannot be found. Question is up if there should be a "SKIPPED" state and making tox return a "0" success result. This should probably be explicitely enabled via a command line option. If you agree, file an issue at <http://bitbucket.org/hpk42/tox> . | 5,190 |
68,564,322 | I have a 143k lowcase word dictionary and I want to count the frequency of the first two letters
(ie: `aa* = 14, ab* = 534, ac = 714` ... `za = 65,` ... `zz = 0` ) and put it in a bidimensional array.
However I have no idea how to even go about iterating them without switches or a bunch of if elses I tried looking on ... | 2021/07/28 | [
"https://Stackoverflow.com/questions/68564322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16498000/"
] | The code assumes that the input has one word per line without leading spaces and will count all words that start with two ASCII letters from `'a'`..`'z'`. As the statement in the question is not fully clear, I further assume that the character encoding is ASCII or at least ASCII compatible. (The question states: "there... | Such job is more suitable for languages like Python, Perl, Ruby etc. instead of C. I suggest at least trying C++.
If you don't have to write it in C, here is my Python version: (since you didn't mention it in the question - are you working on an embedded system or something where C/ASM are the only options?)
```py
FI... | 5,193 |
68,932,000 | ```
from typing import List
def dailyTemperatures(temperatures: List[int]) -> List[int]:
temp_count = len(temperatures)
ans = [0]*temp_count
stack = []
idx_stack = []
for idx in range(temp_count-1,-1,-1): // first point
temperature = temperatures[idx]
last_temp_idx = 0
while ... | 2021/08/26 | [
"https://Stackoverflow.com/questions/68932000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16607199/"
] | Since the address of `cs` is sent to a function and that function may spawn goroutines that may hold a reference to `cs` after the function returns, it is moved to heap.
In the second case, `cs` is a pointer. There is no need to move the pointer itself to the heap, because that the function `Unmarshal` can refer to is... | `proto.Unmarshal`
```
func Unmarshal(buf []byte, pb Message)
```
```
type Message interface {
Reset()
String() string
ProtoMessage()
}
```
interface{} can be every type, It is difficult to determine the specific types of its parameters during compilation, and escape will also occur.
but if interface{}... | 5,202 |
66,675,001 | I'm trying to use `sklearn_porter` to train a Random Forest Modell in python which then should be exported to C code.
This is my code:
```
from sklearn_porter import Porter
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
import sys
sys.path.append('../../../../..')
iris_data... | 2021/03/17 | [
"https://Stackoverflow.com/questions/66675001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12959163/"
] | You should use `connects_to database: { writing: :wn }`
When you specify only `reading:` keyword you will get this error `No connection pool for 'Wn' found`. You can only use `reading:` together with `writing:` when you have a read replica.
See docs for more info <https://edgeguides.rubyonrails.org/active_record_mult... | Create an abstract class in `models/wn.rb` ...
```
class Wn < ActiveRecord::Base
self.abstract_class = true
connects_to database: { reading: :wn }
end
```
then in `models/ci_harves_record.rb`
```
class CiHarvestRecord < Wn
self.table_name = "ciHarvest"
end
``` | 5,203 |
23,530,703 | We're currently working with Cassandra on a single node cluster to test application development on it. Right now, we have a really huge data set consisting of approximately 70M lines of texts that we would like dump into a Cassandra.
We have tried all of the following:
* Line by line insertion using python Cassandra ... | 2014/05/08 | [
"https://Stackoverflow.com/questions/23530703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3613688/"
] | The sstableloader is the fastest way to import data into Cassandra. You have to write the code to generate the sstables, but if you really care about speed this will give you the most bang for your buck.
This article is a bit old, but the basics still apply to how you [generate the SSTables](http://www.datastax.com/de... | I have a two node Cassandra 2.? cluster. Each node is I7 4200 MQ laptop, 1 TB HDD, 16 gig RAM). Have imported almost 5 billion rows using copy command. Each CSV file is a about 63 gig with approx 275 million rows. Takes about 8-10 hours to complete the import/per file.
Approx 6500 rows per sec.
YAML file is set to u... | 5,204 |
17,155,724 | So I am working on this project where I take input from the user (a file name ) and then open and check for stuff. the file name is "cur"
Now suppose the name of my file is `kb.py` (Its in python)
If I run it on my terminal then first I will do:
python kb.y and then there will a prompt and user will give the input.
I'... | 2013/06/17 | [
"https://Stackoverflow.com/questions/17155724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2438430/"
] | Just use `sys.argv`, like this:
```
import sys
# this part executes when the script is run from the command line
if __name__ == '__main__':
if len(sys.argv) != 2: # check for the correct number of arguments
print 'usage: python kb.py cur'
else:
call_your_code(sys.argv[1]) # first command line ... | For simply stuff `sys.argv[]` is the way to go, for more complicated stuff, have a look at the [argparse-module](http://docs.python.org/2/howto/argparse.html)
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
action="store_true... | 5,205 |
72,215,886 | How to write python code that let the computer know if the list is a right sequence and the position doesn't matter, it will return true, otherwise it return false.
below are some of my example, I really don't know how to start
```
b=[1,2,3,4,5] #return true
b=[1,2,2,1,3] # return false
b=[2,3,1,5,4] #return true
b=[2... | 2022/05/12 | [
"https://Stackoverflow.com/questions/72215886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | sort function is O(nlogn), we can use for loop which is O(n):
```
def check_seq(in_list):
now_ele = set()
min_ele = max_ele = in_list[0]
for i in in_list:
if i in now_ele:
return False
min_ele = min(i, min_ele)
max_ele = max(i, max_ele)
now_ele.add(i)
if ma... | This question is quite simple and can be solved a few ways.
1. The conditional approach - if there is a number that is bigger than the length of the list, it automatically cannot be a sequence because there can only be numbers from 1-n where n is the size of the list. Also, you have to check if there are any duplicate... | 5,206 |
46,725,942 | I'm writing some calculation tasks which would be efficient in Python or Java, but Sidekiq does not seem to support external consumers.
I'm aware there's a workaround to spawn a task using system call:
```
class MyWorker
include Sidekiq::Worker
def perform(*args)
`python script.py -c args` # and watch out us... | 2017/10/13 | [
"https://Stackoverflow.com/questions/46725942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3340588/"
] | You can use apply and which:
```
df <- data.frame( x1 = c(0, 0, 1), x2 = c(1, 0 , 0), x3 = c(0, 1 , 0) )
idx <- apply( df, 1, function(row) which( row == 1 ) )
cbind( df, Number = colnames( df[ , idx] ) )
x1 x2 x3 Number
1 0 1 0 x2
2 0 0 1 x3
3 1 0 0 x1
``` | We can use `max.col` to find the column index of logical matrix (`df1[-1]=="1+"`). Add 1 to it because we used only from 2nd column. Then, with `names(df1)` get the corresponding names
```
df1$Number <- names(df1)[max.col(df1[-1]=="1+")+1]
df1$Number
#[1] "X3000" "X1234" "X7500"
``` | 5,210 |
8,722,182 | I'm getting a "DoesNotExist" error with the following set up - I've been trying to debug for a while and just can't figure it out.
```
class Video(models.Model):
name = models.CharField(max_length=100)
type = models.CharField(max_length=100)
owner = models.ForeignKey(User, related_name='videos')
...
... | 2012/01/04 | [
"https://Stackoverflow.com/questions/8722182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/801820/"
] | Since you have not posted your full traceback, my guess is that your owner FK is not optional, and you are not specifying one in your model form.
You need to post a full traceback. | I think it has to be class `VideoForm(ModelForm)` instead of `VideoForm(modelForm)`.
If you aren't going to use the foreign key in the form use `exclude = ('owner')` | 5,215 |
21,356,122 | I have a small project at home, where I need to scrape a website for links every once in a while and save the links in a txt file.
The script need to run on my Synology NAS, therefore the script needs to be written in bash script or python without using any plugins or external libraries as I can't install it on the NA... | 2014/01/25 | [
"https://Stackoverflow.com/questions/21356122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3235644/"
] | You can use `urllib2` that ships as free with Python. Using it you can easily get the html of any url
```
import urllib2
response = urllib2.urlopen('http://python.org/')
html = response.read()
```
Now, about the parsing the html. You can still use `BeautifulSoup` without installing it. From [their site](http://www.c... | I recommend using Python's htmlparser library. It will parse the page into a hierarchy of objects for you. You can then find the a href tags.
<http://docs.python.org/2/library/htmlparser.html>
There are lots of examples of using this library to find links, so I won't list all of the code, but here is a working examp... | 5,216 |
22,180,285 | My python function is given a (long) list of path arguments, each of which can possibly be a glob. I make a pass over this list using `glob.glob` to extract all the matching filenames, like this:
```
files = [filename for pattern in patterns for filename in glob.glob(pattern)]
```
That works, but the filesystem I'm... | 2014/03/04 | [
"https://Stackoverflow.com/questions/22180285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1061433/"
] | According to [the fnmatch source code](http://code.google.com/p/unladen-swallow/source/browse/trunk/Lib/fnmatch.py), the only special characters it recognizes are `*`, `?`, `[` and `]`. Hence any pattern that does not contain any of these will only match itself. We can therefore implement the `cheapglob` mentioned in t... | I don't think you'll find much, as your idea of a trivial pattern might not be mine. Also, from a comp-sci point of view, it might be impossible to tell from inspection whether a pushdown automata is going to run in a set amount of time given the inputs you're running it against, without actually running it against tho... | 5,218 |
60,538,828 | Here I am trying to scrape the teacher jobs from the <https://www.indeed.co.in/?r=us> I want to get that uploaded to the excel sheet like jobtitle, institute/school, salary, howmanydaysagoposted
I wrote the code for scraping like this but I am getting all the text from the xpath which I defined
```
import selenium.we... | 2020/03/05 | [
"https://Stackoverflow.com/questions/60538828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12798693/"
] | I'd encourage you to checkout beautiful soup <https://pypi.org/project/beautifulsoup4/>
I've used this for scraping tables,
```
def read_table(table):
"""Read an IP Address table.
Args:
table: the Soup <table> element
Returns:
None if the table isn't an IP Address table, otherwise a list of
... | You'll have to nevigate to every page and **scrape** them one by one i.e. you'll have to automate click on next page button in selenium(use xpath of Next Page button element). Then extract using page source function.
Hope I could help. | 5,219 |
22,258,738 | I am trying to list items in a S3 container with the following code.
```
import boto.s3
from boto.s3.connection import OrdinaryCallingFormat
conn = boto.connect_s3(calling_format=OrdinaryCallingFormat())
mybucket = conn.get_bucket('Container001')
for key in mybucket.list():
print key.name.encode('utf-8')
```
T... | 2014/03/07 | [
"https://Stackoverflow.com/questions/22258738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394040/"
] | As @garnaat mentioned and @Rico [answered in another question](https://stackoverflow.com/a/22462419/3162882) `connect_to_region` works with `OrdinaryCallingFormat`:
```
conn = boto.s3.connect_to_region(
region_name = '<your region>',
aws_access_key_id = '<access key>',
aws_secret_access_key = '<secret key>',
... | in terminal run
>
> nano ~/.boto
>
>
>
if there is some configs try to comment or rename file and connect again. (it helps me)
<http://boto.cloudhackers.com/en/latest/boto_config_tut.html>
there is boto config file directories. take a look one by one and clean them all, it will work by default configs. also co... | 5,221 |
56,832,149 | I have an awkward csv file and I need to skip the first row to read it.
I'm doing this easily with python/pandas
```
df = pd.read_csv(filename, skiprows=1)
```
but I don't know how to do it in Go.
```
package main
import (
"encoding/csv"
"fmt"
"log"
"os"
)
type mwericsson struct {
id stri... | 2019/07/01 | [
"https://Stackoverflow.com/questions/56832149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8660255/"
] | >
> skip the first row when reading a csv file
>
>
>
---
For example,
```
package main
import (
"bufio"
"encoding/csv"
"fmt"
"io"
"os"
)
func readSample(rs io.ReadSeeker) ([][]string, error) {
// Skip first row (line)
row1, err := bufio.NewReader(rs).ReadSlice('\n')
if err != ni... | Simply call [`Reader.Read()`](https://golang.org/pkg/encoding/csv/#Reader.Read) to read a line, then proceed to read the rest with [`Reader.ReadAll()`](https://golang.org/pkg/encoding/csv/#Reader.ReadAll).
See this example:
```
src := "one,two,three\n1,2,3\n4,5,6"
r := csv.NewReader(strings.NewReader(src))
if _, err... | 5,222 |
11,774,163 | this is the idea. I'll have 'main' python script that will start (using subprocess) app1 and app2. 'main' script will send input to app1 and output result to app2 and vice versa (and main script will need to remember what was sent so I can't send pipe from app1 to app2).
This is main script.
```
import subprocess
imp... | 2012/08/02 | [
"https://Stackoverflow.com/questions/11774163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/554778/"
] | Add `prvi.stdin.flush()` after `prvi.stdin.write(...)`.
Explanation: To optimize communication between processes, the OS will buffer 4KB of data before it sends that whole buffer to the other process. If you send less data, you need to tell the OS "That's it. Send it *now*" -> `flush()`
**[EDIT]** The next problem is... | **main.py**
```
import subprocess
import time
def main():
prvi = subprocess.Popen(['python', 'random1.py'], stdin = subprocess.PIPE , stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
prvi.stdin.write('131231\n')
time.sleep(1) # maybe it needs to wait
print "procitano", prvi.stdout.read()
if __n... | 5,225 |
4,181,573 | Is there such a program that can open a little input box and send the input to stdout? If there isn't, any suggestions for how to do this (maybe python with TkInter)? | 2010/11/15 | [
"https://Stackoverflow.com/questions/4181573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/507857/"
] | If you're looking for something that works in text mode, then [`dialog`](http://linux.die.net/man/1/dialog) or [`whiptail`](http://linux.die.net/man/1/whiptail) are two options. | The oldest would probably be [dialog](http://www.linuxjournal.com/article/2807). Another example of such a program is [Zenity](http://freshmeat.net/projects/zenity) and another would be [Xdialog](http://xdialog.free.fr/) (all pretty much replacements for dialog).
They tend to do more than just accepting user input, a... | 5,227 |
10,592,891 | Dear Stack Overflow community,
I'm writing in hopes that you might be able to help me connect to an 802.15.4 wireless transceiver using C# or C++. Let me explain a little bit about my project. This semester, I spent some time developing a wireless sensor board that would transmit light, temperature, humidity, and moti... | 2012/05/15 | [
"https://Stackoverflow.com/questions/10592891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1394922/"
] | Thanks everyone for the help. The key to everything was using [LibUSBDotNet](http://sourceforge.net/projects/libusbdotnet/). Once I had installed and referenced that into my project... I was able to create a console window that could handle the incoming sensor data. I did need to port some of the functions from the ori... | I'm not 100% sure on exactly how to do this but after having a quick look around I can see that the core of the problem is you need to implement something like the ZigBoard lib in C#.
The ZigBoard lib uses a python USB lib to communicate using an API with the USB device, you should be able to [LibUsbDotNet](http://sou... | 5,228 |
56,081,778 | I have a shell script which runs to predict something on raspberrypi which has python version 2.7 as well as 3.5. To support audio features I have made python 3.5 as default. when I run the shell script it is taking version 2.7 and throwing an error.[The error is shown in this link](https://i.stack.imgur.com/QhlMc.png) | 2019/05/10 | [
"https://Stackoverflow.com/questions/56081778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9350170/"
] | It's not exactly clear based on the wording of your question how you have your scripts are set up. However, if you are calling python in the shell script, you can always specify python3 or python2 instead of just calling python (which points to your system's default). This would look something like this:
```
$ python3... | I would suggest [adding an alias to the root bashrc file](https://askubuntu.com/a/492787) as you seem to be calling this thing as the root user.
something to the effect of `alias python=python3.5` at the bottom of the file `~root/.bashrc` may have the effect your looking for although I'm sure there's a more permanent ... | 5,229 |
35,074,895 | I have a module with constants (data types and other things).
Let's call the module constants.py
Let's pretend it contains the following:
```
# noinspection PyClassHasNoInit
class SimpleTypes:
INT = 'INT'
BOOL = 'BOOL'
DOUBLE = 'DOUBLE'
# noinspection PyClassHasNoInit
class ComplexTypes:
LIST = 'LIS... | 2016/01/29 | [
"https://Stackoverflow.com/questions/35074895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3240126/"
] | I think I have it. You can use **inspect.getmembers** to return the items in the module. Each item is a tuple of (*name*, *value*). I tried it with the following code. **dir** gives only the names of the module members; **getmembers** also returns the values. You can look for the desired value in the second element of ... | The builtin method .dir(class) will return all the attributes of a class given. Your if statement can therefore be `if myVar in dir(constants.ComplexTypes):` | 5,231 |
12,645,195 | To install python IMagick binding wand api on windows 64 bit (python 2.6)
This is what I did:
1. downloaded and installed [ImageMagick-6.5.8-7-Q16-windows-dll.exe](http://www.imagemagick.org/download/binaries/ImageMagick-6.5.8-7-Q16-windows-dll.exe)
2. downloaded `wand` module from <http://pypi.python.org/pypi/Wand>
... | 2012/09/28 | [
"https://Stackoverflow.com/questions/12645195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1705984/"
] | You have to set `MAGICK_HOME` environment variable first. See the last part of [this section](http://docs.wand-py.org/en/0.2-maintenance/guide/install.html#install-imagemagick-on-windows).
>
> [](https://i.stack.imgur.com/KKEG5.png)
>
> (source: [wand-py.org](http://docs.wan... | First i had to install ImageMagic and set Envrioment Variable `MAGIC_HOME` ,just after i was able to install `Wand` from `pip` | 5,234 |
62,062,054 | I'm new to docker and I created a docker image and this is how my docker file looks like.
```
FROM python:3.8.3
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
postgresql-client \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get install -y gcc libtool-ltdl-devel xmlsec1-1.2.20 xmlsec1-... | 2020/05/28 | [
"https://Stackoverflow.com/questions/62062054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10437046/"
] | When you give `CMD` (or `RUN` or `ENTRYPOINT`) in the JSON-array form, you're responsible for manually breaking up the command into "words". That is, you're running the equivalent of the quoted shell command
```sh
'tail -f /dev/null'
```
and the whole thing gets interpreted as one "word" -- the spaces and options ar... | `CMD` will append after `ENTRYPOINT`
Since node:12.17.0-alpine have default `ENTRYPONINT node`
Your dockerfile will becomes
```
node tail -f /dev/null
```
### option1
Override ENTRYPOINT in build time
```
ENTRYPOINT tail -f /dev/null
```
### option2
Override ENTRYPOINT in run time
```
docker run --entrypoint... | 5,235 |
9,629,477 | For example, given a python numpy.ndarray `a = array([[1, 2], [3, 4], [5, 6]])`, I want to select the 0th and 2nd row of array `a` into a new array `b`, such that `b` becomes `array([[1,2],[5,6]]`.
I need to solution to work on more general problems, where the original 2d array can have more rows and I should be able ... | 2012/03/09 | [
"https://Stackoverflow.com/questions/9629477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/228173/"
] | You can use list indexing:
```
a[ [0,2], ]
```
More generally, to select rows `i:j` and `k:p` (I'm assuming in the python sense, meaning rows i to j but not including j):
```
a[ range(i,j) + range(k,p) , ]
```
Note that the `range(i,j) + range(k,p)` creates a *flat* list of `[ i, i+1, ..., j-1, k, k+1, ..., p-1... | `numpy` is kind of clever when it comes to indexing. You can give it a list of indexes and it will return the sliced part.
```
In : a = numpy.array([[i]*10 for i in range(10)])
In : a
Out:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[3, 3... | 5,238 |
54,995,041 | I'm coding with python 3.6 and am working on a Genetic Algorithm. When generating a new population, when I append the new values to the array all the values in the array are changed to the new value. Is there something wrong with my functions?
Code:
```
from fuzzywuzzy import fuzz
import numpy as np
import random
im... | 2019/03/05 | [
"https://Stackoverflow.com/questions/54995041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10227474/"
] | The Appium method hideKeyboard() is **known to be unstable** when used on iPhone devices, as listed in Appium’s currently known open issues. Using this method for an iOS device may cause the Appium script to hang. Appium identifies that the problem is because - "There is no automation hook for hiding the keyboard,...ra... | The Appium method hideKeyboard() is known to be unstable when used on iPhone devices, as listed in Appium’s currently known open issues. Using this method for an iOS device may cause the Appium script to hang. Appium identifies that the problem is because - "There is no automation hook for hiding the keyboard,...rather... | 5,239 |
58,350,001 | I have two python dictionaries.
Sample:
```
{
'hello' : 10
'phone' : 12
'sky' : 13
}
{
'hello' : 8
'phone' :15
'red' :4
}
```
This is the dictionary of counts of words in books 'book1' and 'book2' respectively.
How can I generate a pd dataframe, which looks like this:
```
hello phone sky red
book1 10 12 ... | 2019/10/12 | [
"https://Stackoverflow.com/questions/58350001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12133862/"
] | You need this:
```
pd.DataFrame([words, counts], index=['books1', 'books2'])
```
Output:
```
hello phone red sky
books1 10 12 NaN 13.0
books2 8 15 4.0 NaN
``` | Use `df.set_index([‘book1’, ‘book2’])`. See the docs here: <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html> | 5,248 |
10,062,646 | Superficially, an easy question: how do I get a great-looking PDF from my XML document? Actually, my input is a subset of XHTML with a few custom attributes added (to save some information on citation sources, etc). I've been exploring some routes and would like to get some feedback if anyone has tried some of this bef... | 2012/04/08 | [
"https://Stackoverflow.com/questions/10062646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214446/"
] | I've done something like this in the past (that is, maintaining master versions of documents in XML, and wanting to produce LaTeX output from them).
I've used PassiveTeX in the past, but I found creating stylesheets to be hard work -- the usual result of writing two languages at once. I got it to work, and the result ... | You might want to check [questions tagged with XML on TeX.sx](https://tex.stackexchange.com/questions/tagged/xml), especially [this](https://tex.stackexchange.com/questions/11260/is-there-some-typesetting-system-that-uses-xml-notation) one. I suggest you use ConTeXt; the current version has no problems with Unicode and... | 5,252 |
2,558,107 | In the [App Engine docs](http://code.google.com/appengine/docs/python/xmpp/overview.html#XMPP_Addresses), a JID is defined like this:
>
> An application can send and receive
> messages using several kinds of
> addresses, or "JIDs."
>
>
>
On Wikipedia, however, a JID is defined like this:
>
> Every user on the... | 2010/04/01 | [
"https://Stackoverflow.com/questions/2558107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/306533/"
] | A JID is globally unique in that anyone sending an XMPP message as you@domain.com can be you.
However, an App Engine app can send XMPP messages as any number of JIDs.
Your app can send XMPP messages as `your-app-id@appspot.com` or as `foo@your-app-id.appspotchat.com` or as `bar@your-app-id.appspotchat.com` or as `any... | Since I happened to have this up in my browser, the current best canonical definition of JIDs is here: [draft-saintandre-xmpp-address](http://xmpp.org/internet-drafts/draft-saintandre-xmpp-address-00.html), which just got pulled out of [RFC3920bis](http://xmpp.org/internet-drafts/draft-ietf-xmpp-3920bis-06.html). | 5,257 |
71,668,239 | I am working on some plotly image processing for my work. I have been using matplotlib but need something more interactive, so I switched to dash and plotly. My goal is for people on my team to be able to draw a shape around certain parts of an image and return pixel values.
I am using this documentation and want a si... | 2022/03/29 | [
"https://Stackoverflow.com/questions/71668239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18599127/"
] | Use following as time generator with 15min interval and then use other date time functions as needed to extract date part or time part in separate columns.
```
with CTE as
(select timestampadd(min,seq4()*15 ,date_trunc(hour, current_timestamp())) as time_count
from table(generator(rowcount=>4*24)))
select time_count ... | There are many answers to this question [h](https://stackoverflow.com/questions/71666252/generate-series-equivalent-in-snowflake/71666318#71666318) [e](https://stackoverflow.com/questions/71473750/duplicating-a-row-a-certain-number-of-times-and-then-adding-30-mins-to-a-timesta/71475320#71475320) [r](https://stackoverfl... | 5,258 |
16,373,317 | In my website, each user has their own login id and password, so if a user is logged in, he can add, edit and update his record only.
models.py is
```
class Report(models.Model):
user = models.ForeignKey(User, null=False)
name = models.CharField(max_length=20, null=True, blank=True)
```
views.py
```
def pr... | 2013/05/04 | [
"https://Stackoverflow.com/questions/16373317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2215612/"
] | You may use a [`BackgroundWorker`](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) to do the operation that you need in different thread like the following :
```
BackgroundWorker bgw;
public Form1()
{
InitializeComponent();
bgw = new BackgroundWorker();... | You can use a background thread for this long-running operation, if it is not ui-intensive.
```
ThreadPool.QueueUserWorkItem((o) => /* long running operation*/)
``` | 5,259 |
44,355,493 | The following python code gives me the different combinations from the given values.
```
import itertools
iterables = [ [1,2,3,4], [88,99], ['a','b'] ]
for t in itertools.product(*iterables):
print t
```
Output:-
```
(1, 88, 'a')
(1, 88, 'b')
(1, 99, 'a')
(1, 99, 'b')
(2, 88, 'a')
```
and so on.
Can some o... | 2017/06/04 | [
"https://Stackoverflow.com/questions/44355493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8110677/"
] | **Yes, you can.** Possible ways:
**1)** Use Gradle plugin [gradle-console-reporter](https://github.com/ksoichiro/gradle-console-reporter) to report various kinds of summaries to console. JUnit, JaCoCo and Cobertura reports are supported.
In your case, following output will be printed to console:
```
...
BUILD SUCC... | AFAIK Gradle does not support this, each project is treated separately.
To support your use case some aggregation task can be created to parse a report and to update some value at root project and finally print that value to stdout.
**Update with approximate code for solution:**
```
subprojects {
task aggregateC... | 5,260 |
58,285,474 | ```
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc != 0)
{
System.out.println("first number: ");
int firstNum = sc.nextInt();
System.out.prin... | 2019/10/08 | [
"https://Stackoverflow.com/questions/58285474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9783604/"
] | You need to declare the variable out of while scope and update it until condition is not met
Try this:
```
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int firstNum = 1;
int secondNum = 1;... | Hi just remove the while block since it has no sence to use it
Here the corrected code
```
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("first number: ");
int ... | 5,261 |
3,867,131 | I'm stuck for a full afternoon now trying to get python to build in 32bit mode. I run a 64bit Linux machine with openSUSE 11.3, I have the necessary -devel and -32bit packages installed to build applications in 32bit mode.
The problem with the python build seems to be not in the make run itself, but in the afterwards ... | 2010/10/05 | [
"https://Stackoverflow.com/questions/3867131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/467244/"
] | You'll need to pass the appropriate
flags to gcc and ld to tell the compiler
to compile and produce 32bit binaries.
Use `--build` and `--host`.
```
./configure --help
System types:
--build=BUILD configure for building on BUILD [guessed]
--host=HOST cross-compile to build programs to run on HOST [BUILD]
... | Regarding why, since Kirk (and probably others) wonder, here is an example: I have a Python app with large dicts of dicts containing light-weight objects. This consumes almost twice as much RAM on 64bit as on 32bit simply due to the pointers. I need to run a few instances of 2GB (32bit) each and the extra RAM quickly a... | 5,270 |
44,153,457 | Alright matplotlib afficionados, we know how to plot a [donut chart](https://stackoverflow.com/questions/36296101/donut-chart-python), but what is better than a donut chart? A double-donut chart. Specifically: We have a set of elements that fall into disjoint categories and sub-categories of the first categorization. T... | 2017/05/24 | [
"https://Stackoverflow.com/questions/44153457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/626537/"
] | To obtain a double donut chart, you can plot as many pie charts in the same plot as you want. So the outer pie would have a `width` set to its wedges and the inner pie would have a radius that is less or equal `1-width`.
```
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.axis('equal')
... | I adapted the example you provided; you can tackle your problem by plotting two donuts on the same figure, with a smaller outer radius for one of them.
```
import matplotlib.pyplot as plt
import numpy as np
def make_pie(sizes, text,colors,labels, radius=1):
col = [[i/255 for i in c] for c in colors]
plt.axi... | 5,271 |
47,302,085 | It is not yet clear for me what `metrics` are (as given in the code below). What exactly are they evaluating? Why do we need to define them in the `model`? Why we can have multiple metrics in one model? And more importantly what is the mechanics behind all this?
Any scientific reference is also appreciated.
```python... | 2017/11/15 | [
"https://Stackoverflow.com/questions/47302085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3705055/"
] | As in [keras metrics](https://keras.io/metrics/) page described:
>
> A metric is a function that is used to judge the performance of your
> model
>
>
>
Metrics are frequently used with early stopping callback to terminate training and avoid overfitting | Reference: [Keras Metrics Documentation](https://keras.io/metrics/)
As given in the documentation page of `keras metrics`, a `metric` judges the performance of your model. The `metrics` argument in the `compile` method holds the list of metrics that needs to be evaluated by the model during its training and testing ph... | 5,272 |
38,782,191 | Dlib has a really handy, fast and efficient object detection routine, and I wanted to make a cool face tracking example similar to the example [here](https://realpython.com/blog/python/face-detection-in-python-using-a-webcam/).
OpenCV, which is widely supported, has VideoCapture module that is fairly quick (a fifth of... | 2016/08/05 | [
"https://Stackoverflow.com/questions/38782191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/778234/"
] | I tried multithreading, and it was just as slow, then I multithreaded with just the `.read()` in the thread, no processing, no thread locking, and it worked quite fast - maybe 1 second or so of delay, not 3 or 5. See <http://www.pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/>
```
from __fut... | If you want to show a frame read in OpenCV, you can do it with the help of `cv2.imshow()` function without any need of changing the colors order. On the other hand, if you still want to show the picture in matplotlib, then you can't avoid using the methods like this:
```
b,g,r = cv2.split(img)
img = cv2.merge((b,g,r))... | 5,281 |
48,738,061 | ```
M = eval(input("Input the first number "))
N = eval(input("Input the second number(greater than M) "))
sum = 0
while M <= N:
if M % 2 == 1:
sum = sum + M
M = M + 1
print(sum)
```
This is my python code, every time I run the program, it prints the number twice. (1 1... | 2018/02/12 | [
"https://Stackoverflow.com/questions/48738061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You may use
```
import re
text = 'MIKE an entry for mike WILL and here is wills text DAVID and this belongs to david'
subs = ['MIKE','WILL','TOM','DAVID']
res = re.findall(r'({0})\s*(.*?)(?=\s*(?:{0}|$))'.format("|".join(subs)), text)
print(res)
# => [('MIKE', 'an entry for mike'), ('WILL', 'and here is wills text'), ... | You can also use the following regex to achieve your goal:
```
(MIKE.*)(?= WILL)|(WILL.*)(?= DAVID)|(DAVID.*)
```
It uses Positive lookahead to get the intermediate strings. (<http://www.rexegg.com/regex-quickstart.html>)
**TESTED:** <https://regex101.com/r/ZSJJVG/1> | 5,286 |
24,687,665 | I would eventually like to pass data from python data structures to Javascript elements that will render it in a Dygraphs graph within an iPython Notebook.
I am new to using notebooks, especially the javascript/nobebook interaction. I have the latest Dygraphs library saved locally on my machine. At the very least, I ... | 2014/07/10 | [
"https://Stackoverflow.com/questions/24687665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176806/"
] | The trick is to pass the DataFrame into JavaScript and convert it into a [format](http://dygraphs.com/data.html) that dygraphs can handle. Here's the code I used ([notebook here](https://gist.github.com/danvk/e81557c88d61e34dbd75))
```
html = """
<script src="http://dygraphs.com/dygraph-combined.js"></script>
<div id=... | danvk's solution is cleaner and faster than this, but I also was able to get this to work by building a Dygraph String from a DataFrame. It seems limited to about 15K points, but the benefit is that once created, the page can be saved as a static html page and the Dygraphs plot stays in place. Makes for a nice portable... | 5,287 |
65,804,384 | So im trying to make a decimal to binary convertor in python without using the bin
and this is incomplete, but for now im trying to get 'a' as a list with all the factors that led to the conversion
for example if the decimal inputed = 75,
then 'a' should be = [64, 8, 2, 1]
Can someone tell me how to correct my code
b... | 2021/01/20 | [
"https://Stackoverflow.com/questions/65804384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15031531/"
] | You can't assign to positions in a list that don't exist.
Instead of
```
a[x] = raise_to_power(2, count)
```
add the result to the list using [list.append](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types)
```
a.append(raise_to_power(2, count))
``` | I think you can do this with fewer steps.
```
num = int(input("Enter a number: "))
b = []
while num > 0:
b.append(num%2)
num = num//2
f = [(2*a)**i for i,a in enumerate(b) if a != 0]
f = f[::-1]
print (f)
```
This will give you the following result:
```
Enter a number: 75
[64, 8, 2, 1]
Enter a number: 36
... | 5,288 |
34,321,618 | First things first I am not a professional with Regular Expressions and have been depending on [this cookbook](https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch06s11.html), [this tool](http://pythex.org/) and [this other tool](http://pythex.org/)
Now when I try run it it pyth... | 2015/12/16 | [
"https://Stackoverflow.com/questions/34321618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/944900/"
] | Two main problems:
* `re.findall` will return a list of tuples if your pattern has any capturing groups in it. Since your pattern is using groups in a very odd way, you will end up seeing some weird results from this. Make use of non capturing groups by using `(?:` instead of just plain `(` parentheses.
* because if t... | Can you try this regex?
```
((?:\d+,?)+\.?\d+)
```
<https://regex101.com/r/qN0gV9/1> | 5,290 |
44,992,717 | I recently began self-learning python, and have been using this language for an online course in algorithms. For some reason, many of my codes I created for this course are very slow (relatively to C/C++ Matlab codes I have created in the past), and I'm starting to worry that I am not using python properly.
Here is a... | 2017/07/09 | [
"https://Stackoverflow.com/questions/44992717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8277919/"
] | Try using `xrange` instead of `range`.
The difference between them is that `**xrange**` generates **the values as you use them** instead of `range`, which tries to generate a static list at runtime. | Unfortunately, python's amazing flexibility and ease comes at the cost of being slow. And also, for such large values of iteration, I suggest using itertools module as it has faster caching.
The xrange is a good solution however if you want to iterate over dictionaries and such, it's better to use itertools as in that... | 5,291 |
3,679,974 | What I'd like to achieve is the launch of the following shell command:
```
mysql -h hostAddress -u userName -p userPassword
databaseName < fileName
```
From within a python 2.4 script with something not unlike:
```
cmd = ["mysql", "-h", ip, "-u", mysqlUser, dbName, "<", file]
subprocess.call(cmd)
```
This pukes ... | 2010/09/09 | [
"https://Stackoverflow.com/questions/3679974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443779/"
] | You have to feed the file into mysql stdin by yourself. This should do it.
```
import subprocess
...
filename = ...
cmd = ["mysql", "-h", ip, "-u", mysqlUser, dbName]
f = open(filename)
subprocess.call(cmd, stdin=f)
``` | The symbol `<` has this meaning (i. e. reading a file to `stdin`) only in shell. In Python you should use either of the following:
1) Read file contents in your process and push it to `stdin` of the child process:
```
fd = open(filename, 'rb')
try:
subprocess.call(cmd, stdin=fd)
finally:
fd.close()
```
2) ... | 5,294 |
68,563,978 | This question is basically on how to use regular expressions but I couldn't find any answer to it in a lot of very closely related questions.
I create coverage reports in a gitlab pipeline using [coverage.py](https://coverage.readthedocs.io/en/coverage-5.5/) and [py.test](https://docs.pytest.org/en/6.2.x/) which look ... | 2021/07/28 | [
"https://Stackoverflow.com/questions/68563978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3734059/"
] | It is easier to use `awk` here:
```sh
cov_score=$(awk '$1 == "TOTAL" {print $NF+0}' coverage37.log)
```
Here `$1 == "TOTAL"` matches a line with first word as `TOTAL` and `print $NF+0` prints number part of last field. | rather than get approximate values from non-machine-readable outputs you'd be best to use coverage's programmatic apis, either `coverage xml` or `coverage json`
here's an example using the json output (note I send it to `/dev/stdout`, by default it goes to `coverage.json`)
```
$ coverage json -o /dev/stdout | jq .tot... | 5,297 |
67,347,194 | The thing is , that I am given some code and it is structured this way that we expect some accesses to not - initialised elements in the list. (I don't want to change the logic behind it, because it deals with some math concepts ). But I've been given the code in some other language and I want to do the same with pytho... | 2021/05/01 | [
"https://Stackoverflow.com/questions/67347194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14386149/"
] | you can handle it with:
```
except IndexError:
pass
```
full code:
```
a = []
for i in range(1, 10, 2): a.append(i)
for j in range(10):
try:
a[i] += 1
except IndexError:
pass
finally:
a.append(1)
``` | ```
a = []
for i in range(1,10,2):
a.append(i)
try:
for j in range(10):
a[i] +=1
except:
pass
finally:
a.append(1)
print(a)
``` | 5,300 |
59,414,043 | Below is my project structure:
```
- MyProject
- src
- Master.py
- Myfolder
- file1
- Myfolder2
- file2
```
when i tried to run `python3 Master.py` from `src` folder i get
```
ModuleNotFoundError: No Module name 'src'
```
when i tried to run Master.py from root using this command ... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59414043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4984616/"
] | Given the updated directory structure, you should add an `__init__.py` file to `myfolder` with the following line:
```py
from .file1 import * # or
# from .file1 import something # or
# from . import file1
```
and then in `master.py` do
```py
import myfolder # or
# from myfolder import file1 # or
# from myfolder.f... | While my solution worked with what was suggested by Maxim i also learned that with the help of simple `os.chdir(os.path.dirname('/usr/dirname'))` i was able to resolve the issue and i also did not have to add `__init__.py` anywhere in the package | 5,301 |
32,140,380 | I'm looking for a pythonic (1-line) way to extract a range of values from an array
Here's some sample code that will extract the array elements that are >2 and <8 from x,y data, and put them into a new array. Is there a way to accomplish this on a single line? The code below works but seems kludgier than it needs to be... | 2015/08/21 | [
"https://Stackoverflow.com/questions/32140380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4618362/"
] | You can chain together boolean arrays using `&` for element-wise `logical and` and `|` for element-wise `logical or`, so that the condition `2 < x0` and `x0 < 8` becomes
```
mask = (2 < x0) & (x0 < 8)
```
---
For example,
```
import numpy as np
x0 = np.array([0,3,9,8,3,4,5])
y0 = np.array([2,3,5,7,8,1,0])
mask =... | ```
import numpy as np
x0 = np.array([0,3,9,8,3,4,5])
y0 = np.array([2,3,5,7,8,1,0])
list( zip( *[(x,y) for x, y in zip(x0, y0) if 1<=x<=3 or 7<=x<=9] ) )
# [(3, 9, 8, 3), (3, 5, 7, 8)]
``` | 5,302 |
64,995,258 | I started learning python few days ago and im looking to create a simple program that creates conclusion text that shows what have i bought and how much have i paid depended on my inputs. So far i have created the program and technically it works well. But im having a problem with specifying the parts in text that migh... | 2020/11/24 | [
"https://Stackoverflow.com/questions/64995258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14702072/"
] | * Give each group a consecutive range. For example, for 15%, the range will be between 30 and 45.
* Pick a random number between 0 and 100.
* Find in which range that random number falls:
```sql
create or replace temp table probs
as
select 'a' id, 1 value, 20 prob
union all select 'a', 2, 30
union all select 'a', 3,... | Felipe's answer is great, it definitely solved the problem.
While trying out different approaches yesterday, I tested out this approach on Felipe's table and it seems to be working as well.
I'm giving each record a random probability and comparing against the actual probability. The idea is that if the random probabi... | 5,303 |
60,482,258 | How can i replace a string in list of lists in python but i want to apply the changes only to the specific index and not affecting the other index, here some example:
```
mylist = [["test_one", "test_two"], ["test_one", "test_two"]]
```
i want to change the word "test" to "my" so the result would be only affecting t... | 2020/03/02 | [
"https://Stackoverflow.com/questions/60482258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9675410/"
] | Use indexing:
```
newlist = []
for l in mylist:
l[1] = l[1].replace("test", "my")
newlist.append(l)
print(newlist)
```
Or oneliner if you always have two elements in the sublist:
```
newlist = [[i, j.replace("test", "my")] for i, j in mylist]
print(newlist)
```
Output:
```
[['test_one', 'my_two'], ['test... | There is a way to do this on one line but it is not coming to me at the moment. Here is how to do it in two lines.
```
for two_word_list in mylist:
two_word_list[1] = two_word_list.replace("test", "my")
``` | 5,304 |
53,048,002 | I have a semicolon separated csv file which has the following form:
```
indx1; string1; char1; entry1
indx2; string1; char2; entry2
indx3; string2; char2; entry3
indx4; string1; char1; entry4
indx5; string3; char2; entry5
```
I want to get unique entries of the 1st and 2nd columns of this file in the form of a ... | 2018/10/29 | [
"https://Stackoverflow.com/questions/53048002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10415983/"
] | You could use [sets](https://docs.python.org/2.7/library/stdtypes.html#set) to keep track of the already seen values in the needed columns. Since you say that the order doesn't matter, you could just convert the sets to lists after processing all rows:
```
import csv
col1, col2 = set(), set()
with open('data.csv') a... | This should work. You can use it as benchmark.
```
myDict1 = {}
myDict2 = {}
with open('data.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
for row in csv_reader:
myDict1[row[1]] = 0
myDict2[row[2]] = 0
x = myDict1.keys()
y = myDict2.keys()
``` | 5,305 |
10,631,419 | My django app saves django models to a remote database. Sometimes the saves are bursty. In order to free the main thread (\*thread\_A\*) of the application from the time toll of saving multiple objects to the database, I thought of transferring the model objects to a separate thread (\*thread\_B\*) using [`collections.... | 2012/05/17 | [
"https://Stackoverflow.com/questions/10631419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348545/"
] | Django's `save()` does nothing special to the GIL. In fact, there is hardly anything you can do with the GIL in Python code -- when it is executed, the thread must hold the GIL.
There are only two ways the GIL could get released in `save()`:
* Python decides to switch threads (after [`sys.getcheckinterval()`](http://... | I think python dont lock anything by itself, but database does. | 5,306 |
68,006,937 | I am trying to make a daily line graph for certain stocks, but am running into an issue. Getting the 'Close' price every 2 minutes functions correctly, but when I try and get 'Datetime' I am getting an error. I believe yfinance used pandas to create a dataframe, but I may be wrong. Regardless, I am having issues pullin... | 2021/06/16 | [
"https://Stackoverflow.com/questions/68006937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16245213/"
] | Datetime is no column name, it just looks like one:
[](https://i.stack.imgur.com/gK5iQ.png)
Try
`print(stock.history(period='1d',interval='2m).keys())`
and you will see. | The Datetime column is the index of the dataframe. If you reset the index you can do whatever with the ['Datetime'] column. | 5,309 |
41,761,293 | I am trying to access the worklogs in python by using the [jira python library](http://jira.readthedocs.io/en/latest/examples.html). I am doing the following:
```
issues = jira.search_issues("key=MYTICKET-1")
print(issues[0].fields.worklogs)
issue = jira.search_issues("MYTICKET-1")
print(issue.fields.worklogs)
```
... | 2017/01/20 | [
"https://Stackoverflow.com/questions/41761293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1581090/"
] | This is because **it seems** `jira.JIRA.search_issues` doesn't fetch all "builtin" fields, like `worklog`, by default (although documentation only uses vague term ["fields - [...] Default is to include *all fields*"](https://jira.readthedocs.io/en/master/api.html?highlight=worklogs#jira.JIRA.search_issues)
- "all" ou... | This question [here](https://stackoverflow.com/questions/24375473/access-specific-information-within-worklogs-in-jira-python) is similar to yours and someone has posted a work around.
There is a also a [similar question on Github](https://github.com/pycontribs/jira/issues/224) in relation to attachments (not worklogs... | 5,310 |
48,244,805 | I need to execute a function named "send()" who contain an ajax request.
This function is in ajax.js (included in )
The Ajax success update the src of my image.
This function work well, I don't think that it is the problem
But when I load the page, send() function is not executed :o I don't understand why.
After loa... | 2018/01/13 | [
"https://Stackoverflow.com/questions/48244805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8846114/"
] | There is no function named `send` in your code. You have a function named `envoi`. Change `function envoi()` to `function send()` The hazards of multilingual coding!
**Edit: since you updated your answer, try this.**
```
<script>
$(document).ready(function() {
send();
alert($("#image").attr('src'));
});
</scr... | The format of the javascript is incorrect. The Scope of your solution needs to be managed with JQuery. If you simply want to call the function when the page loads, you can call the function inside the JQuery handler. Also, your syntax is not correct.
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
... | 5,311 |
61,549,690 | I have a bash script that starts my python script. Point of this is, that I hand over a lot of (sometimes changing) arguments to the python script. So I found it useful to start my python script with a bash script where I "save" my argument list.
```
#!/bin/bash
cd $(dirname $0)
python3 script.py [arg0] [arg1]
```
I... | 2020/05/01 | [
"https://Stackoverflow.com/questions/61549690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Sounds like a case of operator precedence? Does it work if you wrap the second part in brackets, like
```js
console.log('myFather.__proto__ === Object.prototype:' + (myFather.__proto__ === Object.prototype))
```
Operator precedence, as documented at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refer... | You are actually doing this :
```
console.log( ('myFather.__proto__ === Object.prototype:' + myFather.__proto__) === Object.prototype);
```
So the result of this equality is `false` | 5,314 |
48,364,407 | I'm new to python and I have found tons of my questions have already been answered. In 7 years of coding various languages, I've never actually posted a question on here before, so I'm really stumped this time.
I'm using python 3.6
I have a pandas dataframe with a column that is just Boolean values. I have some code ... | 2018/01/21 | [
"https://Stackoverflow.com/questions/48364407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9246417/"
] | `False not in S` is equivalent to `False not in S.index`. Since the first index element is 0 (which, in turn, is numerically equivalent to `False`), `False` is technically `in` `S`. | When you call `s.values` you are going to have access to a `numpy.array` version of the pandas Series/Dataframe.
Pandas provides a method called `isin` that is going to behave correctly, when calling `s.isin([False])` | 5,315 |
36,468,707 | I'm having trouble loading the R-package `edgeR` in Python using `rpy2`.
When I run:
```
import rpy2.robjects as robjects
robjects.r('''
library(edgeR)
''')
```
I get the following error:
```
/home/user/.local/lib/python2.7/site-packages/rpy2/robjects/functions.py:106: UserWarning: Loading required package: l... | 2016/04/07 | [
"https://Stackoverflow.com/questions/36468707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5964533/"
] | If you want 2 different file button, you need to give them different names.
```
<form action="" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="userfile1" size="20">
<input type="file" name="userfile2" size="20">
<input type="submit" name="submit" value="upload">
```
Than... | ```
<form action="http://localhost/cod_login/club/test2" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="userfile" size="20" multiple="">
<input type="submit" name="submit" value="upload">
</form>
``` | 5,317 |
43,246,862 | Is there a way to create a cloudformation template, which invokes REST API calls to an EC2 instance ?
The use case is to modify the configuration of the application without having to use update stack and user-data, because user-data updation is disruptive.
I did search through all the documentation and found that thi... | 2017/04/06 | [
"https://Stackoverflow.com/questions/43246862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2617/"
] | I would attack this with Lambda, but it seems as though you already thought of that and might be dismissing it.
A little bit of a hack, but could you add Files to the instance via Metadata where the source is the REST url?
e.g.
```
"Type": "AWS::EC2::Instance",
"Metadata": {
"AWS::CloudFormation::Init": {
... | Lambda triggered by the event. Lifecycle hooks can be helpful.
You can hack CoudFormation, but please mind: it is not designed for this. | 5,320 |
3,893,038 | I use Hakyll to generate some documentation and I noticed that it has a weird way of closing the HTML tags in the code it generates.
There was a page where they said that you must generate the markup as they do, or the layout of your page will be broken under some conditions, but I can't find it now.
I created a smal... | 2010/10/08 | [
"https://Stackoverflow.com/questions/3893038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/212865/"
] | It's actually [pandoc](http://johnmacfarlane.net/pandoc/) that's generating the HTML code. There's a good explanation in the Pandoc issue tracker:
<http://code.google.com/p/pandoc/issues/detail?id=134>
>
> The reason is
> because any whitespace (including newline and tabs) between HTML tags will cause the
> brows... | There are times when stripping the white space between two tags will make a difference, particularly when dealing with inline elements. | 5,321 |
3,183,185 | I want to send emails from my app engine application using one of my Google Apps accounts. According to the [GAE python docs](http://code.google.com/appengine/docs/python/mail/overview.html):
*The From: address can be the email address of a registered administrator (developer) of the application, the current user if s... | 2010/07/06 | [
"https://Stackoverflow.com/questions/3183185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/358925/"
] | You're misusing the send()/recv() functions. send() and recv() are not required to send as much data as you request, due to limits that may be present in the kernel. You have to call send() over and over until all data has been pushed through.
e.g.:
```
int sent = 0;
int rc;
while ( sent < should_send )
{
rc = sen... | 1. m\_socket can't possibly be null the line after you call `m_socket = new Socket(...)`. It will either throw an exception or assign a `Socket` to m\_socket, never null. So that test is pointless.
2. After you call `readLine()` you must check for a null return value, which means EOS, which means the other end has clos... | 5,323 |
29,682,897 | I am using py2neo and I would like to extract the information from query returns so that I can do stuff with it in python. For example, I have a DB containing three "Person" nodes:
`for num in graph.cypher.execute("MATCH (p:Person) RETURN count(*)"):
print num`
outputs:
`>> count(*)`
`3`
Sorry for shitty formatti... | 2015/04/16 | [
"https://Stackoverflow.com/questions/29682897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2505865/"
] | The clue is in the question: "Assume that I have a fetcher that fetches an image from a given link on a separate thread. The image will then be **cached** in memory."
And the answer is the `cache()` operator:
"remember the sequence of items emitted by the Observable and emit the same sequence to future Subscribers"
... | Have a look at `ConnectableObservable` and the `.replay()` method.
I'm currently using this is my fragments to handle orientation changes:
Fragment's onCreate:
```
ConnectableObservable<MyThing> connectableObservable =
retrofitService.fetchMyThing()
.map(...)
.replay();
connectableObservable.c... | 5,325 |
53,892,106 | i wanted to make a python file that makes a copy of itself, then executes it and closes itself, then the copy makes another copy of itself and so on...
i am not asking for people to write my code and this could be taken as just a fun challenge, but i want to learn more about this stuff and help is appreciated.
i have... | 2018/12/22 | [
"https://Stackoverflow.com/questions/53892106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10756702/"
] | I don't have enough rep to reply to @Prune:
`os.startfile(file)` only works on Windows, and is [replaced by](https://docs.python.org/3/library/subprocess.html) `subprocess.call`
`shutil.copy2(src, dst)` works on both Windows and Linux.
Try this solution as well:
```
import shutil
import subprocess
old_file = __file... | You're close; you have things in the wrong order. Create the new file, *then* execute it.
```
import os
old_file = __file__
new_file = generate_unique_file_name()
os.system('cp ' + old_file + ' ' + new_file) #UNIX syntax; for Windows, use "copy"
os.startfile(new_file)
```
You'll have to choose & code your preferre... | 5,327 |
47,393,177 | I'm actually working on a django project and i'm migrating to a CustomUser model. On the database everything have gone well and now i want to force my user to update their informations (to respect the new model)
I would like to do it when they login (I set all the e-mail to end with @mysite.tmp in order to know if the... | 2017/11/20 | [
"https://Stackoverflow.com/questions/47393177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8876232/"
] | You can write the logic as:
```
select *
from table
where (Vendorname = @Vendor) OR (@Vendor IS NULL)
```
One caution: This may not be as optimized as your version, if you have an index on `Vendorname`. | ```
select *
from table
where Vendorname = case when @Vendor is not null then @Vendor else Vendorname end;
``` | 5,328 |
62,097,023 | I have a list with weekly figures and need to obtain the grouped totals by month.
The following code does the job, but there should be a more pythonic way of doing it with using the standard libraries.
The drawback of the code below is that the list needs to be in sorted order.
```
#Test data (not sorted)
sum_weekly=... | 2020/05/30 | [
"https://Stackoverflow.com/questions/62097023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1897688/"
] | You could use `defaultdict` to store the result instead of a list. The keys of the dictionary would be the months and you can simply add the values with the same month (key).
Possible implementation:
```py
# Test Data
from collections import defaultdict
sum_weekly = [('2020/01/05', 59), ('2020/01/19', 88), ('2020/01... | You can use `itertools.groupby` (it is part of standard library) - it does pretty much what you did under the hood (grouping together sequences of elements for which the key function gives same output). It can look like the following:
```
import itertools
def select_month(item):
return item[0].split('/')[1]
def ... | 5,333 |
43,252,531 | I am installing python 3.5, django 1.10 and psycopg2 2.7.1 on Amazon EC2 server in order to use a Postgresql database. I am using python 3 inside a virtual environment, and followed the classic installation steps:
```
cd /home/mycode
virtualenv-3.5 p3env
source p3env/bin/activate
pip install django
cd kenbot
django-ad... | 2017/04/06 | [
"https://Stackoverflow.com/questions/43252531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5591278/"
] | As suggested by @dentemm: the issue was resolved by copying all the psysopg2 directories from their current location in the lib64 directory, to the directory where django was installed /home/mycode/p3env/lib/python3.5/dist-packages. | Uninstalling and then reinstalling the library really helped!
>
> **(venv)$ pip uninstall psycopg2**
>
>
>
---
>
> **(venv)$ pip install psycopg2**
>
>
> | 5,340 |
52,101,595 | SQLAlchemy nicely documents [how to use Association Objects with `back_populates`](http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#association-object).
However, when copy-and-pasting the example from that documentation, adding children to a parent throws a `KeyError` as following code shows. The mode... | 2018/08/30 | [
"https://Stackoverflow.com/questions/52101595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/543875/"
] | **tldr;** We have to use Association Proxy extensions *and* create a custom constructor for the association object which takes the child object as the first (!) parameter. See solution based on the example from the question below.
SQLAlchemy's documentation actually states in the next paragraph that we aren't done yet... | So to make a long story short.
You need to append an association object containing your child object onto your parent. Otherwise, you need to follow Lars' suggestion about a proxy association.
I recommend the former since it's the ORM-based way:
```
p = Parent()
p.children.append(Association(child = Child()))
sessio... | 5,341 |
35,996,175 | ```
'''
Created on 13.3.2016
worm game
@author: Hai
'''
import pygame
import random
from pygame import * ##
class Worm:
def __init__(self, surface):
self.surface = surface
self.x = surface.get_width() / 2
self.y = surface.get_height() / 2
self.length = 1
self.grow_to = 50
... | 2016/03/14 | [
"https://Stackoverflow.com/questions/35996175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4802223/"
] | I had to remove all the N preview stuff from my sdk to make things normal again. Don't forget the cache too.
```
sdk/extras/android/m2repository/com/android/support/design|support-v-13|ect./24~
``` | The syntax of xml line you wrote is wrong
instead of
`android:setTextColor=""`
use
```
android:textColor=""
``` | 5,342 |
14,738,725 | I am asked:
>
> Using your raspberry pi, write a python script that determines the randomness
> of /dev/random and /dev/urandom. Read bytes and histogram the results.
> Plot in matplotlib. For your answer include the python script.
>
>
>
I am currently lost on the phrasing "determines the randomness."
I can re... | 2013/02/06 | [
"https://Stackoverflow.com/questions/14738725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779920/"
] | Could it be as simple as:
```
In [664]: f = open("/dev/random", "rb")
In [665]: len(set(f.read(256)))
Out[665]: 169
In [666]: ff = open("/dev/urandom", "rb")
In [667]: len(set(ff.read(256)))
Out[667]: 167
In [669]: len(set(f.read(512)))
Out[669]: 218
In [670]: len(set(ff.read(512)))
Out[670]: 224
```
ie. asking ... | Your experience may be exactly what they're looking for. From the man page of urandom(4):
>
> When read, the /dev/random device will only return
> random bytes within the estimated number of bits of noise
> in the entropy pool. /dev/random should be suitable for uses that need very high quality randomness such as
>... | 5,344 |
66,104,854 | I want to download the data from `USDA` site with custom queries. So instead of manually selecting queries in the website, I am thinking about how should I do this handier in python. To do so, I used `request`, `http` to access the url and read the content, it is not intuitive for me how should I pass the queries then ... | 2021/02/08 | [
"https://Stackoverflow.com/questions/66104854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14126595/"
] | A few details
* simplest format is text rather that HTML. Got URL from HTML page for text download
* `requests(params=)` is a `dict`. Built it up and passed, no need to deal with building complete URL string
* clearly text is space delimited, found minimum of double space
```
import io
import requests
import pandas a... | Just format the query data in the url - it's actually a REST API:
To add more query data, as @mullinscr said, you can change the values on the left and press submit, then see the query name in the URL (for example, start date is called `repDate`).
If you hover on the Download as XML link, you will also discover you c... | 5,345 |
57,252,637 | I'm using PySpark (a new thing for me). Now, suppose I Have the following table:
`+-------+-------+----------+
| Col1 | Col2 | Question |
+-------+-------+----------+
| val11 | val12 | q1 |
| val21 | val22 | q2 |
| val31 | val32 | q3 |
+-------+-------+----------+`
and I would like to append to it a new column, `random... | 2019/07/29 | [
"https://Stackoverflow.com/questions/57252637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/690045/"
] | This should do the trick:
```
import pyspark.sql.functions as F
questions = df.select(F.col('Question').alias('random_question'))
random = questions.orderBy(F.rand())
```
Give the dataframes a unique row id:
```
df = df.withColumn('row_id', F.monotonically_increasing_id())
random = random.withColumn('row_id', F.mo... | The above answer is wrong. You are not guaranteed to have the same set of ids in the two dataframes and you will lose rows.
```
df = spark.createDataFrame(pd.DataFrame({'a':[1,2,3,4],'b':[10,11,12,13],'c':[100,101,102,103]}))
questions = df.select(F.col('a').alias('random_question'))
random = questions.orderBy(F.rand(... | 5,346 |
57,373,034 | I have a list of tuples:
```
d = [("a", "x"), ("b", "y"), ("a", "y")]
```
and the `DataFrame`:
```
y x
b 0.0 0.0
a 0.0 0.0
```
I would like to replace any `0s` with `1s` if the row and column labels correspond to a tuple in `d`, such that the new DataFrame is:
```
y x
b 1.0 0.0
a 1.0 1.0
... | 2019/08/06 | [
"https://Stackoverflow.com/questions/57373034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6017833/"
] | **Approach #1: No bad entries in `d`**
Here's one NumPy based method -
```
def assign_val(df, d, newval=1):
# Get d-rows,cols as arrays for efficient usage latet on
di,dc = np.array([j[0] for j in d]), np.array([j[1] for j in d])
# Get col and index data
i,c = df.index.values.astype(di.dtype),d... | Use [`get_dummies`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html) with `DataFrame` constructor:
```
df = pd.get_dummies(pd.DataFrame(d).set_index(0)[1]).rename_axis(None).max(level=0)
```
Or use `zip` with `Series`:
```
lst = list(zip(*d))
df = pd.get_dummies(pd.Series(lst[1], i... | 5,347 |
40,664,226 | i'm tryng to get some tweet data from a MySql database.
I've got tons of encoding errors while i was developing this code. This last for is the only way i got for running the code and getting this outfile full with \uxx characters all around, as you can see here:
```
[{..., "lang_tweet": "es", "text_tweet": "Recuerdo ... | 2016/11/17 | [
"https://Stackoverflow.com/questions/40664226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5298808/"
] | This is not a string concatenation, but adding `.x` and `.y` to pointer to `","`:
```
cursorLocation.x + "," + cursorLocation.y
```
Instead, try e.g.:
```
char s[256];
sprintf_s(s, "%d,%d", cursorLocation.x, cursorLocation.y);
OutputDebugStringA(s); // added 'A' after @IInspectable's comment, but
... | String concatenation doesn't work with integers.
Try using `std::ostringstream`:
```
std::ostringstream out_stream;
out_stream << cursorLocation.x << ", " << cursorLocation.y;
OuputDebugString(out_stream.str().c_str());
``` | 5,348 |
45,375,944 | While parsing attributes using [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__), my [`@staticmethod`](https://docs.python.org/3/library/functions.html?highlight=staticmethod#staticmethod) is not [`callable`](https://docs.python.org/3/library/functions.html?highlight=staticmethod#callable).
... | 2017/07/28 | [
"https://Stackoverflow.com/questions/45375944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/938111/"
] | The reason for this behavior is the descriptor protocol. The `C.foo` won't return a `staticmethod` but a normal function while the `'foo'` in `__dict__` is a [`staticmethod`](https://docs.python.org/library/functions.html#staticmethod) (and `staticmethod` is a descriptor).
In short `C.foo` isn't the same as `C.__dict_... | You can't check if a `staticmethod` object is callable or not. This was discussed on the tracker in [Issue 20309 -- Not all method descriptors are callable](https://bugs.python.org/issue20309) and closed as "not a bug".
In short, there's been no rationale for implementing `__call__` for staticmethod objects. The buil... | 5,349 |
50,117,538 | I use windows 7 without admin rights and i would like to use python3.
Even if i set PYTHONPATH, environment variable is ignored. However PYTHONPATH is valid when printed.
```
>>> print(sys.path)
['c:\\Python365\\python36.zip', 'c:\\Python365']
>>> print(os.environ["PYTHONPATH"])
d:\libs
```
any idea ?
thank you ver... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50117538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2922846/"
] | When using the embedded distribution (.zip file), then the `PYTHONPATH` environment variable is not respected. If this behavior is needed, then one needs to add some Python code that load the setting it from os.environ.get('PYTHONPATH', '') split the directories and add them to `sys.path`.
Also note that pip is not su... | Add the contents of PYTHONPATH to python.\_pth in the root folder one entry per line. | 5,350 |
17,585,207 | I copied this verbatim from python.org unittest documentation:
```
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(s... | 2013/07/11 | [
"https://Stackoverflow.com/questions/17585207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1913647/"
] | Check that you are really using 2.7 python.
Tested using `pythonbrew`:
```
$ pythonbrew use 2.7.2
$ python test.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
$ pythonbrew use 2.6.5
$ python test.py
.E.
=========================================================... | If you're using 2.7 and still seeing this issue, it could be because you're not using python's `unittest` module. Some other modules like `twisted` provide `assertRaises` and though they try to maintain compatibility with python's `unittest`, your particular version of that module may be out of date. | 5,351 |
56,045,986 | I was given this as an exercise. I could of course sort a list by using **sorted()** or other ways from Python Standard Library, but I can't in this case. I **think** I'm only supposed to use **reduce()**.
```
from functools import reduce
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(lambda a,b : (b,a) if ... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56045986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/764285/"
] | Here is one way to sort the list using `reduce`:
```
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
sorted_arr = reduce(
lambda a, b: [x for x in a if x <= b] + [b] + [x for x in a if x > b],
arr,
[]
)
print(sorted_arr)
#[1, 1, 2, 3, 3, 3, 5, 6, 9, 17]
```
At each reduce step, build a new output list which concat... | I think you're misunderstanding how reduce works here. Reduce is synonymous to *right-fold* in some other languages (e.g. Haskell). The first argument expects a function which takes two parameters: an *accumulator* and an element to accumulate.
Let's hack into it:
```
arr = [17, 2, 3, 6, 1, 3, 1, 9, 5, 3]
reduce(lamb... | 5,353 |
59,398,271 | I am doing object tracking on my videos which are in .mpg format what i am doing is i am using OpenCV to track the objects but i am facing some while opening it in my code i have attached my code.
```
import cv2
import sys
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if __name__ == '__main__'... | 2019/12/18 | [
"https://Stackoverflow.com/questions/59398271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7449718/"
] | POSSIBLY WRONG PATH
Check if Stroll.mpg is in right there in your working directory. If yes try with an .mp4 video. Most probably the path is wrong or file name Is misspelled.
Refer: <https://answers.opencv.org/question/1965/cv2videocapture-cannot-read-from-file/> | Make sure your opencv is compiled *with ffmpeg* which provides all those media-decoders (probably missing without).
[Someone with a similar problem](https://answers.opencv.org/question/220468/video-from-ip-camera-cant-find-starting-number-cvicvextractpattern/) due to this. | 5,362 |
43,401,174 | I'm new to python and I would like to know if this is possible or not:
I want to create an object and attach to it another object.
```
OBJECT A
Child 1
Child 2
OBJECT B
Child 3
Child 4
Child 5
Child 6
Child 7
```
is this possible ? | 2017/04/13 | [
"https://Stackoverflow.com/questions/43401174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6218501/"
] | If you are talking about object oriented terms, yes you can,you dont explain clearly what you want to do, but the 2 things that come to my mind if you are talking about OOP are:
* If you are talking about inheritance you can make child objects extend parent objects when you create your child class: class child(parent)... | Here is an example:
In this scenario an object can be a person without being an employee, however to be an employee they must be a person. Therefor the person class is a parent to the employee
Here's the link to an article that really helped me understand inheritance:
<http://www.python-course.eu/python3_inheritance.... | 5,363 |
21,047,114 | For sublime text, I installed RstPreview, downloaded `docutils-0.11`, and installed it by running `C:\Anaconda\python setup.py install` in Command Prompt (I am using windows 7 64 bits).
When I press `Ctrl+Shift+R` to parse a `.rst` file I get the following,
 for this plugin, it doesn't look like there is any good way of getting it to work on Windows. I can expand on the technicalities if you want, but basically this plugin relies on installing a third-party package (`docutils`) into the version... | I just came across restview, which does work on windows and offers a nice approach for providing feedback about how your rst file will be rendered as html. Here is an excerpt from the [restview pypi page](https://pypi.python.org/pypi/restview).
>
> A viewer for ReStructuredText documents that renders them on the fly.... | 5,365 |
57,645,717 | I'm trying to dockerize my python code but centos latest image does not have python3 in the repository packages at all .
I tried:
```
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
* base: mirror.karneval.cz
* extras: mirror.karneval.cz
* updates: mirror.karneval.cz
================... | 2019/08/25 | [
"https://Stackoverflow.com/questions/57645717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10306308/"
] | Well i tested some other images as well like Ubuntu:latest and alpine:latest and python3 not installed by default but it's in the repos and you can install by the package manager
In Centos:latest I can confirm that python3 isn't in the default configured Repos of the image
However you can find it in other Repos as m... | I need python3.5 or later in centos:latest Docker image, and I found that I can get it easily by:
```
RUN yum -y install epel-release
RUN yum -y install python3 python3-pip
```
This way I get:
```
[user@machine /]# python3 --version
Python 3.6.8
```
And I can use "pip3 install package" to install additional pytho... | 5,366 |
8,179,068 | I'm working with SQLAlchemy for the first time and was wondering...generally speaking is it enough to rely on python's default equality semantics when working with SQLAlchemy vs id (primary key) equality?
In other projects I've worked on in the past using ORM technologies like Java's Hibernate, we'd always override .e... | 2011/11/18 | [
"https://Stackoverflow.com/questions/8179068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/964823/"
] | Short answer: No, unless you're working with multiple Session objects.
Longer answer, quoting the awesome [documentation](http://www.sqlalchemy.org/docs/orm/tutorial.html#adding-new-objects):
>
> The ORM concept at work here is known as an identity map and ensures that all operations upon a particular row within a S... | I had a few situations where my sqlalchemy application would load multiple instances of the same object (multithreading/ different sqlalchemy sessions ...). It was absolutely necessary to override eq() for those objects or I would get various problems. This could be a problem in my application design, but it probably d... | 5,367 |
12,214,326 | I am new in python and I making a new code and I need a little help
Main file :
```
import os
import time
import sys
import app
import dbg
import dbg
import me
sys.path.append("lib")
class TraceFile:
def write(self, msg):
dbg.Trace(msg)
class TraceErrorFile:
def write(self, msg):
dbg.TraceE... | 2012/08/31 | [
"https://Stackoverflow.com/questions/12214326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638487/"
] | Why not doing this: define a method in the module you import and call this method 5 times in a loop with a certain `time.sleep(x)` in each iteration.
Edit:
Consider this is your module to import (e.g. `very_good_module.py`):
```
def interesting_action():
print "Wow, I did not expect this! This is a very good mod... | ```
#my_module.py (print hello once)
print "hello"
#main (print hello n times)
import time
import my_module # this will print hello
import my_module # this will not print hello
reload(my_module) # this will print hello
for i in xrange(n-2):
reload(my_module) #this will print hello n-2 times
time.sleep(seconds... | 5,368 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.