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 timeit ( output ) : b = time . time ( ) yield print output , 'time used: %.3fs' % ( time . time ( ) - b )
0
python print time cost
If output is string then print the string and also time used
cosqa-train-15900
def timeit(output): """ If output is string, then print the string and also time used """ b = time.time() yield print output, 'time used: %.3fs' % (time.time()-b)
def format_time ( timestamp ) : format_string = '%Y_%m_%d_%Hh%Mm%Ss' formatted_time = datetime . datetime . fromtimestamp ( timestamp ) . strftime ( format_string ) return formatted_time
0
python print time format from timestamp
Formats timestamp to human readable format
cosqa-train-15901
def format_time(timestamp): """Formats timestamp to human readable format""" format_string = '%Y_%m_%d_%Hh%Mm%Ss' formatted_time = datetime.datetime.fromtimestamp(timestamp).strftime(format_string) return formatted_time
def executable_exists ( executable ) : for directory in os . getenv ( "PATH" ) . split ( ":" ) : if os . path . exists ( os . path . join ( directory , executable ) ) : return True return False
1
how to express if something exist in python
Test if an executable is available on the system .
cosqa-train-15902
def executable_exists(executable): """Test if an executable is available on the system.""" for directory in os.getenv("PATH").split(":"): if os.path.exists(os.path.join(directory, executable)): return True return False
def pout ( msg , log = None ) : _print ( msg , sys . stdout , log_func = log . info if log else None )
0
python print to stdout or logger
Print msg to stdout and option log at info level .
cosqa-train-15903
def pout(msg, log=None): """Print 'msg' to stdout, and option 'log' at info level.""" _print(msg, sys.stdout, log_func=log.info if log else None)
def extract_table_names ( query ) : # a good old fashioned regex. turns out this worked better than actually parsing the code tables_blocks = re . findall ( r'(?:FROM|JOIN)\s+(\w+(?:\s*,\s*\w+)*)' , query , re . IGNORECASE ) tables = [ tbl for block in tables_blocks for tbl in re . findall ( r'\w+' , block ) ] return set ( tables )
1
how to extract tables of a sql database in python
Extract table names from an SQL query .
cosqa-train-15904
def extract_table_names(query): """ Extract table names from an SQL query. """ # a good old fashioned regex. turns out this worked better than actually parsing the code tables_blocks = re.findall(r'(?:FROM|JOIN)\s+(\w+(?:\s*,\s*\w+)*)', query, re.IGNORECASE) tables = [tbl for block in tables_blocks for tbl in re.findall(r'\w+', block)] return set(tables)
def print_tree ( self , indent = 2 ) : config . LOGGER . info ( "{indent}{data}" . format ( indent = " " * indent , data = str ( self ) ) ) for child in self . children : child . print_tree ( indent + 1 )
0
python print tree recursion
print_tree : prints out structure of tree Args : indent ( int ) : What level of indentation at which to start printing Returns : None
cosqa-train-15905
def print_tree(self, indent=2): """ print_tree: prints out structure of tree Args: indent (int): What level of indentation at which to start printing Returns: None """ config.LOGGER.info("{indent}{data}".format(indent=" " * indent, data=str(self))) for child in self.children: child.print_tree(indent + 1)
def get_key_by_value ( dictionary , search_value ) : for key , value in dictionary . iteritems ( ) : if value == search_value : return ugettext ( key )
1
how to finda key uisng a vlue in python dict
searchs a value in a dicionary and returns the key of the first occurrence
cosqa-train-15906
def get_key_by_value(dictionary, search_value): """ searchs a value in a dicionary and returns the key of the first occurrence :param dictionary: dictionary to search in :param search_value: value to search for """ for key, value in dictionary.iteritems(): if value == search_value: return ugettext(key)
def algo_exp ( x , m , t , b ) : return m * np . exp ( - t * x ) + b
0
python program adjustable sigmoid functions
mono - exponential curve .
cosqa-train-15907
def algo_exp(x, m, t, b): """mono-exponential curve.""" return m*np.exp(-t*x)+b
def iflatten ( L ) : for sublist in L : if hasattr ( sublist , '__iter__' ) : for item in iflatten ( sublist ) : yield item else : yield sublist
0
how to flatten a set python
Iterative flatten .
cosqa-train-15908
def iflatten(L): """Iterative flatten.""" for sublist in L: if hasattr(sublist, '__iter__'): for item in iflatten(sublist): yield item else: yield sublist
def longest_run_1d ( arr ) : v , rl = rle_1d ( arr ) [ : 2 ] return np . where ( v , rl , 0 ) . max ( )
1
python program for longest run of a number in a list
Return the length of the longest consecutive run of identical values .
cosqa-train-15909
def longest_run_1d(arr): """Return the length of the longest consecutive run of identical values. Parameters ---------- arr : bool array Input array Returns ------- int Length of longest run. """ v, rl = rle_1d(arr)[:2] return np.where(v, rl, 0).max()
def imflip ( img , direction = 'horizontal' ) : assert direction in [ 'horizontal' , 'vertical' ] if direction == 'horizontal' : return np . flip ( img , axis = 1 ) else : return np . flip ( img , axis = 0 )
0
how to flip a matrix python
Flip an image horizontally or vertically .
cosqa-train-15910
def imflip(img, direction='horizontal'): """Flip an image horizontally or vertically. Args: img (ndarray): Image to be flipped. direction (str): The flip direction, either "horizontal" or "vertical". Returns: ndarray: The flipped image. """ assert direction in ['horizontal', 'vertical'] if direction == 'horizontal': return np.flip(img, axis=1) else: return np.flip(img, axis=0)
def build_docs ( directory ) : os . chdir ( directory ) process = subprocess . Popen ( [ "make" , "html" ] , cwd = directory ) process . communicate ( )
0
python program to print document in a specific folder
Builds sphinx docs from a given directory .
cosqa-train-15911
def build_docs(directory): """Builds sphinx docs from a given directory.""" os.chdir(directory) process = subprocess.Popen(["make", "html"], cwd=directory) process.communicate()
def dedupe_list ( l ) : result = [ ] for el in l : if el not in result : result . append ( el ) return result
1
how to force a particular order of list in python
Remove duplicates from a list preserving the order .
cosqa-train-15912
def dedupe_list(l): """Remove duplicates from a list preserving the order. We might be tempted to use the list(set(l)) idiom, but it doesn't preserve the order, which hinders testability and does not work for lists with unhashable elements. """ result = [] for el in l: if el not in result: result.append(el) return result
def _chunk_write ( chunk , local_file , progress ) : local_file . write ( chunk ) progress . update_with_increment_value ( len ( chunk ) )
0
python progress bar for file upload
Write a chunk to file and update the progress bar
cosqa-train-15913
def _chunk_write(chunk, local_file, progress): """Write a chunk to file and update the progress bar""" local_file.write(chunk) progress.update_with_increment_value(len(chunk))
def safe_int_conv ( number ) : try : return int ( np . array ( number ) . astype ( int , casting = 'safe' ) ) except TypeError : raise ValueError ( 'cannot safely convert {} to integer' . format ( number ) )
1
how to force integer type input in python
Safely convert a single number to integer .
cosqa-train-15914
def safe_int_conv(number): """Safely convert a single number to integer.""" try: return int(np.array(number).astype(int, casting='safe')) except TypeError: raise ValueError('cannot safely convert {} to integer'.format(number))
def getpackagepath ( ) : moduleDirectory = os . path . dirname ( __file__ ) packagePath = os . path . dirname ( __file__ ) + "/../" return packagePath
0
python project root folder
* Get the root path for this python package - used in unit testing code *
cosqa-train-15915
def getpackagepath(): """ *Get the root path for this python package - used in unit testing code* """ moduleDirectory = os.path.dirname(__file__) packagePath = os.path.dirname(__file__) + "/../" return packagePath
def hash_iterable ( it ) : hash_value = hash ( type ( it ) ) for value in it : hash_value = hash ( ( hash_value , value ) ) return hash_value
1
how to generate hash of tuple python
Perform a O ( 1 ) memory hash of an iterable of arbitrary length .
cosqa-train-15916
def hash_iterable(it): """Perform a O(1) memory hash of an iterable of arbitrary length. hash(tuple(it)) creates a temporary tuple containing all values from it which could be a problem if it is large. See discussion at: https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ """ hash_value = hash(type(it)) for value in it: hash_value = hash((hash_value, value)) return hash_value
def _normal_prompt ( self ) : sys . stdout . write ( self . __get_ps1 ( ) ) sys . stdout . flush ( ) return safe_input ( )
0
python prompt input invisible
Flushes the prompt before requesting the input
cosqa-train-15917
def _normal_prompt(self): """ Flushes the prompt before requesting the input :return: The command line """ sys.stdout.write(self.__get_ps1()) sys.stdout.flush() return safe_input()
def md5_string ( s ) : m = hashlib . md5 ( ) m . update ( s ) return str ( m . hexdigest ( ) )
0
how to generate md5 hash python
Shortcut to create md5 hash : param s : : return :
cosqa-train-15918
def md5_string(s): """ Shortcut to create md5 hash :param s: :return: """ m = hashlib.md5() m.update(s) return str(m.hexdigest())
def write_only_property ( f ) : docstring = f . __doc__ return property ( fset = f , doc = docstring )
0
python property setter not callable
cosqa-train-15919
def write_only_property(f): """ @write_only_property decorator. Creates a property (descriptor attribute) that accepts assignment, but not getattr (use in an expression). """ docstring = f.__doc__ return property(fset=f, doc=docstring)
def _rnd_datetime ( self , start , end ) : return self . from_utctimestamp ( random . randint ( int ( self . to_utctimestamp ( start ) ) , int ( self . to_utctimestamp ( end ) ) , ) )
1
how to generate random datetime in python
Internal random datetime generator .
cosqa-train-15920
def _rnd_datetime(self, start, end): """Internal random datetime generator. """ return self.from_utctimestamp( random.randint( int(self.to_utctimestamp(start)), int(self.to_utctimestamp(end)), ) )
def message_from_string ( s , * args , * * kws ) : from future . backports . email . parser import Parser return Parser ( * args , * * kws ) . parsestr ( s )
0
python protobuf parse from string
Parse a string into a Message object model .
cosqa-train-15921
def message_from_string(s, *args, **kws): """Parse a string into a Message object model. Optional _class and strict are passed to the Parser constructor. """ from future.backports.email.parser import Parser return Parser(*args, **kws).parsestr(s)
def _unique_id ( self , prefix ) : _id = self . _id_gen self . _id_gen += 1 return prefix + str ( _id )
1
how to generate unique identifier python
Generate a unique ( within the graph ) identifer internal to graph generation .
cosqa-train-15922
def _unique_id(self, prefix): """ Generate a unique (within the graph) identifer internal to graph generation. """ _id = self._id_gen self._id_gen += 1 return prefix + str(_id)
def getEdges ( npArr ) : edges = np . concatenate ( ( [ 0 ] , npArr [ : , 0 ] + npArr [ : , 2 ] ) ) return np . array ( [ Decimal ( str ( i ) ) for i in edges ] )
1
python put bins into array
get np array of bin edges
cosqa-train-15923
def getEdges(npArr): """get np array of bin edges""" edges = np.concatenate(([0], npArr[:,0] + npArr[:,2])) return np.array([Decimal(str(i)) for i in edges])
def _get_random_id ( ) : symbols = string . ascii_uppercase + string . ascii_lowercase + string . digits return '' . join ( random . choice ( symbols ) for _ in range ( 15 ) )
0
how to generate unique random numbers in python
Get a random ( i . e . unique ) string identifier
cosqa-train-15924
def _get_random_id(): """ Get a random (i.e., unique) string identifier""" symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.choice(symbols) for _ in range(15))
def add_arrow ( self , x1 , y1 , x2 , y2 , * * kws ) : self . panel . add_arrow ( x1 , y1 , x2 , y2 , * * kws )
0
python pylab draw arrow on x and y axis
add arrow to plot
cosqa-train-15925
def add_arrow(self, x1, y1, x2, y2, **kws): """add arrow to plot""" self.panel.add_arrow(x1, y1, x2, y2, **kws)
def ci ( a , which = 95 , axis = None ) : p = 50 - which / 2 , 50 + which / 2 return percentiles ( a , p , axis )
0
how to get 25th and 75th percentile + python
Return a percentile range from an array of values .
cosqa-train-15926
def ci(a, which=95, axis=None): """Return a percentile range from an array of values.""" p = 50 - which / 2, 50 + which / 2 return percentiles(a, p, axis)
def get_callable_documentation ( the_callable ) : return wrap_text_in_a_box ( title = get_callable_signature_as_string ( the_callable ) , body = ( getattr ( the_callable , '__doc__' ) or 'No documentation' ) . replace ( '\n' , '\n\n' ) , style = 'ascii_double' )
0
python pylint how to write a function doctring
Return a string with the callable signature and its docstring .
cosqa-train-15927
def get_callable_documentation(the_callable): """Return a string with the callable signature and its docstring. :param the_callable: the callable to be analyzed. :type the_callable: function/callable. :return: the signature. """ return wrap_text_in_a_box( title=get_callable_signature_as_string(the_callable), body=(getattr(the_callable, '__doc__') or 'No documentation').replace( '\n', '\n\n'), style='ascii_double')
def string_to_identity ( identity_str ) : m = _identity_regexp . match ( identity_str ) result = m . groupdict ( ) log . debug ( 'parsed identity: %s' , result ) return { k : v for k , v in result . items ( ) if v }
0
how to get a dict out of a string in python
Parse string into Identity dictionary .
cosqa-train-15928
def string_to_identity(identity_str): """Parse string into Identity dictionary.""" m = _identity_regexp.match(identity_str) result = m.groupdict() log.debug('parsed identity: %s', result) return {k: v for k, v in result.items() if v}
def main ( output = None , error = None , verbose = False ) : runner = Runner ( args = [ "--verbose" ] if verbose is not False else None ) runner . run ( output , error )
0
python pylint variable overwrite
The main ( cli ) interface for the pylint runner .
cosqa-train-15929
def main(output=None, error=None, verbose=False): """ The main (cli) interface for the pylint runner. """ runner = Runner(args=["--verbose"] if verbose is not False else None) runner.run(output, error)
def wget ( url ) : import urllib . parse request = urllib . request . urlopen ( url ) filestring = request . read ( ) return filestring
1
how to get a file from web in python
Download the page into a string
cosqa-train-15930
def wget(url): """ Download the page into a string """ import urllib.parse request = urllib.request.urlopen(url) filestring = request.read() return filestring
def update_one ( self , query , doc ) : if self . table is None : self . build_table ( ) if u"$set" in doc : doc = doc [ u"$set" ] allcond = self . parse_query ( query ) try : result = self . table . update ( doc , allcond ) except : # TODO: check table.update result # check what pymongo does in that case result = None return UpdateResult ( raw_result = result )
0
python pymongo update field based on other field
Updates one element of the collection
cosqa-train-15931
def update_one(self, query, doc): """ Updates one element of the collection :param query: dictionary representing the mongo query :param doc: dictionary representing the item to be updated :return: UpdateResult """ if self.table is None: self.build_table() if u"$set" in doc: doc = doc[u"$set"] allcond = self.parse_query(query) try: result = self.table.update(doc, allcond) except: # TODO: check table.update result # check what pymongo does in that case result = None return UpdateResult(raw_result=result)
def compose ( * parameter_functions ) : def composed_fn ( var_name , variable , phase ) : for fn in parameter_functions : variable = fn ( var_name , variable , phase ) return variable return composed_fn
0
how to get a function in python to apply to a changes number of variables
Composes multiple modification functions in order .
cosqa-train-15932
def compose(*parameter_functions): """Composes multiple modification functions in order. Args: *parameter_functions: The functions to compose. Returns: A parameter modification function that consists of applying all the provided functions. """ def composed_fn(var_name, variable, phase): for fn in parameter_functions: variable = fn(var_name, variable, phase) return variable return composed_fn
def from_pydatetime ( cls , pydatetime ) : return cls ( date = Date . from_pydate ( pydatetime . date ) , time = Time . from_pytime ( pydatetime . time ) )
1
python pymysql converts mysqldatetime to python datetime
Creates sql datetime2 object from Python datetime object ignoring timezone
cosqa-train-15933
def from_pydatetime(cls, pydatetime): """ Creates sql datetime2 object from Python datetime object ignoring timezone @param pydatetime: Python datetime object @return: sql datetime2 object """ return cls(date=Date.from_pydate(pydatetime.date), time=Time.from_pytime(pydatetime.time))
def list_files ( directory ) : return [ f for f in pathlib . Path ( directory ) . iterdir ( ) if f . is_file ( ) and not f . name . startswith ( '.' ) ]
0
how to get a list of files in directory in python
Returns all files in a given directory
cosqa-train-15934
def list_files(directory): """Returns all files in a given directory """ return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]
def cover ( session ) : session . interpreter = 'python3.6' session . install ( 'coverage' , 'pytest-cov' ) session . run ( 'coverage' , 'report' , '--show-missing' , '--fail-under=100' ) session . run ( 'coverage' , 'erase' )
0
python pytest jenkins coverage report
Run the final coverage report . This outputs the coverage report aggregating coverage from the unit test runs ( not system test runs ) and then erases coverage data .
cosqa-train-15935
def cover(session): """Run the final coverage report. This outputs the coverage report aggregating coverage from the unit test runs (not system test runs), and then erases coverage data. """ session.interpreter = 'python3.6' session.install('coverage', 'pytest-cov') session.run('coverage', 'report', '--show-missing', '--fail-under=100') session.run('coverage', 'erase')
def get_font_list ( ) : font_map = pangocairo . cairo_font_map_get_default ( ) font_list = [ f . get_name ( ) for f in font_map . list_families ( ) ] font_list . sort ( ) return font_list
1
how to get a list of fonts in python
Returns a sorted list of all system font names
cosqa-train-15936
def get_font_list(): """Returns a sorted list of all system font names""" font_map = pangocairo.cairo_font_map_get_default() font_list = [f.get_name() for f in font_map.list_families()] font_list.sort() return font_list
def run_tests ( self ) : with _save_argv ( _sys . argv [ : 1 ] + self . addopts ) : result_code = __import__ ( 'pytest' ) . main ( ) if result_code : raise SystemExit ( result_code )
0
python pytest with files
Invoke pytest replacing argv . Return result code .
cosqa-train-15937
def run_tests(self): """ Invoke pytest, replacing argv. Return result code. """ with _save_argv(_sys.argv[:1] + self.addopts): result_code = __import__('pytest').main() if result_code: raise SystemExit(result_code)
def contextMenuEvent ( self , event ) : self . menu . popup ( event . globalPos ( ) ) event . accept ( )
1
python qmenu popup size 1
Reimplement Qt method
cosqa-train-15938
def contextMenuEvent(self, event): """Reimplement Qt method""" self.menu.popup(event.globalPos()) event.accept()
def remove_parameter ( self , name ) : if name in self . __query : self . __query . pop ( name )
1
python query remove element
Remove the specified parameter from this query
cosqa-train-15939
def remove_parameter(self, name): """ Remove the specified parameter from this query :param name: name of a parameter to remove :return: None """ if name in self.__query: self.__query.pop(name)
def combinations ( l ) : result = [ ] for x in xrange ( len ( l ) - 1 ) : ls = l [ x + 1 : ] for y in ls : result . append ( ( l [ x ] , y ) ) return result
0
how to get combinations of list in python
Pure - Python implementation of itertools . combinations ( l 2 ) .
cosqa-train-15940
def combinations(l): """Pure-Python implementation of itertools.combinations(l, 2).""" result = [] for x in xrange(len(l) - 1): ls = l[x + 1:] for y in ls: result.append((l[x], y)) return result
def urlencoded ( body , charset = 'ascii' , * * kwargs ) : return parse_query_string ( text ( body , charset = charset ) , False )
1
python query string parsing
Converts query strings into native Python objects
cosqa-train-15941
def urlencoded(body, charset='ascii', **kwargs): """Converts query strings into native Python objects""" return parse_query_string(text(body, charset=charset), False)
def bbox ( self ) : return self . left , self . top , self . right , self . bottom
0
how to get combobox box in python by self method
BBox
cosqa-train-15942
def bbox(self): """BBox""" return self.left, self.top, self.right, self.bottom
def PopTask ( self ) : try : _ , task = heapq . heappop ( self . _heap ) except IndexError : return None self . _task_identifiers . remove ( task . identifier ) return task
0
python queue how to remove an item
Retrieves and removes the first task from the heap .
cosqa-train-15943
def PopTask(self): """Retrieves and removes the first task from the heap. Returns: Task: the task or None if the heap is empty. """ try: _, task = heapq.heappop(self._heap) except IndexError: return None self._task_identifiers.remove(task.identifier) return task
def parse_cookies ( self , req , name , field ) : return core . get_value ( req . COOKIES , name , field )
1
how to get cookie from request in python
Pull the value from the cookiejar .
cosqa-train-15944
def parse_cookies(self, req, name, field): """Pull the value from the cookiejar.""" return core.get_value(req.COOKIES, name, field)
def random_color ( _min = MIN_COLOR , _max = MAX_COLOR ) : return color ( random . randint ( _min , _max ) )
1
python rand with min max
Returns a random color between min and max .
cosqa-train-15945
def random_color(_min=MIN_COLOR, _max=MAX_COLOR): """Returns a random color between min and max.""" return color(random.randint(_min, _max))
def sample_correlations ( self ) : C = np . corrcoef ( self . X . T ) corr_matrix = ExpMatrix ( genes = self . samples , samples = self . samples , X = C ) return corr_matrix
0
how to get correlation coefficient matrix in python numpy
Returns an ExpMatrix containing all pairwise sample correlations .
cosqa-train-15946
def sample_correlations(self): """Returns an `ExpMatrix` containing all pairwise sample correlations. Returns ------- `ExpMatrix` The sample correlation matrix. """ C = np.corrcoef(self.X.T) corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C) return corr_matrix
def get_incomplete_path ( filename ) : random_suffix = "" . join ( random . choice ( string . ascii_uppercase + string . digits ) for _ in range ( 6 ) ) return filename + ".incomplete" + random_suffix
0
python random filename string
Returns a temporary filename based on filename .
cosqa-train-15947
def get_incomplete_path(filename): """Returns a temporary filename based on filename.""" random_suffix = "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(6)) return filename + ".incomplete" + random_suffix
def shape ( self ) : if not self . data : return ( 0 , 0 ) return ( len ( self . data ) , len ( self . dimensions ) )
0
how to get dataset dimenion in python
Compute the shape of the dataset as ( rows cols ) .
cosqa-train-15948
def shape(self): """Compute the shape of the dataset as (rows, cols).""" if not self.data: return (0, 0) return (len(self.data), len(self.dimensions))
def rnormal ( mu , tau , size = None ) : return np . random . normal ( mu , 1. / np . sqrt ( tau ) , size )
1
python random number generation normal distribution
Random normal variates .
cosqa-train-15949
def rnormal(mu, tau, size=None): """ Random normal variates. """ return np.random.normal(mu, 1. / np.sqrt(tau), size)
def get_file_name ( url ) : return os . path . basename ( urllib . parse . urlparse ( url ) . path ) or 'unknown_name'
0
how to get dynamic file name in python
Returns file name of file at given url .
cosqa-train-15950
def get_file_name(url): """Returns file name of file at given url.""" return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'
def rlognormal ( mu , tau , size = None ) : return np . random . lognormal ( mu , np . sqrt ( 1. / tau ) , size )
0
python random truncated gaussian
Return random lognormal variates .
cosqa-train-15951
def rlognormal(mu, tau, size=None): """ Return random lognormal variates. """ return np.random.lognormal(mu, np.sqrt(1. / tau), size)
def root_parent ( self , category = None ) : return next ( filter ( lambda c : c . is_root , self . hierarchy ( ) ) )
1
how to get first child only python
Returns the topmost parent of the current category .
cosqa-train-15952
def root_parent(self, category=None): """ Returns the topmost parent of the current category. """ return next(filter(lambda c: c.is_root, self.hierarchy()))
def get_randomized_guid_sample ( self , item_count ) : dataset = self . get_whitelist ( ) random . shuffle ( dataset ) return dataset [ : item_count ]
1
python randomize items in a list
Fetch a subset of randomzied GUIDs from the whitelist
cosqa-train-15953
def get_randomized_guid_sample(self, item_count): """ Fetch a subset of randomzied GUIDs from the whitelist """ dataset = self.get_whitelist() random.shuffle(dataset) return dataset[:item_count]
def get_offset_topic_partition_count ( kafka_config ) : metadata = get_topic_partition_metadata ( kafka_config . broker_list ) if CONSUMER_OFFSET_TOPIC not in metadata : raise UnknownTopic ( "Consumer offset topic is missing." ) return len ( metadata [ CONSUMER_OFFSET_TOPIC ] )
0
how to get kafka topics python
Given a kafka cluster configuration return the number of partitions in the offset topic . It will raise an UnknownTopic exception if the topic cannot be found .
cosqa-train-15954
def get_offset_topic_partition_count(kafka_config): """Given a kafka cluster configuration, return the number of partitions in the offset topic. It will raise an UnknownTopic exception if the topic cannot be found.""" metadata = get_topic_partition_metadata(kafka_config.broker_list) if CONSUMER_OFFSET_TOPIC not in metadata: raise UnknownTopic("Consumer offset topic is missing.") return len(metadata[CONSUMER_OFFSET_TOPIC])
def add_range ( self , sequence , begin , end ) : sequence . parser_tree = parsing . Range ( self . value ( begin ) . strip ( "'" ) , self . value ( end ) . strip ( "'" ) ) return True
1
python range on a string
Add a read_range primitive
cosqa-train-15955
def add_range(self, sequence, begin, end): """Add a read_range primitive""" sequence.parser_tree = parsing.Range(self.value(begin).strip("'"), self.value(end).strip("'")) return True
def getScriptLocation ( ) : location = os . path . abspath ( "./" ) if __file__ . rfind ( "/" ) != - 1 : location = __file__ [ : __file__ . rfind ( "/" ) ] return location
0
how to get location of python
Helper function to get the location of a Python file .
cosqa-train-15956
def getScriptLocation(): """Helper function to get the location of a Python file.""" location = os.path.abspath("./") if __file__.rfind("/") != -1: location = __file__[:__file__.rfind("/")] return location
def max_values ( args ) : return Interval ( max ( x . low for x in args ) , max ( x . high for x in args ) )
0
python rangefunction to include even the higher limit
Return possible range for max function .
cosqa-train-15957
def max_values(args): """ Return possible range for max function. """ return Interval(max(x.low for x in args), max(x.high for x in args))
def get_last_modified_timestamp ( self ) : cmd = "find . -print0 | xargs -0 stat -f '%T@ %p' | sort -n | tail -1 | cut -f2- -d' '" ps = subprocess . Popen ( cmd , shell = True , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) output = ps . communicate ( ) [ 0 ] print output
1
how to get most recently added file in directory python
Looks at the files in a git root directory and grabs the last modified timestamp
cosqa-train-15958
def get_last_modified_timestamp(self): """ Looks at the files in a git root directory and grabs the last modified timestamp """ cmd = "find . -print0 | xargs -0 stat -f '%T@ %p' | sort -n | tail -1 | cut -f2- -d' '" ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) output = ps.communicate()[0] print output
def camel_to_snake_case ( name ) : pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])' return '_' . join ( map ( str . lower , re . findall ( pattern , name ) ) )
0
python re compile case sensitive
Takes a camelCased string and converts to snake_case .
cosqa-train-15959
def camel_to_snake_case(name): """Takes a camelCased string and converts to snake_case.""" pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])' return '_'.join(map(str.lower, re.findall(pattern, name)))
def runcode ( code ) : for line in code : print ( '# ' + line ) exec ( line , globals ( ) ) print ( '# return ans' ) return ans
0
how to get output from a code line multiple times in python
Run the given code line by line with printing as list of lines and return variable ans .
cosqa-train-15960
def runcode(code): """Run the given code line by line with printing, as list of lines, and return variable 'ans'.""" for line in code: print('# '+line) exec(line,globals()) print('# return ans') return ans
def read_utf8 ( fh , byteorder , dtype , count , offsetsize ) : return fh . read ( count ) . decode ( 'utf-8' )
0
python read binary file as utf8
Read tag data from file and return as unicode string .
cosqa-train-15961
def read_utf8(fh, byteorder, dtype, count, offsetsize): """Read tag data from file and return as unicode string.""" return fh.read(count).decode('utf-8')
def run_cmd ( command , verbose = True , shell = '/bin/bash' ) : process = Popen ( command , shell = True , stdout = PIPE , stderr = STDOUT , executable = shell ) output = process . stdout . read ( ) . decode ( ) . strip ( ) . split ( '\n' ) if verbose : # return full output including empty lines return output return [ line for line in output if line . strip ( ) ]
0
how to get output of bash command in python
internal helper function to run shell commands and get output
cosqa-train-15962
def run_cmd(command, verbose=True, shell='/bin/bash'): """internal helper function to run shell commands and get output""" process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell) output = process.stdout.read().decode().strip().split('\n') if verbose: # return full output including empty lines return output return [line for line in output if line.strip()]
def replace_all ( filepath , searchExp , replaceExp ) : for line in fileinput . input ( filepath , inplace = 1 ) : if searchExp in line : line = line . replace ( searchExp , replaceExp ) sys . stdout . write ( line )
0
python read file and replace string according the match
Replace all the ocurrences ( in a file ) of a string with another value .
cosqa-train-15963
def replace_all(filepath, searchExp, replaceExp): """ Replace all the ocurrences (in a file) of a string with another value. """ for line in fileinput.input(filepath, inplace=1): if searchExp in line: line = line.replace(searchExp, replaceExp) sys.stdout.write(line)
def import_js ( path , lib_name , globals ) : with codecs . open ( path_as_local ( path ) , "r" , "utf-8" ) as f : js = f . read ( ) e = EvalJs ( ) e . execute ( js ) var = e . context [ 'var' ] globals [ lib_name ] = var . to_python ( )
0
how to get python to read javascript
Imports from javascript source file . globals is your globals ()
cosqa-train-15964
def import_js(path, lib_name, globals): """Imports from javascript source file. globals is your globals()""" with codecs.open(path_as_local(path), "r", "utf-8") as f: js = f.read() e = EvalJs() e.execute(js) var = e.context['var'] globals[lib_name] = var.to_python()
def file_to_str ( fname ) : data = None # rU = read with Universal line terminator with open ( fname , 'rU' ) as fd : data = fd . read ( ) return data
0
python read file as giant string
Read a file into a string PRE : fname is a small file ( to avoid hogging memory and its discontents )
cosqa-train-15965
def file_to_str(fname): """ Read a file into a string PRE: fname is a small file (to avoid hogging memory and its discontents) """ data = None # rU = read with Universal line terminator with open(fname, 'rU') as fd: data = fd.read() return data
def dedup ( seq ) : seen = set ( ) for item in seq : if item not in seen : seen . add ( item ) yield item
1
how to get rid of repeats list python
Remove duplicates from a list while keeping order .
cosqa-train-15966
def dedup(seq): """Remove duplicates from a list while keeping order.""" seen = set() for item in seq: if item not in seen: seen.add(item) yield item
def loads ( string ) : f = StringIO . StringIO ( string ) marshaller = JavaObjectUnmarshaller ( f ) marshaller . add_transformer ( DefaultObjectTransformer ( ) ) return marshaller . readObject ( )
0
python read in a java serialized object as a string
Deserializes Java objects and primitive data serialized by ObjectOutputStream from a string .
cosqa-train-15967
def loads(string): """ Deserializes Java objects and primitive data serialized by ObjectOutputStream from a string. """ f = StringIO.StringIO(string) marshaller = JavaObjectUnmarshaller(f) marshaller.add_transformer(DefaultObjectTransformer()) return marshaller.readObject()
def _run_cmd_get_output ( cmd ) : process = subprocess . Popen ( cmd . split ( ) , stdout = subprocess . PIPE ) out , err = process . communicate ( ) return out or err
0
how to get shell command results in python
Runs a shell command returns console output .
cosqa-train-15968
def _run_cmd_get_output(cmd): """Runs a shell command, returns console output. Mimics python3's subprocess.getoutput """ process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) out, err = process.communicate() return out or err
def _calc_dir_size ( path ) : dir_size = 0 for ( root , dirs , files ) in os . walk ( path ) : for fn in files : full_fn = os . path . join ( root , fn ) dir_size += os . path . getsize ( full_fn ) return dir_size
0
how to get size of directory in python
Calculate size of all files in path .
cosqa-train-15969
def _calc_dir_size(path): """ Calculate size of all files in `path`. Args: path (str): Path to the directory. Returns: int: Size of the directory in bytes. """ dir_size = 0 for (root, dirs, files) in os.walk(path): for fn in files: full_fn = os.path.join(root, fn) dir_size += os.path.getsize(full_fn) return dir_size
def standard_input ( ) : with click . get_text_stream ( "stdin" ) as stdin : while stdin . readable ( ) : line = stdin . readline ( ) if line : yield line . strip ( ) . encode ( "utf-8" )
0
python read lines of text from standard input
Generator that yields lines from standard input .
cosqa-train-15970
def standard_input(): """Generator that yields lines from standard input.""" with click.get_text_stream("stdin") as stdin: while stdin.readable(): line = stdin.readline() if line: yield line.strip().encode("utf-8")
def get_file_string ( filepath ) : with open ( os . path . abspath ( filepath ) ) as f : return f . read ( )
0
how to get string from open file python
Get string from file .
cosqa-train-15971
def get_file_string(filepath): """Get string from file.""" with open(os.path.abspath(filepath)) as f: return f.read()
def import_public_rsa_key_from_file ( filename ) : with open ( filename , "rb" ) as key_file : public_key = serialization . load_pem_public_key ( key_file . read ( ) , backend = default_backend ( ) ) return public_key
1
python read rsa public key
Read a public RSA key from a PEM file .
cosqa-train-15972
def import_public_rsa_key_from_file(filename): """ Read a public RSA key from a PEM file. :param filename: The name of the file :param passphrase: A pass phrase to use to unpack the PEM file. :return: A cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey instance """ with open(filename, "rb") as key_file: public_key = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) return public_key
def camel_to_underscore ( string ) : string = FIRST_CAP_RE . sub ( r'\1_\2' , string ) return ALL_CAP_RE . sub ( r'\1_\2' , string ) . lower ( )
0
python reading in underscore problem
Convert camelcase to lowercase and underscore .
cosqa-train-15973
def camel_to_underscore(string): """Convert camelcase to lowercase and underscore. Recipe from http://stackoverflow.com/a/1176023 Args: string (str): The string to convert. Returns: str: The converted string. """ string = FIRST_CAP_RE.sub(r'\1_\2', string) return ALL_CAP_RE.sub(r'\1_\2', string).lower()
def center_eigenvalue_diff ( mat ) : N = len ( mat ) evals = np . sort ( la . eigvals ( mat ) ) diff = np . abs ( evals [ N / 2 ] - evals [ N / 2 - 1 ] ) return diff
0
how to get the eigen values of an image in python
Compute the eigvals of mat and then find the center eigval difference .
cosqa-train-15974
def center_eigenvalue_diff(mat): """Compute the eigvals of mat and then find the center eigval difference.""" N = len(mat) evals = np.sort(la.eigvals(mat)) diff = np.abs(evals[N/2] - evals[N/2-1]) return diff
def recursively_update ( d , d2 ) : for k , v in d2 . items ( ) : if k in d : if isinstance ( v , dict ) : recursively_update ( d [ k ] , v ) continue d [ k ] = v
0
python recursive dictionary tree update
dict . update but which merges child dicts ( dict2 takes precedence where there s conflict ) .
cosqa-train-15975
def recursively_update(d, d2): """dict.update but which merges child dicts (dict2 takes precedence where there's conflict).""" for k, v in d2.items(): if k in d: if isinstance(v, dict): recursively_update(d[k], v) continue d[k] = v
def entropy ( string ) : p , lns = Counter ( string ) , float ( len ( string ) ) return - sum ( count / lns * math . log ( count / lns , 2 ) for count in p . values ( ) )
0
how to get the lexcial diversity in a strings using python
Compute entropy on the string
cosqa-train-15976
def entropy(string): """Compute entropy on the string""" p, lns = Counter(string), float(len(string)) return -sum(count/lns * math.log(count/lns, 2) for count in p.values())
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 )
0
python redis create connection pool
Connect to a redis instance .
cosqa-train-15977
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 _regex_span ( _regex , _str , case_insensitive = True ) : if case_insensitive : flags = regex . IGNORECASE | regex . FULLCASE | regex . VERSION1 else : flags = regex . VERSION1 comp = regex . compile ( _regex , flags = flags ) matches = comp . finditer ( _str ) for match in matches : yield match
0
how to get the span from a match python re
Return all matches in an input string . : rtype : regex . match . span : param _regex : A regular expression pattern . : param _str : Text on which to run the pattern .
cosqa-train-15978
def _regex_span(_regex, _str, case_insensitive=True): """Return all matches in an input string. :rtype : regex.match.span :param _regex: A regular expression pattern. :param _str: Text on which to run the pattern. """ if case_insensitive: flags = regex.IGNORECASE | regex.FULLCASE | regex.VERSION1 else: flags = regex.VERSION1 comp = regex.compile(_regex, flags=flags) matches = comp.finditer(_str) for match in matches: yield match
def __contains__ ( self , key ) : pickled_key = self . _pickle_key ( key ) return bool ( self . redis . hexists ( self . key , pickled_key ) )
0
python redis exists key
Return True if * key * is present else False .
cosqa-train-15979
def __contains__(self, key): """Return ``True`` if *key* is present, else ``False``.""" pickled_key = self._pickle_key(key) return bool(self.redis.hexists(self.key, pickled_key))
def getTypeStr ( _type ) : if isinstance ( _type , CustomType ) : return str ( _type ) if hasattr ( _type , '__name__' ) : return _type . __name__ return ''
0
how to get the type of an object in python
r Gets the string representation of the given type .
cosqa-train-15980
def getTypeStr(_type): r"""Gets the string representation of the given type. """ if isinstance(_type, CustomType): return str(_type) if hasattr(_type, '__name__'): return _type.__name__ return ''
def values ( self ) : for val in self . _client . hvals ( self . key_prefix ) : yield self . _loads ( val )
0
python redis how to get all keys
: see :: meth : RedisMap . keys
cosqa-train-15981
def values(self): """ :see::meth:RedisMap.keys """ for val in self._client.hvals(self.key_prefix): yield self._loads(val)
def rgba_bytes_tuple ( self , x ) : return tuple ( int ( u * 255.9999 ) for u in self . rgba_floats_tuple ( x ) )
1
how to get tuple of colors in image python
Provides the color corresponding to value x in the form of a tuple ( R G B A ) with int values between 0 and 255 .
cosqa-train-15982
def rgba_bytes_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B,A) with int values between 0 and 255. """ return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))
def get_instance ( key , expire = None ) : global _instances try : instance = _instances [ key ] except KeyError : instance = RedisSet ( key , _redis , expire = expire ) _instances [ key ] = instance return instance
0
python redis set return value
Return an instance of RedisSet .
cosqa-train-15983
def get_instance(key, expire=None): """Return an instance of RedisSet.""" global _instances try: instance = _instances[key] except KeyError: instance = RedisSet( key, _redis, expire=expire ) _instances[key] = instance return instance
def generate_unique_host_id ( ) : host = "." . join ( reversed ( socket . gethostname ( ) . split ( "." ) ) ) pid = os . getpid ( ) return "%s.%d" % ( host , pid )
1
how to get unique id using python
Generate a unique ID that is somewhat guaranteed to be unique among all instances running at the same time .
cosqa-train-15984
def generate_unique_host_id(): """Generate a unique ID, that is somewhat guaranteed to be unique among all instances running at the same time.""" host = ".".join(reversed(socket.gethostname().split("."))) pid = os.getpid() return "%s.%d" % (host, pid)
def __setitem__ ( self , field , value ) : return self . _client . hset ( self . key_prefix , field , self . _dumps ( value ) )
0
python redis write set
: see :: meth : RedisMap . __setitem__
cosqa-train-15985
def __setitem__(self, field, value): """ :see::meth:RedisMap.__setitem__ """ return self._client.hset(self.key_prefix, field, self._dumps(value))
def get_week_start_end_day ( ) : t = date . today ( ) wd = t . weekday ( ) return ( t - timedelta ( wd ) , t + timedelta ( 6 - wd ) )
0
how to get weekending date in python
Get the week start date and end date
cosqa-train-15986
def get_week_start_end_day(): """ Get the week start date and end date """ t = date.today() wd = t.weekday() return (t - timedelta(wd), t + timedelta(6 - wd))
def __repr__ ( self ) : return str ( { 'name' : self . _name , 'watts' : self . _watts , 'type' : self . _output_type , 'id' : self . _integration_id } )
0
python refer to object as string representation
Returns a stringified representation of this object .
cosqa-train-15987
def __repr__(self): """Returns a stringified representation of this object.""" return str({'name': self._name, 'watts': self._watts, 'type': self._output_type, 'id': self._integration_id})
def _defaultdict ( dct , fallback = _illegal_character ) : out = defaultdict ( lambda : fallback ) for k , v in six . iteritems ( dct ) : out [ k ] = v return out
0
how to give default value if key does not exist in dictionary python
Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed .
cosqa-train-15988
def _defaultdict(dct, fallback=_illegal_character): """Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed. """ out = defaultdict(lambda: fallback) for k, v in six.iteritems(dct): out[k] = v return out
def unapostrophe ( text ) : text = re . sub ( r'[%s]s?$' % '' . join ( APOSTROPHES ) , '' , text ) return text
0
python reg expression replace apostrophe
Strip apostrophe and s from the end of a string .
cosqa-train-15989
def unapostrophe(text): """Strip apostrophe and 's' from the end of a string.""" text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text) return text
def _validate_input_data ( self , data , request ) : validator = self . _get_input_validator ( request ) if isinstance ( data , ( list , tuple ) ) : return map ( validator . validate , data ) else : return validator . validate ( data )
0
how to give python validation in input
Validate input data .
cosqa-train-15990
def _validate_input_data(self, data, request): """ Validate input data. :param request: the HTTP request :param data: the parsed data :return: if validation is performed and succeeds the data is converted into whatever format the validation uses (by default Django's Forms) If not, the data is returned unchanged. :raises: HttpStatusCodeError if data is not valid """ validator = self._get_input_validator(request) if isinstance(data, (list, tuple)): return map(validator.validate, data) else: return validator.validate(data)
def ismatch ( text , pattern ) : if hasattr ( pattern , 'search' ) : return pattern . search ( text ) is not None else : return pattern in text if Config . options . case_sensitive else pattern . lower ( ) in text . lower ( )
0
python regex contains case insensitive
Test whether text contains string or matches regex .
cosqa-train-15991
def ismatch(text, pattern): """Test whether text contains string or matches regex.""" if hasattr(pattern, 'search'): return pattern.search(text) is not None else: return pattern in text if Config.options.case_sensitive \ else pattern.lower() in text.lower()
def set_xlimits ( self , row , column , min = None , max = None ) : subplot = self . get_subplot_at ( row , column ) subplot . set_xlimits ( min , max )
1
how to give x axis limits in python plot
Set x - axis limits of a subplot .
cosqa-train-15992
def set_xlimits(self, row, column, min=None, max=None): """Set x-axis limits of a subplot. :param row,column: specify the subplot. :param min: minimal axis value :param max: maximum axis value """ subplot = self.get_subplot_at(row, column) subplot.set_xlimits(min, max)
def get_numbers ( s ) : result = map ( int , re . findall ( r'[0-9]+' , unicode ( s ) ) ) return result + [ 1 ] * ( 2 - len ( result ) )
0
python regex get all integers
Extracts all integers from a string an return them in a list
cosqa-train-15993
def get_numbers(s): """Extracts all integers from a string an return them in a list""" result = map(int, re.findall(r'[0-9]+', unicode(s))) return result + [1] * (2 - len(result))
def now_time ( str = False ) : if str : return datetime . datetime . now ( ) . strftime ( "%Y-%m-%d %H:%M:%S" ) return datetime . datetime . now ( )
1
how to grab current time in python 3
Get the current time .
cosqa-train-15994
def now_time(str=False): """Get the current time.""" if str: return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") return datetime.datetime.now()
def camel_to_snake_case ( name ) : pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])' return '_' . join ( map ( str . lower , re . findall ( pattern , name ) ) )
0
python regexp case insensitive
Takes a camelCased string and converts to snake_case .
cosqa-train-15995
def camel_to_snake_case(name): """Takes a camelCased string and converts to snake_case.""" pattern = r'[A-Z][a-z]+|[A-Z]+(?![a-z])' return '_'.join(map(str.lower, re.findall(pattern, name)))
def _add_hash ( source ) : source = '\n' . join ( '# ' + line . rstrip ( ) for line in source . splitlines ( ) ) return source
0
how to hash multiple lines in python
Add a leading hash # at the beginning of every line in the source .
cosqa-train-15996
def _add_hash(source): """Add a leading hash '#' at the beginning of every line in the source.""" source = '\n'.join('# ' + line.rstrip() for line in source.splitlines()) return source
def GetValueByName ( self , name ) : pyregf_value = self . _pyregf_key . get_value_by_name ( name ) if not pyregf_value : return None return REGFWinRegistryValue ( pyregf_value )
1
python regkey get name of key
Retrieves a value by name .
cosqa-train-15997
def GetValueByName(self, name): """Retrieves a value by name. Value names are not unique and pyregf provides first match for the value. Args: name (str): name of the value or an empty string for the default value. Returns: WinRegistryValue: Windows Registry value if a corresponding value was found or None if not. """ pyregf_value = self._pyregf_key.get_value_by_name(name) if not pyregf_value: return None return REGFWinRegistryValue(pyregf_value)
def get_input ( input_func , input_str ) : val = input_func ( "Please enter your {0}: " . format ( input_str ) ) while not val or not len ( val . strip ( ) ) : val = input_func ( "You didn't enter a valid {0}, please try again: " . format ( input_str ) ) return val
1
how to have a string for a function input in python
Get input from the user given an input function and an input string
cosqa-train-15998
def get_input(input_func, input_str): """ Get input from the user given an input function and an input string """ val = input_func("Please enter your {0}: ".format(input_str)) while not val or not len(val.strip()): val = input_func("You didn't enter a valid {0}, please try again: ".format(input_str)) return val
def find_number ( regex , s ) : result = find_string ( regex , s ) if result is None : return None return int ( result )
0
python regular expression for finding an integer from a string
Find a number using a given regular expression . If the string cannot be found returns None . The regex should contain one matching group as only the result of the first group is returned . The group should only contain numeric characters ( [ 0 - 9 ] + ) . s - The string to search . regex - A string containing the regular expression . Returns an integer or None .
cosqa-train-15999
def find_number(regex, s): """Find a number using a given regular expression. If the string cannot be found, returns None. The regex should contain one matching group, as only the result of the first group is returned. The group should only contain numeric characters ([0-9]+). s - The string to search. regex - A string containing the regular expression. Returns an integer or None. """ result = find_string(regex, s) if result is None: return None return int(result)