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
24,557,707
I have an Echoprint local webserver (uses tokyotyrant, python, solr) set up on a Linux virtual machine. I can access it through the browser or curl in the virtual machine using http//localhost:8080 and in the non-virtual machine (couldn't find out how to say it better) I use the IP on the virtual machine also with the...
2014/07/03
[ "https://Stackoverflow.com/questions/24557707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2996499/" ]
Took a while to figure it out but here's the working code. ``` using System; using System.Runtime.InteropServices; using System.Text; using System.IO; using System.Threading; namespace Foreground { class GetForegroundWindowTest { /// Foreground dll's [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpel...
You can also use ``` private static extern int ShowWindow(int hwnd, int nCmdShow); ``` to hide a window. This method takes the integer handler of the window (instead of pointer). Using **[Spy++](https://msdn.microsoft.com/en-us/library/dd460729.aspx)** (in Visual Studio tools) you can get the **Class Name** and **Wi...
8,216
66,102,225
I'm using `jwilder/nginx-proxy` and `jrcs/letsencrypt-nginx-proxy-companion` images to create the ssl certificates automatically. When the server is updated and I run `docker-compose down` and `docker-compose up -d` the following error appears: ``` letsencrypt_1 | [Mon Feb 8 11:48:47 UTC 2021] Please check log file ...
2021/02/08
[ "https://Stackoverflow.com/questions/66102225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10279746/" ]
I had this problem and finally got it figured out. You need to add a volume to the `nginx-proxy:` and `letsencrypt:` services' `volumes:` sections - something like this: ``` volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - certs:/etc/nginx/certs:ro - vhostd:/etc/nginx/vhost.d - html:/usr/share/nginx/html...
You need to mount `acme:/etc/acme.sh` folder for `nginx-proxy` because it's created each time when you do up/down. Plus, add `acme:` to the last `volumes:` section. Entry from your log file proves it: ``` letsencrypt_1 | [Mon Feb 8 11:48:48 UTC 2021] The domain key is here: /etc/acme.sh/[email protected]/example.com/...
8,217
26,061,610
I am using `python version 2.7` and `pip version is 1.5.6`. I want to install extra libraries from url like a git repo on setup.py is being installed. I was putting extras in `install_requires` parameter in `setup.py`. This means, my library requires extra libraries and they must also be installed. ``` ... install...
2014/09/26
[ "https://Stackoverflow.com/questions/26061610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029816/" ]
You need to make sure you include the dependency in your `install_requires` too. Here's an example `setup.py` ``` #!/usr/bin/env python from setuptools import setup setup( name='foo', version='0.0.1', install_requires=[ 'balog==0.0.7' ], dependency_links=[ 'https://github.com/bala...
Pip removed support for dependency\_links a while back. The [latest version of pip that supports dependency\_links is 1.3.1](https://pip.pypa.io/en/latest/news.html), to install it ``` pip install pip==1.3.1 ``` your dependency links should work at that point. Please note, that dependency\_links were always the last...
8,218
69,450,482
I was trying to install matplotlib but I'm getting this long error. I don't really have any idea what is wrong. ``` ERROR: Command errored out with exit status 1: command: 'C:\Python310\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Bilguun\\AppData\\Local\\Temp\\pip-insta...
2021/10/05
[ "https://Stackoverflow.com/questions/69450482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17079850/" ]
> > *"What causes the segmentation fault..."* > > > There are several places that have potential for segmentation fault. One that stands out is this: ``` char filename[4]; ... sprintf(filename, "%03i.jpg", 0); ``` In this example, `filename` has enough space to contain 3 characters + `nul` terminator. It needs ...
as ryker stated, there are several points of possible failures here. another is `int SIZE = sizeof(raw);` sets SIZE to be the size of a pointer (4/8 bytes).
8,223
23,985,903
I was wondering if there are any BDD-style 'describe-it' unit-testing frameworks for Python that are maintained and production ready. I have found [describe](https://pypi.python.org/pypi/describe/0.1.2), but it doesn't seem to be maintained and has no documentation. I've also found [sure](http://falcao.it/sure) which r...
2014/06/02
[ "https://Stackoverflow.com/questions/23985903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2483075/" ]
I've been looking for this myself and came across [mamba](https://github.com/nestorsalceda/mamba). In combination with the fluent assertion library [expects](https://github.com/jaimegildesagredo/expects) it allows you to write BDD-style unit tests in Python that look like this: ``` from mamba import describe, context,...
If you are expecting something exactly like rspec/capybara in python, then I am afraid you are in for a disappointment. The problem is ruby provides you much more freedom than python does (with much more support for open classes and extensive metaprogramming). I have to say there is a fundamental difference between phi...
8,225
49,425,827
I want to import some tables from a postgres database into Elastic search and also hold the tables in sync with the data in elastic search. I have looked at a course on udemy, and also talked with a colleague who has a lot of experience with this issue to see what the best way to do it is. I am surprised to hear from b...
2018/03/22
[ "https://Stackoverflow.com/questions/49425827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4415079/" ]
It depends on your use case. A common practice is to handle this on the application layer. Basically what you do is to replicate the actions of one db to the other. So for example if you save one entry in postgres you do the same in elasticsearch. If you do this however you'll have to have a queuing system in place. ...
As anything in life,best is subjective. Your colleague likes to write and maintain code to keep this in sync. There's nothing wrong with that. I would say the best way would be to use some data pipeline. There's plethora of choices, really overwheleming, you can explore the various solutions which support Postgres a...
8,226
3,254,096
My Python application is constructed as such that some functionality is available as plugins. The plugin architecture currently is very simple: I have a plugins folder/package which contains some python modules. I load the relevant plugin as follows: ``` plugin_name = blablabla try: module = __import__(plugin_nam...
2010/07/15
[ "https://Stackoverflow.com/questions/3254096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50899/" ]
[PyInstaller](http://www.pyinstaller.org) lets you import external files as well. If you run it over your application, it will not package those files within the executable. You will then have to make sure that paths are correct (that is, your application can find the modules on the disk in the correct directory), and ...
I suggest you use pkg\_resources entry\_points features (from setuptools/distribute) to implement plugin discovery and instantiation: first, it's a standard way to do that; second, it does not suffer the problem you mention AFAIK. All you have to do to extend the application is to package some plugins into an egg that ...
8,229
23,599,970
I would like to ask your help. I have started learning python, and there are a task that I can not figure out how to complete. So here it is. We have a input.txt file containing the next 4 rows: ``` f(x, 3*y) * 54 = 64 / (7 * x) + f(2*x, y-6) x + f(21*y, x - 32/y) + 4 = f(21 ,y) 86 - f(7 + x*10, y+ 232) = f(12*x-4...
2014/05/12
[ "https://Stackoverflow.com/questions/23599970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3626828/" ]
The Firemonkey canvas on Windows is probably not using the GPU. If you are using XE6 you can > > set the global variable FMX.Types.GlobalUseGPUCanvas to true in the initialization section. > > > [Documentation](http://docwiki.embarcadero.com/Libraries/en/FMX.Types.GlobalUseGPUCanvas) Otherwise, in XE5 stick a T...
When you draw a circle in canvas (ie GPUCanvas) then you draw in fact around 50 small triangles. this is how GPUCanvas work. it's even worse with for exemple Rectangle with round rect. I also found that Canvas.BeginScene and Canvas.endScene are very slow operation. you can try to put form.quality to highperformance to ...
8,236
25,279,746
I am writing a test application in python and to test some particular scenario, I need to launch my python child process in windows SYSTEM account. I can do this by creating exe from my python script and then use that while creating windows service. But this option is not good for me because in future if I change anyth...
2014/08/13
[ "https://Stackoverflow.com/questions/25279746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1811739/" ]
1. Create a service that runs permanently. 2. Arrange for the service to have an IPC communications channel. 3. From your desktop python code, send messages to the service down that IPC channel. These messages specify the action to be taken by the service. 4. The service receives the message and performs the action. Th...
You could also use Windows Task Scheduler, it can run a script under SYSTEM account and its interface is easy (if you do not test too often :-) )
8,237
49,551,704
I'm new to python and selenium and wondering how I could take a group of text from a web page and input it into an array. Currently, what I have now is a method that, instead of using an array, uses a string and un-neatly displays it. ``` # returns a list of names in the order it is displayed def gather_names(self): ...
2018/03/29
[ "https://Stackoverflow.com/questions/49551704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9519161/" ]
When you use `pyinstaller` to compile your script to `executable` in `windows 10` and want to use it in `window 7` it won't work. But you can compile it with `pyinstaller` in `windows 7` and use the executable in `windows 7, 8, and 10` Also take note of this, take into consideration `32-bit and 64-bit` version of the...
maybe you could try using cx\_Freeze package to build your app, in windows (Note: if your PC is 64 Bits the app gonna be in that architecture and 32Bits if is x86 or 32 Bits) run cmd and type this ``` pip install cx_Freeze ``` Then make a file called setup.py ubicated in the same directory into that and add this co...
8,240
66,132,304
i am trying to post on facebook wall using selenium in python. I am able to login but after login it cant find class name of status box which i copied from browser here is my code- ``` from selenium import webdriver from selenium.webdriver.common.keys import Keys import time user_name = "email" password = "password"...
2021/02/10
[ "https://Stackoverflow.com/questions/66132304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11942305/" ]
try to find element by Xpath for example: **driver.find\_element(By.XPATH, '//button[text()="Some text"]')** to find the xpath from the browser, just right click on something in the webpage and press inspect after that right click, a menu will appear, navigate to copy then another menu will appear, press copy fullpath...
The problem is that `driver.find_element_by_class_name()` can be used for one class, and not multiple classes as you have: `a8c37x1j ni8dbmo4 stjgntxs l9j0dhe7` which are multiple classes separated by spaces. Refer to the solution [suggested here](https://stackoverflow.com/a/44760303/12106481), it suggests using `find...
8,241
53,384,795
I have this data structure: ``` [array([[0, 1, 0, 1, 1, 1, 0, 5, 1, 0, 2, 1]]), array([[0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0], [1, 3, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0]]), array([[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], etc.... ``` I want to flatten this into a list of lists...
2018/11/20
[ "https://Stackoverflow.com/questions/53384795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I believe you're looking for `vstack`: ``` >>> np.vstack(l) array([[0, 1, 0, 1, 1, 1, 0, 5, 1, 0, 2, 1], [0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0], [1, 3, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) ``` Note that this is equivalen...
Use `flatten`: ``` print([i.flatten() for i in l]) ``` Or: ``` print(list(map(lambda x: x.flatten(),l))) ``` Both output: ``` [array([0, 1, 0, 1, 1, 1, 0, 5, 1, 0, 2, 1]), array([0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 1, 3, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0]), array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 0,...
8,242
62,262,007
``` import base64 s = "05052020" ``` python2.7 ``` base64.b64encode(s) ``` output is string `'MDUwNTIwMjA='` python 3.7 ``` base64.b64encode(b"05052020") ``` output is bytes ``` b'MDUwNTIwMjA=' ``` I want to replace = with "a" ``` s = str(base64.b64encode(b"05052020"))[2:-1] s = s.replace("=", "a") ``` ...
2020/06/08
[ "https://Stackoverflow.com/questions/62262007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4450090/" ]
If you tried both language servers and VS Code made you reload then you have tried the options currently available to you from the Python extension. We are actively working on making it better, though, and hope to having something to say about it shortly. But if you can't wait you can try something like <https://marke...
It might be a problem related to Pylance. By default, Pylance only looks for modules in the root directory. Making some tweaks in the settings made sure everything I import in VSCode works as if it's imported in PyCharm. Please see: <https://stackoverflow.com/a/67099842/6381389>
8,243
69,675,173
Following is the content of `foo.py` ```py import sys print(sys.executable) ``` When I execute this, I can get the full path of the the Python interpreter that called this script. ```sh $ /mingw64/bin/python3.9.exe foo.py /mingw64/bin/python3.9.exe ``` How to do this in nim (`nimscript`)?
2021/10/22
[ "https://Stackoverflow.com/questions/69675173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1805129/" ]
The question mentions [NimScript](https://nim-lang.github.io/Nim/nims.html), which has other uses in the Nim ecosystem, but can also be used to write executable scripts instead of using, e.g., Bash or Python. You can use the [`selfExe`](https://nim-lang.github.io/Nim/nimscript.html#selfExe) proc to get the path to the ...
Nim is compiled, so I assume you want to get the path of the application's own binary? If so, you can do that with: ``` import std/os echo getAppFilename() ```
8,244
47,405,748
I am reading python official documentation word by word. In the 3.3. Special method names [3.3.1. Basic customization](https://docs.python.org/3/reference/datamodel.html#basic-customization) It does specify 16 special methods under `object` basic customization, I collect them as following: ``` In [47]: bc =['__new__...
2017/11/21
[ "https://Stackoverflow.com/questions/47405748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7301792/" ]
I hope this will help you and it works fine on my project. ``` public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123; public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 124; public static final int MY_PERMISSIONS_REQUEST_CAMERA = 124; @TargetApi(Build...
Try adding permission to MANIFEST file. ``` <uses-permission android:name="android.permission.CAMERA" /> ``` and in your checkPermissionsR() get this permission ``` ContextCompat.checkSelfPermission(this, Manifest.permission.Camera) ```
8,246
59,783,094
I am running `py.test` 4.3.1 with `python` 3.7.6 on a Mac (Mojave) and I want to get the list of markers for the 'session', once at the begin of the run. In `conftest.py` I have tried using the following function: ``` @pytest.fixture(scope="session", autouse=True) def collab_setup(request): print([marker.name fo...
2020/01/17
[ "https://Stackoverflow.com/questions/59783094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1581090/" ]
If the `locationName` gets as input `[1,5]` then the code should look like this: ``` filterData(locationName: number[]) { return ELEMENT_DATA.filter(object => { return locationName.includes(object.position); }); } ```
You can use [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) ``` ELEMENT_DATA.filter(function (object) { return locationName.indexOf(object.position) !== -1; // -1 means not present }); ``` or with underscore JS , using the same predicate: `...
8,255
14,490,845
Python 2.6 on Redhat 6.3 I have a device that saves 32 bit floating point value across 2 memory registers, split into most significant word and least significant word. I need to convert this to a float. I have been using the following code found on SO and it is similar to code I have seen elsewhere ``` #!/usr/bin/en...
2013/01/23
[ "https://Stackoverflow.com/questions/14490845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1635823/" ]
If you have the raw bytes (e.g. read from memory, from file, over the network, ...) you can use `struct` for this: ``` >>> import struct >>> struct.unpack('>f', '\x3f\x9a\xec\xb5')[0] 1.2103487253189087 ``` Here, `\x3f\x9a\xec\xb5` are your input registers, 16282 (hex 0x3f9a) and 60597 (hex 0xecb5) expressed as byte...
The way you've converting the two `int`s makes implicit assumptions about [endianness](http://en.wikipedia.org/wiki/Endianness) that I believe are wrong. So, let's back up a step. You know that the first argument is the most significant word, and the second is the least significant word. So, rather than try to figure ...
8,256
58,770,519
How to do this ``` c++ -> Python -> c++ ^ | | | ----------------- ``` 1. C++ app is hosting python. 2. Python creates a class, which is actually a wrapping to c/c++ object 3. How to get access from hosting c++ to c/c++ pointer of this object created by python? **Example with code:** ...
2019/11/08
[ "https://Stackoverflow.com/questions/58770519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/548894/" ]
``` #include <Python.h> int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); Py_Initialize(); object module = import("__main__"); object space = module.attr("__dict__"); exec("from cat import Cat \n" "cat = Cat(10) \n", space); Cat& cat = extract<Cat&>(space["cat"]); std::cout<...
In case the wrapper is open source, use the wrapper's python object struct from C++. Cast the PyObject \* to that struct which should have a PyObject as its first member iirc, and simply access the pointer to the C++ instance. Make sure that the instance is not deleted while you're using it by keeping the wrapper inst...
8,257
6,124,701
I feel like this is simple, but I just don't know enough about python to do it correctly. I have two files: 1. File with lines listing an id number and whether that id is used. Format is 'id, isUsed'. 2. File with rules containing one rule for each id. So what I want to do is to parse through the file with id-used p...
2011/05/25
[ "https://Stackoverflow.com/questions/6124701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240522/" ]
I suggest you read the rules file into a dictionary (id -> rule). Then, as you read the config file, write out the corresponding rule (including a comment if you need to). some pseudocode: ``` rules = {} for id, rule in read_rules_file(): rules[id] = rule for id, isUsed in read_pairs_file(): if isUsed: ...
I don't know why I didn't think of this before, but there is another way to do this. First, you read which rules should be used (or not used) into memory, I stored it into a dictionary. ``` def readRulesIntoMemory(fileName): rules = {} # Open csv file with rule id, isUsed pairs fd = open(fileName, 'r') ...
8,258
63,749,945
I'm a beginner at python and I made this random date generator which should generate year-month-date output. And 4,6,9,11 months have 30 days, all others 31. But I'm having a problem where february in leap year still generates date=30 despite if and elif having the condition where M must be 2. ``` import random impor...
2020/09/05
[ "https://Stackoverflow.com/questions/63749945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14224115/" ]
Several problems mentioned in comments: * you are using `rand` instead of `random` * you are using `G` when presumably it should be `Y` See a refactored code, rewriting the `if` statements to first test `M` then test `Y`. ``` import random import calendar for i in range(500): Y = random.randint(0, 170) M = r...
The final else-block is executed if `M == 2` and overwrites `D`. Simple solution can be to reorder the two if parts: ``` import random as rand import calendar for i in range(500): G = rand.randint(0, 170) M = rand.randint(1, 12) if M == 4 or M == 6 or M == 9 or M == 11: D=rand.randint(1, 30) ...
8,259
6,132,423
I was trying to install SCRAPY and play with it. The tutorial says to run this: ``` scrapy startproject tutorial ``` Can you please break this down to help me understand it. I have various releases of Python on my Windows 7 machine for various conflicting projects, so when I installed Scrapy with their .exe, i...
2011/05/26
[ "https://Stackoverflow.com/questions/6132423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160245/" ]
scrapy is a batch file which execute a python file called "scrapy", so you need to add the file "scrapy"'s path to your PATH environment. if that is still not work, make "scrapy.py" file with content ``` from scrapy.cmdline import execute execute() ``` and run `\python26_32bit\python.exe scrapy.py startproject tuto...
Try ``` C:\Python26_32bit\Scripts\Scrapy startproject tutorial ``` or add `C:\Python26_32bit\Scripts` to your path
8,260
70,058,771
Im trying to use python to determine the continued fractions of pi by following the stern brocot tree. Its simple, if my estimation of pi is too high, take a left, if my estimation of pi is too low, take a right. Im using `mpmath` to get arbitrary precision floating numbers, as python doesn't support that, but no matt...
2021/11/21
[ "https://Stackoverflow.com/questions/70058771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16155472/" ]
Never fails that as soon as I post a question I find the answer. For anyone else looking for something similar: The first bracket matches all slashes `[/]` The parenthesis capture the group, in this case the group of numbers `([0-9])` The `[0-9]` searches the range of numbers between 0 and 9 `{8}` is the quantifier, i...
Use ```php /\d{8}/ ``` See [regex proof](https://regex101.com/r/sPLT7b/1). **EXPLANATION** ```php -------------------------------------------------------------------------------- / '/' -------------------------------------------------------------------------------- \d{8} ...
8,263
71,857,414
**The error :** from asyncio.windows\_events import NULL File "/app/.heroku/python/lib/python3.10/asyncio/windows\_events.py", line 6, in raise ImportError('win32 only') ImportError: win32 only **please how can i fix this ?**
2022/04/13
[ "https://Stackoverflow.com/questions/71857414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18793327/" ]
I had the same error while trying to deploy: ``` File "/tmp/build_4a1c8563/base/models.py", line 1, in <module> from asyncio.windows_events import NULL File "/app/.heroku/python/lib/python3.9/asyncio/windows_events.py", line 6, in <module> raise ImportError('win32 only') ``` I deleted the "from asyncio...
I had the same error while deploying: your IDE have imported `from asyncio.windows_events import NULL` line automatically while you were typing NULL Just delete this line ``` from asyncio.windows_events import NULL ```
8,264
42,164,772
I can't achieve to make summaries work with the Estimator API of Tensorflow. The Estimator class is very useful for many reasons: I have already implemented my own classes which are really similar but I am trying to switch to this one. Here is the code sample: ``` import tensorflow as tf import tensorflow.contrib.la...
2017/02/10
[ "https://Stackoverflow.com/questions/42164772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5184894/" ]
The intended use case is that you let the Estimator save summaries for you. There are options in [RunConfig](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/estimators/run_config.py#L182) for configuring summary writing. RunConfigs get passed when [constructing the Estimator](...
Just have `tf.summary.scalar("loss", loss)` in the `model_fn`, and run the code without `summary_hook`. The loss is recorded and shown in the tensorboard. --- See also: * [Tensorflow - Using tf.summary with 1.2 Estimator API](https://stackoverflow.com/questions/45086109/tensorflow-using-tf-summary-with-1-2-estimator...
8,265
24,021,831
I'm a Transifex user, I need to retrieve my dashboard page with the list of all the projects of my organization. that is, the page I see when I login: <https://www.transifex.com/organization/(my_organization_name)/dashboard> I can access Transifex API with this code: ``` import urllib.request as url usr = 'myusernam...
2014/06/03
[ "https://Stackoverflow.com/questions/24021831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3704129/" ]
The call to > > /projects/ > > > returns your projects along with all the public projects that you can have access (like what you said). You can search for the ones that you need by modifying the call to something like: > > <https://www.transifex.com/api/2/projects/?start=1&end=6> > > > Doing so the number ...
Transifex comes with an API, and you can use it to fetch all the projects you have. I think that what you need [this](http://docs.transifex.com/developer/api/projects) GET request on projects. It returns a list of (slug, name, description, source\_language\_code) for all projects that you have access to in JSON format...
8,266
60,202,828
I have been learning about the Trie structure through python. What is a little bit different about his trie compared to other tries is the fact that we are trying to implement a counter into every node of the trie in order to do an autocomplete (that is the final hope for the project). So far, I decided that having a r...
2020/02/13
[ "https://Stackoverflow.com/questions/60202828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11659038/" ]
Try this ``` mapply(function(x,y){paste(intersect(x,y),collapse=", ")}, strsplit(as.character(df$text),"\\, | "), strsplit(as.character(df$word),"\\, | ")) [1] "red, green" "red" "blue" ```
``` library(tidyverse) df %>% mutate(newcol = stringr::str_extract_all(text,gsub(", +","|",word))) country text word newcol 1 CA paint red green green, red, blue red, green 2 IN painting red red red 3 US painting blue re...
8,267
12,794,357
I have 2 python scripts inside my c:\Python32 1)Tima\_guess.py which looks like this: ``` #Author:Roshan Mehta #Date :9th October 2012 import random,time,sys ghost =''' 0000 0 000---- 00000-----0-0 ----0000---0 ''' guess_taken = 0 print('Hello! What is your name?') name = input() light_switch = random.randint(1,12...
2012/10/09
[ "https://Stackoverflow.com/questions/12794357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1716525/" ]
After building, add re.pyc to the library.zip file. To get re.pyc, all you need to do is run re.py successfully, then open `__pycache__` folder, then you will see a file like re.cpython-32.pyc, rename it to re.pyc and voila!
**setup.py** ``` from cx_Freeze import setup, Executable build_exe_options = {"includes": ["re"]} setup( name = "Console game", version = "0.1", description = "Nothing!", options = {"build_exe": build_exe_options}, executables = [Executable("Tima_guess.py")]) ```
8,269
55,577,991
I am trying to install `fiona=1.6` but I get the following error ``` conda install fiona=1.6 WARNING: The conda.compat module is deprecated and will be removed in a future release. Collecting package metadata: done Solving environment: - The environment is inconsistent, please check the package plan carefully The fo...
2019/04/08
[ "https://Stackoverflow.com/questions/55577991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3590067/" ]
Python Versions =============== The [Conda Forge channel only has gdal v1.11.4 for Python 2.7, 3.4, and 3.5](https://anaconda.org/conda-forge/gdal/files?version=1.11.4). You either need to use a newer version of Fiona (current is 1.8) or make a new env that includes one of those older Python versions. For example, ...
Doing what the error message told me to, > > To search for alternate channels that may provide the conda package you're > looking for, navigate to <https://anaconda.org> > > > and typing in `gdal` in the search box led me to <https://anaconda.org/conda-forge/gdal> which has this installation instruction: > > `...
8,270
23,871,680
I downloaded the git repo from the official link, ``` git clone git:// ``` and I ran `./configure && make && make install` where the `make install` returns with error: ``` LINK(target) /usr/local/bin/node/out/Release/node: Finished touch /usr/local/bin/node/out/Release/obj.target/node_dtrace_header.stamp touc...
2014/05/26
[ "https://Stackoverflow.com/questions/23871680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1948292/" ]
You can use an injection interceptor. > > For EJB 3 Session Beans and Message-Driven Beans, Spring provides a > convenient interceptor that resolves Spring 2.5's @Autowired > annotation in the EJB component class: > org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor. > This interceptor can be app...
I understand you question as: you have problem to inject a request scoped bean into another using spring. so try this: ``` <bean id="boo" class="Boo" scope="request"> <aop:scoped-proxy/> </bean> <bean id="foo" class="Foo"> <property name="boo" ref="Boo" /> </bean> ```
8,271
13,549,699
I wish to mock a class with the following requirements: * The class has public read/write properties, defined in its `__init__()` method * The class has public attribute which is auto-incremented on object creation * I wish to use `autospec=True`, so the class's API will be strictly checks on calls A simplified class...
2012/11/25
[ "https://Stackoverflow.com/questions/13549699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/499721/" ]
Since no answers are coming in, I'll post what worked for me (not necessarily the best approach, but here goes): I've created a mock factory which creates a `Mock()` object, sets its `id` property using the syntax described [here](http://www.voidspace.org.uk/python/mock/mock.html#mock.PropertyMock), and returns the ob...
Sorry to dig up an old post, but something that would allow you to do precisely what you would like to achieve is to patch `calc_x_times_y` and `calc_x_div_y` and set `autospec=True` there, as opposed to Mocking the creation of the entire class. Something like: ``` @patch('MyClass.calc_x_times_y') @patch('MyClass.cal...
8,272
58,016,261
So, i am trying to create a linear functions in python such has `y = x` without using `numpy.linspace()`. In my understanding numpy.linspace() gives you an array which is discontinuous. But to fo I am trying to find the intersection of `y = x` and a function unsolvable analytically ( such has the one in the picture ) ...
2019/09/19
[ "https://Stackoverflow.com/questions/58016261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12091717/" ]
Since your functions are differentiable, you could use the [Newton-Raphson method](https://en.wikipedia.org/wiki/Newton%27s_method) implemented by `scipy.optimize`: ``` >>> scipy.optimize.newton(lambda x: 1.5*(1-math.exp(-x))-x, 10) 0.8742174657987283 ``` Computing the error is very straightforward: ``` >>> def f(x...
“Not solvable analytically” means there is no closed-form solution. In other words, you cant write down a single answer on paper like a number or equation and circle it and say ”thats my answer.” For some math problems it’s impossible to do so. Instead, for these kinds of problems, we can approximate the solution by ru...
8,273
15,040,884
I want to list all the keys stored in the memcached server. I googled for the same, I got some python/php scripts that can list the same. I tested it but all went failed and none gave me full keys. I can see thousands of keys using telnet command ``` stats items ``` I used perl script that uses telnet to list keys,...
2013/02/23
[ "https://Stackoverflow.com/questions/15040884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308498/" ]
memcache does not provide an api to exhaustively list all keys. "stats items" is as good as it gets to list the first 1M of keys. More info here: <http://www.darkcoding.net/software/memcached-list-all-keys/> Not sure if that helps you but redis (which could be considered a superset of memcache) provides a more compreh...
It you use python-memcached, and would like to export all the items in memcache server, I summerized two methods to the problem in this question: [Export all keys and values from memcached with python-memcache](https://stackoverflow.com/questions/5730276/export-all-keys-and-values-from-memcached-with-python-memcache)
8,275
3,224,924
Is there anything in python that lets me dump out a random object in such a way as to see its underlying data representation? I am coming from Perl where Data::Dumper does a reasonable job of letting me see how a data structure is laid out. Is there anything that does the same thing in python? Thanks!
2010/07/11
[ "https://Stackoverflow.com/questions/3224924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365530/" ]
Well `Dumper` in Perl gives you a representation of an object that can be `eval`'d by the interpreter to give you the original object. An object's `repr` in Python tries to do that, and sometimes it's possible. A `dict`'s `repr` or a `str`'s `repr` do this, and some classes like `datetime` and `timedelta` also do this....
After much searching about for this exactly myself, I came across this Dumper equivalent which I typically import now. <https://salmon-protocol.googlecode.com/svn-history/r24/trunk/salmon-playground/dumper.py>
8,276
9,595,009
What is the difference between [`warnings.warn()`](https://docs.python.org/library/warnings.html#warnings.warn) and [`logging.warn()`](https://docs.python.org/library/logging.html#logging.Logger.warning) in terms of what they do and how they should be used?
2012/03/07
[ "https://Stackoverflow.com/questions/9595009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84952/" ]
I agree with the other answer -- `logging` is for logging and `warning` is for warning -- but I'd like to add more detail. Here is a tutorial-style HOWTO taking you through the steps in using the `logging` module. <https://docs.python.org/3/howto/logging.html> It directly answers your question: > > warnings.warn()...
Besides the [canonical explanation in official documentation](https://docs.python.org/2/howto/logging.html#when-to-use-logging) > > warnings.warn() in library code if the issue is avoidable and the client application should be modified to eliminate the warning > > > logging.warning() if there is nothing the client ...
8,277
2,248,699
Is there something like twisted (python) or eventmachine (ruby) in .net land? Do I even need this abstraction? I am listening to a single IO device that will be sending me events for three or four analog sensors attached to it. What are the risks of simply using a looped `UdpClient`? I can't miss any events, but will ...
2010/02/11
[ "https://Stackoverflow.com/questions/2248699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804/" ]
I think you are making it too complicated. Just have 1 UDP socket open, and set an async callback on it. For every incoming packet put it in a queue, and set the callback again. Thats it. make sure that when queuing and dequeueing you set a lock on the queue. it's as simple as that and performance will be great. R
I would recommend [ICE](http://www.zeroc.com) it's a communication engine that will abstract threading and communication to you (documentation is kind of exhaustive).
8,279
57,087,455
I need to compare data in two tables. These tables are similar in schema but will have different data values. I want to export these data to csv or similar format and then check for differences. I would like to perform this check with a python script. I have already figured out how to export the data to csv format. Bu...
2019/07/18
[ "https://Stackoverflow.com/questions/57087455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4817150/" ]
I finally managed to get it working by adding `contentContainerStyle={{borderRadius: 6, overflow: 'hidden'}}` to the FlatList.
Recreated the structure and for me its working fine with border radius Snack link: <https://snack.expo.io/@msbot01/disrespectful-chocolate> ``` <View style={styles.container}> <ImageBackground source={{uri: 'https://artofislamicpattern.com/wp-content/uploads/2012/10/3.jpg'}} style={{width: '100%', height: '100...
8,282
30,950,941
I have my Django app set up on Elastic Beanstalk and recently made a change to the DB that I would like to have applied to the live DB now. I understand that I need to set this up as a container command, and after checking the DB I can see that the migration was run, but I can't figure out how to have more controls ove...
2015/06/20
[ "https://Stackoverflow.com/questions/30950941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2989731/" ]
Make sure that the same settings are used when migrating and running! Thus I would recommend you change this kind of code in ***django.config*** ```yaml container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate" leader_only: true ``` to: ```yaml contain...
In reference to Oscar Chen answer, you can set environmental variables using eb cli with ``` eb setenv key1=value1 key2=valu2 ...etc ```
8,284
57,901,995
i have a dockerfile which looks like this: ``` FROM python:3.7-slim-stretch ENV PIP pip RUN \ $PIP install --upgrade pip && \ $PIP install scikit-learn && \ $PIP install scikit-image && \ $PIP install rasterio && \ $PIP install geopandas && \ $PIP install matplotlib COPY sentools sentool...
2019/09/12
[ "https://Stackoverflow.com/questions/57901995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11310755/" ]
If the base code is same, and only the container is supposed to run up with different Python Script, So then I will suggest using single Docker and you will not worry about the management of two docker image. Set `vegetation.py` to default, when container is up without passing ENV it will run `vegetation.py` and if th...
If you insist in creating separate images, you can always use the [ARG](https://docs.docker.com/engine/reference/builder/#arg) command. ``` FROM python:3.7-slim-stretch ARG file_to_copy ENV PIP pip RUN \ $PIP install --upgrade pip && \ $PIP install scikit-learn && \ $PIP install scikit-image && \ $PIP...
8,294
18,238,558
I am new to python language. My problem is I have two python scripts : Automation script A and a main script B. Script A internally calls script B. Script B exits whenever an exception is caught using sys.exit(1) functionality. Now, whenever script B exits it result in exit of script A also. Is there any way to stop ex...
2013/08/14
[ "https://Stackoverflow.com/questions/18238558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2286286/" ]
You should encapsulate the code in a try except block. That will catch your exception, and continue executing script A.
`sys.exit()` actually raises a `SystemExit` exception which is caught and handled by the Python interpreter. All you have to do is put the call into to "script B" into a try/except block that catches `SystemExit` before it bubbles all the way up. For example: ``` try: script_b.do_stuff() except SystemExit as e: ...
8,297
63,867,203
I wrote some code in python to see how many times one number can be divided by a number, until it gets a value of one. ``` counter_var = 1 quotient = num1/num2 if quotient<1: print('1 time') else: while quotient >= 1: quotient = num1/num2 counter_var = counter_var + 1 print(counter_var) ...
2020/09/13
[ "https://Stackoverflow.com/questions/63867203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14108602/" ]
you are not changing the value of quotient in the while loop. it remains constant. instead of **quotient = num1/num2** it should be **quotient /= num2** if I understand your problem correctly.
well to start, you're missing assignment to numbers, in the case of num1>num2 , you will be entering an endless while loop and hence you will never get to the `print(counter_var)` snippet
8,298
3,300,716
I'm attempting to use mysql after only having worked with sqlite in the past. I've installed `XAMPP` on Linux (ubuntu) and have `mysql` up and running fine (seems like that with phpMyadmin at least). However, I'm having trouble getting the MySQLdb (the python lib) working {installed this using apt}. to be exact: ```p...
2010/07/21
[ "https://Stackoverflow.com/questions/3300716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264875/" ]
For the record (and thanks to a pointer from Igancio), I found that the below works (terrible I didn't think of this before): ``` db=MySQLdb.connect( user="root" ,passwd="" ,db="my_db" ,unix_socket="/opt/lampp/var/mysql/mysql.sock") ```
It means that you didn't start the MySQL server, or it's configured to not use a domain socket.
8,303
53,798,252
I'm fairly new to python and attempting to add lines 1-10 of a csv into a JSON file, however, I only seem to be getting the 10th line of the CSV. I can't seem to figure out what is incorrect about my argument. Any help appcreated! ``` import csv, json, itertools csvFilePath = "example.csv" jsonFilePath = "example.jso...
2018/12/15
[ "https://Stackoverflow.com/questions/53798252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10796111/" ]
At `data = csvRow`, the `data` variable keeps getting overwritten, so at the end only the last line you read will be inside `data`. Try something like this: ``` import csv, json, itertools csvFilePath = "example.csv" jsonFilePath = "example.json" # Read the CSV and add data to a dictionary data = {} with open(csvFil...
Assuming that the input CSV is ``` 1,2,3,4,5 a,b,c,d,e ``` We have the following code: ``` import json import csv inpf = open("test.csv", "r") csv_reader = csv.reader(inpf) # here you slice the columns with [2:4] for example lines = [row[2:4] for row in csv_reader] inpf.close() lines_json = json.dumps(lines) out...
8,306
43,732,642
I need the status of the task like if it is running or upforretry or failed within the same dag. So i tried to get it using the below code, though i got no output... ``` Auto = PythonOperator( task_id='test_sleep', python_callable=execute_on_emr, op_kwargs={'cmd':'python /home/hadoop/test/testsleep.py'}, ...
2017/05/02
[ "https://Stackoverflow.com/questions/43732642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6714806/" ]
Okay, I think I know what you're doing and I don't really agree with it, but I'll start with an answer. A straightforward, but hackish, way would be to query the task\_instance table. I'm in postgres, but the structure should be the same. Start by grabbing the task\_ids and state of the task you're interested in with ...
You can use the command line Interface for this: ``` airflow task_state [-h] [-sd SUBDIR] dag_id task_id execution_date ``` For more on this you can refer official airflow documentation: <http://airflow.incubator.apache.org/cli.html>
8,308
12,125,362
In a [previous question](https://stackoverflow.com/questions/12124275/splitting-a-string-by-capital-letters-python), it was suggested that, in order to divide a string and store it, I should use a list, like so: ``` [a for a in re.split(r'([A-Z][a-z]*)', 'MgSO4') if a] ['Mg', u'S', u'O', u'4'] ``` What I'd like to a...
2012/08/25
[ "https://Stackoverflow.com/questions/12125362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1423819/" ]
If your goal is to be able to add up the molecular weights of the atoms comprising a molecule, I suggest doing your regular expressions a bit differently. Instead of having the numbers mixed in with the element symbols in your split list, attach them to the preceding element instead (and attach a 1 if there was no numb...
After running ``` >>> import re >>> elements = [a for a in re.split(r'([A-Z][a-z]*)', 'MgSO4') if a] ``` you can access the splitted parts using indices ``` >>> print elements[0] 'Mg' >>> print elements[-1] # print the last element '4' ```
8,313
34,794,417
I am trying to make kivy work with SDL2 on centos 7 but when I run my main.py I get the following messages: ``` [INFO ] [Logger ] Record log in /home/etienne/.kivy/logs/kivy_16-01-14_51.txt [INFO ] [Kivy ] v1.9.1 [INFO ] [Python ] v2.7.5 (default, Nov 20 2015, 02:00:19) [GCC 4.8.5 20150623 (Red...
2016/01/14
[ "https://Stackoverflow.com/questions/34794417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5269531/" ]
Actually `sprintf` didn't work for me, so if you don't mind a common dependency: ``` #reproducible example -- this happens with zip codes sometimes X <- data.frame(A = c('10002','8540','BIRD'), stringsAsFactors=FALSE) # X$A <- sprintf('%05s',X$A) didn't work for me # Note in ?sprintf: 0: For numbers, pad to the field...
Try something like this (assuming data frame name and column name are right): ``` element_of_X$a <- with(element_of_X , ifelse(nchar(a) == 4, paste('0', a, sep = ''), a) ```
8,315
46,050,045
I would like to run a bigquery query from python only if it is below a certain cost estimation. Is there a way to programmatically check the estimated cost of a query before executing it, just like the Web UI (see attached image)? [![enter image description here](https://i.stack.imgur.com/UWdbL.png)](https://i.stack.i...
2017/09/05
[ "https://Stackoverflow.com/questions/46050045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1134753/" ]
Yes, you can use the `dryRun` flag. This will return `totalBytesProcessed` i.e. the amount of data that will be processed if the query is executed. <https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.dryRun> [![enter image description here](https://i.stack.imgur.com/Rd2lO.png)](https://i.stac...
> > I would like to run a bigquery query from python only if it is below a certain cost estimation > > > First, please note - BigQuery UI in fact uses DryRun which only estimates `Total Bytes Processed` leaving another important factor `Billing Tier` unknown. Use of DryRun of course useful and can help in cert...
8,324
59,077,162
I am using Python 3.8 and Pip 3.8 I cannot seem to install certain modules using pip. For example, when attempting to install the keras module: ``` (venv) C:\Users\Spencer Pruitt\PycharmProjects\MNIST Analyzer>pip install keras Collecting keras Using cached https://files.pythonhosted.org/packages/ad/fd/6bfe87920d7f...
2019/11/27
[ "https://Stackoverflow.com/questions/59077162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12447974/" ]
Please use version <3.7 of python for numpy installation. Or see module/package required which version of python. So, just upgrade and degrade the python version to work with packages.
See [this thread](https://github.com/numpy/numpy/issues/11451) re: spaces in path causing issues with installing numpy. Any possibility of moving your virtual environment/project to something like "C:\Temp\MNIST\_Analyzer"? [This thread](https://stackoverflow.com/questions/15472430/using-virtualenv-with-spaces-in-a-p...
8,325
28,664,632
This is my project set up: ``` my_project ./my_project ./__init__.py ./foo ./__init__.py ./bar.py ./tests ./__init__.py ./test_bar.py ``` Inside `test_bar.py` I have the following import statement: `from foo import bar` However wh...
2015/02/22
[ "https://Stackoverflow.com/questions/28664632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2680879/" ]
``` import sys sys.path.append('/path/to/my_project/') ``` Now you can import ``` from foo import bar ```
You can use relative imports: ``` from ..foo import bar ``` <https://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports> but i think too that using absolute paths by [installing](https://docs.python.org/2/distutils/setupscript.html) your project in venv is better way.
8,326
62,126,379
Very sorry in advance for the long paste. The code is straight from the text. It may be due to class `Scene`, that seems to have the instruction to: subclass it and implement enter(). But I don't know what that means. ```py from sys import exit from random import randint from textwrap import dedent class Scene(obj...
2020/06/01
[ "https://Stackoverflow.com/questions/62126379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9808986/" ]
The `enter` method for the `Death` Scene doesn't return anything. In Python, all functions without an explicit return statement return `None`, which explains the error you're getting. ``` class Death(Scene): quips = [ "You died. You kinda suck at this.", "Your Mom would be proud...if she were sma...
As the error says, ``` next_scene_name = current_scene.enter() AttributeError: 'Nonetype' object has no attribute 'enter' ``` That means that your `current_scene` variable is equal to `None` when you call `current_scene.enter()` in the `play` method. You need to make sure the variable `current_scene` is properly in...
8,329
16,178,519
I wrote a metaclass that I'm using for logging purposes in my python project. It makes every class automatically log all activity. The only issue is that I don't want to go into every file and have to add in: ``` __metaclass__ = myMeta ``` Is there a way to set the metaclass in the top level folder so that all the f...
2013/04/23
[ "https://Stackoverflow.com/questions/16178519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1226565/" ]
No, you can only specify the metaclass per class or per module. You cannot set it for the whole package. In Python 3.1 and onwards, you *can* intercept the `builtins.__build_class__` hook and insert a metaclass programatically, see [Overriding the default type() metaclass before Python runs](https://stackoverflow.com/...
Here's a simple technique. Just *subclass* the *class* itself with `__metaclass__` attribute in the subclass. This process can be automated. util.py ``` class A(object): def __init__(self, first, second): self.first = first self.second = second def __str__(self): return '{} {}'.format...
8,330
20,428,784
Is it possible to write every line, I receive from this script, into a mysql table ? I want to have 2 columns: The ip-adress I need for the command (ipAdresse) and a part of the output of the command itself (I want to split some content of the output).. I do not want to ask for any code but I just want to know whether ...
2013/12/06
[ "https://Stackoverflow.com/questions/20428784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2968265/" ]
Instead of using `respond_to?` why don't you do: ``` def date_or_time?(obj) obj.kind_of?(Date) || obj.kind_of?(Time) end [19] pry(main)> a = Date.new => #<Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)> [20] pry(main)> date_or_time? a => true [21] pry(main)> b = DateTime.new => #<DateTime: -4712-01-01T00:00:00+00:00 ...
Alternatively you could still use `respond_to?` with `:iso8601`. I believe only 'date-y' types will respond to that (Date, Time, DateTime).
8,331
11,174,532
I connect to a mysql database using pymysql and after executing a request I got the following string: `\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0`. This should be 5 characters in utf8, but when I do `print s.encode('utf-8')` I get this: `╨╝╨░╤А╨║╨░`. The string looks like byte representation of unicode characters, whic...
2012/06/24
[ "https://Stackoverflow.com/questions/11174532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1477552/" ]
You want to `decode` (not `encode`) to get a unicode string from a byte string. ``` >>> s = '\xd0\xbc\xd0\xb0\xd1\x80\xd0\xba\xd0\xb0' >>> us = s.decode('utf-8') >>> print us марка ``` Note that you may not be able to `print` it because it contains characters outside ASCII. But you should be able to see its value in...
Mark is right: you need to decode the string. Byte strings become Unicode strings by decoding them, encoding goes the other way. This and many other details are at [Pragmatic Unicode, or, How Do I Stop The Pain?](http://bit.ly/unipain).
8,332
9,425,556
I'm trying to use the app wapiti to make some security test in a web project running in localhost, but i have some problems with the syntax of Python. I follow the instructions that they give in wapiti project site and write this: ``` C:\Python27\python C:\Wapiti\wapiti.py http://server.com/base/url/ ``` but i get t...
2012/02/24
[ "https://Stackoverflow.com/questions/9425556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1229915/" ]
MapKit does not expose a means of performing driving directions. So, it's not as simple as asking the map to display a course from location A to location B. You have two options: 1) Integrate with Google's API to get the driving directions, and overlay your own lines onto the MapKit map. or 2) Simply direct your use...
Actually there is no api supported by iPhone sdk to draw route on map. There a repo on github which is using google maps api to draw route on map by using map overlay. It has some limitation but you can take help from this repo - <https://github.com/kishikawakatsumi/MapKit-Route-Directions>
8,333
32,788,322
I want to add a column in a `DataFrame` with some arbitrary value (that is the same for each row). I get an error when I use `withColumn` as follows: ``` dt.withColumn('new_column', 10).head(5) ``` ```none --------------------------------------------------------------------------- AttributeError ...
2015/09/25
[ "https://Stackoverflow.com/questions/32788322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1245418/" ]
**Spark 2.2+** Spark 2.2 introduces `typedLit` to support `Seq`, `Map`, and `Tuples` ([SPARK-19254](https://issues.apache.org/jira/browse/SPARK-19254)) and following calls should be supported (Scala): ```scala import org.apache.spark.sql.functions.typedLit df.withColumn("some_array", typedLit(Seq(1, 2, 3))) df.withC...
In spark 2.2 there are two ways to add constant value in a column in DataFrame: 1) Using `lit` 2) Using `typedLit`. The difference between the two is that `typedLit` can also handle parameterized scala types e.g. List, Seq, and Map **Sample DataFrame:** ``` val df = spark.createDataFrame(Seq((0,"a"),(1,"b"),(2,...
8,334
36,791,792
I am using django-cors-headers to overcome cors issues in python django. But I am getting. > > 'Access-Control-Allow-Origin' header contains multiple values '\*, \*', but only one is allowed. while trying to access using angularjs from <http://localhost:8000> > > > here is my settings for CORS that I am using. ...
2016/04/22
[ "https://Stackoverflow.com/questions/36791792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1433639/" ]
You need to do ``` MIDDLEWARE_CLASSES = ( ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ) CORS_ORIGIN_ALLOW_ALL = True #for testing. ``` Look `CorsMiddleware` is on top of `CommonMiddleware`. Hope this helps.
``` CORS_ORIGIN_ALLOW_ALL = False ``` change allow all to false
8,337
30,930,052
(I'm using Python 3.4 for this, on Windows) So, I have this code I whipped out to better show my troubles: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import os os.startfile('C:\\téxt.txt') ``` On IDLE it works as it should (it just opens that file I specified), but on Console (double-click) it keeps saying ...
2015/06/19
[ "https://Stackoverflow.com/questions/30930052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5026708/" ]
try this. Select tableview and go to Attribute Inspector. In separator just set the table view separator color to clear color.
Try this. Select tableview and go to Attribute Inspector. Find the property Separator and make it Default to None. And also set the color to Clear Color. I hope it will work for you...good luck !! :)
8,338
11,697,096
I am trying to send a message through GCM (Google Cloud Messaging). I have registered through Google APIs, I can send a regID to my website (which is a Google App Engine Backend) from multiple Android test phones. However, I can't send anything to GCM from Google App Engine. Here is what I am trying to use. ``` re...
2012/07/28
[ "https://Stackoverflow.com/questions/11697096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256336/" ]
What are data2 and data3 used for ? The data you are posting was not proper json so you need to use json.dumps(data).Code should be like this : ``` json_data = {"collapse_key" : "Food-Promo", "data" : { "Category" : "FOOD", "Type": "VEG", }, "registration_ids": [regId], } ur...
Try using [python-gcm](https://github.com/geeknam/python-gcm). It can handle errors as well.
8,340
67,828,477
Iterable objects are those that implement `__iter__` function, which returns an iterator object, i.e. and object providing the functions `__iter__` and `__next__` and behaving correctly. Usually the size of the iterable object is not known beforehand, and iterable object is not expected to know how long the iteration w...
2021/06/03
[ "https://Stackoverflow.com/questions/67828477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6087087/" ]
It sounds like you're asking about something like `__length_hint__`. Excerpts from [PEP 424 – A method for exposing a length hint](https://peps.python.org/pep-0424/): > > CPython currently defines a `__length_hint__` method on several types, such as various iterators. This method is then used by various other functio...
If I now understand your question, you're still trying to combine two concepts that don't combine in quite this way. `generator` is a subclass of `iterator`; it's a process. `len` applies to data objects -- in particular, to the *iterable* object, as opposed to the *iterator* that traverses the object. Therefore, a ge...
8,343
4,364,087
Can this be somehow overcome? Can a child process create a subprocess? The problem is, I have a ready application which needs to call a Python script. This script on its own works perfectly, but it needs to call existing shell scripts. Schematically the problem is in the following code: ### parent.py ``` import sub...
2010/12/06
[ "https://Stackoverflow.com/questions/4364087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457921/" ]
> > There should be nothing stopping you from using subprocess in both child.py and parent.py > > > I am able to run it perfectly fine. :) **Issue Debugging**: > > You are using `python` and `/usr/sfw/bin/python`. > > > 1. Is bare python pointing to the same python? 2. Can you check by typing 'which pytho...
Using `subprocess.call` is not the proper way to do it. In my view, `subprocess.Popen` would be better. parent.py: ``` 1 import subprocess 2 3 process = subprocess.Popen(['python', './child.py', 'arg1', 'arg2'],\ 4 stdin=subprocess.PIPE, stdout=subprocess.PIPE,\ 5 stderr=subprocess.PIPE) 6 process.w...
8,344
38,909,543
I am trying to convert a string to hex character by character, but I cant figure it out in Python3. In older python versions, what I have below works: ``` test = "This is a test" for c in range(0, len(test) ): print( "0x%s"%string_value[i].encode("hex") ) ``` But with python3 I am getting the following error: ...
2016/08/12
[ "https://Stackoverflow.com/questions/38909543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1902666/" ]
In python 3x Use [`binascii`](https://docs.python.org/3.1/library/binascii.html) instead of hex: ``` >>> import binascii >>> binascii.hexlify(b'< character / string>') ```
How about: ``` >>> test = "This is a test" >>> for c in range(0, len(test) ): ... print( "0x%x"%ord(test[c])) ... 0x54 0x68 0x69 0x73 0x20 0x69 0x73 0x20 0x61 0x20 0x74 0x65 0x73 0x74 ```
8,346
14,307,518
I am only an hour into learning how [cron](http://en.wikipedia.org/wiki/Cron) jobs work, and this is what I have done so far. I’m using `crontab -e` to add my cron command, which is: `0/1 * * * * /usr/bin/python /home/my_username/hello.py > /home/my_username/log.txt` `crontab -l` confirms that my command is there. H...
2013/01/13
[ "https://Stackoverflow.com/questions/14307518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1972942/" ]
Experiment shows that the `0/1` seems to be the problem. `0/1` *should* be equivalent to `*`. If you replace `0/1` with `*`, it should work. Here's my experimental crontab: ``` 0/1 * * * * echo 0/1 >> cron0.log * * * * * echo star >> cron1.log ``` This creates `cron1.log` but not `cron0.log`. I'll look into th...
`0/1` seems to be formatted wrong for your version of cron. I found this on [wikipedia](http://en.wikipedia.org/wiki/Cron#cite_ref-8): > > Some versions of cron may not accept a value preceding "/" if it is not a range, > such as "0". An alternative would be replacing the zero with an asterisk. > > > So Keith ...
8,349
60,963,452
I am loading in a very large image (60,000 x 80,000 pixels) and am exceeding the max pixels I can load: ```none cv2.error: OpenCV(4.2.0) /Users/travis/build/skvark/opencv-python/opencv/modules/imgcodecs/src/loadsave.cpp:75: error: (-215:Assertion failed) pixels <= CV_IO_MAX_IMAGE_PIXELS in function 'validateInput...
2020/04/01
[ "https://Stackoverflow.com/questions/60963452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10537728/" ]
You have to modify the openCV source files and then compile it your own. EDIT: You can also modify environment variables ``` export CV_IO_MAX_IMAGE_PIXELS=1099511627776 ```
For my problem I should have specified it was a .tif file (NOTE most large images will be in this file format anyway). In which case a very easy way to load it in to a numpy array (so it can then work with OpenCV) is with the package tifffile. ``` pip install tifffile as tifi ``` This will install it in your python ...
8,350
40,012,264
I am new to python. I am trying to print sum of all duplicates nos and products of non-duplicates nos from the python list. for examples list = [2,2,4,4,5,7,8,9,9]. what i want is sum= 2+2+4+4+9+9 and product=5\*7\*8.
2016/10/13
[ "https://Stackoverflow.com/questions/40012264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4024000/" ]
You should not create a new `User` object when writing the parcel. You are operating on the current object instance. I guess you can perform all the logic for object creation and reading the parcel in the `createFromParcel()` method but I have seen the pattern below more often where you pass the parcel into a construc...
For really **Boolean** (not **boolean**) I would go with: ``` @Override public void writeToParcel(Parcel out, int flags) { if (open_now == null) { out.writeInt(-1); } else { out.writeInt(open_now ? 1 : 0); } ``` and ``` private MyClass(Parcel in) { switch ...
8,352
41,065,879
I am having trouble executing this python command and it keeps flagging this specific line. I've read the other posts about EOL, but I can't seem to find an issue with the types of quotes used. ``` logfile = "/Volumes/AC_SMN/03_DIGITAL_12/MD5_CHECKSUM_REPORTS/Text_Files” + id + ".txt" SyntaxError: EOL while scanning ...
2016/12/09
[ "https://Stackoverflow.com/questions/41065879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7273874/" ]
The quote character after Text\_Files is incorrect. You could try this: ``` logfile = "/Volumes/AC_SMN/03_DIGITAL_12/MD5_CHECKSUM_REPORTS/Text_Files" + id + ".txt" ``` However, I would recommend using the string formatting syntax instead: ``` logfile = "/Volumes/AC_SMN/03_DIGITAL_12/MD5_CHECKSUM_REPORTS/Text_Files{...
you have used wrong quote at the end of `Text_Files” + id +` ``` logfile = "/Volumes/AC_SMN/03_DIGITAL_12/MD5_CHECKSUM_REPORTS/Text_Files” + id + ".txt" ``` instead use this (double quotes at the end of the string) ``` logfile = "/Volumes/AC_SMN/03_DIGITAL_12/MD5_CHECKSUM_REPORTS/Text_Files" + id + ".txt" ```
8,353
2,366,056
I'm learning python with 'Dive Into Python 3' and It's very hard to remember everything, without writing something, but there are no exercises in this book. So I ask here, where can i find them to remember everything better.
2010/03/02
[ "https://Stackoverflow.com/questions/2366056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271388/" ]
I used [ProjectEuler.net](http://projecteuler.net/) when learning Python. It also helped sharpen my math skills.
Find a good Code Kata website: Here's a list I compiled. <http://slott-softwarearchitect.blogspot.com/2009/08/code-kata-resources.html> I've also collected lots of exercises: <http://homepage.mac.com/s_lott/books/python.html> This book, however, covers only Python 2.6, so it may be more confusing than helpful.
8,354
57,901,183
I am using python to parse CSV file but I face an issue how to extract "Davies" element from second row. CSV looks like this ``` "_submissionusersID","_submissionresponseID","username","firstname","lastname","userid","phone","emailaddress","load_date" "b838b35d-ca18-4c7c-874a-828298ae3345","e9cde2ff-33a7-477e-b3b9-1...
2019/09/12
[ "https://Stackoverflow.com/questions/57901183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4655668/" ]
In the end I sort of solved this by repeatedly subscribing and unsubscribing from the ZMQ socket. ``` # This is run every time the subscriber receive function is called socket.setsockopt(zmq.SUBSCRIBE, '') md = socket.recv_json() msg = socket.recv() socket.setsockopt(zmq.UNSUBSCRIBE, '') ``` Essentially, I made it ...
Are you looking for `zmq.CONFLATE` option ("Last Message Only")? Something like this in subscriber side: ``` context = zmq.Context() socket = context.socket(zmq.SUB) socket.setsockopt(zmq.SUBSCRIBE, '') socket.setsockopt(zmq.CONFLATE, 1) # last msg only. socket.connect("tcp://localhost:%s" % port) # must be placed...
8,356
18,046,817
I have been trying to add sub-directories to an "items" list and have settled on accomplishing this with the below code. ``` root, dirs, files = iter(os.walk(PATH_TO_DIRECTORY)).next() items = [{ 'label': directory, 'path': plugin.url_for('test') } for count, directory in enumerate(dirs)] ``` The above works, b...
2013/08/04
[ "https://Stackoverflow.com/questions/18046817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1743833/" ]
I have no idea what plugin.url\_for() does, but you should be able to speed it a bit doit it this way: ``` plugin_url_for = plugin.url_for _, dirs, _ = iter(os.walk(PATH_TO_DIRECTORY)).next() items = [{ 'label': directory, 'path': plugin_url_for('test') } for directory in dirs] ``` I dropped root, files variabl...
``` dirlist = [] for root, dirs, files in os.walk(PATH_TO_DIRECTORY): dirlist += dirs ``` Should do the trick! For your revised question, I think what you really need is probably the output of: ``` Dirdict = {} for (root, dirs, files) in os.walk (START): Dirdict [root] = dirs ``` You might wish or need so...
8,357
28,147,183
I was reading about builder.connect\_signals which maps handlers of glade files with methods in your python file. Apparently works, except for the Main Window, which is not destroying when you close it. If you run it from terminal is still running and have to Ctrl-C to completely close the application. Here is my pyth...
2015/01/26
[ "https://Stackoverflow.com/questions/28147183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/598070/" ]
On closing window your window destroying but main loop of program don't stop, you must connect **destroy** event to the method/function that quit from this loop that ran from last line of code. Make some change in below lines of codes: ``` #if (window): # window.connect("destroy", gtk.main_quit) ``` change to: ...
You can use `GtkApplication` and `GtkApplicationWindow` to manage it for you. When Application has no more open windows, it will automatically terminate. ``` #!/usr/bin/env python import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import Gio class Mixer(Gtk.Application): d...
8,358
69,398,944
I have this easy code to connect to download some data using `GRPC` ``` creds = grpc.ssl_channel_credentials() channel = grpc.secure_channel(f'{HOST}:{PORT}', credentials=creds) stub = liveops_pb2_grpc.LiveOpsStub(channel=channel) request = project_pb2.ListProjectsRequest(organization=ORGANIZATION) projects = stub.Lis...
2021/09/30
[ "https://Stackoverflow.com/questions/69398944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5556466/" ]
You can do that with the method [String#[]](https://ruby-doc.org/core-2.7.0/String.html#method-i-5B-5D) with an argument that is a regular expression. ``` r = /.*?\.(?:rb|com|net|br)(?!\.br)/ '[email protected]'[r] #=> "[email protected]" 'alvaro-neves@stoc...
This should work for your scenario: ```rb expr = /^(.+\.(?:br|com|net))-[^']+(')$/ str = "email = '[email protected]'" str.gsub(expr, '\1\2') ```
8,359
50,598,438
I am tracing a python script like this: ``` python -m trace --ignore-dir=$HOME/lib64:$HOME/lib:/usr -t bin/myscript.py ``` Some lines look like this: ``` --- modulename: __init__, funcname: getEffectiveLevel __init__.py(1325): logger = self __init__.py(1326): while logger: __init__.py(1327): ...
2018/05/30
[ "https://Stackoverflow.com/questions/50598438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/633961/" ]
if the purpose is finding the full path, then check [hunter](https://python-hunter.readthedocs.io/en/latest/readme.html#id1) project, it even has support for [query-style](https://python-hunter.readthedocs.io/en/latest/cookbook.html) tracing. ``` # a modified example from docs # do check the documentation it is easy t...
Unfortunately there is no flag/command-line option to enable that. So the immediate (and probably correct) answer is: **No**. If you're okay with messing with the built-in libraries you can easily make it possible by changing the line that reads: ``` print (" --- modulename: %s, funcname: %s" % (modulename, c...
8,362
69,271,213
There are several ways in python to generate a greyscale image from an RGB version. One of those is just to read an image as greyscale using OpenCV. ``` im = cv2.imread(img, 0) ``` While `0` equals `cv2.IMREAD_GRAYSCALE` There are many different algorithms to handle this operation [well explained here.](https://www...
2021/09/21
[ "https://Stackoverflow.com/questions/69271213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152497/" ]
I think basically @Dan Mašek already answered the question in the comment section. I will try to summarize the findings for jpg files as an answer and I am glad about any improvements. CMYK to Grayscale ----------------- If you want to convert your jpg file from CMYK we have to look into [grfmt\_jpeg.cpp](https://...
in OpenCV [documentation](https://github.com/opencv/opencv/blob/master/modules/imgcodecs/include/opencv2/imgcodecs.hpp) you can find: ``` IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image (codec internal conversion). ``` Also > > When using IMREAD\_GRAYSCALE, the codec'...
8,364
30,196,585
I've been struggling for hours on a problem that is making me insane. I installed Python 2.7 with Cygwin and added Scipy, Numpy, Matplotlib (1.4.3) and Ipython. When I decided to run `ipython --pylab` I get the following error: ``` /usr/lib/python2.7/site-packages/matplotlib/transforms.py in <module>() 37 import nump...
2015/05/12
[ "https://Stackoverflow.com/questions/30196585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4892337/" ]
For others having this problem, in my case, the solution was simple. The problem was caused by having the wrong matplot library installed on your computer; creating an error in finding the correct matplotlib path. In my case, I had installed matplotlib on a different version of python. Simply update matplotlib on your ...
I doubt that most of you brought here by Google have the problem I had, but just in case: I got the above "ImportError: No module named \_path" (on Fedora 17) because I was trying to make use of matplotlib by just setting sys.path to point to where I had built the latest version (1.5.1 at the time). Don't do that. On...
8,365
46,368,931
Here is my main.py: ``` #!/usr/bin/env python3 from kivy.app import App from kivy.lang import Builder from kivy.metrics import dp from kivy.properties import ObjectProperty from kivy.uix.image import Image from kivy.uix.widget import Widget from kivy.uix.boxlayout import BoxLayout from kivymd.bottomsheet import MDList...
2017/09/22
[ "https://Stackoverflow.com/questions/46368931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4085793/" ]
This works for me Try not to change MDRaisedButton size\_hint to 1 it raised this clock error , my suggestion is not to change any kivymd button size\_hint it is by default None rather you can change size in dp
This bug still persists in `MDRaisedButton` of KivyMD. A simple workaround to solve it is using `size_hint` instead of `size_hint_x`. For example in your case, replace ``` MDRaisedButton: size_hint_x: 1 ``` by ``` MDRaisedButton: size_hint: 1., None ```
8,367
14,206,637
I am really new to the use of Python and the associated packages that can be installed. As a biologist I am looking for a lot of new packages that would help me model species systems, ecological change etc.. and after a lot of "Google-ing" I came across scikit-learn. However, I am having trouble installing it. And I wi...
2013/01/08
[ "https://Stackoverflow.com/questions/14206637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1956404/" ]
scikit-learn does not support Python 3 yet. For now you need Python 2.7. Proper support for Python 3 is expected for the 0.14 release scheduled for Q2-2013.
I am no expert, but in my understanding the print statement in Python 3.\* is now a function, called like: print(). So, a quick solution in this case is to change ``` print "I: Seeding RNGs with %r" % _random_seed ``` to ``` print("I: Seeding RNGs with %r" % _random_seed) ```
8,368
9,331,000
I'm trying to remove large blocks of text from a file using python. Each block of text begins with /translation="SOMETEXT" Ending with the second quote. Can anyone give me some advice on how to accomplish this? Thank you
2012/02/17
[ "https://Stackoverflow.com/questions/9331000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1216584/" ]
You can use re.sub like this: ``` import re re.sub("/translation=\".*?\" ", "", s) ```
If performance doesn't matter, you could do something like this. Regular expressions would probably be faster, but this is simpler. ``` def remtxt(s,startstr,endstr): while startstr in s: startpos=s.index(startstr) try: endpos=s.index(endstr,startpos+len(...
8,369
71,155,282
Below is the html tag. I want to return the value in span as an integer in python selenium. Can you help me out? ```html <span class="pendingCount"> <img src="/static/media/sandPot.a436d753.svg" alt="sandPot"> <span>2</span> </span> ```
2022/02/17
[ "https://Stackoverflow.com/questions/71155282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14902563/" ]
You could use the dates for the x-axis, the 'constant' column for the y-axis, and the Cluster id for the coloring. You can create a custom legend using a list of colored rectangles. ```py import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator import pandas as pd import numpy as np N = 100 df = pd....
You could just plot a normal bar graph, with 1 bar corresponding to 1 day. If you make the width also 1, it will look as if the patches are contiguous. [![enter image description here](https://i.stack.imgur.com/jtFlV.png)](https://i.stack.imgur.com/jtFlV.png) ``` import numpy as np import matplotlib.pyplot as plt fr...
8,370
48,655,638
I think what I am trying to do is pretty much like [github issue in zeep repo](https://github.com/mvantellingen/python-zeep/issues/412) --- but sadly there is no response to this issue yet. I researched suds and installed and tried -- did not even get sending parameter to work and thought zeep seems better maintained? ...
2018/02/07
[ "https://Stackoverflow.com/questions/48655638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2379736/" ]
You can use a Plugin for editing the xml as a plain string. I used this plugin for keeping the characters '<' and '>' in a CDATA element. ``` from xml import etree from zeep import Plugin class my_plugin(Plugin): def egress(self, envelope, http_headers, operation, binding_options): xml_string = etree.Ele...
On Python 3.9, @David Ortiz answer didn't work for me, maybe something has changed. The `etree_to_string` was failing to convert the XML to string. What worked for me, instead of a plugin, I created a custom transport, that replaced the stripped tags with the correct characters, just like David's code, before the post...
8,371
56,316,244
I have some strange behavior on python 3.7 with a nested list comprehension that involves a generator. **This works:** ``` i = range(20) n = [1, 2, 3] result = [min(x + y for x in i) for y in n] ``` It does **not work** if `i` is a generator: ``` i = (p for p in range(20)) n = [1, 2, 3] result = [min(x + y for x ...
2019/05/26
[ "https://Stackoverflow.com/questions/56316244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51627/" ]
In both of your last examples, you try to iterate on the generator again after it got exhausted. In your last example, `list(i)` is evaluated again for each value of `y`, so `i` will be exhausted after the first run. You have to make a list of the values it yields once before, as in: ``` i = (p for p in range(20)) ...
The generator is emptied after the first for loop for both `for x in i` or `for x in list(i)`, instead you need to convert the generator to a list, (which essentially iterates over the generator and empties it) beforehand and use that list Note that this essentially defeats the purpose of a generator, since now this ...
8,372
70,969,920
I am looping over a list of dictionaries and I have to drop/ignore either one or more keys of the each dictionary in the list and write it to a MongoDB. What is the efficient pythonic way of doing this ? **Example:** ``` employees = [ {'name': "Tom", 'age': 10, 'salary': 10000, 'floor': 10}, {'name': "Mark", 'age': ...
2022/02/03
[ "https://Stackoverflow.com/questions/70969920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14066217/" ]
In the context you ask about you can think that closure is a function that references to some variables that are defined in its outer scope (for other cases see the answer by @phipsgabler). Here is a minimal example: ``` julia> function est_mean(x) function fun(m) return m - mean(x) ...
I'm going to complement Bogumił's answer by showing you what he has deliberately left out: a closure does not have to be a function in the strict sense. In fact, you could write them on your own, if nested functions were disallowed in Julia: ``` struct LikelihoodClosure X y end (l::LikelihoodClosure)(β) = -lo...
8,375
21,811,851
This question has been troubling me for some days now and I've tried asking in many places for advice, but it seems that nobody can answer it clearly or even provide a reference to an answer. I've also tried searching for tutorials, but I just cannot find any type of tutorial that explains how you would use a reusable...
2014/02/16
[ "https://Stackoverflow.com/questions/21811851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1663535/" ]
TL;DR: ------ Nope & it depends... Some (Very) Common Reusable Apps -------------------------------- * [django.contrib.admin](https://docs.djangoproject.com/en/dev/ref/contrib/admin/) * [django.contrib.auth](https://docs.djangoproject.com/en/dev/ref/contrib/auth/) * [django.contrib.staticfiles](https://docs.djangopr...
I'm not sure why you think you need a main app for the "frontend" stuff. The point of a reusable app is that it takes care of everything, you just add (usually) a single URL to include the urls.py of the app, plus your own templates and styling as required. And you certainly don't need to wrap the app's views in your ...
8,376
48,642,572
I'm trying to port a custom class from Python 2 to Python 3. I can't find the right syntax to port the iterator for the class. Here is a MVCE of the real class and my attempts to solve this so far: Working Python 2 code: ``` class Temp: def __init__(self): self.d = dict() def __iter__(self): r...
2018/02/06
[ "https://Stackoverflow.com/questions/48642572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490400/" ]
As the error message suggests, your `__iter__` function does not return an iterator, which you can easily fix using the built-in `iter` function ``` class Temp: def __init__(self): self.d = {} def __iter__(self): return iter(self.d.items()) ``` This will make your class iterable. Alternativel...
I don't know what works in Python 2. But on Python 3 iterators can be most easily created using something called a [generator](https://www.pythoncentral.io/python-generators-and-yield-keyword/). I am providing the name and the link so that you can research further. ``` class Temp: def __init__(self): self....
8,377
21,179,140
Okay, so in a terminal, after importing and making the necessary objects--I typed: ``` for links in soup.find_all('a'): print(links.get('href')) ``` which gave me all the links on a wikipedia page (roughly 250). No problems. However, in a program I am coding, I only receive about 60 links (and this is scraping...
2014/01/17
[ "https://Stackoverflow.com/questions/21179140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204909/" ]
This is not my answer. I got it from [here](http://fryandata.wordpress.com/2014/06/17/24/), which has helped me before. ``` from bs4 import BeautifulSoup import csv # Create .csv file with headers f=csv.writer(open("nyccMeetings.csv","w")) f.writerow(["Name", "Date", "Time", "Location", "Topic"])...
I have encountered many problems in my web scraping projects; however, BeautifulSoup was never the culprit. I highly suspect you are having the same problem I had scraping Wikipedia. Wikipedia did not like my user-agent and was returning a page other than what I requested. Try adding a user-agent in your code e.g. `M...
8,378
13,925,355
I wanted to run the command: `repo init -u https://android.googlesource.com/platform/manifest -b android-4.1.1_r6` and got the following output: `Traceback (most recent call last): File "/home/anu/bin/repo", line 91, in <module> import readline ImportError: No module named readline` So to fix the above, I tried t...
2012/12/18
[ "https://Stackoverflow.com/questions/13925355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649409/" ]
``` sudo apt-get install libncurses5-dev ``` And then rerun you command
If you are running an 64 bit OS, you might have to install the i386 versions of the libraries. A lot (all?) of the Android host commands are 32-bit only.
8,379
43,748,464
I have a large number of files with $Log expanded-keyword text at the end that needs to be deleted. I am looking to modify an existing python 2.7 script to do this but cannot get the regex working correctly. The text to strip from the end of a file looks like this: ``` /* one or more lines of .. .. possible text $Log...
2017/05/02
[ "https://Stackoverflow.com/questions/43748464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/947860/" ]
You can use: ``` result = re.sub(r"/\*\s+\*+\s+\$Log.*?\*/", "", subject, 0, re.DOTALL) ``` --- [![enter image description here](https://i.stack.imgur.com/YTKkn.jpg)](https://i.stack.imgur.com/YTKkn.jpg) --- [Regex Demo](https://regex101.com/r/6AgeQe/4) [Python Demo](https://ideone.com/QJmjUy)
It is a bit unclear what you are expecting as output. My understanding is that you are trying to extract the comment. I'm assuming that the comment appears on the 3rd line and you have to just extract the third line using regex. Regex Expression used: ``` (\$Log:.*[\r\n]*.*[\r\n])(.*) ``` After using the regex for m...
8,381
62,791,323
I have recently upgraded my python/opencv for a project to python 3.7 + opencv 4.3.0 and now I have an issue with opencvs imshow. I am running Ubuntu 18.04 and am using conda venvs. I tried to rerun this piece of code multiple times and half the time it correctly displays the white image, and half the time it displays...
2020/07/08
[ "https://Stackoverflow.com/questions/62791323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13890473/" ]
``` django_find_project = True ``` Add this to your `pytest.ini`. **EDIT:** It looks like you have spelled `DJANGO_SETTINGS_MODULE` wrong in your `pytest.ini`. Please fix it.
Pytest has an order of precedence when choosing which settings.py to be used in tests and the settings in the pytest.ini is only used as last resort. Pytest first looks at the `--ds` setting when running your tests, if that is not set it then used the environment variable `DJANGO_SETTINGS_MODULE`, if this also not set...
8,383
48,986,755
I have a list which contains zeros and non-zero values. I want to find the range of zeros and non-zero values in terms of tuple inside the list. I am looking for package free solution with pythonic way. E.g. ``` a = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 11, 12, 12, 12, 13, 13, 17, 17, ...
2018/02/26
[ "https://Stackoverflow.com/questions/48986755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7819943/" ]
You could `enumerate()` to get the indexes, `itertools.groupby()` to group falsy (`0`) and truthy values together, and extract the start and end indexes with `operator.itemgetter(0, -1)`: ``` from operator import truth, itemgetter from itertools import groupby [itemgetter(0,-1)([i for i,v in g]) for _, g in groupby(e...
``` import numpy as np unique, counts = np.unique(a, return_counts=True) idx = tuple(zip(unique, counts)) ``` I think this will work for you.
8,386
72,404,096
Trying to run examples or telegram bots from official site - <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples> Installed : ``` pip install python-telegram-bot ``` and when i run the example, i got error back that version is not compatible. ``` if __version_info__ < (20, 0, 0, "alpha"...
2022/05/27
[ "https://Stackoverflow.com/questions/72404096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14333315/" ]
Assuming you have only one non-NaN per row, you can `stack`: ```py df.stack().droplevel(1).to_frame(name='Fruits') ``` Output: ``` Fruits 0 Apple 1 Pear 2 Orange 3 Mango 4 banana ``` #### Handling rows with only NaNs: ```py df.stack().droplevel(1).to_frame(name='Fruits').reindex(df.index) ``` Outpu...
I think this should give the desired output - `df['Fruit1'].fillna(df['Fruit2'])`
8,395
33,919,806
Is there a recommended way for using BeautifulSoup 4 in python when you have a table with no class or attribute values? I was considering just using Get\_Text() to dump the text out but if I wanted to pick individual values out or break the table into more discrete sections how would I go about it ? ```html <table ce...
2015/11/25
[ "https://Stackoverflow.com/questions/33919806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2645252/" ]
Let's look at your jQuery: ``` $('div#info.Data') // Gets <div> with id="info" and class="Data" // ^ You have id and class reversed! .eq(1) // This gets the 2nd element in the array // ^ You only tried to get 1 element. What is the 2nd? .text() // Returns co...
First of all, you have you're `id` and `class` the wrong way round but this is a simple fix. An alternative to your solution is to grab all the content, split it out into an array and then clean the empty strings caused by the new lines and `<br />` tags. This can then be used in any matter you like. ```js $(docume...
8,402
38,259,749
How can I split the a column into two separate ones. Would apply be the way to go about this? I want to keep the other columns in the DataFrame. For example I have a column called "last\_created" with a bunch of dates and times: "2016-07-01 09:50:09" I want to create two new columns "date" and "time" with the split v...
2016/07/08
[ "https://Stackoverflow.com/questions/38259749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5405782/" ]
`now()` is mysql function . In PHP we use **[time()](http://php.net/manual/en/function.time.php)** to get the current timestamp It is used as ``` $now = time();// get current timestamp ``` Use [**`strtotime()`**](http://php.net/manual/en/function.strtotime.php) to convert date in time stamp then use for comparison...
You are in right Direction, change it like ``` <?php //SELECT QUERY... foreach($events->results() as $e): $now = date("Y-m-d H:i:s"); if(date("Y-m-d H:i:s", strtotime($e->event_date)) >= $now){ echo "<h1>Show Event</h1>"; }else{ echo "<h1>DON'T Show Event</h1>"; ...
8,403
29,650,935
I am trying to convert a python game (made with pygame) into a exe file for windows, and I did using cx\_Freeze. No problems there. The thing is that when I launch myGame.exe, it opens the normal Pygame window and a console window(which I do not want). Is there a way to remove the console window? I read most of th...
2015/04/15
[ "https://Stackoverflow.com/questions/29650935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3580258/" ]
So what was wrong, was that the setup.py file was missing a parameter. What you need to add is `base = "Win32GUI"` to declare that you do not need a console window upon launch of the application. Here's the code: ``` import cx_Freeze exe = [cx_Freeze.Executable("myGame.py", base = "Win32GUI")] # <-- HERE cx_F...
The parameter can be passed also by the shell if you are making a quick executable like this: ``` cxfreeze my_program.py --base-name=WIN32GUI ```
8,404
16,797,850
I am trying to get gimp to use a reasonable default path in a "save as" plugin, and to do that I need to be able to specify the default with the return value of a function (I believe). Currently, my code is something like: ``` def do_the_foo(image, __unused_drawable, directory): # ... do something register( ...
2013/05/28
[ "https://Stackoverflow.com/questions/16797850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The fastest way would be to store the relevant data somewhere in a cache, and then print it, when you have time for it. Printing to the console is definitely slow, and using printf is maybe also not a good idea, especially if there are several variables to convert. Since I don't know the dynamics of your code, I can o...
You can switch buffering on by using C89's `setvbuf()`
8,405
64,964,188
Is there any simple way to swap character of string in python. In my case I want to swap `.` and `,` from `5.123.673,682`. So my string should become `5,123,673.682`. I have tried: ``` number = '5.123.673,682' number = number.replace('.', 'temp') number = number.replace(',', '.') number = number.replace('temp', ',') ...
2020/11/23
[ "https://Stackoverflow.com/questions/64964188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975806/" ]
One way using `dict.get`: ``` mapper = {".": ",", ",":"."} "".join([mapper.get(s, s) for s in '5.123.673,682']) ``` Or using `str.maketrans` and `str.translate`: ``` '5.123.673,682'.translate(str.maketrans(".,", ",.")) ``` Output: ``` '5,123,673.682' ```
This is a pythonic and clean approach to do that ```py def swap(c): if c == ',': return '.' elif c == '.': return ',' else: return c number = '5.123.673,682' new_number = ''.join(swap(o) for o in number) ```
8,406
72,317,862
``` Please here is my code def train_apparentflow_net(): code_path = config.code_dir fold = int(sys.argv[1]) print('fold = {}'.format(fold)) if fold == 0: mode_train = 'all' mode_val = 'all' elif fold in range(1,6): mode_train = 'train' mode_val = 'val' else: ...
2022/05/20
[ "https://Stackoverflow.com/questions/72317862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19131126/" ]
Please look at the following answer [sys.argv[1] description](https://stackoverflow.com/questions/4117530/sys-argv1-meaning-in-script) It is failing as there is no argument provided. You could try ``` fold = int(sys.argv[0]) ```
if all you need is to select the model, why not add the names in a list and select base on index like this ``` model_list = ["model_apparentflow_net_fold0_epoch050.h5", "model_apparentflow_net_fold1_epoch050.h5", "model_apparentflow_net_fold2_epoch050.h5", "model_apparentflow_net_fold3_epoch050.h5", "model_apparentf...
8,408
3,405,073
Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this: ``` mydict[key][subkey][subkey2]="value" ``` without having to check that mydict[key] etc. are actually set to be a dict, e.g. using ``` if not key in mydict: mydict[key]={} ``` The creation o...
2010/08/04
[ "https://Stackoverflow.com/questions/3405073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369113/" ]
``` class D(dict): def __missing__(self, key): self[key] = D() return self[key] d = D() d['a']['b']['c'] = 3 ```
You could use a tuple as the key for the dict and then you don't have to worry about subdictionaries at all: ``` mydict[(key,subkey,subkey2)] = "value" ``` Alternatively, if you really need to have subdictionaries for some reason you could use [`collections.defaultdict`](http://docs.python.org/library/collections.ht...
8,409
61,590,884
my list looks like: ``` lst ['78251'], ['18261'], ['435921'], ['74252'], ...] ``` I want to place that numbers into a url code <http://api.brain-map.org/api/v2/data/query.xml?criteria=model::SectionDataSet,rma::criteria,[failed>$eq%27false%27],products[abbreviation$eq%27Mouse%27],genes[entrez\_id$eq%27**inhere**...
2020/05/04
[ "https://Stackoverflow.com/questions/61590884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9353795/" ]
The URL is complex, but see example URL: ``` a= 'http://api.brain-map.org/api/v2/data/query.xml?criteria=' + i + '&gene=model:' + i ```
Try this much more pythonic approach, using .format(): ``` for i in lst: b = "http://api.brain-map.org/api/v2/data/query.xml?criteria=model::SectionDataSet,rma::criteria,[failed$eq%27false%27],products[abbreviation$eq%27Mouse%27],genes[entrez_id$eq%27{}%27]".format(i[0]) ```
8,412
41,254,635
Basically I'm just starting out with python networking and python in general and I can't get my TCP client to send data. It says: ``` Traceback (most recent call last): File "script.py", line 14, in <module> client.send(data) #this is where I get the error TypeError: a bytes-like object is required, not 'str' `...
2016/12/21
[ "https://Stackoverflow.com/questions/41254635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7323709/" ]
You are probably using Python 3.X. [`socket.send()`](https://docs.python.org/3.5/library/socket.html#socket.socket.send) expected a bytes type argument but `data` is an unicode string. You must encode the string using [`str.encode()`](https://docs.python.org/3/library/stdtypes.html#str.encode) method. Similarly you wou...
If you are using python2.x your code is correct. As in the documentation for python2 [`socket.send()`](https://docs.python.org/2/library/socket.html#socket.socket.send) takes a string parameter. But if you are using python3.x you can see that [`socket.send()`](https://docs.python.org/3.6/library/socket.html#socket.sock...
8,415
3,246,021
I am posting to Hudson server using curl from the command line using the following-- ``` curl -X POST -d '<run><log encoding="hexBinary">4142430A</log><result>0</result><duration>2000</duration></run>' \ http://user:pass@myhost/hudson/job/_jobName_/postBuildResult ``` as shown in the hudson documentation..can I emu...
2010/07/14
[ "https://Stackoverflow.com/questions/3246021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/361179/" ]
``` import urllib2 req = urllib2.Request(url, data) response = urllib2.urlopen(req) result = response.read() ``` where data is the encoded data you want to POST. You can encode a dict using urllib like this: ``` import urllib values = { 'foo': 'bar' } data = urllib.urlencode(values) ```
The modern day solution to this is much simpler with the [requests](http://docs.python-requests.org/) module (tagline: *HTTP for humans!* :) ``` import requests r = requests.post('http://httpbin.org/post', data = {'key':'value'}, auth=('user', 'passwd')) r.text # response as a string r.content # response as a ...
8,418
7,149,137
Within a python program I need to run a command in background, without displaying its output. Therefore I'm doing `os.system("nohup " + command + " &")` for now. Edit : `command` shouldn't be killed/closed when python program exits. However that will only work on Linux, and the content of the file will end up in `noh...
2011/08/22
[ "https://Stackoverflow.com/questions/7149137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692562/" ]
You are looking for a daemon process. Look at [How do you create a daemon in Python?](https://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python) or <http://blog.ianbicking.org/daemon-best-practices.html>
Look into the [subprocess](http://docs.python.org/library/subprocess.html) module. ``` from subprocess import Popen, PIPE process = Popen(['command', 'arg'], stdout=PIPE) ```
8,419
22,084,046
Python 2.7.5 I added the homebrew/science to my brew taps. I ran ``` brew install opencv. ``` bash profile I added ``` export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH ``` I've opened the headgazer folder and run ``` python tracker.py Traceback (most recent call last): File "tracker.py",...
2014/02/28
[ "https://Stackoverflow.com/questions/22084046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172232/" ]
Very straightforward with `awk`: ``` $ cat file 1 2 3 4 5 6 ``` ``` $ awk 'NR==3{print "hello\n"}1' file 1 2 hello 3 4 5 6 ``` Where `NR` is the line number. You can set it to any number you wish to insert text to.
Does it have to be sed? ``` head -2 infile ; echo Hello ; echo ; tail +3 infile ```
8,420
61,453,511
I have my flask app which would serve my flutter app using HTTP requests. Everything is okay when the mobile phone is connected to the PC. But once after we deploy the app to the mobile phone and detach it from the PC, how would the flask app serve the flutter app? Is there any way which would start the python script ...
2020/04/27
[ "https://Stackoverflow.com/questions/61453511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11170382/" ]
for testing purpose you can use ngrok to deploy your flask server, for more info [ngrok](https://ngrok.com/docs)
Your phone when connected to the PC is accessing a Flask app via 'localhost'. You have two options to make it work (i.e. access Flask based REST APIs from the mobile when not connected to the PC). 1. Expose Flask app to the network. And make sure both PC and the mobile phone are on the same wifi. [This](https://stacko...
8,425