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 out ( self , output , newline = True ) : click . echo ( output , nl = newline )
1
making clickable text in python
Outputs a string to the console ( stdout ) .
cosqa-train-14300
def out(self, output, newline=True): """Outputs a string to the console (stdout).""" click.echo(output, nl=newline)
def check_by_selector ( self , selector ) : elem = find_element_by_jquery ( world . browser , selector ) if not elem . is_selected ( ) : elem . click ( )
1
python webdriver checkbox checked
Check the checkbox matching the CSS selector .
cosqa-train-14301
def check_by_selector(self, selector): """Check the checkbox matching the CSS selector.""" elem = find_element_by_jquery(world.browser, selector) if not elem.is_selected(): elem.click()
def timestamp_to_datetime ( timestamp ) : from datetime import datetime , timedelta obj = datetime . fromtimestamp ( timestamp [ 0 ] ) return obj + timedelta ( microseconds = int ( timestamp [ 1 ] ) )
0
manipulate timestamp datatype python
Convert an ARF timestamp to a datetime . datetime object ( naive local time )
cosqa-train-14302
def timestamp_to_datetime(timestamp): """Convert an ARF timestamp to a datetime.datetime object (naive local time)""" from datetime import datetime, timedelta obj = datetime.fromtimestamp(timestamp[0]) return obj + timedelta(microseconds=int(timestamp[1]))
def check_by_selector ( self , selector ) : elem = find_element_by_jquery ( world . browser , selector ) if not elem . is_selected ( ) : elem . click ( )
1
python webkit check element
Check the checkbox matching the CSS selector .
cosqa-train-14303
def check_by_selector(self, selector): """Check the checkbox matching the CSS selector.""" elem = find_element_by_jquery(world.browser, selector) if not elem.is_selected(): elem.click()
def map ( cls , iterable , func , * a , * * kw ) : return cls ( func ( x , * a , * * kw ) for x in iterable )
1
map python 'function' object is not iterable
Iterable - first replacement of Python s built - in map () function .
cosqa-train-14304
def map(cls, iterable, func, *a, **kw): """ Iterable-first replacement of Python's built-in `map()` function. """ return cls(func(x, *a, **kw) for x in iterable)
def _close_websocket ( self ) : close_method = getattr ( self . _websocket , "close" , None ) if callable ( close_method ) : asyncio . ensure_future ( close_method ( ) , loop = self . _event_loop ) self . _websocket = None self . _dispatch_event ( event = "close" )
1
python websocket logout after send a message
Closes the websocket connection .
cosqa-train-14305
def _close_websocket(self): """Closes the websocket connection.""" close_method = getattr(self._websocket, "close", None) if callable(close_method): asyncio.ensure_future(close_method(), loop=self._event_loop) self._websocket = None self._dispatch_event(event="close")
def _group_dict_set ( iterator ) : d = defaultdict ( set ) for key , value in iterator : d [ key ] . add ( value ) return dict ( d )
1
mapping a set with a dictionary in python
Make a dict that accumulates the values for each key in an iterator of doubles .
cosqa-train-14306
def _group_dict_set(iterator): """Make a dict that accumulates the values for each key in an iterator of doubles. :param iter[tuple[A,B]] iterator: An iterator :rtype: dict[A,set[B]] """ d = defaultdict(set) for key, value in iterator: d[key].add(value) return dict(d)
def _increase_file_handle_limit ( ) : logging . info ( 'Increasing file handle limit to {}' . format ( constants . FILE_HANDLE_LIMIT ) ) resource . setrlimit ( resource . RLIMIT_NOFILE , ( constants . FILE_HANDLE_LIMIT , resource . RLIM_INFINITY ) )
1
python windows increase file handle limit
Raise the open file handles permitted by the Dusty daemon process and its child processes . The number we choose here needs to be within the OS X default kernel hard limit which is 10240 .
cosqa-train-14307
def _increase_file_handle_limit(): """Raise the open file handles permitted by the Dusty daemon process and its child processes. The number we choose here needs to be within the OS X default kernel hard limit, which is 10240.""" logging.info('Increasing file handle limit to {}'.format(constants.FILE_HANDLE_LIMIT)) resource.setrlimit(resource.RLIMIT_NOFILE, (constants.FILE_HANDLE_LIMIT, resource.RLIM_INFINITY))
def asMaskedArray ( self ) : return ma . masked_array ( data = self . data , mask = self . mask , fill_value = self . fill_value )
1
masked array to numpy array python
Creates converts to a masked array
cosqa-train-14308
def asMaskedArray(self): """ Creates converts to a masked array """ return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)
def acquire_nix ( lock_file ) : # pragma: no cover fd = os . open ( lock_file , OPEN_MODE ) try : fcntl . flock ( fd , fcntl . LOCK_EX | fcntl . LOCK_NB ) except ( IOError , OSError ) : os . close ( fd ) else : return fd
1
python windows lock file
Acquire a lock file on linux or osx .
cosqa-train-14309
def acquire_nix(lock_file): # pragma: no cover """Acquire a lock file on linux or osx.""" fd = os.open(lock_file, OPEN_MODE) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except (IOError, OSError): os.close(fd) else: return fd
def array ( self ) : return np . arange ( self . start , self . stop , self . step )
0
matlab equivalent of python arange
return the underlying numpy array
cosqa-train-14310
def array(self): """ return the underlying numpy array """ return np.arange(self.start, self.stop, self.step)
def __Logout ( si ) : try : if si : content = si . RetrieveContent ( ) content . sessionManager . Logout ( ) except Exception as e : pass
1
python windows session logout check
Disconnect ( logout ) service instance
cosqa-train-14311
def __Logout(si): """ Disconnect (logout) service instance @param si: Service instance (returned from Connect) """ try: if si: content = si.RetrieveContent() content.sessionManager.Logout() except Exception as e: pass
def clear_matplotlib_ticks ( self , axis = "both" ) : ax = self . get_axes ( ) plotting . clear_matplotlib_ticks ( ax = ax , axis = axis )
1
matplotlib python remove ticks
Clears the default matplotlib ticks .
cosqa-train-14312
def clear_matplotlib_ticks(self, axis="both"): """Clears the default matplotlib ticks.""" ax = self.get_axes() plotting.clear_matplotlib_ticks(ax=ax, axis=axis)
def Proxy ( f ) : def Wrapped ( self , * args ) : return getattr ( self , f ) ( * args ) return Wrapped
1
python wrapper function for a method
A helper to create a proxy method in a class .
cosqa-train-14313
def Proxy(f): """A helper to create a proxy method in a class.""" def Wrapped(self, *args): return getattr(self, f)(*args) return Wrapped
def is_square_matrix ( mat ) : mat = np . array ( mat ) if mat . ndim != 2 : return False shape = mat . shape return shape [ 0 ] == shape [ 1 ]
1
matrix in python to check accurecy
Test if an array is a square matrix .
cosqa-train-14314
def is_square_matrix(mat): """Test if an array is a square matrix.""" mat = np.array(mat) if mat.ndim != 2: return False shape = mat.shape return shape[0] == shape[1]
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 write a dictionary to file
Saves dictionary as CSV file .
cosqa-train-14315
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 argmax ( l , f = None ) : if f : l = [ f ( i ) for i in l ] return max ( enumerate ( l ) , key = lambda x : x [ 1 ] ) [ 0 ]
1
max function for a list of strings in python
http : // stackoverflow . com / questions / 5098580 / implementing - argmax - in - python
cosqa-train-14316
def argmax(l,f=None): """http://stackoverflow.com/questions/5098580/implementing-argmax-in-python""" if f: l = [f(i) for i in l] return max(enumerate(l), key=lambda x:x[1])[0]
def _write_color_colorama ( fp , text , color ) : foreground , background , style = get_win_color ( color ) colorama . set_console ( foreground = foreground , background = background , style = style ) fp . write ( text ) colorama . reset_console ( )
0
python write colored text to file
Colorize text with given color .
cosqa-train-14317
def _write_color_colorama (fp, text, color): """Colorize text with given color.""" foreground, background, style = get_win_color(color) colorama.set_console(foreground=foreground, background=background, style=style) fp.write(text) colorama.reset_console()
def SegmentMax ( a , ids ) : func = lambda idxs : np . amax ( a [ idxs ] , axis = 0 ) return seg_map ( func , a , ids ) ,
1
maximum 2 dimentional array python
Segmented max op .
cosqa-train-14318
def SegmentMax(a, ids): """ Segmented max op. """ func = lambda idxs: np.amax(a[idxs], axis=0) return seg_map(func, a, ids),
def write_fits ( data , header , file_name ) : hdu = fits . PrimaryHDU ( data ) hdu . header = header hdulist = fits . HDUList ( [ hdu ] ) hdulist . writeto ( file_name , overwrite = True ) logging . info ( "Wrote {0}" . format ( file_name ) ) return
1
python write fits header to another
Combine data and a fits header to write a fits file .
cosqa-train-14319
def write_fits(data, header, file_name): """ Combine data and a fits header to write a fits file. Parameters ---------- data : numpy.ndarray The data to be written. header : astropy.io.fits.hduheader The header for the fits file. file_name : string The file to write Returns ------- None """ hdu = fits.PrimaryHDU(data) hdu.header = header hdulist = fits.HDUList([hdu]) hdulist.writeto(file_name, overwrite=True) logging.info("Wrote {0}".format(file_name)) return
def md5_string ( s ) : m = hashlib . md5 ( ) m . update ( s ) return str ( m . hexdigest ( ) )
0
md5 for python 3
Shortcut to create md5 hash : param s : : return :
cosqa-train-14320
def md5_string(s): """ Shortcut to create md5 hash :param s: :return: """ m = hashlib.md5() m.update(s) return str(m.hexdigest())
def write_string ( value , buff , byteorder = 'big' ) : data = value . encode ( 'utf-8' ) write_numeric ( USHORT , len ( data ) , buff , byteorder ) buff . write ( data )
1
python write or don't write bytecodes
Write a string to a file - like object .
cosqa-train-14321
def write_string(value, buff, byteorder='big'): """Write a string to a file-like object.""" data = value.encode('utf-8') write_numeric(USHORT, len(data), buff, byteorder) buff.write(data)
def get_file_md5sum ( path ) : with open ( path , 'rb' ) as fh : h = str ( hashlib . md5 ( fh . read ( ) ) . hexdigest ( ) ) return h
1
md5 of a file python
Calculate the MD5 hash for a file .
cosqa-train-14322
def get_file_md5sum(path): """Calculate the MD5 hash for a file.""" with open(path, 'rb') as fh: h = str(hashlib.md5(fh.read()).hexdigest()) return h
def set_icon ( self , bmp ) : _icon = wx . EmptyIcon ( ) _icon . CopyFromBitmap ( bmp ) self . SetIcon ( _icon )
1
python wx set icon
Sets main window icon to given wx . Bitmap
cosqa-train-14323
def set_icon(self, bmp): """Sets main window icon to given wx.Bitmap""" _icon = wx.EmptyIcon() _icon.CopyFromBitmap(bmp) self.SetIcon(_icon)
def start_task ( self , task ) : self . info ( "Calculating {}..." . format ( task ) ) self . tasks [ task ] = self . timer ( )
1
measure start of task in python
Begin logging of a task
cosqa-train-14324
def start_task(self, task): """Begin logging of a task Stores the time this task was started in order to return time lapsed when `complete_task` is called. Parameters ---------- task : str Name of the task to be started """ self.info("Calculating {}...".format(task)) self.tasks[task] = self.timer()
def __call__ ( self , xy ) : x , y = xy return ( self . x ( x ) , self . y ( y ) )
1
python x and y coordiante
Project x and y
cosqa-train-14325
def __call__(self, xy): """Project x and y""" x, y = xy return (self.x(x), self.y(y))
def merge ( self , obj ) : for attribute in dir ( obj ) : if '__' in attribute : continue setattr ( self , attribute , getattr ( obj , attribute ) )
1
merge objects without overwrite python
This function merge another object s values with this instance
cosqa-train-14326
def merge(self, obj): """This function merge another object's values with this instance :param obj: An object to be merged with into this layer :type obj: object """ for attribute in dir(obj): if '__' in attribute: continue setattr(self, attribute, getattr(obj, attribute))
def elXpath ( self , xpath , dom = None ) : if dom is None : dom = self . browser return expect ( dom . is_element_present_by_xpath , args = [ xpath ] )
1
python xpath elements exist
check if element is present by css
cosqa-train-14327
def elXpath(self, xpath, dom=None): """check if element is present by css""" if dom is None: dom = self.browser return expect(dom.is_element_present_by_xpath, args=[xpath])
def dict_merge ( set1 , set2 ) : return dict ( list ( set1 . items ( ) ) + list ( set2 . items ( ) ) )
1
merging two similar dictionaries in python
Joins two dictionaries .
cosqa-train-14328
def dict_merge(set1, set2): """Joins two dictionaries.""" return dict(list(set1.items()) + list(set2.items()))
def serialize_yaml_tofile ( filename , resource ) : stream = file ( filename , "w" ) yaml . dump ( resource , stream , default_flow_style = False )
1
python yaml writ to json like file
Serializes a K8S resource to YAML - formatted file .
cosqa-train-14329
def serialize_yaml_tofile(filename, resource): """ Serializes a K8S resource to YAML-formatted file. """ stream = file(filename, "w") yaml.dump(resource, stream, default_flow_style=False)
def fn_min ( self , a , axis = None ) : return numpy . nanmin ( self . _to_ndarray ( a ) , axis = axis )
1
minimum value of array numpy python
Return the minimum of an array ignoring any NaNs .
cosqa-train-14330
def fn_min(self, a, axis=None): """ Return the minimum of an array, ignoring any NaNs. :param a: The array. :return: The minimum value of the array. """ return numpy.nanmin(self._to_ndarray(a), axis=axis)
def guess_title ( basename ) : base , _ = os . path . splitext ( basename ) return re . sub ( r'[ _-]+' , r' ' , base ) . title ( )
1
python, detect file name
Attempt to guess the title from the filename
cosqa-train-14331
def guess_title(basename): """ Attempt to guess the title from the filename """ base, _ = os.path.splitext(basename) return re.sub(r'[ _-]+', r' ', base).title()
def _obj_cursor_to_dictionary ( self , cursor ) : if not cursor : return cursor cursor = json . loads ( json . dumps ( cursor , cls = BSONEncoder ) ) if cursor . get ( "_id" ) : cursor [ "id" ] = cursor . get ( "_id" ) del cursor [ "_id" ] return cursor
1
mongodb cursor to json object python3
Handle conversion of pymongo cursor into a JSON object formatted for UI consumption
cosqa-train-14332
def _obj_cursor_to_dictionary(self, cursor): """Handle conversion of pymongo cursor into a JSON object formatted for UI consumption :param dict cursor: a mongo document that should be converted to primitive types for the client code :returns: a primitive dictionary :rtype: dict """ if not cursor: return cursor cursor = json.loads(json.dumps(cursor, cls=BSONEncoder)) if cursor.get("_id"): cursor["id"] = cursor.get("_id") del cursor["_id"] return cursor
def dict_to_html_attrs ( dict_ ) : res = ' ' . join ( '%s="%s"' % ( k , v ) for k , v in dict_ . items ( ) ) return res
1
python, dict to html
Banana banana
cosqa-train-14333
def dict_to_html_attrs(dict_): """ Banana banana """ res = ' '.join('%s="%s"' % (k, v) for k, v in dict_.items()) return res
def mostCommonItem ( lst ) : # This elegant solution from: http://stackoverflow.com/a/1518632/1760218 lst = [ l for l in lst if l ] if lst : return max ( set ( lst ) , key = lst . count ) else : return None
1
most common item in list python
Choose the most common item from the list or the first item if all items are unique .
cosqa-train-14334
def mostCommonItem(lst): """Choose the most common item from the list, or the first item if all items are unique.""" # This elegant solution from: http://stackoverflow.com/a/1518632/1760218 lst = [l for l in lst if l] if lst: return max(set(lst), key=lst.count) else: return None
def extract_module_locals ( depth = 0 ) : f = sys . _getframe ( depth + 1 ) global_ns = f . f_globals module = sys . modules [ global_ns [ '__name__' ] ] return ( module , f . f_locals )
1
python, get function stack
Returns ( module locals ) of the funciton depth frames away from the caller
cosqa-train-14335
def extract_module_locals(depth=0): """Returns (module, locals) of the funciton `depth` frames away from the caller""" f = sys._getframe(depth + 1) global_ns = f.f_globals module = sys.modules[global_ns['__name__']] return (module, f.f_locals)
def _most_common ( iterable ) : data = Counter ( iterable ) return max ( data , key = data . __getitem__ )
1
most common value in an array python
Returns the most common element in iterable .
cosqa-train-14336
def _most_common(iterable): """Returns the most common element in `iterable`.""" data = Counter(iterable) return max(data, key=data.__getitem__)
def astype ( array , y ) : if isinstance ( y , autograd . core . Node ) : return array . astype ( numpy . array ( y . value ) . dtype ) return array . astype ( numpy . array ( y ) . dtype )
0
python, how to apply astype function
A functional form of the astype method .
cosqa-train-14337
def astype(array, y): """A functional form of the `astype` method. Args: array: The array or number to cast. y: An array or number, as the input, whose type should be that of array. Returns: An array or number with the same dtype as `y`. """ if isinstance(y, autograd.core.Node): return array.astype(numpy.array(y.value).dtype) return array.astype(numpy.array(y).dtype)
def dict_merge ( set1 , set2 ) : return dict ( list ( set1 . items ( ) ) + list ( set2 . items ( ) ) )
0
most optimized way to merge 2 dictionaries in python
Joins two dictionaries .
cosqa-train-14338
def dict_merge(set1, set2): """Joins two dictionaries.""" return dict(list(set1.items()) + list(set2.items()))
def save ( self ) : if self . path : self . _saveState ( self . path ) else : self . saveAs ( )
1
python, model saved in session
save the current session override if session was saved earlier
cosqa-train-14339
def save(self): """save the current session override, if session was saved earlier""" if self.path: self._saveState(self.path) else: self.saveAs()
def list_move_to_front ( l , value = 'other' ) : l = list ( l ) if value in l : l . remove ( value ) l . insert ( 0 , value ) return l
1
move an item in list to front python
if the value is in the list move it to the front and return it .
cosqa-train-14340
def list_move_to_front(l,value='other'): """if the value is in the list, move it to the front and return it.""" l=list(l) if value in l: l.remove(value) l.insert(0,value) return l
def user_return ( self , frame , return_value ) : pdb . Pdb . user_return ( self , frame , return_value )
1
python, pdb, step out of function, shortcut
This function is called when a return trap is set here .
cosqa-train-14341
def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" pdb.Pdb.user_return(self, frame, return_value)
def move_up ( lines = 1 , file = sys . stdout ) : move . up ( lines ) . write ( file = file )
1
move cursor down line python
Move the cursor up a number of lines .
cosqa-train-14342
def move_up(lines=1, file=sys.stdout): """ Move the cursor up a number of lines. Esc[ValueA: Moves the cursor up by the specified number of lines without changing columns. If the cursor is already on the top line, ANSI.SYS ignores this sequence. """ move.up(lines).write(file=file)
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 }
1
python, turn a string into a dict
Parse string into Identity dictionary .
cosqa-train-14343
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 move_up ( lines = 1 , file = sys . stdout ) : move . up ( lines ) . write ( file = file )
0
move cursor up and to beginning of line python
Move the cursor up a number of lines .
cosqa-train-14344
def move_up(lines=1, file=sys.stdout): """ Move the cursor up a number of lines. Esc[ValueA: Moves the cursor up by the specified number of lines without changing columns. If the cursor is already on the top line, ANSI.SYS ignores this sequence. """ move.up(lines).write(file=file)
def get_url_args ( url ) : url_data = urllib . parse . urlparse ( url ) arg_dict = urllib . parse . parse_qs ( url_data . query ) return arg_dict
1
python2 url parse query to dict
Returns a dictionary from a URL params
cosqa-train-14345
def get_url_args(url): """ Returns a dictionary from a URL params """ url_data = urllib.parse.urlparse(url) arg_dict = urllib.parse.parse_qs(url_data.query) return arg_dict
def _parse_array ( self , tensor_proto ) : try : from onnx . numpy_helper import to_array except ImportError as e : raise ImportError ( "Unable to import onnx which is required {}" . format ( e ) ) np_array = to_array ( tensor_proto ) . reshape ( tuple ( tensor_proto . dims ) ) return mx . nd . array ( np_array )
1
mxnet ndarray to python list
Grab data in TensorProto and convert to numpy array .
cosqa-train-14346
def _parse_array(self, tensor_proto): """Grab data in TensorProto and convert to numpy array.""" try: from onnx.numpy_helper import to_array except ImportError as e: raise ImportError("Unable to import onnx which is required {}".format(e)) np_array = to_array(tensor_proto).reshape(tuple(tensor_proto.dims)) return mx.nd.array(np_array)
def list2dict ( list_of_options ) : d = { } for key , value in list_of_options : d [ key ] = value return d
1
python3 2 list to dictionary
Transforms a list of 2 element tuples to a dictionary
cosqa-train-14347
def list2dict(list_of_options): """Transforms a list of 2 element tuples to a dictionary""" d = {} for key, value in list_of_options: d[key] = value return d
def unit_ball_L2 ( shape ) : x = tf . Variable ( tf . zeros ( shape ) ) return constrain_L2 ( x )
1
name 'python' is not defined tensorflow
A tensorflow variable tranfomed to be constrained in a L2 unit ball .
cosqa-train-14348
def unit_ball_L2(shape): """A tensorflow variable tranfomed to be constrained in a L2 unit ball. EXPERIMENTAL: Do not use for adverserial examples if you need to be confident they are strong attacks. We are not yet confident in this code. """ x = tf.Variable(tf.zeros(shape)) return constrain_L2(x)
def to_dicts ( recarray ) : for rec in recarray : yield dict ( zip ( recarray . dtype . names , rec . tolist ( ) ) )
0
python3 array to dict
convert record array to a dictionaries
cosqa-train-14349
def to_dicts(recarray): """convert record array to a dictionaries""" for rec in recarray: yield dict(zip(recarray.dtype.names, rec.tolist()))
def to_distribution_values ( self , values ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) # avoid RuntimeWarning: divide by zero encountered in log return numpy . log ( values )
1
natural log of array in python
Returns numpy array of natural logarithms of values .
cosqa-train-14350
def to_distribution_values(self, values): """ Returns numpy array of natural logarithms of ``values``. """ with warnings.catch_warnings(): warnings.simplefilter("ignore") # avoid RuntimeWarning: divide by zero encountered in log return numpy.log(values)
def dt_to_ts ( value ) : if not isinstance ( value , datetime ) : return value return calendar . timegm ( value . utctimetuple ( ) ) + value . microsecond / 1000000.0
1
python3 datetime to integer timestamp
If value is a datetime convert to timestamp
cosqa-train-14351
def dt_to_ts(value): """ If value is a datetime, convert to timestamp """ if not isinstance(value, datetime): return value return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0
def log_loss ( preds , labels ) : log_likelihood = np . sum ( labels * np . log ( preds ) ) / len ( preds ) return - log_likelihood
1
negative log likelihood python code tobit regression
Logarithmic loss with non - necessarily - binary labels .
cosqa-train-14352
def log_loss(preds, labels): """Logarithmic loss with non-necessarily-binary labels.""" log_likelihood = np.sum(labels * np.log(preds)) / len(preds) return -log_likelihood
def filehash ( path ) : with open ( path , "rU" ) as f : return md5 ( py3compat . str_to_bytes ( f . read ( ) ) ) . hexdigest ( )
1
python3 file md5 hash
Make an MD5 hash of a file ignoring any differences in line ending characters .
cosqa-train-14353
def filehash(path): """Make an MD5 hash of a file, ignoring any differences in line ending characters.""" with open(path, "rU") as f: return md5(py3compat.str_to_bytes(f.read())).hexdigest()
def full_like ( array , value , dtype = None ) : shared = empty_like ( array , dtype ) shared [ : ] = value return shared
1
new array object that looks at the same data in python
Create a shared memory array with the same shape and type as a given array filled with value .
cosqa-train-14354
def full_like(array, value, dtype=None): """ Create a shared memory array with the same shape and type as a given array, filled with `value`. """ shared = empty_like(array, dtype) shared[:] = value return shared
def caller_locals ( ) : import inspect frame = inspect . currentframe ( ) try : return frame . f_back . f_back . f_locals finally : del frame
1
python3 get function locals
Get the local variables in the caller s frame .
cosqa-train-14355
def caller_locals(): """Get the local variables in the caller's frame.""" import inspect frame = inspect.currentframe() try: return frame.f_back.f_back.f_locals finally: del frame
def __next__ ( self ) : # Retrieve the row, thereby incrementing the line number: row = super ( UnicodeReaderWithLineNumber , self ) . __next__ ( ) return self . lineno + 1 , row
1
next line to read in python
cosqa-train-14356
def __next__(self): """ :return: a pair (1-based line number in the input, row) """ # Retrieve the row, thereby incrementing the line number: row = super(UnicodeReaderWithLineNumber, self).__next__() return self.lineno + 1, row
def last_modified_date ( filename ) : mtime = os . path . getmtime ( filename ) dt = datetime . datetime . utcfromtimestamp ( mtime ) return dt . replace ( tzinfo = pytz . utc )
1
python3 get last modified time
Last modified timestamp as a UTC datetime
cosqa-train-14357
def last_modified_date(filename): """Last modified timestamp as a UTC datetime""" mtime = os.path.getmtime(filename) dt = datetime.datetime.utcfromtimestamp(mtime) return dt.replace(tzinfo=pytz.utc)
def mag ( z ) : if isinstance ( z [ 0 ] , np . ndarray ) : return np . array ( list ( map ( np . linalg . norm , z ) ) ) else : return np . linalg . norm ( z )
1
norm of a numpy array python
Get the magnitude of a vector .
cosqa-train-14358
def mag(z): """Get the magnitude of a vector.""" if isinstance(z[0], np.ndarray): return np.array(list(map(np.linalg.norm, z))) else: return np.linalg.norm(z)
def get_obj ( ref ) : oid = int ( ref ) return server . id2ref . get ( oid ) or server . id2obj [ oid ]
0
python3 get object id
Get object from string reference .
cosqa-train-14359
def get_obj(ref): """Get object from string reference.""" oid = int(ref) return server.id2ref.get(oid) or server.id2obj[oid]
def normalize_path ( path ) : return os . path . normcase ( os . path . realpath ( os . path . expanduser ( path ) ) )
0
normalize path address python
Convert a path to its canonical case - normalized absolute version .
cosqa-train-14360
def normalize_path(path): """ Convert a path to its canonical, case-normalized, absolute version. """ return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
def enable_gtk3 ( self , app = None ) : from pydev_ipython . inputhookgtk3 import create_inputhook_gtk3 self . set_inputhook ( create_inputhook_gtk3 ( self . _stdin_file ) ) self . _current_gui = GUI_GTK
0
python3 gtk how to detect gui does not response
Enable event loop integration with Gtk3 ( gir bindings ) .
cosqa-train-14361
def enable_gtk3(self, app=None): """Enable event loop integration with Gtk3 (gir bindings). Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for Gtk3, which allows the Gtk3 to integrate with terminal based applications like IPython. """ from pydev_ipython.inputhookgtk3 import create_inputhook_gtk3 self.set_inputhook(create_inputhook_gtk3(self._stdin_file)) self._current_gui = GUI_GTK
def v_normalize ( v ) : vmag = v_magnitude ( v ) return [ v [ i ] / vmag for i in range ( len ( v ) ) ]
1
normalize vector python numpy
Normalizes the given vector . The vector given may have any number of dimensions .
cosqa-train-14362
def v_normalize(v): """ Normalizes the given vector. The vector given may have any number of dimensions. """ vmag = v_magnitude(v) return [ v[i]/vmag for i in range(len(v)) ]
def get_table_names ( connection ) : cursor = connection . cursor ( ) cursor . execute ( "SELECT name FROM sqlite_master WHERE type == 'table'" ) return [ name for ( name , ) in cursor ]
1
python3 how to print out sqlite table names
Return a list of the table names in the database .
cosqa-train-14363
def get_table_names(connection): """ Return a list of the table names in the database. """ cursor = connection.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type == 'table'") return [name for (name,) in cursor]
def _to_array ( value ) : if isinstance ( value , ( tuple , list ) ) : return array ( value ) elif isinstance ( value , ( float , int ) ) : return np . float64 ( value ) else : return value
1
np array from list python
As a convenience turn Python lists and tuples into NumPy arrays .
cosqa-train-14364
def _to_array(value): """As a convenience, turn Python lists and tuples into NumPy arrays.""" if isinstance(value, (tuple, list)): return array(value) elif isinstance(value, (float, int)): return np.float64(value) else: return value
def getvariable ( name ) : import inspect fr = inspect . currentframe ( ) try : while fr : fr = fr . f_back vars = fr . f_locals if name in vars : return vars [ name ] except : pass return None
1
python3 inspect get local variable
Get the value of a local variable somewhere in the call stack .
cosqa-train-14365
def getvariable(name): """Get the value of a local variable somewhere in the call stack.""" import inspect fr = inspect.currentframe() try: while fr: fr = fr.f_back vars = fr.f_locals if name in vars: return vars[name] except: pass return None
def _histplot_bins ( column , bins = 100 ) : col_min = np . min ( column ) col_max = np . max ( column ) return range ( col_min , col_max + 2 , max ( ( col_max - col_min ) // bins , 1 ) )
1
number of bins in histogram python
Helper to get bins for histplot .
cosqa-train-14366
def _histplot_bins(column, bins=100): """Helper to get bins for histplot.""" col_min = np.min(column) col_max = np.max(column) return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))
def _is_target_a_directory ( link , rel_target ) : target = os . path . join ( os . path . dirname ( link ) , rel_target ) return os . path . isdir ( target )
0
python3 isdir check directory or symbol link
If creating a symlink from link to a target determine if target is a directory ( relative to dirname ( link )) .
cosqa-train-14367
def _is_target_a_directory(link, rel_target): """ If creating a symlink from link to a target, determine if target is a directory (relative to dirname(link)). """ target = os.path.join(os.path.dirname(link), rel_target) return os.path.isdir(target)
def sem ( inlist ) : sd = stdev ( inlist ) n = len ( inlist ) return sd / math . sqrt ( n )
1
number of standard deviations python from a fit
Returns the estimated standard error of the mean ( sx - bar ) of the values in the passed list . sem = stdev / sqrt ( n )
cosqa-train-14368
def sem(inlist): """ Returns the estimated standard error of the mean (sx-bar) of the values in the passed list. sem = stdev / sqrt(n) Usage: lsem(inlist) """ sd = stdev(inlist) n = len(inlist) return sd / math.sqrt(n)
def merge ( self , other ) : newstart = min ( self . _start , other . start ) newend = max ( self . _end , other . end ) return Range ( newstart , newend )
1
python3 merge two ranges
Merge this range object with another ( ranges need not overlap or abut ) .
cosqa-train-14369
def merge(self, other): """ Merge this range object with another (ranges need not overlap or abut). :returns: a new Range object representing the interval containing both ranges. """ newstart = min(self._start, other.start) newend = max(self._end, other.end) return Range(newstart, newend)
def algo_exp ( x , m , t , b ) : return m * np . exp ( - t * x ) + b
1
numerically solve exponential equations in python
mono - exponential curve .
cosqa-train-14370
def algo_exp(x, m, t, b): """mono-exponential curve.""" return m*np.exp(-t*x)+b
def to_str ( obj ) : if not isinstance ( obj , str ) and PY3 and isinstance ( obj , bytes ) : obj = obj . decode ( 'utf-8' ) return obj if isinstance ( obj , string_types ) else str ( obj )
1
python3 move a byte object to string
Attempts to convert given object to a string object
cosqa-train-14371
def to_str(obj): """Attempts to convert given object to a string object """ if not isinstance(obj, str) and PY3 and isinstance(obj, bytes): obj = obj.decode('utf-8') return obj if isinstance(obj, string_types) else str(obj)
def _array2cstr ( arr ) : out = StringIO ( ) np . save ( out , arr ) return b64encode ( out . getvalue ( ) )
1
numpy array to string python
Serializes a numpy array to a compressed base64 string
cosqa-train-14372
def _array2cstr(arr): """ Serializes a numpy array to a compressed base64 string """ out = StringIO() np.save(out, arr) return b64encode(out.getvalue())
def one_hot ( x , size , dtype = np . float32 ) : return np . array ( x [ ... , np . newaxis ] == np . arange ( size ) , dtype )
1
python3 numpy generate onehot vector
Make a n + 1 dim one - hot array from n dim int - categorical array .
cosqa-train-14373
def one_hot(x, size, dtype=np.float32): """Make a n+1 dim one-hot array from n dim int-categorical array.""" return np.array(x[..., np.newaxis] == np.arange(size), dtype)
def read_numpy ( fh , byteorder , dtype , count , offsetsize ) : dtype = 'b' if dtype [ - 1 ] == 's' else byteorder + dtype [ - 1 ] return fh . read_array ( dtype , count )
1
python3 numpy load bytes object has no attribute read
Read tag data from file and return as numpy array .
cosqa-train-14374
def read_numpy(fh, byteorder, dtype, count, offsetsize): """Read tag data from file and return as numpy array.""" dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1] return fh.read_array(dtype, count)
def fetch ( self ) : api = self . doapi_manager return api . _domain ( api . request ( self . url ) [ "domain" ] )
1
odoo python return domain
Fetch & return a new Domain object representing the domain s current state
cosqa-train-14375
def fetch(self): """ Fetch & return a new `Domain` object representing the domain's current state :rtype: Domain :raises DOAPIError: if the API endpoint replies with an error (e.g., if the domain no longer exists) """ api = self.doapi_manager return api._domain(api.request(self.url)["domain"])
def run ( self ) : try : self . run_checked ( ) except KeyboardInterrupt : thread . interrupt_main ( ) except Exception : self . internal_error ( )
1
python3 raise keyboard interrupt programatically
Handle keyboard interrupt and other errors .
cosqa-train-14376
def run (self): """Handle keyboard interrupt and other errors.""" try: self.run_checked() except KeyboardInterrupt: thread.interrupt_main() except Exception: self.internal_error()
def autoconvert ( string ) : for fn in ( boolify , int , float ) : try : return fn ( string ) except ValueError : pass return string
1
only take certain type into def python
Try to convert variables into datatypes .
cosqa-train-14377
def autoconvert(string): """Try to convert variables into datatypes.""" for fn in (boolify, int, float): try: return fn(string) except ValueError: pass return string
def _stdin_ready_posix ( ) : infds , outfds , erfds = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return bool ( infds )
1
python3 stdin check if pending char
Return True if there s something to read on stdin ( posix version ) .
cosqa-train-14378
def _stdin_ready_posix(): """Return True if there's something to read on stdin (posix version).""" infds, outfds, erfds = select.select([sys.stdin],[],[],0) return bool(infds)
def list_i2str ( ilist ) : slist = [ ] for el in ilist : slist . append ( str ( el ) ) return slist
1
onvert list into array in python
Convert an integer list into a string list .
cosqa-train-14379
def list_i2str(ilist): """ Convert an integer list into a string list. """ slist = [] for el in ilist: slist.append(str(el)) return slist
def askopenfilename ( * * kwargs ) : try : from Tkinter import Tk import tkFileDialog as filedialog except ImportError : from tkinter import Tk , filedialog root = Tk ( ) root . withdraw ( ) root . update ( ) filenames = filedialog . askopenfilename ( * * kwargs ) root . destroy ( ) return filenames
1
python3 tkinter filedialog askopenfilename
Return file name ( s ) from Tkinter s file open dialog .
cosqa-train-14380
def askopenfilename(**kwargs): """Return file name(s) from Tkinter's file open dialog.""" try: from Tkinter import Tk import tkFileDialog as filedialog except ImportError: from tkinter import Tk, filedialog root = Tk() root.withdraw() root.update() filenames = filedialog.askopenfilename(**kwargs) root.destroy() return filenames
def open_file ( file , mode ) : if hasattr ( file , "read" ) : return file if hasattr ( file , "open" ) : return file . open ( mode ) return open ( file , mode )
1
open a file in r and w mode in python
Open a file .
cosqa-train-14381
def open_file(file, mode): """Open a file. :arg file: file-like or path-like object. :arg str mode: ``mode`` argument for :func:`open`. """ if hasattr(file, "read"): return file if hasattr(file, "open"): return file.open(mode) return open(file, mode)
def timedelta_seconds ( timedelta ) : return ( timedelta . total_seconds ( ) if hasattr ( timedelta , "total_seconds" ) else timedelta . days * 24 * 3600 + timedelta . seconds + timedelta . microseconds / 1000000. )
1
python3 total number of seconds in timedelta
Returns the total timedelta duration in seconds .
cosqa-train-14382
def timedelta_seconds(timedelta): """Returns the total timedelta duration in seconds.""" return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds") else timedelta.days * 24 * 3600 + timedelta.seconds + timedelta.microseconds / 1000000.)
def load_image ( fname ) : with open ( fname , "rb" ) as f : i = Image . open ( fname ) #i.load() return i
1
opening an image in python
read an image from file - PIL doesnt close nicely
cosqa-train-14383
def load_image(fname): """ read an image from file - PIL doesnt close nicely """ with open(fname, "rb") as f: i = Image.open(fname) #i.load() return i
def re_raise ( self ) : if self . exc_info is not None : six . reraise ( type ( self ) , self , self . exc_info [ 2 ] ) else : raise self
1
python3 traceback remove raise code
Raise this exception with the original traceback
cosqa-train-14384
def re_raise(self): """ Raise this exception with the original traceback """ if self.exc_info is not None: six.reraise(type(self), self, self.exc_info[2]) else: raise self
def load ( filename ) : path , name = os . path . split ( filename ) path = path or '.' with util . indir ( path ) : return pickle . load ( open ( name , 'rb' ) )
1
opening an pickle file python
Load the state from the given file moving to the file s directory during load ( temporarily moving back after loaded )
cosqa-train-14385
def load(filename): """ Load the state from the given file, moving to the file's directory during load (temporarily, moving back after loaded) Parameters ---------- filename : string name of the file to open, should be a .pkl file """ path, name = os.path.split(filename) path = path or '.' with util.indir(path): return pickle.load(open(name, 'rb'))
def remote_file_exists ( self , url ) : status = requests . head ( url ) . status_code if status != 200 : raise RemoteFileDoesntExist
1
pythonrequests check if file exists
Checks whether the remote file exists .
cosqa-train-14386
def remote_file_exists(self, url): """ Checks whether the remote file exists. :param url: The url that has to be checked. :type url: String :returns: **True** if remote file exists and **False** if it doesn't exist. """ status = requests.head(url).status_code if status != 200: raise RemoteFileDoesntExist
def get_order ( self , codes ) : return sorted ( codes , key = lambda e : [ self . ev2idx . get ( e ) ] )
1
ordering names in lexiographical order python
Return evidence codes in order shown in code2name .
cosqa-train-14387
def get_order(self, codes): """Return evidence codes in order shown in code2name.""" return sorted(codes, key=lambda e: [self.ev2idx.get(e)])
def insort_no_dup ( lst , item ) : import bisect ix = bisect . bisect_left ( lst , item ) if lst [ ix ] != item : lst [ ix : ix ] = [ item ]
1
quckiest way to insert something into a sorted list python
If item is not in lst add item to list at its sorted position
cosqa-train-14388
def insort_no_dup(lst, item): """ If item is not in lst, add item to list at its sorted position """ import bisect ix = bisect.bisect_left(lst, item) if lst[ix] != item: lst[ix:ix] = [item]
def merge ( left , right , how = 'inner' , key = None , left_key = None , right_key = None , left_as = 'left' , right_as = 'right' ) : return join ( left , right , how , key , left_key , right_key , join_fn = make_union_join ( left_as , right_as ) )
0
outer join without the intersection python
Performs a join using the union join function .
cosqa-train-14389
def merge(left, right, how='inner', key=None, left_key=None, right_key=None, left_as='left', right_as='right'): """ Performs a join using the union join function. """ return join(left, right, how, key, left_key, right_key, join_fn=make_union_join(left_as, right_as))
def _fetch_all_as_dict ( self , cursor ) : desc = cursor . description return [ dict ( zip ( [ col [ 0 ] for col in desc ] , row ) ) for row in cursor . fetchall ( ) ]
0
query result to a list mysql python
Iterates over the result set and converts each row to a dictionary
cosqa-train-14390
def _fetch_all_as_dict(self, cursor): """ Iterates over the result set and converts each row to a dictionary :return: A list of dictionaries where each row is a dictionary :rtype: list of dict """ desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ]
def tab ( self , output ) : import csv csvwriter = csv . writer ( self . outfile , dialect = csv . excel_tab ) csvwriter . writerows ( output )
1
output the query to a excel file python
Output data in excel - compatible tab - delimited format
cosqa-train-14391
def tab(self, output): """Output data in excel-compatible tab-delimited format""" import csv csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab) csvwriter.writerows(output)
def test ( ) : dns = ReverseDNS ( ) print ( dns . lookup ( '192.168.0.1' ) ) print ( dns . lookup ( '8.8.8.8' ) ) # Test cache print ( dns . lookup ( '8.8.8.8' ) )
1
question 2what python function is used to perform a dns lookup
Test for ReverseDNS class
cosqa-train-14392
def test(): """Test for ReverseDNS class""" dns = ReverseDNS() print(dns.lookup('192.168.0.1')) print(dns.lookup('8.8.8.8')) # Test cache print(dns.lookup('8.8.8.8'))
def add_widgets ( self , * widgets_or_spacings ) : layout = self . layout ( ) for widget_or_spacing in widgets_or_spacings : if isinstance ( widget_or_spacing , int ) : layout . addSpacing ( widget_or_spacing ) else : layout . addWidget ( widget_or_spacing )
0
padding or spacing kivy python
Add widgets / spacing to dialog vertical layout
cosqa-train-14393
def add_widgets(self, *widgets_or_spacings): """Add widgets/spacing to dialog vertical layout""" layout = self.layout() for widget_or_spacing in widgets_or_spacings: if isinstance(widget_or_spacing, int): layout.addSpacing(widget_or_spacing) else: layout.addWidget(widget_or_spacing)
def _sort_r ( sorted , processed , key , deps , dependency_tree ) : if key in processed : return processed . add ( key ) for dep_key in deps : dep_deps = dependency_tree . get ( dep_key ) if dep_deps is None : log . debug ( '"%s" not found, skipped' , Repr ( dep_key ) ) continue _sort_r ( sorted , processed , dep_key , dep_deps , dependency_tree ) sorted . append ( ( key , deps ) )
1
quick sort recursion python
Recursive topological sort implementation .
cosqa-train-14394
def _sort_r(sorted, processed, key, deps, dependency_tree): """Recursive topological sort implementation.""" if key in processed: return processed.add(key) for dep_key in deps: dep_deps = dependency_tree.get(dep_key) if dep_deps is None: log.debug('"%s" not found, skipped', Repr(dep_key)) continue _sort_r(sorted, processed, dep_key, dep_deps, dependency_tree) sorted.append((key, deps))
def save_list ( key , * values ) : return json . dumps ( { key : [ _get_json ( value ) for value in values ] } )
1
pass a list to json function python
Convert the given list of parameters to a JSON object .
cosqa-train-14395
def save_list(key, *values): """Convert the given list of parameters to a JSON object. JSON object is of the form: { key: [values[0], values[1], ... ] }, where values represent the given list of parameters. """ return json.dumps({key: [_get_json(value) for value in values]})
def readwav ( filename ) : from scipy . io . wavfile import read as readwav samplerate , signal = readwav ( filename ) return signal , samplerate
1
quickly read wave files python
Read a WAV file and returns the data and sample rate
cosqa-train-14396
def readwav(filename): """Read a WAV file and returns the data and sample rate :: from spectrum.io import readwav readwav() """ from scipy.io.wavfile import read as readwav samplerate, signal = readwav(filename) return signal, samplerate
def iget_list_column_slice ( list_ , start = None , stop = None , stride = None ) : if isinstance ( start , slice ) : slice_ = start else : slice_ = slice ( start , stop , stride ) return ( row [ slice_ ] for row in list_ )
1
pass a slice of list in python as variable
iterator version of get_list_column
cosqa-train-14397
def iget_list_column_slice(list_, start=None, stop=None, stride=None): """ iterator version of get_list_column """ if isinstance(start, slice): slice_ = start else: slice_ = slice(start, stop, stride) return (row[slice_] for row in list_)
def rnormal ( mu , tau , size = None ) : return np . random . normal ( mu , 1. / np . sqrt ( tau ) , size )
1
random normal distribution in python
Random normal variates .
cosqa-train-14398
def rnormal(mu, tau, size=None): """ Random normal variates. """ return np.random.normal(mu, 1. / np.sqrt(tau), size)
def dimensions ( self ) : size = self . pdf . getPage ( 0 ) . mediaBox return { 'w' : float ( size [ 2 ] ) , 'h' : float ( size [ 3 ] ) }
1
pdfpages python size page
Get width and height of a PDF
cosqa-train-14399
def dimensions(self): """Get width and height of a PDF""" size = self.pdf.getPage(0).mediaBox return {'w': float(size[2]), 'h': float(size[3])}