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 |
|---|---|---|---|---|---|
54,064,946 | I am working in jupyter with python in order to clean a set of data that I have retrieved from an analysis software and I would like to have an equal number of samples that pass and fail. Basically my dataframe in pandas looks like this:
```
grade section area_steel Nx Myy utilisation Accceptable
0 C16/20 STD ... | 2019/01/06 | [
"https://Stackoverflow.com/questions/54064946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10876004/"
] | Using formatting string and assuming that `optimal_system` is your dictionary:
```
with open('output.txt', 'w') as f:
for k in optimal_system.keys():
f.write("{}: {}\n".format(k, optimal_system[k]))
```
**EDIT**
As pointed by @wwii, the code above can be also written as:
```
with open('output.txt', 'w'... | You can use the [`pprint` module](https://docs.python.org/3/library/pprint.html) -- it also works for all other data structures.
To force every entry on a new line, set the `width` argument to something low. The `stream` argument lets you directly write to the file.
```
import pprint
mydata = {'Optimal Temperature (K)... |
9,164,176 | >
> **Possible Duplicate:**
>
> [Good Primer for Python Slice Notation](https://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation)
>
>
>
I have a string and I'm splitting in a `;` character, I would like to associate this string with variables, but for me just the first x strings is usef... | 2012/02/06 | [
"https://Stackoverflow.com/questions/9164176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/737640/"
] | Yes! Use [slicing](https://stackoverflow.com/q/509211/21475):
```
az1, el1, az2, el2, rfsspe = data_point.split(";")[:5]
```
That "slices" the list to get the first 5 elements only. | The way, I do this is usually to add all the variables to a list(var\_list) and then when I'm processsing the list I do something like
```
for x in var_list[:5]:
print x #or do something
``` |
58,414,350 | Is there a way for Airflow to skip current task from the PythonOperator? For example:
```py
def execute():
if condition:
skip_current_task()
task = PythonOperator(task_id='task', python_callable=execute, dag=some_dag)
```
And also marking the task as "Skipped" in Airflow UI? | 2019/10/16 | [
"https://Stackoverflow.com/questions/58414350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7730549/"
] | Figured it out! Skipping task is as easy as:
```py
def execute():
if condition:
raise AirflowSkipException
task = PythonOperator(task_id='task', python_callable=execute, dag=some_dag)
``` | The easiest solution to skip a task:
```py
def execute():
if condition:
return
task = PythonOperator(task_id='task', python_callable=execute, dag=some_dag)
```
Unfortunately, it will mark task as `DONE` |
49,145,328 | I am new to using google colaboratory (colab) and pydrive along with it. I am trying to load data in 'CAS\_num\_strings' which was written in a pickle file in a specific directory on my google drive using colab as:
```
pickle.dump(CAS_num_strings,open('CAS_num_strings.p', 'wb'))
dump_meta = {'title': 'CAS.pkl', 'paren... | 2018/03/07 | [
"https://Stackoverflow.com/questions/49145328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9407842/"
] | Apply the `click` event for `<tr>` and pass the current reference `this` to the calling function like `<tr onclick="callme(this)">`. From the javascript get the current row reference and find all the `td` inside that. Now get the values using `innerHTML` and assign it to the respective input fields("id\_type" , "event\... | According to HTML spec `id` attribute should be unique in a page,
so if you have multiple elements with same `id`, your HTML is not valid.
`getElementById()` should only ever return one element. You can't make it return multiple elements.
So you can use unique `id` for each row or try using `class` |
62,328,382 | I'm new to python and plotly.graph\_objects. I created some maps similar to the example found here: [United States Choropleth Map](https://plotly.com/python/choropleth-maps/#united-states-choropleth-map)
I'd like to combine the maps into one figure with a common color scale. I've looked at lots of examples of people us... | 2020/06/11 | [
"https://Stackoverflow.com/questions/62328382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373313/"
] | The solution is to not use the `$_COOKIE` array, but a variable
```php
<?php
// Use a variable
$cookieValue = 1;
// Check the cookie
if ((isset($_COOKIE["i"])) && !empty($_COOKIE["i"])) {
$cookieValue = (int)$_COOKIE["i"] + 1;
}
// Push the cookie
setcookie("i", $cookieValue);
// Use the variable
echo $cookieV... | ```
else{
setcookie("i",1);
header("Refresh:0");
}
``` |
57,464,273 | I have a dataframe with a columns that contain GPS coordinates. I want to convert the columns that are in degree seconds to degree decimals. For example, I have a 2 columns named "lat\_sec" and "long\_sec" that are formatted with values like 186780.8954N. I tried to write a function that saves the last character in the... | 2019/08/12 | [
"https://Stackoverflow.com/questions/57464273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11771163/"
] | By doing `float(coordinate[:-1]/3600)` you are dividing `str` by `int` which is not possible, what you can do is convert the `str` into `float` than divide it by integer `3600` which gives you `float` output.
Second you are not using `apply` properly and there is no `lat_sec` column to which you are applying your func... | In your code above, inside `convertDec` method, there is also an error in :
```
decimal = float(coordinate[:-1]/3600)
```
You need to convert the `coordinate` to float first before divide it with 3600.
So, your code above should look like this :
```
import pandas as pd
# Your example dataset
dictCoordinates = {
... |
37,947,178 | I am using python and I have to write a program to create files of a total of 160 GB. I ran the program overnight and it was able to create files of 100 GB. However, after that it stopped running and gave an error saying "No space left on device".
QUESTION : I wanted to ask if it was possible to start running the pro... | 2016/06/21 | [
"https://Stackoverflow.com/questions/37947178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6465134/"
] | Steps to fix this error in windows 10/8/7
1.Check your javac path on Windows using Windows Explorer C:\Program Files\Java\jdk1.7.0\_02\bin and copy the address.
2.Go to Control Panel. Environment Variables and Insert the address at the beginning of var. Path followed by semicolon. i.e C:\Program Files\Java\jdk1.7.0\_... | You need to add the location of your JDK to your PATH variable, if you wish to call javac.exe without the path.
```
set PATH=%PATH%;C:\path\to\your\JDK\bin\dir
```
Then...
```
javac.exe MyFirstProgram.java
```
OR, you can simply call it via the full path to javac.exe from your JDK installation e.g.
```
C:\path\t... |
74,188,813 | In practicing python, I've come across the sliding window technique but don't quite understand the implementation. Given a string k and integer N, the code is to loop through, thereby moving the window from left to right. However, the capture of the windowed elements as well as how the window grows is fuzzy to me.
The... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74188813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10047888/"
] | Instead of trying to solve =b) it might be easier to look at  and just solve this iteratively, taking advantage of Python's integer type. This way you can avoid the float domain, and its associated ... | You can use decimals and play with precision and rounding instead of floats in this case
Like this:
```
from decimal import Decimal, Context, ROUND_HALF_UP, ROUND_HALF_DOWN
ctx1 = Context(prec=20, rounding=ROUND_HALF_UP)
ctx2 = Context(prec=20, rounding=ROUND_HALF_DOWN)
ctx1.divide(Decimal(243).ln( ctx1) , Decimal(3... |
74,188,813 | In practicing python, I've come across the sliding window technique but don't quite understand the implementation. Given a string k and integer N, the code is to loop through, thereby moving the window from left to right. However, the capture of the windowed elements as well as how the window grows is fuzzy to me.
The... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74188813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10047888/"
] | How about this? Is this what you are looking for?
```
import math
def ilog(a: int, p:int) -> int:
"""
find the largest b such that p ** b <= a
"""
float_log = math.log(a, p)
if (candidate := math.ceil(float_log))**p <= a:
return candidate
return int(float_log)
print(ilog(243, 3))
p... | You can use decimals and play with precision and rounding instead of floats in this case
Like this:
```
from decimal import Decimal, Context, ROUND_HALF_UP, ROUND_HALF_DOWN
ctx1 = Context(prec=20, rounding=ROUND_HALF_UP)
ctx2 = Context(prec=20, rounding=ROUND_HALF_DOWN)
ctx1.divide(Decimal(243).ln( ctx1) , Decimal(3... |
74,188,813 | In practicing python, I've come across the sliding window technique but don't quite understand the implementation. Given a string k and integer N, the code is to loop through, thereby moving the window from left to right. However, the capture of the windowed elements as well as how the window grows is fuzzy to me.
The... | 2022/10/25 | [
"https://Stackoverflow.com/questions/74188813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10047888/"
] | Instead of trying to solve =b) it might be easier to look at  and just solve this iteratively, taking advantage of Python's integer type. This way you can avoid the float domain, and its associated ... | How about this? Is this what you are looking for?
```
import math
def ilog(a: int, p:int) -> int:
"""
find the largest b such that p ** b <= a
"""
float_log = math.log(a, p)
if (candidate := math.ceil(float_log))**p <= a:
return candidate
return int(float_log)
print(ilog(243, 3))
p... |
58,877,657 | I am learning python
I have project structure shown below.
```
i3cmd
i3lib
__init__.py
i3common.py
i3sound
i3sound.py
```
==============================================================
**init**.py is empty
i3common.py (removed actual code to simplify the post)
```
def rangeofdata(cmd, d... | 2019/11/15 | [
"https://Stackoverflow.com/questions/58877657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446934/"
] | I think you are just missing the installation of the `Lombok` on `intellij`
double click on `Lombok.jar` and chose the `intelliJ IDE`
Example config for lombok annotation procession in your `build.gradle` :
```
dependencies {
compileOnly('org.projectlombok:lombok:1.16.20')
annotationProcessor 'org.projectlomb... | Line `compileOnly 'org.projectlombok:lombok:1.18.8'` shows that you're using gradle.
I think the easiest way to check whether it works or not can be just running the gradle build (without IDE).
Since lombok is an annotation processor, as long as the code passes the compilation, it's supposed to work (and the chances ... |
58,877,657 | I am learning python
I have project structure shown below.
```
i3cmd
i3lib
__init__.py
i3common.py
i3sound
i3sound.py
```
==============================================================
**init**.py is empty
i3common.py (removed actual code to simplify the post)
```
def rangeofdata(cmd, d... | 2019/11/15 | [
"https://Stackoverflow.com/questions/58877657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446934/"
] | ### Lombok 1.18.8: @Wither
If you look at the actual implementation of `withA()` you will notice that it relies on an all-args constructors. To make your example work, try to add it, as well as a no-arg constructor:
```
@Wither
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int a;
}
```
The ... | I think you are just missing the installation of the `Lombok` on `intellij`
double click on `Lombok.jar` and chose the `intelliJ IDE`
Example config for lombok annotation procession in your `build.gradle` :
```
dependencies {
compileOnly('org.projectlombok:lombok:1.16.20')
annotationProcessor 'org.projectlomb... |
58,877,657 | I am learning python
I have project structure shown below.
```
i3cmd
i3lib
__init__.py
i3common.py
i3sound
i3sound.py
```
==============================================================
**init**.py is empty
i3common.py (removed actual code to simplify the post)
```
def rangeofdata(cmd, d... | 2019/11/15 | [
"https://Stackoverflow.com/questions/58877657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446934/"
] | ### Lombok 1.18.8: @Wither
If you look at the actual implementation of `withA()` you will notice that it relies on an all-args constructors. To make your example work, try to add it, as well as a no-arg constructor:
```
@Wither
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int a;
}
```
The ... | Line `compileOnly 'org.projectlombok:lombok:1.18.8'` shows that you're using gradle.
I think the easiest way to check whether it works or not can be just running the gradle build (without IDE).
Since lombok is an annotation processor, as long as the code passes the compilation, it's supposed to work (and the chances ... |
8,595,689 | I'm trying to send a request to an API that only accepts XML. I've used `elementtree.SimpleXMLWriter` to build the XML tree and it's stored in a StringIO object. That's all fine and dandy.
The problem is that I have to urlencode the StringIO object in order to send it to the API. But when I try, I get:
```
File "C:... | 2011/12/21 | [
"https://Stackoverflow.com/questions/8595689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/625840/"
] | As the links you provided point out, php is not a persistent language and there is no way to have persistence across sessions (i.e. page loads). You can create a middle ground though by running a second php script as a daemon, and have your main script (i.e. the one the user hits) connect to that (yes - over a socket..... | If you need to keep the connection open, you need to keep the PHP script open. Commonly PHP is just invoked and then closed after the script has run (CGI, CLI), or it's a mixture (mod\_php in apache, FCGI) in which sometimes the PHP interpreter stays in memory after your script has finished (so everything associated fr... |
60,780,826 | I try to write a python function that counts a specific word in a string.
My regex pattern doesn't work when the word I want to count is repeated multiple times in a row. The pattern seems to work well otherwise.
Here is my function
```
import re
def word_count(word, text):
return len(re.findall('(^|\s|\b)'+re.... | 2020/03/20 | [
"https://Stackoverflow.com/questions/60780826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7915157/"
] | Problem is in your regex. Your regex is using 2 capture groups and `re.findall` will return any capture groups if available. That needs to change to non-capture groups using `(?:...)`
Besides there is reason to use `(^|\s|\b)` as `\b` or word boundary is suffice which covers all the cases besides `\b` is zero width.
... | I am not sure this is 100% because I don't understand the part about passing the function the word to search for when you are just looking for words that repeat in a string. So maybe consider...
```
import re
pattern = r'\b(\w+)( \1\b)+'
def word_count(text):
split_words = text.split(' ')
count = 0
for s... |
66,702,514 | I am trying to create a function that would take a user inputted number and determine if the number is an integer or a floating-point depending on what the mode is set to. I am very new to python and learning the language and I am getting an invalid syntax error and I don't know what to do. So far I am making the integ... | 2021/03/19 | [
"https://Stackoverflow.com/questions/66702514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15429618/"
] | `.testcontainer.properties` in my `$HOME` directory fixed the issue for me.
This file is used to override properties but I am still not sure how that fixes the issue.
I see in my `.gitlab.yml` that what we do and just imitated that in my local, that solved the issue. | For some it might help to update the version of testcontainers |
62,421,333 | I have a dataframe like image1. I want to convert it to image2.
I have tried r, python, and excel but failed. Excel formula: =INDEX(AV2:AW2,MODE(MATCH(AV2:AW2,AV2:AW2,0))) give me N/A output.
the "k2" column would be the most common element from "knumbers" column. Any Help. Best, Zillur
[, function(x)
names(sort(table(x), decreasing = TRUE)[1]))
``` | Python solution:
```
# Initialise pandas, and mode in session:
import pandas as pd
from statistics import mode
# Scalar denoting the full path to file (including file name): filepath => string scalar
filepath = ''
# Read in the Excel sheet: df => Data Frame
df = pd.read_excel(filepath)
# Find modal element per r... |
9,905,874 | I'm running into a problem that I haven't seen anyone on StackOverflow encounter or even google for that matter.
My main goal is to be able to replace occurences of a string in the file with another string. Is there a way there a way to be able to acess all of the lines in the file.
The problem is that when I try to ... | 2012/03/28 | [
"https://Stackoverflow.com/questions/9905874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297872/"
] | Try:
```
f = open("filename.txt", "rb")
```
On Windows, `rb` means open file in binary mode. According to the docs, text mode vs. binary mode only has an impact on end-of-line characters. But (if I remember correctly) I believe opening files in text mode on Windows also does something with EOF (hex 1A).
You can als... | If you use the file like this:
```
with open("filename.txt") as f:
for line in f:
newfile.write(line.replace("string1", "string2"))
```
It should only read into memory one line at a time, unless you keep a reference to that line in memory.
After each line is read it will be up to pythons garbage colle... |
9,905,874 | I'm running into a problem that I haven't seen anyone on StackOverflow encounter or even google for that matter.
My main goal is to be able to replace occurences of a string in the file with another string. Is there a way there a way to be able to acess all of the lines in the file.
The problem is that when I try to ... | 2012/03/28 | [
"https://Stackoverflow.com/questions/9905874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297872/"
] | Are you sure the problem is with reading and not with writing out?
Do you close the file that is written to, either explicitly `newfile.close()` or using the `with` construct?
Not closing the output file is often the source of such problems when buffering is going on somewhere. If that's the case in your setting too, ... | If you use the file like this:
```
with open("filename.txt") as f:
for line in f:
newfile.write(line.replace("string1", "string2"))
```
It should only read into memory one line at a time, unless you keep a reference to that line in memory.
After each line is read it will be up to pythons garbage colle... |
9,905,874 | I'm running into a problem that I haven't seen anyone on StackOverflow encounter or even google for that matter.
My main goal is to be able to replace occurences of a string in the file with another string. Is there a way there a way to be able to acess all of the lines in the file.
The problem is that when I try to ... | 2012/03/28 | [
"https://Stackoverflow.com/questions/9905874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297872/"
] | Try:
```
f = open("filename.txt", "rb")
```
On Windows, `rb` means open file in binary mode. According to the docs, text mode vs. binary mode only has an impact on end-of-line characters. But (if I remember correctly) I believe opening files in text mode on Windows also does something with EOF (hex 1A).
You can als... | Are you sure the problem is with reading and not with writing out?
Do you close the file that is written to, either explicitly `newfile.close()` or using the `with` construct?
Not closing the output file is often the source of such problems when buffering is going on somewhere. If that's the case in your setting too, ... |
68,945,015 | I need a simple python library to convert PDF to image (render the PDF as is), but after hours of searching, I keep hitting the same wall, I find libraries like `pdf2image` python library (and many similar ones), which depend on external applications or wrap command-line tools.
Although there are workarounds to allow ... | 2021/08/26 | [
"https://Stackoverflow.com/questions/68945015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452748/"
] | You said "Ended up using pdf2image"
[pdf2image (MIT)](https://pypi.org/project/pdf2image/). A python (3.6+) module that wraps pdftoppm (GPL?) and pdftocairo (GPL?) to convert PDF to a PIL Image object.
Generally [Poppler (GPL)](https://en.wikipedia.org/wiki/Poppler_(software)) spinoffs from Open Source [Xpdf (GPL)](h... | You can convert PDF's to images without external dependencies using PyMuPDF. I use it for Azure functions.
Install with `pip install PyMuPDF`
In your python file:
```
import fitz
pdfDoc = fitz.open(filepath)
img = pdfDoc[0].get_pixmap(matrix=fitz.Matrix(2,2))
bytesimg = img.tobytes()
```
This takes the first page ... |
31,941,951 | In my Python code I use a third party shared object, a `.so` file, which I suspect to contains a memory leak.
During the run of my program I have a loop where I repeatedly call functions of the shared object. While the programm is running I can see in `htop`, that the memory usage is steadily increasing. When the RAM... | 2015/08/11 | [
"https://Stackoverflow.com/questions/31941951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380038/"
] | The exact cause of the exception is, that the number `1439284609013` is too big to fit into `Integer`.
However, the actual issue lies elsewhere. I have looked at the source code, your parameters seem to be wrong:
```
emp1 ~/KT/bkp 1439284609013 1439284641872
```
You have given a `String`, another `String` and two `... | I entered only the start time and end time. Export is expecting versions before start and end time. So finally I entered the version number it worked.
```
./hbase org.apache.hadoop.hbase.mapreduce.Export emp1 ~/KT/bkp 2147483647 1439284609013 1439284646830
``` |
31,941,951 | In my Python code I use a third party shared object, a `.so` file, which I suspect to contains a memory leak.
During the run of my program I have a loop where I repeatedly call functions of the shared object. While the programm is running I can see in `htop`, that the memory usage is steadily increasing. When the RAM... | 2015/08/11 | [
"https://Stackoverflow.com/questions/31941951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380038/"
] | Timestamps are usually associated to Long types, that have 64 bits
Integers have 32 bits and the range is only -2,147,483,648 to 2,147,483,647 in Java | I entered only the start time and end time. Export is expecting versions before start and end time. So finally I entered the version number it worked.
```
./hbase org.apache.hadoop.hbase.mapreduce.Export emp1 ~/KT/bkp 2147483647 1439284609013 1439284646830
``` |
67,280,726 | I want to extract some data from a text file to a dataframe :
the text file look like this
```
URL: http://www.nytimes.com/2016/06/30/sports/baseball/washington-nationals-max-scherzer-baffles-mets-completing-a-sweep.html
WASHINGTON — Stellar .... stretched thin.
“We were going t......e do anything.”
Wednesday’s ... ... | 2021/04/27 | [
"https://Stackoverflow.com/questions/67280726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10586681/"
] | ```
# read file
file = open('ny.txt', encoding="utf8").read()
url = []
text = []
# split text at every 2-new-lines
# elements at 'odd' positions are 'urls'
# elements at 'even' positions are 'text/content'
for ind, line in enumerate(file.split('\n\n')):
if ind%2==0:
url.append(line)
else:
text... | You can do it easily in the following way:
```
import pandas as pd
text = '''URL: http://www.nytimes.com/2016/06/30/sports/baseball/washington-nationals-max-scherzer-baffles-mets-completing-a-sweep.html
WASHINGTON — Stellar .... stretched thin.
“We were going t......e do anything.”
Wednesday’s ... starter.
“We’re n.... |
63,506,041 | Am new to python and am trying to read a PDF file to pull the `ID No.`. I have been successful so far to extract the text out of the PDF file using `pdfplumber`. Below is the code block:
```
import pdfplumber
with pdfplumber.open('ABC.pdf') as pdf_file:
firstpage = pdf_file.pages[0]
raw_text = firstpage.extra... | 2020/08/20 | [
"https://Stackoverflow.com/questions/63506041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7855187/"
] | Try using a regular expression:
```
import pdfplumber
import re
with pdfplumber.open('ABC.pdf') as pdf_file:
firstpage = pdf_file.pages[0]
raw_text = firstpage.extract_text()
m = re.search(r'ID No\. : (\d+)', raw_text)
if m:
print(m.group(1))
```
Of course you'll have to iterate over *all* t... | If the length of the id number is always the same, I would try to find the location of it with the find-function. `position = raw_text.find('ID No. : ')`should return the position of the I in ID No. position + 9 should be the first digit of the id. When the number has always a length of 8 you could get it with `int(raw... |
63,506,041 | Am new to python and am trying to read a PDF file to pull the `ID No.`. I have been successful so far to extract the text out of the PDF file using `pdfplumber`. Below is the code block:
```
import pdfplumber
with pdfplumber.open('ABC.pdf') as pdf_file:
firstpage = pdf_file.pages[0]
raw_text = firstpage.extra... | 2020/08/20 | [
"https://Stackoverflow.com/questions/63506041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7855187/"
] | Try using a regular expression:
```
import pdfplumber
import re
with pdfplumber.open('ABC.pdf') as pdf_file:
firstpage = pdf_file.pages[0]
raw_text = firstpage.extract_text()
m = re.search(r'ID No\. : (\d+)', raw_text)
if m:
print(m.group(1))
```
Of course you'll have to iterate over *all* t... | If you are new to Python and actually need to process serious amounts of data, I suggest that you look at Scala as an alternative.
For data processing in general, and regular expression matching in particular, the time it takes to get results is much reduced.
Here is an answer to your question in Scala instead of Pyt... |
14,657,498 | I'd like to create a `text/plain` message using Markdown formatting and transform that into a `multipart/alternative` message where the `text/html` part has been generated from the Markdown.
I've tried using the filter command to filter this through a python program that creates the message, but it seems that the messa... | 2013/02/02 | [
"https://Stackoverflow.com/questions/14657498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053149/"
] | Inside your `DialogFragment`, call [`Fragment.setRetainInstance(boolean)`](http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance%28boolean%29) with the value `true`. You don't need to save the fragment manually, the framework already takes care of all of this. Calling this will prevent your... | One of the advantages of using `dialogFragment` compared to just using `alertDialogBuilder` is exactly because dialogfragment can automatically recreate itself upon rotation without user intervention.
However, when the dialogfragment does not recreate itself, it is possible that you overwrite `onSaveInstanceState` but... |
14,657,498 | I'd like to create a `text/plain` message using Markdown formatting and transform that into a `multipart/alternative` message where the `text/html` part has been generated from the Markdown.
I've tried using the filter command to filter this through a python program that creates the message, but it seems that the messa... | 2013/02/02 | [
"https://Stackoverflow.com/questions/14657498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053149/"
] | Inside your `DialogFragment`, call [`Fragment.setRetainInstance(boolean)`](http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance%28boolean%29) with the value `true`. You don't need to save the fragment manually, the framework already takes care of all of this. Calling this will prevent your... | This is a convenience method using the fix from antonyt's answer:
```
public class RetainableDialogFragment extends DialogFragment {
public RetainableDialogFragment() {
setRetainInstance(true);
}
@Override
public void onDestroyView() {
Dialog dialog = getDialog();
// handles h... |
14,657,498 | I'd like to create a `text/plain` message using Markdown formatting and transform that into a `multipart/alternative` message where the `text/html` part has been generated from the Markdown.
I've tried using the filter command to filter this through a python program that creates the message, but it seems that the messa... | 2013/02/02 | [
"https://Stackoverflow.com/questions/14657498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053149/"
] | Inside your `DialogFragment`, call [`Fragment.setRetainInstance(boolean)`](http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance%28boolean%29) with the value `true`. You don't need to save the fragment manually, the framework already takes care of all of this. Calling this will prevent your... | In case nothing helps, and you need a solution that works, you can go on the safe side, and each time you open a dialog save its basic info to the activity ViewModel (and remove it from this list when you dismiss dialog). This basic info could be dialog type and some id (the information you need in order to open this d... |
14,657,498 | I'd like to create a `text/plain` message using Markdown formatting and transform that into a `multipart/alternative` message where the `text/html` part has been generated from the Markdown.
I've tried using the filter command to filter this through a python program that creates the message, but it seems that the messa... | 2013/02/02 | [
"https://Stackoverflow.com/questions/14657498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053149/"
] | Inside your `DialogFragment`, call [`Fragment.setRetainInstance(boolean)`](http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance%28boolean%29) with the value `true`. You don't need to save the fragment manually, the framework already takes care of all of this. Calling this will prevent your... | Most of the answers here are incorrect because they use setRetainInstance(true), but this is now deprecated as of [API 28](https://developer.android.com/reference/android/app/Fragment.html#setRetainInstance%28boolean%29). Here is the solution I am using:
```
fun isDialogVisible(fm: FragmentManager): Boolean {
val ... |
14,657,498 | I'd like to create a `text/plain` message using Markdown formatting and transform that into a `multipart/alternative` message where the `text/html` part has been generated from the Markdown.
I've tried using the filter command to filter this through a python program that creates the message, but it seems that the messa... | 2013/02/02 | [
"https://Stackoverflow.com/questions/14657498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053149/"
] | One of the advantages of using `dialogFragment` compared to just using `alertDialogBuilder` is exactly because dialogfragment can automatically recreate itself upon rotation without user intervention.
However, when the dialogfragment does not recreate itself, it is possible that you overwrite `onSaveInstanceState` but... | In case nothing helps, and you need a solution that works, you can go on the safe side, and each time you open a dialog save its basic info to the activity ViewModel (and remove it from this list when you dismiss dialog). This basic info could be dialog type and some id (the information you need in order to open this d... |
14,657,498 | I'd like to create a `text/plain` message using Markdown formatting and transform that into a `multipart/alternative` message where the `text/html` part has been generated from the Markdown.
I've tried using the filter command to filter this through a python program that creates the message, but it seems that the messa... | 2013/02/02 | [
"https://Stackoverflow.com/questions/14657498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053149/"
] | One of the advantages of using `dialogFragment` compared to just using `alertDialogBuilder` is exactly because dialogfragment can automatically recreate itself upon rotation without user intervention.
However, when the dialogfragment does not recreate itself, it is possible that you overwrite `onSaveInstanceState` but... | Most of the answers here are incorrect because they use setRetainInstance(true), but this is now deprecated as of [API 28](https://developer.android.com/reference/android/app/Fragment.html#setRetainInstance%28boolean%29). Here is the solution I am using:
```
fun isDialogVisible(fm: FragmentManager): Boolean {
val ... |
14,657,498 | I'd like to create a `text/plain` message using Markdown formatting and transform that into a `multipart/alternative` message where the `text/html` part has been generated from the Markdown.
I've tried using the filter command to filter this through a python program that creates the message, but it seems that the messa... | 2013/02/02 | [
"https://Stackoverflow.com/questions/14657498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053149/"
] | This is a convenience method using the fix from antonyt's answer:
```
public class RetainableDialogFragment extends DialogFragment {
public RetainableDialogFragment() {
setRetainInstance(true);
}
@Override
public void onDestroyView() {
Dialog dialog = getDialog();
// handles h... | In case nothing helps, and you need a solution that works, you can go on the safe side, and each time you open a dialog save its basic info to the activity ViewModel (and remove it from this list when you dismiss dialog). This basic info could be dialog type and some id (the information you need in order to open this d... |
14,657,498 | I'd like to create a `text/plain` message using Markdown formatting and transform that into a `multipart/alternative` message where the `text/html` part has been generated from the Markdown.
I've tried using the filter command to filter this through a python program that creates the message, but it seems that the messa... | 2013/02/02 | [
"https://Stackoverflow.com/questions/14657498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1053149/"
] | This is a convenience method using the fix from antonyt's answer:
```
public class RetainableDialogFragment extends DialogFragment {
public RetainableDialogFragment() {
setRetainInstance(true);
}
@Override
public void onDestroyView() {
Dialog dialog = getDialog();
// handles h... | Most of the answers here are incorrect because they use setRetainInstance(true), but this is now deprecated as of [API 28](https://developer.android.com/reference/android/app/Fragment.html#setRetainInstance%28boolean%29). Here is the solution I am using:
```
fun isDialogVisible(fm: FragmentManager): Boolean {
val ... |
40,390,874 | So, I'm making a Bank class in python. It has the basic functions of deposit, withdrawing, and checking your balance. I'm having trouble with a transfer method though.
This is my code for the class.
```
def __init__(self, customerID):
self.ID = customerID
self.total = 0
def deposit(self, amount):
self.to... | 2016/11/02 | [
"https://Stackoverflow.com/questions/40390874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6023942/"
] | ```
def __init__(self, customerID):
self.ID = customerID
self.__class__.__dict__.setdefault("idents",{})[self.ID] = self
self.total = 0
@classmethod
def get_bank(cls,id):
return cls.__dict__.setdefault("idents",{}).get(id)
```
is one kind of gross way you could do it
```
bank2_found = Bank.get_bank(... | You could store all the ID numbers and their associated objects in a dict with the ID as the key and the object as the value. |
31,977,902 | How can I calculates the elapsed time between a start time and an end time of a event using python, in format like 00:00:00 and 23:59:59? | 2015/08/13 | [
"https://Stackoverflow.com/questions/31977902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5221453/"
] | Make it easy on yourself and try to make your code easy to read. I personally prefer to write my html cleanly and outside of echo statements like so:
**Html**
```
if (strlen($in) > 0 and strlen($in) < 20) {
$sql = "select name, entry, displayid from item_template where name like '%{$in}%' LIMIT 10"; // the query
... | Ok, here goes...
1. Use event delegation in your JavaScript to handle the button clicks. This will work for all present and future buttons
```
jQuery(function($) {
var $theInput = $('#theinput');
$(document).on('click', '.button', function() {
$theInput.val(this.value);
});
});
```
2. Less import... |
47,717,179 | If my python script is pivoting and i can no predict how many columns will be outputed, can this be done with the U-SQL REDUCE statement?
e.g.
```
@pythonOutput =
REDUCE @filteredBets ON [BetDetailID]
PRODUCE [BetDetailID] string, EventID float
USING new Extension.Python.Reducer(pyScript:@myScript);
```... | 2017/12/08 | [
"https://Stackoverflow.com/questions/47717179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2725941/"
] | If you have a way to produce a `SqlMap<string,string>` value from within Python (I am not sure if that is supported right now, you can do it with a C# reducer :)), then you could use the map for the dynamic schema part.
If it is not supported in Python, please file a feature request at <http://aka.ms/adlfeedback>. | The only way right now is to serialize all the columns into a single column, either as a byte[] or string in your python script. SqlMap/SqlArray are not supported yet as output columns. |
50,113,683 | i try to train.py in object\_detection in under git url
<https://github.com/tensorflow/models/tree/master/research/object_detection>
However, the following error occurs.
>
> ModuleNotFoundError: No module named 'object\_detection'
>
>
>
So I tried to solve the problem by writing the following code.
```
import ... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50113683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9019755/"
] | try this:
python setup.py build
python setup.py install | I had to do:
`sudo pip3 install -e .` ([ref](https://github.com/tensorflow/models/issues/2031#issuecomment-343782858))
`sudo python3 setup.py install`
System:
OS: Ubuntu 16.04, Anaconda (I guess this is why I need to use `pip3` and `python3` even I made virtual environment with Pyehon 3.8) |
50,113,683 | i try to train.py in object\_detection in under git url
<https://github.com/tensorflow/models/tree/master/research/object_detection>
However, the following error occurs.
>
> ModuleNotFoundError: No module named 'object\_detection'
>
>
>
So I tried to solve the problem by writing the following code.
```
import ... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50113683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9019755/"
] | There are a number of modules in the object\_detection folder, and I have created setup.py in the parent directory(research folder) to import all of them.
```
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['Pillow>=1.0', 'Matplotlib>=2.1', 'Cython>=0.28.1']
setup(
name='ob... | I had to do:
`sudo pip3 install -e .` ([ref](https://github.com/tensorflow/models/issues/2031#issuecomment-343782858))
`sudo python3 setup.py install`
System:
OS: Ubuntu 16.04, Anaconda (I guess this is why I need to use `pip3` and `python3` even I made virtual environment with Pyehon 3.8) |
50,113,683 | i try to train.py in object\_detection in under git url
<https://github.com/tensorflow/models/tree/master/research/object_detection>
However, the following error occurs.
>
> ModuleNotFoundError: No module named 'object\_detection'
>
>
>
So I tried to solve the problem by writing the following code.
```
import ... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50113683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9019755/"
] | You need to export the environmental variables every time you open a new terminal in that environment.
Please note that there are are back quotes on each of the pwd in the command as this might not be showing in the command below. Back quote is the same as the tilde key without pressing the shift key (US keyboard).
... | try this:
python setup.py build
python setup.py install |
50,113,683 | i try to train.py in object\_detection in under git url
<https://github.com/tensorflow/models/tree/master/research/object_detection>
However, the following error occurs.
>
> ModuleNotFoundError: No module named 'object\_detection'
>
>
>
So I tried to solve the problem by writing the following code.
```
import ... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50113683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9019755/"
] | Try install **Tensorflow Object Detection Library Packaged**
```
pip install tensorflow-object-detection-api
``` | Cause of this error is installing object\_detection library, So one of the solution which can work is running the below command inside models/research
```
sudo python setup.py install
```
If such solution does not work, please execute the below command one by one in the directory models/research
```
expor... |
50,113,683 | i try to train.py in object\_detection in under git url
<https://github.com/tensorflow/models/tree/master/research/object_detection>
However, the following error occurs.
>
> ModuleNotFoundError: No module named 'object\_detection'
>
>
>
So I tried to solve the problem by writing the following code.
```
import ... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50113683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9019755/"
] | Cause of this error is installing object\_detection library, So one of the solution which can work is running the below command inside models/research
```
sudo python setup.py install
```
If such solution does not work, please execute the below command one by one in the directory models/research
```
expor... | There are a number of modules in the object\_detection folder, and I have created setup.py in the parent directory(research folder) to import all of them.
```
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['Pillow>=1.0', 'Matplotlib>=2.1', 'Cython>=0.28.1']
setup(
name='ob... |
50,113,683 | i try to train.py in object\_detection in under git url
<https://github.com/tensorflow/models/tree/master/research/object_detection>
However, the following error occurs.
>
> ModuleNotFoundError: No module named 'object\_detection'
>
>
>
So I tried to solve the problem by writing the following code.
```
import ... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50113683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9019755/"
] | You did have "sys.path.append()" before you imported the object detection, so I am surprised that you are facing this error!
Please check that the path you have used in sys.path.append() is right.
Well, the only and obvious answer for the error is that the path of the module is not added properly.
Besides the variou... | I had to do:
`sudo pip3 install -e .` ([ref](https://github.com/tensorflow/models/issues/2031#issuecomment-343782858))
`sudo python3 setup.py install`
System:
OS: Ubuntu 16.04, Anaconda (I guess this is why I need to use `pip3` and `python3` even I made virtual environment with Pyehon 3.8) |
50,113,683 | i try to train.py in object\_detection in under git url
<https://github.com/tensorflow/models/tree/master/research/object_detection>
However, the following error occurs.
>
> ModuleNotFoundError: No module named 'object\_detection'
>
>
>
So I tried to solve the problem by writing the following code.
```
import ... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50113683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9019755/"
] | Cause of this error is installing object\_detection library, So one of the solution which can work is running the below command inside models/research
```
sudo python setup.py install
```
If such solution does not work, please execute the below command one by one in the directory models/research
```
expor... | I had to do:
`sudo pip3 install -e .` ([ref](https://github.com/tensorflow/models/issues/2031#issuecomment-343782858))
`sudo python3 setup.py install`
System:
OS: Ubuntu 16.04, Anaconda (I guess this is why I need to use `pip3` and `python3` even I made virtual environment with Pyehon 3.8) |
50,113,683 | i try to train.py in object\_detection in under git url
<https://github.com/tensorflow/models/tree/master/research/object_detection>
However, the following error occurs.
>
> ModuleNotFoundError: No module named 'object\_detection'
>
>
>
So I tried to solve the problem by writing the following code.
```
import ... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50113683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9019755/"
] | Try install **Tensorflow Object Detection Library Packaged**
```
pip install tensorflow-object-detection-api
``` | There are a number of modules in the object\_detection folder, and I have created setup.py in the parent directory(research folder) to import all of them.
```
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['Pillow>=1.0', 'Matplotlib>=2.1', 'Cython>=0.28.1']
setup(
name='ob... |
50,113,683 | i try to train.py in object\_detection in under git url
<https://github.com/tensorflow/models/tree/master/research/object_detection>
However, the following error occurs.
>
> ModuleNotFoundError: No module named 'object\_detection'
>
>
>
So I tried to solve the problem by writing the following code.
```
import ... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50113683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9019755/"
] | And finally, If you've followed all the steps here and are at your wit's end...make sure the file that you're running (the one with your source code in it ya know), isn't named `object_detection.py` - that would preclude it being searched for as a module.
Certainly I've never done anything like this that led me to add... | I had to do:
`sudo pip3 install -e .` ([ref](https://github.com/tensorflow/models/issues/2031#issuecomment-343782858))
`sudo python3 setup.py install`
System:
OS: Ubuntu 16.04, Anaconda (I guess this is why I need to use `pip3` and `python3` even I made virtual environment with Pyehon 3.8) |
50,113,683 | i try to train.py in object\_detection in under git url
<https://github.com/tensorflow/models/tree/master/research/object_detection>
However, the following error occurs.
>
> ModuleNotFoundError: No module named 'object\_detection'
>
>
>
So I tried to solve the problem by writing the following code.
```
import ... | 2018/05/01 | [
"https://Stackoverflow.com/questions/50113683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9019755/"
] | Cause of this error is installing object\_detection library, So one of the solution which can work is running the below command inside models/research
```
sudo python setup.py install
```
If such solution does not work, please execute the below command one by one in the directory models/research
```
expor... | You did have "sys.path.append()" before you imported the object detection, so I am surprised that you are facing this error!
Please check that the path you have used in sys.path.append() is right.
Well, the only and obvious answer for the error is that the path of the module is not added properly.
Besides the variou... |
49,191,477 | The `hypot` function, introduced into C in the 1999 revision of the language, calculates the hypotenuse of a right triangle given the other sides as arguments, but with care taken to avoid the over/underflow which would result from the naive implementation as
```
double hypot(double a, double b)
{
return sqrt(a*a +... | 2018/03/09 | [
"https://Stackoverflow.com/questions/49191477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/468334/"
] | Assuming IEEE 754 basic 64-bit binary floating-point, I would consider an algorithm such as:
* Set *s* (for scale) to be 2−512 if 2100 ≤ *a*, 2+512 if *a* < 2−100, and 1 otherwise.
* Let *a*' be *a*•*s* and *b*' be *b*•*s*.
* Compute sqrt(*a*'•*a*' − *b*'•*b*') / *s*.
Notes about the reasoning:
* If *a* is large (or... | `hypot` has its idiosyncrasies in that it's one of a *very select few* C standard library functions that does **not** propagate `NaN`! (Another one is `pow` for the case where the first argument being 1.)
Setting that aside, I'd be inclined to write merely
```
returns sqrt(h * h - a * a); // h is the hypotenuse
```
... |
49,191,477 | The `hypot` function, introduced into C in the 1999 revision of the language, calculates the hypotenuse of a right triangle given the other sides as arguments, but with care taken to avoid the over/underflow which would result from the naive implementation as
```
double hypot(double a, double b)
{
return sqrt(a*a +... | 2018/03/09 | [
"https://Stackoverflow.com/questions/49191477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/468334/"
] | The first thing to do is factorize:
```
b = sqrt(h*h - a*a) = sqrt((h-a)*(h+a))
```
We have not only avoided some overflow, but also gained accuracy.
If any factor is close to `1E+154 = sqrt(1E+308)` (max with IEEE 754 64 bits float) then we must also avoid overflow:
```
sqrt((h-a)*(h+a)) = sqrt(h-a) * sqrt(h+a)
... | `hypot` has its idiosyncrasies in that it's one of a *very select few* C standard library functions that does **not** propagate `NaN`! (Another one is `pow` for the case where the first argument being 1.)
Setting that aside, I'd be inclined to write merely
```
returns sqrt(h * h - a * a); // h is the hypotenuse
```
... |
49,191,477 | The `hypot` function, introduced into C in the 1999 revision of the language, calculates the hypotenuse of a right triangle given the other sides as arguments, but with care taken to avoid the over/underflow which would result from the naive implementation as
```
double hypot(double a, double b)
{
return sqrt(a*a +... | 2018/03/09 | [
"https://Stackoverflow.com/questions/49191477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/468334/"
] | This answer assumes a platform that uses floating-point arithmetic compliant with IEEE-754 (2008) and provides fused multiply-add (FMA) capability. Both conditions are met by common architectures such as x86-64, ARM64, and Power. FMA is exposed in ISO C99 and later C standards as a standard math function `fma()`. On ha... | `hypot` has its idiosyncrasies in that it's one of a *very select few* C standard library functions that does **not** propagate `NaN`! (Another one is `pow` for the case where the first argument being 1.)
Setting that aside, I'd be inclined to write merely
```
returns sqrt(h * h - a * a); // h is the hypotenuse
```
... |
49,191,477 | The `hypot` function, introduced into C in the 1999 revision of the language, calculates the hypotenuse of a right triangle given the other sides as arguments, but with care taken to avoid the over/underflow which would result from the naive implementation as
```
double hypot(double a, double b)
{
return sqrt(a*a +... | 2018/03/09 | [
"https://Stackoverflow.com/questions/49191477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/468334/"
] | The first thing to do is factorize:
```
b = sqrt(h*h - a*a) = sqrt((h-a)*(h+a))
```
We have not only avoided some overflow, but also gained accuracy.
If any factor is close to `1E+154 = sqrt(1E+308)` (max with IEEE 754 64 bits float) then we must also avoid overflow:
```
sqrt((h-a)*(h+a)) = sqrt(h-a) * sqrt(h+a)
... | Assuming IEEE 754 basic 64-bit binary floating-point, I would consider an algorithm such as:
* Set *s* (for scale) to be 2−512 if 2100 ≤ *a*, 2+512 if *a* < 2−100, and 1 otherwise.
* Let *a*' be *a*•*s* and *b*' be *b*•*s*.
* Compute sqrt(*a*'•*a*' − *b*'•*b*') / *s*.
Notes about the reasoning:
* If *a* is large (or... |
49,191,477 | The `hypot` function, introduced into C in the 1999 revision of the language, calculates the hypotenuse of a right triangle given the other sides as arguments, but with care taken to avoid the over/underflow which would result from the naive implementation as
```
double hypot(double a, double b)
{
return sqrt(a*a +... | 2018/03/09 | [
"https://Stackoverflow.com/questions/49191477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/468334/"
] | This answer assumes a platform that uses floating-point arithmetic compliant with IEEE-754 (2008) and provides fused multiply-add (FMA) capability. Both conditions are met by common architectures such as x86-64, ARM64, and Power. FMA is exposed in ISO C99 and later C standards as a standard math function `fma()`. On ha... | Assuming IEEE 754 basic 64-bit binary floating-point, I would consider an algorithm such as:
* Set *s* (for scale) to be 2−512 if 2100 ≤ *a*, 2+512 if *a* < 2−100, and 1 otherwise.
* Let *a*' be *a*•*s* and *b*' be *b*•*s*.
* Compute sqrt(*a*'•*a*' − *b*'•*b*') / *s*.
Notes about the reasoning:
* If *a* is large (or... |
49,191,477 | The `hypot` function, introduced into C in the 1999 revision of the language, calculates the hypotenuse of a right triangle given the other sides as arguments, but with care taken to avoid the over/underflow which would result from the naive implementation as
```
double hypot(double a, double b)
{
return sqrt(a*a +... | 2018/03/09 | [
"https://Stackoverflow.com/questions/49191477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/468334/"
] | The first thing to do is factorize:
```
b = sqrt(h*h - a*a) = sqrt((h-a)*(h+a))
```
We have not only avoided some overflow, but also gained accuracy.
If any factor is close to `1E+154 = sqrt(1E+308)` (max with IEEE 754 64 bits float) then we must also avoid overflow:
```
sqrt((h-a)*(h+a)) = sqrt(h-a) * sqrt(h+a)
... | This answer assumes a platform that uses floating-point arithmetic compliant with IEEE-754 (2008) and provides fused multiply-add (FMA) capability. Both conditions are met by common architectures such as x86-64, ARM64, and Power. FMA is exposed in ISO C99 and later C standards as a standard math function `fma()`. On ha... |
393,637 | I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ... | 2008/12/26 | [
"https://Stackoverflow.com/questions/393637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] | Possible solution: <http://groups.google.com/group/django-users/browse_thread/thread/2c7421cdb9b99e48>
>
> Until recently I was curious to test
> this on Django 1.1.1. Will this
> exception be thrown again... surprise,
> there it was again. It took me some
> time to debug this, helpful hint was
> that it only s... | In the end I switched back to Apache + mod\_python (I was having other random errors with fcgi, besides this one) and everything is good and stable now.
The question still remains open. In case anybody has this problem in the future and solves it they can record the solution here for future reference. :) |
393,637 | I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ... | 2008/12/26 | [
"https://Stackoverflow.com/questions/393637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] | Change from method=prefork to method=threaded solved the problem for me. | Have you considered downgrading to Python 2.5.x (2.5.4 specifically)? I don't think Django would be considered mature on Python 2.6 since there are some backwards incompatible changes. However, I doubt this will fix your problem.
Also, Django 1.0.2 fixed some nefarious little bugs so make sure you're running that. Thi... |
393,637 | I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ... | 2008/12/26 | [
"https://Stackoverflow.com/questions/393637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] | Smells like a possible threading problem. Django is *not* guaranteed thread-safe although the in-file docs seem to indicate that Django/FCGI can be run that way. Try running with prefork and then beat the crap out of the server. If the problem goes away ... | Have you considered downgrading to Python 2.5.x (2.5.4 specifically)? I don't think Django would be considered mature on Python 2.6 since there are some backwards incompatible changes. However, I doubt this will fix your problem.
Also, Django 1.0.2 fixed some nefarious little bugs so make sure you're running that. Thi... |
393,637 | I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ... | 2008/12/26 | [
"https://Stackoverflow.com/questions/393637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] | In the end I switched back to Apache + mod\_python (I was having other random errors with fcgi, besides this one) and everything is good and stable now.
The question still remains open. In case anybody has this problem in the future and solves it they can record the solution here for future reference. :) | Smells like a possible threading problem. Django is *not* guaranteed thread-safe although the in-file docs seem to indicate that Django/FCGI can be run that way. Try running with prefork and then beat the crap out of the server. If the problem goes away ... |
393,637 | I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ... | 2008/12/26 | [
"https://Stackoverflow.com/questions/393637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] | Possible solution: <http://groups.google.com/group/django-users/browse_thread/thread/2c7421cdb9b99e48>
>
> Until recently I was curious to test
> this on Django 1.1.1. Will this
> exception be thrown again... surprise,
> there it was again. It took me some
> time to debug this, helpful hint was
> that it only s... | Maybe the PYTHONPATH and PATH environment variable is different for both setups (Apache+mod\_python and lighttpd + FastCGI). |
393,637 | I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ... | 2008/12/26 | [
"https://Stackoverflow.com/questions/393637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] | In the end I switched back to Apache + mod\_python (I was having other random errors with fcgi, besides this one) and everything is good and stable now.
The question still remains open. In case anybody has this problem in the future and solves it they can record the solution here for future reference. :) | The problem could be mainly with Imports. Atleast thats what happened to me.
I wrote my own solution after finding nothing from the web. Please check my blogpost here: [Simple Python Utility to check all Imports in your project](http://nandakishore.posterous.com/simple-djangopython-utility-to-check-all-the)
Ofcourse t... |
393,637 | I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ... | 2008/12/26 | [
"https://Stackoverflow.com/questions/393637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] | In the end I switched back to Apache + mod\_python (I was having other random errors with fcgi, besides this one) and everything is good and stable now.
The question still remains open. In case anybody has this problem in the future and solves it they can record the solution here for future reference. :) | An applicable quote:
`"2019 anyone?"
- half of YouTube comments, circa 2019`
If anyone is still dealing with this, make sure your app is "eagerly forking" such that your Python DB driver (`psycopg2` for me) isn't sharing resources between processes.
I solved this issue on uWSGI by adding the `lazy-apps = true` opti... |
393,637 | I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ... | 2008/12/26 | [
"https://Stackoverflow.com/questions/393637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] | In the end I switched back to Apache + mod\_python (I was having other random errors with fcgi, besides this one) and everything is good and stable now.
The question still remains open. In case anybody has this problem in the future and solves it they can record the solution here for future reference. :) | Change from method=prefork to method=threaded solved the problem for me. |
393,637 | I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ... | 2008/12/26 | [
"https://Stackoverflow.com/questions/393637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] | An applicable quote:
`"2019 anyone?"
- half of YouTube comments, circa 2019`
If anyone is still dealing with this, make sure your app is "eagerly forking" such that your Python DB driver (`psycopg2` for me) isn't sharing resources between processes.
I solved this issue on uWSGI by adding the `lazy-apps = true` opti... | Have you considered downgrading to Python 2.5.x (2.5.4 specifically)? I don't think Django would be considered mature on Python 2.6 since there are some backwards incompatible changes. However, I doubt this will fix your problem.
Also, Django 1.0.2 fixed some nefarious little bugs so make sure you're running that. Thi... |
393,637 | I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ... | 2008/12/26 | [
"https://Stackoverflow.com/questions/393637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5475/"
] | In the end I switched back to Apache + mod\_python (I was having other random errors with fcgi, besides this one) and everything is good and stable now.
The question still remains open. In case anybody has this problem in the future and solves it they can record the solution here for future reference. :) | Maybe the PYTHONPATH and PATH environment variable is different for both setups (Apache+mod\_python and lighttpd + FastCGI). |
43,893,431 | I am new to python(version 3.4.) and I am wondering how I can make a code similar to this one:
```
#block letters
B1 = ("BBBB ")
B2 = ("B B ")
B3 = ("B B ")
B4 = ("BBBB ")
B5 = ("B B ")
B6 = ("B B ")
B7 = ("BBBB ")
B = [B1, B2, B3, B4, B5, B6, B7]
E1 = ("EEEEE ")
E2 = ("E ")
E3 = ("E ")
E4 = ("EEE... | 2017/05/10 | [
"https://Stackoverflow.com/questions/43893431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7991835/"
] | >
> **Assumption**: you have **all** the letters constructed and that **all letters have the same number of rows**.
>
>
>
In that case you can **construct a dictionary**, like:
```
ascii_art = { 'B': B, 'E': E, 'N': N }
```
of course in real life, you construct a dictionary with all letters, and perhaps spaces,... | First you'd have to manually make the alphabet as you did before,
```
N1 = ("N N")
N2 = ("NN N")
N3 = ("N N N")
N4 = ("N N N")
N5 = ("N N N")
N6 = ("N NN")
N7 = ("N N")
N = [N1, N2, N3, N4, N5, N6, N7]
```
Do that for each letter. [a-z]
```
# Now to let user input print your alphabet we will use a dict... |
43,893,431 | I am new to python(version 3.4.) and I am wondering how I can make a code similar to this one:
```
#block letters
B1 = ("BBBB ")
B2 = ("B B ")
B3 = ("B B ")
B4 = ("BBBB ")
B5 = ("B B ")
B6 = ("B B ")
B7 = ("BBBB ")
B = [B1, B2, B3, B4, B5, B6, B7]
E1 = ("EEEEE ")
E2 = ("E ")
E3 = ("E ")
E4 = ("EEE... | 2017/05/10 | [
"https://Stackoverflow.com/questions/43893431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7991835/"
] | >
> **Assumption**: you have **all** the letters constructed and that **all letters have the same number of rows**.
>
>
>
In that case you can **construct a dictionary**, like:
```
ascii_art = { 'B': B, 'E': E, 'N': N }
```
of course in real life, you construct a dictionary with all letters, and perhaps spaces,... | Without getting super sophisticated, you need to hardcore (i.e. statically define) each letter as a list of strings, similar to how you did it with B, E and N.
Then you build a dictionary that maps each letter to the corresponding list:
```
>>> letters = {
... 'b': ["BBBB ", "B B ", "B B ", "BBBB ", "B B ... |
43,893,431 | I am new to python(version 3.4.) and I am wondering how I can make a code similar to this one:
```
#block letters
B1 = ("BBBB ")
B2 = ("B B ")
B3 = ("B B ")
B4 = ("BBBB ")
B5 = ("B B ")
B6 = ("B B ")
B7 = ("BBBB ")
B = [B1, B2, B3, B4, B5, B6, B7]
E1 = ("EEEEE ")
E2 = ("E ")
E3 = ("E ")
E4 = ("EEE... | 2017/05/10 | [
"https://Stackoverflow.com/questions/43893431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7991835/"
] | >
> **Assumption**: you have **all** the letters constructed and that **all letters have the same number of rows**.
>
>
>
In that case you can **construct a dictionary**, like:
```
ascii_art = { 'B': B, 'E': E, 'N': N }
```
of course in real life, you construct a dictionary with all letters, and perhaps spaces,... | I have found a less complicated(for me) answer. I don't understand how to use zip or map, but this way work with out them.And I can understand what the code is doing.
```
A =[" A ", #CREATING LIST OF LETTERS
" A A ",
" A A ",
"AAAAAAA ",
"A A ",
"A A ",
"A A "]
```
crea... |
43,893,431 | I am new to python(version 3.4.) and I am wondering how I can make a code similar to this one:
```
#block letters
B1 = ("BBBB ")
B2 = ("B B ")
B3 = ("B B ")
B4 = ("BBBB ")
B5 = ("B B ")
B6 = ("B B ")
B7 = ("BBBB ")
B = [B1, B2, B3, B4, B5, B6, B7]
E1 = ("EEEEE ")
E2 = ("E ")
E3 = ("E ")
E4 = ("EEE... | 2017/05/10 | [
"https://Stackoverflow.com/questions/43893431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7991835/"
] | First you'd have to manually make the alphabet as you did before,
```
N1 = ("N N")
N2 = ("NN N")
N3 = ("N N N")
N4 = ("N N N")
N5 = ("N N N")
N6 = ("N NN")
N7 = ("N N")
N = [N1, N2, N3, N4, N5, N6, N7]
```
Do that for each letter. [a-z]
```
# Now to let user input print your alphabet we will use a dict... | I have found a less complicated(for me) answer. I don't understand how to use zip or map, but this way work with out them.And I can understand what the code is doing.
```
A =[" A ", #CREATING LIST OF LETTERS
" A A ",
" A A ",
"AAAAAAA ",
"A A ",
"A A ",
"A A "]
```
crea... |
43,893,431 | I am new to python(version 3.4.) and I am wondering how I can make a code similar to this one:
```
#block letters
B1 = ("BBBB ")
B2 = ("B B ")
B3 = ("B B ")
B4 = ("BBBB ")
B5 = ("B B ")
B6 = ("B B ")
B7 = ("BBBB ")
B = [B1, B2, B3, B4, B5, B6, B7]
E1 = ("EEEEE ")
E2 = ("E ")
E3 = ("E ")
E4 = ("EEE... | 2017/05/10 | [
"https://Stackoverflow.com/questions/43893431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7991835/"
] | Without getting super sophisticated, you need to hardcore (i.e. statically define) each letter as a list of strings, similar to how you did it with B, E and N.
Then you build a dictionary that maps each letter to the corresponding list:
```
>>> letters = {
... 'b': ["BBBB ", "B B ", "B B ", "BBBB ", "B B ... | I have found a less complicated(for me) answer. I don't understand how to use zip or map, but this way work with out them.And I can understand what the code is doing.
```
A =[" A ", #CREATING LIST OF LETTERS
" A A ",
" A A ",
"AAAAAAA ",
"A A ",
"A A ",
"A A "]
```
crea... |
1,839,567 | I have a vector consisting of a point, speed and direction. We will call this vector R. And another vector that only consists of a point and a speed. No direction. We will call this one T.
Now, what I am trying to do is to find the shortest intersection point of these two vectors. Since T has no direction, this is prov... | 2009/12/03 | [
"https://Stackoverflow.com/questions/1839567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223779/"
] | My math could be a bit rusty, but try this:
*p* and *q* are the position vectors, *d* and *e* are the direction vectors. After time *t*, you want them to be at the same place:
**(1)** *p+t\*d = q+t\*e*
Since you want the direction vector *e*, write it like this
**(2)** *e = (p-q)/t + d*
Now you don't need the tim... | 1. Let's assume that the first point,
A, has zero speed. In this case, it
should be very simple to find the
direction which will give the
fastest intersection.
2. Now, A **does** have a speed. We can force it to have zero speed by deducting it's speed vector from the vector of B. Now we can solve as we did in 1.
Just ... |
1,839,567 | I have a vector consisting of a point, speed and direction. We will call this vector R. And another vector that only consists of a point and a speed. No direction. We will call this one T.
Now, what I am trying to do is to find the shortest intersection point of these two vectors. Since T has no direction, this is prov... | 2009/12/03 | [
"https://Stackoverflow.com/questions/1839567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223779/"
] | My math could be a bit rusty, but try this:
*p* and *q* are the position vectors, *d* and *e* are the direction vectors. After time *t*, you want them to be at the same place:
**(1)** *p+t\*d = q+t\*e*
Since you want the direction vector *e*, write it like this
**(2)** *e = (p-q)/t + d*
Now you don't need the tim... | OK, if I understand you right, you have
R = [ xy0, v, r ]
T = [ xy1, v ]
If you are concerned about the shortest intersection point, this will be achieved when your positions are identical, and in an Euclidean space this also forces the direction of the second "thing" being perpendicular to the first. You can write ... |
1,839,567 | I have a vector consisting of a point, speed and direction. We will call this vector R. And another vector that only consists of a point and a speed. No direction. We will call this one T.
Now, what I am trying to do is to find the shortest intersection point of these two vectors. Since T has no direction, this is prov... | 2009/12/03 | [
"https://Stackoverflow.com/questions/1839567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223779/"
] | My math could be a bit rusty, but try this:
*p* and *q* are the position vectors, *d* and *e* are the direction vectors. After time *t*, you want them to be at the same place:
**(1)** *p+t\*d = q+t\*e*
Since you want the direction vector *e*, write it like this
**(2)** *e = (p-q)/t + d*
Now you don't need the tim... | In nature hunters use the constant bearing decreasing range algorithm to catch prey.
I like the explanation of how bats do this [link text](http://www.plosbiology.org/article/info:doi%2F10.1371%2Fjournal.pbio.0040108 "Echolocating Bats Use a Nearly Time-Optimal Strategy to Intercept Prey")
We need to define a few more... |
1,839,567 | I have a vector consisting of a point, speed and direction. We will call this vector R. And another vector that only consists of a point and a speed. No direction. We will call this one T.
Now, what I am trying to do is to find the shortest intersection point of these two vectors. Since T has no direction, this is prov... | 2009/12/03 | [
"https://Stackoverflow.com/questions/1839567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223779/"
] | 1. Let's assume that the first point,
A, has zero speed. In this case, it
should be very simple to find the
direction which will give the
fastest intersection.
2. Now, A **does** have a speed. We can force it to have zero speed by deducting it's speed vector from the vector of B. Now we can solve as we did in 1.
Just ... | OK, if I understand you right, you have
R = [ xy0, v, r ]
T = [ xy1, v ]
If you are concerned about the shortest intersection point, this will be achieved when your positions are identical, and in an Euclidean space this also forces the direction of the second "thing" being perpendicular to the first. You can write ... |
1,839,567 | I have a vector consisting of a point, speed and direction. We will call this vector R. And another vector that only consists of a point and a speed. No direction. We will call this one T.
Now, what I am trying to do is to find the shortest intersection point of these two vectors. Since T has no direction, this is prov... | 2009/12/03 | [
"https://Stackoverflow.com/questions/1839567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223779/"
] | In nature hunters use the constant bearing decreasing range algorithm to catch prey.
I like the explanation of how bats do this [link text](http://www.plosbiology.org/article/info:doi%2F10.1371%2Fjournal.pbio.0040108 "Echolocating Bats Use a Nearly Time-Optimal Strategy to Intercept Prey")
We need to define a few more... | OK, if I understand you right, you have
R = [ xy0, v, r ]
T = [ xy1, v ]
If you are concerned about the shortest intersection point, this will be achieved when your positions are identical, and in an Euclidean space this also forces the direction of the second "thing" being perpendicular to the first. You can write ... |
34,278,955 | On the linux system I'm using, the scheduler is not very generous giving cpu time to subprocesses spawned from python's multiprocessing module. When using 4 subprocceses on a 4-core machine, I get around 22% CPU according to `ps`. However, if the subprocesses are child processes of the shell, and not the python program... | 2015/12/15 | [
"https://Stackoverflow.com/questions/34278955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483516/"
] | I don't believe your benchmarks are executing as independent tasks as you might think they do. You didn't show the code of `function` but I suspect it does some synchronization.
I wrote the following benchmark. If I run the script with either the `--fork` or the `--mp` option, I always get 400 % CPU utilization (on my... | Welcome to the CPython Global Interpreter Lock. Your threads show up as distinct processes to the linux kernel (that is how threads are implemented in Linux in general: each thread gets its own process so the kernel can schedule them).
So why isn't Linux scheduling more than one of them to run at a time (that is why ... |
49,037,104 | So, I am making a login system in python with tkinter and I want it to move to another page after the email and password have been validated. The only way I have found to do this is by using a button click command. I only want it to move on to the next page after the email and password have been validated. Thanks in ad... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7698965/"
] | You can split the string and then `Array.includes` to check whether the value exists in the array or not.
```js
function check(str, val){
return str.split(", ").includes(val+"");
}
var str = "1, 13, 112, 12, 1212, 555"
console.log(check(str, 12));
console.log(check(str, 121));
console.log(check(str, 1212));
... | Another possible answer :
```js
var twelve = /(^| )12(,|$)/;
var s = "1, 13, 112, 12, 1212, 555";
console.log(twelve.test(s)); // true
```
About the regular expression
----------------------------
Following your comment, let me give you a little help to understand the first line.
`/(^| )12(,|$)/` is a regular ex... |
49,037,104 | So, I am making a login system in python with tkinter and I want it to move to another page after the email and password have been validated. The only way I have found to do this is by using a button click command. I only want it to move on to the next page after the email and password have been validated. Thanks in ad... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7698965/"
] | You can split the string and then `Array.includes` to check whether the value exists in the array or not.
```js
function check(str, val){
return str.split(", ").includes(val+"");
}
var str = "1, 13, 112, 12, 1212, 555"
console.log(check(str, 12));
console.log(check(str, 121));
console.log(check(str, 1212));
... | I think .includes() isn't supported on google sheets. But this seems to work:
```
/**
@customfunction
*/
function AK_CHECK(input){
var split_cell = input.split(",").indexOf("12");
if (split_cell > -1){
return "Bicycle"
} else {
return "NO"}
}
``` |
49,037,104 | So, I am making a login system in python with tkinter and I want it to move to another page after the email and password have been validated. The only way I have found to do this is by using a button click command. I only want it to move on to the next page after the email and password have been validated. Thanks in ad... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49037104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7698965/"
] | Another possible answer :
```js
var twelve = /(^| )12(,|$)/;
var s = "1, 13, 112, 12, 1212, 555";
console.log(twelve.test(s)); // true
```
About the regular expression
----------------------------
Following your comment, let me give you a little help to understand the first line.
`/(^| )12(,|$)/` is a regular ex... | I think .includes() isn't supported on google sheets. But this seems to work:
```
/**
@customfunction
*/
function AK_CHECK(input){
var split_cell = input.split(",").indexOf("12");
if (split_cell > -1){
return "Bicycle"
} else {
return "NO"}
}
``` |
7,598,159 | I am trying to access the Amazon Advertising through Python and I created a Python script to automate the authentication process. This file, called amazon.py is located in ~/PROJECT/APP/amazon.py.
I want to be able to play around with the API, so I launched python manage.py shell from the ~/PROJECT directory to enter ... | 2011/09/29 | [
"https://Stackoverflow.com/questions/7598159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971235/"
] | ```
int* ptr = (int*)&a;
```
This is dangerous (this itself doesn't invoke UB, though). But this,
```
*ptr = 3;
```
This invokes undefined behavior (UB), because you're attempting to modify the `const` object pointing to by `ptr`. UB means anything could happen. Note that `a` is truly a const object.
§7.1.5.1/4 (... | Don't do things like this. It's undefined behavior.
If you lie to the compiler, it will get its revenge (c) |
7,598,159 | I am trying to access the Amazon Advertising through Python and I created a Python script to automate the authentication process. This file, called amazon.py is located in ~/PROJECT/APP/amazon.py.
I want to be able to play around with the API, so I launched python manage.py shell from the ~/PROJECT directory to enter ... | 2011/09/29 | [
"https://Stackoverflow.com/questions/7598159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971235/"
] | ```
int* ptr = (int*)&a;
```
This is dangerous (this itself doesn't invoke UB, though). But this,
```
*ptr = 3;
```
This invokes undefined behavior (UB), because you're attempting to modify the `const` object pointing to by `ptr`. UB means anything could happen. Note that `a` is truly a const object.
§7.1.5.1/4 (... | I have a hypothesis that I have not tested:
Compiler set aside an address for a (0xbf88d51c), and fills it with 2. int \*ptr gets set to that address, and \*ptr = 3 put 3 at that address. So \*ptr now points to a 3. But when it comes across the value a, compiler hard codes the "2", as though you'd said `#define a 2`.
... |
7,598,159 | I am trying to access the Amazon Advertising through Python and I created a Python script to automate the authentication process. This file, called amazon.py is located in ~/PROJECT/APP/amazon.py.
I want to be able to play around with the API, so I launched python manage.py shell from the ~/PROJECT directory to enter ... | 2011/09/29 | [
"https://Stackoverflow.com/questions/7598159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971235/"
] | ```
int* ptr = (int*)&a;
```
This is dangerous (this itself doesn't invoke UB, though). But this,
```
*ptr = 3;
```
This invokes undefined behavior (UB), because you're attempting to modify the `const` object pointing to by `ptr`. UB means anything could happen. Note that `a` is truly a const object.
§7.1.5.1/4 (... | That's because compiler replaces `... " " << a << " " ...` with `... " " << 2 << " " ...`.
It does so to avoid reading `a`'s value from memory when it's already know, constant and can be added right to assembler instruction. |
7,598,159 | I am trying to access the Amazon Advertising through Python and I created a Python script to automate the authentication process. This file, called amazon.py is located in ~/PROJECT/APP/amazon.py.
I want to be able to play around with the API, so I launched python manage.py shell from the ~/PROJECT directory to enter ... | 2011/09/29 | [
"https://Stackoverflow.com/questions/7598159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971235/"
] | Don't do things like this. It's undefined behavior.
If you lie to the compiler, it will get its revenge (c) | I have a hypothesis that I have not tested:
Compiler set aside an address for a (0xbf88d51c), and fills it with 2. int \*ptr gets set to that address, and \*ptr = 3 put 3 at that address. So \*ptr now points to a 3. But when it comes across the value a, compiler hard codes the "2", as though you'd said `#define a 2`.
... |
7,598,159 | I am trying to access the Amazon Advertising through Python and I created a Python script to automate the authentication process. This file, called amazon.py is located in ~/PROJECT/APP/amazon.py.
I want to be able to play around with the API, so I launched python manage.py shell from the ~/PROJECT directory to enter ... | 2011/09/29 | [
"https://Stackoverflow.com/questions/7598159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971235/"
] | Don't do things like this. It's undefined behavior.
If you lie to the compiler, it will get its revenge (c) | That's because compiler replaces `... " " << a << " " ...` with `... " " << 2 << " " ...`.
It does so to avoid reading `a`'s value from memory when it's already know, constant and can be added right to assembler instruction. |
12,961,475 | I am looking for a way to parse the following commandline syntax using the argparse module in python3:
```
myapp.py [folder] [[from] to]
```
Meaning: The user may optionally define a folder, which defaults to cwd. Additionally the user may pass up to two integers. If only one number is given, it should be stored in ... | 2012/10/18 | [
"https://Stackoverflow.com/questions/12961475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1110748/"
] | Use options; that's what they're there for (and what `argparse` is good at parsing).
Thus, a syntax like
```
myapp.py [-F folder] [[from] to]
```
would make a lot more sense, and be easier to parse. | I couldn't see a way to do it without using a named argument for folder:
```
# usage: argparsetest2.py [-h] [--folder [FOLDER]] [to] [fr]
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument('--folder', dest='folder', nargs='?', default=os.getcwd())
parser.add_argument('to', type=int, nar... |
12,961,475 | I am looking for a way to parse the following commandline syntax using the argparse module in python3:
```
myapp.py [folder] [[from] to]
```
Meaning: The user may optionally define a folder, which defaults to cwd. Additionally the user may pass up to two integers. If only one number is given, it should be stored in ... | 2012/10/18 | [
"https://Stackoverflow.com/questions/12961475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1110748/"
] | You can do something quite silly:
```
import argparse
import os
class MyAction(argparse.Action):
def __call__(self,parser,namespace,values,option_string=None):
namespace.numbers = []
namespace.path = os.getcwd()
for v in values:
if os.path.isdir(v):
namespace.pa... | I couldn't see a way to do it without using a named argument for folder:
```
# usage: argparsetest2.py [-h] [--folder [FOLDER]] [to] [fr]
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument('--folder', dest='folder', nargs='?', default=os.getcwd())
parser.add_argument('to', type=int, nar... |
12,961,475 | I am looking for a way to parse the following commandline syntax using the argparse module in python3:
```
myapp.py [folder] [[from] to]
```
Meaning: The user may optionally define a folder, which defaults to cwd. Additionally the user may pass up to two integers. If only one number is given, it should be stored in ... | 2012/10/18 | [
"https://Stackoverflow.com/questions/12961475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1110748/"
] | I'd also suggest parsing sys.argv yourself.
FWIW, I parse sys.argv even on projects where argparse or similar would work, because parsing sys.argv yourself plays nicely with pylint or flake8. | I couldn't see a way to do it without using a named argument for folder:
```
# usage: argparsetest2.py [-h] [--folder [FOLDER]] [to] [fr]
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument('--folder', dest='folder', nargs='?', default=os.getcwd())
parser.add_argument('to', type=int, nar... |
46,341,816 | I'm working on a Python project using PyCharm and now I need to generate the corresponding API documentation. I'm documenting the code methods and classes using `docstrings`. I read about Sphinx and Doxygen, with Sphinx being the most recommended right now. I tried to configure Sphinx whitin PyCharm but I had no luck i... | 2017/09/21 | [
"https://Stackoverflow.com/questions/46341816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8078050/"
] | Just solved excatly the same problem Juan. **Sphinx unfortunately is not a fully automated doc generator from code comments** like doxygen, jautodoc etc.
As in the link mentioned in mzjn's [comment](https://stackoverflow.com/a/25555982/1980180) some steps are necessary for a proper work.
As I see you are working on P... | Prior to `make html` you should do the reading the apidoc comments from your code and creating .rst files.
You should run something like this from your project root folder:
```
sphinx-apidoc . -o ./docs -f tests
```
This will rewrite .rst files (hence `-f`) in `docs` folder and ignore to do the apidoc reading in `te... |
13,788,349 | Reading Guido's infamous answer to the question [Sorting a million 32-bit integers in 2MB of RAM using Python](http://neopythonic.blogspot.fr/2008/10/sorting-million-32-bit-integers-in-2mb.html), I discovered the module [heapq](http://docs.python.org/2.7/library/heapq.html).
I also discover I didn't understand jack ab... | 2012/12/09 | [
"https://Stackoverflow.com/questions/13788349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] | `heapq` implements [binary heaps](https://en.wikipedia.org/wiki/Binary_heap), which are a partially sorted data structure. In particular, they have three interesting operations:
* `heapify` turns a list into a heap, in-place, in O(*n*) time;
* `heappush` adds an element to the heap in O(lg *n*) time;
* `heappop` retri... | For example: you have a set of 1000 floating-point number. You want to repeatedly remove the smallest item from the set and replace it with a random number between 0 and 1. The fastest way to do it is with the heapq module:
```
heap = [0.0] * 1000
# heapify(heap) # usually you need this, but not if the list is initi... |
51,347,732 | I am trying to replace a block of text which is spanning over multiple lines of text file using python. Here is how my input file looks like.
input.txt:
```
ABCD abcd (
. X (x),
.Y (y)
);
ABCD1 abcd1 (
. X1 (x1),
.Y1 (y1)
);
```
I am reading the above file with the below code and trying to replace the tex... | 2018/07/15 | [
"https://Stackoverflow.com/questions/51347732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843912/"
] | Running `oc whoami --show-console` returns the link to the console app. | Thanks, `oc login` helped me to get the web console url |
51,347,732 | I am trying to replace a block of text which is spanning over multiple lines of text file using python. Here is how my input file looks like.
input.txt:
```
ABCD abcd (
. X (x),
.Y (y)
);
ABCD1 abcd1 (
. X1 (x1),
.Y1 (y1)
);
```
I am reading the above file with the below code and trying to replace the tex... | 2018/07/15 | [
"https://Stackoverflow.com/questions/51347732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843912/"
] | You can obtain the console URL in OpenShift Container Platform 4 as follows:
```
$ oc get routes -n openshift-console
``` | Thanks, `oc login` helped me to get the web console url |
51,347,732 | I am trying to replace a block of text which is spanning over multiple lines of text file using python. Here is how my input file looks like.
input.txt:
```
ABCD abcd (
. X (x),
.Y (y)
);
ABCD1 abcd1 (
. X1 (x1),
.Y1 (y1)
);
```
I am reading the above file with the below code and trying to replace the tex... | 2018/07/15 | [
"https://Stackoverflow.com/questions/51347732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3843912/"
] | Running `oc whoami --show-console` returns the link to the console app. | You can obtain the console URL in OpenShift Container Platform 4 as follows:
```
$ oc get routes -n openshift-console
``` |
34,394,650 | I have a python's pexpect code where it sends some commands listed in a file.
Say I store some commands in a file named `commandbase`
```
ls -l /dev/
ls -l /home/ramana
ls -l /home/ramana/xyz
ls -l /home/ramana/xxx
ls -l /home/ramana/xyz/abc
ls -l /home/ramana/xxx/def
ls -l /home/dir/
```
and so on.
Observe here t... | 2015/12/21 | [
"https://Stackoverflow.com/questions/34394650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4894197/"
] | This can be done with a list comprehension...
```
paths = ['/dev/', '/dev/ramana/', ...]
command = 'ls -l'
commandsandpaths = [command + ' ' + x for x in paths]
```
`commandsandpaths` will be a list with...
```
ls -l /dev/
ls -l /dev/ramana/
```
Personally, I prefer to use string formatting rather than string con... | Your requirements are a little more complicated than it appears at first glance. Below I have adopted a convention to use lists `[...]` to indicate things to concatenate, and tuples `(...)` for things to choose from, i.e. optionals.
Your list of path names can now be expressed as this:-
```
database = (
'dev',
... |
34,394,650 | I have a python's pexpect code where it sends some commands listed in a file.
Say I store some commands in a file named `commandbase`
```
ls -l /dev/
ls -l /home/ramana
ls -l /home/ramana/xyz
ls -l /home/ramana/xxx
ls -l /home/ramana/xyz/abc
ls -l /home/ramana/xxx/def
ls -l /home/dir/
```
and so on.
Observe here t... | 2015/12/21 | [
"https://Stackoverflow.com/questions/34394650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4894197/"
] | This can be done with a list comprehension...
```
paths = ['/dev/', '/dev/ramana/', ...]
command = 'ls -l'
commandsandpaths = [command + ' ' + x for x in paths]
```
`commandsandpaths` will be a list with...
```
ls -l /dev/
ls -l /dev/ramana/
```
Personally, I prefer to use string formatting rather than string con... | Not sure what these variables of which you speak are. They look like path segments to me.
Assuming you have a tree data structure consisting of nodes where each node is a tuple of a path segment, and a list of subtrees:
```
tree = [
('dev', []),
('home', [
('ramana', [
('xyz', [
... |
35,205,173 | I am trying to learn numpy array slicing.
But this is a syntax i cannot seem to understand.
What does
`a[:1]` do.
I ran it in python.
```
a = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
a = a.reshape(2,2,2,2)
a[:1]
```
**Output:**
```
array([[[ 5, 6],
[ 7, 8]],
[[13, 14],
[15,... | 2016/02/04 | [
"https://Stackoverflow.com/questions/35205173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1939166/"
] | The commas in slicing are to separate the various dimensions you may have. In your first example you are reshaping the data to have 4 dimensions each of length 2. This may be a little difficult to visualize so if you start with a 2D structure it might make more sense:
```
>>> a = np.arange(16).reshape((4, 4))
>>> a
... | It might pay to explore the `shape` and individual entries as we go along.
Let's start with
```
>>> a = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
>>> a.shape
(16, )
```
This is a one-dimensional array of length 16.
Now let's try
```
>>> a = a.reshape(2,2,2,2)
>>> a.shape
(2, 2, 2, 2)
```
It's a multi-d... |
35,205,173 | I am trying to learn numpy array slicing.
But this is a syntax i cannot seem to understand.
What does
`a[:1]` do.
I ran it in python.
```
a = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
a = a.reshape(2,2,2,2)
a[:1]
```
**Output:**
```
array([[[ 5, 6],
[ 7, 8]],
[[13, 14],
[15,... | 2016/02/04 | [
"https://Stackoverflow.com/questions/35205173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1939166/"
] | The commas in slicing are to separate the various dimensions you may have. In your first example you are reshaping the data to have 4 dimensions each of length 2. This may be a little difficult to visualize so if you start with a 2D structure it might make more sense:
```
>>> a = np.arange(16).reshape((4, 4))
>>> a
... | To answer the second part of your question (generating arrays of sequential values) you can use [`np.arange(start, stop, step)`](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.arange.html) or [`np.linspace(start, stop, num_elements)`](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.li... |
62,719,356 | Hi i'm codding a bot in python
to the zoom download api, but
but now i'm going through this. I need to know the name of the file I am downloading through that URL, but inside the URL it does not contain the name of the file. It is just downloaded automatically through it.
Ex of an download URL:
<https://zztop.us/rec/... | 2020/07/03 | [
"https://Stackoverflow.com/questions/62719356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13860212/"
] | with the help of Mostafa Labib I managed to get where I wanted, here is the code working for those who want to know the filename of a file downloaded by download\_url of zoom
```
from urllib.request import urlopen
from os.path import basename
url="https://zztop.us/rec/download/6cUsfr5pjo3GNfGtgSDAv9xIXbzy9vms0iRKq6YNn... | You can use urllib to parse the link then get the filename from the headers.
```
from urllib.request import urlopen
url = "https://zztop.us/rec/download/6cUsf-r5pjo3GNfGtgSDAv9xIXbzy9vms0iRKq6YNn0m8UHILNlKiMrMWMecDkmKyv5o675Hp1ZrKPF16"
response = urlopen(url)
filename = response.headers.get_filename()
print(filename)... |
11,459,861 | I am a molecular biologist using Biopython to analyze mutations in genes and my problem is this:
I have a file containing many different sequences (millions), most of which are duplicates. I need to find the duplicates and discard them, keeping one copy of each unique sequence. I was planning on using the module editd... | 2012/07/12 | [
"https://Stackoverflow.com/questions/11459861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513202/"
] | If you want to filter out exact duplicates, you can use the `set` Python built-in type. As an example :
```
a = ["tccggatcc", "actcctgct", "tccggatcc"] # You have a list of sequences
s = set(a) # Put that into a set
```
`s` is then equal to `['tccggatcc', 'actcctgct']`, without duplicates. | Don't be afraid of files! ;-)
I'm posting an example by assuming the following:
1. its a text-file
2. one sequence per line
-
```
filename = 'sequence.txt'
with open(filename, 'r') as sqfile:
sequences = sqfile.readlines() # now we have a list of strings
#discarding the duplicates:
uniques = list(set(sequences)... |
11,459,861 | I am a molecular biologist using Biopython to analyze mutations in genes and my problem is this:
I have a file containing many different sequences (millions), most of which are duplicates. I need to find the duplicates and discard them, keeping one copy of each unique sequence. I was planning on using the module editd... | 2012/07/12 | [
"https://Stackoverflow.com/questions/11459861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513202/"
] | Assuming your file consists solely of sequences arranged one sequence per line, I would suggest the following:
```
seq_file = open(#your file)
sequences = [seq for seq in seq_file]
uniques = list(set(sequences))
```
Assuming you have the memory for it. How many millions?
ETA:
Was reading the comments above (but ... | If you want to filter out exact duplicates, you can use the `set` Python built-in type. As an example :
```
a = ["tccggatcc", "actcctgct", "tccggatcc"] # You have a list of sequences
s = set(a) # Put that into a set
```
`s` is then equal to `['tccggatcc', 'actcctgct']`, without duplicates. |
11,459,861 | I am a molecular biologist using Biopython to analyze mutations in genes and my problem is this:
I have a file containing many different sequences (millions), most of which are duplicates. I need to find the duplicates and discard them, keeping one copy of each unique sequence. I was planning on using the module editd... | 2012/07/12 | [
"https://Stackoverflow.com/questions/11459861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513202/"
] | If you want to filter out exact duplicates, you can use the `set` Python built-in type. As an example :
```
a = ["tccggatcc", "actcctgct", "tccggatcc"] # You have a list of sequences
s = set(a) # Put that into a set
```
`s` is then equal to `['tccggatcc', 'actcctgct']`, without duplicates. | Four things come to mind:
1. You can use a set(), as described by F.X. - assuming the unique
strings will all fit in memory
2. You can use one file per sequence, and feed the files to a program
like equivs3e:
<http://stromberg.dnsalias.org/~strombrg/equivalence-classes.html#python-3e>
3. You could perhaps use a gdbm a... |
11,459,861 | I am a molecular biologist using Biopython to analyze mutations in genes and my problem is this:
I have a file containing many different sequences (millions), most of which are duplicates. I need to find the duplicates and discard them, keeping one copy of each unique sequence. I was planning on using the module editd... | 2012/07/12 | [
"https://Stackoverflow.com/questions/11459861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513202/"
] | Assuming your file consists solely of sequences arranged one sequence per line, I would suggest the following:
```
seq_file = open(#your file)
sequences = [seq for seq in seq_file]
uniques = list(set(sequences))
```
Assuming you have the memory for it. How many millions?
ETA:
Was reading the comments above (but ... | Don't be afraid of files! ;-)
I'm posting an example by assuming the following:
1. its a text-file
2. one sequence per line
-
```
filename = 'sequence.txt'
with open(filename, 'r') as sqfile:
sequences = sqfile.readlines() # now we have a list of strings
#discarding the duplicates:
uniques = list(set(sequences)... |
11,459,861 | I am a molecular biologist using Biopython to analyze mutations in genes and my problem is this:
I have a file containing many different sequences (millions), most of which are duplicates. I need to find the duplicates and discard them, keeping one copy of each unique sequence. I was planning on using the module editd... | 2012/07/12 | [
"https://Stackoverflow.com/questions/11459861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1513202/"
] | Does it have to be Python?
If the sequences are simply text strings one per line then a shell script will be very efficient:
```
sort input-file-name | uniq > output-file-name
```
This will do the job on files up to 2GB on 32 bit Linux.
If you are on Windows then install the GNU utils <http://gnuwin32.sourceforge.... | Don't be afraid of files! ;-)
I'm posting an example by assuming the following:
1. its a text-file
2. one sequence per line
-
```
filename = 'sequence.txt'
with open(filename, 'r') as sqfile:
sequences = sqfile.readlines() # now we have a list of strings
#discarding the duplicates:
uniques = list(set(sequences)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.