lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I have a 3D numpy array . I would like to form a new 3d array by executing a function on successive 2d slices along an axis , and stacking the resulting slices together . Clearly there are many ways to do this ; I 'd like to do it in the most concise way possible . I 'd think this would be possible with numpy.vectorize... | new3dmat = np.vectorize ( func2dmat ) ( my3dmat ) new3dmat = np.empty_like ( my3dmat ) for i in range ( my3dmat.shape [ 0 ] ) : new3dmat [ i ] = func2dmat ( my3dmat [ i ] ) | Numpy Vectorized Function Over Successive 2d Slices |
Python | I was given to understand that calling print obj would call obj.__str__ ( ) which would in turn return a string to print to the console . Now I head a problem with Unicode where I could not print any non-ascii characters . I got the typical `` ascii out of range '' stuff.While experimenting the following worked : With ... | print obj.__str__ ( ) print obj.__repr__ ( ) print obj return self.__repr__ ( ) .encode ( sys.stdout.encoding ) # -*- coding : utf-8 -*- class Sample ( object ) : def __init__ ( self ) : self.name = u '' üé '' def __repr__ ( self ) : return self.name def __str__ ( self ) : return self.nameobj = Sample ( ) print obj.__s... | Python difference between print obj and print obj.__str__ ( ) [ at least with Unicode ? ] |
Python | I 'm wondering if anyone knows how to vectorize feature hashing in Python.For example , this is my code : In feature hashing , h represents the indices of the new vector I am hashing x to , i.e the index 0 of the hashed vector should have 4 and 6 summed up , index 1 should have 4 , 0 and 1 summed up , etc . The resulti... | import numpy as np hashlen = 5 x = np.array ( [ 4 , 7 , 4 , 2 , 6 , 8 , 0 , 6 , 3 , 1 ] ) h = np.array ( [ 0 , 3 , 1 , 2 , 4 , 2 , 1 , 0 , 3 , 1 ] ) w = np.array ( [ 10 , 5 , 10 , 10 , 6 ] ) for itr in range ( hashlen ) : w [ itr ] = np.sum ( x [ np.where ( h==itr ) ] ) w = np.zeros ( hashlen ) w [ h ] += x w = np.zero... | Vectorizing feature hashing in python |
Python | I am trying to port python code ( spark sql distance to nearest holiday ) to scala . I do not ( yet ) have so much scala experience , but break does not seem clean / the scala way to do it . Please , can you show me how to `` cleanly '' port this to scala.Here the same code in a bit more context https : //gist.github.c... | last_holiday = index.value [ 0 ] for next_holiday in index.value : if next_holiday > = date : break last_holiday = next_holiday if last_holiday > date : last_holiday = None if next_holiday < date : next_holiday = None breakable { for ( next_holiday < - indexAT.value ) { val next = next_holiday.toLocalDate println ( `` ... | porting python to scala |
Python | I am trying to get the total no of items in my list which is updated from a SQLAlchemy command , it is a jagged array something like this..I get the output as : 10How do I get the length as : 16 ? that is total no of items in the list ? | list = [ [ 'linux ' ] , [ 'ML ' ] , [ 'linux ' , 'ML ' , 'Data Science ' , 'GIT ' ] , [ 'linux ' , 'Data Science ' , 'GIT ' ] , [ 'GIT ' ] , [ 'ML ' , 'GIT ' ] , [ 'linux ' ] , [ 'linux ' ] , [ 'linux ' ] , [ 'Data Science ' ] ] length = len ( list ) | How to get the length of an jagged array in python |
Python | z3py snippet : http : //rise4fun.com/Z3Py/mfPUOutput : Any value of x would do but z3 returns empty model . Does a missing free variable x in the model indicates that any integer value is a valid model ? | x = Int ( ' x ' ) s = Solver ( ) s.add ( x < = x ) print s.check ( ) print s.model ( ) print s.model ( ) .sexpr ( ) sat [ ] | Empty model in z3 |
Python | I have created a Google App Engine project in Python it runs on my localhost but when I upload it onto geo-event-maps.appspot.com the markers are not displaying.I have a cron which runs to call on /place.I have no log errorsMy datastore is empty ! The txt files are being uploaded with : Is there a way of checking the f... | file_path = os.path.dirname ( __file__ ) path = os.path.join ( file_path , 'storing ' , 'txtFiles ' ) `` 'Created on Mar 30 , 2011 @ author : kimmasterson '' ' # ! /usr/bin/env pythonfrom google.appengine.ext import webappfrom google.appengine.ext import dbfrom placemaker import placemakerimport loggingimport wsgiref.h... | Markers not showing on Google Map in Google App Engine |
Python | Is there a pythonic preferred way to do this that I would do in C++ : I really like that syntax , imo it 's a lot cleaner than having temporary variables everywhere . The only other way that 's not overly complex isI guess I 'm complaining about a pretty pedantic issue . I just miss the former syntax . | for s in str : if r = regex.match ( s ) : print r.groups ( ) for s in str : r = regex.match ( s ) if r : print r.groups ( ) | pythonic way to rewrite an assignment in an if statement |
Python | I search a text based data format which supports multiline strings.JSON does not allow multiline strings : My desired output : This question is about input and output . The data format should be editable with a editor like vi , emacs or notepad.I do n't care if simple quotes `` or tripple quotes ( like in Python ) `` '... | > > > import json > > > json.dumps ( dict ( text='first line\nsecond line ' ) ) ' { `` text '' : `` first line\\nsecond line '' } ' { `` text '' : `` first linesecond line '' } | Text based data format which supports multiline strings |
Python | I have a library class where depending how it 's imported , a method that relies on the self.__module__ for identification changes behavior - depending on if I import it relatively or absolutely . Is there a way to force the self.__name__ attribute of a class to return itself absolutely ? I realize one solution would b... | project/ mylib/ foo.py LibraryClass def get_name ( self ) : return `` % s. % s. % s '' % \ ( self.__module__ , self.__class__.__name__ , self.some_init_property ) prog/ utils.py fooClass ( LibraryClass ) bar.py def some_func ( ) # see below def some_func_absolute ( ) : from prog.utils import fooClass f = fooClass ( `` ... | Get self.__module__ of class regardless of how imported |
Python | I have this listAccording to this questionI have done it by using this codeOutput - : [ [ 9112 , 5625 ] , [ 1232 ] ] problemNow I want to remove duplicate numbers like this.I was using this code but it was n't workingError - : Note - : I want to keep only first original digits . ( eg - : 1232 need to become 123 not 132... | names = [ [ `` cat '' , 9112 , `` dog123 '' , 5625 ] , [ `` luck '' , 1232 , `` bad23 '' ] ] names = [ [ `` cat '' , 9112 , `` dog123 '' , 5625 ] , [ `` luck '' , 1232 , `` bad23 '' ] ] new = [ [ x for x in y if isinstance ( x , int ) ] for y in names ] expected output - : [ [ 912 , 562 ] , [ 123 ] ] m = sorted ( list ... | How to remove duplicate digits from integers in list |
Python | I am currently trying to record some utterances , in which the record session should start when a key is pressed and held down , and stop when it is released . I made the python script for recording and storing the data.. Problem with the script is the audio file does n't seem to record anything , the duration of the f... | from pynput import keyboardimport timeimport pyaudioimport waveCHUNK = 8192FORMAT = pyaudio.paInt16CHANNELS = 2RATE = 44100RECORD_SECONDS = 5WAVE_OUTPUT_FILENAME = `` output.wav '' p = pyaudio.PyAudio ( ) frames = [ ] def callback ( in_data , frame_count , time_info , status ) : return ( in_data , pyaudio.paContinue ) ... | Output audio file not created correctly , or has unknown duration time |
Python | I have this data file and I have to find the 3 largest numbers it containsTherefore I have written the following code , but it only searches the first row of numbers instead of the entire list . Can anyone help to find the error ? | 24.7 25.7 30.6 47.5 62.9 68.5 73.7 67.9 61.1 48.5 39.6 20.016.1 19.1 24.2 45.4 61.3 66.5 72.1 68.4 60.2 50.9 37.4 31.110.4 21.6 37.4 44.7 53.2 68.0 73.7 68.2 60.7 50.2 37.2 24.621.5 14.7 35.0 48.3 54.0 68.2 69.6 65.7 60.8 49.1 33.2 26.019.1 20.6 40.2 50.0 55.3 67.7 70.7 70.3 60.6 50.7 35.8 20.714.0 24.1 29.4 46.6 58.6 ... | Error in function to return 3 largest values from a list of numbers |
Python | I 'm try to use `` virtualenvwrapper-win '' to build django project on my windows 10 pc . I think i setup it correctly , and it seems work fine . but I ca n't see what virtual environment am i using right now . it does n't show in front of the command line . But on my laptop , i can see it correctly.Above is the comman... | C : \Users\User > workonPass a name to activate one of the following virtualenvs : ==============================================================================C : \Users\User > mkvirtualenv my_djangocreated virtual environment CPython3Windows ( dest=C : \Users\User\Envs\my_django , clear=False , global=False ) with s... | windows cmd not showing python virtualenvwrapper in front of the command |
Python | I have successfully followed this example for how to connect C++ and python . It works fine when I use the given Makefile . When I try to use cmake instead , it does not go as well.C++ Code : Makefile : When I compile this I get a .so file that can be included in the script I really want to use cmake instead of a manua... | # include < boost/python.hpp > # include < iostream > extern `` C '' char const* greet ( ) { return `` hello , world '' ; } BOOST_PYTHON_MODULE ( hello_ext ) { using namespace boost : :python ; def ( `` greet '' , greet ) ; } int main ( ) { std : :cout < < greet ( ) < < std : :endl ; return 0 ; } # location of the Pyth... | BoostPython and CMake |
Python | In common implementations such as Linux/Glibc , Windows/MSVC and BSD/Mac OS X , willfor N , M > 0 , actually shrink the buffer returned by malloc in the realloc call , in the sense that up to M bytes may return to the free list ? And more importantly , is there a chance that it reallocates the buffer ? I want to know b... | void *p = malloc ( N + M ) ; // assume this does n't failp = realloc ( p , N ) ; // nor this | Does realloc actually shrink buffers in common implementations ? |
Python | I have a constraint problem that I 'm trying to solve with python-constraintSo let 's say I have 3 locations : loc1 , ... loc3Also , I have 7 devices : device1 , ... device7Max amount of devices in each location : loc1:3 , loc2:4 , loc3:2 ( for example maximum of 3 devices in loc1 and so on ... ) And some constraints a... | from constraint import * problem = Problem ( ) for key in locations_devices_dict : problem.addVariable ( key , locations_devices_dict [ key ] ) # problem.addVariable ( `` loc1 '' , [ 'device1 ' , 'device3 ' , 'device7 ' ] ) problem.addConstraint ( AllDifferentConstraint ( ) ) problem.addConstraint ( MaxSumConstraint ( ... | python Constraints - constraining the amount |
Python | I 've got a python list of dictionaries : Whats the most efficient/cleanest way to order that list by weight then factor ( numerically ) . The resulting list should look like : | mylist = [ { 'id':0 , 'weight':10 , 'factor':1 , 'meta ' : 'ABC ' } , { 'id':1 , 'weight':5 , 'factor':1 , 'meta ' : 'ABC ' } , { 'id':2 , 'weight':5 , 'factor':2 , 'meta ' : 'ABC ' } , { 'id':3 , 'weight':1 , 'factor':1 , 'meta ' : 'ABC ' } ] mylist = [ { 'id':3 , 'weight':1 , 'factor':1 , 'meta ' : 'ABC ' } , { 'id':... | Ordering a list of dictionaries in python |
Python | The world contains agents at different locations , with only a single agent at any location . Each agent knows where he 's at , but I also need to quickly check if there 's an agent at a given location . Hence , I also maintain a map from locations to agents . I have a problem deciding where this map belongs to : class... | class World : def __init__ ( self , n_agents ) : # ... self.agents = [ ] self.agent_locations = { } for id in range ( n_agents ) : x , y = self.find_location ( ) agent = Agent ( self , x , y ) self.agents.append ( agent ) self.agent_locations [ x , y ] = agent def update_agent_location ( self , agent , x , y ) : del se... | Which class should store the lookup table ? |
Python | We get this error when uploading a large file ( more than 10Mb but less than 100Mb ) : Or this error when the file is more than 5MbIt seems that this API is looking at the file size and trying to upload it via multi part or resumable method . I ca n't imagine that is something that as a caller of this API I should be c... | 403 POST https : //www.googleapis.com/upload/storage/v1/b/dm-scrapes/o ? uploadType=resumable : ( 'Response headers must contain header ' , 'location ' ) 403 POST https : //www.googleapis.com/upload/storage/v1/b/dm-scrapes/o ? uploadType=multipart : ( 'Request failed with status code ' , 403 , 'Expected one of ' , < HT... | Uploading large files to Google Storage GCE from a Kubernetes pod |
Python | I need to do a `` ~ '' operation in Python but not taking account of 2 's complement . I managed to do that by using XOR , do you know another way to do this ? ( more efficient ) | a = 0b101b = 0b10101print bin ( a ^ ( 2 ** a.bit_length ( ) - 1 ) ) # 0b10print bin ( b ^ ( 2 ** b.bit_length ( ) - 1 ) ) # 0b1010 | `` Bitwise Not '' in Python disconsidering 2 's complement |
Python | I am trying to make a brush function that draws onto a canvas with a calligraphy style of brush , thin one way , thick the other . Right now , the actual drawing of the brush footprint works , but the code does not run fast enough , and the actual line keeps cutting ( as shown in the gif ) .This is my code right now : ... | import pygameimport osimport randomfrom pygame.locals import *flags = DOUBLEBUFpygame.init ( ) pygame.event.set_allowed ( [ QUIT ] ) current_path = os.path.dirname ( __file__ ) # The directory the main file is iniconPath = os.path.join ( current_path , 'images ' ) # The icon folder pathdisplayWidth = 1280displayHeight ... | How do I make pygame draw along all points on a line between 2 points ? |
Python | I am trying to move s3 files from a `` non-deleting '' bucket ( meaning I ca n't delete the files ) to GCS using airflow . I can not be guaranteed that new files will be there everyday , but I must check for new files everyday.my problem is the dynamic creation of subdags . If there ARE files , I need subdags . If ther... | from airflow import modelsfrom airflow.utils.helpers import chainfrom airflow.providers.amazon.aws.hooks.s3 import S3Hookfrom airflow.operators.python_operator import PythonOperator , BranchPythonOperatorfrom airflow.operators.dummy_operator import DummyOperatorfrom airflow.operators.subdag_operator import SubDagOperat... | trying to create dynamic subdags from parent dag based on array of filenames |
Python | Possible Duplicate : Python : Retrieve items from a set Consider the following code : So new_item is in s because it is equivalent to one of its items , but it is a different object.What I want is to get item1 from s given new_item is in s.One solution I have come up with is straightforward but not very efficient : Ano... | > > > item1 = ( 1 , ) > > > item2 = ( 2 , ) > > > s = set ( [ item1 , item2 ] ) > > > sset ( [ ( 2 , ) , ( 1 , ) ] ) > > > new_item = ( 1 , ) > > > new_item in sTrue > > > new_item == item1True > > > new_item is item1False def get_item ( s , new_item ) : for item in s : if item == new_item : return item > > > get_item ... | Is there a way to get an item from a set in O ( 1 ) time ? |
Python | I want to do the equivalent ofusing Python 's C API . In other words , I want to create a Python class which has a static variable , using C.How can I do this ? | class Foo ( object ) : bar = 1 | How can I create a static variable in a Python class via the C API ? |
Python | I am having some issues when trying to import StanfordNER Tagger to use for NER . Here is my code ( took portions of this from other posts here ) : The error I am getting highlights the last line of code telling me : Any help would be great ! Edit : Here is another line of code that worked for me . For what inside Stan... | import osdef install_java ( ) : ! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null os.environ [ `` JAVA_HOME '' ] = `` /usr/lib/jvm/java-8-openjdk-amd64 '' ! java -versioninstall_java ( ) ! pip install StanfordCoreNLPfrom stanfordcorenlp import StanfordCoreNLPnlp = StanfordCoreNLP ( 'stanford-corenlp ' , lang=... | Importing StanfordNER Tagger Google Colab |
Python | Is there a way to run my current python code in vim without making any changes to the file ? Normally , when I want to test my code from within vim , I would execute this : However , this overrides the current file I am editing . Often , I add print statements or comment stuff out to see why my code is n't working . I ... | : w ! python | Running Python code in Vim without saving |
Python | In Python 2.7 , running the following code : gives the following result : But if I change the code to below : I get the different error : Why is Python considering a is a local variable when it is an int , global when list ? What 's the rationale behind this ? P.S . : I was experimenting after reading this thread . | def f ( ) : a = a + 1f ( ) Traceback ( most recent call last ) : File `` test.py '' , line 4 , in < module > f ( ) File `` test.py '' , line 2 , in f a = a + 1UnboundLocalError : local variable ' a ' referenced before assignment def f ( ) : a [ 0 ] = a [ 0 ] + 1f ( ) Traceback ( most recent call last ) : File `` test.p... | Python global and local variables |
Python | I have a dataframe like this ... I want to add a column called 'log_ret ' where the value from 'a_return ' or 'b_return ' is used based on the value in the 'instrument_holding ' column . Like this ... As you can see , if the row 's value for 'instrument_holding ' is ' a ' , 'log_ret ' has the value from 'a_return ' and... | a_return b_return bc_ratio instrument_holding 0 NaN NaN -0.165286 a 1 0.996474 1.013166 -0.164637 a 2 0.997730 0.993540 -0.170058 a 3 1.024294 1.024318 -0.184530 a 4 1.019071 1.047297 -0.148644 a 5 0.992243 1.008210 -0.188752 a 6 1.010331 1.039020 -0.098413 a 7 0.989542 0.991899 0.025051 b 8 1.005197 1.002527 -0.025051... | python pandas dataframe create new column from other columns ' cells |
Python | I create a coverage report like this : My .coveragerc file looks like this : But my report looks like this : How can I remove the standard library packages with 0 % cover from the report ? Obviously listing them in omit does not work the way I expect ... | nosetests -- with-coverage -- cover-html # .coveragerc to control coverage.py [ run ] branch = Trueomit = contextlib , ctypes , ctypes._endian , ctypes.util , filecmp , getpass , sets , subprocess , uuid [ report ] exclude_lines = pragma : no cover ... ... ... .Name Stmts Miss Branch BrPart Cover Missing -- -- -- -- --... | remove packages from coverage report |
Python | I 'm building C++ < - > Python bindings using Cython , and I can not find how to return a C++ object from a Python method.More specifically , when compiling peak_detection_.pyx , shown below , I get for the last linesI understand the error , but I would not mind some help/pointers about how to fix it.peak_detection.hpp... | peak_detection_.pyx:35:36 : Can not convert 'vector [ Peak ] ' to Python object def getPeaks ( self , data ) : return self.thisptr.getPeaks ( data ) # ifndef PEAKDETECTION_H # define PEAKDETECTION_H # include < string > # include < map > # include < vector > # include `` peak.hpp '' class PeakDetection { public : PeakD... | How to expose a function returning a C++ object to Python using Cython ? |
Python | A little bit of background , I am loading about 60,000 images to colab to train a GAN . I have already uploaded them to Drive and the directory structure contains folders for different classes ( about 7-8 ) inside root . I am loading them to colab as follows : which gives the ouput : I am further processing them as fol... | root = `` drive/My Drive/data/images '' root = pathlib.Path ( root ) list_ds = tf.data.Dataset.list_files ( str ( root/'*/* ' ) ) for f in list_ds.take ( 3 ) : print ( f.numpy ( ) ) b'drive/My Drive/data/images/folder_1/2994.jpg ' b'drive/My Drive/data/images/folder_1/6628.jpg ' b'drive/My Drive/data/images/folder_2/37... | Google colab not loading image files while using tensorflow 2.0 batched dataset |
Python | EDIT : This question is heavily outdated ! numba now supports Enum and namedtuple out of the box , which both provide a reasonable solution for grouping constants.I 'm doing some bitshifting in python and want to speed it up with numba . For that , I have lots of constant integer values , that I have to handle in a pos... | class SomeConstantsContainer : SOME_NAME = 0x1 SOME_OTHER_CONSTANT = 0x2 AND_ANOTHER_CONSTANT = 0x4 # $ 29.2 = global ( SomeConstantsContainer : < class 'constants.SomeConstantContainer ' > ) : : pyobject # $ 29.3 = getattr ( attr=SOME_VARIABLE , value= $ 29.2 ) : : pyobject from numpy import npSOME_STUPID_CONSTANT = n... | Best way to handle multiple constants in a container with numba ? |
Python | Forgive me if this has been asked before . I have looked around a lot , but I get the feeling that I do n't have the proper vocabulary to find this by searching the web.I have a multithreaded application in python . I want to be able to lock a certain block of code but only to other threads with a certain condition . L... | ( 1 ) def foo ( bar ) : ( 2 ) ( 3 ) lock ( bar ) ( 4 ) # Code block ALPHA ( two threads with equivalent bar should not be in here ) ( 5 ) unlock ( bar ) | value based thread lock |
Python | Reversing a tuple and reversing a list returns objects of different type : They have the same dir . Neither type is a subclass of the other . Why is that ? What can one do that the other ca n't ? | > > > reversed ( ( 1,2 ) ) < reversed at 0x7fffe802f748 > > > > reversed ( [ 1,2 ] ) < list_reverseiterator at 0x7fffebdd4400 > | What 's the difference between a reversed tuple and a reversed list ? |
Python | I 'm building a pytest plugin and I currently log by adding something similar to the following two lines at the top of the plugin file : However , this does not seem to take into account pytest configuration ( through either command line options or ini file ) such as the log file path , logger format , etc.I can manual... | logging.basicConfig ( ) log = logging.getLogger ( PLUGIN_NAME ) | How should I log in my pytest plugin ? |
Python | In trying to answer a question for another user , I came across something that piqued my curiosity : Will change the working directory as far as Python is concerned , so if I am in /home/username/ , and I run os.chdir ( '.. ' ) , any subsequent code will work as though I am in /home/ . For example , if I then do : file... | import osos.chdir ( '.. ' ) import globfiles = glob.glob ( '*.py ' ) # ! /bin/bashcd /tmptouch foo.txt | Possible to change directory and have change persist when script finishes ? |
Python | I 'm trying to implement a toggle comment feature in QScintilla that works with multiple selection . Unfortunately I do n't know very well how to do it , so far I 've come up with this code : Relevant Qscintilla docs live here : ScintillaDocQScintilla2MultipleSelectionAndVirtualSpaceRight now the feature just support o... | import sysimport reimport mathfrom PyQt5.Qt import * # noqafrom PyQt5.Qsci import QsciScintillafrom PyQt5 import Qscifrom PyQt5.Qsci import QsciLexerCPPclass Commenter ( ) : def __init__ ( self , sci , comment_str ) : self.sci = sci self.comment_str = comment_str def is_commented_line ( self , line ) : return line.stri... | How to implement a comment feature that works with multiple selections in QScintilla ? |
Python | I have a matrixI want a new matrix , where the value of the entry in row i and column j is the product of all the entries of the ith row of A , except for the cell of that row in the jth column.The solution that first occurred to me wasBut this only works so long as no entries have values zero.Any thoughts ? Thank you ... | A = np.array ( [ [ 0.2 , 0.4 , 0.6 ] , [ 0.5 , 0.5 , 0.5 ] , [ 0.6 , 0.4 , 0.2 ] ] ) array ( [ [ 0.24 , 0.12 , 0.08 ] , [ 0.25 , 0.25 , 0.25 ] , [ 0.08 , 0.12 , 0.24 ] ] ) np.repeat ( np.prod ( A , 1 , keepdims = True ) , 3 , axis = 1 ) / A B = np.zeros ( ( 3 , 3 ) ) for i in range ( 3 ) : for j in range ( 3 ) : B [ i ... | In numpy , calculating a matrix where each cell contains the product of all the other entries in that row |
Python | I have sales statistic data in array form to calc standard deviation or average from this data . let said +-20 % differential is normal situation , 23 is obviously a special case . what 's the best algorithm ( in any language , pseudo or any principle ) to find this unusual value ? | stats = [ 100 , 98 , 102 , 100 , 108 , 23 , 120 ] | Finding unusual value in an array , list |
Python | SetupI encountered the 404 problem after following the unaccepted answers of the question AppEngine datastore - backup programatically I have enabled the Datastore Admin , as suggested by one of the answer provider . I can manually trigger a datastore backup in Google App Engine console and the backup runs without any ... | cron : - description : Regular backup url : /_backup/fullbackup schedule : every 24 hours _ah/datastore_admin/backup.create ? gs_bucket_name= % 2Fgs % 2Ftest.appspot.com % 2F21-06-2015 & kind=Test & kind=TestContent & kind=TestDocument & filesystem=gs task = taskqueue.add ( url='/_ah/datastore_admin/backup.create ' , m... | 404 when trying to create backup in a Google App Engine project |
Python | What do these mean ? I 've seen this syntax used in some standard Python modules when fetching documentation via PyCharm , and I have no idea what it means . What 's the hinted type for a in my example ? What types can I pass to this function ? The particular example where I 've seen this is in tkinter 's Frame __init_... | def f ( a : { int , float } ) : pass | Python - curly braces in type hints |
Python | Is it safe to modify a mutable object returned by a method of a standard library object ? Here 's one specific example ; but I 'm looking for a general answer if possible.Is this code safe ? I 'm concerned that by changing groupdict ( ) I 'm corrupting the object m ( which I still need for later ) .I tested this out , ... | # m is a MatchObject # I know there 's only one named group in the regex # I want to retrieve the name and the valueg , v = m.groupdict ( ) .popitem ( ) # do something else with m | python : changing dictionary returned by groupdict ( ) |
Python | Is it considered bad practice to re-use the same iterating variable name throughout multiple for-loops in a given script ? For example , I know that the url variable is n't limited in scope to the for loop , so there 's potential while using the url variable outside of the for loop for it to get messy and may be more d... | for url in urls1 : print urlfor url in urls2 : print urlfor url in urls3 : print url | Is it considered bad practice to re-use an iterating variable multiple times in a given script ? |
Python | I 'm using sqlalchemy with postgresql . And I 'm newbie of sqlalchemy.I made forien key for model `` User '' called `` to_user_id '' to model `` Invitation '' and this key is not nullable.When I try to delete instance of model `` User '' usingAnd sqlalchemy set invitation 's to_user_id to NULL automatically before dele... | session.delete ( user ) IntegrityError : ( IntegrityError ) null value in column `` to_user_id '' violates not-null constraint class User ( Base ) : `` ' User model `` ' __tablename__='User ' id = Column ( Integer , primary_key=True ) class Invitation ( Base ) : `` ' Invitation model `` ' __tablename__ = 'Invitation ' ... | sqlalchemy updates another model before deletion |
Python | What I have now is : I am able to open the webdriver and I see the extension that I added on the right top corner in google Chrome , however the driver does n't go to google.com . I have searched a lot and I ca n't find the solution to it.Here is the link to the extension : https : //chrome.google.com/webstore/detail/b... | chrome_options = Options ( ) chrome_options.add_extension ( r '' C : \Users\x\OneDrive\Desktop\pp\crxSolver.crx '' ) driver = webdriver.Chrome ( r ' C : \Users\x\OneDrive\Desktop\chromedriver.exe ' , options=chrome_options ) driver.get ( `` https : //www.google.com '' ) | Selenium Chromedriver not navigating to url |
Python | I have two certificates , a root.crt that was used to sign client.crt.I want to verify that the client.crt was indeed signed by root.key.Using openssl on terminal , it works like this : However using pyOpenSSL - following the documentation and this blog post - I tried something like this : I get this error : What am I ... | $ openssl verify -CAfile root.crt client.crt > client.crt : OK client_cert = OpenSSL.crypto.load_certificate ( OpenSSL.crypto.FILETYPE_PEM , file ( 'client.crt ' ) .read ( ) ) root_cert = OpenSSL.crypto.load_certificate ( OpenSSL.crypto.FILETYPE_PEM , file ( 'root.crt ' ) .read ( ) ) store = OpenSSL.crypto.X509Store ( ... | How to verify certificate signature in pyOpenSSL ? |
Python | Is it possible to pass a vector to a trained neural network so it only chooses from a subset of the classes it was trained to recognize . For example , I have a network trained to recognize numbers and letters , but I know that the images I 'm running it on next will not contain lowercase letters ( Such as images of se... | import numpy as npdef softmax ( arr ) : return np.exp ( arr ) /np.exp ( arr ) .sum ( ) # Stand ins for previous layer/NN output and vector of allowed answers.output = np.array ( [ 0.15885351,0.94527385,0.33977026 , -0.27237907,0.32012873 , 0.44839673 , -0.52375875 , -0.99423903 , -0.06391236,0.82529586 ] ) restrictions... | Limit neural network output to subset of trained classes |
Python | I executed some commands in shell with python . I need to show the command response in shell . But the commands will execute 10s . I need to wait . How can I show the echo of the commands instantly . Following is my codeAnd I need to use the output of the command . so I ca n't use subprocess.call | cmd = `` commands '' output = subprocess.Popen ( cmd , shell=True , stdout=subprocess.PIPE ) print ( output.stdout.read ( ) ) | How to print the output of shell instantly by python script |
Python | I am wondering how to create forgiving dictionary ( one that returns a default value if a KeyError is raised ) .In the following code example I would get a KeyError ; for exampleIn order not to get one I would 1 . Have to catch the exception or use get.I would like to not to have to do that with my dictionary ... | a = { 'one':1 , 'two':2 } print a [ 'three ' ] | A forgiving dictionary |
Python | I 'm making a clone of Ballz , a mobile game where you have to shoot a whole bunch of balls at blocks that break after multiple hits . It 's like BrickBreaker on steroids . I 've got it working mostly , but I ca n't figure out how to shoot the balls one after another . I know from testing that at the time of shooting ,... | import pygameimport mathimport randomfrom vector import *backgroundColor = ( 0 , 0 , 0 ) ballColor = ( 255 , 255 , 255 ) sizeOfOneBlock = 50.0realDimension = 600.0blockNumberInLine = int ( realDimension/sizeOfOneBlock ) size = [ int ( realDimension ) , int ( realDimension ) ] # eg . probability ( 1/3 ) def probability ... | Why are my balls sticking together ? |
Python | I want a point after each three digits in a big number ( e.g . 4.100.200.300 ) .This question is specific to Pythons string formatting mini-language . | > > > x = 4100200300 > > > print ( ' { } '.format ( x ) ) 4100200300 | Print a big integer with punctions with Python3 string formatting mini-language |
Python | Why does str ( A ( ) ) seemingly call A.__repr__ ( ) and not dict.__str__ ( ) in the example below ? Output : | class A ( dict ) : def __repr__ ( self ) : return 'repr ( A ) ' def __str__ ( self ) : return dict.__str__ ( self ) class B ( dict ) : def __str__ ( self ) : return dict.__str__ ( self ) print 'call : repr ( A ) expect : repr ( A ) get : ' , repr ( A ( ) ) # worksprint 'call : str ( A ) expect : { } get : ' , str ( A (... | Python base class method call : unexpected behavior |
Python | I came across a bizarre situation while doing some large number division in python.and Why is there a difference between the two approaches ? int ( ) appears to be at the least int64 because int ( 2^63 - 1 ) and 2^63 - 1 are the same values . | int ( 1012337203685477580 / 2 ) = 506168601842738816 int ( 1012337203685477580 > > 1 ) = 506168601842738790 | Difference in long int division in python 3 |
Python | Pythons memoryview does not support datetime64 or timedelta . Ok . But when I try to create a memoryview of a structured array that includes a datetime64 or timedelta , it appears to work ... unless I assign it to a variable ! This seriously challenges my understanding of the way Python fundamentally works . How can f ... | In [ 19 ] : memoryview ( zeros ( 10 , dtype= [ ( `` A '' , `` m8 [ s ] '' ) ] ) ) Out [ 19 ] : < memory at 0x7f1d455d6048 > In [ 20 ] : x = memoryview ( zeros ( 10 , dtype= [ ( `` A '' , `` m8 [ s ] '' ) ] ) ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --... | Why does creating this memoryview raise a ValueError only when assigning to a variable ? |
Python | How should I map indices of a numpy matrix ? For example : The row/column indices are 0 , 1 , 2.So : Let s say I need to map these indices , converting 0 , 1 , 2 into , e.g . 10 , ' A ' , ' B ' in the way that : I can just set a dict and use it to access the elements , but I would like to know if it is possible to do s... | mx = np.matrix ( [ [ 5,6,2 ] , [ 3,3,7 ] , [ 0,1,6 ] ] > > > mx [ 0,0 ] 5 mx [ 10,10 ] # returns 5mx [ 10 , ' A ' ] # returns 6 and so on.. | Map index of numpy matrix |
Python | I have to print a pyramid of numbers with this rule : odd index : 1 to index , even index : index to 1 : I wrote this code : but the output is : I 'm a beginner with recursion , I 'll be glad for your explanations too.thanks . | 121123432112345654321123456787654321123456789 def printFigure ( rows ) : if rows > 0 : if rows % 2 == 0 : printFigure ( rows-1 ) while ( rows > 0 ) : print ( str ( rows ) [ : :-1 ] , end = `` ) rows -= 1 print ( `` ) if rows % 2 == 1 : printFigure ( rows-1 ) while ( rows > 0 ) : print ( str ( rows ) , end = `` ) rows -... | Recursively print pyramid of numbers |
Python | I need to find a random color , given a specific seed number - fast.given the same ID twice , should return the same color.I did this : The problem is that calculating the sha1 of numbers many times is very slow in total . ( I 'm using this function about 100k times ) Edit : The reason I use a hash function is that I w... | def id_to_random_color ( number ) : random_bytes = hashlib.sha1 ( bytes ( number ) ) .digest ( ) return [ int ( random_bytes [ -1 ] ) / 255 , int ( random_bytes [ -2 ] ) / 255 , int ( random_bytes [ -3 ] ) / 255 , 1.0 ] | Python - Get random color , given a seed number as fast as possible |
Python | I use a decorator to extend memoization via lru_cache to methods of objects which are n't themselves hashable ( following stackoverflow.com/questions/33672412/python-functools-lru-cache-with-class-methods-release-object ) . This memoization works fine with python 3.6 but shows unexpected behavior on python 3.7 . Observ... | import randomimport weakreffrom functools import lru_cachedef memoize_method ( func ) : # From stackoverflow.com/questions/33672412/python-functools-lru-cache-with-class-methods-release-object def wrapped_func ( self , *args , **kwargs ) : self_weak = weakref.ref ( self ) @ lru_cache ( ) def cached_method ( *args_ , **... | Memoization of method working on python 3.6 but not on 3.7.3 |
Python | I am trying to interrogate this site to get the list of offers . The problem is that we need to fill 2 forms ( 2 POST queries ) before receiving the final result . This what I have done so far : First I am sending the first POST after setting the cookies : Then trying to retrieve the offers using the second post query ... | library ( httr ) set_cookies ( .cookies = c ( a = `` 1 '' , b = `` 2 '' ) ) first_url < - `` https : //compare.switchon.vic.gov.au/submit '' body < - list ( energy_category= '' electricity '' , location= '' home '' , `` location-home '' = '' shift '' , `` retailer-company '' = '' '' , postcode= '' 3000 '' , distributor... | Multi POST query ( session mode ) |
Python | I have the strange problem , that the intersection of planes in SymPy works with simple examples , but fails for one with more complicated coordinates . I post both a simple example that works , and the one that fails . As the Povray images show , I have three planes that go through vertices of a polyhedron and are per... | from sympy import Point3D , PlanepointR = Point3D ( 1/2 , 0 , 1/2 ) pointG = Point3D ( 1 , 0 , 0 ) planeR = Plane ( pointR , pointR ) planeG = Plane ( pointG , pointG ) print ( '\n # # # # # # # # Intersection of the planes : ' ) lineRG = planeR.intersection ( planeG ) [ 0 ] # yellowprint ( lineRG ) print ( '\n # # # #... | Why does SymPy calculate wrong intersections of planes ? |
Python | Suppose the following code : It is easily seen that a str input leads to an int output and vice versa . Is there a way to specify the return type so that it encodes this inverse relationship ? | from typing import Uniondef invert ( value : Union [ str , int ] ) - > Union [ int , str ] : if isinstance ( value , str ) : return int ( value ) elif isinstance ( value , int ) : return str ( value ) else : raise ValueError ( `` value must be 'int ' or 'str ' '' ) | Is there a way to specify a conditional type hint in Python ? |
Python | A lot of times , I wrote queries like the following : So , I would like to write my own version of select , an alternative of it . Something like to avoid me writing every time the first part of the predicate , if u.available and u.friends > 0 . My question is more general : how can I write a function like select that ... | pony.orm.select ( u for u in User if u.available and u.friends > 0 and ... ) | Writing select functions for customized Pony |
Python | Pictures will explain the title : Under LMDE & Ubuntu 12.04 my GtkIconView looks like this - its correct in terms of the spacing between the icons : Under Ubuntu 12.10 , 13.04 & Fedora 17 the same code displays as follows : N.B . - This is a rhythmbox python plugin - source code is here on GitHubI 've checked the follo... | # ! /usr/bin/env pythonfrom gi.repository import Gtk , GdkPixbufwindow = Gtk.Window ( ) window.connect ( 'delete_event ' , Gtk.main_quit ) ui = Gtk.Builder ( ) ui.add_from_file ( 'reproduce.ui ' ) page = ui.get_object ( 'main_box ' ) window.add ( page ) ls = Gtk.ListStore ( str , GdkPixbuf.Pixbuf ) icon = GdkPixbuf.Pix... | What causes the different display behaviour for a GtkIconView between different GTK versions ? |
Python | and happy new year ! I have a model which will hold some hundreds of thousands of records . The model looks like this : I want to know all clients a certain user is dealing with . To get the unique client ids , I could use the Django ORM alone : or do the following : Both will produce the same result . But which one wi... | class Transaction ( models.Model ) : user = models.ForeignKey ( User ) client = models.ForeignKey ( Client ) amount = models.FloatField ( ) Transaction.objects.filter ( user=the_user ) .distinct ( 'client_id ' ) .values_list ( 'client_id ' , flat=True ) set ( Transaction.objects.filter ( user=the_user ) .values_list ( ... | Which one scales better ? ORM 's distinct ( ) or python set ( ) |
Python | I want to iterate over the rows of a CSR Matrix and divide each element by the sum of the row , similar to this here : numpy divide row by row sumMy problem is that I 'm dealing with a large matrix : ( 96582 , 350138 ) And when applying the operation from the linked post , it bloats up my memory , since the returned ma... | for row in counts : row = row / row.sum ( ) from scipy import sparseimport timestart_time = curr_time = time.time ( ) mtx = sparse.csr_matrix ( ( 0 , counts.shape [ 1 ] ) ) for i , row in enumerate ( counts ) : prob_row = row / row.sum ( ) mtx = sparse.vstack ( [ mtx , prob_row ] ) if i % 1000 == 0 : delta_time = time.... | Large Numpy Scipy CSR Matrix , row wise operation |
Python | I have a large array where each row is a time series and thus needs to stay in order.I want to select a random window of a given size for each row.Example : What an ideal solution would look like to me : But unfortunately this does not workWhat I 'm going with right now is terribly slow : Sure , I could do the same wit... | > > > import numpy as np > > > arr = np.array ( range ( 42 ) ) .reshape ( 6,7 ) > > > arrarray ( [ [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] , [ 7 , 8 , 9 , 10 , 11 , 12 , 13 ] , [ 14 , 15 , 16 , 17 , 18 , 19 , 20 ] , [ 21 , 22 , 23 , 24 , 25 , 26 , 27 ] , [ 28 , 29 , 30 , 31 , 32 , 33 , 34 ] , [ 35 , 36 , 37 , 38 , 39 , 40 , 41 ]... | Selecting Random Windows from Multidimensional Numpy Array Rows |
Python | The Python tarfile library does not detect a broken tar.Very nice , the command line tool recognizes an unexpected EOF.Not nice . The Python library decodes the file , but raises no exception.How to detect unexpected EOF with the Python library ? I want to avoid the subprocess module.The parameter errorlevel does not h... | user @ host $ wc -c good.tar143360 good.taruser @ host $ head -c 130000 good.tar > cut.taruser @ host $ tar -tf cut.tar ... tar : Unexpected EOF in archivetar : Error is not recoverable : exiting now user @ host $ pythonPython 2.7.6 ( default , Mar 22 2014 , 22:59:56 ) > > > import tarfile > > > tar=tarfile.open ( 'cut... | tar.extractall ( ) does not recognize unexpected EOF |
Python | Is there a way to get the difference between those two lists ? Basically , I need a scaleable way to get the differences between 2 lists that contain dictionaries . So I 'm trying to compare those lists , and just get a return of { 'key3 ' : 'item3 ' } | list1 = [ { 'key1 ' : 'item1 ' } , { 'key2 ' : 'item2 ' } ] list2 = [ { 'key1 ' : 'item1 ' } , { 'key2 ' : 'item2 ' } , { 'key3 ' : 'item3 ' } ] | Getting the difference between 2 lists that contain dictionaries |
Python | What is this called in python : Is that an array .. of ... erhm one dictionary ? Is thatA tuple ? ( or whatever they call it ? ) | [ ( '/ ' , MainPage ) ] ( ) | What is this construct called in python : ( x , y ) |
Python | I 'm trying to write a bzr post-commit hook for my private bugtracker , but I 'm stuck at the function signature of How can I extract the commit message for the branch from this with bzrlib in Python ? | post_commit ( local , master , old_revno , old_revid , new_revno , mew_revid ) | How can I get a commit message from a bzr post-commit hook ? |
Python | In order to match the Unicode word boundaries [ as defined in the Annex # 29 ] in Python , I have been using the regex package with flags regex.WORD | regex.V1 ( regex.UNICODE should be default since the pattern is a Unicode string ) in the following way : It works well in this rather simple cases . However , I was won... | > > > s= '' here are some words '' > > > regex.findall ( r'\w ( ? : \B\S ) * ' , s , flags = regex.V1 | regex.WORD ) [ 'here ' , 'are ' , 'some ' , 'words ' ] > > > regex.findall ( r'\w ( ? : \B\S ) * ' , `` x ' z '' , flags = regex.V1 | regex.WORD ) [ `` x ' z '' ] > > > regex.findall ( r'\w ( ? : \B\S ) * ' , `` l'av... | Matching Unicode word boundaries in Python |
Python | I 'm currently developing an application which needs to connect a MQ Queue in order to have the queue saving message information inside another service . Once it 's done , the service returns a result message through the MQ Queue and it is returned to me . I 'm sending a string message that contains a XML message simil... | < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < peticionDemanda > < subtipo > DEMANDA CONTRATACIÓN < /subtipo > < /peticionDemanda > class MQManager : def __init__ ( self ) : self.queue_manager = config.queue_manager self.channel = config.channel self.port = config.port self.host = config.host self.conn_info = c... | How can I configure CCSID value in my Queue Manager using `` pymqi '' Python library ? |
Python | I am wondering about how many times this while loop would execute . This is a function that adds two numbers using XOR and AND . | def Add ( x , y ) : # Iterate till there is no carry while ( y ! = 0 ) : # carry now contains common # set bits of x and y carry = x & y # Sum of bits of x and y where at # least one of the bits is not set x = x ^ y # Carry is shifted by one so that # adding it to x gives the required sum y = carry < < 1 return x `` | How many times will the while loop be executed ? |
Python | I have this code : I expect to see different memory peak usages for this code with the line df2=deepcopy ( df ) and without it . But the memory shows exactly the same result . Is n't deepcopy supposed to clone the object and therefore increase memory usage ? | import resourcefrom copy import deepcopyimport pandas as pdimport randomn=100000df = pd.DataFrame ( { ' x ' : [ random.randint ( 1 , 1000 ) for i in range ( n ) ] , ' y ' : [ random.randint ( 1 , 1000 ) for i in range ( n ) ] , ' z ' : [ random.randint ( 1 , 1000 ) for i in range ( n ) ] } ) df2=deepcopy ( df ) print '... | Why does n't deepcopy of a Pandas DataFrame affect memory usage ? |
Python | Example : It 's really annoying to type a list of strings in python : I often do something like this to save me having to type quotation marks all over the place : Those took the same amount of time , and I got 2x the # of months typed in . Another example : instead of : which took much less time . | [ `` January '' , `` February '' , `` March '' , `` April '' , ... ] `` January February March April May June July August ... '' .split ( ) [ ( ' a ' , ' 9 ' ) , ( ' 4 ' , ' 3 ' ) , ( ' z ' , ' x ' ) ... ] map ( tuple , `` a9 43 zx '' .split ( ) ) | Is it acceptable to use tricks to save programmer when putting data in your code ? |
Python | I am trying to figure out whether or not a column in a pandas dataframe is boolean or not ( and if so , if it has missing values and so on ) .In order to test the function that I created I tried to create a dataframe with a boolean column with missing values . However , I would say that missing values are handled exclu... | > boolean = pd.Series ( [ True , False , None ] ) > print ( boolean ) 0 True1 False2 Nonedtype : object > boolean = pd.Series ( [ True , False , np.nan ] ) .astype ( bool ) > print ( boolean ) 0 True1 False2 Truedtype : bool | Bool and missing values in pandas |
Python | In this pull request it looks like type hinting support for descriptors was added.However it looks like no finalized `` correct '' usage example was ever posted , nor does it looks like any documentation was ever added to the typing module or to Mypy.It looks like the correct usage is something like this : which seems ... | from typing import TypeVarT = TypeVar ( 'T ' ) V = TypeVar ( ' V ' ) class classproperty ( ) : def __init__ ( self , getter : Callable [ [ Type [ T ] , V ] ) - > None : self.getter = getter def __get__ ( self , instance : Optional [ T ] , owner : Type [ T ] ) - > V return self.getter ( owner ) def forty_two ( cls : Typ... | Type hinting with descriptors |
Python | I 've been trying to capture the layout of an HTML page using BeautifulSoup4 and recursion . The idea is to have linked data structures of parents to children , for example , a layout like this : Would be stored in a list like so : I 've had a hard time finding Q & A on this specific problem , so instead I 've tried mo... | < html > < h1 > < ! -- Contents -- > < /h1 > < div > < div > < ! -- Contents -- > < /div > < /div > < /html > html = [ h1 , div ] # Where h1 and div are also lists also containing lists def listGen ( l , hObj ) : # Where hObj is a BS4 object and l is a sorted lists containing direct children to the html tag z = [ ] for... | Using BeautifulSoup 4 and recursion to capture the structure of HTML nested tags |
Python | How do I highlight python code in my Rnw files ( LaTeX files ) ? I 'm using RStudio 's `` Compile PDF '' function to run pdflatex.There are two related questions ( Q1 , Q2 ) for markdown files , but this questions is specific to Rnw files.Example : | \documentclass { article } \begin { document } < < > > =print ( `` This is R '' ) @ < < engine='python ' > > =print `` This is python '' @ \end { document } | Python syntax highlighting in LaTeX in Rstudio with knitR |
Python | I 'm trying to group values in a few csv files into bins that are in an XML file ( groups.xml ) . I have the following code that works to a certain extent but does n't give what I 'm expecting : Current output : with an error : Expected output : | import os , sysimport globimport pandas as pdimport xml.etree.cElementTree as ETdef xml_parse ( ) : try : os.chdir ( `` path/to/files '' ) filename = [ file1 for file1 in glob.glob ( `` *.csv '' ) ] filename = [ i.split ( ' . ' , 1 ) [ 0 ] for i in filename ] # filename = '\n'.join ( filename ) os.chdir ( '.. ' ) outpu... | Grouping values using pandas cut |
Python | I have a list of lists in Python like the following : I want to remove all the inner lists that are a superset ( a list that contain all the elements of another list , but with additional elements ) of another inner list . For the example above , removing the supersets should result in the following : How can I accompl... | [ [ 1,2,3 ] , [ 2,3 ] , [ 2,4,3 ] , [ 4,5 ] , [ 5 ] ] [ [ 2,3 ] , [ 5 ] ] | How can you remove superset lists from a list of lists in Python ? |
Python | The following does n't work for some reason : Is there a way to do this , or is my only alternative to resort to some kind of metaclass trickery ? | > > > class foo ( object ) : ... @ property ... @ classmethod ... def bar ( cls ) : ... return `` asdf '' ... > > > foo.bar < property object at 0x1da8d0 > > > > foo.bar + '\n'Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : unsupported operand type ( s ) for + : 'property... | Is there any way to create a class property in Python ? |
Python | I 'm working with 3D pointcloud of Lidar . The points are given by numpy array that looks like this : I 'd like to keep my data grouped into cubes of size 50*50*50 so that every cube preserves some hashable index and numpy indices of my points it contains . In order to get splitting , I assign cubes = points \\ 50 whic... | points = np.array ( [ [ 61651921 , 416326074 , 39805 ] , [ 61605255 , 416360555 , 41124 ] , [ 61664810 , 416313743 , 39900 ] , [ 61664837 , 416313749 , 39910 ] , [ 61674456 , 416316663 , 39503 ] , [ 61651933 , 416326074 , 39802 ] , [ 61679969 , 416318049 , 39500 ] , [ 61674494 , 416316677 , 39508 ] , [ 61651908 , 41632... | What is the fastest way to map group names of numpy array to indices ? |
Python | I have a data frame ( sample , not real ) : df = Now I want to fill NaN values with previous couple ( ! ! ! ) values of row ( fill Nan with left existing couple of numbers and apply to the whole row ) and apply this to the whole dataset.There are a lot of answers concerning filling the columns . But inthis case I need ... | A B C D E F 0 3 4 NaN NaN NaN NaN 1 9 8 NaN NaN NaN NaN 2 5 9 4 7 NaN NaN 3 5 7 6 3 NaN NaN 4 2 6 4 3 NaN NaN A B C D E F 0 3 4 3 4 3 4 1 9 8 9 8 9 8 2 5 9 4 7 4 7 3 5 7 6 3 6 3 4 2 6 4 3 4 3 | Fill NaN based on previous value of row |
Python | When calling IPython.embed ( ) is it possible to give it a command or magic function to run after embeding happens . I would like to run something like this My current workaround is to copy the command string to the clipboard , spawn a background thread which sends keystrokes % paste followed by enter to the current wi... | import IPythonIPython.embed ( command= ' % pylab qt4 ' ) | Can you specify a command to run after you embed into IPython ? |
Python | As mathematical concepts , I am well aware of what inf and nan actually are . But what I am really interested in is how they are implemented in programming languages.In python , I can use inf and nan in arithmetic and conditional expressions , like this : This would lead me to believe that python internally has a speci... | > > > nan = float ( 'nan ' ) > > > inf = float ( 'inf ' ) > > > 1 + infinf > > > inf + infinf > > > inf - infnan > > > inf == infTrue > > > nan == nanFalse | How are Inf and NaN implemented ? |
Python | I have three lists X , Y , Z as follows : I am trying to remove both duplicated set of values at the same index of the lists get a reduced list as follows , all three list will always have the same length initially and at the end as well : I tried using the zip ( X , Y , Z ) function but I ca n't index it and the dict.... | X : [ 1 , 1 , 2 , 3 , 4 , 5 , 5 , 5 ] Y : [ 3 , 3 , 2 , 6 , 7 , 1 , 1 , 2 ] Z : [ 0 , 0 , 1 , 1 , 2 , 3 , 3 , 4 ] X : [ 2 , 3 , 4 , 5 ] Y : [ 2 , 6 , 7 , 2 ] Z : [ 1 , 1 , 2 , 4 ] | Remove both duplicates in multiple lists python |
Python | I 've always liked Python'sso you can then just use bhn.thing rather than the considerably more verbose big_honkin_name.thing in your source.I 've seen two type of namespace use in C++ code , either : ( which I 'm assured is a bad thing ) or : Is there a way to get Python functionality in C++ code , something like : | import big_honkin_name as bhn using namespace big_honkin_name ; // includes fn ( ) .int a = fn ( 27 ) ; int a = big_honkin_name : :fn ( 27 ) ; alias namespace big_honkin_name as bhn ; int a = bhn : :fn ( 27 ) ; | Is there an C++ equivalent to Python 's `` import bigname as b '' ? |
Python | I am trying to figure out how I will use the label information of my dataset with Generative Adversarial Networks . I am trying to use the following implementation of conditional GANs that can be found here . My dataset contains two different image domains ( real objects and sketches ) with common class information ( c... | def discriminator_loss ( y_true , y_pred ) : BATCH_SIZE=100 return K.mean ( K.binary_crossentropy ( K.flatten ( y_pred ) , K.concatenate ( [ K.ones_like ( K.flatten ( y_pred [ : BATCH_SIZE , : , : , : ] ) ) , K.zeros_like ( K.flatten ( y_pred [ : BATCH_SIZE , : , : , : ] ) ) ] ) ) , axis=-1 ) def discriminator_on_gener... | Add class information to keras network |
Python | I 'm trying to scrape nature.com to perform some analysis on journal articles . When I execute the following : I expect Beautifulsoup to print `` 25 '' ( the number of search results ) 10 times ( one for every page ) but it does n't . Instead , it prints : Looking at the html source shows that there should be 25 result... | import requestsfrom bs4 import BeautifulSoupimport requery = `` http : //www.nature.com/search ? journal=nature & order=date_desc '' for page in range ( 1 , 10 ) : req = requests.get ( query + `` & page= '' + str ( page ) ) soup = BeautifulSoup ( req.text ) cards = soup.findAll ( `` li '' , `` mb20 card cleared '' ) ma... | Beautifulsoup Can not FindAll |
Python | This is the python code to check if the recording works fine : It works fine till here..Now I have to check in the physical device , whether the recording is actually present or not..I have to go to the device File Manager , to check for the presence of the recorded audio ( recording.mp3 ) How can I write the test case... | def setUp ( self ) : '' Setup for the test '' desired_caps = { } desired_caps [ 'browserName ' ] = '' desired_caps [ 'platformName ' ] = 'Android ' desired_caps [ 'platformVersion ' ] = ' 4.4.2 ' desired_caps [ 'deviceName ' ] = 'd65d04425101de ' # Returns abs path relative to this file and not cwd desired_caps [ 'app ... | Functional test of an android app using appium and python |
Python | I 'm trying to generate a large PDF using a Flask application . The pdf generation involves generating ten long pdfs , and then merging them together . The application runs using Gunicorn with the flags : -- worker-class gevent -- workers 2.Here 's what my server-side code looks like : The client side code looks like :... | @ app.route ( '/pdf/create ' , methods= [ 'POST ' , 'GET ' ] ) def create_pdf ( ) : def generate ( ) : for section in pdfs : yield `` data : Generating % s pdf\n\n '' % section # Generate pdf with pisa ( takes up to 2 minutes ) yield `` data : Merging PDFs\n\n '' # Merge pdfs ( takes up to 2 minutes ) yield `` data : /... | Loading an eventstream through Gunicorn + Flask |
Python | In Python , it is easy to break an n-long list into k-size chunks if n is a multiple of k ( IOW , n % k == 0 ) . Here 's my favorite approach ( straight from the docs ) : ( The trick is that [ iter ( x ) ] * k produces a list of k references to the same iterator , as returned by iter ( x ) . Then zip generates each chu... | > > > k = 3 > > > n = 5 * k > > > x = range ( k * 5 ) > > > zip ( * [ iter ( x ) ] * k ) [ ( 0 , 1 , 2 ) , ( 3 , 4 , 5 ) , ( 6 , 7 , 8 ) , ( 9 , 10 , 11 ) , ( 12 , 13 , 14 ) ] > > > zip ( * [ iter ( x ) ] * ( k + 1 ) ) [ ( 0 , 1 , 2 , 3 ) , ( 4 , 5 , 6 , 7 ) , ( 8 , 9 , 10 , 11 ) ] > > > map ( None , * [ iter ( x ) ] *... | Simple idiom to break an n-long list into k-long chunks , when n % k > 0 ? |
Python | I am trying to use surface.blits with the area parameter to improve the performance of my code . When I use the area parameter for blits , I run into the following error : SystemError : < 'method 'blits ' of 'pygame.Surface ' objects > returned a result with an error set.If I remove the area parameter , blits work as I... | import sysimport randomimport pygamepygame.init ( ) tilemap = pygame.image.load ( 'pattern.jpg ' ) tilesize = 64size = 4w , h = size*64 , size*64screen = pygame.display.set_mode ( ( w , h ) ) while True : screen.fill ( ( 0 , 0 , 0 ) ) for event in pygame.event.get ( ) : if event.type == pygame.QUIT : sys.exit ( ) blit_... | pygame surface.blits when using area argument |
Python | Let 's have a class that has function that fails from time to time but after some actions it just works perfectly.Real life example would be Mysql Query that raises _mysql_exceptions.OperationalError : ( 2006 , 'MySQL server has gone away ' ) but after client reconnection it works fine.I 've tried to write decorator fo... | def _auto_reconnect_wrapper ( func ) : `` ' Tries to reconnects dead connection `` ' def inner ( self , *args , _retry=True , **kwargs ) : try : return func ( self , *args , **kwargs ) except Mysql.My.OperationalError as e : # No retry ? Rethrow if not _retry : raise # Handle server connection errors only # http : //de... | Generator recovery using decorator |
Python | I have list of dictionaries . These dictionaries basically have just one key-value each.For example : I am trying to divide the list of dictionaries lst into sublists after every occurrence of a dictionary with a specific key `` a '' . I tried using other ways that I saw on the internet but as I am new to python , I am... | lst = [ { ' x ' : 23 } , { ' y ' : 23432 } , { ' z ' : 78451 } , { ' a ' : 564 } , { ' x ' : 45 } , { ' y ' : 7546 } , { ' a ' : 4564 } , { ' x ' : 54568 } , { ' y ' : 4515 } , { ' z ' : 78457 } , { ' b ' : 5467 } , { ' a ' : 784 } ] final_lst = [ [ { ' x ' : 23 } , { ' y ' : 23432 } , { ' z ' : 78451 } , { ' a ' : 564... | Splitting list of dictionary into sublists after the occurence of particular key of dictionary |
Python | In a pandas dataframe I have a column that looks like : I need to group all the value where the first elements are E , M , or L and then , for each group , I need to create a subgroup where the index is 1 , 2 , or 3 which will contain a record for each lowercase letter ( a , b , c , ... ) Potentially the solution shoul... | 0 M1 E2 L3 M.14 M.25 M.36 E.17 E.28 E.39 E.410 L.111 L.212 M.1.a13 M.1.b14 M.1.c15 M.2.a16 M.3.a17 E.1.a18 E.1.b19 E.1.c20 E.2.a21 E.3.a22 E.3.b23 E.4.a 0 1 2E 1 a b c 2 a 3 a b 4 aL 1 2M 1 a b c 2 a 3 a df.groupby ( [ 0,1,2 ] ) .count ( ) df [ 2 ] [ ( df [ 0 ] == ' L ' ) & ( df [ 2 ] .isnull ( ) ) & ( df [ 1 ] .notnul... | pandas groupby operation with missing data |
Python | I have tried to write the following code , I am trying to write a code in Python 3.7 that just opens a web browser and the website fed to it in the Command Line : Example.pyI have entered the following command in the cmd : And I have the following traceback : I am very new to Python . This is my first code here . I am ... | import sysfrom mechanize import Browserbrowser = Browser ( ) browser.set_handle_equiv ( True ) browser.set_handle_gzip ( True ) browser.set_handle_redirect ( True ) browser.set_handle_referer ( True ) browser.set_handle_robots ( False ) # pretend you are a real browserbrowser.addheaders = [ ( 'Mozilla/5.0 ( Windows NT ... | Mechanize : too many values to unpack ( expected 2 ) |
Python | I sometimes use embed at a certain point in a script to quickly flesh out some local functionality . Minimal example : Developing a local function often requires a new import . However , importing a module in the IPython session does not seem to work , when used in a function . For instance : This is rather confusing ,... | # ! /usr/bin/env python # ... import IPythonIPython.embed ( ) In [ 1 ] : import osIn [ 2 ] : def local_func ( ) : return os.path.sepIn [ 3 ] : local_func ( ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -NameError Traceback ( most recent call last ) < ip... | How to make imports / closures work from IPython 's embed ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.