code_tokens
stringlengths
60
3.94k
label
int64
0
1
doc
stringlengths
16
98
docstring_tokens
stringlengths
0
1.41k
idx
stringlengths
13
17
code
stringlengths
87
6.4k
def popup ( self , title , callfn , initialdir = None ) : super ( DirectorySelection , self ) . popup ( title , callfn , initialdir )
1
tkinter folder chooser python
Let user select a directory .
cosqa-train-14700
def popup(self, title, callfn, initialdir=None): """Let user select a directory.""" super(DirectorySelection, self).popup(title, callfn, initialdir)
def _match_literal ( self , a , b = None ) : return a . lower ( ) == b if not self . case_sensitive else a == b
1
python check string match without letter case
Match two names .
cosqa-train-14701
def _match_literal(self, a, b=None): """Match two names.""" return a.lower() == b if not self.case_sensitive else a == b
def closing_plugin ( self , cancelable = False ) : self . dialog_manager . close_all ( ) self . shell . exit_interpreter ( ) return True
1
tkinter python gui exit button not working
Perform actions before parent main window is closed
cosqa-train-14702
def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" self.dialog_manager.close_all() self.shell.exit_interpreter() return True
def is_readable ( filename ) : return os . path . isfile ( filename ) and os . access ( filename , os . R_OK )
1
python check that can open file
Check if file is a regular file and is readable .
cosqa-train-14703
def is_readable(filename): """Check if file is a regular file and is readable.""" return os.path.isfile(filename) and os.access(filename, os.R_OK)
def is_connected ( self ) : try : return self . socket is not None and self . socket . getsockname ( ) [ 1 ] != 0 and BaseTransport . is_connected ( self ) except socket . error : return False
1
to test if the connection is made to python
Return true if the socket managed by this connection is connected
cosqa-train-14704
def is_connected(self): """ Return true if the socket managed by this connection is connected :rtype: bool """ try: return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self) except socket.error: return False
def is_timestamp ( obj ) : return isinstance ( obj , datetime . datetime ) or is_string ( obj ) or is_int ( obj ) or is_float ( obj )
0
python check type equals datetime
Yaml either have automatically converted it to a datetime object or it is a string that will be validated later .
cosqa-train-14705
def is_timestamp(obj): """ Yaml either have automatically converted it to a datetime object or it is a string that will be validated later. """ return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)
def count_words ( file ) : c = Counter ( ) with open ( file , 'r' ) as f : for l in f : words = l . strip ( ) . split ( ) c . update ( words ) return c
1
tokenize sentence python and count the words
Counts the word frequences in a list of sentences .
cosqa-train-14706
def count_words(file): """ Counts the word frequences in a list of sentences. Note: This is a helper function for parallel execution of `Vocabulary.from_text` method. """ c = Counter() with open(file, 'r') as f: for l in f: words = l.strip().split() c.update(words) return c
def isreal ( obj ) : return ( ( obj is not None ) and ( not isinstance ( obj , bool ) ) and isinstance ( obj , ( int , float ) ) )
1
python check type of object in method
Test if the argument is a real number ( float or integer ) .
cosqa-train-14707
def isreal(obj): """ Test if the argument is a real number (float or integer). :param obj: Object :type obj: any :rtype: boolean """ return ( (obj is not None) and (not isinstance(obj, bool)) and isinstance(obj, (int, float)) )
def __run ( self ) : sys . settrace ( self . globaltrace ) self . __run_backup ( ) self . run = self . __run_backup
1
tracing python code execution
Hacked run function which installs the trace .
cosqa-train-14708
def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup
def validate_email ( email ) : from django . core . validators import validate_email from django . core . exceptions import ValidationError try : validate_email ( email ) return True except ValidationError : return False
1
python check valid email
Validates an email address Source : Himanshu Shankar ( https : // github . com / iamhssingh ) Parameters ---------- email : str
cosqa-train-14709
def validate_email(email): """ Validates an email address Source: Himanshu Shankar (https://github.com/iamhssingh) Parameters ---------- email: str Returns ------- bool """ from django.core.validators import validate_email from django.core.exceptions import ValidationError try: validate_email(email) return True except ValidationError: return False
def irecarray_to_py ( a ) : pytypes = [ pyify ( typestr ) for name , typestr in a . dtype . descr ] def convert_record ( r ) : return tuple ( [ converter ( value ) for converter , value in zip ( pytypes , r ) ] ) return ( convert_record ( r ) for r in a )
1
transform types in array python
Slow conversion of a recarray into a list of records with python types .
cosqa-train-14710
def irecarray_to_py(a): """Slow conversion of a recarray into a list of records with python types. Get the field names from :attr:`a.dtype.names`. :Returns: iterator so that one can handle big input arrays """ pytypes = [pyify(typestr) for name,typestr in a.dtype.descr] def convert_record(r): return tuple([converter(value) for converter, value in zip(pytypes,r)]) return (convert_record(r) for r in a)
def is_image ( filename ) : # note: isfile() also accepts symlinks return os . path . isfile ( filename ) and filename . lower ( ) . endswith ( ImageExts )
1
python check whether a file is an image
Determine if given filename is an image .
cosqa-train-14711
def is_image(filename): """Determine if given filename is an image.""" # note: isfile() also accepts symlinks return os.path.isfile(filename) and filename.lower().endswith(ImageExts)
def _encode_gif ( images , fps ) : writer = WholeVideoWriter ( fps ) writer . write_multi ( images ) return writer . finish ( )
1
transforma each frame of gif into jpg python
Encodes numpy images into gif string .
cosqa-train-14712
def _encode_gif(images, fps): """Encodes numpy images into gif string. Args: images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape `[time, height, width, channels]` where `channels` is 1 or 3. fps: frames per second of the animation Returns: The encoded gif string. Raises: IOError: If the ffmpeg command returns an error. """ writer = WholeVideoWriter(fps) writer.write_multi(images) return writer.finish()
def num_leaves ( tree ) : if tree . is_leaf : return 1 else : return num_leaves ( tree . left_child ) + num_leaves ( tree . right_child )
1
tree get number of nodes python
Determine the number of leaves in a tree
cosqa-train-14713
def num_leaves(tree): """Determine the number of leaves in a tree""" if tree.is_leaf: return 1 else: return num_leaves(tree.left_child) + num_leaves(tree.right_child)
def _pip_exists ( self ) : return os . path . isfile ( os . path . join ( self . path , 'bin' , 'pip' ) )
1
python checking virtualenv location
Returns True if pip exists inside the virtual environment . Can be used as a naive way to verify that the environment is installed .
cosqa-train-14714
def _pip_exists(self): """Returns True if pip exists inside the virtual environment. Can be used as a naive way to verify that the environment is installed.""" return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def _crop_list_to_size ( l , size ) : for x in range ( size - len ( l ) ) : l . append ( False ) for x in range ( len ( l ) - size ) : l . pop ( ) return l
1
truncate list size python
Make a list a certain size
cosqa-train-14715
def _crop_list_to_size(l, size): """Make a list a certain size""" for x in range(size - len(l)): l.append(False) for x in range(len(l) - size): l.pop() return l
def duplicated_rows ( df , col_name ) : _check_cols ( df , [ col_name ] ) dups = df [ pd . notnull ( df [ col_name ] ) & df . duplicated ( subset = [ col_name ] ) ] return dups
1
python chekc duplicate columns in dataset
Return a DataFrame with the duplicated values of the column col_name in df .
cosqa-train-14716
def duplicated_rows(df, col_name): """ Return a DataFrame with the duplicated values of the column `col_name` in `df`.""" _check_cols(df, [col_name]) dups = df[pd.notnull(df[col_name]) & df.duplicated(subset=[col_name])] return dups
def delimited ( items , character = '|' ) : return '|' . join ( items ) if type ( items ) in ( list , tuple , set ) else items
0
turn a list of characters into a string python
Returns a character delimited version of the provided list as a Python string
cosqa-train-14717
def delimited(items, character='|'): """Returns a character delimited version of the provided list as a Python string""" return '|'.join(items) if type(items) in (list, tuple, set) else items
def is_image ( filename ) : # note: isfile() also accepts symlinks return os . path . isfile ( filename ) and filename . lower ( ) . endswith ( ImageExts )
0
python chekcing if file is an image
Determine if given filename is an image .
cosqa-train-14718
def is_image(filename): """Determine if given filename is an image.""" # note: isfile() also accepts symlinks return os.path.isfile(filename) and filename.lower().endswith(ImageExts)
def list2dict ( lst ) : dic = { } for k , v in lst : dic [ k ] = v return dic
1
turn a list of list into dictionary python
Takes a list of ( key value ) pairs and turns it into a dict .
cosqa-train-14719
def list2dict(lst): """Takes a list of (key,value) pairs and turns it into a dict.""" dic = {} for k,v in lst: dic[k] = v return dic
def closeEvent ( self , e ) : self . emit ( 'close_widget' ) super ( DockWidget , self ) . closeEvent ( e )
1
python child widget close signal
Qt slot when the window is closed .
cosqa-train-14720
def closeEvent(self, e): """Qt slot when the window is closed.""" self.emit('close_widget') super(DockWidget, self).closeEvent(e)
def time_string ( seconds ) : s = int ( round ( seconds ) ) # round to nearest second h , s = divmod ( s , 3600 ) # get hours and remainder m , s = divmod ( s , 60 ) # split remainder into minutes and seconds return "%2i:%02i:%02i" % ( h , m , s )
1
turn seconds into hours minutes python
Returns time in seconds as a string formatted HHHH : MM : SS .
cosqa-train-14721
def time_string(seconds): """Returns time in seconds as a string formatted HHHH:MM:SS.""" s = int(round(seconds)) # round to nearest second h, s = divmod(s, 3600) # get hours and remainder m, s = divmod(s, 60) # split remainder into minutes and seconds return "%2i:%02i:%02i" % (h, m, s)
def close_database_session ( session ) : try : session . close ( ) except OperationalError as e : raise DatabaseError ( error = e . orig . args [ 1 ] , code = e . orig . args [ 0 ] )
1
python close database connection
Close connection with the database
cosqa-train-14722
def close_database_session(session): """Close connection with the database""" try: session.close() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
def load_files ( files ) : for py_file in files : LOG . debug ( "exec %s" , py_file ) execfile ( py_file , globals ( ) , locals ( ) )
1
turning python files into executables
Load and execute a python file .
cosqa-train-14723
def load_files(files): """Load and execute a python file.""" for py_file in files: LOG.debug("exec %s", py_file) execfile(py_file, globals(), locals())
def close ( self ) : if not self . _closed : self . __flush ( ) object . __setattr__ ( self , "_closed" , True )
1
python close flush object
Flush the file and close it .
cosqa-train-14724
def close(self): """Flush the file and close it. A closed file cannot be written any more. Calling :meth:`close` more than once is allowed. """ if not self._closed: self.__flush() object.__setattr__(self, "_closed", True)
def isnumber ( * args ) : return all ( map ( lambda c : isinstance ( c , int ) or isinstance ( c , float ) , args ) )
1
typehint param python multiple types
Checks if value is an integer long integer or float .
cosqa-train-14725
def isnumber(*args): """Checks if value is an integer, long integer or float. NOTE: Treats booleans as numbers, where True=1 and False=0. """ return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))
def socket_close ( self ) : if self . sock != NC . INVALID_SOCKET : self . sock . close ( ) self . sock = NC . INVALID_SOCKET
1
python closing socket connection early
Close our socket .
cosqa-train-14726
def socket_close(self): """Close our socket.""" if self.sock != NC.INVALID_SOCKET: self.sock.close() self.sock = NC.INVALID_SOCKET
def _get_local_ip ( ) : return set ( [ x [ 4 ] [ 0 ] for x in socket . getaddrinfo ( socket . gethostname ( ) , 80 , socket . AF_INET ) ] ) . pop ( )
1
ubuntu python local ip
Get the local ip of this device
cosqa-train-14727
def _get_local_ip(): """ Get the local ip of this device :return: Ip of this computer :rtype: str """ return set([x[4][0] for x in socket.getaddrinfo( socket.gethostname(), 80, socket.AF_INET )]).pop()
def lin_interp ( x , rangeX , rangeY ) : s = ( x - rangeX [ 0 ] ) / mag ( rangeX [ 1 ] - rangeX [ 0 ] ) y = rangeY [ 0 ] * ( 1 - s ) + rangeY [ 1 ] * s return y
1
python co2 concentertion interpolate exmple
Interpolate linearly variable x in rangeX onto rangeY .
cosqa-train-14728
def lin_interp(x, rangeX, rangeY): """ Interpolate linearly variable x in rangeX onto rangeY. """ s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0]) y = rangeY[0] * (1 - s) + rangeY[1] * s return y
def checkbox_uncheck ( self , force_check = False ) : if self . get_attribute ( 'checked' ) : self . click ( force_click = force_check )
1
uncheck checkbox python tkinter
Wrapper to uncheck a checkbox
cosqa-train-14729
def checkbox_uncheck(self, force_check=False): """ Wrapper to uncheck a checkbox """ if self.get_attribute('checked'): self.click(force_click=force_check)
def median ( data ) : data . sort ( ) num_values = len ( data ) half = num_values // 2 if num_values % 2 : return data [ half ] return 0.5 * ( data [ half - 1 ] + data [ half ] )
0
python code for median from even numbered list
Calculate the median of a list .
cosqa-train-14730
def median(data): """Calculate the median of a list.""" data.sort() num_values = len(data) half = num_values // 2 if num_values % 2: return data[half] return 0.5 * (data[half-1] + data[half])
def isTestCaseDisabled ( test_case_class , method_name ) : test_method = getattr ( test_case_class , method_name ) return getattr ( test_method , "__test__" , 'not nose' ) is False
1
unit test to disable python
I check to see if a method on a TestCase has been disabled via nose s convention for disabling a TestCase . This makes it so that users can mix nose s parameterized tests with green as a runner .
cosqa-train-14731
def isTestCaseDisabled(test_case_class, method_name): """ I check to see if a method on a TestCase has been disabled via nose's convention for disabling a TestCase. This makes it so that users can mix nose's parameterized tests with green as a runner. """ test_method = getattr(test_case_class, method_name) return getattr(test_method, "__test__", 'not nose') is False
def set_cursor_position ( self , position ) : position = self . get_position ( position ) cursor = self . textCursor ( ) cursor . setPosition ( position ) self . setTextCursor ( cursor ) self . ensureCursorVisible ( )
1
python code for moving cursor without user intervention
Set cursor position
cosqa-train-14732
def set_cursor_position(self, position): """Set cursor position""" position = self.get_position(position) cursor = self.textCursor() cursor.setPosition(position) self.setTextCursor(cursor) self.ensureCursorVisible()
def test ( ctx , all = False , verbose = False ) : cmd = 'tox' if all else 'py.test' if verbose : cmd += ' -v' return ctx . run ( cmd , pty = True ) . return_code
1
unittest python3 run a single test
Run the tests .
cosqa-train-14733
def test(ctx, all=False, verbose=False): """Run the tests.""" cmd = 'tox' if all else 'py.test' if verbose: cmd += ' -v' return ctx.run(cmd, pty=True).return_code
def get_selected_values ( self , selection ) : return [ v for b , v in self . _choices if b & selection ]
1
python code for selection list s
Return a list of values for the given selection .
cosqa-train-14734
def get_selected_values(self, selection): """Return a list of values for the given selection.""" return [v for b, v in self._choices if b & selection]
def __call__ ( self , actual_value , expect ) : self . _expect = expect if self . expected_value is NO_ARG : return self . asserts ( actual_value ) return self . asserts ( actual_value , self . expected_value )
1
unittesting python assert a function is called
Main entry point for assertions ( called by the wrapper ) . expect is a function the wrapper class uses to assert a given match .
cosqa-train-14735
def __call__(self, actual_value, expect): """Main entry point for assertions (called by the wrapper). expect is a function the wrapper class uses to assert a given match. """ self._expect = expect if self.expected_value is NO_ARG: return self.asserts(actual_value) return self.asserts(actual_value, self.expected_value)
def save_excel ( self , fd ) : from pylon . io . excel import ExcelWriter ExcelWriter ( self ) . write ( fd )
0
python code to access an excel file and write to it
Saves the case as an Excel spreadsheet .
cosqa-train-14736
def save_excel(self, fd): """ Saves the case as an Excel spreadsheet. """ from pylon.io.excel import ExcelWriter ExcelWriter(self).write(fd)
def set_global ( node : Node , key : str , value : Any ) : node . node_globals [ key ] = value
0
update global vars in def python
Adds passed value to node s globals
cosqa-train-14737
def set_global(node: Node, key: str, value: Any): """Adds passed value to node's globals""" node.node_globals[key] = value
def is_valid_file ( parser , arg ) : arg = os . path . abspath ( arg ) if not os . path . exists ( arg ) : parser . error ( "The file %s does not exist!" % arg ) else : return arg
1
python code to check if file doesnot exisits
Check if arg is a valid file that already exists on the file system .
cosqa-train-14738
def is_valid_file(parser, arg): """Check if arg is a valid file that already exists on the file system.""" arg = os.path.abspath(arg) if not os.path.exists(arg): parser.error("The file %s does not exist!" % arg) else: return arg
def update ( self , params ) : dev_info = self . json_state . get ( 'deviceInfo' ) dev_info . update ( { k : params [ k ] for k in params if dev_info . get ( k ) } )
1
update the value inside json python
Update the dev_info data from a dictionary .
cosqa-train-14739
def update(self, params): """Update the dev_info data from a dictionary. Only updates if it already exists in the device. """ dev_info = self.json_state.get('deviceInfo') dev_info.update({k: params[k] for k in params if dev_info.get(k)})
def _begins_with_one_of ( sentence , parts_of_speech ) : doc = nlp ( sentence ) if doc [ 0 ] . tag_ in parts_of_speech : return True return False
1
python code to check if first sentence contains pronoun tag
Return True if the sentence or fragment begins with one of the parts of speech in the list else False
cosqa-train-14740
def _begins_with_one_of(sentence, parts_of_speech): """Return True if the sentence or fragment begins with one of the parts of speech in the list, else False""" doc = nlp(sentence) if doc[0].tag_ in parts_of_speech: return True return False
def rest_put_stream ( self , url , stream , headers = None , session = None , verify = True , cert = None ) : res = session . put ( url , headers = headers , data = stream , verify = verify , cert = cert ) return res . text , res . status_code
1
uploading a file with python http put
Perform a chunked PUT request to url with requests . session This is specifically to upload files .
cosqa-train-14741
def rest_put_stream(self, url, stream, headers=None, session=None, verify=True, cert=None): """ Perform a chunked PUT request to url with requests.session This is specifically to upload files. """ res = session.put(url, headers=headers, data=stream, verify=verify, cert=cert) return res.text, res.status_code
def EvalBinomialPmf ( k , n , p ) : return scipy . stats . binom . pmf ( k , n , p )
1
python code to compute the probability of even using pmf
Evaluates the binomial pmf .
cosqa-train-14742
def EvalBinomialPmf(k, n, p): """Evaluates the binomial pmf. Returns the probabily of k successes in n trials with probability p. """ return scipy.stats.binom.pmf(k, n, p)
def get_url_nofollow ( url ) : try : response = urlopen ( url ) code = response . getcode ( ) return code except HTTPError as e : return e . code except : return 0
1
urlopen get status code python3 getcode
function to get return code of a url
cosqa-train-14743
def get_url_nofollow(url): """ function to get return code of a url Credits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/ """ try: response = urlopen(url) code = response.getcode() return code except HTTPError as e: return e.code except: return 0
def energy_string_to_float ( string ) : energy_re = re . compile ( "(-?\d+\.\d+)" ) return float ( energy_re . match ( string ) . group ( 0 ) )
1
python code to extract float number from given string
Convert a string of a calculation energy e . g . - 1 . 2345 eV to a float .
cosqa-train-14744
def energy_string_to_float( string ): """ Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float. Args: string (str): The string to convert. Return (float) """ energy_re = re.compile( "(-?\d+\.\d+)" ) return float( energy_re.match( string ).group(0) )
def compare ( a , b ) : s = 0 for i in range ( len ( a ) ) : s = s + abs ( a [ i ] - b [ i ] ) return s
0
use array 1 to compare to array 2 in python
Compare items in 2 arrays . Returns sum ( abs ( a ( i ) - b ( i )))
cosqa-train-14745
def compare(a, b): """ Compare items in 2 arrays. Returns sum(abs(a(i)-b(i))) """ s=0 for i in range(len(a)): s=s+abs(a[i]-b[i]) return s
def hflip ( img ) : if not _is_pil_image ( img ) : raise TypeError ( 'img should be PIL Image. Got {}' . format ( type ( img ) ) ) return img . transpose ( Image . FLIP_LEFT_RIGHT )
1
python code to flip an image vertically
Horizontally flip the given PIL Image .
cosqa-train-14746
def hflip(img): """Horizontally flip the given PIL Image. Args: img (PIL Image): Image to be flipped. Returns: PIL Image: Horizontall flipped image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) return img.transpose(Image.FLIP_LEFT_RIGHT)
def ex ( self , cmd ) : with self . builtin_trap : exec cmd in self . user_global_ns , self . user_ns
0
use function from outer scope in inner scope python
Execute a normal python statement in user namespace .
cosqa-train-14747
def ex(self, cmd): """Execute a normal python statement in user namespace.""" with self.builtin_trap: exec cmd in self.user_global_ns, self.user_ns
def get_creation_datetime ( filepath ) : if platform . system ( ) == 'Windows' : return datetime . fromtimestamp ( os . path . getctime ( filepath ) ) else : stat = os . stat ( filepath ) try : return datetime . fromtimestamp ( stat . st_birthtime ) except AttributeError : # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. return None
1
python code to get the date of creation of file
Get the date that a file was created .
cosqa-train-14748
def get_creation_datetime(filepath): """ Get the date that a file was created. Parameters ---------- filepath : str Returns ------- creation_datetime : datetime.datetime or None """ if platform.system() == 'Windows': return datetime.fromtimestamp(os.path.getctime(filepath)) else: stat = os.stat(filepath) try: return datetime.fromtimestamp(stat.st_birthtime) except AttributeError: # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. return None
def _fill_array_from_list ( the_list , the_array ) : for i , val in enumerate ( the_list ) : the_array [ i ] = val return the_array
1
use function return values to fill array in python
Fill an array from a list
cosqa-train-14749
def _fill_array_from_list(the_list, the_array): """Fill an `array` from a `list`""" for i, val in enumerate(the_list): the_array[i] = val return the_array
def _sort_lambda ( sortedby = 'cpu_percent' , sortedby_secondary = 'memory_percent' ) : ret = None if sortedby == 'io_counters' : ret = _sort_io_counters elif sortedby == 'cpu_times' : ret = _sort_cpu_times return ret
0
use lambda function in python for sorting
Return a sort lambda function for the sortedbykey
cosqa-train-14750
def _sort_lambda(sortedby='cpu_percent', sortedby_secondary='memory_percent'): """Return a sort lambda function for the sortedbykey""" ret = None if sortedby == 'io_counters': ret = _sort_io_counters elif sortedby == 'cpu_times': ret = _sort_cpu_times return ret
def sample_colormap ( cmap_name , n_samples ) : colors = [ ] colormap = cm . cmap_d [ cmap_name ] for i in np . linspace ( 0 , 1 , n_samples ) : colors . append ( colormap ( i ) ) return colors
0
python color maps for matlab
Sample a colormap from matplotlib
cosqa-train-14751
def sample_colormap(cmap_name, n_samples): """ Sample a colormap from matplotlib """ colors = [] colormap = cm.cmap_d[cmap_name] for i in np.linspace(0, 1, n_samples): colors.append(colormap(i)) return colors
def calculate_size ( name , count ) : data_size = 0 data_size += calculate_size_str ( name ) data_size += INT_SIZE_IN_BYTES return data_size
1
use len in python flask template
Calculates the request payload size
cosqa-train-14752
def calculate_size(name, count): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES return data_size
def set_color ( self , fg = None , bg = None , intensify = False , target = sys . stdout ) : raise NotImplementedError
1
python color theme dont change after calling color pallete
Set foreground - and background colors and intensity .
cosqa-train-14753
def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout): """Set foreground- and background colors and intensity.""" raise NotImplementedError
def polyline ( self , arr ) : for i in range ( 0 , len ( arr ) - 1 ) : self . line ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] , arr [ i + 1 ] [ 0 ] , arr [ i + 1 ] [ 1 ] )
1
use list to draw lines python
Draw a set of lines
cosqa-train-14754
def polyline(self, arr): """Draw a set of lines""" for i in range(0, len(arr) - 1): self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1])
def colorize ( string , color , * args , * * kwargs ) : string = string . format ( * args , * * kwargs ) return color + string + colorama . Fore . RESET
0
python colorama back and foreground color
Implements string formatting along with color specified in colorama . Fore
cosqa-train-14755
def colorize(string, color, *args, **kwargs): """ Implements string formatting along with color specified in colorama.Fore """ string = string.format(*args, **kwargs) return color + string + colorama.Fore.RESET
def multiply ( traj ) : z = traj . x * traj . y traj . f_add_result ( 'z' , z = z , comment = 'I am the product of two reals!' )
1
use product of one funtion in another python
Sophisticated simulation of multiplication
cosqa-train-14756
def multiply(traj): """Sophisticated simulation of multiplication""" z=traj.x*traj.y traj.f_add_result('z',z=z, comment='I am the product of two reals!')
def column_names ( self , table ) : table_info = self . execute ( u'PRAGMA table_info(%s)' % quote ( table ) ) return ( column [ 'name' ] for column in table_info )
1
use python to display column names in database
An iterable of column names for a particular table or view .
cosqa-train-14757
def column_names(self, table): """An iterable of column names, for a particular table or view.""" table_info = self.execute( u'PRAGMA table_info(%s)' % quote(table)) return (column['name'] for column in table_info)
def matchfieldnames ( field_a , field_b ) : normalised_a = field_a . replace ( ' ' , '_' ) . lower ( ) normalised_b = field_b . replace ( ' ' , '_' ) . lower ( ) return normalised_a == normalised_b
0
python compare optional strings case insensitive
Check match between two strings ignoring case and spaces / underscores . Parameters ---------- a : str b : str Returns ------- bool
cosqa-train-14758
def matchfieldnames(field_a, field_b): """Check match between two strings, ignoring case and spaces/underscores. Parameters ---------- a : str b : str Returns ------- bool """ normalised_a = field_a.replace(' ', '_').lower() normalised_b = field_b.replace(' ', '_').lower() return normalised_a == normalised_b
def filter_regex ( names , regex ) : return tuple ( name for name in names if regex . search ( name ) is not None )
1
use tuple pattern matching in python
Return a tuple of strings that match the regular expression pattern .
cosqa-train-14759
def filter_regex(names, regex): """ Return a tuple of strings that match the regular expression pattern. """ return tuple(name for name in names if regex.search(name) is not None)
def assert_looks_like ( first , second , msg = None ) : first = _re . sub ( "\s+" , " " , first . strip ( ) ) second = _re . sub ( "\s+" , " " , second . strip ( ) ) if first != second : raise AssertionError ( msg or "%r does not look like %r" % ( first , second ) )
1
python compare string is similar to another one
Compare two strings if all contiguous whitespace is coalesced .
cosqa-train-14760
def assert_looks_like(first, second, msg=None): """ Compare two strings if all contiguous whitespace is coalesced. """ first = _re.sub("\s+", " ", first.strip()) second = _re.sub("\s+", " ", second.strip()) if first != second: raise AssertionError(msg or "%r does not look like %r" % (first, second))
def constraint_range_dict ( self , * args , * * kwargs ) : bins = self . bins ( * args , * * kwargs ) return [ { self . name + '__gte' : a , self . name + '__lt' : b } for a , b in zip ( bins [ : - 1 ] , bins [ 1 : ] ) ] space = self . space ( * args , * * kwargs ) resolution = space [ 1 ] - space [ 0 ] return [ { self . name + '__gte' : s , self . name + '__lt' : s + resolution } for s in space ]
0
using a factors of a range as a dictionary index in python
Creates a list of dictionaries which each give a constraint for a certain section of the dimension .
cosqa-train-14761
def constraint_range_dict(self,*args,**kwargs): """ Creates a list of dictionaries which each give a constraint for a certain section of the dimension. bins arguments overwrites resolution """ bins = self.bins(*args,**kwargs) return [{self.name+'__gte': a,self.name+'__lt': b} for a,b in zip(bins[:-1],bins[1:])] space = self.space(*args,**kwargs) resolution = space[1] - space[0] return [{self.name+'__gte': s,self.name+'__lt': s+resolution} for s in space]
def is_equal_strings_ignore_case ( first , second ) : if first and second : return first . upper ( ) == second . upper ( ) else : return not ( first or second )
1
python compare string regardless upper
The function compares strings ignoring case
cosqa-train-14762
def is_equal_strings_ignore_case(first, second): """The function compares strings ignoring case""" if first and second: return first.upper() == second.upper() else: return not (first or second)
def Date ( value ) : from datetime import datetime try : return datetime ( * reversed ( [ int ( val ) for val in value . split ( '/' ) ] ) ) except Exception as err : raise argparse . ArgumentTypeError ( "invalid date '%s'" % value )
1
using argparser change date format from csv file in python
Custom type for managing dates in the command - line .
cosqa-train-14763
def Date(value): """Custom type for managing dates in the command-line.""" from datetime import datetime try: return datetime(*reversed([int(val) for val in value.split('/')])) except Exception as err: raise argparse.ArgumentTypeError("invalid date '%s'" % value)
def compare_dict ( da , db ) : sa = set ( da . items ( ) ) sb = set ( db . items ( ) ) diff = sa & sb return dict ( sa - diff ) , dict ( sb - diff )
1
python compare two dicts and get diff
Compare differencs from two dicts
cosqa-train-14764
def compare_dict(da, db): """ Compare differencs from two dicts """ sa = set(da.items()) sb = set(db.items()) diff = sa & sb return dict(sa - diff), dict(sb - diff)
def assert_list ( self , putative_list , expected_type = string_types , key_arg = None ) : return assert_list ( putative_list , expected_type , key_arg = key_arg , raise_type = lambda msg : TargetDefinitionException ( self , msg ) )
1
using assert with lists python
: API : public
cosqa-train-14765
def assert_list(self, putative_list, expected_type=string_types, key_arg=None): """ :API: public """ return assert_list(putative_list, expected_type, key_arg=key_arg, raise_type=lambda msg: TargetDefinitionException(self, msg))
def compare ( string1 , string2 ) : if len ( string1 ) != len ( string2 ) : return False result = True for c1 , c2 in izip ( string1 , string2 ) : result &= c1 == c2 return result
1
python compare two strings for characters in common
Compare two strings while protecting against timing attacks
cosqa-train-14766
def compare(string1, string2): """Compare two strings while protecting against timing attacks :param str string1: the first string :param str string2: the second string :returns: True if the strings are equal, False if not :rtype: :obj:`bool` """ if len(string1) != len(string2): return False result = True for c1, c2 in izip(string1, string2): result &= c1 == c2 return result
def print_display_png ( o ) : s = latex ( o , mode = 'plain' ) s = s . strip ( '$' ) # As matplotlib does not support display style, dvipng backend is # used here. png = latex_to_png ( '$$%s$$' % s , backend = 'dvipng' ) return png
1
using latex with python
A function to display sympy expression using display style LaTeX in PNG .
cosqa-train-14767
def print_display_png(o): """ A function to display sympy expression using display style LaTeX in PNG. """ s = latex(o, mode='plain') s = s.strip('$') # As matplotlib does not support display style, dvipng backend is # used here. png = latex_to_png('$$%s$$' % s, backend='dvipng') return png
def __similarity ( s1 , s2 , ngrams_fn , n = 3 ) : ngrams1 , ngrams2 = set ( ngrams_fn ( s1 , n = n ) ) , set ( ngrams_fn ( s2 , n = n ) ) matches = ngrams1 . intersection ( ngrams2 ) return 2 * len ( matches ) / ( len ( ngrams1 ) + len ( ngrams2 ) )
1
python compare two strings for percent similarity
The fraction of n - grams matching between two sequences
cosqa-train-14768
def __similarity(s1, s2, ngrams_fn, n=3): """ The fraction of n-grams matching between two sequences Args: s1: a string s2: another string n: an int for the n in n-gram Returns: float: the fraction of n-grams matching """ ngrams1, ngrams2 = set(ngrams_fn(s1, n=n)), set(ngrams_fn(s2, n=n)) matches = ngrams1.intersection(ngrams2) return 2 * len(matches) / (len(ngrams1) + len(ngrams2))
def insort_no_dup ( lst , item ) : import bisect ix = bisect . bisect_left ( lst , item ) if lst [ ix ] != item : lst [ ix : ix ] = [ item ]
1
using sort to move element in to new position in list python
If item is not in lst add item to list at its sorted position
cosqa-train-14769
def insort_no_dup(lst, item): """ If item is not in lst, add item to list at its sorted position """ import bisect ix = bisect.bisect_left(lst, item) if lst[ix] != item: lst[ix:ix] = [item]
def __complex__ ( self ) : if self . _t != 99 or self . key != [ 're' , 'im' ] : return complex ( float ( self ) ) return complex ( float ( self . re ) , float ( self . im ) )
1
python complex object is not subscriptable
Called to implement the built - in function complex () .
cosqa-train-14770
def __complex__(self): """Called to implement the built-in function complex().""" if self._t != 99 or self.key != ['re', 'im']: return complex(float(self)) return complex(float(self.re), float(self.im))
def extract_pdfminer ( self , filename , * * kwargs ) : stdout , _ = self . run ( [ 'pdf2txt.py' , filename ] ) return stdout
0
using textract python with a pdf file
Extract text from pdfs using pdfminer .
cosqa-train-14771
def extract_pdfminer(self, filename, **kwargs): """Extract text from pdfs using pdfminer.""" stdout, _ = self.run(['pdf2txt.py', filename]) return stdout
def _pdf_at_peak ( self ) : return ( self . peak - self . low ) / ( self . high - self . low )
0
python compute pdf percentile
Pdf evaluated at the peak .
cosqa-train-14772
def _pdf_at_peak(self): """Pdf evaluated at the peak.""" return (self.peak - self.low) / (self.high - self.low)
def is_valid ( number ) : n = str ( number ) if not n . isdigit ( ) : return False return int ( n [ - 1 ] ) == get_check_digit ( n [ : - 1 ] )
1
validate credit card number using string input in python
determines whether the card number is valid .
cosqa-train-14773
def is_valid(number): """determines whether the card number is valid.""" n = str(number) if not n.isdigit(): return False return int(n[-1]) == get_check_digit(n[:-1])
def items ( self , section_name ) : return [ ( k , v ) for k , v in super ( GitConfigParser , self ) . items ( section_name ) if k != '__name__' ]
0
python configparser get all keys in a section
: return : list (( option value ) ... ) pairs of all items in the given section
cosqa-train-14774
def items(self, section_name): """:return: list((option, value), ...) pairs of all items in the given section""" return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']
def validate_email ( email ) : from django . core . validators import validate_email from django . core . exceptions import ValidationError try : validate_email ( email ) return True except ValidationError : return False
0
validate email using python 3
Validates an email address Source : Himanshu Shankar ( https : // github . com / iamhssingh ) Parameters ---------- email : str
cosqa-train-14775
def validate_email(email): """ Validates an email address Source: Himanshu Shankar (https://github.com/iamhssingh) Parameters ---------- email: str Returns ------- bool """ from django.core.validators import validate_email from django.core.exceptions import ValidationError try: validate_email(email) return True except ValidationError: return False
def connect_rds ( aws_access_key_id = None , aws_secret_access_key = None , * * kwargs ) : from boto . rds import RDSConnection return RDSConnection ( aws_access_key_id , aws_secret_access_key , * * kwargs )
1
python connect to aws rds
: type aws_access_key_id : string : param aws_access_key_id : Your AWS Access Key ID
cosqa-train-14776
def connect_rds(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.rds.RDSConnection` :return: A connection to RDS """ from boto.rds import RDSConnection return RDSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)
def is_valid_file ( parser , arg ) : if not os . path . exists ( arg ) : parser . error ( "File %s not found" % arg ) else : return arg
1
validate file name not working in python
verify the validity of the given file . Never trust the End - User
cosqa-train-14777
def is_valid_file(parser,arg): """verify the validity of the given file. Never trust the End-User""" if not os.path.exists(arg): parser.error("File %s not found"%arg) else: return arg
def __connect ( ) : global redis_instance if use_tcp_socket : redis_instance = redis . StrictRedis ( host = hostname , port = port ) else : redis_instance = redis . StrictRedis ( unix_socket_path = unix_socket )
1
python connect to redis on windows
Connect to a redis instance .
cosqa-train-14778
def __connect(): """ Connect to a redis instance. """ global redis_instance if use_tcp_socket: redis_instance = redis.StrictRedis(host=hostname, port=port) else: redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)
def is_valid_file ( parser , arg ) : arg = os . path . abspath ( arg ) if not os . path . exists ( arg ) : parser . error ( "The file %s does not exist!" % arg ) else : return arg
1
validate file path in python
Check if arg is a valid file that already exists on the file system .
cosqa-train-14779
def is_valid_file(parser, arg): """Check if arg is a valid file that already exists on the file system.""" arg = os.path.abspath(arg) if not os.path.exists(arg): parser.error("The file %s does not exist!" % arg) else: return arg
def _read_stdin ( ) : line = sys . stdin . readline ( ) while line : yield line line = sys . stdin . readline ( )
1
python constantly readstdin without enter
Generator for reading from standard input in nonblocking mode .
cosqa-train-14780
def _read_stdin(): """ Generator for reading from standard input in nonblocking mode. Other ways of reading from ``stdin`` in python waits, until the buffer is big enough, or until EOF character is sent. This functions yields immediately after each line. """ line = sys.stdin.readline() while line: yield line line = sys.stdin.readline()
def read ( self ) : for line in self . io . read ( ) : with self . parse_line ( line ) as j : yield j
1
python consume json feed
Iterate over all JSON input ( Generator )
cosqa-train-14781
def read(self): """Iterate over all JSON input (Generator)""" for line in self.io.read(): with self.parse_line(line) as j: yield j
def get_code ( module ) : fp = open ( module . path ) try : return compile ( fp . read ( ) , str ( module . name ) , 'exec' ) finally : fp . close ( )
1
view compiled code of python
Compile and return a Module s code object .
cosqa-train-14782
def get_code(module): """ Compile and return a Module's code object. """ fp = open(module.path) try: return compile(fp.read(), str(module.name), 'exec') finally: fp.close()
def stringify_dict_contents ( dct ) : return { str_if_nested_or_str ( k ) : str_if_nested_or_str ( v ) for k , v in dct . items ( ) }
1
python conver dic to string
Turn dict keys and values into native strings .
cosqa-train-14783
def stringify_dict_contents(dct): """Turn dict keys and values into native strings.""" return { str_if_nested_or_str(k): str_if_nested_or_str(v) for k, v in dct.items() }
def prettyprint ( d ) : print ( json . dumps ( d , sort_keys = True , indent = 4 , separators = ( "," , ": " ) ) )
1
visualize json nest tree in python
Print dicttree in Json - like format . keys are sorted
cosqa-train-14784
def prettyprint(d): """Print dicttree in Json-like format. keys are sorted """ print(json.dumps(d, sort_keys=True, indent=4, separators=("," , ": ")))
def _parse_canonical_int64 ( doc ) : l_str = doc [ '$numberLong' ] if len ( doc ) != 1 : raise TypeError ( 'Bad $numberLong, extra field(s): %s' % ( doc , ) ) return Int64 ( l_str )
1
python conver mongo number long to int
Decode a JSON int64 to bson . int64 . Int64 .
cosqa-train-14785
def _parse_canonical_int64(doc): """Decode a JSON int64 to bson.int64.Int64.""" l_str = doc['$numberLong'] if len(doc) != 1: raise TypeError('Bad $numberLong, extra field(s): %s' % (doc,)) return Int64(l_str)
def dumped ( text , level , indent = 2 ) : return indented ( "{\n%s\n}" % indented ( text , level + 1 , indent ) or "None" , level , indent ) + "\n"
1
vs code python default indentation
Put curly brackets round an indented text
cosqa-train-14786
def dumped(text, level, indent=2): """Put curly brackets round an indented text""" return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n"
def is_int ( value ) : if isinstance ( value , bool ) : return False try : int ( value ) return True except ( ValueError , TypeError ) : return False
1
python convern int to bool
Return True if value is an integer .
cosqa-train-14787
def is_int(value): """Return `True` if ``value`` is an integer.""" if isinstance(value, bool): return False try: int(value) return True except (ValueError, TypeError): return False
def zoom_cv ( x , z ) : if z == 0 : return x r , c , * _ = x . shape M = cv2 . getRotationMatrix2D ( ( c / 2 , r / 2 ) , 0 , z + 1. ) return cv2 . warpAffine ( x , M , ( c , r ) )
0
warp perspective cv2 python
Zoom the center of image x by a factor of z + 1 while retaining the original image size and proportion .
cosqa-train-14788
def zoom_cv(x,z): """ Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion. """ if z==0: return x r,c,*_ = x.shape M = cv2.getRotationMatrix2D((c/2,r/2),0,z+1.) return cv2.warpAffine(x,M,(c,r))
def find_commons ( lists ) : others = lists [ 1 : ] return [ val for val in lists [ 0 ] if is_in_all ( val , others ) ]
1
python count common items between lists
Finds common values
cosqa-train-14789
def find_commons(lists): """Finds common values :param lists: List of lists :return: List of values that are in common between inner lists """ others = lists[1:] return [ val for val in lists[0] if is_in_all(val, others) ]
def _get_compiled_ext ( ) : for ext , mode , typ in imp . get_suffixes ( ) : if typ == imp . PY_COMPILED : return ext
1
what extensions do python files use
Official way to get the extension of compiled files ( . pyc or . pyo )
cosqa-train-14790
def _get_compiled_ext(): """Official way to get the extension of compiled files (.pyc or .pyo)""" for ext, mode, typ in imp.get_suffixes(): if typ == imp.PY_COMPILED: return ext
def not0 ( a ) : return matrix ( list ( map ( lambda x : 1 if x == 0 else x , a ) ) , a . size )
1
python count non zeros in matrix
Return u if u! = 0 return 1 if u == 0
cosqa-train-14791
def not0(a): """Return u if u!= 0, return 1 if u == 0""" return matrix(list(map(lambda x: 1 if x == 0 else x, a)), a.size)
def return_letters_from_string ( text ) : out = "" for letter in text : if letter . isalpha ( ) : out += letter return out
1
what function goes through the letters in a string? python
Get letters from string only .
cosqa-train-14792
def return_letters_from_string(text): """Get letters from string only.""" out = "" for letter in text: if letter.isalpha(): out += letter return out
def count_rows_with_nans ( X ) : if X . ndim == 2 : return np . where ( np . isnan ( X ) . sum ( axis = 1 ) != 0 , 1 , 0 ) . sum ( )
1
python count number of nan in numpy array
Count the number of rows in 2D arrays that contain any nan values .
cosqa-train-14793
def count_rows_with_nans(X): """Count the number of rows in 2D arrays that contain any nan values.""" if X.ndim == 2: return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()
def link ( self , mu , dist ) : return np . log ( mu ) - np . log ( dist . levels - mu )
0
what glm to model lognormal distribution python
glm link function this is useful for going from mu to the linear prediction
cosqa-train-14794
def link(self, mu, dist): """ glm link function this is useful for going from mu to the linear prediction Parameters ---------- mu : array-like of legth n dist : Distribution instance Returns ------- lp : np.array of length n """ return np.log(mu) - np.log(dist.levels - mu)
def _count_leading_whitespace ( text ) : idx = 0 for idx , char in enumerate ( text ) : if not char . isspace ( ) : return idx return idx + 1
1
python count whitespace characters
Returns the number of characters at the beginning of text that are whitespace .
cosqa-train-14795
def _count_leading_whitespace(text): """Returns the number of characters at the beginning of text that are whitespace.""" idx = 0 for idx, char in enumerate(text): if not char.isspace(): return idx return idx + 1
def lines ( self ) : if self . _lines is None : self . _lines = self . obj . content . splitlines ( ) return self . _lines
1
what python object has the attribute 'splitlines'
cosqa-train-14796
def lines(self): """ :return: """ if self._lines is None: self._lines = self.obj.content.splitlines() return self._lines
def coverage ( ) : run ( "coverage run --source {PROJECT_NAME} -m py.test" . format ( PROJECT_NAME = PROJECT_NAME ) ) run ( "coverage report -m" ) run ( "coverage html" ) webbrowser . open ( 'file://' + os . path . realpath ( "htmlcov/index.html" ) , new = 2 )
1
python coverage report html
check code coverage quickly with the default Python
cosqa-train-14797
def coverage(): """check code coverage quickly with the default Python""" run("coverage run --source {PROJECT_NAME} -m py.test".format(PROJECT_NAME=PROJECT_NAME)) run("coverage report -m") run("coverage html") webbrowser.open('file://' + os.path.realpath("htmlcov/index.html"), new=2)
def fail ( message = None , exit_status = None ) : print ( 'Error:' , message , file = sys . stderr ) sys . exit ( exit_status or 1 )
1
what variable to use to quit a program in python
Prints the specified message and exits the program with the specified exit status .
cosqa-train-14798
def fail(message=None, exit_status=None): """Prints the specified message and exits the program with the specified exit status. """ print('Error:', message, file=sys.stderr) sys.exit(exit_status or 1)
def md_to_text ( content ) : text = None html = markdown . markdown ( content ) if html : text = html_to_text ( content ) return text
0
python covert markdown to html with highlight
Converts markdown content to text
cosqa-train-14799
def md_to_text(content): """ Converts markdown content to text """ text = None html = markdown.markdown(content) if html: text = html_to_text(content) return text