qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
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...
There is no need to read the entire dictionary into memory, or even to buffer lines. The dictionary consists of words, one per line. This means it has this structure: ``` "aardvark\nabacus\n" ``` The first two characters of the file are the first digraph. The other interesting digraphs are all characters which immed...
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...
You are started in the right direction. You do need a 2D array 27 x 27 for a single case (e.g. lowercase or uppercase), not including digits. To handle digits, just add another 11 x 11 array and map 2-digit frequencies there. The reason you can't use a flat 1D array and map to it without serious indexing gymnastics is ...
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{}...
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 ```
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...
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...
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...
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 solution needs O(n) runtime and O(n) space ```py def is_consecutive(l: list[int]): if not l: return False low = min(l) high = max(l) # Bounds Check if high - low != len(l) - 1: return False # Test all indices exist test_vec = [False] * len(l) # O(n) for i in rang...
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/" ]
Create a set and one to compare with -- based on minimum and maximum: ``` isRightSequence = set(range(min(b), max(b)+1)) == set(b) ```
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...
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/" ]
Create a set and one to compare with -- based on minimum and maximum: ``` isRightSequence = set(range(min(b), max(b)+1)) == set(b) ```
This solution needs O(n) runtime and O(n) space ```py def is_consecutive(l: list[int]): if not l: return False low = min(l) high = max(l) # Bounds Check if high - low != len(l) - 1: return False # Test all indices exist test_vec = [False] * len(l) # O(n) for i in rang...
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" ```
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/" ]
An approach with `which`: ``` dat$Number <- names(dat)[which(dat == "1+", arr.ind = TRUE)[ , 2]] # [1] "X1234" "X3000" "X7500" ```
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" ```
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/" ]
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" ```
You can also use the `col` function to return the proper variable name index like this: ``` names(mat)[col(mat)[which(mat == "1+")]] [1] "X1234" "X3000" "X7500" ```
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 ```
You can also use the `col` function to return the proper variable name index like this: ``` names(mat)[col(mat)[which(mat == "1+")]] [1] "X1234" "X3000" "X7500" ```
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/" ]
An approach with `which`: ``` dat$Number <- names(dat)[which(dat == "1+", arr.ind = TRUE)[ , 2]] # [1] "X1234" "X3000" "X7500" ```
You can also use the `col` function to return the proper variable name index like this: ``` names(mat)[col(mat)[which(mat == "1+")]] [1] "X1234" "X3000" "X7500" ```
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')`
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...
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...
Based on your example, you need something like this: ``` wget -q -O- https://dl.dropboxusercontent.com/s/wm6mt2ew0nnqdu6/links.html?dl=1 | sed -r 's#<a href="([^"]+)">([^<]+)</a>.*$#\2 - \1#' > links.txt ``` `cat links.txt` **outputs:** ``` 1Visit W3Schools - http://www.w3schools.com/ 2Visit W3Schools - http://www....
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...
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.
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/" ]
try this, don't forget to import selenium modules ``` from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait url = 'https://www.indeed.co.in/?r=us' driver.get(url) driver.find_element_by_xpath('//*[@id="tex...
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.
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...
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...
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/" ]
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...
while it was informative to learn about io.ReadSeeker, I think a simpler way to skip the first line/row (often times the header) of a csv is to use the slice functionality as follows: ``` func readCsv(filename string) [][]string { f, err := os.Open(filename) if err != nil { log.Fatal(err) } def...
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...
while it was informative to learn about io.ReadSeeker, I think a simpler way to skip the first line/row (often times the header) of a csv is to use the slice functionality as follows: ``` func readCsv(filename string) [][]string { f, err := os.Open(filename) if err != nil { log.Fatal(err) } def...
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...
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...
* use `-u` flag to make random1.py output unbuffered * use p.stdout.readline() instead of .read() time.sleep is unnecessary due to .read blocks.
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...
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...
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 ...
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...
You can select version of existent python explicitly at the top of the script. For example, I have a script which subexecutes script in 2.7.12 python and in 3.5.2 python. Let it be named: "different py versioned.sh" Its code: ``` #! /bin/bash ./'py in default.py' ./'py in 3.5.py' ``` Code of 'py in 3.5.py': ``` #...
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):`
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/" ]
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):`
If I have understood the question correctly, you want to define a custom `type`. You don't really need to import any modules. There are a number of ways you can do this, e.g. meta classes, however, a simple method is as follows: ``` my_type = type('ComplexTypes', (object,), {'LIST': 'LIST'}) var = my_type() ``` Now...
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 ...
If I have understood the question correctly, you want to define a custom `type`. You don't really need to import any modules. There are a number of ways you can do this, e.g. meta classes, however, a simple method is as follows: ``` my_type = type('ComplexTypes', (object,), {'LIST': 'LIST'}) var = my_type() ``` Now...
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)](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`
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...
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/" ]
The correct Dockerfile: ``` FROM node:12.17.0-alpine WORKDIR /src/webui RUN apk update && apk add bash CMD ["tail", "-f", "/dev/null"] ``` So the difference is that this: ``` CMD ["tail -f /dev/null"] ``` needs to be: ``` CMD ["tail", "-f", "/dev/null"] ``` You can read more about CMD in the official Docker [d...
`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...
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...
The correct Dockerfile: ``` FROM node:12.17.0-alpine WORKDIR /src/webui RUN apk update && apk add bash CMD ["tail", "-f", "/dev/null"] ``` So the difference is that this: ``` CMD ["tail -f /dev/null"] ``` needs to be: ``` CMD ["tail", "-f", "/dev/null"] ``` You can read more about CMD in the official Docker [d...
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...
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...
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...
You can also simply use ***driver.navigate().back();*** (for the older version of appium)
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 problem is trying to hide the keyboard on the first place. Set DesiredCapabilities as ``` cap.setCapability("connectHardwareKeyboard", false); ``` This will keep the keyboard hidden by default. Do your operation of entering data by sendKeys() ``` appDriver.findElementByXPath("//XCUIElementTypeOther[@name=\"Con...
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...
You define the capabilities like this. ``` desiredCapabilities.setCapability("unicodeKeyboard", true); desiredCapabilities.setCapability("resetKeyboard", true); ```
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...
If you're using Android u can use adb to hide the keyboard , send adb command from your code ``` adb shell input keyevent 111 ```
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...
If you are using android, use the below method. If keyboard is visible (by id) ``` driver.pressKeyCode(4); //Android back button ``` else ``` logger keyboard is not active ``` Above method will dismiss the keyboard by invoking system back button.
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...
Best solution for this problem is, just add `capability` in your program. ``` capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "uiautomator2"); ```
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...
``` public void clickAfterFindingElement(By by) { try { getDriver().waitForCondition(ExpectedConditions.elementToBeClickable(by)); getDriver().findElement(by).click(); } catch (NoSuchElementException | TimeoutException e) { swipeUp(); getDriver().findE...
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...
I'm testing a React Native app in a iPad simulator via Appium and WebdriverIO. ``` import { remote } from 'webdriverio'; client = await remote(opts); ``` I eventually found doing **two actions in a row** worked reliably, but one doesn't e.g. ``` await client.hideKeyboard('tapOut') await client.hideKeyboard('tapOut'...
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>
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/" ]
try the below code,hope this helps ``` dict1 = { 'hello' : 10, 'phone' : 12, 'sky' : 13 } dict2 = { 'hello' : 8, 'phone' :15, 'red' :4 } import pandas as pd df = pd.DataFrame([dict1,dict2], index=['book1','book2']) print(df) ``` Ouput will be: ``` hello phone sky red book1 10 12 13.0 NaN book...
Use `df.set_index([‘book1’, ‘book2’])`. See the docs here: <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html>
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 ```
Assuming you have a list of dictionaries, you could do something like this: ``` import pandas as pd from itertools import chain data = [{ 'hello': 10, 'phone': 12, 'sky': 13, }, { 'hello': 8, 'phone': 15, 'red': 4 }] df = pd.DataFrame(data=data, columns=set(chain.from_iter...
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/" ]
try the below code,hope this helps ``` dict1 = { 'hello' : 10, 'phone' : 12, 'sky' : 13 } dict2 = { 'hello' : 8, 'phone' :15, 'red' :4 } import pandas as pd df = pd.DataFrame([dict1,dict2], index=['book1','book2']) print(df) ``` Ouput will be: ``` hello phone sky red book1 10 12 13.0 NaN book...
Assuming you have a list of dictionaries, you could do something like this: ``` import pandas as pd from itertools import chain data = [{ 'hello': 10, 'phone': 12, 'sky': 13, }, { 'hello': 8, 'phone': 15, 'red': 4 }] df = pd.DataFrame(data=data, columns=set(chain.from_iter...
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...
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/" ]
In the end, I've decided to go with [Pandoc](https://pandoc.org/MANUAL.html#creating-a-pdf), seems to be very polished and solid code base. One potential drawback is that you have to limit yourself to the number of markup features available in Pandoc's internal representation which maps basically one-to-one to its [ext...
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...
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/" ]
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...
If you want more options on how to customize your TeX output, I would suggest using this: [xml2tex](https://github.com/transpect/xml2tex) It's based on a declarative configuration where you can specify your mapping from XML to TeX. MathML and XML tables (HTML and CALS) are automatically converted to TeX. Thus, it's O...
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 ...
If you want more options on how to customize your TeX output, I would suggest using this: [xml2tex](https://github.com/transpect/xml2tex) It's based on a declarative configuration where you can specify your mapping from XML to TeX. MathML and XML tables (HTML and CALS) are automatically converted to TeX. Thus, it's O...
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/" ]
In the end, I've decided to go with [Pandoc](https://pandoc.org/MANUAL.html#creating-a-pdf), seems to be very polished and solid code base. One potential drawback is that you have to limit yourself to the number of markup features available in Pandoc's internal representation which maps basically one-to-one to its [ext...
If you want more options on how to customize your TeX output, I would suggest using this: [xml2tex](https://github.com/transpect/xml2tex) It's based on a declarative configuration where you can specify your mapping from XML to TeX. MathML and XML tables (HTML and CALS) are automatically converted to TeX. Thus, it's O...
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 [email protected] can be you. However, an App Engine app can send XMPP messages as any number of JIDs. Your app can send XMPP messages as `[email protected]` or as `[email protected]` or as `[email protected]` 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).
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...
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*/) ```
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...
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 ...
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 should have some kind of an "infinite" loop like so: ``` public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true) { System.out.println("first number: "); int firstNum = sc.nextInt(); if (firstNum ...
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 ...
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;...
You cannot compare the Object sc with an integer value 0. You can do the below code. ``` public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { System.out.println("first number: "); int firstNum = sc.nextInt(); while(firstNum != 0) ...
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 should have some kind of an "infinite" loop like so: ``` public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true) { System.out.println("first number: "); int firstNum = sc.nextInt(); if (firstNum ...
You cannot compare the Object sc with an integer value 0. You can do the below code. ``` public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { System.out.println("first number: "); int firstNum = sc.nextInt(); while(firstNum != 0) ...
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;...
You should have some kind of an "infinite" loop like so: ``` public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true) { System.out.println("first number: "); int firstNum = sc.nextInt(); if (firstNum ...
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;...
It's ugly af but it will let you understand the process ``` package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); boolean continueRunning = true; while (continueRunning) { System.out.pr...
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;...
also ugly but i will sleep better tonight. ``` public static void main(String[] args) { Scanner scanner = new Scanner(System.in); requestNumbersAndSum(scanner); } private static void requestNumbersAndSum(Scanner scanner) { int firstNum = requestANum(scanner, "first number: "); ...
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 should have some kind of an "infinite" loop like so: ``` public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true) { System.out.println("first number: "); int firstNum = sc.nextInt(); if (firstNum ...
It's ugly af but it will let you understand the process ``` package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); boolean continueRunning = true; while (continueRunning) { System.out.pr...
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 should have some kind of an "infinite" loop like so: ``` public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true) { System.out.println("first number: "); int firstNum = sc.nextInt(); if (firstNum ...
also ugly but i will sleep better tonight. ``` public static void main(String[] args) { Scanner scanner = new Scanner(System.in); requestNumbersAndSum(scanner); } private static void requestNumbersAndSum(Scanner scanner) { int firstNum = requestANum(scanner, "first number: "); ...
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...
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...
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...
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/" ]
So in order to understand what `metrics` are, it's good to start by understanding what a `loss` function is. Neural networks are mostly trained using gradient methods by an iterative process of decreasing a `loss` function. A `loss` is designed to have two crucial properties - first, the smaller its value is, the bett...
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
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
From an implementation point of view, losses and metrics are actually identical functions in Keras: ``` Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tensorflow.keras as Keras >>> print...
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
Loss helps find the best solution your model can produce. Metric actually tells us how good it is. Imagine, we found the regression line (that has the least minimum squared error). Is that a good enough solution? This is what the metric will answer(considering the shape and spread of data, ideally!).
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/" ]
So in order to understand what `metrics` are, it's good to start by understanding what a `loss` function is. Neural networks are mostly trained using gradient methods by an iterative process of decreasing a `loss` function. A `loss` is designed to have two crucial properties - first, the smaller its value is, the bett...
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...
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/" ]
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...
Loss helps find the best solution your model can produce. Metric actually tells us how good it is. Imagine, we found the regression line (that has the least minimum squared error). Is that a good enough solution? This is what the metric will answer(considering the shape and spread of data, ideally!).
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/" ]
So in order to understand what `metrics` are, it's good to start by understanding what a `loss` function is. Neural networks are mostly trained using gradient methods by an iterative process of decreasing a `loss` function. A `loss` is designed to have two crucial properties - first, the smaller its value is, the bett...
From an implementation point of view, losses and metrics are actually identical functions in Keras: ``` Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tensorflow.keras as Keras >>> print...
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/" ]
So in order to understand what `metrics` are, it's good to start by understanding what a `loss` function is. Neural networks are mostly trained using gradient methods by an iterative process of decreasing a `loss` function. A `loss` is designed to have two crucial properties - first, the smaller its value is, the bett...
Loss helps find the best solution your model can produce. Metric actually tells us how good it is. Imagine, we found the regression line (that has the least minimum squared error). Is that a good enough solution? This is what the metric will answer(considering the shape and spread of data, ideally!).
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/" ]
From an implementation point of view, losses and metrics are actually identical functions in Keras: ``` Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tensorflow.keras as Keras >>> print...
Loss helps find the best solution your model can produce. Metric actually tells us how good it is. Imagine, we found the regression line (that has the least minimum squared error). Is that a good enough solution? This is what the metric will answer(considering the shape and spread of data, ideally!).
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))...
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 feel your pain. I actually recently worked with that webcam script (multiple iterations; substantially edited). I got it to work really well, I think. So that you can see what I did, I created a GitHub Gist with the details (code; HTML readme file; sample output): <https://gist.github.com/victoriastuart/8092a3dd7e97...
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))...
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/" ]
Maybe the problem is that there is a threshold is set. As described [here](https://github.com/davisking/dlib/issues/547) ``` dots = detector(frame, 1) ``` Should be changed to ``` dots = detector(frame) ``` To avoid a threshold. This is works for me, but at the same time, there is a problem that frames are proce...
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))...
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 feel your pain. I actually recently worked with that webcam script (multiple iterations; substantially edited). I got it to work really well, I think. So that you can see what I did, I created a GitHub Gist with the details (code; HTML readme file; sample output): <https://gist.github.com/victoriastuart/8092a3dd7e97...
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...
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 feel your pain. I actually recently worked with that webcam script (multiple iterations; substantially edited). I got it to work really well, I think. So that you can see what I did, I created a GitHub Gist with the details (code; HTML readme file; sample output): <https://gist.github.com/victoriastuart/8092a3dd7e97...
Maybe the problem is that there is a threshold is set. As described [here](https://github.com/davisking/dlib/issues/547) ``` dots = detector(frame, 1) ``` Should be changed to ``` dots = detector(frame) ``` To avoid a threshold. This is works for me, but at the same time, there is a problem that frames are proce...
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>
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...
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 ...
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)) ```
You could do it recursively: ``` def decimal_to_binary(inp): power = 1 tmp = 1 while 2**power <= inp: tmp = 2**power power += 1 if inp-tmp != 0: return [tmp] + decimal_to_binary(inp-tmp) else: return [tmp] print(decimal_to_binary(75)) [64, 8, 2, 1] ```
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>
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...
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/" ]
Performance is [not an explicit design goal of Python](http://python-history.blogspot.nl/2009/01/pythons-design-philosophy.html): > > Don’t fret too much about performance--plan to optimize later when > needed. > > > That's one of the reasons why Python integrated with a lot of high performance calculating backe...
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.
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/" ]
Performance is [not an explicit design goal of Python](http://python-history.blogspot.nl/2009/01/pythons-design-philosophy.html): > > Don’t fret too much about performance--plan to optimize later when > needed. > > > That's one of the reasons why Python integrated with a lot of high performance calculating backe...
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...
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) ...
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) ```
As Andrey correctly noticed, the `<` redirection operator is interpreted by shell. Hence another possible solution: ``` import os os.system("mysql -h " + ip + " -u " + mysqlUser + " " + dbName) ``` It works because `os.system` passes its argument to the shell. Note that I assumed that all used variables come from a...
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/" ]
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) ...
As Andrey correctly noticed, the `<` redirection operator is interpreted by shell. Hence another possible solution: ``` import os os.system("mysql -h " + ip + " -u " + mysqlUser + " " + dbName) ``` It works because `os.system` passes its argument to the shell. Note that I assumed that all used variables come from a...
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...
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.
Also if you dont want to store it in a file for some reason, you can do `cov_score=$(coverage report | awk '$1 == "TOTAL" {print $NF+0}')`
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/" ]
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...
Also if you dont want to store it in a file for some reason, you can do `cov_score=$(coverage report | awk '$1 == "TOTAL" {print $NF+0}')`