qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
18,950,409
I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration. For example: ``` #!/usr/bin/python doubleDict = dict() doubleDict['one'] = dict() doubleDict['one']['type'] = 'animal' doubleDict['on...
2013/09/23
[ "https://Stackoverflow.com/questions/18950409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174102/" ]
For-loops in `dict`s iterates over the keys and not over the values. To iterate over the values do: ``` for thing in doubleDict.itervalues(): print thing print thing['type'] print thing['name'] print thing['species'] ``` I used your exact same code, but added the `.itervalues()` at t...
these all work... but looking at your code, why not use a named tuple instead? from collections import namedtuple LivingThing = namedtuple('LivingThing', 'type name species') doubledict['one'] = LivingThing(type='animal', name='joe', species='monkey') doubledict['one'].name doubledict['one'].\_asdict['name']
18,950,409
I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration. For example: ``` #!/usr/bin/python doubleDict = dict() doubleDict['one'] = dict() doubleDict['one']['type'] = 'animal' doubleDict['on...
2013/09/23
[ "https://Stackoverflow.com/questions/18950409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174102/" ]
A generic way to get to the nested results: ``` for thing in doubleDict.values(): print(thing) for vals in thing.values(): print(vals) ``` or ``` for thing in doubleDict.values(): print(thing) print('\n'.join(thing.values())) ```
You could use @Haidro's answer but make it more generic with a double loop: ``` for key1 in doubleDict: print(doubleDict[key1]) for key2 in doubleDict[key1]: print(doubleDict[key1][key2]) {'type': 'plant', 'name': 'moe', 'species': 'oak'} plant moe oak {'type': 'animal', 'name': 'joe', 'species': 'mon...
18,950,409
I have a two dimensional associative array (dictionary). I'd like to iterate over the first dimension using a for loop, and extract the second dimension's dictionary at each iteration. For example: ``` #!/usr/bin/python doubleDict = dict() doubleDict['one'] = dict() doubleDict['one']['type'] = 'animal' doubleDict['on...
2013/09/23
[ "https://Stackoverflow.com/questions/18950409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1174102/" ]
A generic way to get to the nested results: ``` for thing in doubleDict.values(): print(thing) for vals in thing.values(): print(vals) ``` or ``` for thing in doubleDict.values(): print(thing) print('\n'.join(thing.values())) ```
these all work... but looking at your code, why not use a named tuple instead? from collections import namedtuple LivingThing = namedtuple('LivingThing', 'type name species') doubledict['one'] = LivingThing(type='animal', name='joe', species='monkey') doubledict['one'].name doubledict['one'].\_asdict['name']
48,000,225
I have two dataframes as follows: `leader`: ```none 0 11 1 8 2 5 3 9 4 8 5 6 [6065 rows x 2 columns] ```none `DatasetLabel`: ```none 0 1 .... 7 8 9 10 11 12 0 A J .... 1 2 5 NaN NaN NaN 1 B K .... 3 4 NaN NaN NaN NaN [4095 rows x 14 columns] ``` The Information dataset colu...
2017/12/28
[ "https://Stackoverflow.com/questions/48000225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3806649/" ]
You can use `apply` to index into `leader` and exchange values with `DatasetLabel`, although it's not very pretty. One issue is that Pandas won't let us index with `NaN`. Converting to `str` provides a workaround. But that creates a second issue, namely, column `9` is of type `float` (because `NaN` is `float`), so `5...
The [source code](https://github.com/pandas-dev/pandas/blob/v1.5.2/pandas/core/indexing.py#L1828-L1882) shows that this error occurs when you try to broadcast a list-like object (numpy array, list, set, tuple etc.) to multiple columns or rows but didn't specify the index correctly. Of course, list-like objects don't ha...
7,007,400
I have a small python application, which uses pyttsx for some text to speech. How it works: simply say whatever is there in the clipboard. The program works as expected inside eclipse. But if run on cmd.exe it only works partly if the text on the clipboard is too large(a few paras). Why ? when run from cmd, it prin...
2011/08/10
[ "https://Stackoverflow.com/questions/7007400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161179/" ]
Checked that the problem is not in the code that reads the text from the clipboard. You should check if your eclipse setup specifies custom environment variables for the project which do not exist outside Eclipse. Especially: * PYTHONPATH (and also additional projects on which your program could depend in your setup...
In fact, eclipse itself uses a commandline command to start it's apps. You should check what command eclipse is giving to start the program. It might be a bit verbose, but you can start from there and test what is necessary and what isn't. You can find out the commandline eclipse uses by running the program and then ...
7,007,400
I have a small python application, which uses pyttsx for some text to speech. How it works: simply say whatever is there in the clipboard. The program works as expected inside eclipse. But if run on cmd.exe it only works partly if the text on the clipboard is too large(a few paras). Why ? when run from cmd, it prin...
2011/08/10
[ "https://Stackoverflow.com/questions/7007400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161179/" ]
In fact, eclipse itself uses a commandline command to start it's apps. You should check what command eclipse is giving to start the program. It might be a bit verbose, but you can start from there and test what is necessary and what isn't. You can find out the commandline eclipse uses by running the program and then ...
turns out pythonpath wasn't set properly on my system. Edit: turns out pythonpath isn't the problem. I have no idea whats the problem. arghhhhhhhhhhhhhhhhhhhhhhhh
7,007,400
I have a small python application, which uses pyttsx for some text to speech. How it works: simply say whatever is there in the clipboard. The program works as expected inside eclipse. But if run on cmd.exe it only works partly if the text on the clipboard is too large(a few paras). Why ? when run from cmd, it prin...
2011/08/10
[ "https://Stackoverflow.com/questions/7007400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161179/" ]
Checked that the problem is not in the code that reads the text from the clipboard. You should check if your eclipse setup specifies custom environment variables for the project which do not exist outside Eclipse. Especially: * PYTHONPATH (and also additional projects on which your program could depend in your setup...
turns out pythonpath wasn't set properly on my system. Edit: turns out pythonpath isn't the problem. I have no idea whats the problem. arghhhhhhhhhhhhhhhhhhhhhhhh
32,678,690
How to install pip for python3.4 when my pi have python3.2 and python3.4 when I used `sudo install python3-pip` it's only for python3.2 but I want install pip for python3.4
2015/09/20
[ "https://Stackoverflow.com/questions/32678690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5089211/" ]
Python 3.4 has `pip` included, see [*What's New in Python 3.4*](https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-453). Just execute: ``` python3.4 -m ensurepip ``` to install it if it is missing for you. See the [`ensurepip` module documentation](https://docs.python.org/3/library/ensurepip.html) for further...
You can go to your python 3.4 directory scripts and run it's pip in: `../python3.4/scripts`
32,678,690
How to install pip for python3.4 when my pi have python3.2 and python3.4 when I used `sudo install python3-pip` it's only for python3.2 but I want install pip for python3.4
2015/09/20
[ "https://Stackoverflow.com/questions/32678690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5089211/" ]
Python 3.4 has `pip` included, see [*What's New in Python 3.4*](https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-453). Just execute: ``` python3.4 -m ensurepip ``` to install it if it is missing for you. See the [`ensurepip` module documentation](https://docs.python.org/3/library/ensurepip.html) for further...
You should compile python 3.4 and use venv for python3 environment: 1. Check if you have installed required dependencies: ``` sudo apt-get install build-essential sudo apt-get install libc6-dev libreadline-dev libz-dev libncursesw5-dev libssl-dev libgdbm-dev libsqlite3-dev libbz2-dev liblzma-dev tk-dev ``` 2. Downl...
7,921,973
i'm writing an installer using py2exe which needs to run in admin to have permission to perform various file operations. i've modified some sample code from the user\_access\_controls directory that comes with py2exe to create the setup file. creating/running the generated exe works fine when i run it on my own compute...
2011/10/27
[ "https://Stackoverflow.com/questions/7921973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971550/" ]
Try to set `options={'py2exe': {'bundle_files': 1}},` and `zipfile = None` in setup section. Python will make single .exe file without dependencies. Example: ``` from distutils.core import setup import py2exe setup( console=['watt.py'], options={'py2exe': {'bundle_files': 1}}, zipfile = None ) ```
I rewrite your setup script for you. This will work ``` from distutils.core import setup import py2exe # The targets to build # create a target that says nothing about UAC - On Python 2.6+, this # should be identical to "asInvoker" below. However, for 2.5 and # earlier it will force the app into compatibility mode ...
71,853,039
In short, how do I get this: [![enter image description here](https://i.stack.imgur.com/JBBws.jpg)](https://i.stack.imgur.com/JBBws.jpg) From this: ```py def fiblike(ls, n): store = [] for i in range(n): a = ls.pop(0) ls.append(sum(ls)+a) store.appe...
2022/04/13
[ "https://Stackoverflow.com/questions/71853039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
* Getting pair token balance of contracts > > web3.eth.contract(address=token\_address,abi=abi).functions.balanceOf(contract\_address).call() > > > * and then get current price of each token / USDT by calling function slot0 in pool tokenA/USDT & tokenB/USDT > > slot0 = contract.functions.slot0().call() > > > ...
No offense but you are following a hard way, which needs to use `TickBitmap` to get the next initialized tick (Remember not all ticks are initialized unless necessary.) Alternatively the easy way to get a pool's TVL is to query Uniswap V3's [subgraph](https://thegraph.com/hosted-service/subgraph/ianlapham/uniswap-v3-s...
60,325,327
I wrote an app in python3.7.5 that connects to RabbitMQ: ======================================================== ### Using Ubuntu as the docker-machine I am running rabbitmq with docker: `docker run --name rabbitmq -p 5671:5671 -p 5672:5672 -p 15672:15672 --hostname rabbitmq rabbitmq:3.6.6-management` TEST: ----...
2020/02/20
[ "https://Stackoverflow.com/questions/60325327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1125913/" ]
According to <https://docs.docker.com/network/host/>, > > Note: Given that the container does not have its own IP-address when using host mode networking, port-mapping does not take effect, and the -p, --publish, -P, and --publish-all option are ignored, producing a warning instead: > > > I am not sure this is y...
RabbitMQ container ``` docker run --name rabbitmq \ -p 5671:5671 -p 5672:5672 -p 15672:15672 \ --hostname rabbitmq \ --network host \ # <-- Add this line, now both container see each other rabbitmq:3.6.6-management ``` App container ``` docker run \ -P \ --env ENVIRONMEN...
66,169,625
I have two CSV files: **File 1** ``` Id, 1st, 2nd 1, first, row 2, second, row ``` **File 2** ``` Id, 1st, 2nd 1, first, row 2, second, line 3, third, row ``` I am just starting in python and need to write some code, which can do the diff on these files based on primary columns and in this case first column "Id"...
2021/02/12
[ "https://Stackoverflow.com/questions/66169625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15196604/" ]
I suggest you load both CSV files as Pandas DataFrames, and then you use and outer `merge` with indicator to know what rows changed in the second file. Then, you use `query` to get only the rows that changed in the second file, and you drop the indicator column ('\_merge'). ```py import pandas as pd df1 = pd.read_csv...
I'd also use pandas, as Enrico suggested, for anything more complex than your example. But if you want to do it in pure Python, you can convert your rows into sets and compute a set difference: ```py import csv from io import StringIO data1 = """Id, 1st, 2nd 1, first, row 2, second, row""" data2 = """Id, 1st, 2nd 1, ...
60,532,107
Trying to find out the correct number of parallel processes to run with [python multiprocessing](https://docs.python.org/3.6/library/multiprocessing.html). Scripts below are run on an 8-core, 32 GB (Ubuntu 18.04) machine. (There were only system processes and basic user processes running while the below was tested.) ...
2020/03/04
[ "https://Stackoverflow.com/questions/60532107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333610/" ]
> > **Q** : *"**Why** is running 5 to 8 in parallel at a time **worse than running 4** at a time?"* > > > Well, there are several reasons and we will start from a static, easiest observable one : Since the **silicon design** ( for which they used a few hardware tricks ) **does not scale** beyond the 4. So **the ...
Most likely cause is that you are running the program on a CPU that uses [simultaneous multithreading (SMT)](https://en.wikipedia.org/wiki/Simultaneous_multithreading), better known as [hyper-threading](https://en.wikipedia.org/wiki/Hyper-threading) on Intel units. To cite after wiki, *for each processor core that is p...
73,171,968
I'm trying to make a form where JavaScript makes the authentication of it. After JavaScript says that the user followed the rules correctly, the JavaScript file collects the data typed by the user, so the data is sent to Python (with the help of ajax). From the Python file, I want that it recognizes the data and finall...
2022/07/29
[ "https://Stackoverflow.com/questions/73171968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19575161/" ]
A very simple, and performant way of checking if all pixels are the same, would be to use PIL's `getextrema()` which tells you the brightest and darkest pixel in an image. So you would just test if they are the same and that would work if testing they were both zero, or any other number. It will be performant because i...
1. Convert image to 3D numpy array [enter link description here](https://ru.stackoverflow.com/questions/1145128/%D0%9A%D0%B0%D0%BA-%D0%BF%D1%80%D0%B5%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C-jpg-%D0%B2-%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2-numpy) 2. Check if all elements of an array are the same [ente...
69,607,510
``` import csv import mysql.connector as mysql marathons = [] with open ("marathon_results.csv") as file: data = csv.reader(file) next(data) for rij in data: year = rij[0], winner = rij[1], gender = rij[2], country = rij[3], time = rij[4], marathon = rij[5],...
2021/10/17
[ "https://Stackoverflow.com/questions/69607510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17025019/" ]
The problem is in these lines: ```py year = rij[0], winner = rij[1], gender = rij[2], country = rij[3], time = rij[4], marathon = rij[5], ``` The trailing commas cause `year`, `winner`, `gender` and so on to be created as 1-tuples. It's the same as writing ```py ...
Your sql comad had a & instead of a %. I additionally simplified the data loop ``` import csv import mysql.connector as mysql marathons = [] with open ("test2.csv") as file: data = csv.reader(file) next(data) marathons = [tuple(row) for row in data] conn = mysql.connect( host="localhost", us...
46,053,097
I have created and API using python+flask. When is try to hit the api using postman or chrome it works fine and I am able to get to the api. On the other hand when I try to use python ``` import requests requests.get("http://localhost:5050/") ``` I get 407. I guess that the proxy of the our environment is not allo...
2017/09/05
[ "https://Stackoverflow.com/questions/46053097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6128923/" ]
According to [requests module documentation](http://docs.python-requests.org/en/master/user/advanced/#proxies) you can either provide proxy details through environment variable **HTTP\_PROXY** (in case use Linux distribution): ``` $ export HTTP_PROXY="http://corporate-proxy:port" $ python >>> import requests >>> reque...
Try ``` import requests from flask_cors import CORS, cross_origin app = Flask(__name__) cors = CORS(app, resources={r"/*": {"origins": "*"}}) requests.get("http://localhost:5050/") ```
7,641,592
I [recently asked a question](https://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using p...
2011/10/03
[ "https://Stackoverflow.com/questions/7641592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
You can compress the data with [bzip2](http://docs.python.org/library/bz2.html): ``` from __future__ import with_statement # Only for Python 2.5 import bz2,json,contextlib hugeData = {'key': {'x': 1, 'y':2}} with contextlib.closing(bz2.BZ2File('data.json.bz2', 'wb')) as f: json.dump(hugeData, f) ``` Load it like ...
> > faster, or even possible, to zip this pickle file prior to [writing] > > > Of course it's possible, but there's no reason to try to make an explicit zipped copy in memory (it might not fit!) before writing it, when you can *automatically cause it to be zipped as it is written, with built-in standard library fu...
7,641,592
I [recently asked a question](https://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using p...
2011/10/03
[ "https://Stackoverflow.com/questions/7641592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
You can compress the data with [bzip2](http://docs.python.org/library/bz2.html): ``` from __future__ import with_statement # Only for Python 2.5 import bz2,json,contextlib hugeData = {'key': {'x': 1, 'y':2}} with contextlib.closing(bz2.BZ2File('data.json.bz2', 'wb')) as f: json.dump(hugeData, f) ``` Load it like ...
Look at Google's [ProtoBuffers](http://code.google.com/apis/protocolbuffers/docs/techniques.html#large-data). Although they are not designed for large files out-of-the box, like audio-video files, they do well with object serialization as in your case, because they were designed for it. Practice shows that some day you...
7,641,592
I [recently asked a question](https://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using p...
2011/10/03
[ "https://Stackoverflow.com/questions/7641592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
Python code would be extremely slow when it comes to implementing data serialization. If you try to create an equivalent to Pickle in pure Python, you'll see that it will be super slow. Fortunately the built-in modules which perform that are quite good. Apart from `cPickle`, you will find the `marshal` module, which i...
You can compress the data with [bzip2](http://docs.python.org/library/bz2.html): ``` from __future__ import with_statement # Only for Python 2.5 import bz2,json,contextlib hugeData = {'key': {'x': 1, 'y':2}} with contextlib.closing(bz2.BZ2File('data.json.bz2', 'wb')) as f: json.dump(hugeData, f) ``` Load it like ...
7,641,592
I [recently asked a question](https://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using p...
2011/10/03
[ "https://Stackoverflow.com/questions/7641592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
You can compress the data with [bzip2](http://docs.python.org/library/bz2.html): ``` from __future__ import with_statement # Only for Python 2.5 import bz2,json,contextlib hugeData = {'key': {'x': 1, 'y':2}} with contextlib.closing(bz2.BZ2File('data.json.bz2', 'wb')) as f: json.dump(hugeData, f) ``` Load it like ...
I'd just expand on phihag's answer. When trying to serialize an object approaching the size of RAM, **pickle/cPickle should be avoided**, since it [requires additional memory of 1-2 times the size of the object](http://www.shocksolution.com/2010/01/storing-large-numpy-arrays-on-disk-python-pickle-vs-hdf5adsf/) in orde...
7,641,592
I [recently asked a question](https://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using p...
2011/10/03
[ "https://Stackoverflow.com/questions/7641592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
> > faster, or even possible, to zip this pickle file prior to [writing] > > > Of course it's possible, but there's no reason to try to make an explicit zipped copy in memory (it might not fit!) before writing it, when you can *automatically cause it to be zipped as it is written, with built-in standard library fu...
Look at Google's [ProtoBuffers](http://code.google.com/apis/protocolbuffers/docs/techniques.html#large-data). Although they are not designed for large files out-of-the box, like audio-video files, they do well with object serialization as in your case, because they were designed for it. Practice shows that some day you...
7,641,592
I [recently asked a question](https://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using p...
2011/10/03
[ "https://Stackoverflow.com/questions/7641592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
Python code would be extremely slow when it comes to implementing data serialization. If you try to create an equivalent to Pickle in pure Python, you'll see that it will be super slow. Fortunately the built-in modules which perform that are quite good. Apart from `cPickle`, you will find the `marshal` module, which i...
> > faster, or even possible, to zip this pickle file prior to [writing] > > > Of course it's possible, but there's no reason to try to make an explicit zipped copy in memory (it might not fit!) before writing it, when you can *automatically cause it to be zipped as it is written, with built-in standard library fu...
7,641,592
I [recently asked a question](https://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using p...
2011/10/03
[ "https://Stackoverflow.com/questions/7641592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
Python code would be extremely slow when it comes to implementing data serialization. If you try to create an equivalent to Pickle in pure Python, you'll see that it will be super slow. Fortunately the built-in modules which perform that are quite good. Apart from `cPickle`, you will find the `marshal` module, which i...
Look at Google's [ProtoBuffers](http://code.google.com/apis/protocolbuffers/docs/techniques.html#large-data). Although they are not designed for large files out-of-the box, like audio-video files, they do well with object serialization as in your case, because they were designed for it. Practice shows that some day you...
7,641,592
I [recently asked a question](https://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using p...
2011/10/03
[ "https://Stackoverflow.com/questions/7641592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
I'd just expand on phihag's answer. When trying to serialize an object approaching the size of RAM, **pickle/cPickle should be avoided**, since it [requires additional memory of 1-2 times the size of the object](http://www.shocksolution.com/2010/01/storing-large-numpy-arrays-on-disk-python-pickle-vs-hdf5adsf/) in orde...
Look at Google's [ProtoBuffers](http://code.google.com/apis/protocolbuffers/docs/techniques.html#large-data). Although they are not designed for large files out-of-the box, like audio-video files, they do well with object serialization as in your case, because they were designed for it. Practice shows that some day you...
7,641,592
I [recently asked a question](https://stackoverflow.com/questions/7626848/maximum-python-object-which-can-be-passed-to-write) regarding how to save large python objects to file. I had previously run into problems converting massive Python dictionaries into string and writing them to file via `write()`. Now I am using p...
2011/10/03
[ "https://Stackoverflow.com/questions/7641592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/654789/" ]
Python code would be extremely slow when it comes to implementing data serialization. If you try to create an equivalent to Pickle in pure Python, you'll see that it will be super slow. Fortunately the built-in modules which perform that are quite good. Apart from `cPickle`, you will find the `marshal` module, which i...
I'd just expand on phihag's answer. When trying to serialize an object approaching the size of RAM, **pickle/cPickle should be avoided**, since it [requires additional memory of 1-2 times the size of the object](http://www.shocksolution.com/2010/01/storing-large-numpy-arrays-on-disk-python-pickle-vs-hdf5adsf/) in orde...
21,068,471
Running the following python script through web site works fine and (as expected) stops the playback of MPD: ``` #!/usr/bin/env python import subprocess subprocess.call(["mpc", "stop"]) print ("Content-type: text/plain;charset=utf-8\n\n") print("Hello") ``` This script however causes an error (playback starts as ex...
2014/01/11
[ "https://Stackoverflow.com/questions/21068471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143211/" ]
1. You're running your script in some sort of CGI-like environment. I would strongly suggest using a light web framework like Flask or Bottle. 2. `mpc play` is writing to stdout. You need to silence it: ``` import os with open(os.devnull, 'w') as dev_null: subprocess.call(["mpc", "stop"], stdout=dev_null) ``` 3....
You need to use `\r\n` line endings.
2,700,195
I have some data that I would like to save to a MAT file (version 4 or 5, or any version, for that matter). The catch: I wanted to do this without using matlab libraries, since this code will not necessary run in a machine with matlab. My program uses Java and C++, so any existing library in those languages that achiev...
2010/04/23
[ "https://Stackoverflow.com/questions/2700195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/227103/" ]
C: [matio](http://sourceforge.net/projects/matio/) Java: [jmatio](http://sourceforge.net/projects/jmatio/) (I'm really tempted to, so I will, tell you to learn to google) But really, it's not that hard to write matfiles using `fwrite` if you don't need to handle some of the more complex stuff (nested structs, cl...
MAT files since version 7 are HDF5 based. I recall that they use some rather funny conventions, but you may be able to reverse engineer what you need. There are certainly HDF5 writing libraries for both Java and C++. Along these lines, Matlab can read/write several standard formats, including HDF5. It may be easiest t...
31,073,212
When running: mkvirtualenv test I get following error: ``` File "/usr/lib/python3/dist-packages/virtualenv.py", line 2378, in <module> main() File "/usr/lib/python3/dist-packages/virtualenv.py", line 830, in main symlink=options.symlink) File "/usr/lib/python3/dist-packages/virtualenv.py", line 999, i...
2015/06/26
[ "https://Stackoverflow.com/questions/31073212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3294412/" ]
You are likely getting the error because you cannot create the virtualenv folder in the current working directory. If you do an `ls -ld .` you'll see the output of the current directory you're running the command from, e.g.: ``` ➜ ~ ls -ld . drwxr-xr-x+ 114 tfisher staff 3876 Jun 26 08:46 . ``` and if you do a...
i have did the same the issue i found is : > > `echo $WORKON_HOME` > > > you will find : ***/home/user/.virtualenvs/extra\_path*** just yoy need to remove this extra\_path added after ***.virtualenvs*** path from your ***.bashrc*** and then *source* it again try again creating *mkvirtualenv*
31,073,212
When running: mkvirtualenv test I get following error: ``` File "/usr/lib/python3/dist-packages/virtualenv.py", line 2378, in <module> main() File "/usr/lib/python3/dist-packages/virtualenv.py", line 830, in main symlink=options.symlink) File "/usr/lib/python3/dist-packages/virtualenv.py", line 999, i...
2015/06/26
[ "https://Stackoverflow.com/questions/31073212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3294412/" ]
You are likely getting the error because you cannot create the virtualenv folder in the current working directory. If you do an `ls -ld .` you'll see the output of the current directory you're running the command from, e.g.: ``` ➜ ~ ls -ld . drwxr-xr-x+ 114 tfisher staff 3876 Jun 26 08:46 . ``` and if you do a...
I don't think you can't create a test virtualenv.
31,073,212
When running: mkvirtualenv test I get following error: ``` File "/usr/lib/python3/dist-packages/virtualenv.py", line 2378, in <module> main() File "/usr/lib/python3/dist-packages/virtualenv.py", line 830, in main symlink=options.symlink) File "/usr/lib/python3/dist-packages/virtualenv.py", line 999, i...
2015/06/26
[ "https://Stackoverflow.com/questions/31073212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3294412/" ]
i have did the same the issue i found is : > > `echo $WORKON_HOME` > > > you will find : ***/home/user/.virtualenvs/extra\_path*** just yoy need to remove this extra\_path added after ***.virtualenvs*** path from your ***.bashrc*** and then *source* it again try again creating *mkvirtualenv*
I don't think you can't create a test virtualenv.
3,934,777
I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization. I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s...
2010/10/14
[ "https://Stackoverflow.com/questions/3934777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133374/" ]
I don't think there is a language native implementation of memoization. But you can implement it easily, as a decorator of your method. You have to maintain a Map: the key of your Map is the parameter, the value the result. Here is a simple implementation, for a one-arg method: ``` Map<Integer, Integer> memoizator =...
You could use the [Function](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Function.html) interface in Google's [guava](http://code.google.com/p/guava-libraries/) library to easily achieve what you're after: ``` import java.util.HashMap; import java.util.Map; import com.google.common....
3,934,777
I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization. I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s...
2010/10/14
[ "https://Stackoverflow.com/questions/3934777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133374/" ]
Spring 3.1 now provides a [`@Cacheable` annotation](http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html), which does exactly this. > > As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the ca...
I don't think there is a language native implementation of memoization. But you can implement it easily, as a decorator of your method. You have to maintain a Map: the key of your Map is the parameter, the value the result. Here is a simple implementation, for a one-arg method: ``` Map<Integer, Integer> memoizator =...
3,934,777
I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization. I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s...
2010/10/14
[ "https://Stackoverflow.com/questions/3934777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133374/" ]
I don't think there is a language native implementation of memoization. But you can implement it easily, as a decorator of your method. You have to maintain a Map: the key of your Map is the parameter, the value the result. Here is a simple implementation, for a one-arg method: ``` Map<Integer, Integer> memoizator =...
[Cyclops](https://github.com/aol/cyclops) offers Memoisation for Functions, Suppliers, Callables, Predicates and by extension methods (via Method References) ([see javadoc](http://static.javadoc.io/com.aol.cyclops/cyclops-functions/4.0.2/com/aol/cyclops/functions/Memoise.html)) E.g. Given a variable called that coun...
3,934,777
I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization. I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s...
2010/10/14
[ "https://Stackoverflow.com/questions/3934777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133374/" ]
I came across a memoization library called [Tek271](http://www.tek271.com/software/java/memoizer) which appears to use annotations to memoize functions as you describe.
You could use the [Function](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Function.html) interface in Google's [guava](http://code.google.com/p/guava-libraries/) library to easily achieve what you're after: ``` import java.util.HashMap; import java.util.Map; import com.google.common....
3,934,777
I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization. I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s...
2010/10/14
[ "https://Stackoverflow.com/questions/3934777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133374/" ]
Spring 3.1 now provides a [`@Cacheable` annotation](http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html), which does exactly this. > > As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the ca...
I came across a memoization library called [Tek271](http://www.tek271.com/software/java/memoizer) which appears to use annotations to memoize functions as you describe.
3,934,777
I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization. I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s...
2010/10/14
[ "https://Stackoverflow.com/questions/3934777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133374/" ]
I came across a memoization library called [Tek271](http://www.tek271.com/software/java/memoizer) which appears to use annotations to memoize functions as you describe.
[Cyclops](https://github.com/aol/cyclops) offers Memoisation for Functions, Suppliers, Callables, Predicates and by extension methods (via Method References) ([see javadoc](http://static.javadoc.io/com.aol.cyclops/cyclops-functions/4.0.2/com/aol/cyclops/functions/Memoise.html)) E.g. Given a variable called that coun...
3,934,777
I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization. I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s...
2010/10/14
[ "https://Stackoverflow.com/questions/3934777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133374/" ]
Spring 3.1 now provides a [`@Cacheable` annotation](http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html), which does exactly this. > > As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the ca...
You could use the [Function](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Function.html) interface in Google's [guava](http://code.google.com/p/guava-libraries/) library to easily achieve what you're after: ``` import java.util.HashMap; import java.util.Map; import com.google.common....
3,934,777
I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization. I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s...
2010/10/14
[ "https://Stackoverflow.com/questions/3934777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133374/" ]
You could use the [Function](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Function.html) interface in Google's [guava](http://code.google.com/p/guava-libraries/) library to easily achieve what you're after: ``` import java.util.HashMap; import java.util.Map; import com.google.common....
[Cyclops](https://github.com/aol/cyclops) offers Memoisation for Functions, Suppliers, Callables, Predicates and by extension methods (via Method References) ([see javadoc](http://static.javadoc.io/com.aol.cyclops/cyclops-functions/4.0.2/com/aol/cyclops/functions/Memoise.html)) E.g. Given a variable called that coun...
3,934,777
I have a few functions in my code where it makes much sense (seems even mandatory) to use memoization. I don't want to implement that manually for every function separately. Is there some way (for example [like in Python](http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)) I can just use an annotation or do s...
2010/10/14
[ "https://Stackoverflow.com/questions/3934777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133374/" ]
Spring 3.1 now provides a [`@Cacheable` annotation](http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html), which does exactly this. > > As the name implies, @Cacheable is used to demarcate methods that are cacheable - that is, methods for whom the result is stored into the ca...
[Cyclops](https://github.com/aol/cyclops) offers Memoisation for Functions, Suppliers, Callables, Predicates and by extension methods (via Method References) ([see javadoc](http://static.javadoc.io/com.aol.cyclops/cyclops-functions/4.0.2/com/aol/cyclops/functions/Memoise.html)) E.g. Given a variable called that coun...
71,972,703
I am trying to to a very simple python request using `requests.get` but am getting the following error using this code: ``` url = 'https://www.tesco.com/' status = requests.get(url) ``` The error: ``` requests.exceptions.SSLError: HTTPSConnectionPool(host='www.tesco.com', port=443): Max retries exceeded with url: /...
2022/04/22
[ "https://Stackoverflow.com/questions/71972703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10574250/" ]
Explanation =========== The errors is caused by an invalid or expired [SSL Certificate](https://www.gogetssl.com/wiki/ssl-basics/what-is-ssl-tls/) When making a GET request to a server such as `www.tesco.com` you have 2 options, an [http](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) and an [https](https...
Paraphrasing [similar post](https://stackoverflow.com/questions/41287979/cant-access-certain-sites-requests-get-in-python-3) to your specific question. Response 403 means forbidden, in other words, the website understands the request but doesn't allow access. It could be a security measure to prevent scraping. As a w...
69,751,866
I am getting this error while Executing simple **Recursion Program** in **Python**. ``` RecursionError Traceback (most recent call last) <ipython-input-19-e831d27779c8> in <module> 4 num = 7 5 ----> 6 factorial(num) <ipython-input-19-e831d27779c8> in factorial(n) 1 de...
2021/10/28
[ "https://Stackoverflow.com/questions/69751866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15926850/" ]
A recursive function has a simple rule to follow. 1. Create an exit condition 2. Call yourself (the function) somewhere. Your factorial function only calls itself. And it will not stop in any condition (goes on to negative). Then you hit maximum recursion depth. You should stop when you hit a certain point. In your...
You have to return another value at some point. Example below: ``` def factorial(n): if n == 1: return 1 return (n * factorial(n-1)) ``` Else, your recursive loop will not stop and go to - infinity.
24,023,512
I know this is probably not a good style, but I was wondering if it is possible to construct a class when a static method is called ``` class myClass(): def __init__(self): self.variable = "this worked" @staticmethod def test_class(var=myClass().variable): print self.variable if "__name__...
2014/06/03
[ "https://Stackoverflow.com/questions/24023512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3692553/" ]
Perhaps the easiest is to turn it into a `classmethod` instead: ``` class myClass(object): def __init__(self): self.variable = "this worked" @classmethod def test_class(cls): var = cls().variable print var if __name__ == "__main__": myClass.test_class() ``` See [What is the...
Yes, the default value for a function argument has to be definable at the point that the function appears, and a class isn't actually finished defining until the end of the "class block." The easiest way to do what you're trying to do is: ``` @staticmethod def test_class(var=None): if var is None: var = myClass()....
59,867,504
I am very new to the Python language and have a small program. It had been working but something change and now I can't get it to run. It's having a problem with finding 'pyodbc'. I installed the 'pyodbc' package so I don't understand why there error. I am using Python 3.7.6. Thank you for your help! **pip install pyo...
2020/01/22
[ "https://Stackoverflow.com/questions/59867504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3216326/" ]
If I'm understanding your question correctly and you're looking for how frequent two of the same categories are 1 in the same row (e.g. pairwise like @M-- asked), here's how I've done it in the past. I'm sure there's a more graceful way of going about it though :D ``` library(dplyr) library(tidyr) test.df <- structur...
You can use arules which is geared from this kind of analysis. You can read more about some of its uses [here](https://cran.r-project.org/web/packages/arules/vignettes/arules.pdf) So this is your data: ``` df = structure(list(Type_SunflowerSeeds = c(1L, 1L, 1L, 0L, 0L), Type_SafflowerSeeds = c(0L, 0L, 0L, 0L, 0L), T...
55,483,057
I have the following task in one of my ansible playbook: ``` - name: Generate vault token uri: url: "{{vault_address}}/v1/auth/github/login" method: POST body: "{ \"token\": \"{{ token }}\" }" validate_certs: no body_format: json register: vault_token - nam...
2019/04/02
[ "https://Stackoverflow.com/questions/55483057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5996587/" ]
Add `-vvvv` to your command line to debug. As you specified `body_format: json`, you can simplify your `body` part: ``` - name: Generate vault token uri: url: "{{vault_address}}/v1/auth/github/login" method: POST body: token: mytoken validate_certs: no body_format: json ```
I was able to get past this issue with ansible version `2.7.9` I was on `2.0.0.2`
11,639,577
I installed oauth2 by just downloading tar.gz package and doing `python setup.py install`. However I'm getting this error ``` bash-3.2$ python Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license...
2012/07/24
[ "https://Stackoverflow.com/questions/11639577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730403/" ]
I don't have an answer, but I have some general suggestions: Run `python setup.py install` with the same python that you intend to use it from (in your case one is capitalised, the other is not). I always `export` my bashrc variables to ensure they are global, but I am not sure that is your issue here. When running ...
it looks like you have two different versions of python installed, and one of them you launched using Python as opposed to python. Since your second example workd, it looks like you've installed oauth2 using Python.
34,579,327
I am receiving this error in Python 3.5.1. > > json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) > > > Here is my code: ``` import json import urllib.request connection = urllib.request.urlopen('http://python-data.dr-chuck.net/comments_220996.json') js = connection.read() print(js) info...
2016/01/03
[ "https://Stackoverflow.com/questions/34579327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4679487/" ]
If you look at the output you receive from `print()` and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by `b`): ```none b'{\n "note":"This file ..... ``` If you fetch the URL using a tool such as `curl -v`, you will see that the content type is ```none ...
in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use *try json.loads(str) except* to check your input
25,937,443
In Python, I have three lists containing x and y coordinates. Each list contains 128 points. How can I find the the closest three points in an efficient way? This is my working python code but it isn't efficient enough: ``` def findclosest(c1, c2, c3): mina = 999999999 for i in c1: for j in...
2014/09/19
[ "https://Stackoverflow.com/questions/25937443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4058928/" ]
As written, this is problematic, you are trying to write to a vector for which you did not yet allocate memory. Option 1 - Resize your vectors ahead of time ``` vector< vector<int> > matrix; cout << "Filling matrix with test numbers."; matrix.resize(4); // resize top level vector for (int i = 0; i < 4; i++) { ma...
You have not allocated any space for your 2d vector. So in your current code, you are trying to access some memory that does not belong to your program's memory space. This will result in Segmentation Fault. try: ``` vector<vector<int> > matrix(4, vector<int>(4)); ``` If you want to give all elements the same val...
25,937,443
In Python, I have three lists containing x and y coordinates. Each list contains 128 points. How can I find the the closest three points in an efficient way? This is my working python code but it isn't efficient enough: ``` def findclosest(c1, c2, c3): mina = 999999999 for i in c1: for j in...
2014/09/19
[ "https://Stackoverflow.com/questions/25937443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4058928/" ]
As written, this is problematic, you are trying to write to a vector for which you did not yet allocate memory. Option 1 - Resize your vectors ahead of time ``` vector< vector<int> > matrix; cout << "Filling matrix with test numbers."; matrix.resize(4); // resize top level vector for (int i = 0; i < 4; i++) { ma...
``` vector<int> v2d1(3, 7); vector<vector<int> > v2d2(4, v2d1); for (int i = 0; i < v2d2.size(); i++) { for(int j=0; j <v2d2[i].size(); j++) { cout<<v2d2[i][j]<<" "; } cout << endl; } ```
25,937,443
In Python, I have three lists containing x and y coordinates. Each list contains 128 points. How can I find the the closest three points in an efficient way? This is my working python code but it isn't efficient enough: ``` def findclosest(c1, c2, c3): mina = 999999999 for i in c1: for j in...
2014/09/19
[ "https://Stackoverflow.com/questions/25937443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4058928/" ]
You have not allocated any space for your 2d vector. So in your current code, you are trying to access some memory that does not belong to your program's memory space. This will result in Segmentation Fault. try: ``` vector<vector<int> > matrix(4, vector<int>(4)); ``` If you want to give all elements the same val...
``` vector<int> v2d1(3, 7); vector<vector<int> > v2d2(4, v2d1); for (int i = 0; i < v2d2.size(); i++) { for(int j=0; j <v2d2[i].size(); j++) { cout<<v2d2[i][j]<<" "; } cout << endl; } ```
14,510,286
I'm currently writing an application which allows the user to extend it via a 'plugin' type architecture. They can write additional python classes based on a BaseClass object I provide, and these are loaded against various application signals. The exact number and names of the classes loaded as plugins is unknown befor...
2013/01/24
[ "https://Stackoverflow.com/questions/14510286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233608/" ]
The [metaclass approach](http://martyalchin.com/2008/jan/10/simple-plugin-framework/) is useful for this issue in Python < 3.6 (see @quasoft's answer for Python 3.6+). It is very simple and acts automatically on any imported module. In addition, complex logic can be applied to plugin registration with very little effor...
The approach from will-hart was the most useful one to me! For i needed more control I wrapped the Plugin Base class in a function like: ``` def get_plugin_base(name='Plugin', cls=object, metaclass=PluginMount): def iter_func(self): for mod in self._models: ...
14,510,286
I'm currently writing an application which allows the user to extend it via a 'plugin' type architecture. They can write additional python classes based on a BaseClass object I provide, and these are loaded against various application signals. The exact number and names of the classes loaded as plugins is unknown befor...
2013/01/24
[ "https://Stackoverflow.com/questions/14510286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233608/" ]
Since [Python 3.6](https://docs.python.org/3/whatsnew/3.6.html) a new class method [`__init_subclass__`](https://docs.python.org/3/reference/datamodel.html#object.__init_subclass__) is added, that is called on a base class, whenever a new subclass is created. This method can further simplify the solution offered by wi...
The approach from will-hart was the most useful one to me! For i needed more control I wrapped the Plugin Base class in a function like: ``` def get_plugin_base(name='Plugin', cls=object, metaclass=PluginMount): def iter_func(self): for mod in self._models: ...
1,933,217
I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings. I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in [Ruby](http://github.com/whymirror/mouseh...
2009/12/19
[ "https://Stackoverflow.com/questions/1933217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143725/" ]
Squid and Apache both have mechanisms to call external scripts for allow/deny decisions per-request. This allows you to use either for their proxy engines, but call your external script per request for processing of arbitrary complexity. Your code only has to manage the business logic, not the heavy lifting. In Apache...
If you looking for a Perl solution then take a look at [`HTTP::Proxy`](http://search.cpan.org/dist/HTTP-Proxy/) Not sure of any mod\_perl solutions though. [CPAN](http://search.cpan.org) does bring up [`Apache::Proxy`](http://search.cpan.org/dist/Apache-Proxy/) and Googling brings up [MyProxy](http://sourceforge.net/p...
1,933,217
I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings. I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in [Ruby](http://github.com/whymirror/mouseh...
2009/12/19
[ "https://Stackoverflow.com/questions/1933217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143725/" ]
If you looking for a Perl solution then take a look at [`HTTP::Proxy`](http://search.cpan.org/dist/HTTP-Proxy/) Not sure of any mod\_perl solutions though. [CPAN](http://search.cpan.org) does bring up [`Apache::Proxy`](http://search.cpan.org/dist/Apache-Proxy/) and Googling brings up [MyProxy](http://sourceforge.net/p...
I'd use [squid](http://www.squid-cache.org/), which can execute other programs to change the requests on the fly.
1,933,217
I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings. I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in [Ruby](http://github.com/whymirror/mouseh...
2009/12/19
[ "https://Stackoverflow.com/questions/1933217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143725/" ]
Squid and Apache both have mechanisms to call external scripts for allow/deny decisions per-request. This allows you to use either for their proxy engines, but call your external script per request for processing of arbitrary complexity. Your code only has to manage the business logic, not the heavy lifting. In Apache...
I've been working on a HTTP library in python, written with proxy servers specifically in mind as a use case. It isn't very mature at this point (certainly needs more testing, and unit tests), but it's complete enough that I find it useful. I don't know if it would meet any of your needs or not. The library is called...
1,933,217
I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings. I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in [Ruby](http://github.com/whymirror/mouseh...
2009/12/19
[ "https://Stackoverflow.com/questions/1933217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143725/" ]
I've been working on a HTTP library in python, written with proxy servers specifically in mind as a use case. It isn't very mature at this point (certainly needs more testing, and unit tests), but it's complete enough that I find it useful. I don't know if it would meet any of your needs or not. The library is called...
I'd use [squid](http://www.squid-cache.org/), which can execute other programs to change the requests on the fly.
1,933,217
I'm looking for a way to script a transparent forward proxy such as the ones that users point their browsers to in proxy settings. I've discovered a distinct tradeoff in forward proxies between scriptability and robustness. For example, their are countless proxies developed in [Ruby](http://github.com/whymirror/mouseh...
2009/12/19
[ "https://Stackoverflow.com/questions/1933217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143725/" ]
Squid and Apache both have mechanisms to call external scripts for allow/deny decisions per-request. This allows you to use either for their proxy engines, but call your external script per request for processing of arbitrary complexity. Your code only has to manage the business logic, not the heavy lifting. In Apache...
I'd use [squid](http://www.squid-cache.org/), which can execute other programs to change the requests on the fly.
29,397,839
I am SSHed into a remote machine and I do not have rights to download python packages but I want to use 3rd party applications for my project. I found `cx_freeze` but I'm not sure if that is what I need. What I want to achieve is to be able to run different parts of my project (will mains everywhere) with command line...
2015/04/01
[ "https://Stackoverflow.com/questions/29397839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815710/" ]
When you pass an primitive array such as `char[]` to `Arrays.asList`, that method can't return a `List<char>`, because primitive types aren't allowed as type arguments. But it can and does produce a `List<char[]>`. Your random `char` is never equal to the single `char[]` inside the `List`, so any duplicate `char` is al...
Add you Alphabet in a ArrayList and remove the element selected at each turn of your while. Then update your rand.nextInt like: ``` rand.nextInt(AlphabetList.size()); ``` And your ALPHABET like: ``` List<char> AlphabetList = Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p'...
29,397,839
I am SSHed into a remote machine and I do not have rights to download python packages but I want to use 3rd party applications for my project. I found `cx_freeze` but I'm not sure if that is what I need. What I want to achieve is to be able to run different parts of my project (will mains everywhere) with command line...
2015/04/01
[ "https://Stackoverflow.com/questions/29397839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815710/" ]
When you pass an primitive array such as `char[]` to `Arrays.asList`, that method can't return a `List<char>`, because primitive types aren't allowed as type arguments. But it can and does produce a `List<char[]>`. Your random `char` is never equal to the single `char[]` inside the `List`, so any duplicate `char` is al...
By default the Random numbers generated are duplicate, To overcome this you can keep on adding numbers to the Collection Set till you have all unique numbers ``` while(set.size()< 26) { while (set.add(random.nextInt(26)) != true); } ``` Other way is add all integer to the list & then shuffle it. ```...
70,702,139
I am building a snap to test integration of a python script and a python SDK with snapcraft and there appears to be a conflict when two python 'parts' are built in the same snap. What is the best way to build a snap with multiple python modules? I have a simple script which imports the SDK and then prints some inform...
2022/01/13
[ "https://Stackoverflow.com/questions/70702139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17927115/" ]
Looks like your problem is that you are trying to run python main.py from within the Python interpreter, which is why you're seeing that traceback. Make sure you're out of the interpreter: ``` exit() ``` Then run the **python main.py** command from bash or command prompt or whatever.
Invoke python scripts like this: ``` PS C:\Users\sween\Desktop> python ./a.py ``` Not like this: ``` PS C:\Users\sween\Desktop> python Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ./a.py ...
70,702,139
I am building a snap to test integration of a python script and a python SDK with snapcraft and there appears to be a conflict when two python 'parts' are built in the same snap. What is the best way to build a snap with multiple python modules? I have a simple script which imports the SDK and then prints some inform...
2022/01/13
[ "https://Stackoverflow.com/questions/70702139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17927115/" ]
Looks like your problem is that you are trying to run python main.py from within the Python interpreter, which is why you're seeing that traceback. Make sure you're out of the interpreter: ``` exit() ``` Then run the **python main.py** command from bash or command prompt or whatever.
For better assistance, you may need to provide your Python version. For **Python 3.8**, use `from tkinter import Tk` or `from tkinter import *`. If this did not solve your problem, you may have problem with **tkinter** installation.
70,702,139
I am building a snap to test integration of a python script and a python SDK with snapcraft and there appears to be a conflict when two python 'parts' are built in the same snap. What is the best way to build a snap with multiple python modules? I have a simple script which imports the SDK and then prints some inform...
2022/01/13
[ "https://Stackoverflow.com/questions/70702139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17927115/" ]
Looks like your problem is that you are trying to run python main.py from within the Python interpreter, which is why you're seeing that traceback. Make sure you're out of the interpreter: ``` exit() ``` Then run the **python main.py** command from bash or command prompt or whatever.
First thing I noticed was you need to switch out `root.Canvas` with `tk.Canvas`. ``` import tkinter as tk from tkinter import filedialog, Text import os root = tk.Tk() canvas = tk.Canvas(root, height=700, width=700, bg="#263d42") canvas.pack() root.mainloop() ``` Although even using your original unedited script,...
70,702,139
I am building a snap to test integration of a python script and a python SDK with snapcraft and there appears to be a conflict when two python 'parts' are built in the same snap. What is the best way to build a snap with multiple python modules? I have a simple script which imports the SDK and then prints some inform...
2022/01/13
[ "https://Stackoverflow.com/questions/70702139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17927115/" ]
Looks like your problem is that you are trying to run python main.py from within the Python interpreter, which is why you're seeing that traceback. Make sure you're out of the interpreter: ``` exit() ``` Then run the **python main.py** command from bash or command prompt or whatever.
Your syntax error is on line 6: Instead of: canvas = root.Canvas(root, height=700, width=700, bg="#263d42") Try: canvas = Canvas(root, height=700, width=700, bg="#263d42")
70,702,139
I am building a snap to test integration of a python script and a python SDK with snapcraft and there appears to be a conflict when two python 'parts' are built in the same snap. What is the best way to build a snap with multiple python modules? I have a simple script which imports the SDK and then prints some inform...
2022/01/13
[ "https://Stackoverflow.com/questions/70702139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17927115/" ]
Invoke python scripts like this: ``` PS C:\Users\sween\Desktop> python ./a.py ``` Not like this: ``` PS C:\Users\sween\Desktop> python Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ./a.py ...
For better assistance, you may need to provide your Python version. For **Python 3.8**, use `from tkinter import Tk` or `from tkinter import *`. If this did not solve your problem, you may have problem with **tkinter** installation.
70,702,139
I am building a snap to test integration of a python script and a python SDK with snapcraft and there appears to be a conflict when two python 'parts' are built in the same snap. What is the best way to build a snap with multiple python modules? I have a simple script which imports the SDK and then prints some inform...
2022/01/13
[ "https://Stackoverflow.com/questions/70702139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17927115/" ]
Invoke python scripts like this: ``` PS C:\Users\sween\Desktop> python ./a.py ``` Not like this: ``` PS C:\Users\sween\Desktop> python Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ./a.py ...
First thing I noticed was you need to switch out `root.Canvas` with `tk.Canvas`. ``` import tkinter as tk from tkinter import filedialog, Text import os root = tk.Tk() canvas = tk.Canvas(root, height=700, width=700, bg="#263d42") canvas.pack() root.mainloop() ``` Although even using your original unedited script,...
70,702,139
I am building a snap to test integration of a python script and a python SDK with snapcraft and there appears to be a conflict when two python 'parts' are built in the same snap. What is the best way to build a snap with multiple python modules? I have a simple script which imports the SDK and then prints some inform...
2022/01/13
[ "https://Stackoverflow.com/questions/70702139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17927115/" ]
Invoke python scripts like this: ``` PS C:\Users\sween\Desktop> python ./a.py ``` Not like this: ``` PS C:\Users\sween\Desktop> python Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ./a.py ...
Your syntax error is on line 6: Instead of: canvas = root.Canvas(root, height=700, width=700, bg="#263d42") Try: canvas = Canvas(root, height=700, width=700, bg="#263d42")
70,702,139
I am building a snap to test integration of a python script and a python SDK with snapcraft and there appears to be a conflict when two python 'parts' are built in the same snap. What is the best way to build a snap with multiple python modules? I have a simple script which imports the SDK and then prints some inform...
2022/01/13
[ "https://Stackoverflow.com/questions/70702139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17927115/" ]
First thing I noticed was you need to switch out `root.Canvas` with `tk.Canvas`. ``` import tkinter as tk from tkinter import filedialog, Text import os root = tk.Tk() canvas = tk.Canvas(root, height=700, width=700, bg="#263d42") canvas.pack() root.mainloop() ``` Although even using your original unedited script,...
For better assistance, you may need to provide your Python version. For **Python 3.8**, use `from tkinter import Tk` or `from tkinter import *`. If this did not solve your problem, you may have problem with **tkinter** installation.
70,702,139
I am building a snap to test integration of a python script and a python SDK with snapcraft and there appears to be a conflict when two python 'parts' are built in the same snap. What is the best way to build a snap with multiple python modules? I have a simple script which imports the SDK and then prints some inform...
2022/01/13
[ "https://Stackoverflow.com/questions/70702139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17927115/" ]
First thing I noticed was you need to switch out `root.Canvas` with `tk.Canvas`. ``` import tkinter as tk from tkinter import filedialog, Text import os root = tk.Tk() canvas = tk.Canvas(root, height=700, width=700, bg="#263d42") canvas.pack() root.mainloop() ``` Although even using your original unedited script,...
Your syntax error is on line 6: Instead of: canvas = root.Canvas(root, height=700, width=700, bg="#263d42") Try: canvas = Canvas(root, height=700, width=700, bg="#263d42")
28,780,489
When am trying to run the chron job in django using below command ``` python manage.py runcrons ``` its showing one error like below ``` $ python manage.py runcrons No handlers could be found for logger "django_cron" ``` Does any one have any idea about this error? Any help is appreciated.
2015/02/28
[ "https://Stackoverflow.com/questions/28780489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4582293/" ]
It is kind of given in the error you get. You are missing a handler for the "django\_cron" logger. See for example <https://stackoverflow.com/a/7048543/1197616>. Also have a look at the docs for Django, <https://docs.djangoproject.com/en/dev/topics/logging/>.
Actually the *django-cron* library does not require a 'django\_cron' logger. I resolved the same problem by running the migrations of django\_cron: ``` python manage.py migrate #migrate database ```
62,978,500
I have made a python program that uses Pygame. For some reason, I can't close the window when pressing the red cross. I tried using Command+Q but it doesn't work as well. I have to quit idle (my python interpreter) to close the window. Is there any other way to make the window close by pressing the red 'x' at the top r...
2020/07/19
[ "https://Stackoverflow.com/questions/62978500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12987382/" ]
A pygame window can be closed properly if you use a different python interpreter. Try using pycharm, you can close pygame windows using pycharm.
Try this: ``` import pygame, sys from pygame.locals import * pygame.init() screen = pygame.display.set_mode((800,800)) while True: pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() ```
62,978,500
I have made a python program that uses Pygame. For some reason, I can't close the window when pressing the red cross. I tried using Command+Q but it doesn't work as well. I have to quit idle (my python interpreter) to close the window. Is there any other way to make the window close by pressing the red 'x' at the top r...
2020/07/19
[ "https://Stackoverflow.com/questions/62978500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12987382/" ]
You should just force quit the window or run another program to close the window. When you run a different program, the window should close.
Try this: ``` import pygame, sys from pygame.locals import * pygame.init() screen = pygame.display.set_mode((800,800)) while True: pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() ```
62,978,500
I have made a python program that uses Pygame. For some reason, I can't close the window when pressing the red cross. I tried using Command+Q but it doesn't work as well. I have to quit idle (my python interpreter) to close the window. Is there any other way to make the window close by pressing the red 'x' at the top r...
2020/07/19
[ "https://Stackoverflow.com/questions/62978500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12987382/" ]
A pygame window can be closed properly if you use a different python interpreter. Try using pycharm, you can close pygame windows using pycharm.
You should just force quit the window or run another program to close the window. When you run a different program, the window should close.
20,905,702
I'm currently working with Freeswitch and its [event socket library](http://wiki.freeswitch.org/wiki/Event_Socket_Library) (through the [mod event socket](http://wiki.freeswitch.org/wiki/Mod_event_socket)). For instance: ``` from ESL import ESLconnection cmd = 'uuid_kill %s' % active_call # active_call comes from a ...
2014/01/03
[ "https://Stackoverflow.com/questions/20905702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030960/" ]
Short answer: `cmd` likely contains a Unicode string, which cannot be trivially converted to a `const char *`. The error message likely comes from a wrapper framework that automates writing Python bindings for C libraries, such as SWIG or ctypes. The framework knows what to do with a byte string, but punts on Unicode s...
I had similar problem, and I solved it by doing this: `cmd = 'uuid_kill %s'.encode('utf-8')`
28,431,765
So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed... I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this: ``` Open ...
2015/02/10
[ "https://Stackoverflow.com/questions/28431765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381537/" ]
* OS: Win 10, * Python 3.8.1 + selenium==3.141.0 ``` from selenium import webdriver import time driver = webdriver.Firefox(executable_path=r'TO\Your\Path\geckodriver.exe') driver.get('https://www.google.com/') # Open a new window driver.execute_script("window.open('');") # Switch to the new window driver.switch_to....
I tried for a very long time to duplicate tabs in Chrome running using action\_keys and send\_keys on body. The only thing that worked for me was an answer [here](https://stackoverflow.com/a/41633373/10488716). This is what my duplicate tabs def ended up looking like, probably not the best but it works fine for me. ``...
28,431,765
So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed... I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this: ``` Open ...
2015/02/10
[ "https://Stackoverflow.com/questions/28431765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381537/" ]
I'd stick to [ActionChains](https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains) for this. **Here's a function which opens a new tab and switches to that tab:** ```py import time from selenium.webdriver.common.action_chains import ActionChains def open_in_new_tab(driver, el...
``` tabs = {} def new_tab(): global browser hpos = browser.window_handles.index(browser.current_window_handle) browser.execute_script("window.open('');") browser.switch_to.window(browser.window_handles[hpos + 1]) return(browser.current_window_handle) def switch_tab(name): global tabs globa...
28,431,765
So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed... I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this: ``` Open ...
2015/02/10
[ "https://Stackoverflow.com/questions/28431765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381537/" ]
you can use this to open a new tab ``` driver.execute_script("window.open('http://google.com', 'new_window')") ```
``` #Change the method of finding the element if needed self.find_element_by_xpath(element).send_keys(Keys.CONTROL + Keys.ENTER) ``` This will find the element and open it in a new tab. self is just the name used for the webdriver object.
28,431,765
So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed... I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this: ``` Open ...
2015/02/10
[ "https://Stackoverflow.com/questions/28431765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381537/" ]
**This worked for me:-** ``` link = "https://www.google.com/" driver.execute_script('''window.open("about:blank");''') # Opening a blank new tab driver.switch_to.window(driver.window_handles[1]) # Switching to newly opend tab driver.get(link) ```
Opening the **new empty tab** within same window in chrome browser is **not possible** up to my knowledge but you can open the new tab with web-link. So far I surfed net and I got good working content on this question. Please try to follow the steps without missing. ``` import selenium.webdriver as webdriver from sel...
28,431,765
So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed... I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this: ``` Open ...
2015/02/10
[ "https://Stackoverflow.com/questions/28431765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381537/" ]
you can use this to open a new tab ``` driver.execute_script("window.open('http://google.com', 'new_window')") ```
Opening the **new empty tab** within same window in chrome browser is **not possible** up to my knowledge but you can open the new tab with web-link. So far I surfed net and I got good working content on this question. Please try to follow the steps without missing. ``` import selenium.webdriver as webdriver from sel...
28,431,765
So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed... I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this: ``` Open ...
2015/02/10
[ "https://Stackoverflow.com/questions/28431765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381537/" ]
The other solutions do not work for **chrome driver v83**. Instead, it works as follows, suppose there is only 1 opening tab: ``` driver.execute_script("window.open('');") driver.switch_to.window(driver.window_handles[1]) driver.get("https://www.example.com") ``` If there are already more than 1 opening tabs, you s...
The 4.0.0 version of Selenium supports the following operations: * to open a new tab try: `driver.switch_to.new_window()` * to switch to a specific tab (note that the `tabID` starts from 0): `driver.switch_to.window(driver.window_handles[tabID])`
28,431,765
So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed... I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this: ``` Open ...
2015/02/10
[ "https://Stackoverflow.com/questions/28431765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381537/" ]
I'd stick to [ActionChains](https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains) for this. **Here's a function which opens a new tab and switches to that tab:** ```py import time from selenium.webdriver.common.action_chains import ActionChains def open_in_new_tab(driver, el...
Opening the **new empty tab** within same window in chrome browser is **not possible** up to my knowledge but you can open the new tab with web-link. So far I surfed net and I got good working content on this question. Please try to follow the steps without missing. ``` import selenium.webdriver as webdriver from sel...
28,431,765
So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed... I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this: ``` Open ...
2015/02/10
[ "https://Stackoverflow.com/questions/28431765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381537/" ]
*Editor's note*: This answer no longer works for new Selenium versions. Refer to [this comment](https://stackoverflow.com/questions/28431765/open-web-in-new-tab-selenium-python#comment91110223_28432939). --- You can achieve the opening/closing of a tab by the combination of keys `COMMAND` + `T` or `COMMAND` + `W` (OS...
As already mentioned several times, the following approaches are NOT working anymore: ``` driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't') ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform() ``` Moreover, `driver.execute_script("window.open('');")` is workin...
28,431,765
So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed... I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this: ``` Open ...
2015/02/10
[ "https://Stackoverflow.com/questions/28431765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381537/" ]
**This worked for me:-** ``` link = "https://www.google.com/" driver.execute_script('''window.open("about:blank");''') # Opening a blank new tab driver.switch_to.window(driver.window_handles[1]) # Switching to newly opend tab driver.get(link) ```
As already mentioned several times, the following approaches are NOT working anymore: ``` driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't') ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform() ``` Moreover, `driver.execute_script("window.open('');")` is workin...
28,431,765
So I am trying to open websites on new tabs inside my WebDriver. I want to do this, because opening a new WebDriver for each website takes about 3.5secs using PhantomJS, I want more speed... I'm using a multiprocess python script, and I want to get some elements from each page, so the workflow is like this: ``` Open ...
2015/02/10
[ "https://Stackoverflow.com/questions/28431765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1381537/" ]
just for future reference, the simple way could be done as this: ``` driver.switch_to.new_window() t=driver.window_handles[-1]# Get the handle of new tab driver.switch_to.window(t) driver.get(target_url) # Now the target url is opened in new tab ```
you can use this to open a new tab ``` driver.execute_script("window.open('http://google.com', 'new_window')") ```
27,767,937
Ive been trying to figure this out all night with no luck. Im assuming that this will be a simple question for the more experienced programmer. Im working on a canonical request that I can sign. something like this: ``` canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonica...
2015/01/04
[ "https://Stackoverflow.com/questions/27767937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4400330/" ]
So you want to not have "actual" newlines, but the escape character for newlines in your string? Just add a second slash to `'\n'` to escape it as well, `'\\n'`. Or prepend your strings with r to make them "raw"; in them the backslash is interpreted literally; `r'\n'` (commonly used for regular expressions). ``` canon...
As an alternative and more elegant way you can put your strings in a list and join them with escape the `\n` with add `\` to leading : ``` >>> l=['method', 'canonical_uri', 'canonical_querystring', 'canonical_headers'] >>> print '\\n'.join(l) method\ncanonical_uri\ncanonical_querystring\ncanonical_headers ``` > > ...
14,206,760
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
2013/01/08
[ "https://Stackoverflow.com/questions/14206760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
I was having the same problem. Believe it or not, you have to commit the `.ebextensions` directory and all `*.config` files to version control before you deploy in order for them to show up as environment variables on the server. In order to keep sensitive information out of version control, you can use a config file...
I know this is an old question but for those who still have the same question like I did here is the solution from AWS documentation: <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-softwaresettings.html> > > To configure environment properties in the Elastic Beanstalk console > > > 1. Open...
14,206,760
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
2013/01/08
[ "https://Stackoverflow.com/questions/14206760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
I was having the same problem. Believe it or not, you have to commit the `.ebextensions` directory and all `*.config` files to version control before you deploy in order for them to show up as environment variables on the server. In order to keep sensitive information out of version control, you can use a config file...
I did the following to also get my environment variables that I configure in cloudformation in the non-container phase, eg the regular commands ``` /opt/elasticbeanstalk/bin/get-config environment | python -c "import json,sys; obj=json.load(sys.stdin); f = open('/tmp/eb_env', 'w'); f.write('\n'.join(map(lambda x: 'exp...
14,206,760
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
2013/01/08
[ "https://Stackoverflow.com/questions/14206760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
I did the following to also get my environment variables that I configure in cloudformation in the non-container phase, eg the regular commands ``` /opt/elasticbeanstalk/bin/get-config environment | python -c "import json,sys; obj=json.load(sys.stdin); f = open('/tmp/eb_env', 'w'); f.write('\n'.join(map(lambda x: 'exp...
To set variables on a local run, you can do the following: ``` eb local setenv CONFIG=dev eb local run ``` This also works with Docker MultiContainers, which otherwise will not see your environment.
14,206,760
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
2013/01/08
[ "https://Stackoverflow.com/questions/14206760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
I was having the same problem. Believe it or not, you have to commit the `.ebextensions` directory and all `*.config` files to version control before you deploy in order for them to show up as environment variables on the server. In order to keep sensitive information out of version control, you can use a config file...
I've checked using a modern (i.e., non legacy) container, and found it under /opt/elasticbeanstalk/deploy/configuration/containerconfiguration as a json file. The Behaviour seems to be Platform-Dependent: I remember in PHP in particular, it also creates some shell scripts with the values. Regardless of that, look in...
14,206,760
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
2013/01/08
[ "https://Stackoverflow.com/questions/14206760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
I did the following to also get my environment variables that I configure in cloudformation in the non-container phase, eg the regular commands ``` /opt/elasticbeanstalk/bin/get-config environment | python -c "import json,sys; obj=json.load(sys.stdin); f = open('/tmp/eb_env', 'w'); f.write('\n'.join(map(lambda x: 'exp...
I know this is an old question but for those who still have the same question like I did here is the solution from AWS documentation: <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-softwaresettings.html> > > To configure environment properties in the Elastic Beanstalk console > > > 1. Open...
14,206,760
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
2013/01/08
[ "https://Stackoverflow.com/questions/14206760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
**Option 1:** You can set environment variables using `eb setenv FOO=bar` You can view the environment variables using `eb printenv` **Option 2:** You can create a config file in your .ebextensions directory, for example `00_environment.config`. Then, add your environment variables like this: `option_settings: - ...
To set variables on a local run, you can do the following: ``` eb local setenv CONFIG=dev eb local run ``` This also works with Docker MultiContainers, which otherwise will not see your environment.
14,206,760
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
2013/01/08
[ "https://Stackoverflow.com/questions/14206760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
I was having the same problem. Believe it or not, you have to commit the `.ebextensions` directory and all `*.config` files to version control before you deploy in order for them to show up as environment variables on the server. In order to keep sensitive information out of version control, you can use a config file...
To set variables on a local run, you can do the following: ``` eb local setenv CONFIG=dev eb local run ``` This also works with Docker MultiContainers, which otherwise will not see your environment.
14,206,760
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
2013/01/08
[ "https://Stackoverflow.com/questions/14206760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
I was having the same problem. Believe it or not, you have to commit the `.ebextensions` directory and all `*.config` files to version control before you deploy in order for them to show up as environment variables on the server. In order to keep sensitive information out of version control, you can use a config file...
**Option 1:** You can set environment variables using `eb setenv FOO=bar` You can view the environment variables using `eb printenv` **Option 2:** You can create a config file in your .ebextensions directory, for example `00_environment.config`. Then, add your environment variables like this: `option_settings: - ...
14,206,760
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
2013/01/08
[ "https://Stackoverflow.com/questions/14206760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
I've checked using a modern (i.e., non legacy) container, and found it under /opt/elasticbeanstalk/deploy/configuration/containerconfiguration as a json file. The Behaviour seems to be Platform-Dependent: I remember in PHP in particular, it also creates some shell scripts with the values. Regardless of that, look in...
To set variables on a local run, you can do the following: ``` eb local setenv CONFIG=dev eb local run ``` This also works with Docker MultiContainers, which otherwise will not see your environment.
14,206,760
I have been working on a Django application lately, trying to get it to work with Amazon Elastic Beanstalk. In my `.ebextensions/python.config` file, I have set the following: ``` option_settings: - namespace: aws:elasticbeanstalk:application:environment option_name: ProductionBucket value: s3-bucket-name ...
2013/01/08
[ "https://Stackoverflow.com/questions/14206760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165988/" ]
**Option 1:** You can set environment variables using `eb setenv FOO=bar` You can view the environment variables using `eb printenv` **Option 2:** You can create a config file in your .ebextensions directory, for example `00_environment.config`. Then, add your environment variables like this: `option_settings: - ...
I know this is an old question but for those who still have the same question like I did here is the solution from AWS documentation: <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-softwaresettings.html> > > To configure environment properties in the Elastic Beanstalk console > > > 1. Open...
48,937,024
I am going to write down this pseudocode in python: ``` if (i < .1): doX() elif (i < .3): doY() elif (i < .5): doZ() . . else: doW() ``` The range of numbers may be 20, and each float number which shapes the constraints is read from a list. For the above example (shorter version), it is the list: ``` ...
2018/02/22
[ "https://Stackoverflow.com/questions/48937024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8899386/" ]
``` from bisect import * a=[0.1, 0.3, 0.5, 1] b=["a","b","c","d"] print b[bisect_left(a,0.2)] ```
Here's an answer that you should not use: ``` doX = lambda x: x + 1 doY = lambda x: x + 10 doZ = lambda x: x + 100 ranges = [0.1, 0.3, 0.5, 1] functions = [doX, doY, doZ] answer = lambda x: [func(x) for (low, high), func in zip(zip(ranges[:-1],ranges[1:]), function) if low <= x < high][0] ``` The point is, that g...
48,937,024
I am going to write down this pseudocode in python: ``` if (i < .1): doX() elif (i < .3): doY() elif (i < .5): doZ() . . else: doW() ``` The range of numbers may be 20, and each float number which shapes the constraints is read from a list. For the above example (shorter version), it is the list: ``` ...
2018/02/22
[ "https://Stackoverflow.com/questions/48937024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8899386/" ]
``` from bisect import * a=[0.1, 0.3, 0.5, 1] b=["a","b","c","d"] print b[bisect_left(a,0.2)] ```
``` def a(): print('a returned') def b(): print('b returned') def c(): print('c returned') funcs = [a, b, c] def sample_func(x, funcs=None): if x < 0: return None thresholds = [.40, .60] for i, threshold in enumerate(thresholds): if x <= threshold: return fun...
48,937,024
I am going to write down this pseudocode in python: ``` if (i < .1): doX() elif (i < .3): doY() elif (i < .5): doZ() . . else: doW() ``` The range of numbers may be 20, and each float number which shapes the constraints is read from a list. For the above example (shorter version), it is the list: ``` ...
2018/02/22
[ "https://Stackoverflow.com/questions/48937024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8899386/" ]
``` from bisect import * a=[0.1, 0.3, 0.5, 1] b=["a","b","c","d"] print b[bisect_left(a,0.2)] ```
I suggest you to create the following dictionary with numbers as keys and functions as values: ``` d = {0.1:doX, 0.3:doY, 0.5:doZ, 1:doW} ``` Then use the following code: ``` for n,(k,f) in enumerate(sorted(d.items())): if (i < k) or (n == (len(d) - 1)): f() break ```
63,815,087
I'm porting some Python 2 legacy code and I have this class: ``` class myfile(file): "Wrapper for file object whose read member returns a string buffer" def __init__ (self, *args): return file.__init__ (self, *args) def read(self, size=-1): return create_string_buffer(file.read(self, size)...
2020/09/09
[ "https://Stackoverflow.com/questions/63815087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6271889/" ]
If another way is fine , you can try the below, it is a little dirty though (you can try optimizing it) ``` cols = ['name','color','amount'] u = df[df.columns.difference(cols)].join(df[cols].agg(dict,1).rename('d')) v = (u.groupby(['cat1','cat2','cat3'])['d'].agg(list).reset_index("cat3")) v = v.groupby(v.index).appl...
We can `groupby` on `cat1`, `cat2` and `cat3` and recursively build the dictionary based on the grouped categories: ``` def set_val(d, k, v): if len(k) == 1: d[k[0]] = v else: d[k[0]] = set_val(d.get(k[0], {}), k[1:], v) return d dct = {} for k, g in df.groupby(['cat1', 'cat2', 'cat3']): ...
63,815,087
I'm porting some Python 2 legacy code and I have this class: ``` class myfile(file): "Wrapper for file object whose read member returns a string buffer" def __init__ (self, *args): return file.__init__ (self, *args) def read(self, size=-1): return create_string_buffer(file.read(self, size)...
2020/09/09
[ "https://Stackoverflow.com/questions/63815087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6271889/" ]
If another way is fine , you can try the below, it is a little dirty though (you can try optimizing it) ``` cols = ['name','color','amount'] u = df[df.columns.difference(cols)].join(df[cols].agg(dict,1).rename('d')) v = (u.groupby(['cat1','cat2','cat3'])['d'].agg(list).reset_index("cat3")) v = v.groupby(v.index).appl...
This is a *generic* method adapted from [Shubham Sharma's great Solution](https://stackoverflow.com/a/63816750/1167012) ``` def gen_nested_dict(dataframe, group, inner_key, inner_dict): def set_val(d, k2, v): if len(k2) == 1: d[k2[0]] = v else: d[k2[0]] = set_val(d.get(k2[0]...
63,815,087
I'm porting some Python 2 legacy code and I have this class: ``` class myfile(file): "Wrapper for file object whose read member returns a string buffer" def __init__ (self, *args): return file.__init__ (self, *args) def read(self, size=-1): return create_string_buffer(file.read(self, size)...
2020/09/09
[ "https://Stackoverflow.com/questions/63815087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6271889/" ]
We can `groupby` on `cat1`, `cat2` and `cat3` and recursively build the dictionary based on the grouped categories: ``` def set_val(d, k, v): if len(k) == 1: d[k[0]] = v else: d[k[0]] = set_val(d.get(k[0], {}), k[1:], v) return d dct = {} for k, g in df.groupby(['cat1', 'cat2', 'cat3']): ...
This is a *generic* method adapted from [Shubham Sharma's great Solution](https://stackoverflow.com/a/63816750/1167012) ``` def gen_nested_dict(dataframe, group, inner_key, inner_dict): def set_val(d, k2, v): if len(k2) == 1: d[k2[0]] = v else: d[k2[0]] = set_val(d.get(k2[0]...