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 |
|---|---|---|---|---|---|
14,749,379 | Because *programming* is one of my favorite hobbies I started a small project in python.
I'm trying to make a nutritional calculator for daily routine, see the code below:
```
# Name: nutri.py
# Author: pyn
my_dict = {'chicken':(40, 50, 10),
'pork':(50, 30, 20)
}
foods = raw_input("Enter your food... | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2050432/"
] | using jQuerys hover function, like this:
```
$('#gestaltung_cd').hover(function() {
$('#mainhexa1').toggle();
});
```
(if you don't want to hide the div on blur, then change toggle() to show()) | Here's an example of how to do the first one and you'd just do the same for the other two with the relevant IDs.
```
$("#gestaltung_cd").hover(
function () {
$("#mainhexa1").show();
},
function () {
$("#mainhexa1").hide();
}
);
``` |
14,749,379 | Because *programming* is one of my favorite hobbies I started a small project in python.
I'm trying to make a nutritional calculator for daily routine, see the code below:
```
# Name: nutri.py
# Author: pyn
my_dict = {'chicken':(40, 50, 10),
'pork':(50, 30, 20)
}
foods = raw_input("Enter your food... | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2050432/"
] | Using jQuery's [hover](http://api.jquery.com/hover/) function :
```
var divs = {
cd: 'mainhexa1',
illu: 'mainhexa2',
klassisch: 'mainhexa3'
};
$('[id^=gestaltung]').hover(function(){ // selects all elements whose id starts with gestaltung
$('#'+divs[this.id.slice('gestaltung_'.length)]).toggle(... | ```
$("#gestaltung_cd").hover(function({
$("#mainhexa1").css({ "visibility": "visible" });
}, function() {
//Your hover out function
});
``` |
14,749,379 | Because *programming* is one of my favorite hobbies I started a small project in python.
I'm trying to make a nutritional calculator for daily routine, see the code below:
```
# Name: nutri.py
# Author: pyn
my_dict = {'chicken':(40, 50, 10),
'pork':(50, 30, 20)
}
foods = raw_input("Enter your food... | 2013/02/07 | [
"https://Stackoverflow.com/questions/14749379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2050432/"
] | You could use the sibling selector. As long as div's share the same parent, you can still affect them with hover
[DEMO](http://jsfiddle.net/8LFWR/)
Vital Code:
```
#gestaltung_cd:hover ~ #mainhexa1,
#gestaltung_illu:hover ~ #mainhexa2,
#gestaltung_klassisch:hover ~ #mainhexa3 {
display: block;
}
``` | Just for the record ...
You can do the effect you want only with CSS and HTML ( without javascript ), but you have to place your elements to follow each other and use `+` selector in CSS. Something like :
HTML
```
<div id="gestaltung_cd"></div>
<div id="mainhexa1"></div>
<div id="gestaltung_illu"></div>
<div id="mai... |
7,556,499 | despite using the search function I've been unable to find an answer. I got two assumptions, but don't know in how far they may apply. Now the problem:
I'd like to plot a contour. For this I've got here the following python code:
```
import numpy as np
import matplotlib.pyplot as plt
xi=list_of_distance
yi=list_of_a... | 2011/09/26 | [
"https://Stackoverflow.com/questions/7556499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/329586/"
] | As @rocksportrocker implies, you need to take into account that `histogram2d` returns the edges in addition to the histogram. Another detail is that you probably want to explicitly pass in a range, otherwise one will be chosen for you based on the actual min and max values in your data. You then want to convert the edg... | Your traceback indicates that the error does not raise from the call to matplotlib, it is numpy which raises the ValueError. |
46,437,882 | So this is driving me crazy I have python3 and modwsgi and apache and a virtual host, that work great, as I have several other wsgi scripts that work fine on the server. I also have a django app that works great when I run the dev server.
I have checked that "ldd mod\_wsgi.so" is linked correctly against python3.5
W... | 2017/09/27 | [
"https://Stackoverflow.com/questions/46437882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4216567/"
] | You probably need to tell mod\_wsgi where your project code is. For embedded mode this is done with `WSGIPythonPath` directive. You should preferably though use daemon mode, in which case you would use `python-path` option to `WSGIDaemonProcess` directive. | ok I finally figured out how to fix the issue but not sure exactly why. First off when I was mixing my own wsgi scipts and django I had to specify the daemon process only for the script alias that was django
```
WSGIScriptAlias /certs /var/www/scripts/CavsCertSearch/CavsCertSearch/certstrip.wsgi
WSGIScriptAlias /t... |
12,957,921 | I am attempting to run a python program that can run a dictionary from a file with a list of words with each word given a score and standard deviation. My program looks like this:
```
theFile = open('word-happiness.csv' , 'r')
theFile.close()
def make_happiness_table(filename):
'''make_happiness_table: string ->... | 2012/10/18 | [
"https://Stackoverflow.com/questions/12957921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1712920/"
] | The template parameter to [`std::normal_distribution`](http://en.cppreference.com/w/cpp/numeric/random/normal_distribution) must be a floating-point type (`float`, `double`, or `long double`). Using anything else will result in undefined behavior.
Since normal distribution is a continuous distribution, it isn't really... | You can use `binomial_distribution` with default probability value of 0.5.
[link](http://www.cplusplus.com/reference/random/binomial_distribution/binomial_distribution/)
It will return integer values in range [0,t], with mean at t/2 ( in case t is even else (t+1)/2, (t-1)/2 have equal prob.). You can set the value of ... |
51,572,168 | when i want to see my django website in their server....i open cmd and go to manage.py directory:
```
C:\Users\computer house\Desktop\ahmed>
```
and then i type :
```
python manage.py runserver
```
but i see this error :
```
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execu... | 2018/07/28 | [
"https://Stackoverflow.com/questions/51572168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10102365/"
] | As far as i understood, You have started your project with the following command:
```
C:\Users\computer house\Desktop> python startproject ahmed
```
After that I assume you have similar file structure:
```
ahmed/
├── ahmed/ # make sure this directory exists
│ ├── __init__.py # make sure this file exists.
│ ├──... | check your current directory to have file names `__init__.py` also a directory named `ahmed` contains `__init__.py` |
10,363,853 | I'm trying to talk to a child process using the python subprocess.Popen() call. In my real code, I'm implementing a type of IPC, so I want to write some data, read the response, write some more data, read the response, and so on. Because of this, I cannot use Popen.communicate(), which otherwise works well for the simp... | 2012/04/28 | [
"https://Stackoverflow.com/questions/10363853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/526797/"
] | I would try to use `Popen().communicate()` if you can as it does a lot of nice things for you, but if you need to use `Popen()` exactly as you described, you'll need to set sed to flush its buffer after newlines with the `-l` option:
```
p = subprocess.Popen(['sed', '-l', 's/a/x/g'],
stdout=subpro... | `sed`'s output is buffered and only outputs its data until enough has been cumulated or the input stream is exhausted and closed.
Try this:
```
import subprocess
p = subprocess.Popen(["sed", 's/a/x/g'],
stdout = subprocess.PIPE,
stdin = subprocess.PIPE)
p.stdin.write("abc\n"... |
18,389,273 | I'm using python and having some trouble reading the properties of a file, when the filename includes non-ASCII characters.
One of the files for example is named:
`0-Channel-https∺∯∯services.apps.microsoft.com∯browse∯6.2.9200-1∯615∯Channel.dat`
When I run this:
```python
list2 = os.listdir('C:\\Users\\James\\AppDat... | 2013/08/22 | [
"https://Stackoverflow.com/questions/18389273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084310/"
] | If this is python 2.x, its an encoding issue. If you pass a unicode string to os.listdir such as `u'C:\\my\\pathname'`, it will return unicode strings and they should have the non-ascii chars encoded correctly. See [Unicode Filenames](http://docs.python.org/2/howto/unicode.html#unicode-filenames) in the docs.
Quoting ... | As you are in windows you should try with ntpath module instead of os.path
```
from ntpath import getmtime
```
As I don't have windows I can't test it. Every os has a different path convention, so, Python provides a specific module for the most common operative systems. |
7,281,348 | I'm building a website which allows you to write python code online just like <http://shell.appspot.com/> or <http://ideone.com>. Can someone please provide me some help how I can achieve this? | 2011/09/02 | [
"https://Stackoverflow.com/questions/7281348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/924945/"
] | First of all you can browse their [source code](http://code.google.com/p/google-app-engine-samples/downloads/detail?name=shell_20091112.tar.gz&can=2&q=). The main file is only 321 lines !
Basically it keeps a separate global dict for each user session, then uses `compile` and `exec` to run the code and return the resu... | I am new to python but hopefully following links could help you acheive ur goal,
BaseHTTPServer (http://docs.python.org/library/basehttpserver.html) library can be used for handling web requests and ipython (http://ipython.org) for executing python commands at the backend. |
33,301,838 | I am trying to access a JSON object/dictionary in python however get the error:
>
> TypeError: string indices must be integers if script['title'] ==
> "IT":
>
>
>
and this is my code to try and access that particular key within the dictionary:
```
def CreateScript(scriptsToGenerate):
start = time.clock()
... | 2015/10/23 | [
"https://Stackoverflow.com/questions/33301838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4867148/"
] | Facts:
* `scriptList` is a list of dictionaries (according to you)
* `for item in scriptList:` gets one dictionary at a time
* `proc = Process(target=CreateScript, args=(item))` passes a dictionary to the `CreateScript` function
* `def CreateScript(scriptsToGenerate):` receives a dictionary
* `for script in scriptsToG... | John, what I meant was that you have a json object there, it will need to be treated as such. I think you mean can you do the following?
```
def CreateScript(scriptsToGenerate):
#start = time.clock()
apiLocation = ""
saveFile = ""
i = json.loads(scriptsToGenerate)
if i['title'] == "IT":
tim... |
56,328,818 | I am using fuzzywuzzy in python for fuzzy string matching. I have a set of names in a list named HKCP\_list which I am matching against a pandas column iteratively to get the best possible match. Given below is the code for it
```
import fuzzywuzzy
from fuzzywuzzy import fuzz,process
def search_func(row):
chk = p... | 2019/05/27 | [
"https://Stackoverflow.com/questions/56328818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4762935/"
] | Use this function:
```
typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture) async {
try {
return await aFuture();
} catch (e) {
if (retries > 1) {
return retry(retries - 1, aFuture);
}
rethrow;
}
}
```
And to use it:
```
main(List<String> argu... | This is how I implemented it:
```
Future retry<T>(
{Future<T> Function() function,
int numberOfRetries = 3,
Duration delayToRetry = const Duration(milliseconds: 500),
String message = ''}) async {
int retry = numberOfRetries;
List<Exception> exceptions = [];
while (retry-- > 0) {
try {
... |
56,328,818 | I am using fuzzywuzzy in python for fuzzy string matching. I have a set of names in a list named HKCP\_list which I am matching against a pandas column iteratively to get the best possible match. Given below is the code for it
```
import fuzzywuzzy
from fuzzywuzzy import fuzz,process
def search_func(row):
chk = p... | 2019/05/27 | [
"https://Stackoverflow.com/questions/56328818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4762935/"
] | Use this function:
```
typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture) async {
try {
return await aFuture();
} catch (e) {
if (retries > 1) {
return retry(retries - 1, aFuture);
}
rethrow;
}
}
```
And to use it:
```
main(List<String> argu... | I added an optional delay to Daniel Oliveira's answer:
```
typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture, {Duration delay}) async {
try {
return await aFuture();
} catch (e) {
if (retries > 1) {
if (delay != null) {
await Future.delayed(delay)... |
56,328,818 | I am using fuzzywuzzy in python for fuzzy string matching. I have a set of names in a list named HKCP\_list which I am matching against a pandas column iteratively to get the best possible match. Given below is the code for it
```
import fuzzywuzzy
from fuzzywuzzy import fuzz,process
def search_func(row):
chk = p... | 2019/05/27 | [
"https://Stackoverflow.com/questions/56328818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4762935/"
] | Use this function:
```
typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture) async {
try {
return await aFuture();
} catch (e) {
if (retries > 1) {
return retry(retries - 1, aFuture);
}
rethrow;
}
}
```
And to use it:
```
main(List<String> argu... | [Retry](https://pub.dev/packages/retry) from Dart Neat is a good API and, unofficially, it's from Google:
<https://pub.dev/packages/retry> |
56,328,818 | I am using fuzzywuzzy in python for fuzzy string matching. I have a set of names in a list named HKCP\_list which I am matching against a pandas column iteratively to get the best possible match. Given below is the code for it
```
import fuzzywuzzy
from fuzzywuzzy import fuzz,process
def search_func(row):
chk = p... | 2019/05/27 | [
"https://Stackoverflow.com/questions/56328818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4762935/"
] | I added an optional delay to Daniel Oliveira's answer:
```
typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture, {Duration delay}) async {
try {
return await aFuture();
} catch (e) {
if (retries > 1) {
if (delay != null) {
await Future.delayed(delay)... | This is how I implemented it:
```
Future retry<T>(
{Future<T> Function() function,
int numberOfRetries = 3,
Duration delayToRetry = const Duration(milliseconds: 500),
String message = ''}) async {
int retry = numberOfRetries;
List<Exception> exceptions = [];
while (retry-- > 0) {
try {
... |
56,328,818 | I am using fuzzywuzzy in python for fuzzy string matching. I have a set of names in a list named HKCP\_list which I am matching against a pandas column iteratively to get the best possible match. Given below is the code for it
```
import fuzzywuzzy
from fuzzywuzzy import fuzz,process
def search_func(row):
chk = p... | 2019/05/27 | [
"https://Stackoverflow.com/questions/56328818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4762935/"
] | [Retry](https://pub.dev/packages/retry) from Dart Neat is a good API and, unofficially, it's from Google:
<https://pub.dev/packages/retry> | This is how I implemented it:
```
Future retry<T>(
{Future<T> Function() function,
int numberOfRetries = 3,
Duration delayToRetry = const Duration(milliseconds: 500),
String message = ''}) async {
int retry = numberOfRetries;
List<Exception> exceptions = [];
while (retry-- > 0) {
try {
... |
56,328,818 | I am using fuzzywuzzy in python for fuzzy string matching. I have a set of names in a list named HKCP\_list which I am matching against a pandas column iteratively to get the best possible match. Given below is the code for it
```
import fuzzywuzzy
from fuzzywuzzy import fuzz,process
def search_func(row):
chk = p... | 2019/05/27 | [
"https://Stackoverflow.com/questions/56328818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4762935/"
] | I added an optional delay to Daniel Oliveira's answer:
```
typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture, {Duration delay}) async {
try {
return await aFuture();
} catch (e) {
if (retries > 1) {
if (delay != null) {
await Future.delayed(delay)... | [Retry](https://pub.dev/packages/retry) from Dart Neat is a good API and, unofficially, it's from Google:
<https://pub.dev/packages/retry> |
6,424,676 | I have a list of lists, say:
```
arr = [[1, 2], [1, 3], [1, 4]]
```
I would like to append 100 to each of the inner lists. Output for the above example would be:
```
arr = [[1, 2, 100], [1, 3, 100], [1, 4, 100]]
```
I can of course do:
```
for elem in arr:
elem.append(100)
```
But is there ... | 2011/06/21 | [
"https://Stackoverflow.com/questions/6424676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373948/"
] | The second version should be written like `arr = [elem + [100] for elem in arr]`. But the most pythonic way if you ask me is the first one. The `for` construct has it's own use, and it suits very well here. | You can do
```
[a + [100] for a in arr]
```
The reason why your `append` doesn't work is that `append` doesn't return the list, but rather `None`.
Of course, this is more resource intensive than just doing `append` - you end up making copies of everything. |
6,424,676 | I have a list of lists, say:
```
arr = [[1, 2], [1, 3], [1, 4]]
```
I would like to append 100 to each of the inner lists. Output for the above example would be:
```
arr = [[1, 2, 100], [1, 3, 100], [1, 4, 100]]
```
I can of course do:
```
for elem in arr:
elem.append(100)
```
But is there ... | 2011/06/21 | [
"https://Stackoverflow.com/questions/6424676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373948/"
] | The second version should be written like `arr = [elem + [100] for elem in arr]`. But the most pythonic way if you ask me is the first one. The `for` construct has it's own use, and it suits very well here. | This is the more pythonic way
```
for elem in arr:
elem.append(100)
```
but as an option you can also try this:
```
[arr[i].append(100) for i in range(len(arr))]
print arr # It will return [[1, 2, 100], [1, 3, 100], [1, 4, 100]]
``` |
6,424,676 | I have a list of lists, say:
```
arr = [[1, 2], [1, 3], [1, 4]]
```
I would like to append 100 to each of the inner lists. Output for the above example would be:
```
arr = [[1, 2, 100], [1, 3, 100], [1, 4, 100]]
```
I can of course do:
```
for elem in arr:
elem.append(100)
```
But is there ... | 2011/06/21 | [
"https://Stackoverflow.com/questions/6424676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373948/"
] | Note that your code also works - the only thing you have to know is that there is no need to assign result to variable in such a case:
```
arr = [[1, 2], [1, 3], [1, 4]]
[x.append(100) for x in arr]
```
After execution arr will contain updated list [[1, 2, 100], [1, 3, 100], [1, 4, 100]], e.g it work like in-place u... | You can do
```
[a + [100] for a in arr]
```
The reason why your `append` doesn't work is that `append` doesn't return the list, but rather `None`.
Of course, this is more resource intensive than just doing `append` - you end up making copies of everything. |
6,424,676 | I have a list of lists, say:
```
arr = [[1, 2], [1, 3], [1, 4]]
```
I would like to append 100 to each of the inner lists. Output for the above example would be:
```
arr = [[1, 2, 100], [1, 3, 100], [1, 4, 100]]
```
I can of course do:
```
for elem in arr:
elem.append(100)
```
But is there ... | 2011/06/21 | [
"https://Stackoverflow.com/questions/6424676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373948/"
] | Note that your code also works - the only thing you have to know is that there is no need to assign result to variable in such a case:
```
arr = [[1, 2], [1, 3], [1, 4]]
[x.append(100) for x in arr]
```
After execution arr will contain updated list [[1, 2, 100], [1, 3, 100], [1, 4, 100]], e.g it work like in-place u... | This is the more pythonic way
```
for elem in arr:
elem.append(100)
```
but as an option you can also try this:
```
[arr[i].append(100) for i in range(len(arr))]
print arr # It will return [[1, 2, 100], [1, 3, 100], [1, 4, 100]]
``` |
54,024,663 | I have a python application that is running in Kubernetes. The app has a ping health-check which is called frequently via a REST call and checks that the call returns an HTTP 200. This clutters the Kubernetes logs when I view it through the logs console.
The function definition looks like this:
```
def ping():
re... | 2019/01/03 | [
"https://Stackoverflow.com/questions/54024663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5240483/"
] | In kubernetes, everything in container which you have on `stdout` or `stderr` will come into the kubernetes logs. The only way to exclude the logs of `health-check` ping call remove from kubernetes logs is that, In your application you should redirect output of those ping calls to somefile in say `/var/log/`. This will... | Just invert the logic log on fail in the app, modify the code or wrap with a custom decorator |
54,024,663 | I have a python application that is running in Kubernetes. The app has a ping health-check which is called frequently via a REST call and checks that the call returns an HTTP 200. This clutters the Kubernetes logs when I view it through the logs console.
The function definition looks like this:
```
def ping():
re... | 2019/01/03 | [
"https://Stackoverflow.com/questions/54024663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5240483/"
] | >
> clutters the Kubernetes logs when I view it through the logs console.
>
>
>
Since you said "view", I know it might not be the most accurate way to do this, but works ok:
```
kubectl logs [pod] [options] | awk '!/some health-check pattern|or another annoying pattern to exclude|another pattern you dont want to ... | Just invert the logic log on fail in the app, modify the code or wrap with a custom decorator |
54,024,663 | I have a python application that is running in Kubernetes. The app has a ping health-check which is called frequently via a REST call and checks that the call returns an HTTP 200. This clutters the Kubernetes logs when I view it through the logs console.
The function definition looks like this:
```
def ping():
re... | 2019/01/03 | [
"https://Stackoverflow.com/questions/54024663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5240483/"
] | In kubernetes, everything in container which you have on `stdout` or `stderr` will come into the kubernetes logs. The only way to exclude the logs of `health-check` ping call remove from kubernetes logs is that, In your application you should redirect output of those ping calls to somefile in say `/var/log/`. This will... | >
> clutters the Kubernetes logs when I view it through the logs console.
>
>
>
Since you said "view", I know it might not be the most accurate way to do this, but works ok:
```
kubectl logs [pod] [options] | awk '!/some health-check pattern|or another annoying pattern to exclude|another pattern you dont want to ... |
48,186,159 | My app is installed correctly and its models.py reads:
```
from django.db import models
class Album(models.Model):
artist = models.CharField(max_lenght=250)
album_title = models.CharField(max_lenght=500)
genre = models.CharField(max_lenght=100)
album_logo = models.CharField(max_lenght=1000)
class Son... | 2018/01/10 | [
"https://Stackoverflow.com/questions/48186159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8978159/"
] | Use this:
As per my comment, length (lenght) splelling is wrong.
```
from django.db import models
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.TextField()
class Song(... | You have spelled length wrong here
```
album_title = models.CharField(max_lenght=500)
```
happens to the best of us. |
63,709,035 | I am trying to have a button in HTML that removes a row in the database when I click it. This is for a flask app.
here is the HTML:
```
<div class="container-fluid text-center" id="products">
{% for product in productList %}
<div class='userProduct'>
<a href="{{ product.productURL }}" target="_blank">{... | 2020/09/02 | [
"https://Stackoverflow.com/questions/63709035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11522265/"
] | You're probably passing ID as an integer and your route is expecting a string. Use this instead:
```
@app.route('/delete/<int:id>')
``` | I just encountered the same error,
In my case it was caused by some values being None in the database.
So maybe check whether product.id has missing values.
To handle this, I needed an extra line, which would look something like this for you:
```
@app.route('/delete/<id>') # current line
@app.route('/delete', default... |
31,291,204 | I'm new to Apache Spark and have a simple question about DataFrame caching.
When I cached a DataFrame in memory using `df.cache()` in python, I found that the data is removed after the program terminates.
Can I keep the cached data in memory so that I can access the data for the next run without doing `df.cache()` ... | 2015/07/08 | [
"https://Stackoverflow.com/questions/31291204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2368670/"
] | The cache used with `cache()` is tied to the current spark context; its purpose is to prevent having to recalculate some intermediate results in the current application multiple times. If the context gets closed, the cache is gone. Nor can you share the cache between different running Spark contexts.
To be able to reu... | If you are talking about saving the RDD into disk , use any of the following -

The link is for pyspark , same is available for Java/ Scala as well-#
<https://spark.apache.org/docs/latest/api/python/pyspark.sql.html>
If you were not talking about d... |
38,989,150 | I trying to import a module and use a function from that module in my current python file.
I run the nosetests on the parser\_tests.py file but it fails with "name 'parse\_subject' not defined"
e.g its not finding the parse\_subject function which is clearly defined in the parsrer.py file
This is the parsrer file:
... | 2016/08/17 | [
"https://Stackoverflow.com/questions/38989150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6684586/"
] | ```
SELECT STUFF((
SELECT ','+ Name
FROM MyTable
WHERE ID in (1, 2, 3)
FOR XML PATH('')
), 1, 1, '') AS Names
```
Result:
>
> Apple,Microsoft,Samsung
>
>
> | ```
USE [Database Name]
SELECT COLUMN_NAME,*
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName'
``` |
38,989,150 | I trying to import a module and use a function from that module in my current python file.
I run the nosetests on the parser\_tests.py file but it fails with "name 'parse\_subject' not defined"
e.g its not finding the parse\_subject function which is clearly defined in the parsrer.py file
This is the parsrer file:
... | 2016/08/17 | [
"https://Stackoverflow.com/questions/38989150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6684586/"
] | You can do with `XML PATH`
```
SELECT
(
SELECT
T.Name + ', '
FROM
Tbl T
WHERE
Id in (1, 2, 3)
FOR XML PATH ('')
) DesiredOutput
```
Result looks like `Apple, Microsoft, Samsung,` | ```
USE [Database Name]
SELECT COLUMN_NAME,*
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName'
``` |
38,989,150 | I trying to import a module and use a function from that module in my current python file.
I run the nosetests on the parser\_tests.py file but it fails with "name 'parse\_subject' not defined"
e.g its not finding the parse\_subject function which is clearly defined in the parsrer.py file
This is the parsrer file:
... | 2016/08/17 | [
"https://Stackoverflow.com/questions/38989150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6684586/"
] | ```
SELECT STUFF((
SELECT ','+ Name
FROM MyTable
WHERE ID in (1, 2, 3)
FOR XML PATH('')
), 1, 1, '') AS Names
```
Result:
>
> Apple,Microsoft,Samsung
>
>
> | You can do with `XML PATH`
```
SELECT
(
SELECT
T.Name + ', '
FROM
Tbl T
WHERE
Id in (1, 2, 3)
FOR XML PATH ('')
) DesiredOutput
```
Result looks like `Apple, Microsoft, Samsung,` |
38,989,150 | I trying to import a module and use a function from that module in my current python file.
I run the nosetests on the parser\_tests.py file but it fails with "name 'parse\_subject' not defined"
e.g its not finding the parse\_subject function which is clearly defined in the parsrer.py file
This is the parsrer file:
... | 2016/08/17 | [
"https://Stackoverflow.com/questions/38989150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6684586/"
] | ```
SELECT STUFF((
SELECT ','+ Name
FROM MyTable
WHERE ID in (1, 2, 3)
FOR XML PATH('')
), 1, 1, '') AS Names
```
Result:
>
> Apple,Microsoft,Samsung
>
>
> | As SQL server doesn't support input in runtime, you can either create a stored procedure and pass the input value while executing it. or just run the following query.
```
SELECT NAME
FROM MyTable
WHERE ID IN
(SELECT TOP 3 ID FROM MyTable ORDER BY ID)
``` |
38,989,150 | I trying to import a module and use a function from that module in my current python file.
I run the nosetests on the parser\_tests.py file but it fails with "name 'parse\_subject' not defined"
e.g its not finding the parse\_subject function which is clearly defined in the parsrer.py file
This is the parsrer file:
... | 2016/08/17 | [
"https://Stackoverflow.com/questions/38989150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6684586/"
] | You can do with `XML PATH`
```
SELECT
(
SELECT
T.Name + ', '
FROM
Tbl T
WHERE
Id in (1, 2, 3)
FOR XML PATH ('')
) DesiredOutput
```
Result looks like `Apple, Microsoft, Samsung,` | As SQL server doesn't support input in runtime, you can either create a stored procedure and pass the input value while executing it. or just run the following query.
```
SELECT NAME
FROM MyTable
WHERE ID IN
(SELECT TOP 3 ID FROM MyTable ORDER BY ID)
``` |
41,595,532 | I have a Tkinter button, and for some reason, it accepts width=xx, but not height=xx
I'm using Python 3.5, with Tkinter support by default, on ubuntu 16.04
Here's the code sample:
```
# works: button_enter = ttk.Button(self.frm, text='ok', width = 100)
# works: button_enter.config(width=25)
# fails: button_enter = ... | 2017/01/11 | [
"https://Stackoverflow.com/questions/41595532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/377783/"
] | It's not a bug, that's just how ttk buttons work. If you need a highly configurable button, use a tkinter button. ttk buttons are less configurable on purpose. The goal of ttk widgets is to give you a set of buttons consistent with a particular theme.
Since you're on a linux system you can affect the height with `pack... | Use the **Place()** method instead over **Grid() or Pack() or Config()** . It will work fine. I never used **Config()** method |
41,595,532 | I have a Tkinter button, and for some reason, it accepts width=xx, but not height=xx
I'm using Python 3.5, with Tkinter support by default, on ubuntu 16.04
Here's the code sample:
```
# works: button_enter = ttk.Button(self.frm, text='ok', width = 100)
# works: button_enter.config(width=25)
# fails: button_enter = ... | 2017/01/11 | [
"https://Stackoverflow.com/questions/41595532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/377783/"
] | It's not a bug, that's just how ttk buttons work. If you need a highly configurable button, use a tkinter button. ttk buttons are less configurable on purpose. The goal of ttk widgets is to give you a set of buttons consistent with a particular theme.
Since you're on a linux system you can affect the height with `pack... | Don't import like that:
```
from tkinter.ttk import *
```
If you import with this method, the button will be imported as `ttk` |
631,884 | How do you encode a png image into base64 using python on Windows?
```
iconfile = open("icon.png")
icondata = iconfile.read()
icondata = base64.b64encode(icondata)
```
The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this? | 2009/03/10 | [
"https://Stackoverflow.com/questions/631884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76322/"
] | [Open the file in binary mode](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files):
```
open("icon.png", "rb")
```
I'm not very familiar with Windows, but I'd imagine what's happening is that the file contains a character (0x1A) that [Windows is interpreting as the end of the file](http://www... | To augment the answer from Miles, the [first eight bytes in a PNG file](http://www.libpng.org/pub/png/spec/1.2/PNG-Rationale.html#R.PNG-file-signature) are specially designed:
* 89 - the first byte is a check that
bit 8 hasn't been stripped
* "PNG" - let someone read that it's a
PNG format
* 0d 0a - the DOS end-of-lin... |
8,839,846 | In vim, you can check if a file is open in the current buffer with `bufexists`. For a short filename (not full path), you can check if it's open using `bufexists(bufname('filename'))`.
Is there any way to check if a file is open in a *tab*?
My closest workaround is to do something like:
```
:tabdo if bufnr(bufname(... | 2012/01/12 | [
"https://Stackoverflow.com/questions/8839846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814354/"
] | My impatience and good documentation got the better of me... here's the solution (greatly aided by [Check if current tab is empty in vim](https://stackoverflow.com/questions/5025558/check-if-current-tab-is-empty-in-vim) and [Open vim tab in new (GUI) window?](https://stackoverflow.com/questions/6123424/open-vim-tab-in-... | I'd reply to keflavich, but I can't yet...
I was working on a similar problem where I wanted to mimic the behavior of gvim --remote-tab-silent when opening files inside of gvim. I found this WhichTab script of yours, but ran into problems when there is more than one window open in any given tab. If you split windows ... |
44,894,992 | **On Windows 10, Python 3.6**
Let's say I have a command prompt session open **(not Python command prompt or Python interactive session)** and I've been setting up an environment with a lot of configurations or something of that nature. Is there any way for me to access the history of commands I used in that session w... | 2017/07/03 | [
"https://Stackoverflow.com/questions/44894992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6805800/"
] | You don't need Python at all, use `doskey` facilities for that, i.e.:
```
doskey /history
```
will print out the current session's command history, you can then redirect that to a file if you want to save it:
```
doskey /history > saved_commands.txt
```
If you really want to do it from within Python, you can use ... | You're actually asking for 3 different things there.
1. Getting Python REPL command hisotry
2. Getting info from "prompt", which I assume is the Powershell or CMD.exe.
3. Save the history list to a file.
To get the history from inside your REPL, use:
```py
for i in list(range(readline.get_current_history_length())):... |
73,631,420 | I am scraping web series data from `JSON` and `lists` using python. the problem is with date and time.
I got a function to convert the `duration` format
```
def get_duration(secs):
hour = int(secs/3600)
secs = secs - hour*3600
minute = int(secs/60)
if hour == 0:
return "00:" + str(minute)
e... | 2022/09/07 | [
"https://Stackoverflow.com/questions/73631420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19861079/"
] | That value looks like a timestamp so you could use [`datetime.fromtimestamp`](https://docs.python.org/3/library/datetime.html#datetime.date.fromtimestamp) to convert to a `datetime` object and then [`strftime`](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) to output in the format you want:... | The original question is slightly unclear about the final desired format. If you would like "22 Apr 2019" then the required format string is "%d %b %Y"
```
from datetime import datetime
d = datetime.fromtimestamp(1555939800)
print(d.strftime('%d %b %Y'))
```
Output:
```
22 Apr 2019
``` |
57,159,408 | Am new to python and trying to understand logging (am not new to programming at all though). Trying to replicate log4j logger that we have in Java. Have a simple test project of the following files:
- User.py
- Test.py
- conf/
- logging.conf
- log
All the python files have logger objects to log to specific file menti... | 2019/07/23 | [
"https://Stackoverflow.com/questions/57159408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1300830/"
] | I see a couple of things that may be the issue:
1) you're running 2 separate loggers: each file is instantiating it's own logger pointed to the same file.
2) if you want everything in the same file, then create one logger and pass the reference to other modules via a global var. I find it easier to create a log.py fil... | Thanks tbitson for the pointers. Here is the changed code.
```
import logging
import logging.config
logging.config.fileConfig('conf/logging.conf')
logger = logging.getLogger(__name__)
```
The modified User.py is:
```
from logger import logger
class User:
username = ""
password = ""
def __init__(self, ... |
47,111,787 | I'm trying to set and get keys from ElastiCache (memcached) from a python lambda function using Boto3. I can figure out how to get the endpoints but that's pretty much it. Is there some documentation out there that shows the entire process? | 2017/11/04 | [
"https://Stackoverflow.com/questions/47111787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4891674/"
] | It sounds like you are trying to interact with Memcached via Boto3. This is not possible. Boto3 is for interacting with the AWS API. You can manage your ElastiCache servers via the AWS API, but you can't interact with the Memcached software running on those servers. You need to use a Memcached client library like [pyth... | I had the exact timeout problem listed in the commment of the older post. My bug is in the security group for memcached. Here is the working version in terraform:
```
resource "aws_security_group" "memcached" {
vpc_id = "${aws_vpc.dev.id}"
name = "memcached SG"
ingress {
from_port = "${var.memcached... |
39,899,312 | I am using the Tracer software package (<https://github.com/Teichlab/tracer>).
The program is invoked as followed:
`tracer assemble [options] <file_1> [<file_2>] <cell_name> <output_directory>`
The program runs on a single dataset and the output goes to `/<output_directory>/<cell_name>`
What I want to do now is run ... | 2016/10/06 | [
"https://Stackoverflow.com/questions/39899312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6932623/"
] | I think this will do it, in bash, if I understand correctly -
```bash
for filename in /home/tobias/tracer/datasets/test/*.fastq
do
echo "Processing $filename file..."
basefilename="${filename##*/}" #<---
python tracer assemble --single_end --fragment_length 62 --fragment_sd 1 "$filename" "${basefilename%.fast... | From what I understood the library you use writes output to predefined (non configurable) directory
Let's call it `output_dir`.
At each iteration you should rename the output directory.
So your code should be something like this (pseudo code)
```
for filename in /home/tobias/tracer/datasets/test/*.fastq
do
e... |
69,760,313 | Is there more pythonic way to remove all duplicate elements from a list, while keeping the first and last element?
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
occurence = [i for i, e in enumerate(lst) if e == "foo"]
to_remove = occurence[1:-1]
for i in to_remove:
del lst[i]
print(lst) # ['foo', '... | 2021/10/28 | [
"https://Stackoverflow.com/questions/69760313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7661466/"
] | Use a slice-assignment and unpack/consume a filter?
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
lst[1:-1] = filter(lambda x: x != "foo", lst[1:-1])
print(lst)
```
Output:
```
['foo', 'bar', 'foobar', 'barfoo', 'foo']
``` | You can construct a new list with your requirements using Python's set data structure and slicing like this:
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
new_lst = [lst[0]] + list(set(lst[1:-1])) + [lst[-1]]
``` |
69,760,313 | Is there more pythonic way to remove all duplicate elements from a list, while keeping the first and last element?
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
occurence = [i for i, e in enumerate(lst) if e == "foo"]
to_remove = occurence[1:-1]
for i in to_remove:
del lst[i]
print(lst) # ['foo', '... | 2021/10/28 | [
"https://Stackoverflow.com/questions/69760313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7661466/"
] | Use a slice-assignment and unpack/consume a filter?
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
lst[1:-1] = filter(lambda x: x != "foo", lst[1:-1])
print(lst)
```
Output:
```
['foo', 'bar', 'foobar', 'barfoo', 'foo']
``` | Try below:
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
first, last = lst[0], lst[-1]
seen = {first, last}
seen_add = seen.add
inner = (s for s in lst[1:-1] if not (s in seen or seen_add(s)))
result = [first, *inner, last]
```
Result:
```
['foo', 'bar', 'foobar', 'barfoo', 'foo']
``` |
69,760,313 | Is there more pythonic way to remove all duplicate elements from a list, while keeping the first and last element?
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
occurence = [i for i, e in enumerate(lst) if e == "foo"]
to_remove = occurence[1:-1]
for i in to_remove:
del lst[i]
print(lst) # ['foo', '... | 2021/10/28 | [
"https://Stackoverflow.com/questions/69760313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7661466/"
] | Use a slice-assignment and unpack/consume a filter?
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
lst[1:-1] = filter(lambda x: x != "foo", lst[1:-1])
print(lst)
```
Output:
```
['foo', 'bar', 'foobar', 'barfoo', 'foo']
``` | According to your example, it's necessary to remove the duplicates looking at the entire list and then adding the first and last elements:
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
first, last = lst[0], lst[-1]
data = [first, *set([w for w in lst if w not in [first, last]]), last]
print(data)
```
... |
69,760,313 | Is there more pythonic way to remove all duplicate elements from a list, while keeping the first and last element?
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
occurence = [i for i, e in enumerate(lst) if e == "foo"]
to_remove = occurence[1:-1]
for i in to_remove:
del lst[i]
print(lst) # ['foo', '... | 2021/10/28 | [
"https://Stackoverflow.com/questions/69760313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7661466/"
] | Use a slice-assignment and unpack/consume a filter?
```
lst = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
lst[1:-1] = filter(lambda x: x != "foo", lst[1:-1])
print(lst)
```
Output:
```
['foo', 'bar', 'foobar', 'barfoo', 'foo']
``` | You can try this:
```py
mylist = ["foo", "bar", "foobar", "foo", "barfoo", "foo"]
none_duplicated = list(dict.fromkeys(mylist))
print([mylist[0], *none_duplicated, mylist[-1]])
```
Actually, your question is not about to remove duplicates, but remove the occurrences of your first item in the list (assume first and l... |
66,819,423 | I have homework where I'm asked to build Newton and Lagrange interpolation polynomials. I had no troubles with Lagrange polynomial but with Newton polynomial arises one problem: while Lagrange interpolation polynomial and original function match completely with each other, Newton Interpolation doesn't do this.
[Here is... | 2021/03/26 | [
"https://Stackoverflow.com/questions/66819423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11749578/"
] | One object is created, of type `C`, which contains all of the members of `A`, `B`, and `C`. | Here are some additional information about the relation between a base-class object and a derived-class object:
Every derived object contains a base-class part to which a pointer or reference of the base-class type can be bound. That's the reason why a conversion from derived to base exists, and no implicit Conversi... |
66,819,423 | I have homework where I'm asked to build Newton and Lagrange interpolation polynomials. I had no troubles with Lagrange polynomial but with Newton polynomial arises one problem: while Lagrange interpolation polynomial and original function match completely with each other, Newton Interpolation doesn't do this.
[Here is... | 2021/03/26 | [
"https://Stackoverflow.com/questions/66819423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11749578/"
] | 1. Only one object of type `class C` would be created.
2. So basically in this case, constructors of base classes are called first before the constructor of the derived class is called. In the end, the object of derived class also contains the contents of bases classes. | Here are some additional information about the relation between a base-class object and a derived-class object:
Every derived object contains a base-class part to which a pointer or reference of the base-class type can be bound. That's the reason why a conversion from derived to base exists, and no implicit Conversi... |
56,712,534 | How to append alpha values inside nested list in python?
```
nested_list = [['72010', 'PHARMACY', '-IV', 'FLUIDS', '7.95'], ['TOTAL',
'HOSPITAL', 'CHARGES', '6,720.92'],['PJ72010', 'WORD', 'FLUIDS',
'7.95']]
Expected_output:
[['72010', 'PHARMACY -IV FLUIDS', '7.95'], ['TOTAL HOSPITAL CHARGES', '6,720.92'],['PJ7201... | 2019/06/22 | [
"https://Stackoverflow.com/questions/56712534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11425561/"
] | If you create a function that defines what you mean by word you can use [`itertools.groupby()`](https://docs.python.org/3/library/itertools.html#itertools.groupby) to group by this function. Then you can either append the `join()`ed results or `extend()` depending on whether it's a group of numbers of word.
I'm inferr... | Go through the each nested list. Check the each element of that list . If it is a full alpha den append it in a temporary variable. Once you find a numeric append the temporary and numeric both.
Code:
```
nested_list = [['72010', 'PHARMACY', '-IV', 'FLUIDS', '7.95'], ['TOTAL',
'HOSPITAL', 'CHARGES', '6,720.92'],['PJ7... |
34,902,307 | I have a python script that processes an XML file each day (it is transferred via SFTP to a remote directory, then temporarily copied to a local directory) and stores its information in a MySQL database.
One of my parameters for the file is set to "date=today" so that the correct file is processed each day. This works... | 2016/01/20 | [
"https://Stackoverflow.com/questions/34902307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5451573/"
] | You can use `sys` module and pass the filename as command line argument.
That would be :
```
import sys
today = str(sys.argv[1]) if len(sys.argv) > 1 else datetime.datetime.now().strftime('%Y%m%d')
```
If the name is given as first argument, then `today` variable will be filename given from command line otherwise ... | You can use [argsparse](https://docs.python.org/3/library/argparse.html) to consume command line arguments. You will have to check if specific date is passed and use it instead of the current date
```
if args.date_to_run:
today = args.date_to_run
else:
today = datetime.datetime.now().strftime('%Y%m%d')
```
F... |
73,061,728 | I'm trying to get a better understanding of python imports and namespaces. Take the example of a module testImport.py:
```py
# testImport.py
var1 = 1
def fn1():
return var1
```
if I import this like this:
```py
from testImport import *
```
I can inspect `var1`
```py
>>> var1
1
```
and `fn1()` returns
```... | 2022/07/21 | [
"https://Stackoverflow.com/questions/73061728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13258525/"
] | I'm not sure that you would be able to modify the root node as you are trying to do here. The namespace URI should be `http://www.w3.org/2000/xmlns/p` if it is `p` that you are trying to use as the prefix and you would use `p:root` as the qualifiedName but that would result in the root node being modified like this `<r... | The root element is the root element. You change it by creating a new document with the root element of your choice.
If the the job is left to import all root elements children from another document, then be it (SimpleXML is not that fitting for that, DOMDocument is, see [`DOMDocument::importNode`](https://www.php.net... |
51,943,359 | I have this part on the `docker-compose` that will copy the `angular-cli` frontend and a `scripts` directory.
```
www:
build: ./www
volumes:
- ./www/frontend:/app
- ./www/scripts:/scripts
command: /scripts/init-dev.sh
ports:
- "4200:4200"
- "49153:49153"
```
The `Dockerfile`... | 2018/08/21 | [
"https://Stackoverflow.com/questions/51943359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2111400/"
] | Two options:
1. also start your services with the InProcessServerBuilder, and use the InProcessChannelBuilder to communicate with it, or
2. just contact the server over "localhost" | if you want a cli type of call to your local grpc server, you could checkout <https://github.com/fullstorydev/grpcurl> |
42,990,994 | I have this code
```
python_data_struct = {
'amazon_app_id': amazon_app_id,
'librivox_rest_url': librivox_rest_url,
'librivox_id': librivox_id,
'top': top,
'pacakge': 'junk',
'version': 'junk',
'password': password,
'description': description,
'l... | 2017/03/24 | [
"https://Stackoverflow.com/questions/42990994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/759991/"
] | You can make function calls on ngSubmit
*form class="well" (ngSubmit)="addUserModal.hide(); addUser(model); userForm.reset()" #userForm="ngForm"* | I haven't used AngularJS, but the following works for me in Angular 2, if you're able to use jQuery:
`$(".modal").modal("hide")` |
42,990,994 | I have this code
```
python_data_struct = {
'amazon_app_id': amazon_app_id,
'librivox_rest_url': librivox_rest_url,
'librivox_id': librivox_id,
'top': top,
'pacakge': 'junk',
'version': 'junk',
'password': password,
'description': description,
'l... | 2017/03/24 | [
"https://Stackoverflow.com/questions/42990994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/759991/"
] | I haven't used AngularJS, but the following works for me in Angular 2, if you're able to use jQuery:
`$(".modal").modal("hide")` | Fire button click on submit event in angularJS.
```
<input id="quemodalcancel" type="submit" value="Cancel" class="btn blue_btn" data-dismiss="modal" aria-hidden="true">
$scope.editProduct = function(item){
// submit button code
document.querySelector('#quemodalcancel').click();
}
``` |
42,990,994 | I have this code
```
python_data_struct = {
'amazon_app_id': amazon_app_id,
'librivox_rest_url': librivox_rest_url,
'librivox_id': librivox_id,
'top': top,
'pacakge': 'junk',
'version': 'junk',
'password': password,
'description': description,
'l... | 2017/03/24 | [
"https://Stackoverflow.com/questions/42990994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/759991/"
] | You can make function calls on ngSubmit
*form class="well" (ngSubmit)="addUserModal.hide(); addUser(model); userForm.reset()" #userForm="ngForm"* | Fire button click on submit event in angularJS.
```
<input id="quemodalcancel" type="submit" value="Cancel" class="btn blue_btn" data-dismiss="modal" aria-hidden="true">
$scope.editProduct = function(item){
// submit button code
document.querySelector('#quemodalcancel').click();
}
``` |
59,641,747 | I cannot get it it's bash related or python subprocess, but results are different:
```
>>> subprocess.Popen("echo $HOME", shell=True, stdout=subprocess.PIPE).communicate()
(b'/Users/mac\n', None)
>>> subprocess.Popen(["echo", "$HOME"], shell=True, stdout=subprocess.PIPE).communicate()
(b'\n', None)
```
Why in second... | 2020/01/08 | [
"https://Stackoverflow.com/questions/59641747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6519078/"
] | Use fifo format, which can reconnect.
My working example:
```
-f fifo -fifo_format flv \
-drop_pkts_on_overflow 1 -attempt_recovery 1 -recover_any_error 1 \
rtmp://bla.bla/bla
``` | +1 for the accepted answer, but:
In FFmpeg, an encoder auto-detects it's parameters based on selected output format. Here the output format is unknown (that's correct for formats like "fifo" and "tee") so the encoder won't have all parameters setup the same as if using "flv" output format.
For example: Wowza Streamin... |
58,469,032 | I am starting to learn python and I don't know much about programming right now. In the future, I want to build android applications. Python looks interesting to me.
Can I use python for building Android applications? | 2019/10/20 | [
"https://Stackoverflow.com/questions/58469032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11109516/"
] | You can build android apps in python, but it's not as powerful as android studio, and the apps made by python take more space and are less memory efficient.But the apps work well...
There are several ways to use Python on Android:
BeeWare. BeeWare is a collection of tools for building native user interfaces. ...
Cha... | As of now the official android development languages are **kotlin** and **java** in `android studio` IDE, with the addition of **dart** for cross-platform development in `flutter` SDK. I would advise you stick to whichever you find easiest as per your needs. Although python is more widely accepted in the domains of dat... |
58,469,032 | I am starting to learn python and I don't know much about programming right now. In the future, I want to build android applications. Python looks interesting to me.
Can I use python for building Android applications? | 2019/10/20 | [
"https://Stackoverflow.com/questions/58469032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11109516/"
] | You can build android apps in python, but it's not as powerful as android studio, and the apps made by python take more space and are less memory efficient.But the apps work well...
There are several ways to use Python on Android:
BeeWare. BeeWare is a collection of tools for building native user interfaces. ...
Cha... | You could use python as the back end and vue native as the front end. Vue active can be exported as native android application and put in the app store. The frontend will call API written in back end (in your case, written in python). Check out Vuenative + flask/ django framework. |
74,054,668 | How to convert a `.csv` file to `.npy` efficently?
--------------------------------------------------
I've tried:
```
import numpy as np
filename = "myfile.csv"
vec =np.loadtxt(filename, delimiter=",")
np.save(f"{filename}.npy", vec)
```
While the above works for smallish file, the actual `.csv` file I'm working o... | 2022/10/13 | [
"https://Stackoverflow.com/questions/74054668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | Nice question; Informative in itself.
I understand you want to have the whole data set/array in memory, eventually, as a NumPy array. I assume, then, you have enough (RAM) memory to host such array -- 12M x 1K.
I don't specifically know about how `np.loadtxt` (`genfromtxt`) is operating behind the scenes, so I will t... | TL;DR
=====
Export to a different function other than `.npy` seems inevitable unless your machine is able to handle the size of the data in-memory as per described in [@Brandt answer](https://stackoverflow.com/a/74055562/610569).
---
Reading the data, then processing it (Kinda answering Q part 2)
===================... |
74,054,668 | How to convert a `.csv` file to `.npy` efficently?
--------------------------------------------------
I've tried:
```
import numpy as np
filename = "myfile.csv"
vec =np.loadtxt(filename, delimiter=",")
np.save(f"{filename}.npy", vec)
```
While the above works for smallish file, the actual `.csv` file I'm working o... | 2022/10/13 | [
"https://Stackoverflow.com/questions/74054668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | Nice question; Informative in itself.
I understand you want to have the whole data set/array in memory, eventually, as a NumPy array. I assume, then, you have enough (RAM) memory to host such array -- 12M x 1K.
I don't specifically know about how `np.loadtxt` (`genfromtxt`) is operating behind the scenes, so I will t... | It it's latest version (4.14) vaex support "streaming", i.e. lazy loading of CSV files. It uses pyarrow under the hood so it is supper fast. Try something like
```py
df = vaex.open(my_file.csv)
# or
df = vaex.from_csv_arrow(my_file.csv, lazy=True)
```
Then you can export to bunch of formats as needed, or keep workin... |
74,054,668 | How to convert a `.csv` file to `.npy` efficently?
--------------------------------------------------
I've tried:
```
import numpy as np
filename = "myfile.csv"
vec =np.loadtxt(filename, delimiter=",")
np.save(f"{filename}.npy", vec)
```
While the above works for smallish file, the actual `.csv` file I'm working o... | 2022/10/13 | [
"https://Stackoverflow.com/questions/74054668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | Nice question; Informative in itself.
I understand you want to have the whole data set/array in memory, eventually, as a NumPy array. I assume, then, you have enough (RAM) memory to host such array -- 12M x 1K.
I don't specifically know about how `np.loadtxt` (`genfromtxt`) is operating behind the scenes, so I will t... | I'm not aware of any existing function or utility that directly and efficiently converts csv files into npy files. With efficient I guess primarily meaning with low memory requirements.
Writing a npy file iteratively is indeed possible, with some extra effort. There's already a question on SO that addresses this, see:... |
74,054,668 | How to convert a `.csv` file to `.npy` efficently?
--------------------------------------------------
I've tried:
```
import numpy as np
filename = "myfile.csv"
vec =np.loadtxt(filename, delimiter=",")
np.save(f"{filename}.npy", vec)
```
While the above works for smallish file, the actual `.csv` file I'm working o... | 2022/10/13 | [
"https://Stackoverflow.com/questions/74054668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | Nice question; Informative in itself.
I understand you want to have the whole data set/array in memory, eventually, as a NumPy array. I assume, then, you have enough (RAM) memory to host such array -- 12M x 1K.
I don't specifically know about how `np.loadtxt` (`genfromtxt`) is operating behind the scenes, so I will t... | ```
import numpy as np
import pandas as pd
# Define the input and output file names
csv_file = 'data.csv'
npy_file = 'data.npy'
# Create dummy data
data = np.random.rand(10000, 100)
df = pd.DataFrame(data)
df.to_csv(csv_file, index=False)
# Define the chunk size
chunk_size = 1000
# Read the header row and get the n... |
74,054,668 | How to convert a `.csv` file to `.npy` efficently?
--------------------------------------------------
I've tried:
```
import numpy as np
filename = "myfile.csv"
vec =np.loadtxt(filename, delimiter=",")
np.save(f"{filename}.npy", vec)
```
While the above works for smallish file, the actual `.csv` file I'm working o... | 2022/10/13 | [
"https://Stackoverflow.com/questions/74054668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | TL;DR
=====
Export to a different function other than `.npy` seems inevitable unless your machine is able to handle the size of the data in-memory as per described in [@Brandt answer](https://stackoverflow.com/a/74055562/610569).
---
Reading the data, then processing it (Kinda answering Q part 2)
===================... | I'm not aware of any existing function or utility that directly and efficiently converts csv files into npy files. With efficient I guess primarily meaning with low memory requirements.
Writing a npy file iteratively is indeed possible, with some extra effort. There's already a question on SO that addresses this, see:... |
74,054,668 | How to convert a `.csv` file to `.npy` efficently?
--------------------------------------------------
I've tried:
```
import numpy as np
filename = "myfile.csv"
vec =np.loadtxt(filename, delimiter=",")
np.save(f"{filename}.npy", vec)
```
While the above works for smallish file, the actual `.csv` file I'm working o... | 2022/10/13 | [
"https://Stackoverflow.com/questions/74054668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | It it's latest version (4.14) vaex support "streaming", i.e. lazy loading of CSV files. It uses pyarrow under the hood so it is supper fast. Try something like
```py
df = vaex.open(my_file.csv)
# or
df = vaex.from_csv_arrow(my_file.csv, lazy=True)
```
Then you can export to bunch of formats as needed, or keep workin... | I'm not aware of any existing function or utility that directly and efficiently converts csv files into npy files. With efficient I guess primarily meaning with low memory requirements.
Writing a npy file iteratively is indeed possible, with some extra effort. There's already a question on SO that addresses this, see:... |
74,054,668 | How to convert a `.csv` file to `.npy` efficently?
--------------------------------------------------
I've tried:
```
import numpy as np
filename = "myfile.csv"
vec =np.loadtxt(filename, delimiter=",")
np.save(f"{filename}.npy", vec)
```
While the above works for smallish file, the actual `.csv` file I'm working o... | 2022/10/13 | [
"https://Stackoverflow.com/questions/74054668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610569/"
] | ```
import numpy as np
import pandas as pd
# Define the input and output file names
csv_file = 'data.csv'
npy_file = 'data.npy'
# Create dummy data
data = np.random.rand(10000, 100)
df = pd.DataFrame(data)
df.to_csv(csv_file, index=False)
# Define the chunk size
chunk_size = 1000
# Read the header row and get the n... | I'm not aware of any existing function or utility that directly and efficiently converts csv files into npy files. With efficient I guess primarily meaning with low memory requirements.
Writing a npy file iteratively is indeed possible, with some extra effort. There's already a question on SO that addresses this, see:... |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | You must use `plt.show()` at the end in order to see the plot | `plt.plot(X,y)` function just draws the plot on the canvas. In order to view the plot, you have to specify `plt.show()` after `plt.plot(X,y)`. So,
```
import matplotlib.pyplot as plt
X = //your x
y = //your y
plt.plot(X,y)
plt.show()
``` |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | In matplotlib you have two main options:
1. Create your plots and draw them at the end:
```
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.plot(z, t)
plt.show()
```
2. Create your plots and draw them as soon as they are created:
```
import matplotlib.pyplot as plt
from matplotlib import interactive
interactive... | Save the plot as png
```
plt.savefig("temp.png")
``` |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | In case anyone else ends up here using Jupyter Notebooks, you just need
```
%matplotlib inline
```
[Purpose of "%matplotlib inline"](https://stackoverflow.com/questions/43027980/purpose-of-matplotlib-inline) | You have to use `show()` methode when you done all initialisations in your code in order to see the complet version of plot:
```
import matplotlib.pyplot as plt
plt.plot(x, y)
................
................
plot.show()
``` |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | In matplotlib you have two main options:
1. Create your plots and draw them at the end:
```
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.plot(z, t)
plt.show()
```
2. Create your plots and draw them as soon as they are created:
```
import matplotlib.pyplot as plt
from matplotlib import interactive
interactive... | You have to use `show()` methode when you done all initialisations in your code in order to see the complet version of plot:
```
import matplotlib.pyplot as plt
plt.plot(x, y)
................
................
plot.show()
``` |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | In matplotlib you have two main options:
1. Create your plots and draw them at the end:
```
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.plot(z, t)
plt.show()
```
2. Create your plots and draw them as soon as they are created:
```
import matplotlib.pyplot as plt
from matplotlib import interactive
interactive... | `plt.plot(X,y)` function just draws the plot on the canvas. In order to view the plot, you have to specify `plt.show()` after `plt.plot(X,y)`. So,
```
import matplotlib.pyplot as plt
X = //your x
y = //your y
plt.plot(X,y)
plt.show()
``` |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | In matplotlib you have two main options:
1. Create your plots and draw them at the end:
```
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.plot(z, t)
plt.show()
```
2. Create your plots and draw them as soon as they are created:
```
import matplotlib.pyplot as plt
from matplotlib import interactive
interactive... | In case anyone else ends up here using Jupyter Notebooks, you just need
```
%matplotlib inline
```
[Purpose of "%matplotlib inline"](https://stackoverflow.com/questions/43027980/purpose-of-matplotlib-inline) |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | You must use `plt.show()` at the end in order to see the plot | You have to use `show()` methode when you done all initialisations in your code in order to see the complet version of plot:
```
import matplotlib.pyplot as plt
plt.plot(x, y)
................
................
plot.show()
``` |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | Save the plot as png
```
plt.savefig("temp.png")
``` | You have to use `show()` methode when you done all initialisations in your code in order to see the complet version of plot:
```
import matplotlib.pyplot as plt
plt.plot(x, y)
................
................
plot.show()
``` |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | In case anyone else ends up here using Jupyter Notebooks, you just need
```
%matplotlib inline
```
[Purpose of "%matplotlib inline"](https://stackoverflow.com/questions/43027980/purpose-of-matplotlib-inline) | `plt.plot(X,y)` function just draws the plot on the canvas. In order to view the plot, you have to specify `plt.show()` after `plt.plot(X,y)`. So,
```
import matplotlib.pyplot as plt
X = //your x
y = //your y
plt.plot(X,y)
plt.show()
``` |
8,575,062 | I am sure the configuration of `matplotlib` for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
Ther... | 2011/12/20 | [
"https://Stackoverflow.com/questions/8575062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/504283/"
] | You must use `plt.show()` at the end in order to see the plot | Save the plot as png
```
plt.savefig("temp.png")
``` |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | Reading registry keys:
```
def read(path, root=HKEY_CURRENT_USER):
path, name = os.path.split(path)
with suppress(FileNotFoundError), OpenKey(root, path) as key:
return QueryValueEx(key, name)[0]
```
And writing:
```
def write(path, value, root=HKEY_CURRENT_USER):
path, name = os.path.split(path... | for Creating / writing values in registry key:
```
from winreg import*
import winreg
keyVal = r'SOFTWARE\\python'
try:
key = OpenKey(HKEY_LOCAL_MACHINE, keyVal, 0, KEY_ALL_ACCESS)
except:
key = CreateKey(HKEY_LOCAL_MACHINE, keyVal)
SetValueEx(key, "Start Page", 0, REG_SZ, "snakes")
CloseKey(key)
```
If acc... |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | Same as @Aramanethota but with pep8 and func def for easy usage.
```
REG_PATH = r"SOFTWARE\my_program\Settings"
def set_reg(name, value):
try:
_winreg.CreateKey(_winreg.HKEY_CURRENT_USER, REG_PATH)
registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0,
... | The 'winreg' module is so ...strange working module, so, I wrote a class called 'WindowsRegistry' for working with Windows registry and 'winreg' module easier. I hope it will be more usefull:
```
import winreg
import re
class WindowsRegistry:
"""Class WindowsRegistry is using for easy manipulating Windows registr... |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | Looks like you don't have permission to edit the Registry. Incase if you are Admin, Please run this script in Elevated state. | My solution:
```
def add_key(name,pathh):
try:
keyval=r"System\my path\Register"
if not os.path.exists("keyval"):
key = winreg.CreateKey(winreg.HKEY_CURRENT_USER,keyval)
Registrykey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"System\my path\Register", 0,winreg.KEY_WRITE)
... |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | Reading registry keys:
```
def read(path, root=HKEY_CURRENT_USER):
path, name = os.path.split(path)
with suppress(FileNotFoundError), OpenKey(root, path) as key:
return QueryValueEx(key, name)[0]
```
And writing:
```
def write(path, value, root=HKEY_CURRENT_USER):
path, name = os.path.split(path... | Looks like you don't have permission to edit the Registry. Incase if you are Admin, Please run this script in Elevated state. |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | Python script to read from registry is as follows:
```
try:
root_key=OpenKey(HKEY_CURRENT_USER, r'SOFTWARE\my path to\Registry', 0, KEY_READ)
[Pathname,regtype]=(QueryValueEx(root_key,"Pathname"))
CloseKey(root_key)
if (""==Pathname):
raise WindowsError
except WindowsError:
return [""]
```... | Reading registry keys:
```
def read(path, root=HKEY_CURRENT_USER):
path, name = os.path.split(path)
with suppress(FileNotFoundError), OpenKey(root, path) as key:
return QueryValueEx(key, name)[0]
```
And writing:
```
def write(path, value, root=HKEY_CURRENT_USER):
path, name = os.path.split(path... |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | Same as @Aramanethota but with pep8 and func def for easy usage.
```
REG_PATH = r"SOFTWARE\my_program\Settings"
def set_reg(name, value):
try:
_winreg.CreateKey(_winreg.HKEY_CURRENT_USER, REG_PATH)
registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0,
... | Here is a class I wrote (python 2) which has the ability to restore state when you finish manipulating the registry. The class was not tested properly so it may contain some bugs:
```
import _winreg as winreg
class Registry(object):
def __init__(self, restore_state=False):
self.m_backup = {}
self.... |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | ```
#Python3 version of hugo24's snippet
import winreg
REG_PATH = r"Control Panel\Mouse"
def set_reg(name, value):
try:
winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH)
registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0,
winreg.KEY_WRITE... | Here is a class I wrote (python 2) which has the ability to restore state when you finish manipulating the registry. The class was not tested properly so it may contain some bugs:
```
import _winreg as winreg
class Registry(object):
def __init__(self, restore_state=False):
self.m_backup = {}
self.... |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | Same as @Aramanethota but with pep8 and func def for easy usage.
```
REG_PATH = r"SOFTWARE\my_program\Settings"
def set_reg(name, value):
try:
_winreg.CreateKey(_winreg.HKEY_CURRENT_USER, REG_PATH)
registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0,
... | Reading registry keys:
```
def read(path, root=HKEY_CURRENT_USER):
path, name = os.path.split(path)
with suppress(FileNotFoundError), OpenKey(root, path) as key:
return QueryValueEx(key, name)[0]
```
And writing:
```
def write(path, value, root=HKEY_CURRENT_USER):
path, name = os.path.split(path... |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | for Creating / writing values in registry key:
```
from winreg import*
import winreg
keyVal = r'SOFTWARE\\python'
try:
key = OpenKey(HKEY_LOCAL_MACHINE, keyVal, 0, KEY_ALL_ACCESS)
except:
key = CreateKey(HKEY_LOCAL_MACHINE, keyVal)
SetValueEx(key, "Start Page", 0, REG_SZ, "snakes")
CloseKey(key)
```
If acc... | The 'winreg' module is so ...strange working module, so, I wrote a class called 'WindowsRegistry' for working with Windows registry and 'winreg' module easier. I hope it will be more usefull:
```
import winreg
import re
class WindowsRegistry:
"""Class WindowsRegistry is using for easy manipulating Windows registr... |
15,128,225 | I have developed a python script where i have a setting window which has the options to select the paths for the installation of software.When clicked on OK button of the setting window, i want to write all the selected paths to the registry and read the same when setting window is opened again.
My code looks as below.... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15128225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016950/"
] | Python script to read from registry is as follows:
```
try:
root_key=OpenKey(HKEY_CURRENT_USER, r'SOFTWARE\my path to\Registry', 0, KEY_READ)
[Pathname,regtype]=(QueryValueEx(root_key,"Pathname"))
CloseKey(root_key)
if (""==Pathname):
raise WindowsError
except WindowsError:
return [""]
```... | Same as @Aramanethota but with pep8 and func def for easy usage.
```
REG_PATH = r"SOFTWARE\my_program\Settings"
def set_reg(name, value):
try:
_winreg.CreateKey(_winreg.HKEY_CURRENT_USER, REG_PATH)
registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0,
... |
15,576,693 | I am currently working on a project for one of my classes where I have to implement an AI opponent to play tic-tac-toe using minmax and Alpha-Beta minmax algorithms to determine the moves.
The problem I am having however is attempting to generate a list of possible moves for a board.
My problem code is as follows
`... | 2013/03/22 | [
"https://Stackoverflow.com/questions/15576693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/967929/"
] | This line is a problem:
```
tempBoard = genBoard
```
After this line, you seem to think that you have *two* lists -- the original, still referenced
by `genBoard`, and a new one, now referenced by `tempBoard`. This is not the case.
This line does **not** create a copy of the list. Instead, it binds the name `tempBoa... | I belive Python does not create a copy of your Board but just points to the original version. therefore your printout is:
*"MovesList: "
[[0,(X,O,O,O,O,O,O,O,O)],[1,(X,O,O,O,O,O,O,O,O)],[2,(X,O,O,O,O,O,O,O,O)],* etc.
and your genBoard, variable is changed.
to test that add
*print genBoard*
directly before the end... |
47,801 | I am trying to create a web application using Pylons and the resources on the web point to the [PylonsBook](http://pylonsbook.com/alpha1/authentication_and_authorization) page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?
I tried down... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | I don't think AuthKit is actively maintained anymore. It does use the Paste (<http://pythonpaste.org>) libs though for things like HTTP Basic/Digest authentication. I would probably go ahead and take a look at the source for some inspiration and then use the Paste tools if you want to use HTTP authentication.
There i... | This actually got me interested:[Check out this mailing on the pylons list](http://groups.google.com/group/pylons-discuss/browse_thread/thread/644deb53612af362?hl=en). So AuthKit is being developed, and I will follow the book and get back on the results. |
47,801 | I am trying to create a web application using Pylons and the resources on the web point to the [PylonsBook](http://pylonsbook.com/alpha1/authentication_and_authorization) page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?
I tried down... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | Ok, another update on the subject. It seems that the cheeseshop template is broken. I've followed the chapter you linked in the post and it seems that authkit is working fine. There are some caveats:
1. sqlalchemy has to be in 0.5 version
2. authkit has to be the dev version from svn (easy\_install authkit==dev)
I ma... | I don't think AuthKit is actively maintained anymore. It does use the Paste (<http://pythonpaste.org>) libs though for things like HTTP Basic/Digest authentication. I would probably go ahead and take a look at the source for some inspiration and then use the Paste tools if you want to use HTTP authentication.
There i... |
47,801 | I am trying to create a web application using Pylons and the resources on the web point to the [PylonsBook](http://pylonsbook.com/alpha1/authentication_and_authorization) page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?
I tried down... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | I gave up on authkit and rolled my own:
<http://tonylandis.com/openid-db-authentication-in-pylons-is-easy-with-rpx/> | I don't think AuthKit is actively maintained anymore. It does use the Paste (<http://pythonpaste.org>) libs though for things like HTTP Basic/Digest authentication. I would probably go ahead and take a look at the source for some inspiration and then use the Paste tools if you want to use HTTP authentication.
There i... |
47,801 | I am trying to create a web application using Pylons and the resources on the web point to the [PylonsBook](http://pylonsbook.com/alpha1/authentication_and_authorization) page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?
I tried down... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | Ok, another update on the subject. It seems that the cheeseshop template is broken. I've followed the chapter you linked in the post and it seems that authkit is working fine. There are some caveats:
1. sqlalchemy has to be in 0.5 version
2. authkit has to be the dev version from svn (easy\_install authkit==dev)
I ma... | This actually got me interested:[Check out this mailing on the pylons list](http://groups.google.com/group/pylons-discuss/browse_thread/thread/644deb53612af362?hl=en). So AuthKit is being developed, and I will follow the book and get back on the results. |
47,801 | I am trying to create a web application using Pylons and the resources on the web point to the [PylonsBook](http://pylonsbook.com/alpha1/authentication_and_authorization) page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?
I tried down... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | I gave up on authkit and rolled my own:
<http://tonylandis.com/openid-db-authentication-in-pylons-is-easy-with-rpx/> | This actually got me interested:[Check out this mailing on the pylons list](http://groups.google.com/group/pylons-discuss/browse_thread/thread/644deb53612af362?hl=en). So AuthKit is being developed, and I will follow the book and get back on the results. |
44,532,041 | I want to strip all python docstrings out of a file using simple search and replace, and the following (extremely) simplistic regex does the job for one line doc strings:
[Regex101.com](https://regex101.com/r/PiExji/1)
```
""".*"""
```
How can I extend that to work with multi-liners?
Tried to include `\s` in a num... | 2017/06/13 | [
"https://Stackoverflow.com/questions/44532041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2171758/"
] | As you cannot use an inline `s` (DOTALL) modifier, the usual workaround to match any char is using a character class with opposite shorthand character classes:
```
"""[\s\S]*?"""
```
or
```
"""[\d\D]*?"""
```
or
```
"""[\w\W]*?"""
```
will match `"""` then any 0+ chars, as few as possible as `*?` is a lazy qua... | Sometimes there are multiline strings that are not docstrings. For example, you may have a complicated SQL query that extends across multiple lines. The following attempts to look for multiline strings that appear before class definitions and after function definitions.
```
import re
input_str = """'''
This is a clas... |
43,970,466 | I tried using the below python code to find the websites of the companies. But after trying few times, I face a **Service Unavailable** error.
I have finished the first level of finding the possible domains of the companies. For example :
CompanyExample [u'<http://www.examples.com/>', u'<https://www.example.com/quot... | 2017/05/15 | [
"https://Stackoverflow.com/questions/43970466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7664428/"
] | If you need to check a specific permission try
```
{% if user.hasPermission('administer nodes') %}
<div class="foo"><a href="/">Shorthand link for admins</a></div>
{% endif %}
``` | If you try to check the current user is administer in TWIG file , you can use
```
{% if is_admin %}
<div class="foo"><a href="/">Shorthand link for admins</a></div>
{% endif %}
``` |
2,731,871 | I have a web application in python wherein the user submits their email and password. These values are compared to values stored in a mysql database. If successful, the script generates a session id, stores it next to the email in the database and sets a cookie with the session id, with allows the user to interact with... | 2010/04/28 | [
"https://Stackoverflow.com/questions/2731871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/301860/"
] | You can encode the expiration time as part of your session id.
Then when you validate the session id, you can also check if it has expired, and if so force the user to log-in again.
You can also clean your database periodically, removing expired sessions. | You'd have to add a timestamp to the session ID in the database to know when it ran out.
Better, make the timestamp part of the session ID itself, eg.:
```
Set-Cookie: session=1272672000-(random_number);expires=Sat, 01-May-2010 00:00:00 GMT
```
so that your script can see just by looking at the number at the front ... |
47,412,723 | I'm new in python and I am trying to build a script that gets as an argument a URL and send a GET request to the website and then print the details from the response and the HTML body as well.
The code I wrote:
```
import sys
import urllib.request
url = 'https://%s' % (sys.argv[1])
res = urllib.request.urlopen(url)
... | 2017/11/21 | [
"https://Stackoverflow.com/questions/47412723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You have to handle array of elements separately:
```
var formToJSON = elements => [].reduce.call(elements, (data, element) => {
var isArray = element.name.endsWith('[]');
var name = element.name.replace('[]', '');
data[name] = isArray ? (data[name] || []).concat(element.value) : element.value;
return data;
},... | If you want to convert form data into json object, try the following
```
var formData = JSON.parse(JSON.stringify($('#frm').serializeArray()));
``` |
5,939,850 | I'm writing some shell scripts to check if I can manipulate information on a web server.
I use a bash shell script as a wrapper script to kick off multiple python scripts in sequential order
The wrapper script takes the web server's host name and user name and password. and after performing some tasks, hand's it to th... | 2011/05/09 | [
"https://Stackoverflow.com/questions/5939850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745512/"
] | Please try the following code.
```
<?php
$thumbnail_id = get_post_thumbnail_id(get_the_ID());
if (!empty($thumbnail_id))
{
$thumbnail = wp_get_attachment_image_src($thumbnail_id, 'full');
if (count ($thumbnail) >= 3)
{
$thumbnail_url = $thumbnail[0];
$thumbnail_width = $thumbnail[1];
$thumbnail_heigh... | What about putting a around that an setting the above code and then using CSS to set the width and height? Something like this:
**CSS**
```
.deals img {
width: 620px;
max-height: 295px;
}
```
**HTML / PHP**
```
<div class="deals"><?php the_post_thumbnail( array(620,295) ); ?></div>
``` |
49,809,680 | I'm extremely new to python, I've just got it set up on Visual Studio 2017CE version 15.6.6 on Windows 7 SP1 x64 Home Premium. I went through a couple of walk through tutorials and can verify that at the least Python is installed and working.
I'm trying to follow instructions from the MPIR documentations on building ... | 2018/04/13 | [
"https://Stackoverflow.com/questions/49809680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1757805/"
] | As Intel Core 2 Quad Q9650 is a Yorkfield core from the Penryn family,
18. core2\_penryn (x64)
should be fine. | And for the second part of your question, mpir\_config.py will generate 2 projects in the mpir-3.0.0\build.vc15 solution directory : one for the dynamic lib, and one for the static lib.
Just open mpir.sln and build the desired one. |
53,311,249 | I am reading a utf8 file with normal python text encoding. I also need to get rid of all the quotes in the file. However, the utf8 code has multiple types of quotes and I can't figure out how to get rid of all of them. The code below serves as an example of what I've been trying to do.
```
def change_things(string, re... | 2018/11/15 | [
"https://Stackoverflow.com/questions/53311249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10655038/"
] | You can just type those sorts of into your file, and replace them same as any other character.
```
utf8_quotes = "“”‘’‹›«»"
mystr = 'Text with “quotes”'
mystr.replace('“', '"').replace('”', '"')
```
There's a few different single quote variants too. | There's a list of unicode quote marks at <https://gist.github.com/goodmami/98b0a6e2237ced0025dd>. That should allow you to remove any type of quotes. |
53,311,249 | I am reading a utf8 file with normal python text encoding. I also need to get rid of all the quotes in the file. However, the utf8 code has multiple types of quotes and I can't figure out how to get rid of all of them. The code below serves as an example of what I've been trying to do.
```
def change_things(string, re... | 2018/11/15 | [
"https://Stackoverflow.com/questions/53311249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10655038/"
] | You can just type those sorts of into your file, and replace them same as any other character.
```
utf8_quotes = "“”‘’‹›«»"
mystr = 'Text with “quotes”'
mystr.replace('“', '"').replace('”', '"')
```
There's a few different single quote variants too. | There are multiple ways to do this, regex is one:
```
import re
newstr = re.sub(u'[\u201c\u201d\u2018\u2019]', '', oldstr)
```
Another clean way to do it is to use the [`Unidecode` package](https://pypi.python.org/pypi/Unidecode). This doesn't remove the quotes directly, but converts them to neutral quotes. It also ... |
72,148,172 | Is there a website or git repository where there is a clear listing of all the python packages and other dependencies installed on Google CoLaboratory? Is there a docker image that corresponds to a Google CoLab environment? | 2022/05/06 | [
"https://Stackoverflow.com/questions/72148172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3659451/"
] | I see your question is to view the already installed packages in google colab.
You can run this command for viewing it:
```
!pip list -v | grep [Kk]eras
```
You can also view all the packages, through this command:
```
!pip list -v
```
For more info, visit [this link](https://colab.research.google.com/github/avi... | You can find out about all the packages installed in Colab using
```
!pip list -v
```
Where it shows you the packages' names, versions, locations, and the installer. |
72,148,172 | Is there a website or git repository where there is a clear listing of all the python packages and other dependencies installed on Google CoLaboratory? Is there a docker image that corresponds to a Google CoLab environment? | 2022/05/06 | [
"https://Stackoverflow.com/questions/72148172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3659451/"
] | I see your question is to view the already installed packages in google colab.
You can run this command for viewing it:
```
!pip list -v | grep [Kk]eras
```
You can also view all the packages, through this command:
```
!pip list -v
```
For more info, visit [this link](https://colab.research.google.com/github/avi... | There is no clear listing of all the packages and dependencies installed on Google CoLaboratory. However, you can use the !pip freeze command to list all the packages that are currently installed in your environment.
The github repo for the Google CoLaboratory environment is here: [link](https://github.com/googlecolab... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.