qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
64,765,086
im trying to run a server on my laptop, when in the console i type 'python manage.py runserver' i recieve some errors. could it be i need to import some modules i tried 'pip install python-cron' but that didnt work. the error says: ``` [2020-11-10 09:04:47,241] autoreload: INFO - Watching for file changes with StatRel...
2020/11/10
[ "https://Stackoverflow.com/questions/64765086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13740000/" ]
I have tried to re-create the same design with some minor changes in Flutter. I have to enable flutter web support by following the instructions here: [Flutter Web](https://flutter.dev/docs/get-started/web) [![Flutter Web sample](https://i.stack.imgur.com/oxX5K.gif)](https://i.stack.imgur.com/oxX5K.gif) Regarding the...
You can use the `Drawer` widget inside a `Scaffold`. If you want the navigation drawer to be able to resize according to the browser height and width you can use the [responsive\_scaffold](https://pub.dev/packages/responsive_scaffold) package.
17,041
22,073,028
I just started python three days ago and I am already facing a problem. I couldn't get any information in the www. It looks like a bug - but I think I did s.th. wrong. However I can't find the problem. Here we go: I have 1 List called "inputData". So all I do is, take out the first 10 entries in each array, fit it w...
2014/02/27
[ "https://Stackoverflow.com/questions/22073028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3361064/" ]
Your `inputData` isn't a numpy array, it's a list of arrays. Those two lists don't have the same length: ``` >>> [len(sl) for sl in inputData] [11, 10] ``` numpy arrays can't handle varying lengths. If you try to make an array out of it, instead of having a 2-D array of float dtype, you get a 1-D array of object dty...
Your code as you posted it is not runnable at all, as a bunch of definitions are missing or wrong. After fixing this and some code cleanup, I get the following, which basically shows, everything is working as intended: ``` import numpy as np from copy import deepcopy dataList = [np.array([[ 1.06999998e+01, 1.71811...
17,042
73,749,184
I'm following this [TensorFlow guide](https://github.com/EdjeElectronics/TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10) for object detection models and I've gotten to part 6, which is training your program. I've input this line of code, ``` python train.py --logtostderr --train_dir=trainin...
2022/09/16
[ "https://Stackoverflow.com/questions/73749184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19228228/" ]
I wold try something like this ``` var paymentStatus = JObject.Parse(response.Content)["PaymentStatus"][0]; string statusDescription = paymentStatus["StatusDescription"].ToString(); string merchantTxnRefNo = paymentStatus["MerchantTxnRefNo"].ToString(); ``` or maybe you need c# classes ``` List<PaymentStatus> pay...
Since PaymentStatus resolves to an array, use the indexer to get the object as below var StatusDescription = (string)jObject["PaymentStatus"]`[0]`["MerchantTxnRefNo"];
17,043
52,747,655
I am trying to use the TensorFlow CLI debugger in order to identify the operation which is causing a NaN during training of a network, but when I try to run the code I get an error: `_curses.error: cbreak() returned ERR` I'm running the code on an Ubuntu server, which I'm connecting to via SSH, and have tried to foll...
2018/10/10
[ "https://Stackoverflow.com/questions/52747655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9067015/" ]
Problem solved! The solution was to change ``` sess = tf_debug.LocalCLIDebugWrapperSession(sess) ``` to ``` sess = tf_debug.LocalCLIDebugWrapperSession(sess, ui_type="readline") ``` This is similar to the solution to [this question](https://stackoverflow.com/questions/47833697/how-to-use-tensorflow-debugging-tool...
`cbreak` would return **`ERR`** if you run a curses application that is not on a *real terminal* (i.e., something that works with [POSIX termios calls](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap11.html#tag_11)). From the description, > > but the layers in the network include while loops so are ...
17,044
12,397,182
I am trying to remove all the html surrounding the data that I seek from a webpage so that all that is left is the raw data that I will then be able to input into a database. so if I have something like: ``` <p class="location"> Atlanta, GA </p> ``` The following code would return ``` Atlanta, GA </p> ``` But wha...
2012/09/12
[ "https://Stackoverflow.com/questions/12397182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845888/" ]
As rightfully pointed out in the comments, you should be using a specific library to parse HTML and extract text, here are some examples: * [html2text](http://www.aaronsw.com/2002/html2text/): Limited functionnality, but exactly what you need. * [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/): More comp...
Assuming all you want is to extract the data contained in `<p class="location">` tags, you could use a quick & dirty (but correct) approach with the Python `HTMLParser` module (a simple HTML SAX parser), like this: ``` from HTMLParser import HTMLParser class MyHTMLParser(HTMLParser): PLocationID=0 PCount=0 ...
17,045
64,777,843
Today I come with a two in one set of issues that's on the verge of making me smash my computer to pieces! So please I would greatly appreciate any help as I've been stuck on it for two days now. I have a project where osmnx is required, so I follow the install instructions [provided](https://github.com/gboeing/osmnx#...
2020/11/10
[ "https://Stackoverflow.com/questions/64777843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9935756/" ]
Following droptop recommendation, I actually just did a full clean (another one) reinstall of anaconda where I deleted almost everything that I could. I installed it again and it's working now! Thanks for the help anyway!!
Your fresh anaconda install should have `jupyter`, `jupyterlab` and `spyder` in the `base` environment. Starting the anaconda prompt and typing in `jupyter notebook` should launch jupyter. Try activating your `ox2` environment with another prompt, and follow through from step 3 of this post <https://medium.com/@nrk256...
17,046
59,519,338
Error occurs upon `import numpy as np`; command works fine when typed directly in terminal, but fails when ran via [Code Runner](https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner). My steps to reproduce below. Output of `import sys; print(sys.version)` is `3.7.5 (default, Oct 31 2019, 15:18...
2019/12/29
[ "https://Stackoverflow.com/questions/59519338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10133797/" ]
Based on your comment, it looks like the conda environment is not being activated by VSCode. Selecting the Python interpreter points VSCode to the Python executable (python.exe), but sometimes environmental variables that are set by Conda are used to tell packages with large backends where to look for the compiled bina...
If you deactivate the Code Runner extension and make sure you select the appropriate conda environment using the [Python extension for VS Code](https://marketplace.visualstudio.com/items?itemName=ms-python.python) you will get a green play button instead of a white one. That green play button will use the environment y...
17,047
21,870,728
Hi I am trying to run the multiprocessing example in the docs: <http://docs.python.org/3.4/library/concurrent.futures.html>, the one using prime numbers but with a small difference. I want to be able to call a function with multiple arguments. What I am doing is matching small pieces of text (in a list around 30k long...
2014/02/19
[ "https://Stackoverflow.com/questions/21870728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3015449/" ]
To get the data into the right shape, simply use a generator expression (no need for `zip` at all) and use `submit` rather than `map`: ``` (pattern, executor.submit(processPattern, pattern, ...) for pattern in patterns) ``` To ensure that everything gets executed on the pool (instead of immediately), do not invoke t...
Python *for*-loop is has functional behavior, and it is not possible to change value, which is iterating. ``` with concurrent.futures.ProcessPoolExecutor() as executor: def work(pattern): return processPattern(pattern, numMismatchesAllowed, transformedText, charToIndex, countMatrix, firstOccurrence, suffi...
17,056
57,354,747
I am trying to add a package to PyPi so I can install it with Pip. I am trying to add it using `twine upload dist/*`. This causes me to get multiple SSL errors such as `raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='upload.pypi.org', port=443): Max retries exceeded with url...
2019/08/05
[ "https://Stackoverflow.com/questions/57354747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9868018/" ]
My guess is your school has something in place where they are replacing the original cert with their own, you could maybe get around it using `--cert` and referencing the path for your schools cert, but I think an easier workaround is to copy the files to a non school computer and upload from there.
This could be a number of things, including an out-of-date version of `twine`, or (more likely) an out-of-date version of OpenSSL. Some possible solutions are listed here: <https://github.com/pypa/twine/issues/273>
17,059
48,313,388
I am trying to get selenium working on my headless raspberry pi with firefox. I have it working fine on Windows with chrome. Here are my versions: ``` uname -a Linux megabyte.thompco.com 4.9.59-v7+ #1047 SMP Sun Oct 29 12:19:23 GMT 2017 armv7l GNU/Linux which firefox /usr/bin/firefox firefox --version Mozilla Firefo...
2018/01/18
[ "https://Stackoverflow.com/questions/48313388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039860/" ]
Finally got this to work, but with chromedriver and chrome. You will have to install chrome first: ``` sudo apt-get install chromium-browser ``` Next downloaded the debian package from here: <https://packages.debian.org/stretch/armhf/chromium-driver/download> Unpack the file "chromedriver": ``` mkdir tmp dpkg-deb -...
You can also try declaring the DISPLAY variable, it works especially for remote connections. Run this command on the terminal: ``` export DISPLAY=:0.0 ```
17,060
36,426,547
I am using Ubuntu 14.04 I wanted to install package "requests" to use in python 3.5, so I installed it using pip3. I could see it in /usr/lib/python3.4, but while trying to actually execute scripts with Python 3.5 I always got "ImportError: No module named 'requests'" OK, so I figured, perhaps that's because the pack...
2016/04/05
[ "https://Stackoverflow.com/questions/36426547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4680896/" ]
**First of all, it is a very bad idea to remove your *system* Python 3 in Ubuntu (which 3.4 is in recent subrevisions of Trusty LTS)**. That is because it is a **vital part of the system**. If you run the command `apt-cache rdepends python3`, you'd see that packages such as `ubuntu-minimal`, `ubuntu-release-upgrader-co...
Ubuntu 14.04LTS uses the [*trusty* package list](http://packages.ubuntu.com/trusty/). That repository comes with [Python 3.4.0-0ubuntu2](http://packages.ubuntu.com/trusty/python3). So the `pip` contained in `python3-pip` belongs to *that* version: 3.4. As such, when using Python 3.5, packages installed using Python 3....
17,061
6,397,344
it is a python code..whether implementing using linked list .... is efficient in this way........... ``` data = [] # data storage for stacks represented as linked lists stack = [-1, -1, -1] # pointers to each of three stacks (-1 is the "null" pointer) free = -1 # pointer to list of free stack nod...
2011/06/18
[ "https://Stackoverflow.com/questions/6397344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804287/" ]
In python, a list is a stack: ``` >>> l = [1, 2, 3, 4, 5] >>> l.pop() 5 >>> l.pop() 4 >>> l.append(9) >>> l [1, 2, 3, 9] >>> l.pop() 9 >>> l.pop() 3 >>> l.append(12) >>> l [1, 2, 12] ``` Although it may be an... entertaining exercise to implement a c-style linked list in python, it is unnecessary, and likely to be v...
A far better solution could be using list instead of stack to implement linked list. The code given is stack implementation of linked list, which I believe is a norm in python but in C/C++ you can use list for efficient implementation. A sample code in C would be as follows :- ``` #include <stdio.h> #include <stdlib....
17,063
28,223,747
I'm new to python and want help cleaning up my code. I had to make a definition that takes a string and returns the first half lowercase and second part uppercase. This is my code - but I can't help think there's a cleaner way to write this. ``` def sillycase(string): x = len(string)/2 y = round(x) print...
2015/01/29
[ "https://Stackoverflow.com/questions/28223747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4459432/" ]
You can use `find -exec` for this: ``` find /FolderA -type f -exec sed -i 's/wordA/wordB/g' {} + ```
`find` would be the way to go. A bash alternative: ``` shopt -s globstar files=() for file in FolderA/**; do # double asterisk is not a typo [[ -f "$file" ]] && files+=("$file") done sed -i 's/wordA/wordB/g' "${files[@]}" ```
17,068
55,454,514
I'm using a Kubernetes inventory builder script found here: <https://github.com/kubernetes-sigs/kubespray/blob/master/contrib/inventory_builder/inventory.py> On `line 36`, the ruamel YML library is imported using the code `from ruamel.yaml import YAML`. This library can be found here: <https://pypi.org/project/ruamel....
2019/04/01
[ "https://Stackoverflow.com/questions/55454514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/864245/" ]
`pip` is set to point to the Python 2 installation. To install the library under Python 3, do `pip3 install ruamel.yml`.
you're using python 3 and want to use the package that is with python 2. Go to the directory where your python 3 is, navigate to Scripts and use the pip in there to install the needed library.
17,069
466,321
How can I convert from a unix timestamp (say 1232559922) to a fractional julian date (2454853.03150). I found a website ( <http://aa.usno.navy.mil/data/docs/JulianDate.php> ) that performs a similar calculation but I need to do it programatically. Solutions can be in C/C++, python, perl, bash, etc...
2009/01/21
[ "https://Stackoverflow.com/questions/466321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/280/" ]
The Unix epoch (zero-point) is January 1, 1970 GMT. That corresponds to the Julian day of 2440587.5 So, in pseudo-code: ``` function float getJulianFromUnix( int unixSecs ) { return ( unixSecs / 86400.0 ) + 2440587.5; } ```
I know that this is an old post, but I'll just say ... The answer given by Jason Cohen is a good approximation of the conversion. There is a problem though that relates to the number of seconds in one day. A day is not -exactly- 86400 seconds long, and periodically seconds are added to days in order to keep time sync...
17,075
24,235,241
I recently installed sublime text 2 to try it out before I decide to get sublime text 3 but I can't properly run any code from it. I've hit Ctrl + B and I get an output like this. ``` [Error 2] The system cannot find the file specified [cmd: [u'python', u'-u', u'C:\\Users\\Jeff\\Desktop\\Personal codes\\print.py']] [...
2014/06/16
[ "https://Stackoverflow.com/questions/24235241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3697905/" ]
Instead of adding python to the path, I prefer simply specifying the full path to python in the sublime build. Python.exe is probably installed in one of these (or something similar) ``` C:/Python C:/Program Files/Python C:/Program Files (x86)/Python etc... ``` Once you found it (lets say its in C:\Program Files (x8...
Windows is unable to find your python installation. When you run a command like: ``` python <your_file.py> ``` the first `python` tells your system to find wherever your python binary is and try to run some command by that name. By looking over the path that was echoed, it doesn't look like you actually have your py...
17,080
35,931,198
I searched the forum and all answers are python or C+ related, this is for ruby. I'm trying to figure out how to make the below program prompt the user for an item in the array by typing a number 1-4 (so the position wouldn't start from 0 in the users eyes). It's probably a simple fix, but I am new to this.. I appreci...
2016/03/11
[ "https://Stackoverflow.com/questions/35931198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5281054/" ]
You can try something like this: ``` array = [] puts "please add to the array 4 times" 4.times do array << gets.chomp end puts "#{array}" loop do puts "Select a position in the array by typing a singular number from 1-4" ans = gets.chomp.to_i if ans > 0 && ans <= array.length puts "The element at posit...
You can get the index by combining `gets.chomp` (reads a line of user input and removes the trailing newline character) and `to_i` (convert to integer). Combine this with the ability to access an array's element at a specific index using the `array[index_integer]` method. To piece it together: ``` array = ["first_it...
17,081
17,806,673
Is there a canonical location where to put self-written packages? My own search only yielded a blog post about [where to put version-independent pure Python packages](http://pythonsimple.noucleus.net/python-install/python-site-packages-what-they-are-and-where-to-put-them) and a [SO question for the canonical location u...
2013/07/23
[ "https://Stackoverflow.com/questions/17806673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2375855/" ]
Thanks to the [two](http://docs.python.org/2/install/#how-installation-works) [additional](http://docs.python.org/2/install/#alternate-installation-the-home-scheme) links, I found not only the intended answer to my question, but also a solution that I like even more and that - ironically - was also explained in my firs...
I'd use the home scheme for this: <http://docs.python.org/2/install/#alternate-installation-the-home-scheme>
17,082
25,403,110
I am getting started with Django through [this](http://www.youtube.com/watch?v=3DccH9AMwFQ) beautiful video tutorial.On Tutorial 15 of the video series, there is database migration using **south**. But when I do `python manage.py migrate signups`, I got a whole lot of errors. The first error was: ``` File "C:\Pytho...
2014/08/20
[ "https://Stackoverflow.com/questions/25403110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2673433/" ]
There's that problem, you use boolean as a default value (see `default=True` on line 19 in your migration) for `DateTime` column. That wont work. Just remove that `default=True` from your model and regenerate your migration. You would probably need `null=True` in that column or some time-based default value.
In your migration the `fields.DateTimeField` can not be a Boolean value (default=True). You can edit your migrations set a datetime value ``` import datetime ... default = datetime.datetime(2016,2,25,16,35,658000) ... ``` The `models.DateTimeField` should be a `None` or a `datetime` object
17,087
28,779,395
This is a very easy code to understand things : Main : ```html import pdb #pdb.set_trace() import sys import csv sys.version_info if sys.version_info[0] < 3: from Tkinter import * else: from tkinter import * from Untitled import * main_window =Tk() main_window.title("Welcome") label = Label(main_...
2015/02/28
[ "https://Stackoverflow.com/questions/28779395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4502651/" ]
The `command` lambda does not take any arguments at all; furthermore there is no `evt` that you can catch. A lambda can refer to variables outside it; this is called a closure. Thus your button code should be: ``` bouton1 = Button(main_window, text="Enter", command = lambda: get(Current_Weight, entree1)) ``` And...
Actually, you just need the Entry object entree1 as the lamda pass-in argument. Either statement below would work. ``` bouton1 = Button(main_window, text="Enter", command=lambda x = entree1: get(x)) bouton1 = Button(main_window, text="Enter", command=lambda : get(entree1)) ``` with the function get defined as ``` ...
17,088
17,349,928
I understand that an RGB to HSV conversion should take RGB values 0-255 and convert to HSV values [0-360, 0-1, 0-1]. For example see this [converter in java](http://www.javascripter.net/faq/rgb2hsv.htm): When I run matplotlib.colors.rbg\_to\_hsv on an image, it seems to output values [0-1, 0-1, 0-360] instead. Howeve...
2013/06/27
[ "https://Stackoverflow.com/questions/17349928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1276299/" ]
It works beautifully if, instead of unsigned int RGB values from 0 to 255, you feed it float RGB values from 0 to 1. It would be nice if the documentation specified this, or if the function tried to catch what seems to be a very likely human error. But you can get what you want simply by calling: ``` print colors.rgb_...
Take care, the source comment states input/output should be of dimension M,N,3, and the function fails for RGBA (M,N,4) images, e.g. imported png files.
17,089
65,408,099
When i was practising list&if in python i got stuck with a problem ``` friends=["a","b","c"] print("eklemek mi cikarmak mi istiyosunuz ?") ans=(input()) if ans == 'add': add=input("adding who ?") friends.append(add) if ans=='remove': remove = input("removing who ?") friends.remove(remove) print(remove) ``` ...
2020/12/22
[ "https://Stackoverflow.com/questions/65408099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14871427/" ]
We had the same issue, and managed to fix it by searching for the exact minified function in the minified code (in this case `(0,o.useState`), then search around that code to find some string or identifier that wasn't minifed (found a prop name that was a string) that we could use to find the place in the source code. ...
I had a similar problem, I've realized that my Expo SDK version was an older one, I've upgraded Expo SDK and re-deployed my app, problem did not occur again.
17,090
57,774,652
This function: ```js function print(){ console.log('num 1') setTimeout(() => { global.name = 'max' console.log('num 2') },9000); console.log('num 3'); } print(); console.log(global.name) ``` is priting this: ``` num 1 num 3 undefined num 2 ``` And I need to: 1. print `num 1` 2. wait untill the ...
2019/09/03
[ "https://Stackoverflow.com/questions/57774652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10489311/" ]
The error is cause by this line: ``` options['partitionKey'] = '/Structures' ``` You need to specify the specific value of partition key here, not the column name.For example,my partition key is '/name',and the specific value in this document is 'A'. [![enter image description here](https://i.stack.imgur.com/qvm0f....
``` import datetime as datetime import pandas as pd import json import os URL = 'https://resouceName.documents.azure.com:443/' KEY = 'YourKey' DATABASE_NAME = 'resourceName' CONTAINER_NAME = 'ContainerName' client = CosmosClient(URL, credential=KEY) database = client.get_database_client(DATABASE_NAME) container =...
17,091
39,875,273
I have attempted to create an insertion sort in python, however the list returned is not sorted. What is the problem with my code? Argument given: [3, 2, 1, 4, 5, 8, 7, 9, 6] Result: 2 1 3 6 4 7 5 8 9 Python code: ``` def insertion_sort(mylist): sorted_list = [] for i in mylist: posfound = 0 #defaul...
2016/10/05
[ "https://Stackoverflow.com/questions/39875273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4363434/" ]
You need to change `sorted_list.insert(j-1, i)` to be `sorted_list.insert(j, i)` to insert before position `j`. `insert(j-1, ..)` will insert before the *previous* element, and in the case where `j=0` it'll wrap around and insert before the last element. The [Python data structures tutorial](https://docs.python.org...
As often, it was a off-by-one error, the code below is fixed. I also made some parts a bit prettier. ``` def insertion_sort(mylist): sorted_list = [] for i in mylist: for index, j in enumerate(sorted_list): if j > i: sorted_list.insert(index, i) #put the number in before ele...
17,092
7,615,511
I am writing a python script and I just need the second line of a series of very small text files. I would like to extract this without saving the file to my harddrive as I currently do. I have found a few threads that reference the TempFile and StringIO modules but I was unable to make much sense of them. Currently...
2011/09/30
[ "https://Stackoverflow.com/questions/7615511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/935684/" ]
There's a glitch in iText and iTextSharp but you can fix it pretty easily if you don't mind downloading the source and recompiling it. You need to make a change to two files. Any changes I've made are commented inline in the code. Line numbers are based on the 5.1.2.0 code rev 240 The first is in `iTextSharp.text.html...
I would recommend using [wkhtmltopdf](http://code.google.com/p/wkhtmltopdf/) instead of iText. wkhtmltopdf will output the html exactly as rendered by webkit (Google Chrome, Safari) instead of iText's conversion. It is just a binary that you can call. That being said, I might check the html to ensure that there are par...
17,095
65,470,264
I am pretty new to python. Just been working through some online tutorials on udemy. I seem to have an issue with pip installing modules. * I've tried reinstalling them. * Upgrading my python version. * In VS I always just get `module not found`. If I do it in the cmd prompt this is what I get below. [![error](https...
2020/12/27
[ "https://Stackoverflow.com/questions/65470264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14898017/" ]
> > there is no action called until my final write to parquet. > > > and > > Spark during that final write to parquet call will be able to see that this dataframe is being used in f1 and f2 and will cache the dataframe itself. > > > are correct. If you do `output_df.explain()`, you will see the query plan, w...
You might want to repartition after running `special_rows = df.filter(col('special') > 0)`. There can be a large number of empty partitions after running a filtering operation, [as explained here](https://mungingdata.com/apache-spark/filter-where/). The `new_df_1` will make cache `special_rows` which will be reused by...
17,098
74,081,960
I got my program running fine as explained at: [How can you make a micropython program on a raspberry pi pico autorun?](https://stackoverflow.com/questions/66183596/how-can-you-make-a-micropython-program-on-a-raspberry-pi-pico-autorun/74078142#74078142) I'm installing a `main.py` that does: ``` import machine import ...
2022/10/15
[ "https://Stackoverflow.com/questions/74081960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/895245/" ]
What appears to be happening here is that exiting `screen` (or exiting `picocom` without the tty reset) leaves the [`DTR`](https://en.wikipedia.org/wiki/Data_Terminal_Ready) line on the serial port high. We can verify this by writing some simple code to control the DTR line, like this: ``` #include <unistd.h> #include...
I don't know why it works, but based on advie from larsks: ``` sudo apt install picocom picocom /dev/ttyACM0 ``` and then quit with Ctrl-A Ctrl-X (not Ctrl-A Ctrl-Q) does do what I want. Not sure what `screen` is doing differently exactly. When quitting, Ctrl-Q shows on terminal: ``` Skipping tty reset... ``` an...
17,099
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...
17,100
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...
17,101
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 ...
17,111
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 ```
17,112
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 ...
17,114
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' ... ```
17,119
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]] ``` ...
17,120
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...
17,122
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...
17,123
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...
17,133
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...
17,134
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/)
17,135
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...
17,136
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...
17,139
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...
17,140
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...
17,141
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.
17,142
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 ```
17,143
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...
17,146
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...
17,147
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)] ```
17,148
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. ...
17,151
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.
17,153
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)
17,156
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...
17,159
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>
17,160
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...
17,162
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,164
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) ```
17,173
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...
17,178
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...
17,180
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
17,183
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 ```
17,184
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...
17,185
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!
17,193
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.
17,196
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...
17,198
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.
17,199
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
Your update emulates what the absolute import does: `import package1.module1` if you do it while `module1` being imported. If you'd like to use a dynamic parent package name then to import `module1` in the `module2.py`: ``` import importlib module1 = importlib.import_module('.module1', __package__) ``` --- > > I n...
I ran into this same issue today, and it seems this is indeed broken in python3.4, but works in python3.5. The [changelog](https://docs.python.org/3/whatsnew/3.5.html) has an entry: > > Circular imports involving relative imports are now supported. (Contributed by Brett Cannon and Antoine Pitrou in [bpo-17636](https...
17,204
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There's not a command to do that, but you can iterate over `environ["PATH"]` and look if the file exists, which is actually what `which` does. ``` import os def which(file): for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(os.path.join(path, file)): return os.path.join(p...
You could try something like the following: ``` import os import os.path def which(filename): """docstring for which""" locations = os.environ.get("PATH").split(os.pathsep) candidates = [] for location in locations: candidate = os.path.join(location, filename) if os.path.isfile(candidat...
17,214
4,420,218
I have a VPS running a fresh install of Ubuntu 10.04 LTS. I'm trying to set up a live application using the Flask microframework, but it's giving me trouble. I took notes while I tried to get it running and here's my play-by-play in an effort to pinpoint exactly where I went wrong. INSTALLATION ============ <http://f...
2010/12/12
[ "https://Stackoverflow.com/questions/4420218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511200/" ]
Obviously, it cannot find your "`myapp`" package. You should add it to the path in your `myapp.wsgi` file like this: ``` import sys sys.path.append(DIRECTORY_WHERE_YOUR_PACKAGE_IS_LOCATED) from myapp import app ``` Also, if `myapp` module is a package, you should put and empty `__init__.py` file into its directory.
Edit line `sys.path.append`, it needs to be a string. ``` import sys sys.path.append('directory/where/package/is/located') ``` **Notice** the single quotes.
17,224
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
``` #Shamelessly combined from google and other stackoverflow like sites to form a single function import platform,socket,re,uuid,json,psutil,logging def getSystemInfo(): try: info={} info['platform']=platform.system() info['platform-release']=platform.release() info['platform-vers...
``` import psutil import platform from datetime import datetime import cpuinfo import socket import uuid import re def get_size(bytes, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "...
17,225
13,337,140
Brand new to using python, need help figuring out why my command line is spitting out huge strings of numbers and not the fib sequence up to the var I pass in. Here is what I have so far: ``` import sys def fib(n): a, b = 0, 1 while a < n: print a a, b = b, a+b if __name__ == "__main__": ...
2012/11/12
[ "https://Stackoverflow.com/questions/13337140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816962/" ]
Don't forget to convert the input argument (a string) into an integer type: ``` fib(int(sys.argv[1])) ```
Try `fib(int(sys.argv[1]))`, that might be the problem, but I didn't try it.
17,235
52,557,158
I am new to python. I got this pre written code that downloads data in to report. But I am getting the error > > "write() argument must be str, not bytes". > > > See below code ``` def _download_report(service, response, ostream): logger.info('Downloading keyword report') written_header = False for...
2018/09/28
[ "https://Stackoverflow.com/questions/52557158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10429839/" ]
you'll need to change the last line to ``` ostream.write(istream.read().decode('utf-8')) ``` PS. you may need to replace `'utf-8`` with whatever encoding the data is in
To elaborate more on @sgDysregulation's answer: One peculiarity with python 3 is that strings (`'hello, world'`) and binary strings (`b'hello, world'`) are basically incompatible. As an example, if you're familiar with basic file I/O, there are two types of modes to read a file in - you could use `open('file.txt', 'r'...
17,236
21,322,568
This is my first time asking a question. I am just starting to get into programming, so i am beginning with Python. So I've basically got a random number generator inside of a while loop, thats inside of my "r()' function. What I want to do is take all of the numbers (basically like an infinite amount until i shut down...
2014/01/24
[ "https://Stackoverflow.com/questions/21322568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701400/" ]
You can use ``` numpy.stack(arrays, axis=0) ``` if you have an array of arrays. You can specify the axis in case you want to stack columns and not rows.
You can just call `np.array` on the list of 1D arrays. ``` >>> import numpy as np >>> arrs = [np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9])] >>> arrs [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])] >>> arr2d = np.array(arrs) >>> arr2d.shape (3, 3) >>> arr2d array([[1, 2, 3], [4, 5, 6], [...
17,238
48,683,238
I have this error ``` onecheck(sys.argv[1],sys.argv[2],sys.argv[3]) IndexError: list index out of range ``` I try to make loop a python script . This is code : ``` with open(file) as k: for line in k: aa, bb, cc = line.split(':') time.sleep(5) os.system("python checkfile.py " + cc...
2018/02/08
[ "https://Stackoverflow.com/questions/48683238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8868451/" ]
A fairly simple way of finding groups as you described would be to convert data to a boolean array with ones for data inside groups and 0 for data outside the groups and compute the difference of two consecutive value, this way you'll have 1 for the start of a group and -1 for the end. Here's an example of that : ```...
Your smoothed data has no zeros left: ``` import numpy as np def smooth(y, box_pts): box = np.ones(box_pts)/box_pts print(box) y_smooth = np.convolve(y, box, mode='same') return y_smooth mydata = [0.0, 0.0, 0.0, 0.0,-0.2, 0.143, 0.0, 0.22, 0.135, 0.44, 0.1, 0.0, 0.0, 0.0, 0.0, 0...
17,240
37,646,174
I need to read an analog signal in raspberry and for this purpose I bought an MCP3002 circuit. i plug it in with the correct connections and i have found sample codes over the internet but it doesn't work. Do I need to have an interface or I can do the job without it? Do you have any ideas what can go wrong? Do you ...
2016/06/05
[ "https://Stackoverflow.com/questions/37646174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3254786/" ]
My `pagesize` was set to `0`. I don't know why this would cause the column headers to disappear, but it did. If someone can explain better than me, I'll gladly accept their answer in leu of mine. I set `pagesize` to `14`, and my column headers appeared.
SQL\*Plus has changed the default behavior in ORACLE 12c. With ``` SQL> set head on ``` you get back to the previous behavior. With ``` SQL> set pagesize *n* ``` every *n* rows the header will be repeated.
17,245
10,368,678
I'm attempting to install the DrEdit sample app for python onto GAE. The app runs, but saving or opening a file results in an **HTTP 403 "Access Not Configured Error"**. **client.json** has **client\_id** and **client\_secret** set per the **API Access>Client ID for Drive SDK values**. I have also attempted to use the...
2012/04/29
[ "https://Stackoverflow.com/questions/10368678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363559/" ]
In the services section of the Google API console there are two services relating to drive development, SDK and API. When you create a new Drive SDK entry, Drive API service is not automatically enabled (which doesn't make sense, I don't see when you'd create a drive enabled application without using the drive API). Sw...
And your must also identify in your code the following ``` DriveService.Scope.DriveFile, DriveService.Scope.Drive ``` good luck
17,246
25,190,026
Link shows a graphic visualization taken form census website. Link for the same is shared below. I want to create graphic visualization of the same kind in my python program. Link for the graphic visualization: <http://www.census.gov/dataviz/visualizations/stem/stem-html/> Which kind of visualization is this? is it...
2014/08/07
[ "https://Stackoverflow.com/questions/25190026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3888977/" ]
I don't see a graph that is exactly like the one listed, but matplotlib provides a huge number of options. <http://matplotlib.org/gallery.html> It supports Sankey graphs as well: <http://matplotlib.org/api/sankey_api.html?highlight=sankey#module-matplotlib.sankey>
It's essentially a [weighted graph](http://en.wikipedia.org/wiki/Weighted_graph#Weighted_graphs_and_networks). It looks a lot like a [Sankey diagram](http://en.wikipedia.org/wiki/Sankey_diagram). There is specialized software for visualizing graphs, e.g. [graphviz](http://www.graphviz.org/). There are several Python b...
17,247
9,548,139
Disclaimer: I am new to python and django but have programmed in Drupal I am developing a web-based Wizard (like on Microsoft Windows installation screens) with explanatory text followed by Previous and Next buttons (which are big green left and right arrows). So far, so good. However, my current Wizard page (in proj...
2012/03/03
[ "https://Stackoverflow.com/questions/9548139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1231693/" ]
`<input type="submit" value="Next"/>` This gives you a button with the value 'Next' which acts as a submit button. If this is not what you've wanted, rephrase your question and/or give an example of what action should take place after pressing next.
You might want to use the Django Form wizard, in this case: <https://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-wizard/>
17,252
15,187,184
I am trying to extend the fft code that works fine for 1D arrays in python for images. Actually i know the problem is in logic in extension. I don't know much about FFTs and i have to submit assignments for Image Processing. I will be thankful for any hints or solutions Here is the code, Actually, I'm trying to create...
2013/03/03
[ "https://Stackoverflow.com/questions/15187184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1442667/" ]
Your code is a little hard to follow, but it looks like you are taking the FFT along the same direction both times. Look up the integral from of the FT, you will see that the `x` and `y` integrations are independent. That is (sorry, this notation is awful, `'` indicates a function in Fourier space) ``` FT(f(x, y), x) ...
I agree with isedev that you should use numpy. It already has a great fft package that can do transforms in n-dimensions. <http://docs.scipy.org/doc/numpy/reference/routines.fft.html> <http://docs.scipy.org/doc/numpy-1.4.x/reference/generated/numpy.fft.fft.html>
17,253
7,233,991
I have created a `FileManager` for my personal files. The launcher for this manager is launched by following script. ``` #!/usr/bin/python from ui.MovieManager import MovieManager MovieManager().showView() ``` Movie manager and other modules are situated in the `ui` and `core` packages, but when executing the file...
2011/08/29
[ "https://Stackoverflow.com/questions/7233991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/275097/" ]
It's not python which generates the error. Check this out: ``` blubb@nemo:~$ from ui.MovieManager import MovieManager from: can't read /var/mail/ui.MovieManager ``` Mind you, this is the console, which is a logical consequence of you calling the script with `sh Launcher.py`. Instead, use `./Launcher.py`. For this t...
Have you tried going to the folder where Launcher.py is and running ``` ./Launcher.py ```
17,254
39,075,309
what I met is a code question below: <https://www.patest.cn/contests/pat-a-practise/1001> > > Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits). > > > Input > > > Each input file contains one t...
2016/08/22
[ "https://Stackoverflow.com/questions/39075309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6419115/" ]
I can give you a simple that doesn't match answer, when you enter -1000000, 9 as a, b in your input, you'll get -,999,991.which is wrong. To get the right answer, you really should get to know format in python. To solve this question, you can just write your code like this. `if __name__ == "__main__": aline = input...
Notice the behavior of your code when you input -1000 and 1. You need to handle the minus sign, because it is not a digit.
17,255
21,346,725
I am using python with Pyqt4 for building app on Ubuntu and seems I have trouble with menubar that doesn't show up, thanks for any help. here is the code: ``` import sys from PyQt4 import QtGui class Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() ...
2014/01/25
[ "https://Stackoverflow.com/questions/21346725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1233240/" ]
In ubuntu menubar is outside the application . You can find it in global menu
There is nothing wrong in your code. First you should run your code and maximize your GUI(Graphical User Interface) and you can see that your code run fine and you can understand what actually happen in Ubuntu. Actually Ubuntu always show the menu bar (also your GUI) at the top of the screen no matter what the size of ...
17,256
13,903,467
I am using Win 8, Eclipse and Pydev. I installed Pydev and it can run simple python script. Unfortunately I want to use math module and it gets error sign next to math command. ![enter image description here](https://i.stack.imgur.com/iEN1s.png) Undefined variable. I would be very thankful if you can help me to get...
2012/12/16
[ "https://Stackoverflow.com/questions/13903467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619324/" ]
'math' should be marked as a 'forced builtin' in window > preferences > pydev > interpreter - python (if it's not, that's your problem). If it's properly configured, it probably means that PyDev wasn't able to spawn a shell to inspect the math module, in which case it usually means that there's some firewall blocking ...
I cannot see the screenshot very well, but i see you are doing on the first line: ``` from math import * ``` and then ``` print math.whatever ``` Clearly `math` is an undefined variable here, as you should have used `import math` instead of `from math import *`
17,262
43,407,522
I am used to connect to a local server by using putty. But now I need to create a file by using a script python, this file has a huge size, so I must put it in local server; by using puty, I must entre my host adresse, password, name and the port. How do I do that? This is my script: ``` import numpy as np import...
2017/04/14
[ "https://Stackoverflow.com/questions/43407522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6690199/" ]
In the end, I figured out myself how to achieve Laravel Echo working with Pusher but without Vue.js 1. Follow all the instructions found [here](https://laravel.com/docs/5.4/broadcasting). 2. Assuming you have Pusher installed and configured and Laravel Echo installed via npm, go to `your-project-folder/node_modules/la...
First create event for broadcasting data as per the laravel document. And check console debug that your data being broadcasted or not. If your data is broadcasting than use javascript to listening data as given in pusher document. Here you can check example : <https://pusher.com/docs/javascript_quick_start>
17,265
69,658,798
I have the following python code to convert csv file into json file. ``` def make_json_from_csv(csv_file_path, json_file_path, unique_column_name): import csv import json # create a dictionary data = {} # Open a csv reader called DictReader with open(csv_file_path, encoding='utf-8') as csvf: ...
2021/10/21
[ "https://Stackoverflow.com/questions/69658798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
In Python 3.6+ the dict keep the insertion order, so to fetch the last rows of a dictionary, just do: ``` from itertools import islice x = 5 d = {} for i, v in enumerate("abcdedfghi"): d[i] = v d = dict(islice(d.items(), len(d) - x, len(d))) print(d) ``` **Output** ``` {5: 'd', 6: 'f', 7: 'g', 8: 'h', 9: 'i'}...
I would like to answer my own question by building on Dani Mesejo's answer. The credit goes entirely to him. ``` def make_json(csv_file_path, json_file_path, unique_column_name, no_of_rows_to_extract): import csv import json from itertools import islice # create a dictionary data = {}...
17,268
23,322,025
I am currently using python `pandas` and want to know if there is a way to output the data from pandas into julia `Dataframes` and vice versa. (I think you can call python from Julia with `Pycall` but I am not sure if it works with dataframes) Is there a way to call Julia from python and have it take in `panda`s datafr...
2014/04/27
[ "https://Stackoverflow.com/questions/23322025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3159981/" ]
So there is a library developed for this `PyJulia` is a library used to interface with Julia using Python 2 and 3 <https://github.com/JuliaLang/pyjulia> It is experimental but somewhat works Secondly Julia also has a front end for `pandas` which is `pandas.jl` <https://github.com/malmaud/Pandas.jl> It looks to be...
I'm a novice at this sort of thing but have definitely been using both as of late. Truth be told, they seem very quite comparable but there is far more documentation, Stack Overflow questions, etc pertaining to Pandas so I would give it a slight edge. Do not let that fact discourage you however because Julia has some a...
17,269
40,452,603
I have written a simple Python3 program like below: ``` import sys input = sys.stdin.read() tokens = input.split() print (tokens) a = int(tokens[0]) b = int(tokens[1]) if ((a + b)> 18): print ("Input numbers should be between 0 and 9") else: print(a + b) ``` but while running this like below: ``` C:\Python_...
2016/11/06
[ "https://Stackoverflow.com/questions/40452603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7123148/" ]
`sys.stdin.read()` will read until an EOF (end of file) is encountered. That's why "pressing enter" doesn't seem to do anything. You can send an EOF on Windows by typing `Ctrl`+`Z`, or on \*nix systems with `Ctrl`+`D`. (Note that you probably still need to hit `Enter` before hitting `Ctrl`+`Z`. I don't think the termi...
This happens because `sys.stdin.read` attempts to read *all the data* that the standard input can provide, including new lines, spaces, tabs, *whatever*. It will stop reading only if the interpreter's interrupted or it hits an EndOfFile (Ctrl+D on UNIX-like systems and Ctrl+Z on Windows). The standard function that as...
17,270
69,425,666
I'm currently working on an Applescript math library, which mimics the python `math` module. The python `math` module has some constants, such as [Euler's number](https://en.wikipedia.org/wiki/E_%28mathematical_constant%29) and others. Currently, you can do something like this: ```applescript set math to script "Math"...
2021/10/03
[ "https://Stackoverflow.com/questions/69425666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15209993/" ]
There is no way to explicitly define a constant in AppleScript. There are three approaches that might suffice, depending on what you're trying to achieve. --- If you're using a Scripting Definition (sdef) in your library, you can add an enumeration to define terms you want to reserve, then handle them by cases in cod...
Every handler name with parameters is constant in the AppleScript. You can use this fact. Here, you can't change the name of the handler, so you can consider it like your constant pi identifier. It is true constant because you can't set it, but you can get it whatever you want: ``` on constantPi() 3.14159265359 en...
17,272
47,724,709
I am trying to insert into a postgresql database in python 3.6 and currently am trying to execute this line ``` cur.execute("INSERT INTO "+table_name+"(price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)",(exchange_rate, buy_rate, sell_rate, date)) ``` but every time it tries to run the table name has ' ' ...
2017/12/09
[ "https://Stackoverflow.com/questions/47724709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1771791/" ]
Use it with triple quotes. Also you may pass table\_name as a element of second parameter, too. ``` cur.execute("""INSERT INTO %s (price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)""",(table_name, exchange_rate, buy_rate, sell_rate, date)) ``` More detailed approach; * Triple qoutes give developers a change to ...
Use the new string formatting to have a clean representation. `%s` is explicitly converting to a string, you don't want that. Format chooses the most fitting type for you. ``` table_name = "myTable" exchange_rate = 1 buy_rate = 2 sell_rate = 3 date = 123 x = "INSERT INTO {0} (price, buy, sell, timestamp) VALUES ({1}, ...
17,273
19,612,822
I know that there are different ways to do this, but I just want to know why my regex isn't working. This isn't actually something that I need to do, I just wanted to see if I could do this with a regex, and I have no idea why my code isn't working. Given a string S, I want to find all non-overlapping substrings that ...
2013/10/26
[ "https://Stackoverflow.com/questions/19612822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2073001/" ]
Assuming what you actually want is for the subsequence Q to contain no `a`s between the first `a` and the first `b` and no `a`s or `b`s between the first `b` and the first `c` after the first `b`, the correct regex to use is: ``` r'a[^ab]*b[^abc]*c' ``` The regex that you're currently using will do everything that i...
It could help if you look at the inverse class. In all cases `abc` is the trivial solution. And, in this case non-greedy probably doesn't apply because there are fixed sets of characters used in the example inverse classes. ``` # Type 1 : # ( b or c can be between A,B ) # ( a or b can be between B,C ) ...
17,274
64,146,892
I'm trying to create a word counter in python that prints the longest word, then sorts all words over 5 letters by frequency. The longest word works, and the counter works, I just can't figure out how to make it check only over 5 letters. If I run it, it works, but the words under 5 letters are still there. Here's the...
2020/09/30
[ "https://Stackoverflow.com/questions/64146892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14370546/" ]
Okay, so I took a different approach and changed my code, the following code is now functional although I have no idea what was causing the original issue still. ``` public CharacterController controller; private float speed; public float walkSpeed = 5f; public float runSpeed = 10f; public float turnSpeed = 90f; pub...
This happens because the character controller has a gravity so when you enable it, it uses gravity to the player and drag your player down. To fix this, you will need to write in the script that the player's position is upwards. ``` public float walkSpeed = 3f; public float runSpeed = 6f; public float gravity = -9.81f...
17,275
32,162,757
I am using mongoDB with python . I want user to enter a document in the JSON format so that i can insert that into some collection in my db .How can this be done ?
2015/08/23
[ "https://Stackoverflow.com/questions/32162757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4784437/" ]
Just use conditional aggregation: ``` select Id, (sum(case when Value > 3.0 then 1 else 0 end) - sum(case when Value < 3.0 then 1 else 0 end) -- or maybe 2.9 ) as TotalVotes from [Ratings] group by Id order by Id desc; ``` Alternatively, you could write: ``` select id, sum(case when Value > 3...
SQL Server allows you to specify condition in aggregate functions.In your case, you need to use SUM with conditions.. So, this is how your final query looks like ``` select Id, Value,SUM(CASE WHEN Value>3.0 THEN 1 ELSE -1 END) AS VoteCount from [Ratings] group by Id order by Id desc ```
17,278
50,616,254
I need to do the following operation in python: I have a list of tuples ``` data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)] ``` I have a list of fields: ``` fields = ["name", "age", "vol", "status", "limit"] ``` Each tuple of the data is for each of the fields in order. I have a dic...
2018/05/31
[ "https://Stackoverflow.com/questions/50616254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434649/" ]
I don't remember having this problem but in at least one case I did something that will work around the issue. I put an index.js in the root folder that runs the actual dependency in dist. Then the bin that npm looks for is a file that's present, and it shouldn't freak out. It won't work until tsc is run, of course....
It looks like `preinstall` script is what you need Add in your `package.json` file as ``` { "scripts": { "preinstall" : "tsc ..." // < build stuff } } ``` Reference <https://docs.npmjs.com/misc/scripts>
17,279
56,501,297
I'm trying to setup Visual Studio Code for python and everything is good except Kivy. I have simple code ``` import kivy from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.widget...
2019/06/07
[ "https://Stackoverflow.com/questions/56501297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7869295/" ]
Maybe it should fix it! ``` MyGrid: <MyGrid>: GridLayout: cols:1 size: root.width, root.height GridLayout: cols:2 Label: text: "Name: " TextInput: multinline:False Label: ...
remove the indent from GridLayout:
17,288
46,999,929
I want to create a Telegram Messenger bot with framework *python-telegram-bot*! Now, the bot must send a message with a specific font. This means the bot sends a message with a different and beautiful font - a font different from the Telegram Messenger font. How can I do it?
2017/10/29
[ "https://Stackoverflow.com/questions/46999929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8444979/" ]
No one (even you the official) can send messages in a different font/color, but you can make a suggestion to [@Telegram](https://twitter.com/telegram). They will consider adding this as a feature. There have limited [formatting options](https://core.telegram.org/bots/api#formatting-options) in the message text, and yo...
The only color that you can use is red or set the background color to gray. ``` str = "`Hello`" #this will turn the text red on Telegram. str = "```Hello```" #this will turn the background color gray of the text on Telegram ``` Then at the **sendMessage** function, you need to add the parameter **parse\_mode** a...
17,291
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
I am assuming that votes for 0 count as votes. So `sum` is not a reasonable option. Try a Counter: ``` >>> from collections import Counter >>> x = Counter([-1,-1,-1, 1,1,1,1,0,0,0,0,0,0,0,0]) >>> x Counter({0: 8, 1: 4, -1: 3}) >>> x.most_common(1) [(0, 8)] >>> x.most_common(1)[0][0] 0 ``` So you could write code li...
You can [count occurences](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python) of 0 and test if they are majority. ``` >>> x = [1, 1, 0, 0, 0] >>> if sum(x) == 0 or x.count(0) >= len(x) / 2.0: ... majority = 0 ... else: ... majority = -1 if (sum(x) < 0) else 1...
17,294
7,692,121
I saw [this question](https://stackoverflow.com/questions/4978738/is-there-a-python-equivalent-of-the-c-null-coalescing-operator) but it uses the ?? operator as a null check, I want to use it as a bool true/false test. I have this code in Python: ``` if self.trait == self.spouse.trait: trait = self.trait else: ...
2011/10/07
[ "https://Stackoverflow.com/questions/7692121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116286/" ]
Yes, you can write: ``` trait = self.trait if self.trait == self.spouse.trait else defaultTrait ``` This is called a [Conditional Expression](http://docs.python.org/reference/expressions.html#conditional-expressions) in Python.
On the null-coalescing operator in C#, what you have in the question isn't a correct usage. That would fail at compile time. In C#, the correct way to write what you're attempting would be this: ``` trait = this.trait == this.spouse.trait ? self.trait : defaultTrait ``` Null coalesce in C# returns the first value t...
17,304
42,871,090
As the title says, is there a way to change the default pip to pip2.7 When I run `sudo which pip`, I get `/usr/local/bin/pip` When I run `sudo pip -V`, I get `pip 1.5.6 from /usr/lib/python3/dist-packages (python 3.4)` If there is no problem at all with this mixed version, please do tell. If there is a problem with ...
2017/03/18
[ "https://Stackoverflow.com/questions/42871090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2400585/" ]
* You can use `alias pip = 'pip2.7'`Put this in your `.bashrc` file(If you're using bash,if zsh it should be `.zshrc`). By the way,you should know that `sudo` command change current user,default `root`.So if you have to change user to `root`,maybe you should put it in `/root/.bashrc` * Or you can make a link ``` ln -...
A very intuitive and straightforward method is just modify the settings in `/usr/local/bin/pip`. You don't need alias and symbolic links. For mine: 1. Check the infor: =================== ``` lerner@lerner:~/$ pip -V ``` > > `pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.4)` > > > ``` lerner@lerner:...
17,305
67,948,945
I want to force the Huggingface transformer (BERT) to make use of CUDA. nvidia-smi showed that all my CPU cores were maxed out during the code execution, but my GPU was at 0% utilization. Unfortunately, I'm new to the Hugginface library as well as PyTorch and don't know where to place the CUDA attributes `device = cuda...
2021/06/12
[ "https://Stackoverflow.com/questions/67948945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15445597/" ]
You can make the entire class inherit `torch.nn.Module` like so: ``` class SentimentModel_t(torch.nn.Module): def __init___(...) super(SentimentModel_t, self).__init__() ... ``` Upon initializing your model you can then call `.to(device)` to cast it to the device of your choice, like so: ``` sentiment_m...
I am a bit late to the party. The python package that I wrote already uses your GPU. You can have a look at the [code to see how it was implemented](https://github.com/oliverguhr/german-sentiment-lib/blob/master/germansentiment/sentimentmodel.py) Just install the package: ``` pip install germansentiment ``` and run...
17,308
39,502,345
I have two columns in a pandas dataframe that are supposed to be identical. Each column has many NaN values. I would like to compare the columns, producing a 3rd column containing True / False values; *True* when the columns match, *False* when they do not. This is what I have tried: ``` df['new_column'] = (df['colum...
2016/09/15
[ "https://Stackoverflow.com/questions/39502345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762492/" ]
Or you could just use the `equals` method: ``` df['new_column'] = df['column_one'].equals(df['column_two']) ``` It is a batteries included approach, and will work no matter the `dtype` or the content of the cells. You can also put it in a loop, if you want.
To my understanding, Pandas does not consider NaNs different in element-wise equality and inequality comparison methods. While it does when comparing entire Pandas objects (Series, DataFrame, Panel). > > NaN values are considered different (i.e. NaN != NaN). - [source](https://pandas.pydata.org/pandas-docs/stable/ref...
17,309
65,583,958
I've a Python program as follows: ``` class a: def __init__(self,n): self.n=n def __del__(self,n): print('dest',self.n,n) def b(): d=a('d') c=a('c') d.__del__(8) b() ``` Here, I have given a parameter `n` in `__del__()` just to clear my doubt. Its output : ``` $ python des.py d...
2021/01/05
[ "https://Stackoverflow.com/questions/65583958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
you cannot. pre-defined dunder methods (methods with leading and trailing double underscore) like `__del__` have a fixed signature. If you define them with another signature, then when python calls them using the non-dunder interface (`del`, `len`, ...), the number of arguments is wrong and it fails. To pass `n` to `...
Python objects become a candidate for garbage collection when there are no more references to them (object tagging), so you do not need to create such a destructor. If you want to add optional arguments to a method, it's common to set them to `None` or an empty tuple `()` ``` def other_del(self, x=None): ...
17,312