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
20,795,230
I have blob representing webp image I want to be able to create an image from the blob using Wand and then convert it to jpeg. Is that possible with Wand or any other python library.
2013/12/27
[ "https://Stackoverflow.com/questions/20795230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2442744/" ]
Wand is a wrapper for imagemagick - in general, the file types that Wand supports are based on how imagemagick is configured on the system in question. For example, if you're on a mac using homebrew, it would need to be installed with: ``` brew install imagemagick --with-webp ```
Well I could not do it with Wand. I found another library [Pillow](https://pypi.python.org/pypi/Pillow/). I have a java script code that capture video frame from canvas and convert the webp imge from based64 to binary image and send it using web socket to a server on the server I construct the image and convert it fro...
1,243,418
I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways. ``` resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png ``` Is there a canonical way? On this site I see great examples fo...
2009/08/07
[ "https://Stackoverflow.com/questions/1243418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90025/" ]
Another solution in case you already use [GuzzleHttp](http://docs.guzzlephp.org/). This solution is based on an internal method of `GuzzleHttp\Client`. ```php use GuzzleHttp\Psr7\UriResolver; use GuzzleHttp\Psr7\Utils; function resolve(string $uri, ?string $base_uri): string { $uri = Utils::uriFor(trim($uri)); ...
If your have pecl-http, you can use <http://php.net/manual/en/function.http-build-url.php> ``` <?php $url_parts = parse_url($relative_url); $absolute = http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH); ``` Ex: ``` <?php function getAbsoluteURL($source_url, $relative_url) { $url_parts = parse_url($re...
1,243,418
I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways. ``` resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png ``` Is there a canonical way? On this site I see great examples fo...
2009/08/07
[ "https://Stackoverflow.com/questions/1243418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90025/" ]
If your have pecl-http, you can use <http://php.net/manual/en/function.http-build-url.php> ``` <?php $url_parts = parse_url($relative_url); $absolute = http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH); ``` Ex: ``` <?php function getAbsoluteURL($source_url, $relative_url) { $url_parts = parse_url($re...
Here is another function that can handle protocol relative urls ``` <?php function getAbsoluteURL($to, $from = null) { $arTarget = parse_url($to); $arSource = parse_url($from); $targetPath = isset($arTarget['path']) ? $arTarget['path'] : ''; if (isset($arTarget['host'])) { if (!isset($arTarget...
1,243,418
I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways. ``` resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png ``` Is there a canonical way? On this site I see great examples fo...
2009/08/07
[ "https://Stackoverflow.com/questions/1243418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90025/" ]
other tools that are already linked in page linked in pguardiario's comment: <http://publicmind.in/blog/urltoabsolute/> , <https://github.com/monkeysuffrage/phpuri> . and i have found other tool from comment in <http://nadeausoftware.com/articles/2008/05/php_tip_how_convert_relative_url_absolute_url> : ``` require_on...
I noticed the upvoted answer above uses RegEx, which can be dangerous when dealing with URLs. This function will resolve relative URLs to a *given* current page url in `$pgurl` **without regex**. It successfully resolves: `/home.php?example` types, same-dir `nextpage.php` types, `../...../.../parentdir` types, ful...
1,243,418
I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways. ``` resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png ``` Is there a canonical way? On this site I see great examples fo...
2009/08/07
[ "https://Stackoverflow.com/questions/1243418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90025/" ]
If your have pecl-http, you can use <http://php.net/manual/en/function.http-build-url.php> ``` <?php $url_parts = parse_url($relative_url); $absolute = http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH); ``` Ex: ``` <?php function getAbsoluteURL($source_url, $relative_url) { $url_parts = parse_url($re...
``` function absoluteUri($Path, $URI) { # Requires PHP4 or better. $URL = parse_url($URI); $Str = "{$URL['scheme']}://"; if (isset($URL['user']) || isset($URL['pass'])) $Str .= "{$URL['user']}:{$URL['pass']}@"; $Str .= $URL['host']; if (isset($URL['port'])) $Str .= ":{$URL['port...
1,243,418
I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways. ``` resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png ``` Is there a canonical way? On this site I see great examples fo...
2009/08/07
[ "https://Stackoverflow.com/questions/1243418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90025/" ]
Here is another function that can handle protocol relative urls ``` <?php function getAbsoluteURL($to, $from = null) { $arTarget = parse_url($to); $arSource = parse_url($from); $targetPath = isset($arTarget['path']) ? $arTarget['path'] : ''; if (isset($arTarget['host'])) { if (!isset($arTarget...
``` function absoluteUri($Path, $URI) { # Requires PHP4 or better. $URL = parse_url($URI); $Str = "{$URL['scheme']}://"; if (isset($URL['user']) || isset($URL['pass'])) $Str .= "{$URL['user']}:{$URL['pass']}@"; $Str .= $URL['host']; if (isset($URL['port'])) $Str .= ":{$URL['port...
1,243,418
I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways. ``` resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png ``` Is there a canonical way? On this site I see great examples fo...
2009/08/07
[ "https://Stackoverflow.com/questions/1243418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90025/" ]
If your have pecl-http, you can use <http://php.net/manual/en/function.http-build-url.php> ``` <?php $url_parts = parse_url($relative_url); $absolute = http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH); ``` Ex: ``` <?php function getAbsoluteURL($source_url, $relative_url) { $url_parts = parse_url($re...
I noticed the upvoted answer above uses RegEx, which can be dangerous when dealing with URLs. This function will resolve relative URLs to a *given* current page url in `$pgurl` **without regex**. It successfully resolves: `/home.php?example` types, same-dir `nextpage.php` types, `../...../.../parentdir` types, ful...
1,243,418
I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways. ``` resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png ``` Is there a canonical way? On this site I see great examples fo...
2009/08/07
[ "https://Stackoverflow.com/questions/1243418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90025/" ]
Perhaps this article could help? http:// nashruddin.com/PHP\_Script\_for\_Converting\_Relative\_to\_Absolute\_URL Edit: reproduced code below for convenience ``` <?php function rel2abs($rel, $base) { /* return if already absolute URL */ if (parse_url($rel, PHP_URL_SCHEME) != '' || substr($rel...
Here is another function that can handle protocol relative urls ``` <?php function getAbsoluteURL($to, $from = null) { $arTarget = parse_url($to); $arSource = parse_url($from); $targetPath = isset($arTarget['path']) ? $arTarget['path'] : ''; if (isset($arTarget['host'])) { if (!isset($arTarget...
1,243,418
I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways. ``` resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png ``` Is there a canonical way? On this site I see great examples fo...
2009/08/07
[ "https://Stackoverflow.com/questions/1243418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90025/" ]
Another solution in case you already use [GuzzleHttp](http://docs.guzzlephp.org/). This solution is based on an internal method of `GuzzleHttp\Client`. ```php use GuzzleHttp\Psr7\UriResolver; use GuzzleHttp\Psr7\Utils; function resolve(string $uri, ?string $base_uri): string { $uri = Utils::uriFor(trim($uri)); ...
other tools that are already linked in page linked in pguardiario's comment: <http://publicmind.in/blog/urltoabsolute/> , <https://github.com/monkeysuffrage/phpuri> . and i have found other tool from comment in <http://nadeausoftware.com/articles/2008/05/php_tip_how_convert_relative_url_absolute_url> : ``` require_on...
1,243,418
I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways. ``` resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png ``` Is there a canonical way? On this site I see great examples fo...
2009/08/07
[ "https://Stackoverflow.com/questions/1243418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90025/" ]
Perhaps this article could help? http:// nashruddin.com/PHP\_Script\_for\_Converting\_Relative\_to\_Absolute\_URL Edit: reproduced code below for convenience ``` <?php function rel2abs($rel, $base) { /* return if already absolute URL */ if (parse_url($rel, PHP_URL_SCHEME) != '' || substr($rel...
If your have pecl-http, you can use <http://php.net/manual/en/function.http-build-url.php> ``` <?php $url_parts = parse_url($relative_url); $absolute = http_build_url($source_url, $url_parts, HTTP_URL_JOIN_PATH); ``` Ex: ``` <?php function getAbsoluteURL($source_url, $relative_url) { $url_parts = parse_url($re...
1,243,418
I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways. ``` resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png ``` Is there a canonical way? On this site I see great examples fo...
2009/08/07
[ "https://Stackoverflow.com/questions/1243418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/90025/" ]
Perhaps this article could help? http:// nashruddin.com/PHP\_Script\_for\_Converting\_Relative\_to\_Absolute\_URL Edit: reproduced code below for convenience ``` <?php function rel2abs($rel, $base) { /* return if already absolute URL */ if (parse_url($rel, PHP_URL_SCHEME) != '' || substr($rel...
``` function absoluteUri($Path, $URI) { # Requires PHP4 or better. $URL = parse_url($URI); $Str = "{$URL['scheme']}://"; if (isset($URL['user']) || isset($URL['pass'])) $Str .= "{$URL['user']}:{$URL['pass']}@"; $Str .= $URL['host']; if (isset($URL['port'])) $Str .= ":{$URL['port...
45,952,387
I'm trying to follow along the [Audio Recognition Network](https://www.tensorflow.org/versions/master/tutorials/audio_recognition) tutorial. I've created an Anaconda environment with python 3.6 and followed the install instruction accordingly for installing the GPU whl. I can run the 'hello world' TF example. When I...
2017/08/30
[ "https://Stackoverflow.com/questions/45952387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194267/" ]
It looks like they're releasing the audio\_ops modules in version 1.4 (<https://github.com/tensorflow/tensorflow/issues/11339#issuecomment-327879009>). Until v1.4 is released, an easy way around this is to install the nightly tensorflow build ``` pip install tf-nightly ``` or with the docker image linked in the is...
The short answer: The framework is missing the "audio\_ops.py" and the example wont work until the file is released. Or you code the wrappers. More on this: If you go to the: tensorflow.contrib.framework.python.ops local folder you can find other \*\_ops.py files but not the "audio\_ops.py". If you get it from the ...
55,432,601
I have a string : `5kg`. I need to make the numerical and the textual parts apart. So, in this case, it should produce two parts : `5` and `kg`. For that I wrote a code: ``` grocery_uom = '5kg' unit_weight, uom = grocery_uom.split('[a-zA-Z]+', 1) print(unit_weight) ``` Getting this error: ``` -------------------...
2019/03/30
[ "https://Stackoverflow.com/questions/55432601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6528055/" ]
You don't want to split on the "kg", because that means it's not part of the actual data. Although looking at the docs, I see you can include them <https://docs.python.org/3/howto/regex.html> But the split pattern is intended to be a separater. Here's an example of just making a pattern for exactly what you want: ```...
\*updated to allow for bigger numbers, such as "1,000" Try this. ``` import re grocery_uom = '5kg' split_str = re.split(r'([0-9,?]+)([a-zA-Z]+)', grocery_uom, 1) unit_weight, uom = split_str[1:3] ## Output: 5 kg ```
55,432,601
I have a string : `5kg`. I need to make the numerical and the textual parts apart. So, in this case, it should produce two parts : `5` and `kg`. For that I wrote a code: ``` grocery_uom = '5kg' unit_weight, uom = grocery_uom.split('[a-zA-Z]+', 1) print(unit_weight) ``` Getting this error: ``` -------------------...
2019/03/30
[ "https://Stackoverflow.com/questions/55432601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6528055/" ]
You need to use regex split rather than simple string split and the precise pattern you are looking for splitting is this, ``` (?<=\d)(?=[a-zA-Z]+) ``` Basically the point where is preceded by digit, hence this regex `(?<=\d)` and followed by alphabets, hence this regex `(?=[a-zA-Z]+)` and it can be seen in this dem...
\*updated to allow for bigger numbers, such as "1,000" Try this. ``` import re grocery_uom = '5kg' split_str = re.split(r'([0-9,?]+)([a-zA-Z]+)', grocery_uom, 1) unit_weight, uom = split_str[1:3] ## Output: 5 kg ```
7,047,133
I wrote a test program that looked like this: ``` #!/usr/bin/python def incrementc(): c = c + 1 def main(): c = 5 incrementc() main() print c ``` I'd think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get ``` ...
2011/08/12
[ "https://Stackoverflow.com/questions/7047133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892549/" ]
You're thinking of [dynamic scoping](http://en.wikipedia.org/wiki/Dynamic_scoping#Dynamic_scoping). The problem with dynamic scoping is that the behavior of `incrementc` would depend on previous function calls, which makes it very difficult to reason about the code. Instead most programming languages (also Python) use ...
Global variables are bad. Just like friends and enemys. Keep your friends close but keep your enemys even closer. The function main last a local variable c, assignment the value 5 You then call the function inc..C. The c from main is now out of scope so you are trying to use a value of c that is not in scope - hence ...
7,047,133
I wrote a test program that looked like this: ``` #!/usr/bin/python def incrementc(): c = c + 1 def main(): c = 5 incrementc() main() print c ``` I'd think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get ``` ...
2011/08/12
[ "https://Stackoverflow.com/questions/7047133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892549/" ]
When a variable is assigned to in a scope, Python assumes it's local for the whole scope unless you tell it otherwise. So, to get this to work as you think it will, you need to use two `global` statements: ``` #!/usr/bin/python def incrementc(): global c c = c + 1 def main(): global c c = 5 increm...
Global variables are bad. Just like friends and enemys. Keep your friends close but keep your enemys even closer. The function main last a local variable c, assignment the value 5 You then call the function inc..C. The c from main is now out of scope so you are trying to use a value of c that is not in scope - hence ...
7,047,133
I wrote a test program that looked like this: ``` #!/usr/bin/python def incrementc(): c = c + 1 def main(): c = 5 incrementc() main() print c ``` I'd think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get ``` ...
2011/08/12
[ "https://Stackoverflow.com/questions/7047133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892549/" ]
The variable c isn't passing through because you do not hand any reference to c to the function incrementc. What you're looking at here are 3 scopes, the global scope and those within the functions main and incrementc. In main you've properly defined a variable c, but increment c has no knowledge of this - so attempti...
Global variables are bad. Just like friends and enemys. Keep your friends close but keep your enemys even closer. The function main last a local variable c, assignment the value 5 You then call the function inc..C. The c from main is now out of scope so you are trying to use a value of c that is not in scope - hence ...
7,047,133
I wrote a test program that looked like this: ``` #!/usr/bin/python def incrementc(): c = c + 1 def main(): c = 5 incrementc() main() print c ``` I'd think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get ``` ...
2011/08/12
[ "https://Stackoverflow.com/questions/7047133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892549/" ]
You're thinking of [dynamic scoping](http://en.wikipedia.org/wiki/Dynamic_scoping#Dynamic_scoping). The problem with dynamic scoping is that the behavior of `incrementc` would depend on previous function calls, which makes it very difficult to reason about the code. Instead most programming languages (also Python) use ...
When a variable is assigned to in a scope, Python assumes it's local for the whole scope unless you tell it otherwise. So, to get this to work as you think it will, you need to use two `global` statements: ``` #!/usr/bin/python def incrementc(): global c c = c + 1 def main(): global c c = 5 increm...
7,047,133
I wrote a test program that looked like this: ``` #!/usr/bin/python def incrementc(): c = c + 1 def main(): c = 5 incrementc() main() print c ``` I'd think that since I called incrementc within the body of main, all variables from main would pass to incrementc. But when I run this program I get ``` ...
2011/08/12
[ "https://Stackoverflow.com/questions/7047133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/892549/" ]
You're thinking of [dynamic scoping](http://en.wikipedia.org/wiki/Dynamic_scoping#Dynamic_scoping). The problem with dynamic scoping is that the behavior of `incrementc` would depend on previous function calls, which makes it very difficult to reason about the code. Instead most programming languages (also Python) use ...
The variable c isn't passing through because you do not hand any reference to c to the function incrementc. What you're looking at here are 3 scopes, the global scope and those within the functions main and incrementc. In main you've properly defined a variable c, but increment c has no knowledge of this - so attempti...
14,716,111
I'd like to rename `%paste` to something like `%pp` so that it takes fewer keystrokes. I worked out a way to do that but it seems complicated. Is there a better way? ``` def foo(self, bar): get_ipython().magic("paste") get_ipython().define_magic('pp', foo) ```
2013/02/05
[ "https://Stackoverflow.com/questions/14716111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/461389/" ]
From IPython 0.13, there's a new `%alias_magic` magic function, which you would use as: ``` %alias_magic pp paste ```
use `%alias` magic to do it (if you want it to be permanent use `%store`): ``` In [8]: %alias?? """Define an alias for a system command. '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' ... ```
52,601,350
I'm trying to make a minesweeper game using lists in python. I have have this code so far: ``` import random as r import sys #dimension of board and number of bombs width = int(sys.argv[1]) height = int(sys.argv[2]) b = int(sys.argv[3]) #creates the board board = [[0.0] * width] * height #places bombs for i in rang...
2018/10/02
[ "https://Stackoverflow.com/questions/52601350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10173748/" ]
You can just use `board[x][y] = 0.1` to access index `y` in row `x` of your board. Also, you don't want to build a board like that. The way you're doing it will only actually create 1 array with numbers. Here's your code with some modifications. ``` import random as r # dimension of board and number of bombs # (I'm u...
We are dealing list of list. If we run your board initialization code and modify board value as follows: ``` >>> width = 2; height = 3 >>> board = [[0.0] * width] * height >>> print board [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]] >>> x = 0; y = 1; board[y][x] = 1.1 >>> print board [[1.1, 0.0], [1.1, 0.0], [1.1, 0.0]] ``` ...
52,601,350
I'm trying to make a minesweeper game using lists in python. I have have this code so far: ``` import random as r import sys #dimension of board and number of bombs width = int(sys.argv[1]) height = int(sys.argv[2]) b = int(sys.argv[3]) #creates the board board = [[0.0] * width] * height #places bombs for i in rang...
2018/10/02
[ "https://Stackoverflow.com/questions/52601350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10173748/" ]
Use assignment instead of insert: `board[x][y] = 0.1`. Also, be careful initializing your 2D board. `board = [[0.0] * width] * height` will make one list of size `width` and then will copy pointers to that list for all of the `height` i.e. if you assign 0.1 to the first cell in the first row `board[0][0]` the first it...
We are dealing list of list. If we run your board initialization code and modify board value as follows: ``` >>> width = 2; height = 3 >>> board = [[0.0] * width] * height >>> print board [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]] >>> x = 0; y = 1; board[y][x] = 1.1 >>> print board [[1.1, 0.0], [1.1, 0.0], [1.1, 0.0]] ``` ...
59,661,745
I have pytest-django == 2.9.1 installed I started setting up a test environment according to the instructions. <https://pytest-django.readthedocs.io/en/latest/tutorial.html#step-2-point-pytest-to-your-django-settings> In the second step, in the root of the project, I created a pytest.ini file and added DJANGO\_SETTING...
2020/01/09
[ "https://Stackoverflow.com/questions/59661745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7526559/" ]
had the same issue, there were 2 problems: 1. settings.py had a bug. 2. pytest-django was installed in a different environment. So ensure you can import settings.py as hoefling recommended, and ensure pytest-django is actually installed in your environment
So the [docs](https://pytest-django.readthedocs.io/en/latest/configuring_django.html#order-of-choosing-settings) say that the order of precedence when choosing setting is command line environment variable pytest.ini file. Then it goes further to say you can override this precedence using `addopts`. In my case, I spec...
53,686,556
I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit: ``` model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', ...
2018/12/08
[ "https://Stackoverflow.com/questions/53686556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10754618/" ]
Please note that in almost all scenarios you just have to handle the `catch` and not bother with the validity of the `ObjectID` since mongoose would complain `throw` if invalid `ObjectId` is provided. ``` Model.findOne({ _id: 'abcd' }).exec().catch(error => console.error('error', error)); ``` Other than that you cou...
``` let mongoose = require('mongoose'); let ObjectId = mongoose.Types.ObjectId; let recId1 = "621f1d71aec9313aa2b9074c"; let isValid1 = ObjectId.isValid(recId1); //true console.log("isValid1 = ", isValid1); //true let recId2 = "621f1d71aec9313aa2b9074cd"; let isValid2 = ObjectId.isValid(recId2); //false console.l...
53,686,556
I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit: ``` model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', ...
2018/12/08
[ "https://Stackoverflow.com/questions/53686556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10754618/" ]
@mickl's Answer will be failed for the strings with the length of 12. You should convert any given string to **`MongoDB`** **`ObjectId`** using **`ObjectId`** constructor in **`mongodb`** and then cast it to a string and the check again with the original one. It should be the same. ``` import { ObjectId } from 'mon...
``` let mongoose = require('mongoose'); let ObjectId = mongoose.Types.ObjectId; let recId1 = "621f1d71aec9313aa2b9074c"; let isValid1 = ObjectId.isValid(recId1); //true console.log("isValid1 = ", isValid1); //true let recId2 = "621f1d71aec9313aa2b9074cd"; let isValid2 = ObjectId.isValid(recId2); //false console.l...
53,686,556
I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit: ``` model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', ...
2018/12/08
[ "https://Stackoverflow.com/questions/53686556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10754618/" ]
You can use [.isValid()](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) method on ObjectId, try in mongoose: ``` var mongoose = require('mongoose'); var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true ```
@mickl's Answer will be failed for the strings with the length of 12. You should convert any given string to **`MongoDB`** **`ObjectId`** using **`ObjectId`** constructor in **`mongodb`** and then cast it to a string and the check again with the original one. It should be the same. ``` import { ObjectId } from 'mon...
53,686,556
I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit: ``` model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', ...
2018/12/08
[ "https://Stackoverflow.com/questions/53686556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10754618/" ]
Please note that in almost all scenarios you just have to handle the `catch` and not bother with the validity of the `ObjectID` since mongoose would complain `throw` if invalid `ObjectId` is provided. ``` Model.findOne({ _id: 'abcd' }).exec().catch(error => console.error('error', error)); ``` Other than that you cou...
If you use **Joi** for validating, you can include validation directly in your **Joi schemas**, using **[joi-objectid](https://github.com/pebble/joi-objectid)**: Install joi-objectid: `$ npm i joi-objectid` Define the function to use globally (with Joi already imported): ``` Joi.objectId = require('joi-objectid')(Jo...
53,686,556
I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit: ``` model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', ...
2018/12/08
[ "https://Stackoverflow.com/questions/53686556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10754618/" ]
Please note that in almost all scenarios you just have to handle the `catch` and not bother with the validity of the `ObjectID` since mongoose would complain `throw` if invalid `ObjectId` is provided. ``` Model.findOne({ _id: 'abcd' }).exec().catch(error => console.error('error', error)); ``` Other than that you cou...
@mickl's Answer will be failed for the strings with the length of 12. You should convert any given string to **`MongoDB`** **`ObjectId`** using **`ObjectId`** constructor in **`mongodb`** and then cast it to a string and the check again with the original one. It should be the same. ``` import { ObjectId } from 'mon...
53,686,556
I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit: ``` model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', ...
2018/12/08
[ "https://Stackoverflow.com/questions/53686556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10754618/" ]
You can use [.isValid()](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) method on ObjectId, try in mongoose: ``` var mongoose = require('mongoose'); var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true ```
Please note that in almost all scenarios you just have to handle the `catch` and not bother with the validity of the `ObjectID` since mongoose would complain `throw` if invalid `ObjectId` is provided. ``` Model.findOne({ _id: 'abcd' }).exec().catch(error => console.error('error', error)); ``` Other than that you cou...
53,686,556
I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit: ``` model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', ...
2018/12/08
[ "https://Stackoverflow.com/questions/53686556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10754618/" ]
@mickl's Answer will be failed for the strings with the length of 12. You should convert any given string to **`MongoDB`** **`ObjectId`** using **`ObjectId`** constructor in **`mongodb`** and then cast it to a string and the check again with the original one. It should be the same. ``` import { ObjectId } from 'mon...
If you use **Joi** for validating, you can include validation directly in your **Joi schemas**, using **[joi-objectid](https://github.com/pebble/joi-objectid)**: Install joi-objectid: `$ npm i joi-objectid` Define the function to use globally (with Joi already imported): ``` Joi.objectId = require('joi-objectid')(Jo...
53,686,556
I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit: ``` model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', ...
2018/12/08
[ "https://Stackoverflow.com/questions/53686556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10754618/" ]
You can use [.isValid()](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) method on ObjectId, try in mongoose: ``` var mongoose = require('mongoose'); var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true ```
The API provided ([Mongoose.prototype.isValidObjectId()](https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-isValidObjectId) and for newer versions and ) returns true for random strings like `Manajemenfs2`. With mongoose this is how I ended up doing it: ``` import mongoose from 'mongoose'; const isValid...
53,686,556
I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit: ``` model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', ...
2018/12/08
[ "https://Stackoverflow.com/questions/53686556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10754618/" ]
@mickl's Answer will be failed for the strings with the length of 12. You should convert any given string to **`MongoDB`** **`ObjectId`** using **`ObjectId`** constructor in **`mongodb`** and then cast it to a string and the check again with the original one. It should be the same. ``` import { ObjectId } from 'mon...
The API provided ([Mongoose.prototype.isValidObjectId()](https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-isValidObjectId) and for newer versions and ) returns true for random strings like `Manajemenfs2`. With mongoose this is how I ended up doing it: ``` import mongoose from 'mongoose'; const isValid...
53,686,556
I'm trying to prepare a model that takes an input image of shape 56x56 pixels and 3 channels: (56, 56, 3). Output should be an array of 216 numbers. I reuse a code from a digit recognizer and modified it a little bit: ``` model = Sequential() model.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', ...
2018/12/08
[ "https://Stackoverflow.com/questions/53686556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10754618/" ]
You can use [.isValid()](https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html#objectid-isvalid) method on ObjectId, try in mongoose: ``` var mongoose = require('mongoose'); var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true ```
If you use **Joi** for validating, you can include validation directly in your **Joi schemas**, using **[joi-objectid](https://github.com/pebble/joi-objectid)**: Install joi-objectid: `$ npm i joi-objectid` Define the function to use globally (with Joi already imported): ``` Joi.objectId = require('joi-objectid')(Jo...
48,836,596
I stumbled upon the following syntax in [Python decorator to keep signature and user defined attribute](https://stackoverflow.com/questions/48746567/python-decorator-to-keep-signature-and-user-defined-attribute): ``` > def func(): ... return "Hello World!" ... > func? Signature: func() Docstring: <no docstring> Fi...
2018/02/17
[ "https://Stackoverflow.com/questions/48836596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5079316/" ]
Check if you have added the below detail in your settings file. If yes, then skip this part. **settings.py** ``` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], # Add this to your settings file 'APP_DIRS': True, ...
From Django Docs: Additional form template furniture Don’t forget that a form’s output does not include the surrounding tags, or the form’s submit control. You will have to provide these yourself. <https://docs.djangoproject.com/en/2.0/topics/forms/> You are missing the input with type submit: ``` <input type="sub...
71,215,277
I have been working on writing a Wordle bot, and wanted to see how it preforms with all 13,000 words. The problem is that I am running this through a for loop and it is very inefficient. After running it for 30 minutes, it only gets to around 5%. I could wait all that time, but it would end up being 10+ hours. There ha...
2022/02/22
[ "https://Stackoverflow.com/questions/71215277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18257273/" ]
The performance problems can be massively reduced by using [sets](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset). Any time that you want to repeatedly test for membership (even only a few times), e.g. `if x not in removed`, you want to try to make a set. Lists require checking every element to...
I just wrote a wordle bot that runs in about a second including the web scraping to fetch a list of 5 letter words. ``` import urllib.request from bs4 import BeautifulSoup def getwords(): source = "https://www.thefreedictionary.com/5-letter-words.htm" filehandle = urllib.request.urlopen(source) soup = Bea...
27,935,800
I have been on this for days now. Everytime I attempt to install psycopg2 into a virtual environment on my RHEL VPS it fails with the following error. Anyone with a clue should please help out. Thanks. ``` (pyenv)[root@10 pyenv]# pip install psycopg2==2.5.4 Collecting psycopg2==2.5.4 Using cached psycopg2-2.5.4.tar...
2015/01/14
[ "https://Stackoverflow.com/questions/27935800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669337/" ]
I found my way around it. I noticed it installs successfully globally. So I installed psycopg2 globally and created a new virtual environment with `--system-site-packages` option. Then I installed my other packages using the `-I` option. Hope this helps someone else. OK. I later found out that I had no `gcc` installe...
For me, I'm using Redhat 8 enterprise and my issue wasn't solved by installing gcc and gcc-c++. I was able to solve the issue by installing **python3-devel** and **development tools**. to install them on Redhat using yum manager, please follow this [link](https://linuxize.com/post/how-to-install-pip-on-centos-8/)
30,445,136
I am using z3py. I am trying to check the satisfiability for different problems with different sizes and verify the scalability of the proposed method. However, to do that I need to know the memory consumed by the solver for each problem. Is there a way to access the memory or make the z3py print it in the STATISTICS s...
2015/05/25
[ "https://Stackoverflow.com/questions/30445136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4343141/" ]
You should use `getIntent().getIntExtra(name, defaultValue)` instead of `Integer.parseInt(intent.getStringExtra("page"));` **Update:** ``` int defaultValue = -1;// take any default value of your choice String name = intent.getStringExtra("name"); int page1 = intent.getIntExtra("page", defaultValue); ```
Activity A ``` String textname = (String) dataItem.get("name"); Intent m = new Intent(list.this,main.class); m.putExtra("name",textname); m.putExtra("page",1); startActivity(m); ``` Activity B ``` Intent intent = getIntent(); name = intent.getStringExtra("name"); int page...
30,445,136
I am using z3py. I am trying to check the satisfiability for different problems with different sizes and verify the scalability of the proposed method. However, to do that I need to know the memory consumed by the solver for each problem. Is there a way to access the memory or make the z3py print it in the STATISTICS s...
2015/05/25
[ "https://Stackoverflow.com/questions/30445136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4343141/" ]
You should use `getIntent().getIntExtra(name, defaultValue)` instead of `Integer.parseInt(intent.getStringExtra("page"));` **Update:** ``` int defaultValue = -1;// take any default value of your choice String name = intent.getStringExtra("name"); int page1 = intent.getIntExtra("page", defaultValue); ```
I in other class use the main class and send parameter to it and it work without any problem but just in list class i have problem in other class i like this send parameter ``` protected void onListItemClick(ListView l, View v, int position, long id) { Intent i = new Intent(list_sub.this,main.class); i.putExt...
30,445,136
I am using z3py. I am trying to check the satisfiability for different problems with different sizes and verify the scalability of the proposed method. However, to do that I need to know the memory consumed by the solver for each problem. Is there a way to access the memory or make the z3py print it in the STATISTICS s...
2015/05/25
[ "https://Stackoverflow.com/questions/30445136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4343141/" ]
I in other class use the main class and send parameter to it and it work without any problem but just in list class i have problem in other class i like this send parameter ``` protected void onListItemClick(ListView l, View v, int position, long id) { Intent i = new Intent(list_sub.this,main.class); i.putExt...
Activity A ``` String textname = (String) dataItem.get("name"); Intent m = new Intent(list.this,main.class); m.putExtra("name",textname); m.putExtra("page",1); startActivity(m); ``` Activity B ``` Intent intent = getIntent(); name = intent.getStringExtra("name"); int page...
66,472,929
i try to learn better dict in python. I am using an api "chess.com" ``` data = get_player_game_archives(username).json url = data['archives'][-1] games = requests.get(url).json() game = games['games'][-1] print(games) ``` That's my code and they are no problem and the result is ``` {'games': [{'u...
2021/03/04
[ "https://Stackoverflow.com/questions/66472929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13934941/" ]
According to the [SQL Server docs](https://learn.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql?view=sql-server-ver15), `CHARINDEX` will find the index of the *first* occurrence of the first parameter substring. As for `LIKE` it is highly likely that it is smart enough to stop searching as soon as it fi...
I know this has been answered but it's worth noting that you can create a test harness and see for yourself. I created a 1,000,000 row test; first against a shorter string then against a longer one. ``` SELECT TOP(1000000) SomeCol = NEWID() INTO #t FROM sys.all_columns, sys.all_columns a; DECLARE @x INT, @st DATETIME...
56,337,696
I have this abstract class ``` class Kuku(ABC): def __init__(self): self.a = 4 @property @abstractmethod def kaka(self): pass ``` `kaka` is an abstract property, So I would expect python to enforce it being a property in inheritors, But it allows me to create: ``` class KukuCh...
2019/05/28
[ "https://Stackoverflow.com/questions/56337696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2899096/" ]
I've come across this problem myself, after looking into the options of how to enforce such behaviour I came up with the idea of implementing a class that has that type checking. ``` import abc import inspect from typing import Generic, Set, TypeVar, get_type_hints T = TypeVar('T') class AbstractClassVar(Generic[T])...
You are overriding the `kaka` property in the child class. You must also use `@property` to decorate the overridden methods in the child: ``` from abc import ABC, abstractmethod class Kuku(ABC): def __init__(self): self.a = 4 @property @abstractmethod def kaka(self): pass class...
44,825,529
I am looking for a piece of software (python preferred, but really anything for which a jupyter kernel exists) to fit a data sample to a mixture of t-distributions. I searched quite a while already and it seems to be that this is a somehwat obscure endeavor as most search results turn up for mixture of gaussians (what...
2017/06/29
[ "https://Stackoverflow.com/questions/44825529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1639834/" ]
This seems to work (in R): Simulate example: ``` set.seed(101) x <- c(5+ 3*rt(1000,df=5), 10+1*rt(10000,df=20)) ``` Fit: ``` library(teigen) tt <- teigen(x, Gs=2, # two components scale=FALSE,dfupdate="numeric", models=c("univUU") # univariate model, unconstrained scale and d...
Late to this party but since you prefer something for Python, there appear to be several packages out there on pypi that fit finite Student's t mixtures, including: <https://pypi.org/project/studenttmixture/> <https://pypi.org/project/student-mixture/> <https://pypi.org/project/smm/> so all of these can be installe...
8,251,039
I am currently writing a script where I want to take the data and write it to a spreadsheet. I've found a few modules for writing xls files, however those only seem to work up to python 2.x, and I'm using 3.2 (also on a mac if that's helpful). Anyone have any ideas on how to get a python3.2 script to output to a spread...
2011/11/24
[ "https://Stackoverflow.com/questions/8251039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242191/" ]
Use the **[csv](http://docs.python.org/release/3.0.1/library/csv.html)** module. The intro from the docs: > > The csv module implements classes to read and write tabular data in > CSV format. It allows programmers to say, “write this data in the > format preferred by Excel,” or “read data from this file which was >...
On Windows, you can use the COM interface: <http://users.rcn.com/python/download/quoter.pyw> As @sdolan pointed out, CSV can be a good choice if your data is laid out in a tabular format. Since Excel can save spreadsheets in an XML format, you can use XML tools to access the data.
19,485,233
I am complete newb at python :P. How can I return just the third word of a string using string slicing? Am I close with: ``` splitString = myString.split() print splitString[2] ```
2013/10/21
[ "https://Stackoverflow.com/questions/19485233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2517330/" ]
``` for (int i = 0; i < 5; i++){ int asciiVal = rand()%26 + 97; char asciiChar = asciiVal; cout << asciiChar << " and "; } ```
To convert an `int` ASCII value to character you can also use: ``` int asciiValue = 65; char character = char(asciiValue); cout << character; // output: A cout << char(90); // output: Z ```
19,485,233
I am complete newb at python :P. How can I return just the third word of a string using string slicing? Am I close with: ``` splitString = myString.split() print splitString[2] ```
2013/10/21
[ "https://Stackoverflow.com/questions/19485233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2517330/" ]
``` for (int i = 0; i < 5; i++){ int asciiVal = rand()%26 + 97; char asciiChar = asciiVal; cout << asciiChar << " and "; } ```
``` int main() { int v1, v2, v3, v4, v5,v6,v7; cout << "Enter 7 vals "; cin >> v1 >> v2 >> v3 >> v4 >> v5 >> v6 >> v7; cout << "The phrase is " << char(v1) << char(v2) << " " << char(v3) << " " << char(v4) << char(v5) << char(v6) <<...
19,485,233
I am complete newb at python :P. How can I return just the third word of a string using string slicing? Am I close with: ``` splitString = myString.split() print splitString[2] ```
2013/10/21
[ "https://Stackoverflow.com/questions/19485233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2517330/" ]
To convert an `int` ASCII value to character you can also use: ``` int asciiValue = 65; char character = char(asciiValue); cout << character; // output: A cout << char(90); // output: Z ```
``` int main() { int v1, v2, v3, v4, v5,v6,v7; cout << "Enter 7 vals "; cin >> v1 >> v2 >> v3 >> v4 >> v5 >> v6 >> v7; cout << "The phrase is " << char(v1) << char(v2) << " " << char(v3) << " " << char(v4) << char(v5) << char(v6) <<...
11,296,768
Ok so I got python to run in command prompt I just can't figure out the syntax to call scripts from it. So my file is in c:\python\script so I've been calling like this; ``` "C:\Python\Script" ``` but it doesn't anything and returns ``` ""File<stdin>", line 1" ```
2012/07/02
[ "https://Stackoverflow.com/questions/11296768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1469751/" ]
Is it possible that the connections in question are being intercepted by an enterprise proxy like [bluecoat](http://www.bluecoat.com/) or [websense](http://www.websense.com/) that's middling the SSL session?
Altering the certificate would break its signature, and as your validation shows that something alters the certificate, you should look at *what* changes the certificate, not "how" it's done. The change is simple - as the certificate is self-signed, someone can just create another self-signed certificate with his own...
61,335,488
I'm using a Nodejs server for a WebApp and Mongoose is acting as the ORM. I've got some hooks that fire when data is inserted into a certain collection. I want those hooks to fire when a python script inserts into the mongoDB instance. So if I have a pre save hook, it would modify the python scripts insert according ...
2020/04/21
[ "https://Stackoverflow.com/questions/61335488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11370450/" ]
It is impossible because python and nodejs are 2 different runtimes - separate isolated processes which don't have access to each other memories. Mongoose is a nodejs ORM - a library that maps Javascript objects to Mongodb documents and handles queries to the database. All mongoose hooks belong to javascript space. T...
Mongo itself does not support hooks as a feature, `mongoose` gives you out of the box hooks you can use as you've mentioned. So what can you do to make it work in python? 1. Use an existing framework like python's [eve](https://docs.python-eve.org/en/stable/features.html#insert-events), eve gives you database hooks, m...
57,396,394
I have two dataframes, one bigger, with names and family names, defined as a multi-index (Family and name) dataframe: ``` Age Weight Family Name Marge SIMPSON Bart Lisa Homer Harry POTTER Lilian Lisa James ``` And the another df is sm...
2019/08/07
[ "https://Stackoverflow.com/questions/57396394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9975452/" ]
Your `df1` have multiple index , so normal filter will not work , we can try `reindex` ``` df1 = df1.reindex(pd.MultiIndex.from_frame(df2)) ```
Let `df1` be the bigger dataframe with `MutiIndex` and `df2` smaller one with names. Then you could do something like this: ``` names = set(df2.Name.astype(str).values) df1 = df1.loc[df1.index.get_level_values('Name').isin(names)] ```
57,396,394
I have two dataframes, one bigger, with names and family names, defined as a multi-index (Family and name) dataframe: ``` Age Weight Family Name Marge SIMPSON Bart Lisa Homer Harry POTTER Lilian Lisa James ``` And the another df is sm...
2019/08/07
[ "https://Stackoverflow.com/questions/57396394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9975452/" ]
### `join` ``` df2.join(df1, on=df1.index.names).set_index(df1.index.names) Age Weight Family Name SIMPSON Lisa NaN NaN Bart NaN NaN POTTER Lisa NaN NaN ``` --- ### `merge` ``` df1.merge(df2, on=df1.index.names).set_index(df1.index.names) Age Weight ...
Your `df1` have multiple index , so normal filter will not work , we can try `reindex` ``` df1 = df1.reindex(pd.MultiIndex.from_frame(df2)) ```
57,396,394
I have two dataframes, one bigger, with names and family names, defined as a multi-index (Family and name) dataframe: ``` Age Weight Family Name Marge SIMPSON Bart Lisa Homer Harry POTTER Lilian Lisa James ``` And the another df is sm...
2019/08/07
[ "https://Stackoverflow.com/questions/57396394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9975452/" ]
### `join` ``` df2.join(df1, on=df1.index.names).set_index(df1.index.names) Age Weight Family Name SIMPSON Lisa NaN NaN Bart NaN NaN POTTER Lisa NaN NaN ``` --- ### `merge` ``` df1.merge(df2, on=df1.index.names).set_index(df1.index.names) Age Weight ...
Let `df1` be the bigger dataframe with `MutiIndex` and `df2` smaller one with names. Then you could do something like this: ``` names = set(df2.Name.astype(str).values) df1 = df1.loc[df1.index.get_level_values('Name').isin(names)] ```
32,667,047
I want to program the following (I've just start to learn python): ``` f[i]:=f[i-1]-(1/n)*(1-(1-f[i-1])^n)-(1/n)*(f[i-1])^n+(2*f[0]/n); ``` with `F[0]=x`, `x` belongs to `[0,1]` and `n` a constant integer. My try: ``` import pylab as pl import numpy as np N=20 n=100 h=0.01 T=np.arange(0, 1+h, h) def f(i): if i...
2015/09/19
[ "https://Stackoverflow.com/questions/32667047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5353182/" ]
You calculate `f(i-1)` three times in a single recursion layer - so after the first run you "know" the answer but still calculate it two more times. A naive approach: ``` fi_1 = f(i-1) return fi_1-(1./n)*(1-(1-fi_1)**n)-(1./n)*(fi_1)**n+2.*T/n ``` But of course we can still do better and cache **every** evaluation ...
First of all you are calculating f[i-1] three times when you can save it's result in some variable and calculate it only once : ``` t = f(i-1) return t-(1./n)*(1-(1-t)**n)-(1./n)*(t)**n+2.*T/n ``` It will increase the speed of the program, but I would also like to recommend to calculate f without using recursion. ...
32,667,047
I want to program the following (I've just start to learn python): ``` f[i]:=f[i-1]-(1/n)*(1-(1-f[i-1])^n)-(1/n)*(f[i-1])^n+(2*f[0]/n); ``` with `F[0]=x`, `x` belongs to `[0,1]` and `n` a constant integer. My try: ``` import pylab as pl import numpy as np N=20 n=100 h=0.01 T=np.arange(0, 1+h, h) def f(i): if i...
2015/09/19
[ "https://Stackoverflow.com/questions/32667047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5353182/" ]
The reason why your run time is so slow is the fact that, like the simplistic calculation of the nth fibonacci number it runs in **exponential time** (in this case 3^n). To see this, before F[i] can return it's value, it has to call f[i-1] 3 times, but then each of *those* has to call F[i-2] 3 times (3\*3 calls), and t...
First of all you are calculating f[i-1] three times when you can save it's result in some variable and calculate it only once : ``` t = f(i-1) return t-(1./n)*(1-(1-t)**n)-(1./n)*(t)**n+2.*T/n ``` It will increase the speed of the program, but I would also like to recommend to calculate f without using recursion. ...
52,297,298
i'm facing some issues while trying to fetch a bulk mail via python wincom32.client. Basically, it seems like there's a limit on the number of items that could be opened on a single session, and that is a server-side flag or status.. the problem is that i didn't find out any way to resume/close/re-set and i can't ask ...
2018/09/12
[ "https://Stackoverflow.com/questions/52297298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8979081/" ]
the problem was due to using dictionary to store message data held somehow a reference to it, without letting the resource to be released, even if an explicit `m.Close(0)` was invoked. I've replaced them all with a `"dictkey" : str(m.<field>)` call and the error does not show up anymore.
You keep *all* items in a folder open - that is a really bad idea. Store only the entry ids, and reopen the messages on demand using `Namespace.GetItemFromID`. As soon as you are done with the item, release it.
52,297,298
i'm facing some issues while trying to fetch a bulk mail via python wincom32.client. Basically, it seems like there's a limit on the number of items that could be opened on a single session, and that is a server-side flag or status.. the problem is that i didn't find out any way to resume/close/re-set and i can't ask ...
2018/09/12
[ "https://Stackoverflow.com/questions/52297298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8979081/" ]
First of all thanks Equinox23 for your answer. Just wanted to add few more points to it. The same thing happened for me while accessing bundles of outlook emails. Consider `list1` and `list2`, for every iteration I get the output `list1` and finally, append it to `list2` and reset the list1. After 230+ iterations, I ...
You keep *all* items in a folder open - that is a really bad idea. Store only the entry ids, and reopen the messages on demand using `Namespace.GetItemFromID`. As soon as you are done with the item, release it.
52,297,298
i'm facing some issues while trying to fetch a bulk mail via python wincom32.client. Basically, it seems like there's a limit on the number of items that could be opened on a single session, and that is a server-side flag or status.. the problem is that i didn't find out any way to resume/close/re-set and i can't ask ...
2018/09/12
[ "https://Stackoverflow.com/questions/52297298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8979081/" ]
the problem was due to using dictionary to store message data held somehow a reference to it, without letting the resource to be released, even if an explicit `m.Close(0)` was invoked. I've replaced them all with a `"dictkey" : str(m.<field>)` call and the error does not show up anymore.
First of all thanks Equinox23 for your answer. Just wanted to add few more points to it. The same thing happened for me while accessing bundles of outlook emails. Consider `list1` and `list2`, for every iteration I get the output `list1` and finally, append it to `list2` and reset the list1. After 230+ iterations, I ...
11,632,905
> > **Possible Duplicate:** > > [Inverse dictionary lookup - Python](https://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-python) > > [reverse mapping of dictionary with Python](https://stackoverflow.com/questions/3221475/reverse-mapping-of-dictionary-with-python) > > > How do i get key of ...
2012/07/24
[ "https://Stackoverflow.com/questions/11632905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1485698/" ]
Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value. You can only do this in a loop: ``` [k for (k, v) in i.iteritems() if v == 0] ``` Note that there can be more than one key per value in a dict; `{'a': 0, 'b': 0}` is perfectly legal. If you want ordering you ...
By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. [Python Ordered Dictionary](http://docs.python.org/library/collections.html)
11,632,905
> > **Possible Duplicate:** > > [Inverse dictionary lookup - Python](https://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-python) > > [reverse mapping of dictionary with Python](https://stackoverflow.com/questions/3221475/reverse-mapping-of-dictionary-with-python) > > > How do i get key of ...
2012/07/24
[ "https://Stackoverflow.com/questions/11632905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1485698/" ]
You *could* do something like this: ``` i={'foo':'bar', 'baz':'huh?'} keys=i.keys() #in python 3, you'll need `list(i.keys())` values=i.values() print keys[values.index("bar")] #'foo' ``` However, any time you change your dictionary, you'll need to update your keys,values because **dictionaries are not ordered in ...
By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. [Python Ordered Dictionary](http://docs.python.org/library/collections.html)
11,632,905
> > **Possible Duplicate:** > > [Inverse dictionary lookup - Python](https://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-python) > > [reverse mapping of dictionary with Python](https://stackoverflow.com/questions/3221475/reverse-mapping-of-dictionary-with-python) > > > How do i get key of ...
2012/07/24
[ "https://Stackoverflow.com/questions/11632905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1485698/" ]
You *could* do something like this: ``` i={'foo':'bar', 'baz':'huh?'} keys=i.keys() #in python 3, you'll need `list(i.keys())` values=i.values() print keys[values.index("bar")] #'foo' ``` However, any time you change your dictionary, you'll need to update your keys,values because **dictionaries are not ordered in ...
Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value. You can only do this in a loop: ``` [k for (k, v) in i.iteritems() if v == 0] ``` Note that there can be more than one key per value in a dict; `{'a': 0, 'b': 0}` is perfectly legal. If you want ordering you ...
56,191,147
Im trying to extract user identities from a smartcard, and I need to match this pattern: `CN=LAST.FIRST.MIDDLE.0000000000` And have this result returned: `FIRST.LAST` This would normaly be easy if I were doing this in my own code: ``` # python example string = 'CN=LAST.FIRST.MIDDLE.000000000' pattern = 'CN=(\w+)\.(\...
2019/05/17
[ "https://Stackoverflow.com/questions/56191147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5357869/" ]
I don't think this is possible with just one capturing group. If I read the documentation of keycloak correctly, the capturing group is actually the result of the regular expression. So you can either match FIRST or LAST or both in the original order, but not reorder.
Yes, it is possible. This expression might help you to do so: ``` CN=([A-Z]+)\.(([A-Z]+)+)\.([A-Z]+)\.([0-9]+) ``` ### [Demo](https://regex101.com/r/iosym4/1) [![enter image description here](https://i.stack.imgur.com/69QLP.png)](https://i.stack.imgur.com/69QLP.png) ### RegEx If this wasn't your desired expressi...
54,604,608
I have about 30 SEM (scanning-electron microscope) images like that: [![enter image description here](https://i.stack.imgur.com/uFHNf.png)](https://i.stack.imgur.com/uFHNf.png) What you see is photoresist pillars on a glass substrate. What I would like to do, is to get the mean diameter in x and y-direction as well ...
2019/02/09
[ "https://Stackoverflow.com/questions/54604608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I rarely find Hough useful for realworld applications, thus I'd rather follow the path of denoising, segmentation and ellipse fit. For the denoising, one selects the non local means (NLM). For the segmentation --- just looking at the image --- I came up with a Gaussian mixture model with three classes: one for backgro...
I would go with the `HoughCircles` method, from openCV. It will give you all the circles in the image. Then it will be easy to compute the radius and the position of each circles. Look at : <https://docs.opencv.org/3.4/d4/d70/tutorial_hough_circle.html>
54,604,608
I have about 30 SEM (scanning-electron microscope) images like that: [![enter image description here](https://i.stack.imgur.com/uFHNf.png)](https://i.stack.imgur.com/uFHNf.png) What you see is photoresist pillars on a glass substrate. What I would like to do, is to get the mean diameter in x and y-direction as well ...
2019/02/09
[ "https://Stackoverflow.com/questions/54604608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I rarely find Hough useful for realworld applications, thus I'd rather follow the path of denoising, segmentation and ellipse fit. For the denoising, one selects the non local means (NLM). For the segmentation --- just looking at the image --- I came up with a Gaussian mixture model with three classes: one for backgro...
I use `cv2.ml.EM` to segment the image first in OpenCV (Python), it costs about `13 s`. If just `fitEllipse` on the contours of the threshed image, it costs `5 ms`, the the result maybe not that accurate. Just a tradeoff. [![enter image description here](https://i.stack.imgur.com/4TXOn.jpg)](https://i.stack.imgur.com/...
12,285,754
> > **Possible Duplicate:** > > [Python dictionaries - find second character in a 2-character string which yields minimum value](https://stackoverflow.com/questions/12284913/python-dictionaries-find-second-character-in-a-2-character-string-which-yields) > > > I would like to submit the first item of a tuple ke...
2012/09/05
[ "https://Stackoverflow.com/questions/12285754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1096991/" ]
``` def func(d,y): lis=sorted((x for x in d.items() if x[0][0]==y),key=lambda x:x[1]) return lis[0][0][1] d ={('a','b'):100,('a','c'):200,('a','d'):500,('b','c'):1000,('b','e'):100} ``` output: ``` >>> func(d,'a') 'b' >>> func(d,'b') 'e' ```
``` def minval(my_dict,var_name): return min(filter(lambda x: x[0][0] == var_name,my_dict.items()),key=lambda x:x[1])[0][1] print minval(d,'a') ``` I think Ashwins answer is probably better by pythonic simple is better than complex standards and they probably perform simillarly on a time scale ... his...
12,285,754
> > **Possible Duplicate:** > > [Python dictionaries - find second character in a 2-character string which yields minimum value](https://stackoverflow.com/questions/12284913/python-dictionaries-find-second-character-in-a-2-character-string-which-yields) > > > I would like to submit the first item of a tuple ke...
2012/09/05
[ "https://Stackoverflow.com/questions/12285754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1096991/" ]
Sorting is unnecessary here: ``` >>> d ={('a','b'):100,('a','c'):200,('a','d'):500,('b','c'):1000,('b','e'):100} >>> def func(d, k0): ... return min((k for k in d if k[0] == k0), key=d.get)[1] ... >>> func(d, 'a') 'b' >>> func(d, 'b') 'e' ``` This works by using a generator expression to give only the keys in t...
``` def minval(my_dict,var_name): return min(filter(lambda x: x[0][0] == var_name,my_dict.items()),key=lambda x:x[1])[0][1] print minval(d,'a') ``` I think Ashwins answer is probably better by pythonic simple is better than complex standards and they probably perform simillarly on a time scale ... his...
17,499,757
I have configured a keyboard shortcut using xbindkeys to run a python script. Now, while editing any vim file if that user press that keyboard shortcut- * I want my python script to run this command to paste the path and line no to the system clipboard- `:let @+=expand("%") . ':' . line(".")` * Then I want my script...
2013/07/06
[ "https://Stackoverflow.com/questions/17499757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908544/" ]
Try adding: ``` position:absolute; bottom: 0; ``` to your footer selector.
Well maybe it's because you have a min-height of 95%. If not, you can try: ``` #footer { position: absolute; bottom: 0; margin: 0 auto; } ```
17,499,757
I have configured a keyboard shortcut using xbindkeys to run a python script. Now, while editing any vim file if that user press that keyboard shortcut- * I want my python script to run this command to paste the path and line no to the system clipboard- `:let @+=expand("%") . ':' . line(".")` * Then I want my script...
2013/07/06
[ "https://Stackoverflow.com/questions/17499757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908544/" ]
Try adding: ``` position:absolute; bottom: 0; ``` to your footer selector.
Be careful when using `position: absolute`. As of time of writing, your page breaks when you have too much content on the page (enough content for a scrollbar). I assume you always want the footer below the content. In order to make sure your body's `min-height` styling works, add: ``` html { height: 100% } ``` Add...
17,499,757
I have configured a keyboard shortcut using xbindkeys to run a python script. Now, while editing any vim file if that user press that keyboard shortcut- * I want my python script to run this command to paste the path and line no to the system clipboard- `:let @+=expand("%") . ':' . line(".")` * Then I want my script...
2013/07/06
[ "https://Stackoverflow.com/questions/17499757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908544/" ]
Try adding: ``` position:absolute; bottom: 0; ``` to your footer selector.
try this ``` #footer { background: none repeat scroll 0 0 transparent; color: #4BB3E6; position: fixed; text-align: right; width: 100%; } ```
17,499,757
I have configured a keyboard shortcut using xbindkeys to run a python script. Now, while editing any vim file if that user press that keyboard shortcut- * I want my python script to run this command to paste the path and line no to the system clipboard- `:let @+=expand("%") . ':' . line(".")` * Then I want my script...
2013/07/06
[ "https://Stackoverflow.com/questions/17499757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908544/" ]
Try adding: ``` position:absolute; bottom: 0; ``` to your footer selector.
Use `positon:fixed`, DEMO <http://jsfiddle.net/VDfcC/> ``` #footer { position:fixed; left:0; bottom:0; z-index:10; margin-right: 10%; min-width: 100%; color: #4bb3e6; text-align: right; } ```
17,499,757
I have configured a keyboard shortcut using xbindkeys to run a python script. Now, while editing any vim file if that user press that keyboard shortcut- * I want my python script to run this command to paste the path and line no to the system clipboard- `:let @+=expand("%") . ':' . line(".")` * Then I want my script...
2013/07/06
[ "https://Stackoverflow.com/questions/17499757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908544/" ]
Be careful when using `position: absolute`. As of time of writing, your page breaks when you have too much content on the page (enough content for a scrollbar). I assume you always want the footer below the content. In order to make sure your body's `min-height` styling works, add: ``` html { height: 100% } ``` Add...
Well maybe it's because you have a min-height of 95%. If not, you can try: ``` #footer { position: absolute; bottom: 0; margin: 0 auto; } ```
17,499,757
I have configured a keyboard shortcut using xbindkeys to run a python script. Now, while editing any vim file if that user press that keyboard shortcut- * I want my python script to run this command to paste the path and line no to the system clipboard- `:let @+=expand("%") . ':' . line(".")` * Then I want my script...
2013/07/06
[ "https://Stackoverflow.com/questions/17499757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908544/" ]
try this ``` #footer { background: none repeat scroll 0 0 transparent; color: #4BB3E6; position: fixed; text-align: right; width: 100%; } ```
Well maybe it's because you have a min-height of 95%. If not, you can try: ``` #footer { position: absolute; bottom: 0; margin: 0 auto; } ```
17,499,757
I have configured a keyboard shortcut using xbindkeys to run a python script. Now, while editing any vim file if that user press that keyboard shortcut- * I want my python script to run this command to paste the path and line no to the system clipboard- `:let @+=expand("%") . ':' . line(".")` * Then I want my script...
2013/07/06
[ "https://Stackoverflow.com/questions/17499757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908544/" ]
Use `positon:fixed`, DEMO <http://jsfiddle.net/VDfcC/> ``` #footer { position:fixed; left:0; bottom:0; z-index:10; margin-right: 10%; min-width: 100%; color: #4bb3e6; text-align: right; } ```
Well maybe it's because you have a min-height of 95%. If not, you can try: ``` #footer { position: absolute; bottom: 0; margin: 0 auto; } ```
17,499,757
I have configured a keyboard shortcut using xbindkeys to run a python script. Now, while editing any vim file if that user press that keyboard shortcut- * I want my python script to run this command to paste the path and line no to the system clipboard- `:let @+=expand("%") . ':' . line(".")` * Then I want my script...
2013/07/06
[ "https://Stackoverflow.com/questions/17499757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908544/" ]
Be careful when using `position: absolute`. As of time of writing, your page breaks when you have too much content on the page (enough content for a scrollbar). I assume you always want the footer below the content. In order to make sure your body's `min-height` styling works, add: ``` html { height: 100% } ``` Add...
try this ``` #footer { background: none repeat scroll 0 0 transparent; color: #4BB3E6; position: fixed; text-align: right; width: 100%; } ```
17,499,757
I have configured a keyboard shortcut using xbindkeys to run a python script. Now, while editing any vim file if that user press that keyboard shortcut- * I want my python script to run this command to paste the path and line no to the system clipboard- `:let @+=expand("%") . ':' . line(".")` * Then I want my script...
2013/07/06
[ "https://Stackoverflow.com/questions/17499757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1908544/" ]
Be careful when using `position: absolute`. As of time of writing, your page breaks when you have too much content on the page (enough content for a scrollbar). I assume you always want the footer below the content. In order to make sure your body's `min-height` styling works, add: ``` html { height: 100% } ``` Add...
Use `positon:fixed`, DEMO <http://jsfiddle.net/VDfcC/> ``` #footer { position:fixed; left:0; bottom:0; z-index:10; margin-right: 10%; min-width: 100%; color: #4bb3e6; text-align: right; } ```
12,080,786
I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable: ``` statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl) self.cursor.execute(statmt) ``` This naturally barfs with: ``` statmt="...
2012/08/22
[ "https://Stackoverflow.com/questions/12080786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650424/" ]
When needing a literal `%` inside a Python formatting expression, use `%%`: ``` statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl) ``` See the documentation [section 5.6.2. String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting-operations) for more information.
You don't need to use string interpolation. The execute method handles it for you, so you can do this instead: ``` statmt="select id from %s WHERE `email` LIKE %blah%" self.cursor.execute(statmt, tbl) ```
12,080,786
I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable: ``` statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl) self.cursor.execute(statmt) ``` This naturally barfs with: ``` statmt="...
2012/08/22
[ "https://Stackoverflow.com/questions/12080786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650424/" ]
When needing a literal `%` inside a Python formatting expression, use `%%`: ``` statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl) ``` See the documentation [section 5.6.2. String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting-operations) for more information.
You can use [`str.format`](http://docs.python.org/library/string.html#formatstrings): ``` statmt="select id from {tbl} WHERE `email` LIKE %blah%".format(tbl=tbl) ``` Make sure you're not creating a SQL injection vulnerability.
12,080,786
I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable: ``` statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl) self.cursor.execute(statmt) ``` This naturally barfs with: ``` statmt="...
2012/08/22
[ "https://Stackoverflow.com/questions/12080786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650424/" ]
When needing a literal `%` inside a Python formatting expression, use `%%`: ``` statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl) ``` See the documentation [section 5.6.2. String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting-operations) for more information.
you should escape your percent sign with `%%` You should probably user parameterized queries though with `?` and `,` instead of string interpolation.
12,080,786
I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable: ``` statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl) self.cursor.execute(statmt) ``` This naturally barfs with: ``` statmt="...
2012/08/22
[ "https://Stackoverflow.com/questions/12080786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650424/" ]
You don't need to use string interpolation. The execute method handles it for you, so you can do this instead: ``` statmt="select id from %s WHERE `email` LIKE %blah%" self.cursor.execute(statmt, tbl) ```
You can use [`str.format`](http://docs.python.org/library/string.html#formatstrings): ``` statmt="select id from {tbl} WHERE `email` LIKE %blah%".format(tbl=tbl) ``` Make sure you're not creating a SQL injection vulnerability.
12,080,786
I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable: ``` statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl) self.cursor.execute(statmt) ``` This naturally barfs with: ``` statmt="...
2012/08/22
[ "https://Stackoverflow.com/questions/12080786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650424/" ]
you should escape your percent sign with `%%` You should probably user parameterized queries though with `?` and `,` instead of string interpolation.
You can use [`str.format`](http://docs.python.org/library/string.html#formatstrings): ``` statmt="select id from {tbl} WHERE `email` LIKE %blah%".format(tbl=tbl) ``` Make sure you're not creating a SQL injection vulnerability.
32,239,094
I have text files which look like this (much longer, this is just some lines from it): ``` ATOM 6 H2 ACD Z 1 47.434 34.593 -4.121 1.000 ATOM 7 C ACT Z 2 47.465 33.050 -2.458 1.000 ATOM 8 O ACT Z 2 48.004 33.835 -1.687 1.000 ATOM 9 CH1 ACT Z 2 47.586...
2015/08/27
[ "https://Stackoverflow.com/questions/32239094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261433/" ]
I was looking for the same thing. I ended up with the following solution: ``` figure = plt.figure(figsize=(6,9), dpi=100); graph = figure.add_subplot(111); freq = pandas.value_counts(data) bins = freq.index x=graph.bar(bins, freq.values) #gives the graph without NaN graphmissing = figure.add_subplot(111) y = gr...
As pointed out by [Sreeram TP](https://stackoverflow.com/users/7896849/sreeram-tp), it is possible to use the argument dropna=False in the function value\_counts to include the counts of NaNs. ``` df = pd.DataFrame({'feature1': [1, 2, 2, 4, 3, 2, 3, 4, np.NaN], 'feature2': [4, 4, 3, 4, 1, 4, 3, np.N...
32,239,094
I have text files which look like this (much longer, this is just some lines from it): ``` ATOM 6 H2 ACD Z 1 47.434 34.593 -4.121 1.000 ATOM 7 C ACT Z 2 47.465 33.050 -2.458 1.000 ATOM 8 O ACT Z 2 48.004 33.835 -1.687 1.000 ATOM 9 CH1 ACT Z 2 47.586...
2015/08/27
[ "https://Stackoverflow.com/questions/32239094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261433/" ]
I was looking for the same thing. I ended up with the following solution: ``` figure = plt.figure(figsize=(6,9), dpi=100); graph = figure.add_subplot(111); freq = pandas.value_counts(data) bins = freq.index x=graph.bar(bins, freq.values) #gives the graph without NaN graphmissing = figure.add_subplot(111) y = gr...
Did you try replacing NaN with some other unique value and then plot the histogram? ``` x= some unique value plt.hist(df.replace(np.nan, x) ```
8,774,032
I'm trying to send a POST request to a web app. I'm using the mechanize module (itself a wrapper of urllib2). Anyway, when I try to send a POST request, I get `UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)`. I tried putting the `unicode(string)`, the `unicode(string, ...
2012/01/07
[ "https://Stackoverflow.com/questions/8774032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647897/" ]
I assume you're using Python 2.x. Given a unicode object: ``` myUnicode = u'\u4f60\u597d' ``` encode it using utf-8: ``` mystr = myUnicode.encode('utf-8') ``` Note that you need to specify the encoding explicitly. By default it'll (usually) use ascii.
You don't need to wrap your chars in `unicode` calls, because they're already encoded :) if anything, you need to **DE**-code it to get a unicode object: ``` >>> s = '\xc5\xa1\xc4\x91\xc4\x87\xc4\x8d' # your string >>> s.decode('utf-8') u'\u0161\u0111\u0107\u010d' >>> type(s.decode('utf-8')) <type 'unicode'> ``` I...
8,774,032
I'm trying to send a POST request to a web app. I'm using the mechanize module (itself a wrapper of urllib2). Anyway, when I try to send a POST request, I get `UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)`. I tried putting the `unicode(string)`, the `unicode(string, ...
2012/01/07
[ "https://Stackoverflow.com/questions/8774032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647897/" ]
I assume you're using Python 2.x. Given a unicode object: ``` myUnicode = u'\u4f60\u597d' ``` encode it using utf-8: ``` mystr = myUnicode.encode('utf-8') ``` Note that you need to specify the encoding explicitly. By default it'll (usually) use ascii.
In your example, you use a non-unicode string literal containing non-ascii characters, which results in `prda` becoming a *bytes* string. To achieve this, python uses `sys.stdin.encoding` to automatically encode the string. In your case, this means the string is gets encoded as "utf-8". To convert `prda` to a *unicod...
8,774,032
I'm trying to send a POST request to a web app. I'm using the mechanize module (itself a wrapper of urllib2). Anyway, when I try to send a POST request, I get `UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 0: ordinal not in range(128)`. I tried putting the `unicode(string)`, the `unicode(string, ...
2012/01/07
[ "https://Stackoverflow.com/questions/8774032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647897/" ]
In your example, you use a non-unicode string literal containing non-ascii characters, which results in `prda` becoming a *bytes* string. To achieve this, python uses `sys.stdin.encoding` to automatically encode the string. In your case, this means the string is gets encoded as "utf-8". To convert `prda` to a *unicod...
You don't need to wrap your chars in `unicode` calls, because they're already encoded :) if anything, you need to **DE**-code it to get a unicode object: ``` >>> s = '\xc5\xa1\xc4\x91\xc4\x87\xc4\x8d' # your string >>> s.decode('utf-8') u'\u0161\u0111\u0107\u010d' >>> type(s.decode('utf-8')) <type 'unicode'> ``` I...
60,230,124
I am trying to read a stream from kafka using pyspark. I am using **spark version 3.0.0-preview2** and **spark-streaming-kafka-0-10\_2.12** Before this I just stat zookeeper, kafka and create a new topic: ``` /usr/local/kafka/bin/zookeeper-server-start.sh /usr/local/kafka/config/zookeeper.properties /usr/local/kafka...
2020/02/14
[ "https://Stackoverflow.com/questions/60230124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5674606/" ]
I have successfully resolved this error on Spark 3.0.1 (using PySpark). I would keep things simple and provide the desired packages through the `--packages` argument: ```bash spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.0.1 MyPythonScript.py ``` **Mind the order of arguments otherwise it wil...
If you check the documentation mentioned in the error, it indicates to download a different package - `spark-sql-kafka`, **not** `spark-streaming-kafka`. You can see in your `resolving dependencies` log section, you do not have that. You can also add packages via findspark rather than at the CLI
57,372,207
``` G:\Git\advsol\projects\autotune>conda env create -f env.yml -n auto-tune Using Anaconda API: https://api.anaconda.org Fetching package metadata ................. ResolvePackageNotFound: - matplotlib 2.1.1 py35_0 G:\Git\advsol\projects\autotune> ``` I have tried "conda install matplotlib==2.1.1" it doesn't wor...
2019/08/06
[ "https://Stackoverflow.com/questions/57372207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1577580/" ]
Try `conda install matplotlib=2.1.1`
create a new environment and try the below commands ``` conda install -c conda-forge matplotlib ``` or ``` conda install matplotlib ```
37,477,755
[![Terminal results when running a program](https://i.stack.imgur.com/3PXvF.png)](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to ...
2016/05/27
[ "https://Stackoverflow.com/questions/37477755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4444867/" ]
`SIGSTOP` does not terminate the program, it pauses it, so it is not killed. you should send `SIGCONT` to the program or type `fg` to continue it.
SIGTSTP OR SIGSTOP signal is suspend, can't kill this program, use SIGCONT signal you can wake and continue it ``` Signal Description Signal number on Linux x86[1] SIGABRT Process aborted 6 SIGALRM Signal raised by alarm 14 SIGBUS Bus error: "access to undefined portion of memory object" 7 SIGCHLD Child process t...
37,477,755
[![Terminal results when running a program](https://i.stack.imgur.com/3PXvF.png)](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to ...
2016/05/27
[ "https://Stackoverflow.com/questions/37477755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4444867/" ]
`SIGSTOP` does not terminate the program, it pauses it, so it is not killed. you should send `SIGCONT` to the program or type `fg` to continue it.
Ok,I found the solution. Enter the following command on your linux terminal: ``` ps -ef |grep yourfile.py ``` You will see a number of processes that are still running in the background. To kill them enter the following command: ``` kill -9 pid ``` Don't type pid. Type the numbers identifying the process as show...
37,477,755
[![Terminal results when running a program](https://i.stack.imgur.com/3PXvF.png)](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to ...
2016/05/27
[ "https://Stackoverflow.com/questions/37477755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4444867/" ]
`SIGSTOP` does not terminate the program, it pauses it, so it is not killed. you should send `SIGCONT` to the program or type `fg` to continue it.
You should make sure your threads are running in Daemon mode. This could be what is preventing them from exiting cleanly when you hit `ctrl-c`. Set them up like this: ``` t = threading.Thread() t.daemon = True // <- this is the important bit... t.start() ```
37,477,755
[![Terminal results when running a program](https://i.stack.imgur.com/3PXvF.png)](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to ...
2016/05/27
[ "https://Stackoverflow.com/questions/37477755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4444867/" ]
`SIGSTOP` does not terminate the program, it pauses it, so it is not killed. you should send `SIGCONT` to the program or type `fg` to continue it.
Use the following command to kill all processes and ensure no background processes running. Ctrl+\
37,477,755
[![Terminal results when running a program](https://i.stack.imgur.com/3PXvF.png)](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to ...
2016/05/27
[ "https://Stackoverflow.com/questions/37477755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4444867/" ]
SIGTSTP OR SIGSTOP signal is suspend, can't kill this program, use SIGCONT signal you can wake and continue it ``` Signal Description Signal number on Linux x86[1] SIGABRT Process aborted 6 SIGALRM Signal raised by alarm 14 SIGBUS Bus error: "access to undefined portion of memory object" 7 SIGCHLD Child process t...
Ok,I found the solution. Enter the following command on your linux terminal: ``` ps -ef |grep yourfile.py ``` You will see a number of processes that are still running in the background. To kill them enter the following command: ``` kill -9 pid ``` Don't type pid. Type the numbers identifying the process as show...
37,477,755
[![Terminal results when running a program](https://i.stack.imgur.com/3PXvF.png)](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to ...
2016/05/27
[ "https://Stackoverflow.com/questions/37477755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4444867/" ]
SIGTSTP OR SIGSTOP signal is suspend, can't kill this program, use SIGCONT signal you can wake and continue it ``` Signal Description Signal number on Linux x86[1] SIGABRT Process aborted 6 SIGALRM Signal raised by alarm 14 SIGBUS Bus error: "access to undefined portion of memory object" 7 SIGCHLD Child process t...
Use the following command to kill all processes and ensure no background processes running. Ctrl+\
37,477,755
[![Terminal results when running a program](https://i.stack.imgur.com/3PXvF.png)](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to ...
2016/05/27
[ "https://Stackoverflow.com/questions/37477755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4444867/" ]
You should make sure your threads are running in Daemon mode. This could be what is preventing them from exiting cleanly when you hit `ctrl-c`. Set them up like this: ``` t = threading.Thread() t.daemon = True // <- this is the important bit... t.start() ```
Ok,I found the solution. Enter the following command on your linux terminal: ``` ps -ef |grep yourfile.py ``` You will see a number of processes that are still running in the background. To kill them enter the following command: ``` kill -9 pid ``` Don't type pid. Type the numbers identifying the process as show...
37,477,755
[![Terminal results when running a program](https://i.stack.imgur.com/3PXvF.png)](https://i.stack.imgur.com/3PXvF.png)I am running a python script in linux and i am encountering a problem in running a program multiple times. When i execute the program ,the program runs normally and i give it a SIGTSTP signal ctrl+z to ...
2016/05/27
[ "https://Stackoverflow.com/questions/37477755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4444867/" ]
You should make sure your threads are running in Daemon mode. This could be what is preventing them from exiting cleanly when you hit `ctrl-c`. Set them up like this: ``` t = threading.Thread() t.daemon = True // <- this is the important bit... t.start() ```
Use the following command to kill all processes and ensure no background processes running. Ctrl+\
43,131,671
Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2. How to do it efficienlty with reasonable time and space complexity ? my solution: using dictionary: ``` from collections import defaultdict L=['a','b','c','d','a','d','e','e','g','h'] K=['a','g','i...
2017/03/31
[ "https://Stackoverflow.com/questions/43131671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516609/" ]
You can use python `Counter` for getting count of each word in the list. <https://docs.python.org/2/library/collections.html#counter-objects> ``` >>> L=['a','b','c','d','a','d','e','e','g','h'] >>> from collections import Counter >>> c = Counter(L) >>> c Counter({'a': 2, 'd': 2, 'e': 2, 'b': 1, 'c': 1, 'g': 1, 'h': 1}...
This will work well with respect to space complexity, it's also pythonic, but I'm not too sure about the run time ``` set([x for x in L.extend(K) if L.extend(K).count(x) == 2]) ``` Notice that this returns a set and not a list!
43,131,671
Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2. How to do it efficienlty with reasonable time and space complexity ? my solution: using dictionary: ``` from collections import defaultdict L=['a','b','c','d','a','d','e','e','g','h'] K=['a','g','i...
2017/03/31
[ "https://Stackoverflow.com/questions/43131671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516609/" ]
You can use the collection's counter class to simplify the code: ``` from collections import Counter ... d = Counter(L+K) #we are combining to process both at once ``` Additionally, you can combine lines by doing a conditional for loop. So only if the value is 2, then we will append it to our array. ``` L=['a','b',...
You can use python `Counter` for getting count of each word in the list. <https://docs.python.org/2/library/collections.html#counter-objects> ``` >>> L=['a','b','c','d','a','d','e','e','g','h'] >>> from collections import Counter >>> c = Counter(L) >>> c Counter({'a': 2, 'd': 2, 'e': 2, 'b': 1, 'c': 1, 'g': 1, 'h': 1}...
43,131,671
Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2. How to do it efficienlty with reasonable time and space complexity ? my solution: using dictionary: ``` from collections import defaultdict L=['a','b','c','d','a','d','e','e','g','h'] K=['a','g','i...
2017/03/31
[ "https://Stackoverflow.com/questions/43131671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516609/" ]
You can use the collection's counter class to simplify the code: ``` from collections import Counter ... d = Counter(L+K) #we are combining to process both at once ``` Additionally, you can combine lines by doing a conditional for loop. So only if the value is 2, then we will append it to our array. ``` L=['a','b',...
This will work well with respect to space complexity, it's also pythonic, but I'm not too sure about the run time ``` set([x for x in L.extend(K) if L.extend(K).count(x) == 2]) ``` Notice that this returns a set and not a list!
40,639,665
Not able to solve what is the error. ``` django.db.utils.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. ``` I keep on getting the Trace when i run any of the command below 1. python manage.py makemigrat...
2016/11/16
[ "https://Stackoverflow.com/questions/40639665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5474316/" ]
This usually means that your PostgreSQL server is not running properly. You may want to restart it by Linux ``` sudo /etc/init.d/postgresql restart ``` Windows ``` sc stop postgresql sc start postgresql ``` Mac OS X [How to start PostgreSQL server on Mac OS X?](https://stackoverflow.com/questions/7975556/how-to...
I solved this problem uninstalling and installing postgresql again. **On Mac** Uninstall: ``` brew uninstall --force postgres ``` Install: ``` brew install postgres ``` PS: Change commands for Linux or Windows. After, run makemigrations and migrate.
40,639,665
Not able to solve what is the error. ``` django.db.utils.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. ``` I keep on getting the Trace when i run any of the command below 1. python manage.py makemigrat...
2016/11/16
[ "https://Stackoverflow.com/questions/40639665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5474316/" ]
This usually means that your PostgreSQL server is not running properly. You may want to restart it by Linux ``` sudo /etc/init.d/postgresql restart ``` Windows ``` sc stop postgresql sc start postgresql ``` Mac OS X [How to start PostgreSQL server on Mac OS X?](https://stackoverflow.com/questions/7975556/how-to...
Happens when a process forks and connection established in parent process don't work in child processes. I was using `huggingface/tokenizers` and `BERT` to get sentence embeddings and then inserting those into a Postgres database. The database connection was getting established first and then the tokenizer was forking...
22,720,012
I've been bashing my head on this problem for a while now. I'm dealing with properties setting using the DBus-java bindings for DBus. When Set is called, the value to set is wrapped in a org.freedesktop.types.Variant object from which I have to extract it. Normally if the data is a primitive I can use generics in the ...
2014/03/28
[ "https://Stackoverflow.com/questions/22720012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1444649/" ]
Found the root cause. Changing the SpringServlet's Url mappings to "Rest" resources specific path fixed it. Earlier "/\*" was also interpreted by SpringServlet and was not able to render the index.html. ``` class Application extends SpringBootServletInitializer { public static void main(String[] args) { Sp...
``` @Configuration public class WebConfig implements WebMvcConfigurer { /** do not interpret .123 extension as a lotus spreadsheet */ @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false); } /** ./resources/public i...
30,958,835
I would like to have a function as an optional argument of another function in python but it is not clear for me how I can do that. For example I define the following function: ``` import os, time, datetime def f(t=datetime.datetime.now()): return t.timetuple() ``` I have placed `t=datetime.datetime.now()` in ...
2015/06/20
[ "https://Stackoverflow.com/questions/30958835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/805417/" ]
As mentioned by flask, the default value is evaluated when the function is parsed, so it will be set to one time. The typical solution to this, is to not have the default a mutable value. You can do the followings: ``` def f(t=None): if not t: t = datetime.datetime.now() return t.timetuple() ``` BTW...
The default parameter value is evaluated only once when the function is defined.