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 fast_distinct ( self ) : return self . model . objects . filter ( pk__in = self . values_list ( 'pk' , flat = True ) )
0
is there a select distinct in python
Because standard distinct used on the all fields are very slow and works only with PostgreSQL database this method provides alternative to the standard distinct method . : return : qs with unique objects
cosqa-train-16400
def fast_distinct(self): """ Because standard distinct used on the all fields are very slow and works only with PostgreSQL database this method provides alternative to the standard distinct method. :return: qs with unique objects """ return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))
def __grid_widgets ( self ) : scrollbar_column = 0 if self . __compound is tk . LEFT else 2 self . _canvas . grid ( row = 0 , column = 1 , sticky = "nswe" ) self . _scrollbar . grid ( row = 0 , column = scrollbar_column , sticky = "ns" )
0
python widgets dont expand in grid
Places all the child widgets in the appropriate positions .
cosqa-train-16401
def __grid_widgets(self): """Places all the child widgets in the appropriate positions.""" scrollbar_column = 0 if self.__compound is tk.LEFT else 2 self._canvas.grid(row=0, column=1, sticky="nswe") self._scrollbar.grid(row=0, column=scrollbar_column, sticky="ns")
def test ( ) : import unittest tests = unittest . TestLoader ( ) . discover ( 'tests' ) unittest . TextTestRunner ( verbosity = 2 ) . run ( tests )
1
is there a unit test runner in python
Run the unit tests .
cosqa-train-16402
def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests)
def retry_on_signal ( function ) : while True : try : return function ( ) except EnvironmentError , e : if e . errno != errno . EINTR : raise
0
python will the for loop keep going after the try excpetion
Retries function until it doesn t raise an EINTR error
cosqa-train-16403
def retry_on_signal(function): """Retries function until it doesn't raise an EINTR error""" while True: try: return function() except EnvironmentError, e: if e.errno != errno.EINTR: raise
def all_equal ( arg1 , arg2 ) : if all ( hasattr ( el , '_infinitely_iterable' ) for el in [ arg1 , arg2 ] ) : return arg1 == arg2 try : return all ( a1 == a2 for a1 , a2 in zip ( arg1 , arg2 ) ) except TypeError : return arg1 == arg2
1
is there a way in python to check that 2 numpy arrays are identical
Return a single boolean for arg1 == arg2 even for numpy arrays using element - wise comparison .
cosqa-train-16404
def all_equal(arg1,arg2): """ Return a single boolean for arg1==arg2, even for numpy arrays using element-wise comparison. Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise. If both objects have an '_infinitely_iterable' attribute, they are not be zipped together and are compared directly instead. """ if all(hasattr(el, '_infinitely_iterable') for el in [arg1,arg2]): return arg1==arg2 try: return all(a1 == a2 for a1, a2 in zip(arg1, arg2)) except TypeError: return arg1==arg2
def __init__ ( self , encoding = 'utf-8' ) : super ( StdinInputReader , self ) . __init__ ( sys . stdin , encoding = encoding )
0
python windows stdin encoding
Initializes an stdin input reader .
cosqa-train-16405
def __init__(self, encoding='utf-8'): """Initializes an stdin input reader. Args: encoding (Optional[str]): input encoding. """ super(StdinInputReader, self).__init__(sys.stdin, encoding=encoding)
def check_alert ( self , text ) : try : alert = Alert ( world . browser ) if alert . text != text : raise AssertionError ( "Alert text expected to be {!r}, got {!r}." . format ( text , alert . text ) ) except WebDriverException : # PhantomJS is kinda poor pass
0
is there an alert like in javascript in python
Assert an alert is showing with the given text .
cosqa-train-16406
def check_alert(self, text): """ Assert an alert is showing with the given text. """ try: alert = Alert(world.browser) if alert.text != text: raise AssertionError( "Alert text expected to be {!r}, got {!r}.".format( text, alert.text)) except WebDriverException: # PhantomJS is kinda poor pass
def write_fits ( self , fitsfile ) : tab = self . create_table ( ) hdu_data = fits . table_to_hdu ( tab ) hdus = [ fits . PrimaryHDU ( ) , hdu_data ] fits_utils . write_hdus ( hdus , fitsfile )
0
python write header to fits file
Write the ROI model to a FITS file .
cosqa-train-16407
def write_fits(self, fitsfile): """Write the ROI model to a FITS file.""" tab = self.create_table() hdu_data = fits.table_to_hdu(tab) hdus = [fits.PrimaryHDU(), hdu_data] fits_utils.write_hdus(hdus, fitsfile)
def each_img ( img_dir ) : for fname in utils . each_img ( img_dir ) : fname = os . path . join ( img_dir , fname ) yield cv . imread ( fname ) , fname
1
iterate all the images in a directory + python + opencv
Reads and iterates through each image file in the given directory
cosqa-train-16408
def each_img(img_dir): """ Reads and iterates through each image file in the given directory """ for fname in utils.each_img(img_dir): fname = os.path.join(img_dir, fname) yield cv.imread(fname), fname
def save_dict_to_file ( filename , dictionary ) : with open ( filename , 'w' ) as f : writer = csv . writer ( f ) for k , v in iteritems ( dictionary ) : writer . writerow ( [ str ( k ) , str ( v ) ] )
1
python writing a dict to a file
Saves dictionary as CSV file .
cosqa-train-16409
def save_dict_to_file(filename, dictionary): """Saves dictionary as CSV file.""" with open(filename, 'w') as f: writer = csv.writer(f) for k, v in iteritems(dictionary): writer.writerow([str(k), str(v)])
def path_distance ( points ) : vecs = np . diff ( points , axis = 0 ) [ : , : 3 ] d2 = [ np . dot ( p , p ) for p in vecs ] return np . sum ( np . sqrt ( d2 ) )
1
iterate distance over list of points python
Compute the path distance from given set of points
cosqa-train-16410
def path_distance(points): """ Compute the path distance from given set of points """ vecs = np.diff(points, axis=0)[:, :3] d2 = [np.dot(p, p) for p in vecs] return np.sum(np.sqrt(d2))
def series_table_row_offset ( self , series ) : title_and_spacer_rows = series . index * 2 data_point_rows = series . data_point_offset return title_and_spacer_rows + data_point_rows
0
python xl number of entries in a column
Return the number of rows preceding the data table for * series * in the Excel worksheet .
cosqa-train-16411
def series_table_row_offset(self, series): """ Return the number of rows preceding the data table for *series* in the Excel worksheet. """ title_and_spacer_rows = series.index * 2 data_point_rows = series.data_point_offset return title_and_spacer_rows + data_point_rows
def extract_words ( lines ) : for line in lines : for word in re . findall ( r"\w+" , line ) : yield word
0
iterate over words in text line python
Extract from the given iterable of lines the list of words .
cosqa-train-16412
def extract_words(lines): """ Extract from the given iterable of lines the list of words. :param lines: an iterable of lines; :return: a generator of words of lines. """ for line in lines: for word in re.findall(r"\w+", line): yield word
def as_list ( self ) : return [ self . name , self . value , [ x . as_list for x in self . children ] ]
0
python xml elements as a list
Return all child objects in nested lists of strings .
cosqa-train-16413
def as_list(self): """Return all child objects in nested lists of strings.""" return [self.name, self.value, [x.as_list for x in self.children]]
def __next__ ( self , reward , ask_id , lbl ) : return self . next ( reward , ask_id , lbl )
1
iterator inpython has next next
For Python3 compatibility of generator .
cosqa-train-16414
def __next__(self, reward, ask_id, lbl): """For Python3 compatibility of generator.""" return self.next(reward, ask_id, lbl)
def element_to_string ( element , include_declaration = True , encoding = DEFAULT_ENCODING , method = 'xml' ) : if isinstance ( element , ElementTree ) : element = element . getroot ( ) elif not isinstance ( element , ElementType ) : element = get_element ( element ) if element is None : return u'' element_as_string = tostring ( element , encoding , method ) . decode ( encoding = encoding ) if include_declaration : return element_as_string else : return strip_xml_declaration ( element_as_string )
1
python xml elementtree to string
: return : the string value of the element or element tree
cosqa-train-16415
def element_to_string(element, include_declaration=True, encoding=DEFAULT_ENCODING, method='xml'): """ :return: the string value of the element or element tree """ if isinstance(element, ElementTree): element = element.getroot() elif not isinstance(element, ElementType): element = get_element(element) if element is None: return u'' element_as_string = tostring(element, encoding, method).decode(encoding=encoding) if include_declaration: return element_as_string else: return strip_xml_declaration(element_as_string)
def group_by ( iterable , key_func ) : groups = ( list ( sub ) for key , sub in groupby ( iterable , key_func ) ) return zip ( groups , groups )
0
itertools groupby in python list of dicts by key
Wrap itertools . groupby to make life easier .
cosqa-train-16416
def group_by(iterable, key_func): """Wrap itertools.groupby to make life easier.""" groups = ( list(sub) for key, sub in groupby(iterable, key_func) ) return zip(groups, groups)
def _get_minidom_tag_value ( station , tag_name ) : tag = station . getElementsByTagName ( tag_name ) [ 0 ] . firstChild if tag : return tag . nodeValue return None
1
python xml get value in tag
get a value from a tag ( if it exists )
cosqa-train-16417
def _get_minidom_tag_value(station, tag_name): """get a value from a tag (if it exists)""" tag = station.getElementsByTagName(tag_name)[0].firstChild if tag: return tag.nodeValue return None
def jaccard ( c_1 , c_2 ) : nom = np . intersect1d ( c_1 , c_2 ) . size denom = np . union1d ( c_1 , c_2 ) . size return nom / denom
1
jacquard similarity using python
Calculates the Jaccard similarity between two sets of nodes . Called by mroc .
cosqa-train-16418
def jaccard(c_1, c_2): """ Calculates the Jaccard similarity between two sets of nodes. Called by mroc. Inputs: - c_1: Community (set of nodes) 1. - c_2: Community (set of nodes) 2. Outputs: - jaccard_similarity: The Jaccard similarity of these two communities. """ nom = np.intersect1d(c_1, c_2).size denom = np.union1d(c_1, c_2).size return nom/denom
def required_attributes ( element , * attributes ) : if not reduce ( lambda still_valid , param : still_valid and param in element . attrib , attributes , True ) : raise NotValidXmlException ( msg_err_missing_attributes ( element . tag , * attributes ) )
0
python xml parser check attribute
Check element for required attributes . Raise NotValidXmlException on error .
cosqa-train-16419
def required_attributes(element, *attributes): """Check element for required attributes. Raise ``NotValidXmlException`` on error. :param element: ElementTree element :param attributes: list of attributes names to check :raises NotValidXmlException: if some argument is missing """ if not reduce(lambda still_valid, param: still_valid and param in element.attrib, attributes, True): raise NotValidXmlException(msg_err_missing_attributes(element.tag, *attributes))
def join ( mapping , bind , values ) : return [ ' ' . join ( [ six . text_type ( v ) for v in values if v is not None ] ) ]
1
join list of empty strings and strings python
Merge all the strings . Put space between them .
cosqa-train-16420
def join(mapping, bind, values): """ Merge all the strings. Put space between them. """ return [' '.join([six.text_type(v) for v in values if v is not None])]
def xml_str_to_dict ( s ) : xml = minidom . parseString ( s ) return pythonzimbra . tools . xmlserializer . dom_to_dict ( xml . firstChild )
0
python xml to dictionary
Transforms an XML string it to python - zimbra dict format
cosqa-train-16421
def xml_str_to_dict(s): """ Transforms an XML string it to python-zimbra dict format For format, see: https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md :param: a string, containing XML :returns: a dict, with python-zimbra format """ xml = minidom.parseString(s) return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)
def send ( self , topic , * args , * * kwargs ) : prefix_topic = self . heroku_kafka . prefix_topic ( topic ) return super ( HerokuKafkaProducer , self ) . send ( prefix_topic , * args , * * kwargs )
0
kafka python producer not sending message
Appends the prefix to the topic before sendingf
cosqa-train-16422
def send(self, topic, *args, **kwargs): """ Appends the prefix to the topic before sendingf """ prefix_topic = self.heroku_kafka.prefix_topic(topic) return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs)
def root_parent ( self , category = None ) : return next ( filter ( lambda c : c . is_root , self . hierarchy ( ) ) )
1
python xmlnode get parent
Returns the topmost parent of the current category .
cosqa-train-16423
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 best ( self ) : b = ( - 1e999999 , None ) for k , c in iteritems ( self . counts ) : b = max ( b , ( c , k ) ) return b [ 1 ]
0
keep track of 5 largest values in python
Returns the element with the highest probability .
cosqa-train-16424
def best(self): """ Returns the element with the highest probability. """ b = (-1e999999, None) for k, c in iteritems(self.counts): b = max(b, (c, k)) return b[1]
def _Open ( self , hostname , port ) : try : self . _xmlrpc_server = SimpleXMLRPCServer . SimpleXMLRPCServer ( ( hostname , port ) , logRequests = False , allow_none = True ) except SocketServer . socket . error as exception : logger . warning ( ( 'Unable to bind a RPC server on {0:s}:{1:d} with error: ' '{2!s}' ) . format ( hostname , port , exception ) ) return False self . _xmlrpc_server . register_function ( self . _callback , self . _RPC_FUNCTION_NAME ) return True
0
python xmlrpc doesn't work over a network
Opens the RPC communication channel for clients .
cosqa-train-16425
def _Open(self, hostname, port): """Opens the RPC communication channel for clients. Args: hostname (str): hostname or IP address to connect to for requests. port (int): port to connect to for requests. Returns: bool: True if the communication channel was successfully opened. """ try: self._xmlrpc_server = SimpleXMLRPCServer.SimpleXMLRPCServer( (hostname, port), logRequests=False, allow_none=True) except SocketServer.socket.error as exception: logger.warning(( 'Unable to bind a RPC server on {0:s}:{1:d} with error: ' '{2!s}').format(hostname, port, exception)) return False self._xmlrpc_server.register_function( self._callback, self._RPC_FUNCTION_NAME) return True
def predict ( self , X ) : return [ self . classes [ prediction . argmax ( ) ] for prediction in self . predict_proba ( X ) ]
0
keras python sequential predict batch size one one input
Predict the class for X .
cosqa-train-16426
def predict(self, X): """Predict the class for X. The predicted class for each sample in X is returned. Parameters ---------- X : List of ndarrays, one for each training example. Each training example's shape is (string1_len, string2_len, n_features), where string1_len and string2_len are the length of the two training strings and n_features the number of features. Returns ------- y : iterable of shape = [n_samples] The predicted classes. """ return [self.classes[prediction.argmax()] for prediction in self.predict_proba(X)]
def stop ( pid ) : if psutil . pid_exists ( pid ) : try : p = psutil . Process ( pid ) p . kill ( ) except Exception : pass
1
kill a python process in linux
Shut down a specific process .
cosqa-train-16427
def stop(pid): """Shut down a specific process. Args: pid: the pid of the process to shutdown. """ if psutil.pid_exists(pid): try: p = psutil.Process(pid) p.kill() except Exception: pass
def yaml_to_param ( obj , name ) : return from_pyvalue ( u"yaml:%s" % name , unicode ( yaml . dump ( obj ) ) )
0
python yaml as object attributes
Return the top - level element of a document sub - tree containing the YAML serialization of a Python object .
cosqa-train-16428
def yaml_to_param(obj, name): """ Return the top-level element of a document sub-tree containing the YAML serialization of a Python object. """ return from_pyvalue(u"yaml:%s" % name, unicode(yaml.dump(obj)))
def timeout_thread_handler ( timeout , stop_event ) : stop_happened = stop_event . wait ( timeout ) if stop_happened is False : print ( "Killing program due to %f second timeout" % timeout ) os . _exit ( 2 )
0
kill a python program after a time limit
A background thread to kill the process if it takes too long .
cosqa-train-16429
def timeout_thread_handler(timeout, stop_event): """A background thread to kill the process if it takes too long. Args: timeout (float): The number of seconds to wait before killing the process. stop_event (Event): An optional event to cleanly stop the background thread if required during testing. """ stop_happened = stop_event.wait(timeout) if stop_happened is False: print("Killing program due to %f second timeout" % timeout) os._exit(2)
def ParseMany ( text ) : precondition . AssertType ( text , Text ) if compatibility . PY2 : text = text . encode ( "utf-8" ) return list ( yaml . safe_load_all ( text ) )
1
python yaml load multiple documents
Parses many YAML documents into a list of Python objects .
cosqa-train-16430
def ParseMany(text): """Parses many YAML documents into a list of Python objects. Args: text: A YAML source with multiple documents embedded. Returns: A list of Python data structures corresponding to the YAML documents. """ precondition.AssertType(text, Text) if compatibility.PY2: text = text.encode("utf-8") return list(yaml.safe_load_all(text))
def timeout_thread_handler ( timeout , stop_event ) : stop_happened = stop_event . wait ( timeout ) if stop_happened is False : print ( "Killing program due to %f second timeout" % timeout ) os . _exit ( 2 )
1
kill a thread python after a specified time
A background thread to kill the process if it takes too long .
cosqa-train-16431
def timeout_thread_handler(timeout, stop_event): """A background thread to kill the process if it takes too long. Args: timeout (float): The number of seconds to wait before killing the process. stop_event (Event): An optional event to cleanly stop the background thread if required during testing. """ stop_happened = stop_event.wait(timeout) if stop_happened is False: print("Killing program due to %f second timeout" % timeout) os._exit(2)
def safe_dump ( data , stream = None , * * kwds ) : return yaml . dump ( data , stream = stream , Dumper = ODYD , * * kwds )
0
python yaml special dict representation
implementation of safe dumper using Ordered Dict Yaml Dumper
cosqa-train-16432
def safe_dump(data, stream=None, **kwds): """implementation of safe dumper using Ordered Dict Yaml Dumper""" return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)
def cli_command_quit ( self , msg ) : if self . state == State . RUNNING and self . sprocess and self . sprocess . proc : self . sprocess . proc . kill ( ) else : sys . exit ( 0 )
0
kill command for python
\ kills the child and exits
cosqa-train-16433
def cli_command_quit(self, msg): """\ kills the child and exits """ if self.state == State.RUNNING and self.sprocess and self.sprocess.proc: self.sprocess.proc.kill() else: sys.exit(0)
def yaml_to_param ( obj , name ) : return from_pyvalue ( u"yaml:%s" % name , unicode ( yaml . dump ( obj ) ) )
0
python yaml store as dict
Return the top - level element of a document sub - tree containing the YAML serialization of a Python object .
cosqa-train-16434
def yaml_to_param(obj, name): """ Return the top-level element of a document sub-tree containing the YAML serialization of a Python object. """ return from_pyvalue(u"yaml:%s" % name, unicode(yaml.dump(obj)))
def kill_test_logger ( logger ) : for h in list ( logger . handlers ) : logger . removeHandler ( h ) if isinstance ( h , logging . FileHandler ) : h . close ( )
1
killing logging handlers in python
Cleans up a test logger object by removing all of its handlers .
cosqa-train-16435
def kill_test_logger(logger): """Cleans up a test logger object by removing all of its handlers. Args: logger: The logging object to clean up. """ for h in list(logger.handlers): logger.removeHandler(h) if isinstance(h, logging.FileHandler): h.close()
def trap_exceptions ( results , handler , exceptions = Exception ) : try : for result in results : yield result except exceptions as exc : for result in always_iterable ( handler ( exc ) ) : yield result
1
python yield catch except
Iterate through the results but if an exception occurs stop processing the results and instead replace the results with the output from the exception handler .
cosqa-train-16436
def trap_exceptions(results, handler, exceptions=Exception): """ Iterate through the results, but if an exception occurs, stop processing the results and instead replace the results with the output from the exception handler. """ try: for result in results: yield result except exceptions as exc: for result in always_iterable(handler(exc)): yield result
def _most_common ( iterable ) : data = Counter ( iterable ) return max ( data , key = data . __getitem__ )
0
least common element in a list python
Returns the most common element in iterable .
cosqa-train-16437
def _most_common(iterable): """Returns the most common element in `iterable`.""" data = Counter(iterable) return max(data, key=data.__getitem__)
def connected_socket ( address , timeout = 3 ) : sock = socket . create_connection ( address , timeout ) yield sock sock . close ( )
0
python yield from memory leak
yields a connected socket
cosqa-train-16438
def connected_socket(address, timeout=3): """ yields a connected socket """ sock = socket.create_connection(address, timeout) yield sock sock.close()
def value_left ( self , other ) : return other . value if isinstance ( other , self . __class__ ) else other
1
left right function in python
Returns the value of the other type instance to use in an operator method namely when the method s instance is on the left side of the expression .
cosqa-train-16439
def value_left(self, other): """ Returns the value of the other type instance to use in an operator method, namely when the method's instance is on the left side of the expression. """ return other.value if isinstance(other, self.__class__) else other
def _return_result ( self , done ) : chain_future ( done , self . _running_future ) self . current_future = done self . current_index = self . _unfinished . pop ( done )
0
python yield how to know the function is finish
Called set the returned future s state that of the future we yielded and set the current future for the iterator .
cosqa-train-16440
def _return_result(self, done): """Called set the returned future's state that of the future we yielded, and set the current future for the iterator. """ chain_future(done, self._running_future) self.current_future = done self.current_index = self._unfinished.pop(done)
def pprint ( obj , verbose = False , max_width = 79 , newline = '\n' ) : printer = RepresentationPrinter ( sys . stdout , verbose , max_width , newline ) printer . pretty ( obj ) printer . flush ( ) sys . stdout . write ( newline ) sys . stdout . flush ( )
0
limit character length on print python
Like pretty but print to stdout .
cosqa-train-16441
def pprint(obj, verbose=False, max_width=79, newline='\n'): """ Like `pretty` but print to stdout. """ printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline) printer.pretty(obj) printer.flush() sys.stdout.write(newline) sys.stdout.flush()
def unzip_file_to_dir ( path_to_zip , output_directory ) : z = ZipFile ( path_to_zip , 'r' ) z . extractall ( output_directory ) z . close ( )
0
python zipfile unzip to folder
Extract a ZIP archive to a directory
cosqa-train-16442
def unzip_file_to_dir(path_to_zip, output_directory): """ Extract a ZIP archive to a directory """ z = ZipFile(path_to_zip, 'r') z.extractall(output_directory) z.close()
def _get_xy_scaling_parameters ( self ) : return self . mx , self . bx , self . my , self . by
0
limit x and y python
Get the X / Y coordinate limits for the full resulting image
cosqa-train-16443
def _get_xy_scaling_parameters(self): """Get the X/Y coordinate limits for the full resulting image""" return self.mx, self.bx, self.my, self.by
def start ( self , test_connection = True ) : if self . _context is None : self . _logger . debug ( 'Starting Client' ) self . _context = zmq . Context ( ) self . _poll = zmq . Poller ( ) self . _start_socket ( ) if test_connection : self . test_ping ( )
1
python zmq check if connected
Starts connection to server if not existent .
cosqa-train-16444
def start(self, test_connection=True): """Starts connection to server if not existent. NO-OP if connection is already established. Makes ping-pong test as well if desired. """ if self._context is None: self._logger.debug('Starting Client') self._context = zmq.Context() self._poll = zmq.Poller() self._start_socket() if test_connection: self.test_ping()
def open01 ( x , limit = 1.e-6 ) : try : return np . array ( [ min ( max ( y , limit ) , 1. - limit ) for y in x ] ) except TypeError : return min ( max ( x , limit ) , 1. - limit )
0
limiting a floating number range python
Constrain numbers to ( 0 1 ) interval
cosqa-train-16445
def open01(x, limit=1.e-6): """Constrain numbers to (0,1) interval""" try: return np.array([min(max(y, limit), 1. - limit) for y in x]) except TypeError: return min(max(x, limit), 1. - limit)
def init_mq ( self ) : mq = self . init_connection ( ) self . init_consumer ( mq ) return mq . connection
0
python zmq fork new connection
Init connection and consumer with openstack mq .
cosqa-train-16446
def init_mq(self): """Init connection and consumer with openstack mq.""" mq = self.init_connection() self.init_consumer(mq) return mq.connection
def _on_text_changed ( self ) : if not self . _cleaning : ln = TextHelper ( self ) . cursor_position ( ) [ 0 ] self . _modified_lines . add ( ln )
0
line edit changed signal python
Adjust dirty flag depending on editor s content
cosqa-train-16447
def _on_text_changed(self): """ Adjust dirty flag depending on editor's content """ if not self._cleaning: ln = TextHelper(self).cursor_position()[0] self._modified_lines.add(ln)
def qsize ( self ) : self . mutex . acquire ( ) n = self . _qsize ( ) self . mutex . release ( ) return n
0
python zmq get queue length
Return the approximate size of the queue ( not reliable! ) .
cosqa-train-16448
def qsize(self): """Return the approximate size of the queue (not reliable!).""" self.mutex.acquire() n = self._qsize() self.mutex.release() return n
def _linearInterpolationTransformMatrix ( matrix1 , matrix2 , value ) : return tuple ( _interpolateValue ( matrix1 [ i ] , matrix2 [ i ] , value ) for i in range ( len ( matrix1 ) ) )
0
linear interpolation of 3 arrays in python
Linear oldstyle interpolation of the transform matrix .
cosqa-train-16449
def _linearInterpolationTransformMatrix(matrix1, matrix2, value): """ Linear, 'oldstyle' interpolation of the transform matrix.""" return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1)))
def clean ( some_string , uppercase = False ) : if uppercase : return some_string . strip ( ) . upper ( ) else : return some_string . strip ( ) . lower ( )
0
python, accepting a string input as upper or lower case
helper to clean up an input string
cosqa-train-16450
def clean(some_string, uppercase=False): """ helper to clean up an input string """ if uppercase: return some_string.strip().upper() else: return some_string.strip().lower()
def stack_as_string ( ) : if sys . version_info . major == 3 : stack = io . StringIO ( ) else : stack = io . BytesIO ( ) traceback . print_stack ( file = stack ) stack . seek ( 0 ) stack = stack . read ( ) return stack
0
linux python3 stack trace
stack_as_string
cosqa-train-16451
def stack_as_string(): """ stack_as_string """ if sys.version_info.major == 3: stack = io.StringIO() else: stack = io.BytesIO() traceback.print_stack(file=stack) stack.seek(0) stack = stack.read() return stack
def qsize ( self ) : self . mutex . acquire ( ) n = self . _qsize ( ) self . mutex . release ( ) return n
1
python, get the size of the queue
Return the approximate size of the queue ( not reliable! ) .
cosqa-train-16452
def qsize(self): """Return the approximate size of the queue (not reliable!).""" self.mutex.acquire() n = self._qsize() self.mutex.release() return n
def get_previous_month ( self ) : end = utils . get_month_start ( ) - relativedelta ( days = 1 ) end = utils . to_datetime ( end ) start = utils . get_month_start ( end ) return start , end
0
list following months entered in python
Returns date range for the previous full month .
cosqa-train-16453
def get_previous_month(self): """Returns date range for the previous full month.""" end = utils.get_month_start() - relativedelta(days=1) end = utils.to_datetime(end) start = utils.get_month_start(end) return start, end
def shape_list ( l , shape , dtype ) : return np . array ( l , dtype = dtype ) . reshape ( shape )
1
python, reshape a list to array
Shape a list of lists into the appropriate shape and data type
cosqa-train-16454
def shape_list(l,shape,dtype): """ Shape a list of lists into the appropriate shape and data type """ return np.array(l, dtype=dtype).reshape(shape)
def append_position_to_token_list ( token_list ) : return [ PositionToken ( value . content , value . gd , index , index + 1 ) for ( index , value ) in enumerate ( token_list ) ]
1
list of a list of tokens python
Converts a list of Token into a list of Token asuming size == 1
cosqa-train-16455
def append_position_to_token_list(token_list): """Converts a list of Token into a list of Token, asuming size == 1""" return [PositionToken(value.content, value.gd, index, index+1) for (index, value) in enumerate(token_list)]
def ms_to_datetime ( ms ) : dt = datetime . datetime . utcfromtimestamp ( ms / 1000 ) return dt . replace ( microsecond = ( ms % 1000 ) * 1000 ) . replace ( tzinfo = pytz . utc )
0
python, time to milliseconds
Converts a millisecond accuracy timestamp to a datetime
cosqa-train-16456
def ms_to_datetime(ms): """ Converts a millisecond accuracy timestamp to a datetime """ dt = datetime.datetime.utcfromtimestamp(ms / 1000) return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)
def display_list_by_prefix ( names_list , starting_spaces = 0 ) : cur_prefix , result_lines = None , [ ] space = " " * starting_spaces for name in sorted ( names_list ) : split = name . split ( "_" , 1 ) prefix = split [ 0 ] if cur_prefix != prefix : result_lines . append ( space + prefix + ":" ) cur_prefix = prefix result_lines . append ( space + " * " + name ) return "\n" . join ( result_lines )
1
list of prefixes and show as headers python
Creates a help string for names_list grouped by prefix .
cosqa-train-16457
def display_list_by_prefix(names_list, starting_spaces=0): """Creates a help string for names_list grouped by prefix.""" cur_prefix, result_lines = None, [] space = " " * starting_spaces for name in sorted(names_list): split = name.split("_", 1) prefix = split[0] if cur_prefix != prefix: result_lines.append(space + prefix + ":") cur_prefix = prefix result_lines.append(space + " * " + name) return "\n".join(result_lines)
def _get_random_id ( ) : symbols = string . ascii_uppercase + string . ascii_lowercase + string . digits return '' . join ( random . choice ( symbols ) for _ in range ( 15 ) )
1
python3 create random unique identifier
Get a random ( i . e . unique ) string identifier
cosqa-train-16458
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 is_iterable ( value ) : return isinstance ( value , np . ndarray ) or isinstance ( value , list ) or isinstance ( value , tuple ) , value
1
list or nd array type check python
must be an iterable ( list array tuple )
cosqa-train-16459
def is_iterable(value): """must be an iterable (list, array, tuple)""" return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value
def cint32_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_int32 ) ) : return np . fromiter ( cptr , dtype = np . int32 , count = length ) else : raise RuntimeError ( 'Expected int pointer' )
0
python3 ctypes pointer of array
Convert a ctypes int pointer array to a numpy array .
cosqa-train-16460
def cint32_array_to_numpy(cptr, length): """Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)): return np.fromiter(cptr, dtype=np.int32, count=length) else: raise RuntimeError('Expected int pointer')
def flatten_array ( grid ) : grid = [ grid [ i ] [ j ] for i in range ( len ( grid ) ) for j in range ( len ( grid [ i ] ) ) ] while type ( grid [ 0 ] ) is list : grid = flatten_array ( grid ) return grid
0
list python numpy flatten
Takes a multi - dimensional array and returns a 1 dimensional array with the same contents .
cosqa-train-16461
def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """ grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
def get_md5_for_file ( file ) : md5 = hashlib . md5 ( ) while True : data = file . read ( md5 . block_size ) if not data : break md5 . update ( data ) return md5 . hexdigest ( )
0
python3 get file md5
Get the md5 hash for a file .
cosqa-train-16462
def get_md5_for_file(file): """Get the md5 hash for a file. :param file: the file to get the md5 hash for """ md5 = hashlib.md5() while True: data = file.read(md5.block_size) if not data: break md5.update(data) return md5.hexdigest()
def get_iter_string_reader ( stdin ) : bufsize = 1024 iter_str = ( stdin [ i : i + bufsize ] for i in range ( 0 , len ( stdin ) , bufsize ) ) return get_iter_chunk_reader ( iter_str )
1
python3 how read a stream buffer without eof
return an iterator that returns a chunk of a string every time it is called . notice that even though bufsize_type might be line buffered we re not doing any line buffering here . that s because our StreamBufferer handles all buffering . we just need to return a reasonable - sized chunk .
cosqa-train-16463
def get_iter_string_reader(stdin): """ return an iterator that returns a chunk of a string every time it is called. notice that even though bufsize_type might be line buffered, we're not doing any line buffering here. that's because our StreamBufferer handles all buffering. we just need to return a reasonable-sized chunk. """ bufsize = 1024 iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize)) return get_iter_chunk_reader(iter_str)
def _get_all_constants ( ) : return [ key for key in globals ( ) . keys ( ) if all ( [ not key . startswith ( "_" ) , # publicly accesible key . upper ( ) == key , # uppercase type ( globals ( ) [ key ] ) in _ALLOWED # and with type from _ALLOWED ] ) ]
0
list the constants in a python file dynamically
Get list of all uppercase non - private globals ( doesn t start with _ ) .
cosqa-train-16464
def _get_all_constants(): """ Get list of all uppercase, non-private globals (doesn't start with ``_``). Returns: list: Uppercase names defined in `globals()` (variables from this \ module). """ return [ key for key in globals().keys() if all([ not key.startswith("_"), # publicly accesible key.upper() == key, # uppercase type(globals()[key]) in _ALLOWED # and with type from _ALLOWED ]) ]
def dedupe_list ( l ) : result = [ ] for el in l : if el not in result : result . append ( el ) return result
1
python3 how to remove multiple items from a list
Remove duplicates from a list preserving the order .
cosqa-train-16465
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 recarray ( self ) : return numpy . rec . fromrecords ( self . records , names = self . names )
0
list to np array in python without add additional dimension
Returns data as : class : numpy . recarray .
cosqa-train-16466
def recarray(self): """Returns data as :class:`numpy.recarray`.""" return numpy.rec.fromrecords(self.records, names=self.names)
def ip_address_list ( ips ) : # first, try it as a single IP address try : return ip_address ( ips ) except ValueError : pass # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it return list ( ipaddress . ip_network ( u ( ips ) ) . hosts ( ) )
0
python3 ip expand cidr notations
IP address range validation and expansion .
cosqa-train-16467
def ip_address_list(ips): """ IP address range validation and expansion. """ # first, try it as a single IP address try: return ip_address(ips) except ValueError: pass # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it return list(ipaddress.ip_network(u(ips)).hosts())
def be_array_from_bytes ( fmt , data ) : arr = array . array ( str ( fmt ) , data ) return fix_byteorder ( arr )
0
load in data as bytearray python
Reads an array from bytestring with big - endian data .
cosqa-train-16468
def be_array_from_bytes(fmt, data): """ Reads an array from bytestring with big-endian data. """ arr = array.array(str(fmt), data) return fix_byteorder(arr)
def polite_string ( a_string ) : if is_py3 ( ) and hasattr ( a_string , 'decode' ) : try : return a_string . decode ( 'utf-8' ) except UnicodeDecodeError : return a_string return a_string
0
python3 not equal string
Returns a proper string that should work in both Py3 / Py2
cosqa-train-16469
def polite_string(a_string): """Returns a "proper" string that should work in both Py3/Py2""" if is_py3() and hasattr(a_string, 'decode'): try: return a_string.decode('utf-8') except UnicodeDecodeError: return a_string return a_string
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
load javascript file in python
Imports from javascript source file . globals is your globals ()
cosqa-train-16470
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 paste ( cmd = paste_cmd , stdout = PIPE ) : return Popen ( cmd , stdout = stdout ) . communicate ( ) [ 0 ] . decode ( 'utf-8' )
1
python3 read linux clipboard
Returns system clipboard contents .
cosqa-train-16471
def paste(cmd=paste_cmd, stdout=PIPE): """Returns system clipboard contents. """ return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')
def Load ( file ) : with open ( file , 'rb' ) as file : model = dill . load ( file ) return model
1
loading a file in python
Loads a model from specified file
cosqa-train-16472
def Load(file): """ Loads a model from specified file """ with open(file, 'rb') as file: model = dill.load(file) return model
def py3round ( number ) : if abs ( round ( number ) - number ) == 0.5 : return int ( 2.0 * round ( number / 2.0 ) ) return int ( round ( number ) )
0
python3 round comparison float
Unified rounding in all python versions .
cosqa-train-16473
def py3round(number): """Unified rounding in all python versions.""" if abs(round(number) - number) == 0.5: return int(2.0 * round(number / 2.0)) return int(round(number))
def delete_lines ( self ) : cursor = self . textCursor ( ) self . __select_text_under_cursor_blocks ( cursor ) cursor . removeSelectedText ( ) cursor . deleteChar ( ) return True
0
python3 select all text in a text document and delete text
Deletes the document lines under cursor .
cosqa-train-16474
def delete_lines(self): """ Deletes the document lines under cursor. :return: Method success. :rtype: bool """ cursor = self.textCursor() self.__select_text_under_cursor_blocks(cursor) cursor.removeSelectedText() cursor.deleteChar() return True
def __enter__ ( self ) : self . fd = open ( self . filename , 'a' ) fcntl . lockf ( self . fd , fcntl . LOCK_EX ) return self . fd
0
lock the file python
Acquire a lock on the output file prevents collisions between multiple runs .
cosqa-train-16475
def __enter__(self): """Acquire a lock on the output file, prevents collisions between multiple runs.""" self.fd = open(self.filename, 'a') fcntl.lockf(self.fd, fcntl.LOCK_EX) return self.fd
def to_bytes ( value ) : vtype = type ( value ) if vtype == bytes or vtype == type ( None ) : return value try : return vtype . encode ( value ) except UnicodeEncodeError : pass return value
0
python3 string byte enciode
str to bytes ( py3k )
cosqa-train-16476
def to_bytes(value): """ str to bytes (py3k) """ vtype = type(value) if vtype == bytes or vtype == type(None): return value try: return vtype.encode(value) except UnicodeEncodeError: pass return value
def ln_norm ( x , mu , sigma = 1.0 ) : return np . log ( stats . norm ( loc = mu , scale = sigma ) . pdf ( x ) )
0
log normal distribution in python
Natural log of scipy norm function truncated at zero
cosqa-train-16477
def ln_norm(x, mu, sigma=1.0): """ Natural log of scipy norm function truncated at zero """ return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))
def _run_cmd_get_output ( cmd ) : process = subprocess . Popen ( cmd . split ( ) , stdout = subprocess . PIPE ) out , err = process . communicate ( ) return out or err
0
python3 subprocess get stdout text
Runs a shell command returns console output .
cosqa-train-16478
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 cric__lasso ( ) : model = sklearn . linear_model . LogisticRegression ( penalty = "l1" , C = 0.002 ) # we want to explain the raw probability outputs of the trees model . predict = lambda X : model . predict_proba ( X ) [ : , 1 ] return model
0
logistic regression lasso python
Lasso Regression
cosqa-train-16479
def cric__lasso(): """ Lasso Regression """ model = sklearn.linear_model.LogisticRegression(penalty="l1", C=0.002) # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
def unique ( transactions ) : seen = set ( ) # TODO: Handle comments return [ x for x in transactions if not ( x in seen or seen . add ( x ) ) ]
0
python3 syntax for deletin g duplicate entries
Remove any duplicate entries .
cosqa-train-16480
def unique(transactions): """ Remove any duplicate entries. """ seen = set() # TODO: Handle comments return [x for x in transactions if not (x in seen or seen.add(x))]
def survival ( value = t , lam = lam , f = failure ) : return sum ( f * log ( lam ) - lam * value )
0
logistic regression overflow python
Exponential survival likelihood accounting for censoring
cosqa-train-16481
def survival(value=t, lam=lam, f=failure): """Exponential survival likelihood, accounting for censoring""" return sum(f * log(lam) - lam * value)
def to_identifier ( s ) : if s . startswith ( 'GPS' ) : s = 'Gps' + s [ 3 : ] return '' . join ( [ i . capitalize ( ) for i in s . split ( '_' ) ] ) if '_' in s else s
0
pythone code to make first and last letter of string capital
Convert snake_case to camel_case .
cosqa-train-16482
def to_identifier(s): """ Convert snake_case to camel_case. """ if s.startswith('GPS'): s = 'Gps' + s[3:] return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s
def get_longest_orf ( orfs ) : sorted_orf = sorted ( orfs , key = lambda x : len ( x [ 'sequence' ] ) , reverse = True ) [ 0 ] return sorted_orf
0
longest non decreasing subsequence python
Find longest ORF from the given list of ORFs .
cosqa-train-16483
def get_longest_orf(orfs): """Find longest ORF from the given list of ORFs.""" sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0] return sorted_orf
def get_table_columns ( dbconn , tablename ) : cur = dbconn . cursor ( ) cur . execute ( "PRAGMA table_info('%s');" % tablename ) info = cur . fetchall ( ) cols = [ ( i [ 1 ] , i [ 2 ] ) for i in info ] return cols
1
pythong mysql how to get column names
Return a list of tuples specifying the column name and type
cosqa-train-16484
def get_table_columns(dbconn, tablename): """ Return a list of tuples specifying the column name and type """ cur = dbconn.cursor() cur.execute("PRAGMA table_info('%s');" % tablename) info = cur.fetchall() cols = [(i[1], i[2]) for i in info] return cols
def strip_spaces ( s ) : return u" " . join ( [ c for c in s . split ( u' ' ) if c ] )
0
loooping through a string with white spaces python
Strip excess spaces from a string
cosqa-train-16485
def strip_spaces(s): """ Strip excess spaces from a string """ return u" ".join([c for c in s.split(u' ') if c])
def is_non_empty_string ( input_string ) : try : if not input_string . strip ( ) : raise ValueError ( ) except AttributeError as error : raise TypeError ( error ) return True
1
pythonic way to check if a string is empty
Validate if non empty string
cosqa-train-16486
def is_non_empty_string(input_string): """ Validate if non empty string :param input_string: Input is a *str*. :return: True if input is string and non empty. Raise :exc:`Exception` otherwise. """ try: if not input_string.strip(): raise ValueError() except AttributeError as error: raise TypeError(error) return True
def _unordered_iterator ( self ) : for i , qs in zip ( self . _queryset_idxs , self . _querysets ) : for item in qs : setattr ( item , '#' , i ) yield item
0
loop through queryset python
Return the value of each QuerySet but also add the # property to each return item .
cosqa-train-16487
def _unordered_iterator(self): """ Return the value of each QuerySet, but also add the '#' property to each return item. """ for i, qs in zip(self._queryset_idxs, self._querysets): for item in qs: setattr(item, '#', i) yield item
def handle_qbytearray ( obj , encoding ) : if isinstance ( obj , QByteArray ) : obj = obj . data ( ) return to_text_string ( obj , encoding = encoding )
0
qbytearray to python str
Qt / Python2 / 3 compatibility helper .
cosqa-train-16488
def handle_qbytearray(obj, encoding): """Qt/Python2/3 compatibility helper.""" if isinstance(obj, QByteArray): obj = obj.data() return to_text_string(obj, encoding=encoding)
def searchlast ( self , n = 10 ) : solutions = deque ( [ ] , n ) for solution in self : solutions . append ( solution ) return solutions
0
loops through the last n elements python
Return the last n results ( or possibly less if not found ) . Note that the last results are not necessarily the best ones! Depending on the search type .
cosqa-train-16489
def searchlast(self,n=10): """Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.""" solutions = deque([], n) for solution in self: solutions.append(solution) return solutions
def search ( self , filterstr , attrlist ) : return self . _paged_search_ext_s ( self . settings . BASE , ldap . SCOPE_SUBTREE , filterstr = filterstr , attrlist = attrlist , page_size = self . settings . PAGE_SIZE )
1
query server objects ldap in python
Query the configured LDAP server .
cosqa-train-16490
def search(self, filterstr, attrlist): """Query the configured LDAP server.""" return self._paged_search_ext_s(self.settings.BASE, ldap.SCOPE_SUBTREE, filterstr=filterstr, attrlist=attrlist, page_size=self.settings.PAGE_SIZE)
def osx_clipboard_get ( ) : p = subprocess . Popen ( [ 'pbpaste' , '-Prefer' , 'ascii' ] , stdout = subprocess . PIPE ) text , stderr = p . communicate ( ) # Text comes in with old Mac \r line endings. Change them to \n. text = text . replace ( '\r' , '\n' ) return text
0
mac python clean clipboard
Get the clipboard s text on OS X .
cosqa-train-16491
def osx_clipboard_get(): """ Get the clipboard's text on OS X. """ p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'], stdout=subprocess.PIPE) text, stderr = p.communicate() # Text comes in with old Mac \r line endings. Change them to \n. text = text.replace('\r', '\n') return text
def urlencoded ( body , charset = 'ascii' , * * kwargs ) : return parse_query_string ( text ( body , charset = charset ) , False )
1
querystring to url python
Converts query strings into native Python objects
cosqa-train-16492
def urlencoded(body, charset='ascii', **kwargs): """Converts query strings into native Python objects""" return parse_query_string(text(body, charset=charset), False)
def magnitude ( X ) : r = np . real ( X ) i = np . imag ( X ) return np . sqrt ( r * r + i * i )
0
magnitude of matrix exponential python
Magnitude of a complex matrix .
cosqa-train-16493
def magnitude(X): """Magnitude of a complex matrix.""" r = np.real(X) i = np.imag(X) return np.sqrt(r * r + i * i);
def pack_triples_numpy ( triples ) : if len ( triples ) == 0 : return np . array ( [ ] , dtype = np . int64 ) return np . stack ( list ( map ( _transform_triple_numpy , triples ) ) , axis = 0 )
0
quick way to make a python array with sequence without forloop
Packs a list of triple indexes into a 2D numpy array .
cosqa-train-16494
def pack_triples_numpy(triples): """Packs a list of triple indexes into a 2D numpy array.""" if len(triples) == 0: return np.array([], dtype=np.int64) return np.stack(list(map(_transform_triple_numpy, triples)), axis=0)
def image_set_aspect ( aspect = 1.0 , axes = "gca" ) : if axes is "gca" : axes = _pylab . gca ( ) e = axes . get_images ( ) [ 0 ] . get_extent ( ) axes . set_aspect ( abs ( ( e [ 1 ] - e [ 0 ] ) / ( e [ 3 ] - e [ 2 ] ) ) / aspect )
0
maintaining an aspect ration in gridspec python
sets the aspect ratio of the current zoom level of the imshow image
cosqa-train-16495
def image_set_aspect(aspect=1.0, axes="gca"): """ sets the aspect ratio of the current zoom level of the imshow image """ if axes is "gca": axes = _pylab.gca() e = axes.get_images()[0].get_extent() axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)
def positive_integer ( anon , obj , field , val ) : return anon . faker . positive_integer ( field = field )
1
random int except a number python
Returns a random positive integer ( for a Django PositiveIntegerField )
cosqa-train-16496
def positive_integer(anon, obj, field, val): """ Returns a random positive integer (for a Django PositiveIntegerField) """ return anon.faker.positive_integer(field=field)
def str_dict ( some_dict ) : return { str ( k ) : str ( v ) for k , v in some_dict . items ( ) }
0
make a dict a string python
Convert dict of ascii str / unicode to dict of str if necessary
cosqa-train-16497
def str_dict(some_dict): """Convert dict of ascii str/unicode to dict of str, if necessary""" return {str(k): str(v) for k, v in some_dict.items()}
def runiform ( lower , upper , size = None ) : return np . random . uniform ( lower , upper , size )
0
random number of a given range python
Random uniform variates .
cosqa-train-16498
def runiform(lower, upper, size=None): """ Random uniform variates. """ return np.random.uniform(lower, upper, size)
def stringify_dict_contents ( dct ) : return { str_if_nested_or_str ( k ) : str_if_nested_or_str ( v ) for k , v in dct . items ( ) }
0
make a dictionary a string in python
Turn dict keys and values into native strings .
cosqa-train-16499
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() }