qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
49,411,277
I'm using Python to automate some reporting, but I am stuck trying to connect to an SSAS cube. I am on Windows 7 using Anaconda 4.4, and I am unable to install any libraries beyond those included in Anaconda. I have used pyodbc+pandas to connect to SQL Server databases and extract data with SQL queries, and the goal n...
2018/03/21
[ "https://Stackoverflow.com/questions/49411277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9529670/" ]
SSAS doesn't support [ODBC clients](https://learn.microsoft.com/en-us/sql/analysis-services/instances/data-providers-used-for-analysis-services-connections) . It does provide HTTP access through IIS, which requires [a few configuration steps](https://learn.microsoft.com/en-us/sql/analysis-services/instances/configure-h...
Perhaps this solution will help you <https://stackoverflow.com/a/65434789/14872543> the idea is to use the construct on linced MSSQL Server ``` SELECT olap.* from OpenRowset ('"+ olap_conn_string+"',' " + mdx_string +"') "+ 'as olap' ```
17,554
65,605,972
Before downgrading my GCC, I want to know if there's a way to figure which programs/frameworks or dependencies in my machine will break and if there is a better way to do this for openpose installation? (e.g. changing something in CMake) Is there a hack to fix this without changing my system GCC version and potentiall...
2021/01/07
[ "https://Stackoverflow.com/questions/65605972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2414957/" ]
Solved by downgrading the GCC from 9.3.0 to 7: ``` $ sudo apt remove gcc $ sudo apt-get install gcc-7 g++-7 -y $ sudo ln -s /usr/bin/gcc-7 /usr/bin/gcc $ sudo ln -s /usr/bin/g++-7 /usr/bin/g++ $ sudo ln -s /usr/bin/gcc-7 /usr/bin/cc $ sudo ln -s /usr/bin/g++-7 /usr/bin/c++ $ gcc --version gcc (Ubuntu 7.5.0-6ubuntu2) 7...
You should point to a correct GCC bin file (below 9) from the dependencies in cmake command. no need to downgrade the GCC for example: ``` cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_C_COMPILER=/usr/bin/gcc-8 ```
17,556
53,369,766
Following the [Microsoft Azure documentation for Python developers](https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.models.blob?view=azure-python). The `azure.storage.blob.models.Blob` class does have a private method called `__sizeof__()`. But it returns a constant value of 16, wheth...
2018/11/19
[ "https://Stackoverflow.com/questions/53369766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2604247/" ]
> > I want to have an additional check on the size to judge whether I am dealing with an empty blob. > > > We could use the [BlobProperties().content\_length](https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.models.blobproperties?view=azure-python) to check whether it is a empty b...
``` from azure.storage.blob import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(connect_str) blob_list = blob_service_client.get_container_client(my_container).list_blobs() for blob in blob_list: print("\t" + blob.name) print('\tsize=', blob.size) ```
17,557
39,981,667
I installed Robotframework RIDE with my user credentials and trying to access that by logging in with the another user in the same machine. when i copy paste the ride.py(available in C:/Python27/Scripts) file from my user to another user i can access RIDE by double clicking the ride.py file, but when i try to access us...
2016/10/11
[ "https://Stackoverflow.com/questions/39981667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295988/" ]
I'm using gem [breadcrumbs on rails](https://github.com/weppos/breadcrumbs_on_rails) with devise in my project. If you haven't made User model with devise make that first: ``` rails g devise User rake db:migrate rails generate devise:views users ``` My registration\_controller.rb looks like this: ``` # app/control...
You can generate the devise views with: `rails generate devise:views users` Make sure to replace `users` with whatever your user model name is if it isn't `User` (e.g. `Admin`, `Manager`, etc) You can then add to those views whatever you need to show breadcrumbs.
17,558
14,672,640
I am trying to use python-twitter api in GAE. I need to import Oauth2 and httplib2. Here is how I did For OAuth2, I downloaded github.com/simplegeo/python-oauth2/tree/master/oauth2. For HTTPLib2, I dowloaded code.google.com/p/httplib2/wiki/Install and extracted folder python2/httplib2 to project root folder. my v...
2013/02/03
[ "https://Stackoverflow.com/questions/14672640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/496837/" ]
``` ‘%A%’; ``` v.s. ``` '%A%'; ``` The first has fancy `'` characters. The usual cause for that is Outlook's AutoCorrect.
Problem with the 1st is the single quote. `SQL` doesn't accept that quote. I dont find the one in my keyboard. May be you copied the query from somewhere.
17,559
53,241,645
In Python 3.6, I can use the `__set_name__` hook to get the class attribute name of a descriptor. How can I achieve this in python 2.x? This is the code which works fine in Python 3.6: ``` class IntField: def __get__(self, instance, owner): if instance is None: return self return inst...
2018/11/10
[ "https://Stackoverflow.com/questions/53241645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5766927/" ]
You may be looking for metaclasses, with it you can process the class attributes at class creation time. ``` class FooDescriptor(object): def __get__(self, obj, objtype): print('calling getter') class FooMeta(type): def __init__(cls, name, bases, attrs): for k, v in attrs.iteritems(): ...
There are various solutions with different degrees of hackishness. I always liked to use a class decorator for this. ``` class IntField(object): def __get__(self, instance, owner): if instance is None: return self return instance.__dict__[self.name] def __set__(self, in...
17,561
41,595,720
I am about to upgrade from Django 1.9 to 1.10 and would like to test if I have some deprecated functionality. However using ``` python -Wall manage.py test ``` will show tons and tons of warnings for Django 2.0. Is there a way to suppress warnings only for 2.0 or show only warnings for 1.10?
2017/01/11
[ "https://Stackoverflow.com/questions/41595720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5047630/" ]
**Solution 1 - Using groups** ``` Private Sub Workbook_Open() With Sheet1 Dim i As Long, varLast As Long .Cells.ClearOutline varLast = .Cells(.Rows.Count, "A").End(xlUp).Row .Columns("A:A").Insert Shift:=xlToRight 'helper column For i = 1 To varLast .Range("A" ...
One possibility would be to add a button to each cell and to hide its children rows on *collapse* and display its children rows on *expand*. Each `Excel.Button` executes one common method `TreeNodeClick` where the `Click` method is called on corresponding instance of `TreeNode`. The child rows are hidden or displayed...
17,562
39,469,409
I've just created Django project and ran the server. It works fine but showed me warnings like ``` You have 14 unapplied migration(s)... ``` Then I ran ``` python manage.py migrate ``` in the terminal. It worked but showed me this ``` ?: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the ...
2016/09/13
[ "https://Stackoverflow.com/questions/39469409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4727702/" ]
So my problem was that I used wrong python version for migration. ``` python3.5 manage.py migrate ``` solves the problem.
You are probably using wrong django version. You need `django1.10`
17,563
44,916,289
When I try to install a package for python, the setup.py has the following lines: ``` import os, sys, platform from distutils.core import setup, Extension import subprocess from numpy import get_include from Cython.Distutils import build_ext from Cython.Build import cythonize from Cython.Compiler.Options import get_di...
2017/07/05
[ "https://Stackoverflow.com/questions/44916289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8256442/" ]
Your `package.json` is missing `should` as a dependency. Install it via; `npm install --save-dev should` Also I would recommend you look into [chai](http://chaijs.com/api/bdd/) which in my opinion provides a slightly different API.
**should is an expressive, readable, framework-agnostic assertion library. The main goals of this library are to be expressive and to be helpful. It keeps your test code clean, and your error messages helpful. By default (when you require('should')) should extends the Object.prototype with a single non-enumerable gette...
17,564
23,421,031
What I put in python: ``` phoneNumber = input("Enter your Phone Number: ") print("Your number is", str(phoneNumber)) ``` What I get if I put 021999888: ``` Enter your Phone Number: 021999888 ``` > > Traceback (most recent call last): File "None", line 1, in > invalid token: , line 1, pos 9 > > > What I ge...
2014/05/02
[ "https://Stackoverflow.com/questions/23421031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3595018/" ]
If you have a `0` before a numeric literal, then it is in octal format. In this case any digit greater than 7 will result in an error. I think you should consider storing the phone number as a string, so use `raw_input()` instead. This will also keep the leading 0's.
@perreal is right. You should use `raw_input` instead: ``` >>> phoneNumber = raw_input("Enter your Phone Number: ") >>> print("Your number is", phoneNumber) Enter your Phone Number: 091234123 Your number is 091234123 ```
17,565
67,360,917
i would like to make a groupby on my data to put together dates that are close. (less than 2 minutes) Here an example of what i get ``` > datas = [['A', 51, 'id1', '2020-05-27 05:50:43.346'], ['A', 51, 'id2', > '2020-05-27 05:51:08.347'], ['B', 45, 'id3', '2020-05-24 > 17:23:55.142'],['B', 45, 'id4', '2020-05-24 17:2...
2021/05/02
[ "https://Stackoverflow.com/questions/67360917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15817735/" ]
A compiler is allowed to choose if `char` is signed or unsigned. The standard says that they have to pick, but don't mandate which way they choose. GCC supports `-fsigned-char` and `-funsigned-char` to force this behavior.
The shown output is consistent with `char` being an unsigned data type on the platform in question. The C++ standard allows `char` to be equivalent to either `unsigned char` or `signed char`. If you wish a specific behavior you can explicitly use a cast to `signed char` in your code.
17,568
69,046,120
It shows that tables are successfully created when I do `heroku run -a "app-name" python manage.py migrate` ``` Running python manage.py migrate on ⬢ app_name... up, run.0000 (Free) System check identified some issues: ... Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, home, sessions...
2021/09/03
[ "https://Stackoverflow.com/questions/69046120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11235791/" ]
Re-check your database configuration. The error trace shows that it's using sqlite as the database backend, instead of Postgres as expected: ``` File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute ``` This is then failing because the sqlite database is stor...
please run these command ``` python manage.py syncdb python manage.py migrate python manage.py createsuperuser ``` please make sure that you in your installed app ``` 'django.contrib.auth' ``` and tell me if you still got the same error and then please add your settings.py
17,571
41,875,358
I'm following this guide <https://developers.google.com/sheets/api/quickstart/python> Upon running the sample code they provided (The only thing I changed was the location of the api secret since we already had one set up and the APPLICATION\_NAME) I get this error ``` AttributeError: 'module' object has no attribut...
2017/01/26
[ "https://Stackoverflow.com/questions/41875358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5838056/" ]
I got the same error and investigated on the problem. In my case, it was caused by a file named ''calendar.py" in the same directory. It's said you should avoid using general names that can be used for standard python library.
It may be versioning problem. It could be `python3` version of `httplib2` which cause troubles, try to follow answer from this [post](https://stackoverflow.com/questions/48941042/google-cloud-function-attributeerror-module-object-has-no-attribute-defaul/49970238#49970238)
17,572
33,309,904
On my local environment, with Python 2.7.10, my Django project seems to run perfectly well using .manage.py runserver. But when I tried to deploy the project to my Debian Wheezy server using the same version of python 2.7.10, it encountered 500 internal server error. Upon checking my apache log, I found the error to be...
2015/10/23
[ "https://Stackoverflow.com/questions/33309904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2970242/" ]
writing solution in answer separately for readability of others. ``` for i in [i for i, x in enumerate(hanksArray) if x == hanksYear]: print(hanksArray[i-1]) print(hanksArray[i]) print(hanksArray[i+1]) ```
Quick solution for you will be ``` for i in [i for i, x in enumerate(hanksArray) if x == hanksYear]: print("\n".join(hanksArray[i-1:i+2])) ``` There are numerous other problems with your code anyway
17,573
39,091,551
I am planning on making a game with pygame using gpio buttons. Here is the code: ``` from gpiozero import Button import pygame from time import sleep from sys import exit up = Button(2) left = Button(3) right = Button(4) down = Button(14) fps = pygame.time.Clock() pygame.init() surface = pygame.display.set_mode((1...
2016/08/23
[ "https://Stackoverflow.com/questions/39091551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2945954/" ]
There are two possible ways to close the pygame window . 1. after the end of while loop simply write ``` import sys while 1: ....... pygame.quit() sys.exit() ``` 2.instead of putting a break statement ,replace break in for loop immediately after while as ``` while 1: for event in pygame.event.get(): ...
You need to make a event and within it you need to quit the pygame ``` for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() ```
17,575
14,086,830
I'm punching way above my weight here, but please bear with this Python amateur. I'm a PHP developer by trade and I've hardly touched this language before. What I'm trying to do is call a method in a class...sounds simple enough? I'm utterly baffled about what 'self' refers to, and what is the correct procedure to cal...
2012/12/29
[ "https://Stackoverflow.com/questions/14086830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122776/" ]
The first argument of all methods is usually called `self`. It refers to the instance for which the method is being called. Let's say you have: ``` class A(object): def foo(self): print 'Foo' def bar(self, an_argument): print 'Bar', an_argument ``` Then, doing: ``` a = A() a.foo() #prints...
> > Could someone explain to me, how to call the move method with the variable RIGHT > > > ``` >>> myMissile = MissileDevice(myBattery) # looks like you need a battery, don't know what that is, you figure it out. >>> myMissile.move(MissileDevice.RIGHT) ``` If you have programmed in any other language with class...
17,576
74,663,591
I'm trying to remake Tic-Tac-Toe on python. But, it wont work. I tried ` ``` game_board = ['_'] * 9 print(game_board[0]) + " | " + (game_board[1]) + ' | ' + (game_board[2]) print(game_board[3]) + ' | ' + (game_board[4]) + ' | ' + (game_board[5]) print(game_board[6]) + ' | ' + (game_board[7]) + ' | ' + (game_board[8])...
2022/12/03
[ "https://Stackoverflow.com/questions/74663591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20671383/" ]
``` function put() { var num0 = document.getElementById("text") var num1 = Number(num0.value) var num4 = document.getElementById("text2") var num2 = Number(num4.value) var sub = document.getElementById("submit") var res = num1 + num2 document.getElementById("myp").innerHTML...
You can use the `+` operator, like that: ``` var num1 = +num0.value; ... var num2 = +num4.value; ``` and this will turn your string number into a *floating* point number ```html <input type="text" id="text" placeholder="Number 1" /> <input type="text" id="text2" placeholder="Number 2" /> <button type="submit" id="s...
17,579
43,708,668
I have a simplified python code looking like the following: ``` a = 100 x = 0 for i in range(0, a): x = x + i / float(a) ``` Is there a way to access the maximum amount of iterations inside a `for` loop? Basically the code would change to: ``` x = 0 for i in range(0, 100): x = x + i / float(thisloopsmaxco...
2017/04/30
[ "https://Stackoverflow.com/questions/43708668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6786718/" ]
Yeah, you can.. ``` a = 100 x = 0 r = range(0,a) for i in r: x = x + i / r.stop ``` but if the range isn't counting 1,2,3... then the `stop` won't be the number of steps, e.g. `range(10,12)` doesn't have 12 steps it has 2 steps. And `range(0,100,10)` counts in tens, so it doesn't have 100 steps. So you need to ...
There's nothing built-in, but you can easily compute it yourself: ``` x = 0 myrange = range(0, 100) thisloopsmaxcount = sum(1 for _ in myrange) for i in myrange: x = x + i / float(thisloopsmaxcount) ```
17,581
42,212,502
I have a list of strings, for example: ``` py python co comp computer ``` I simply want to get a string, which contains the biggest possible amount of prefixes. The result should be 'computer' because its prefixes are 'co' and 'comp' (2 prefixes). I have this code (wordlist is a dictionary): ``` for i in wordlist:...
2017/02/13
[ "https://Stackoverflow.com/questions/42212502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7396899/" ]
The data structure you are looking for is called a [trie](https://en.wikipedia.org/wiki/Trie). The Wikipedia article about this kind of search tree is certainly worth reading. The key property of the trie that comes in handy here is this: > > All the descendants of a node have a common prefix of the string associated...
For a large amount of words, you could build a [trie](https://en.wikipedia.org/wiki/Trie). You could then iterate over all the leaves and count the amount of nodes (terminal nodes) with a value between the root and the leaf. With n words, this should require `O(n)` steps compared to your `O(n**2)` solution. This [pa...
17,584
52,884,584
I have this array: ``` countOverlaps = [numA, numB, numC, numD, numE, numF, numG, numH, numI, numJ, numK, numL] ``` and then I condense this array by getting rid of all 0 values: ``` countOverlaps = [x for x in countOverlaps if x != 0] ``` When I do this, I get an output like this: [2, 1,...
2018/10/19
[ "https://Stackoverflow.com/questions/52884584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7010858/" ]
**Updated** Please check below: ``` >>> a = [2, 1, 3, 2, 3, 1, 1] >>> [b for b in a for _ in range(b)] [2, 2, 1, 3, 3, 3, 2, 2, 3, 3, 3, 1, 1] ```
This can be done using list comprehension. So far you had: ``` countOverlaps = [10,25,11,0,10,6,9,0,12,6,0,6,6,11,18] countOverlaps = [x for x in countOverlaps if x != 0] ``` This gives us all non=0 numbers. Then we can do what you want with the following code: ``` mylist = [number for number in list(set(countOverl...
17,586
42,066,449
So I have a function in python which generates a dict like so: ``` player_data = { "player": "death-eater-01", "guild": "monster", "points": 50 } ``` I get this data by calling a function. Once I get this data I want to write this into a file, so I call: ``` g = open('team.json', 'a') with g as outfile: ...
2017/02/06
[ "https://Stackoverflow.com/questions/42066449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1591731/" ]
You shouldn't append data to an existing file. Rather, you should build up a list in Python first which contains all the dicts you want to write, and only then dump it to JSON and write it to the file. If you really can't do that, one option would be to load the existing file, convert it back to Python, then append yo...
To produce valid JSON you will need to load the previous contents of the file, append the new data to that and then write it back to the file. Like so: ``` def append_player_data(player_data, file_name="team.json"): if os.path.exists(file_name): with open(file_name, 'r') as f: all_data = json....
17,587
27,529,610
I'm new to python and currently playing with it. I have a script which does some API Calls to an appliance. I would like to extend the functionality and call different functions based on the arguments given when calling the script. Currently I have the following: ``` parser = argparse.ArgumentParser() parser.add_argu...
2014/12/17
[ "https://Stackoverflow.com/questions/27529610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4370943/" ]
Since it seems like you want to run one, and only one, function depending on the arguments given, I would suggest you use a mandatory positional argument `./prog command`, instead of optional arguments (`./prog --command1` or `./prog --command2`). so, something like this should do it: ``` FUNCTION_MAP = {'top20' : my...
``` # based on parser input to invoke either regression/classification plus other params import argparse parser = argparse.ArgumentParser() parser.add_argument("--path", type=str) parser.add_argument("--target", type=str) parser.add_argument("--type", type=str) parser.add_argument("--deviceType", type=str) args =...
17,588
48,643,925
I am looking through some code and found the following lines: ``` def get_char_count(tokens): return sum(len(t) for t in tokens) def get_long_words_ratio(tokens, nro_tokens): ratio = sum(1 for t in tokens if len(t) > 6) / nro_tokens return ratio ``` As you can see, in the first case the complete express...
2018/02/06
[ "https://Stackoverflow.com/questions/48643925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1150683/" ]
> > Does it return by reference[?] > > > Effectively yes. When you return an object, the id (i.e. memory address) of the object inside the function is the same as the id of the object outside the function. It doesn't make a copy or anything. > > [...] or does it return the value directly? > > > If you're say...
While I prefer the first approach (Since it uses less memory), both expressions are equivalent in behavior. The PEP8 Style Guide doesn't really say anything about this, other than being consistent with your return statements. > > Be consistent in return statements. Either all return statements in a function should r...
17,598
57,948,945
I have a very large square matrix of order around 570,000 x 570,000 and I want to power it by 2. The data is in json format casting to associative array in array (dict inside dict in python) form Let's say I want to represent this matrix: ``` [ [0, 0, 0], [1, 0, 5], [2, 0, 0] ] ``` In json it's stored like: `...
2019/09/15
[ "https://Stackoverflow.com/questions/57948945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10530951/" ]
Numpy is not the problem, you need to input it on a format that numpy can understand, but since your matrix is really big, it probably won't fit in memory, so it's probably a good idea to use a sparse matrix (`scipy.sparse.csr_matrix`): ``` m = scipy.sparse.csr_matrix(( [v for row in data.values() for v in row.val...
> > now I have to somehow translate csr\_matrix back to json serializable > > > Here's one way to do that, using the attributes **data**, **indices**, **indptr** - `m` is the *csr\_matrix*: ``` d = {} end = m.indptr[0] for row in range(m.shape[0]): start = end end = m.indptr[row+1] if end > start: # i...
17,599
744,894
I want to pull certain comments from my py files that give context to translations, rather than manually editing the .pot file basically i want to go from this python file: ``` # For Translators: some useful info about the sentence below _("Some string blah blah") ``` to this pot file: ``` # For Translators: some u...
2009/04/13
[ "https://Stackoverflow.com/questions/744894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55565/" ]
After much pissing about I found the best way to do this: ``` #. Translators: # Blah blah blah _("String") ``` Then search for comments with a . like so: ``` xgettext --language=Python --keyword=_ --add-comments=. --output=test.pot *.py ```
I was going to suggest the `compiler` module, but it ignores comments: f.py: ``` # For Translators: some useful info about the sentence below _("Some string blah blah") ``` ..and the compiler module: ``` >>> import compiler >>> m = compiler.parseFile("f.py") >>> m Module(None, Stmt([Discard(CallFunc(Name('_'), [Co...
17,602
72,029,157
I read book, I try practice these code snippet ```py >>> from lis import parse >>> parse('1.5') 1.5 ``` Then I follow guide at <https://github.com/adamhaney/lispy#getting-started> . My PC is Windows 11 Pro x64. ``` C:\Users\donhu>python -V Python 3.10.4 C:\Users\donhu>pip -V pip 22.0.4 from C:\Program Files\Python...
2022/04/27
[ "https://Stackoverflow.com/questions/72029157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3728901/" ]
You should use [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [`filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). ```js const input = [ { title: "QA", rows: [ { risk: "P1", ...
First your original array needs an opening `[`. Instead of using `Array#forEach` use `Array#map` instead. `.forEach` does not return any result, but can allow you to modify the original array; `.map` on the other hand creates a new array. ```js const input = [{ "title": "QA", "rows": [ { "risk": "P1", "Title": "Server...
17,603
40,427,547
I am looking for a conditional statement in python to look for a certain information in a specified column and put the results in a new column Here is an example of my dataset: ``` OBJECTID CODE_LITH 1 M4,BO 2 M4,BO 3 M4,BO 4 M1,HP-M7,HP-M1 ``` and what I want ...
2016/11/04
[ "https://Stackoverflow.com/questions/40427547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6146748/" ]
Use simple `[row][col]` access to your double pointer. It is more readable and you can avoid errors, as you coded. ``` #include<stdio.h> #include<stdlib.h> int main(void) { int **tab; int ligne; int col; printf("saisir le nbre de lignes volous\n"); scanf("%d", &ligne); printf("saisir le nbre d...
``` int main(void) { int ligne; int col; printf("saisir le nbre de lignes volous\n"); scanf("%d", &ligne); printf("saisir le nbre de colonnes volous\n"); scanf("%d", &col); int tableSize = ligne * (col*sizeof(int)); int * table = (int*) malloc(tableSize); int i,j; for (i=0 ; i ...
17,604
25,826,977
I am currently taking a GIS programming class. The directions for using GDAL and ogr to manipulate the data is written for a Windows PC. I am currently working on a MAC. I am hoping to get some insight on how to translate the .bat code to a .sh code. Thanks!! Windows .bat code: ``` cd /d c:\data\PhiladelphiaBaseLaye...
2014/09/13
[ "https://Stackoverflow.com/questions/25826977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4038027/" ]
I think it's telling you that the `false` in your code will never be reached, because the `true` causes the first part of the expression to be returned. You can simplify it to: ```dart onClick.listen((e) => fonixMenu.hidden = !fonixMenu.hidden); ```
I think what you actually wanted to do was ```dart void main() { .... var menuToggle =querySelector('#lines') ..onClick.listen((e) => fonixMenu.hidden = fonixMenu.hidden == true ? = false : fonixMenu.hidden = true); // ^ 2nd = .... } ``` but Danny's solut...
17,607
23,827,284
I'm new to programing in languages more suited to the web, but I have programmed in vba for excel. What I would like to do is: 1. pass a list (in python) to a casper.js script. 2. Inside the casperjs script I would like to iterate over the python object (a list of search terms) 3. In the casper script I would like t...
2014/05/23
[ "https://Stackoverflow.com/questions/23827284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3098818/" ]
``` $("#show a").click(function(e) { e.preventDefault(); $("#info, #hide").show(); $("#show").hide(); }); $("#hide a").click(function(e) { e.preventDefault(); $("#info, #hide").hide(); $("#show").show(); }); ```
Use this to show/hide the "Details" div: <http://api.jquery.com/toggle/> Also, you could use just one span to display the "Show/Hide" link, changing the text accordingly when you click to toggle.
17,608
50,709,365
I start with the following tabular data : (let's say tests results by version) ``` Item Result Version 0 TO OK V1 1 T1 NOK V1 2 T2 OK V1 3 T3 NOK V1 4 TO OK V2 5 T1 OK V2 6 T2 NOK V2 7 T3 NOK V2 ``` ``` df=p.DataFrame({'Item'...
2018/06/05
[ "https://Stackoverflow.com/questions/50709365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9899968/" ]
I was having this issue with Cocoapods. The solution was to clean the build folder re-install all pods, and then rebuild the app. The issue resolved itself that way.
In the project pane on the LHS, for your build products, don't select them in the list for Target membership in the RHS pane.
17,615
60,311,148
I'm trying to pip install a package in an AWS Lambda function. The method recommended by Amazon is to create a zipped deployment package that includes the dependencies and python function all together (as described in [AWS Lambda Deployment Package in Python](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python...
2020/02/20
[ "https://Stackoverflow.com/questions/60311148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11918892/" ]
I solved this with a one-line adjustment to the original attempt. You just need to add /tmp/ to sys.path so that Python knows to search /tmp/ for the module. All you need to do is add the line `sys.path.insert(1, '/tmp/')`. **Solution** ``` import os import sys import subprocess # pip install custom package to /tmp/...
For some reason subprocess.call() was returning a FileNotFound error when I was trying to `pip3.8 install <package> -t <install-directory>`. I solved this by using os.system() instead of subprocess.call(), and I specified the path of pip directly: `os.system('/var/lang/bin/pip3.8 install <package> -t <install-director...
17,625
32,779,333
I am trying to start learning about writing encryption algorithms, so while using python I am trying to manipulate data down to a binary level so I can add bits to the end of data as well as manipulate to obscure the data. I am not new to programming I am actually a programmer but I am relatively new to python which i...
2015/09/25
[ "https://Stackoverflow.com/questions/32779333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1779617/" ]
Set the color to UIColor.clearColor()
Use clear color for the scrollView background ``` self.scrollView.backgroundColor = UIColor.clearColor() ``` You don't need to set the background color for the view again once you have set the color with a pattern image. If you set the background color again, the pattern image will be removed.
17,626
64,727,574
I am new to python I am writing code to count the frequency of numbers in a list However I get KeyError. How to automatically check if value does not exist and return a default value. My code is below ``` arr = [1,1,2,3,2,1] freq={} for i in arr: freq[i] += freq[i] + 1 ```
2020/11/07
[ "https://Stackoverflow.com/questions/64727574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14595676/" ]
Yes you can leverage the get method of a dictionary. You can simply do ``` arr=[1,1,2,3,2,1] freq={} for i in arr: freq[i] = freq.get(i,0)+1 ``` Please Google for basic question like this before asking on stackoverflow
You want the dictionary's `get` method.
17,629
12,920,856
I have a text file that consists of million of vectors like this:- ``` V1 V1 V1 V3 V4 V1 V1 ``` Note:- ORDER is important. In the above output file, i counted the first vector 3 times. The same pattern is repeated twice after 5th line. There count should be different. I want to count how many times each vector line...
2012/10/16
[ "https://Stackoverflow.com/questions/12920856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1750896/" ]
If order doesn't matter ======================= If you really want to do this in python (as opposed to the `sort filepath | uniq -c` as Jean suggests), then I would do this: ``` import collections with open('path/to/file') as f: counts = collections.Counter(f) outfile = open('path/to/outfile', 'w') for li...
If it all fits into memory, then you could do: ``` from collections import Counter with open('vectors') as fin: counts = Counter(fin) ``` Or, if large, then you can use sqlite3: ``` import sqlite3 db = sqlite3.conncet('/some/path/some/file.db') db.execute('create table vector (vector)') with open('vectors.txt...
17,631
51,341,157
``` CREATE OR REPLACE FUNCTION CLEAN_STRING(in_str varchar) returns varchar AS $$ def strip_slashes(in_str): while in_str.endswith("\\") or in_str.endswith("/"): in_str = in_str[:-1] in_str = in_str.replace("\\", "/") return in_str clean_str = strip_slashes(in_str) return clean_str $$ LANGUAG...
2018/07/14
[ "https://Stackoverflow.com/questions/51341157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3601228/" ]
Your functions are asynchronous and asynchronous functions need some way of indicating when they are finished. Typically this is done with a callback or promise. Without that there is no way to know when they are finished. If they returned a promise, you might do something like this: ```js var fun1 = function() { c...
**You can add the next function *inside* the `setTimeout` callback.** For example, ```js var fun1=function(){ console.log('Started fun1'); setTimeout(()=>{ console.log('Finished fun1'); fun2(); // Start the next timeout. },2000) } var fun2=function(){ console.log('Started fun2...
17,641
58,484,745
let say that thoses python objects below are **locked** we just cannot change the code, all we can is writing right after it. i know it's aweful. but let say that we are forced to work with this. ``` Name01 = "Dorian" Name02 = "Tom" Name04 = "Jerry" Name03 = "Jessica" #let say that there's 99 of them ``` **How to p...
2019/10/21
[ "https://Stackoverflow.com/questions/58484745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11613897/" ]
This could do the trick: ``` Name01 = "Dorian" Name02 = "Tom" Name04 = "Jerry" Name03 = "Jessica" vars = locals().copy() for i in vars: if 'Name' in i: print((i, eval(i))) ``` alternative in one line: ``` Name01 = "Dorian" Name02 = "Tom" Name04 = "Jerry" Name03 = "Jessica" print([(i, eval(i)) for i in...
You can access the global variables through `globals()` or if you want the local variables with `locals()`. They are stored in a `dict`. So ``` for i in range (1,100): print(locals()[f"Name{i:02d}"]) ``` should do what you want.
17,642
27,627,440
I am trying to use the [python-user-agents](https://github.com/selwin/python-user-agents/blob/master/user_agents/parsers.py). I keep running into a number of bugs within the library itself. First it referred to a `from ua_parser import user_agent_parser` that it never defined. So after banging my head, I looked online...
2014/12/23
[ "https://Stackoverflow.com/questions/27627440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2187407/" ]
if you look at the readme from the github link it tells you what to install and how to use the lib: You need pyyaml and ua-parser: ``` pip install pyyaml ua-parser user-agents ``` A working example: ``` In [1]: from user_agents import parse In [2]: ua_string = 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X...
Actually the new version of ua-parser is incompatible with this so you have to install ua-parser==0.3.6
17,649
21,214,531
Howdy: somewhat of a python/programming newbie. I am trying to find each time a certain word starts a new sentence and replace it, which in this case is good old "Bob", replaced with "John". I am using a dictionary and the `.replace()` method to do the replacing - replacing the dictionary key with the associated value....
2014/01/19
[ "https://Stackoverflow.com/questions/21214531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2680443/" ]
You have to adjust either data you are working with or the algorithm to account for this special case. For example you may decorate the beginning of your data with some value and add corresponding replacement to your dictionary. ``` f_begin_deco = '\0\0\0' # Sequence that won't be in data. start_replacements = { f_...
Question to your question: why don't you want to use regex? ``` >>> import re >>> x = "! Bob is a foo bar" >>> re.sub('^[!?.\\n\\s]*Bob','John', x) 'John is a foo bar' >>> x[:2]+re.sub('^[!?.\\n\\s]*Bob','John', x) '! John is a foo bar' ``` Here's my attempt to do it without regex: ``` >>> x = "! Bob is a foo bar" ...
17,650
61,680,684
I am having trouble with a problem in python. I am making a tic tac toe game, i have created a function that takes in a list of lists containing the state of the game such that [[0,0,0],[0,0,0],[0,0,0]] and output a similar list replacing the 0, 1, 2 by "-", "X", "O" respectively as such - ``` def display_board(b): ...
2020/05/08
[ "https://Stackoverflow.com/questions/61680684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13498818/" ]
I know I'm writing very late, but I hope it helps some other people who are looking for the same thing, it has helped me, especially passing the parameters to the connection to the database, to which the variable is assigned in the where and filter the information that is needed. all from the url: <https://developers....
Expanding on Yeisson's answer. Report parameters are passed via query parameter `params`. Value is URL-encoded JSON object with all report parameters that you want to set. So parameter values such as ```json { "ds0.includeToday": true, "ds0.units": "Metric", "ds1.countries": ["Canada", "Mexico"], "ds1.labelN...
17,653
56,576,400
I wanted to create an mapping between two arrays. But in python, doing this resulted in a mapping with **last element getting picked**. ``` array_1 = [0,0,0,1,2,3] array_2 = [4,4,5,6,8,7] mapping = dict(zip(array_1, array_2)) print(mapping) ``` The mapping resulted in `{0: 5, 1: 6, 2: 8, 3: 7}` How to pick the most...
2019/06/13
[ "https://Stackoverflow.com/questions/56576400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11309609/" ]
You can create a dictionary with key and a list of values for the key. Then you can go over the list of values in this dictionary, and update the value to be the most frequent item in the list using [Counter.most\_common](https://docs.python.org/3/library/collections.html#collections.Counter.most_common) ``` from coll...
You can count frequencies of all mappings using `Counter` and then sort those mappings by key and frequency: ``` from collections import Counter array_1 = [0,0,0,1,2,3] array_2 = [4,4,5,6,8,7] c = Counter(zip(array_1, array_2)) dict(i for i, _ in sorted(c.items(), key=lambda x: (x[0], x[1]), reverse=True)) # {3: 7, 2...
17,654
73,956,255
Hi I am running this python code to reduce multi-line patterns to singletons however, I am doing this on extremely large files of 200,000+ lines. Here is my current code: ``` import sys import re with open('largefile.txt', 'r+') as file: string = file.read() string = re.sub(r"((?:^.*\n)+)(?=\1)", "", string,...
2022/10/05
[ "https://Stackoverflow.com/questions/73956255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20154432/" ]
Regexps are compact here, but will never be speedy. For one reason, you have an inherently line-based problem, but regexps are inherently character-based. The regexp engine has to deduce, over & over & over again, where "lines" are by searching for newline characters, one at a time. For a more fundamental reason, every...
Nesting a quantifier within a quantifier is expensive and in this case unnecessary. You can use the following regex without nesting instead: ``` string = re.sub(r"(^.*\n)(?=\1)", "", string, flags=re.M | re.S) ``` In the following test it more than cuts the time in half compared to your approach: <https://replit.c...
17,655
53,569,407
Is it possible to conditionally replace parts of strings in MySQL? Introduction to a problem: Users in my database stored articles (table called "table", column "value", each row = one article) with wrong links to images. I'd like to repair all of them at once. To do that, I have to replace all of the addresses in "hr...
2018/12/01
[ "https://Stackoverflow.com/questions/53569407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10731133/" ]
``` SELECT regexp_replace( value, '^<a href="([^"]+)"><img class="([^"]+)" src="([^"]+)"(.*)$', '<a href="\\3"><img class="\\2" src="\\3"\\4' ) FROM yourTable ``` The replacement only happens if the pattern is matched. * `^` at the start means `start of the string` * `([^"]+)` means `one of more ch...
Solved, thanks to @MatBailie , but I had to modified his answer. The final query, including the update, is ``` UPDATE `table` SET value = REGEXP_REPLACE(value, '(.*)<a href="([^"]+)"><img class="([^"]+)" src="([^"]+)"(.*)', '\\1<a href="\\4"><img class="\\3" src="\\4"\\5' ``` ) A wildcard (.\*) had to be put at th...
17,660
64,950,799
I am trying to group the indexes of the customers based on the following condition with python. If database contains the same contact number or email, the result should return the indexes of the tuples grouped together in a sub-list. For a given database: ``` data = [ ("Customer1","contactA", "emailA"), ("Customer...
2020/11/22
[ "https://Stackoverflow.com/questions/64950799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14091382/" ]
You could build a graph where you connect elements with a common email or with a common contact and then find [connected components](https://en.wikipedia.org/wiki/Component_(graph_theory)) (e.g., by using a [bfs](https://en.wikipedia.org/wiki/Breadth-first_search) visit). In this case I'm using the [networkx](https:...
You could do this: ``` my_contact_dict = {} my_email_dict = {} my_list = [] for pos, cust in enumerate(data): contact_group = my_contact_dict.get(cust[1], set()) # returns empty set if not in dict email_group = my_email_dict.get(cust[2], set()) # contact_group.add (pos) email_group.add (pos) co...
17,661
27,773,111
I'm new to cocos2d-X.I'm trying to set up cocos2d-x for android and I exactly followed below [video](https://www.youtube.com/watch?v=2LI1IrRp_0w&index=2&list=PLRtjMdoYXLf4od_bOKN3WjAPr7snPXzoe) tutorial I failed the steps in terminal with problem (python setup.py command result is not as expected). For example when I...
2015/01/05
[ "https://Stackoverflow.com/questions/27773111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2219111/" ]
Do you copy the path to the terminal? If so, try to delete the trailing whitespace, it will solve the problem.
Cocos script uses `os.path.join($your_path, $some_extra_file)`, so you have to add slash `/` at the end: > > /Users/apple/Documents/Development/Cosos2d-x/android-ndk-r9d/ > > >
17,663
38,361,916
I am trying to insert the following list of dictionaries named `posts` to mongo, and got a `BulkWriteError: batch op errors occurred` error which I don't know how to fix. `posts:` ``` [{'#AUTHID': 'fffafe151f07a30a0ede2038a897b680', 'Records': [ {'DATE': '07/22/09 05:54 PM', 'STATUS': 'Is flying back friday...
2016/07/13
[ "https://Stackoverflow.com/questions/38361916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6200575/" ]
Not to late to answer here, you almost there. I am not sure if the [FAQ](https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_many) updated but please read it properly: > > when calling `insert_many()` with a list of references to a **single** document raises BulkWri...
[Here is output](http://i.stack.imgur.com/SIZQQ.png) in this output records are store which are in list. ``` from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client['post'] posts = [{'#AUTHID': 'fffafe151f07a30a0ede2038a897b680', 'Records': [ {'DATE': '07/22/09 05:54 PM', ...
17,664
18,388,050
I have a large amount of data of this type: ``` array(14) { ["ap_id"]=> string(5) "22755" ["user_id"]=> string(4) "8872" ["exam_type"]=> string(32) "PV Technical Sales Certification" ["cert_no"]=> string(12) "PVTS081112-2" ["explevel"]=> string(1) "0" ["public_state"]=> ...
2013/08/22
[ "https://Stackoverflow.com/questions/18388050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2646265/" ]
Depending on how the code tags are formatted, you could split the line on `"` then pick out the second element. ``` s = 'string(15) "Ivor Abeysekera"' temp = s.split('"')[1] # temp is 'Ivor Abeysekera' ``` Note that this will get rid of the trailing `"`, if you need it you can always just add it back on. In your exa...
**BAD SOLUTION Based on current question** but to answer your question just use ``` info_string = lines[i + 1] value_str = info_string.split(" ",1)[-1].strip(" \"") ``` **BETTER SOLUTION** do you have access to the php generating that .... if you do just do `echo json_encode($data);` instead of using `var_dump` i...
17,665
64,154,088
I am Python coder and got stuck in a question that "How to check input in textbox of tkinter python". The problem is that it is not giving output on writing this code . ``` def start(event): a = main.get(1.0,END) if a == 'ver': print('.....') main = Text(root) main.pack() root.bind('<Return>',start) ...
2020/10/01
[ "https://Stackoverflow.com/questions/64154088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14225987/" ]
We can do this by `get()` method: ``` from tkinter import * a=Tk() def check(): print(x.get('1.0',END)[:-1]) x=Text(a) b=Button(a,text='Check',command=check) x.pack() b.pack() a.mainloop() ```
You should write something like ``` def start(event): t = var.get() if t == 'something': pass var = StringVar() e = Entry(master, textvariable=var) e.pack() e.bind(bind('<Return>',start) ```
17,671
52,113,890
I needed to extend User model to add things like address, score, more user\_types, etc. There are 2 possible ways to achieve that, extend the User model or create a new model that will be connected with the target User with `OneToOneField`. I decided to go with a new model because It seemed easier and It is recommended...
2018/08/31
[ "https://Stackoverflow.com/questions/52113890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4981456/" ]
Take it easy, You can create Profile obj just in the create function. ``` class UserSerializer(serializers.ModelSerializer): trusted = serializers.BooleanField() address = serializers.CharField() class Meta: model = User fields = ('username', 'email', 'password', 'trusted', 'address',) ...
Plase read documentation for Serializers: [Django REST FRAMEWORK](http://www.django-rest-framework.org/api-guide/relations/) -- user related\_name ``` user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile") # models class ProfileSerializer(serializers.ModelSerializer): user = ser...
17,674
27,701,573
I got error message: *{DetachedInstanceError} Parent instance is not bound to a session; lazy load operation of attribute 'owner' cannot proceed* My python code: ``` car_obj = my_query_function() # get a Car object owner_name = car_obj.owner.name # here generate error! ``` My model: ``` class Person(EntityClass):...
2014/12/30
[ "https://Stackoverflow.com/questions/27701573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3778914/" ]
I traced the docs and made it work by adding `lazy='subquery'` ``` owner = relationship('Person', lazy='subquery', cascade='all, delete-orphan', backref=backref('car', cascade='delete'), single_parent=True) ``` <http://docs.sqlalchemy.org/en/rel_0_9/orm/join_conditions.html>
Made it work by adding `joinedload_all()` in `session.query(Car).options()`, for example: ``` cars = session.query(Car).options(joinedload_all('*')).all() session.close() for car in cars: "do your struff" ``` good luck
17,675
29,956,181
I am a newbie in this field, and I am trying to solve a problem (not really sure if it is possible actually) where I want to print on the display some information plus some input from the user. The following works fine: ``` >>> print (" Hello " + input("tellmeyourname: ")) tellmeyourname: dfsdf Hello dfsdf ``` How...
2015/04/29
[ "https://Stackoverflow.com/questions/29956181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4848506/" ]
Starting from Python 3.8, this will become possible using an [assignment expression](https://www.python.org/dev/peps/pep-0572/): ``` print("Your name is: " + (name := input("Tell me your name: "))) print("Your name is still: " + name) ``` Though 'possible' is not the same as 'advisable'... --- But in Python <3.8: ...
**no this is not possible**. well except something like ``` x=input("tell me:");print("blah %s"%(x,)); ``` but thats not really one line ... it just looks like it
17,676
34,300,908
I've been creating an webapp (just for learning purposes) using python django, and have no intention in deploying it. However, is there a way to let someone else, try the webapplication, or more precisely: Is it possible to somehow test the webapp on another computer. I tried to send det source code (and the whole fold...
2015/12/15
[ "https://Stackoverflow.com/questions/34300908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3799968/" ]
You can use ngrok -- <https://ngrok.com/> -- to create a public URL to your local server for testing, and then give that URL to people so they can try your webapp.
You can also use [Localtunnel](https://localtunnel.me) to easily share a web service on your local development without deploying the code in the server. Install the localtunnel ``` npm install -g localtunnel ``` Start a webserver on some local port (eg <http://localhost:8000>) and use the command line interface to...
17,677
56,364,756
My log files have some multiline bytestring in them, like [2019-05-25 19:16:31] b'logstring\r\n\r\nmore log' After I try to extract the original multiline string, how do I convert that to a real string using Python 3? As a simplified example, after reading the log file and stripping the time, I end up with a variabl...
2019/05/29
[ "https://Stackoverflow.com/questions/56364756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2335020/" ]
You can use regex: ``` import re tmp = "b'logstring\r\n\r\nmore log'" r = re.compile(r"b'(.+)'", re.DOTALL|re.MULTILINE) result = r.sub(r"\1", tmp) print(result) # logstring\r\n\r\nmore log ``` You could use this for the entire file or line by line but you may need to slightly change this code to meet your needs. ...
It seems that you can lock down the eval function so that it can't run functions and python builtins. You do this by passing a dictionary of allowed global and local functions. By mapping all builtins to None you can block the execution of regular python commands. With that in place, using eval to evaluate the string c...
17,678
6,467,407
I'm using Jython from within Java; so I have a Java setup similar to below: ``` String scriptname="com/blah/myscript.py" PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState()); InputStream is = this.getClass().getClassLoader().getResourceAsStream(scriptname); interpreter.execfile(is); ``` A...
2011/06/24
[ "https://Stackoverflow.com/questions/6467407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184456/" ]
I'm using Jython 2.5.2 and `runScript` didn't exist, so I had to replace it with `execfile`. Aside from that difference, I also needed to set `argv` in the state object before creating the `PythonInterpreter` object: ``` String scriptname = "myscript.py"; PySystemState state = new PySystemState(); state.argv.append (...
For those people whom the above solution does not work, try the below. This works for me on jython version 2.7.0 ``` String[] params = {"get_AD_accounts.py","-server", "http://xxxxx:8080","-verbose", "-logLevel", "CRITICAL"}; ``` The above replicates the command below. i.e. each argument and its value is separate el...
17,679
16,640,624
I am outputting ``` parec -d "name" ``` You don't need to know this command, just know that as soon as you press enter, it outputs binary data representing audio. My goal is to read this with python in real time, ie start it and have it in a variable "data" I can read from with something like ``` data = p.stdout...
2013/05/19
[ "https://Stackoverflow.com/questions/16640624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2348735/" ]
There are multiple problems and they are not simple (unless the version of the ascensor script is outdated). The first issue is fairly simple, and illustrates the initial problem - some of the documentation doesn't match the code. In particular, the case doesn't match. For example, you have `childType: 'section'` (low...
The reverse of the current answer is now true. Using the latest version of Ascensor (1.8.0 (2014-02-23)), you have to specify the property names in lower case. e.g. change `ChildType: 'section'` to `childType: 'section'`. The examples all around the net are unfortunately using older versions.
17,680
57,361,849
I'm doing some dockerized code in Python (3.5) and flask (1.1.1) working against a CouchDB database (2.3.1) using the cloudant python extension (2.12.0) which seems to be the most up to date library to work against CouchDB. I'm trying to fetch and use a view from the database, but it is not working. I can fetch docume...
2019/08/05
[ "https://Stackoverflow.com/questions/57361849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6879212/" ]
I'm answering my own question, in case someone in the future stumbles upon this. I got the answer from Esteban Laver in the github for python-cloudant and it is what @chrisinmtown mentions in a response up there. I was failing to call fetch() on the design document before using it. Another good suggestion was to use ...
I believe the code posted above creates a new DesignDocument object, and does not search for an existing DesignDocument. After creating that object, it looks like you need to call its fetch() method and **then** check its views property. HTH. p.s. promoting my comment to an answer, hope that's cool in SO land these da...
17,681
6,539,472
I'm reading the book *Introduction to Computer Science Using Python and Pygame* by Paul Craven (note: legally available for free online). In the book, he uses a combination of Python 3.1.3 and Pygame 1.9.1 . In my Linux Ubuntu machine, I have Python 3.1.2 but even after I sudo apt-get installed python-pygame (version 1...
2011/06/30
[ "https://Stackoverflow.com/questions/6539472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/777225/" ]
I hate to re-open an old post, but I had the hardest time installing pygame with a version of python that was not Ubuntu's default build. So I created this tutorial/ how to: [Install python3.1 and pygame1.9.1 in Ubuntu](https://sites.google.com/site/cslappe1/knowledge-base-and-how-to-s/installpython31andpygame191inubu...
Just use the below command to install pygame for Python3. I could install pygame correctly on Ubuntu 16.04 and Python Python 3.5.2. pip3 install pygame
17,682
42,349,191
This is a typical use case for FEM/FVM equation systems, so is perhaps of broader interest. From a triangular mesh à la [![enter image description here](https://i.stack.imgur.com/RS6MJ.png)](https://i.stack.imgur.com/RS6MJ.png) I would like to create a `scipy.sparse.csr_matrix`. The matrix rows/columns represent valu...
2017/02/20
[ "https://Stackoverflow.com/questions/42349191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/353337/" ]
I would try creating the csr structure directly, especially if you are resorting to `np.unique` since this gives you sorted keys, which is half the job done. I'm assuming you are at the point where you have `i, j` sorted lexicographically and overlapping `v` summed using `np.add.at` on the optional `inverse` output of...
So, in the end this turned out to be the difference between COO's and CSR's `sum_duplicates` (just like @hpaulj suspected). Thanks to the efforts of everyone involved here (particularly @paul-panzer), [a PR](https://github.com/scipy/scipy/pull/7078) is underway to give `tocsr` a tremendous speedup. SciPy's `tocsr` doe...
17,692
69,276,976
I've tried to way I was instructed and moved the code in csv I was given into the same folder as my Jupyter Notebook is located. It still isn't reading it. I'm also trying to convert it into a dataframe and get it to 'describe'. I'll post the code and the errors below. Please help! Thank you in advance! ``` import pan...
2021/09/22
[ "https://Stackoverflow.com/questions/69276976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Deno does not currently support "classic" workers. 1. From [Worker() - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker): > > `type`: A [`DOMString`](https://developer.mozilla.org/en-US/docs/Web/API/DOMString) specifying the type of worker to create. The value can be `classic` or `modul...
The information provided in [mfulton26's answer](https://stackoverflow.com/a/69292184/438273) is right, but you don't need a data URL: you simply need to add `{ type: "module" }` to your worker instantiation options. Deno even supports TypeScript as the source for your worker: `blob-worker.ts`: ```ts const workerModu...
17,693
56,452,581
I've almost the same problem like this one: [How to make a continuous alphabetic list python (from a-z then from aa, ab, ac etc)](https://stackoverflow.com/questions/29351492/how-to-make-a-continuous-alphabetic-list-python-from-a-z-then-from-aa-ab-ac-e) But, I am doing a list in gui like excel, where on the vertical h...
2019/06/04
[ "https://Stackoverflow.com/questions/56452581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11329096/" ]
Another alternative, if you want to dive deeper (create up to ~18,000 columns): ``` from string import ascii_lowercase letters = list(ascii_lowercase) num_cols = 100 excel_cols = [] for i in range(0, num_cols - 1): n = i//26 m = n//26 i-=n*26 n-=m*26 col = letters[m-1]+letters[n-1]+letters[i] if ...
Try this code. It works by pretending that all Excel column names have two characters, but the first "character" may be the null string. I get the `product` to accept the null string as a "character" by using a list of characters rather than a string. ``` from string import ascii_lowercase import itertools first_char...
17,694
64,834,395
i use linux nodejs had no problem untill i upgraded my system (sudo apt upgrade) now when i try to install nodejs it say python-minimal mot installed then i knew that it casue of updating python from python2.7.17 to python2.7.18 and python minimal is no longer require ,but now i cant install nodejs cause it ask for pyt...
2020/11/14
[ "https://Stackoverflow.com/questions/64834395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14535629/" ]
jq does not have an `eval` function for evaluating arbitrary jq expressions, but it does provide functions that can be used to achieve much the same effect, the key idea being that certain JSON values can be used to specify query operations. In your case, you would have to translate the jq query into a suitable jq ope...
**TLDR;** The following code does the job: ``` $ a=".[].Header.Tenant"; jq -f <(echo "[$a]") test.json [ "Tenant1", "Tenant2" ] ``` One as well can add/modify the filter in the jq call, if needed: ``` $ a=".[].Header.Tenant"; jq -f <(echo "[$a]|length") test.json 2 ``` **Longer explanation** My ultimate ...
17,696
61,081,016
After following the official RTD installation tutorial for ubuntu18 I manage to do everything (even webhooks) until the point of building, for a project called **test**, where I get the following error: > > python3.6 -mvirtualenv /home/myuser/readthedocs.org/user\_builds/test/envs/latest > > > Followed by: > > ...
2020/04/07
[ "https://Stackoverflow.com/questions/61081016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2236386/" ]
Your running job #3 has only 4 tasks (screenshot #2), thats why you see 4 executors. Spark doesn't need 6 executors to complete 4 tasks. Each executor (screenshot #3) has 5 cores and what looks like 14GB memory ((14GB -300MB) \* 0.6 ~ 7.8GB). See [Spark memory management](https://spark.apache.org/docs/latest/configur...
You have only 2 nodes with 16 vCores each, in total of 32 vCores, which you can very well see in your Yarn UI. Now when you are submitting your job you are requesting Yarn to create 6 containers(executors) with 5 vCores each but then on a single node you can have at max of 2 executors considering 5 cores requirement (...
17,697
21,579,459
I am just starting on Python from a PHP background. I was wondering if there is a more elegant way in assigning a variable the result of an "if ... in" statement? I currently do ``` is_holiday = False if now_date in holidays: is_holiday = True ``` To me it looks like an unnecessary amount of code line or is thi...
2014/02/05
[ "https://Stackoverflow.com/questions/21579459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/912588/" ]
``` is_holiday = now_date in holidays ```
Use [Conditional expressions](http://docs.python.org/2/reference/expressions.html#conditional-expressions): `is_holiday = True if now_date in holidays else False` or just `is_holiday = now_date in holidays`.
17,698
17,502,704
I am trying to use the tempfile module. (<http://docs.python.org/2.7/library/tempfile.html>) I am looking for a temporary file that I could open several times to get several streams to read it. ``` tmp = ... stream1 = # get a stream for the temp file stream2 = # get another stream for the temp file ``` I have tried ...
2013/07/06
[ "https://Stackoverflow.com/questions/17502704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1232891/" ]
File objects (be they temporary or otherwise) cannot be read multiple times without re-positioning the file position back to the start. Your options are: * To reopen the file multiple times, creating multiple file objects for the same file. * To rewind the file object before each read. To reopen the file, use a `Nam...
You could use [`tempfile.mkstemp()`](http://docs.python.org/2.7/library/tempfile.html#tempfile.mkstemp). From the documentation: > > Creates a temporary file in the most secure manner possible. There are no race conditions in the file’s creation, assuming that the platform properly implements the os.O\_EXCL flag for ...
17,699
3,186,526
In debian recently change de default version of python from 2.5 to 2.6 but i need 2.5, how i can configure apache and/or wsgi script to say it use pythons2.5 and not python default?
2010/07/06
[ "https://Stackoverflow.com/questions/3186526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150647/" ]
``` <input type="submit" onclick="this.disabled = true" value="Save"/> ``` or ref [this](https://stackoverflow.com/questions/2545641/how-to-submit-form-only-once-after-multiple-clicking-on-submit)
Using **jQuery**, add onClick handler that returns false: ``` <input type="submit" value="Submit" onClick="$(this).click(function() {return false;});"/> ```
17,700
2,335,762
I want to parse a css file and multiply each pixel value by (2/3). I was wondering if this was possible with sed? I know this is incorrect syntax but i think it'll bring home the explanation of what i want to achieve: ``` sed -e "s|\([0-9]*\)px|int((\1 * 2)/3)|g" file.css ``` So basically I want to take \1, multiply...
2010/02/25
[ "https://Stackoverflow.com/questions/2335762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281403/" ]
use awk ``` $ cat file foo: 3px; bar: 6px $ awk '{for(i=1;i<=NF;i++){if($i~/^[0-9]+px/){o=$i;sub(/^[0-9]+/,"",o);$i=($i+0)*(2/3)o}}}1' file foo: 2px; bar: 4px ```
You can use perl do it like this: ``` echo -e "100px;\n20px;" | perl -pe 's{ (\d*) (?=px) }{ $1*(2/3) }xe' ```
17,710
70,581,125
I am to write a program by taking two integers as input and output their sum on Sololearn using python But I don’t seem to get what they want me to do
2022/01/04
[ "https://Stackoverflow.com/questions/70581125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17833033/" ]
``` num1 = int(input('Enter your first number: ')) num2 = int(input('Enter your second number: ')) print('Your sum is', num1 + num2) ``` I would suggest doing more research on the `input` function in python. Also, in the future, please provide the code that you have already written so that it is easier to answer your...
Try with ```py a = int(input("A: ")) # Convert input string to int b = int(input("B: ")) print("A + B =", a+b) ```
17,715
12,960,522
I am trying to create an enumeration in python. I have seen seen several solutions (The second answer [here](https://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python) by @alec thomas intrigued me most), but I would like to make the enumeration immutable. I found a [python recipe](http...
2012/10/18
[ "https://Stackoverflow.com/questions/12960522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1255482/" ]
Your immediate problem is that the `getter` of a `property` takes `self` as the only parameter, not `attr`. Therefore, you should use something like `lambda self: val` instead. However, that doesn't work because the `lambda` binds the *name* `val`, which changes from iteration to iteration. So you will need to wrap it...
The final implementation (thanks to @nneonneo). * Checks for duplicate enum keys * Checks if enum is empty * Does not allow deletion or modification of enum items ``` def enum(*sequential, **named): # Check for duplicate keys names = list(sequential) names.extend(named.keys()) if len(set(names)) != le...
17,717
63,790,601
``` # Read an integer: a = input() #Now swap it... a[0] = a[1] a[1] = a[0] ``` As you can see I am trying to change the value and trying to swap it.. ``` print(a) ``` ...and then i print it out. But I am getting an error which is as follows: ``` Traceback (most recent call last): File "python", line 4, in <modu...
2020/09/08
[ "https://Stackoverflow.com/questions/63790601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14235043/" ]
Try this: ``` a = input() a = str(a) result = int(a[-1: : -1]) print(result) ``` Output: ( a = 34 ) ``` 43 ```
Based on your question simple thing you can do. As above comment string is not iterable while you as input. You need to convert to `list` to access by index. For swap you need to use temporary variable, so i used `temp` as variable to swap. ``` a = list(input()) #Now swap it... print(a) temp = a[0] a[0] = a[1] a[1] ...
17,718
48,272,939
In advance, thank you for looking at my issue community, My python test script will not execute from my Centos 7 Crontab. This script will execute manually if called either in the containing directory or from the root/any other directory with a full path. My Centos Python location is `/bin/python`. This is included at...
2018/01/16
[ "https://Stackoverflow.com/questions/48272939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6820299/" ]
I had the same problem. Pulling images was working but provisioning a container was not working. In this case the solution was to provide Docker with a configuration file named `~/.docker/config.json` with the following contents. ``` { "proxies": { "default": { "httpProxy": "http://proxy.server....com:808...
I struggled making it work but finally found a working solution on my side. I'm behind a corporate proxy and have a CNTLM properly configured on windows and linked in my docker desktop settings with address `127.0.0.1:3128`. My docker runs under WSL2. The magic tip hereis to link your containers proxies to docker int...
17,719
33,981,803
Lets say I am trying to get the number of different peoples names. user inputs names until they enter a -1, once -1 is entered then loop will break Once entered then i am trying to tabulate the output something likes this names : John Max Joan No of occurrences : 4 1 2 % of occurences : 20% 10% 30% ``` #!/usr/bin/...
2015/11/29
[ "https://Stackoverflow.com/questions/33981803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5466007/" ]
You can use [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter) to count and accumulate the occurrences of names in the given input: ``` counter = collections.Counter() names = ["John", "Max", "Joan"] while True: lst = raw_input("What is your name?") if lst == "-1":...
Counting word frequency in a multi-word string: ``` import sys from collections import defaultdict WORDS = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip...
17,720
45,176,779
I have a python object that looks like this. I am trying to parse this object and turn it to a human readable string which I need to put in the logs. How can I recursively loop through this considering the object could be nested dictionaries or nested lists or dictionaries inside lists inside dictionaries etc. ``` {"...
2017/07/18
[ "https://Stackoverflow.com/questions/45176779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7044618/" ]
The formatting might be a bit off ``` def humanizer(input, result=''): if type(input) == dict: for k, v in input.items(): if type(v) == str: result += '%s:%s\n\t' % (str(k), str(v)) elif type(v) in (dict, list): result += '%s:\n\t' % str(k) ...
Maybe the output of [pformat](https://docs.python.org/3/library/pprint.html#pprint.pformat "pformat") would suit you: ``` from pprint import pformat results_str = pformat(results) ```
17,721
10,226,551
I have a list of floating point numbers and I want to generate another list of period returns from my first list. This is a run of the mill implementation (not tested - and OBVIOUSLY no error checking/handling): ``` a = [100,105,100,95,100] def calc_period_returns(values, period): output = [] startpos, endpo...
2012/04/19
[ "https://Stackoverflow.com/questions/10226551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962891/" ]
Here you go: ``` >>> [100.0 * a1 / a2 - 100 for a1, a2 in zip(a[1:], a)] [5.0, -4.7619047619047592, -5.0, 5.2631578947368354] ``` Since you want to compare neighbor elements of a list, you better create a list of pairs you are interested in, like this: ``` >>> a = range(5) >>> a [0, 1, 2, 3, 4] >>> zip(a, a[1:]) [(...
I don't know how large your list of numbers is going to be, but if you are going to process large amounts of numbers, you should have a look at numpy. The side effect is that calculations look a lot simpler. With numpy, you create an array for your data ``` >>> import numpy as np >>> a = np.array([100,105,100,95,100]...
17,724
17,239,077
Im trying to learn python and started with this, I keep getting a syntax error when i try to run it. the cursor jumps to the end of the close " at def start section. Im not sure where the syntax error is coming from as i speech mark all the print ``` #! python3 # J Presents: Rock, paper, Scissors: The Video Game imp...
2013/06/21
[ "https://Stackoverflow.com/questions/17239077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2401529/" ]
1) You have an indentation error here : ``` try: player = int(player) if player in (1,2,3): return player except ValueError: #Try Except Block Statement pass Print "Oops! I didn't understand that. Please enter 1, 2 or 3." ``` --- 2) Also : ``` if rule...
``` if rules[player} == computer: ``` The curly brace should be a bracket.
17,730
39,194,747
I'm coding some python files with sublime and I'd like to comment multiple selected lines which means putting the character '#' at the beginning of each selected line. Is it possible to create a such shortcut-key Binding on sublime to do that ? Thanks Vincent
2016/08/28
[ "https://Stackoverflow.com/questions/39194747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6767684/" ]
There are a few ways to do this. Primarily, *two*: (1) Use the CPU/processor stack. There are some variants, each with its own limitations. (2) Or, recode your function(s) to use a "stack frame" struct that simulates a "stack". The actual function ceases to be recursive. This can be virtually limitless up to whateve...
All of functions, objects, variable and user defined structures use memory spaces which is control by OS and compiler. So, it means your defined stack works under a general memory space which is specified for the stack of your process in OS. As a result, it does not have a big difference, but you can define an optimize...
17,732
71,561,891
![This is what I want](https://i.stack.imgur.com/lexMT.png "example of what I want")How to make R side by side two column histogram (above) which I am able to do in python ([image taken from here](https://stackoverflow.com/questions/6871201/plot-two-histograms-on-single-chart-with-matplotlib)) and all the answers I hav...
2022/03/21
[ "https://Stackoverflow.com/questions/71561891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18295411/" ]
We remove the `NA` with `na.omit` and get the `first` element - use `[1]` to coerce to `NA` if there are no non-NA elements present ``` library(dplyr) test %>% group_by(name) %>% summarise(across(everything(), ~ first(na.omit(.x))[1])) ``` -output ``` # A tibble: 2 × 4 name test_1 test_2 make_up_test <ch...
Here is an approach with pivoting: ``` library(tidyr) library(dplyr) test %>% pivot_longer(-name, names_to = "names") %>% drop_na() %>% pivot_wider(names_from = names, values_from = value) %>% relocate(test_2, .after = test_1) ``` ``` name test_1 test_2 make_up_test <chr> <dbl> <dbl> <dbl...
17,733
22,358,540
I know how to read bits inside an int in Python but not how to do so on a char. For an int, this elementary operation works: a & (2\*\*bit\_index) . But for a single character it gives the following error message: `unsupported operand type(s) for &: 'str' and 'int'` In case, this "subtlety' matters, I'm also reading m...
2014/03/12
[ "https://Stackoverflow.com/questions/22358540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3275464/" ]
You can use a `bytearray` instead of a string. The individual elements are integers, but you can still do basic string manipulation on the whole: ``` >>> arr = bytearray('foo') >>> type(arr[0]) <type 'int'> >>> arr.replace('o', 'u') bytearray(b'fuu') ```
Python doesn't really have char type. You have a string of length one. You need to convert it to int before you can apply those operators in it. Depending on what is in `my_string` this might work: `int(my_char, 10)`
17,734
50,182,833
I am running a Flask app on Google Cloud App Engine (flex). Running it locally works just fine, but once it deploys I get a `502 Bad Gateway error (nginx)`. Now I would like to figure out what causes this, but I am not able to find any option to view the console logs that my app creates. Since it works just fine on m...
2018/05/04
[ "https://Stackoverflow.com/questions/50182833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6341510/" ]
Had the similar issue. Found that app engine looks for app variable in main.py file. My final app.yaml looks like below. app.yaml -------- ``` runtime: python env: flex entrypoint: gunicorn -b :$PORT main:app runtime_config: python_version: 3 ``` and had requirements.txt, which looks like below. requirements.t...
Here are my theories: * localhost (`127.0.0.1`) is being used; should use `0.0.0.0` * Flask internal WSGI server is being used; should use e.g. [Gunicorn](https://gunicorn.org/) **NB** You **may** develop and test these solutions using Cloud Shell. Cloud Shell (now) includes a [web preview](https://cloud.google.com/s...
17,739
17,029,752
I am scraping 23770 webpages with a pretty simple web scraper using `scrapy`. I am quite new to scrapy and even python, but managed to write a spider that does the job. It is, however, really slow (it takes approx. 28 hours to crawl the 23770 pages). I have looked on the `scrapy` webpage and the mailing lists and `sta...
2013/06/10
[ "https://Stackoverflow.com/questions/17029752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2183630/" ]
Here's a collection of things to try: * use latest scrapy version (if not using already) * check if non-standard middlewares are used * try to increase `CONCURRENT_REQUESTS_PER_DOMAIN`, `CONCURRENT_REQUESTS` settings ([docs](http://doc.scrapy.org/en/latest/topics/settings.html#concurrent-requests)) * turn off logging ...
Looking at your code, I'd say most of that time is spent in network requests rather than processing the responses. All of the tips @alecxe provides in his answer apply, but I'd suggest the `HTTPCACHE_ENABLED` setting, since it caches the requests and avoids doing it a second time. It would help on following crawls and ...
17,740
29,449,659
I have a server application written in python/django (REST api) for accepting a file upload from the client application. I want this uploaded file to be stored in AWS S3. I also want the file to be uploaded from client as multipart form / data . How can i achieve this. Any sample code application will help me to unders...
2015/04/04
[ "https://Stackoverflow.com/questions/29449659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/780805/" ]
If you want to your uploads to go directly to AWS S3, you can use `django-storages` and set your Django file storage backend to use AWS S3. * [django-storages](https://bitbucket.org/david/django-storages) * [django-storages documentation](http://django-storages.readthedocs.org/en/latest/index.html) This will allow yo...
Take a look at `boto` package which provides AWS APIs: ``` from boto.s3.connection import S3Connection s3 = S3Connection(access_key, secret_key) b = s3.get_bucket('<bucket>') mp = b.initiate_multipart_upload('<object>') for i in range(1, <parts>+1): io = <receive-image-part> # E.g. StringIO mp.upload_part_fr...
17,745
48,364,573
New to python and deep learning. I was trying to build an RNN with some data and I don't know where am I going wrong. This is my code: ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline raw = pd.read_excel('Online Retail.xlsx',index_col='InvoiceDate') sales = raw.drop(['Inv...
2018/01/21
[ "https://Stackoverflow.com/questions/48364573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8766071/" ]
I'm not sure where the number `26` came from, but it doesn't match with your data dimensions. After you dropped four columns, the `training_data` array is `(50000, 3)`, of which you take `(11, 3)` batches. This array obviously can't reshape to `(26, 11)`. What you probably meant is this (in `next_batch` function): ``...
The error says that you trying to reshape a tensor with size `33` into a tensor with size `26x11`, which you can't. You should reshape a tensor with size `286` into `26x11`. Try to debug the `next_batch` function by printing the `y_batch` shape in each step using `print (y_batch.get_shape())` and check it, if it has s...
17,746
7,008,175
I wrote such a code to get timezone based on DST for an specific epoch time: ``` def getTimeZoneFromEpoch(epoch) if time.daylight and time.gmtime(epoch).tm_isdst==1: return -time.altzone/3600.0 else: return -time.timezone/3600.0 ``` But i'm not sure its correct, in fact at the moment i mistak...
2011/08/10
[ "https://Stackoverflow.com/questions/7008175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/495838/" ]
I've tested this code to obtain the VM's locale UTC offset. Which, by the way, is only really valid at the moment it is measured. I'm not sure whether your code is equivalent or not. ``` def local_ephemeral_UTC_offset(epoch_time=None): u"Returns a datetime.timedelta object representing the local time offset from UTC...
In short, use `time.localtime()` instead of `time.gmtime()`. --- The problem is that you use `gmtime()` , as the result of the following program shows. ``` from time import * def getTimeZoneFromEpoch(epoch): if daylight and gmtime(epoch).tm_isdst==1: return -altzone/3600.0 else: return -time...
17,747
30,540,825
I have an OS X system where I need to install a module for python 2.6. Both `pip` and `easy_install-2.6` are failing: ``` # /usr/bin/easy_install-2.6 pip Searching for pip Reading http://pypi.python.org/simple/pip/ Download error: unknown url type: https -- Some packages may not be found! Couldn't find index page for ...
2015/05/30
[ "https://Stackoverflow.com/questions/30540825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4146877/" ]
Download the source file [here](https://pypi.python.org/packages/source/p/pip/pip-7.0.1.tar.gz#md5=5627bb807cf3d898a2eba276685537aa). Then do ``` >> cd ~/Downloads >> tar -xzvf pip-7.0.1.tar.gz ``` (replacing `~/Downloads` if necessary). Then ``` >> cd pip-7.0.1 >> sudo python2.6 setup.py install >> cd ``` (the...
By default [Homebrew](http://brew.sh/) provides `pip` command via: `brew install python`. So try installing Python using Homebrew. Try to not use `sudo` when working with `brew`. To verify which files are installed with your Python package, try: ``` $ brew list python /usr/local/Cellar/python/2.7.9/bin/pip /usr/loca...
17,750
70,714,374
How to loop multi-variable data like this in python ? I have latitude and longitude data and I want to pass all these value and run it for 5 times. e.g. **round 1** lat = 13.29 , longitude = 100.34 city = 'ABC' **round 2** lat = 94.09834 ,longitude = 103.34 city = 'XYZ' ,... ,.. ,round 5 Very new to pytho...
2022/01/14
[ "https://Stackoverflow.com/questions/70714374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17859678/" ]
I was getting permission issues because I was running SLES based docker container inside CentOS based host machine. If I use SLES based host machine, I could run the container without any permission issue.
in my case I fixed it by upgrading docker to latest version. [reference link.](https://travis-ci.community/t/unable-to-access-file-structure-of-docker-container-when-running-in-travis/11229)
17,751
28,848,098
I'm trying to make a recursive function that finds all the combinations of a python list. I want to input ['a','b','c'] in my function and as the function runs I want the trace to look like this: ```none ['a','b','c'] ['['a','a'],['b','a'],['c','a']] ['['a','a','b'],['b','a','b'],['c','a','b']] ...
2015/03/04
[ "https://Stackoverflow.com/questions/28848098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1995933/" ]
The right answer is that you should use `itertools.combinations`. But if for some reason you don't want to, and want to write a recursive function, you can use the following piece of code. It is an adaptation of the erlang way of generating combinations, so it may seem a bit weird at first: ``` def combinations(N, it...
Seems that you want all the product of a list, you can use [`itertools.product`](https://docs.python.org/2/library/itertools.html#itertools.product) within the following function to return a list of generators: ``` >>> from itertools import product >>> def pro(li): ... return [product(l,repeat=i) for i in range(...
17,752
11,372,033
I'm getting an error when testing a python script which is installed on my Android Emulator running SDK 2.2 I have installed "Python\_for\_android\_r1.apk" and "sl4a\_r5.apk" in my emulator. It seems that my code is trying to import the following: ``` from urllib import urlencode from urllib2 import urlopen ``` And...
2012/07/07
[ "https://Stackoverflow.com/questions/11372033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/953507/" ]
Your urllib module seems to be found. If the module is not found, python will return you an error at the import. Looking at the error, it appears that you are having problems with urlopen. Is the url you are trying to open valid? Line 124 in urllib2 refers to the opener that you are using to get your response.
`A;tanaStudio3Workspace` this is weird. You have no problem with your import module but the path look really wrong. I could assume if you fix the path, it will be alright but for further investigation you need to provide a real traceback.
17,753
14,163,429
Original: I have recently started getting MySQL OperationalErrors from some of my old code and cannot seem to trace back the problem. Since it was working before, I thought it may have been a software update that broke something. I am using python 2.7 with django runfcgi with nginx. Here is my original code: **views.p...
2013/01/04
[ "https://Stackoverflow.com/questions/14163429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/516476/" ]
Sometimes if you see "OperationalError: (2006, 'MySQL server has gone away')", it is because you are issuing a query that is too large. This can happen, for instance, if you're storing your sessions in MySQL, and you're trying to put something really big in the session. To fix the problem, you need to increase the valu...
SQLAlchemy now has a great write-up on how you can use pinging to be pessimistic about your connection's freshness: <http://docs.sqlalchemy.org/en/latest/core/pooling.html#disconnect-handling-pessimistic> From there, ``` from sqlalchemy import exc from sqlalchemy import event from sqlalchemy.pool import Pool @event...
17,754
7,629,753
I have been doing a lot of studying of the BaseHTTPServer and found that its not that good for multiple requests. I went through this article <http://metachris.org/2011/01/scaling-python-servers-with-worker-processes-and-socket-duplication/#python> and I wanted to know what is the best way for building a HTTP Server f...
2011/10/02
[ "https://Stackoverflow.com/questions/7629753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558397/" ]
I have had very good luck with the CherryPy web server, one of the oldest and most solid of the pure-Python web servers. Just write your application as a WSGI callable and it should be easy to run under CherryPy's multi-threaded server. <http://www.cherrypy.org/>
Indeed, the the HTTP servers provided with the standard python library are meant only for light duty use; For moderate scaling (100's of concurrent connections), `mod_wsgi` in apache is a great choice. If your needs are greater than that(10,000's of concurrent connections), You'll want to look at an asynchronous fram...
17,764
18,267,454
The sql expression : ```sql select * from order where status=0 and adddate(created_time, interval 1 day)>now(); ``` python code: ```python from sqlalchemy.sql.expression import func, text from datetime import datetime closed_orders = DBSession.query(Order).filter(func.dateadd(Order.create_time, t...
2013/08/16
[ "https://Stackoverflow.com/questions/18267454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2688431/" ]
Try this: ``` from sqlalchemy import func import datetime DBSession.query(Order)\ .filter(func.ADDDATE(Order.create_time,1)>datetime.datetime.now()) ```
presto: ``` extract('hour', cast(t_table.open_time,TIMESTAMP)) - 5 == 12 extract('dow', cast(cast(t_table.open_time, TIMESTAMP) - 5,TIMESTAMP)) == 3 ```
17,766
10,618,956
I want to implement a symbol type, which keeps track of the symbols we already have(saved in `_sym_table`), and return them if they exist, or create new ones otherwise. The code: ``` # -*- coding: utf-8 -*- _sym_table = {} class Symbol(object): def __new__(cls, sym): if sym not in _sym_table: ...
2012/05/16
[ "https://Stackoverflow.com/questions/10618956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/403367/" ]
one problem is that `deepcopy` and `copy` have no way of knowing which arguments to pass to `__new__`, therefore they only work with classes that don't require constructor arguments. the reason why you can have `__init__` arguments is that `__init__` isn't called when copying an object, but `__new__` must be called to...
Seems to me you want the Symbol instances to be singletons. Deepcopy, however is supposed to be used when you want an exact copy of an instance, i.e. a different instance that is equal to the original. So the usage here kinda contradicts the purpose of deepcopy. If you want to make it work anyhow, you can define the [...
17,767
70,351,208
I am trying to fit some `experimental data (x and y)` with a `custom function (Srt)` and using `scipy.optimize.curve_fit()`: Reading the data and defining the function, using dummy values (10,10) for Km and Vmax (which are to be determined using the curve fit) works fine, as long as I use `np.asarray()`: ``` from sci...
2021/12/14
[ "https://Stackoverflow.com/questions/70351208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5466187/" ]
Please have a closer look at the [documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) of the `curve_fit` function. Where it states that `ydata` must nominaly be the result of `func(xdata... )`. So the ydata that you hand to `curve_fit` is never passed as argument of the ca...
Your first error is produced by the `t+t0` expression. It `t` is a list `x`, that's a list "concatenate" expression, which is fine for `[1,2,3]+[4,5]` but not `[1,2,3]+5`. That's why `x` and `y` have to arrays. In the second error, what did the ``` print("s",type(s)) print("s",s) ``` show? Apparently `s` is not an ...
17,770
13,961,140
I am a beginner to python and am at the moment having trouble using the command line. I have a script test.py (which only contains `print("Hello.")`), and it is located in the map C:\Python27. In my system variables, I have specified python to be C:\Python27 (I have other versions of Python installed on my computer as ...
2012/12/19
[ "https://Stackoverflow.com/questions/13961140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913042/" ]
Don't type `python test.py` from inside the Python interpreter. Type it at the command prompt, like so: ![cmd.exe](https://i.stack.imgur.com/gc2Q1.png) ![python test.py](https://i.imgur.com/TFUBm.png)
Running from the command line means running from the terminal or DOS shell. You are running it from Python itself.
17,771
61,648,271
**Piece of Code** ``` def wishListCount(): wishlist_count = len(session['Wishlist']) if len(session['Wishlist']) <= 0: return 0 else: return wishlist_count @app.route('/wishlist', methods=['GET', 'POST', 'DELETE']) def wishlist(): if request.method == 'POST': product_id = int(request.form['product_id'...
2020/05/07
[ "https://Stackoverflow.com/questions/61648271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13487131/" ]
To answer my own question, it was happening because of the Spring Boot version which was not ready to handle multistage builds, but after upgrading the service to 2.3.x i can build.
I think it is because of the Jar file not in supported form. That's why jarmode can't process it. Jarmode is a special system used to extracting Layered Jars. You can check out: <https://spring.io/blog/2020/01/27/creating-docker-images-with-spring-boot-2-3-0-m1> for detail info.
17,781
11,121,352
I deleted python .pyc files from my local repo and what I thought I did was to delete from remote github. I pushed all changes. The files are still on the repo but not on my local machine. How do I remove files from the github repo? I tried the following: ``` git rm classes/file.pyc git add . git ``` and even: `...
2012/06/20
[ "https://Stackoverflow.com/questions/11121352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203556/" ]
You should not do `git add`. That's all ``` git rm classes/file.pyc git commit -m"bla bla bla" git push ```
``` git commit -am "A file was deleted" git push ```
17,782
39,545,452
I have a php script that should (I think) run a python script to control the energenie radio controlled plug sockets depending on which button is selected. It seems to work in that it echos back the correct message when the button is pressed but the python scripts don''t appear to run. I have added the line: www-data ...
2016/09/17
[ "https://Stackoverflow.com/questions/39545452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6842362/" ]
[Parallel.Invoke](https://msdn.microsoft.com/en-us/library/dd992634(v=vs.110).aspx) method: ``` Parallel.Invoke( () => method1(), () => method2(), () => method3(), () => method4() ) ``` Add namespace `System.Threading.Tasks`
You can create a list of `Action` delegate where each delegate is a call to a given method: ``` List<Action> actions = new List<Action> { method1, method2, method3 }; ``` And then use [`Parallel.ForEach`](https://msdn.microsoft.com/en-us/library/dd992001(v=vs.110).aspx) to call them in parallel: ``` ...
17,783
57,854,621
I couldn't find any question related to this subject. But does python execute a function after the previous called function is finished or is there in any way parallel execution? **For example:** ``` def a(): print('a') def b(): print('b') a() b() ``` So in this example I would like to know if I can alway...
2019/09/09
[ "https://Stackoverflow.com/questions/57854621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9247792/" ]
Defining the function doesn't mean its execution. Since you defined `a` first, the function object for `a` will be created first, so as for there calls. You can take it as execution timeline starting from top to bottom.
There is no parallel execution of functions in python. The above functions will be executed in the same sequence that they were called in regardless of the amount of computation workload of either of the functions.
17,784
69,165,968
I'm trying to run a legacy React app locally for the first time. I'm on a new Mac M1 with Big Sur 11.5.2. My node version is 16.9.0, and I made python3 the default (although the app seems to be looking for python2). I also upgraded CommandLineTools to the latest version. But when I do a simple `npm install`, I get lot...
2021/09/13
[ "https://Stackoverflow.com/questions/69165968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1660256/" ]
Upgrade `node-sass` to a version higher than 6.0.1 (mine was 4.0.0) solves this issue Ref: [error: no template named 'remove\_cv\_t' in namespace 'std'; did you mean 'remove\_cv'?](https://stackoverflow.com/questions/67241196/error-no-template-named-remove-cv-t-in-namespace-std-did-you-mean-remove)
try this ``` rm -rf node_modules package-lock.json npm install --saveDev node-sass npm install ```
17,789
13,295,064
As part of my course at university I am learning python. A task I have been trying to complete is to write a program that will print out random letters and their corresponding positions in "antidisestablishmentarianism". It will then print the remaining letters on a single line. I have been trying to do this in probab...
2012/11/08
[ "https://Stackoverflow.com/questions/13295064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1809406/" ]
I think part of the problem is that you're creating and manipulating your `worldList` and `usedValues` lists incorrectly. To create a list of characters as `wordList` use `list(word)`. To add a used index to `usedValues` use `usedValues.append(position)`. There's also an issue with how you remove the used values from ...
There are a few problems with your code as it stands. Firstly, this line: ``` wordList =["antidisestablishmentarianism"] ``` doesn't do what you think - it actually creates a list containing the single item `"antidisestablishmentarianism"`. To convert a string into a list of characters, you can use `list()` - and si...
17,790
45,415,081
I have Eclipse with Pydev and RSE installed on my local Windows machine. I want to remote debug a Python application (Odoo 9.0) that is hosted on an Ubuntu 16.04 VPS. I have Pydev installed on the remote machine. I have been able to connect to the remote machine via SSH using a key for authentication and I can browse t...
2017/07/31
[ "https://Stackoverflow.com/questions/45415081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6489912/" ]
If you want to develop the code all remotely (instead of locally), my suggestion is using sshfs (so, you'd do all the changes there directly). You should even be able to create a shell script to a remote interpreter in that case too (i.e.: the interpreter may be any script, so, you could chroot it or even run some pyt...
I found a way to get remote editing and remote debug going with eclipse and pydev from my mac to a Debian linux server (bitnami setup). To set up remote editing and debugging - Read these first <https://www.pydev.org/manual_adv_remote_debugger.html> <https://sites.google.com/site/programmersnotebook/remote-developmen...
17,791
49,168,556
For my project I need to extract the CSS Selectors for a given element that I will find through parsing. What I do is navigate to a page with selenium and then with python-beautiful soup I parse the page and find if there are any elements that I need the CSS Selector of. For example I may try to find any input tags wit...
2018/03/08
[ "https://Stackoverflow.com/questions/49168556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7445289/" ]
Try this. ``` from scrapy.selector import Selector from selenium import webdriver link = "https://example.com" xpath_desire = "normalize-space(//input[@id = 'print'])" path1 = "./chromedriver" driver = webdriver.Chrome(executable_path=path1) driver.get(link) temp_test = driver.find_element_by_css_selector("body") el...
Ok, I am totally new to Python so i am sure that there is a better answer for this, but here's my two cents :) ``` import requests from bs4 import BeautifulSoup url = "https://stackoverflow.com/questions/49168556/extract-css-selector-for- an-element-with-selenium" element = 'a' idName = 'nav-questions' page = request...
17,792
51,160,368
Since the start and end times of DST in a timezone can change every year, so how does python tell if dst is in effect or not?
2018/07/03
[ "https://Stackoverflow.com/questions/51160368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10028264/" ]
So the answer was to use a function for a constant lookup: `$handler = new StreamHandler('/var/log/php/php.log', constant("Monolog\Logger::" . $level));`
``` <?php class Logger { const MY = 1; } $lookingfor = 'MY'; // approach 1 $value1 = (new ReflectionClass('Logger'))->getConstants()[$lookingfor]; // approach 2 $value2 = constant("Logger::" . $lookingfor); echo "$value1|$value2"; ?> ``` Result: "1|1"
17,793