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
async def _thread_coro ( self , * args ) : return await self . _loop . run_in_executor ( self . _executor , self . _function , * args )
0
corotine with thread asyncio python
Coroutine called by MapAsync . It s wrapping the call of run_in_executor to run the synchronous function as thread
cosqa-train-13000
async def _thread_coro(self, *args): """ Coroutine called by MapAsync. It's wrapping the call of run_in_executor to run the synchronous function as thread """ return await self._loop.run_in_executor( self._executor, self._function, *args)
def update_screen ( self ) : self . clock . tick ( self . FPS ) pygame . display . update ( )
1
python full screen adjust to the screen
Refresh the screen . You don t need to override this except to update only small portins of the screen .
cosqa-train-13001
def update_screen(self): """Refresh the screen. You don't need to override this except to update only small portins of the screen.""" self.clock.tick(self.FPS) pygame.display.update()
def sample_correlations ( self ) : C = np . corrcoef ( self . X . T ) corr_matrix = ExpMatrix ( genes = self . samples , samples = self . samples , X = C ) return corr_matrix
1
correlation matrix with respect to python
Returns an ExpMatrix containing all pairwise sample correlations .
cosqa-train-13002
def sample_correlations(self): """Returns an `ExpMatrix` containing all pairwise sample correlations. Returns ------- `ExpMatrix` The sample correlation matrix. """ C = np.corrcoef(self.X.T) corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C) return corr_matrix
def parameter_vector ( self ) : return np . array ( [ getattr ( self , k ) for k in self . parameter_names ] )
1
python function array type
An array of all parameters ( including frozen parameters )
cosqa-train-13003
def parameter_vector(self): """An array of all parameters (including frozen parameters)""" return np.array([getattr(self, k) for k in self.parameter_names])
def count_rows_with_nans ( X ) : if X . ndim == 2 : return np . where ( np . isnan ( X ) . sum ( axis = 1 ) != 0 , 1 , 0 ) . sum ( )
1
count nans in matrix python
Count the number of rows in 2D arrays that contain any nan values .
cosqa-train-13004
def count_rows_with_nans(X): """Count the number of rows in 2D arrays that contain any nan values.""" if X.ndim == 2: return np.where(np.isnan(X).sum(axis=1) != 0, 1, 0).sum()
def log_loss ( preds , labels ) : log_likelihood = np . sum ( labels * np . log ( preds ) ) / len ( preds ) return - log_likelihood
1
python function for logaritthms
Logarithmic loss with non - necessarily - binary labels .
cosqa-train-13005
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 _calc_overlap_count ( markers1 : dict , markers2 : dict , ) : overlaps = np . zeros ( ( len ( markers1 ) , len ( markers2 ) ) ) j = 0 for marker_group in markers1 : tmp = [ len ( markers2 [ i ] . intersection ( markers1 [ marker_group ] ) ) for i in markers2 . keys ( ) ] overlaps [ j , : ] = tmp j += 1 return overlaps
1
count number of overlaps in two python nested lists
Calculate overlap count between the values of two dictionaries
cosqa-train-13006
def _calc_overlap_count( markers1: dict, markers2: dict, ): """Calculate overlap count between the values of two dictionaries Note: dict values must be sets """ overlaps=np.zeros((len(markers1), len(markers2))) j=0 for marker_group in markers1: tmp = [len(markers2[i].intersection(markers1[marker_group])) for i in markers2.keys()] overlaps[j,:] = tmp j += 1 return overlaps
def hex_escape ( bin_str ) : printable = string . ascii_letters + string . digits + string . punctuation + ' ' return '' . join ( ch if ch in printable else r'0x{0:02x}' . format ( ord ( ch ) ) for ch in bin_str )
1
python function for printing all characters in binary
Hex encode a binary string
cosqa-train-13007
def hex_escape(bin_str): """ Hex encode a binary string """ printable = string.ascii_letters + string.digits + string.punctuation + ' ' return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)
def count_list ( the_list ) : count = the_list . count result = [ ( item , count ( item ) ) for item in set ( the_list ) ] result . sort ( ) return result
1
count unique values in a list in python
Generates a count of the number of times each unique item appears in a list
cosqa-train-13008
def count_list(the_list): """ Generates a count of the number of times each unique item appears in a list """ count = the_list.count result = [(item, count(item)) for item in set(the_list)] result.sort() return result
def to_snake_case ( s ) : return re . sub ( '([^_A-Z])([A-Z])' , lambda m : m . group ( 1 ) + '_' + m . group ( 2 ) . lower ( ) , s )
1
python function lowercase variable name
Converts camel - case identifiers to snake - case .
cosqa-train-13009
def to_snake_case(s): """Converts camel-case identifiers to snake-case.""" return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)
def coverage ( ctx , opts = "" ) : return test ( ctx , coverage = True , include_slow = True , opts = opts )
1
coverage python and unit tests
Execute all tests ( normal and slow ) with coverage enabled .
cosqa-train-13010
def coverage(ctx, opts=""): """ Execute all tests (normal and slow) with coverage enabled. """ return test(ctx, coverage=True, include_slow=True, opts=opts)
def _to_numeric ( val ) : if isinstance ( val , ( int , float , datetime . datetime , datetime . timedelta ) ) : return val return float ( val )
1
python function return datatype
Helper function for conversion of various data types into numeric representation .
cosqa-train-13011
def _to_numeric(val): """ Helper function for conversion of various data types into numeric representation. """ if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)): return val return float(val)
def _array2cstr ( arr ) : out = StringIO ( ) np . save ( out , arr ) return b64encode ( out . getvalue ( ) )
1
cpmvertarray to string python 3
Serializes a numpy array to a compressed base64 string
cosqa-train-13012
def _array2cstr(arr): """ Serializes a numpy array to a compressed base64 string """ out = StringIO() np.save(out, arr) return b64encode(out.getvalue())
def unique ( input_list ) : output = [ ] for item in input_list : if item not in output : output . append ( item ) return output
1
python function that check for elements appearing twice in a list
Return a list of unique items ( similar to set functionality ) .
cosqa-train-13013
def unique(input_list): """ Return a list of unique items (similar to set functionality). Parameters ---------- input_list : list A list containg some items that can occur more than once. Returns ------- list A list with only unique occurances of an item. """ output = [] for item in input_list: if item not in output: output.append(item) return output
def main ( ctx , connection ) : ctx . obj = Manager ( connection = connection ) ctx . obj . bind ( )
1
create a bound python
Command line interface for PyBEL .
cosqa-train-13014
def main(ctx, connection): """Command line interface for PyBEL.""" ctx.obj = Manager(connection=connection) ctx.obj.bind()
def identifierify ( name ) : name = name . lower ( ) name = re . sub ( '[^a-z0-9]' , '_' , name ) return name
1
python function that cleans up name
Clean up name so it works for a Python identifier .
cosqa-train-13015
def identifierify(name): """ Clean up name so it works for a Python identifier. """ name = name.lower() name = re.sub('[^a-z0-9]', '_', name) return name
def reduce_freqs ( freqlist ) : allfreqs = np . zeros_like ( freqlist [ 0 ] ) for f in freqlist : allfreqs += f return allfreqs
1
create a list of frequencies python
Add up a list of freq counts to get the total counts .
cosqa-train-13016
def reduce_freqs(freqlist): """ Add up a list of freq counts to get the total counts. """ allfreqs = np.zeros_like(freqlist[0]) for f in freqlist: allfreqs += f return allfreqs
def _is_leap_year ( year ) : isleap = ( ( np . mod ( year , 4 ) == 0 ) & ( ( np . mod ( year , 100 ) != 0 ) | ( np . mod ( year , 400 ) == 0 ) ) ) return isleap
1
python function to determine whether a leap year or not
Determine if a year is leap year .
cosqa-train-13017
def _is_leap_year(year): """Determine if a year is leap year. Parameters ---------- year : numeric Returns ------- isleap : array of bools """ isleap = ((np.mod(year, 4) == 0) & ((np.mod(year, 100) != 0) | (np.mod(year, 400) == 0))) return isleap
def sent2features ( sentence , template ) : return [ word2features ( sentence , i , template ) for i in range ( len ( sentence ) ) ]
1
create a list of words from a sentence python
extract features in a sentence
cosqa-train-13018
def sent2features(sentence, template): """ extract features in a sentence :type sentence: list of token, each token is a list of tag """ return [word2features(sentence, i, template) for i in range(len(sentence))]
def get_rounded ( self , digits ) : result = self . copy ( ) result . round ( digits ) return result
1
python function to round to variable number of digits
Return a vector with the elements rounded to the given number of digits .
cosqa-train-13019
def get_rounded(self, digits): """ Return a vector with the elements rounded to the given number of digits. """ result = self.copy() result.round(digits) return result
def create ( self , ami , count , config = None ) : return self . Launcher ( config = config ) . launch ( ami , count )
1
create an ec2 instance from my ami python
Create an instance using the launcher .
cosqa-train-13020
def create(self, ami, count, config=None): """Create an instance using the launcher.""" return self.Launcher(config=config).launch(ami, count)
def def_linear ( fun ) : defjvp_argnum ( fun , lambda argnum , g , ans , args , kwargs : fun ( * subval ( args , argnum , g ) , * * kwargs ) )
1
python function undefinied inputs
Flags that a function is linear wrt all args
cosqa-train-13021
def def_linear(fun): """Flags that a function is linear wrt all args""" defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs: fun(*subval(args, argnum, g), **kwargs))
def load ( cls , tree_path ) : with open ( tree_path ) as f : tree_dict = json . load ( f ) return cls . from_dict ( tree_dict )
1
create an object tree from a text file in python
Create a new instance from a file .
cosqa-train-13022
def load(cls, tree_path): """Create a new instance from a file.""" with open(tree_path) as f: tree_dict = json.load(f) return cls.from_dict(tree_dict)
def parsed_args ( ) : parser = argparse . ArgumentParser ( description = """python runtime functions""" , epilog = "" ) parser . add_argument ( 'command' , nargs = '*' , help = "Name of the function to run with arguments" ) args = parser . parse_args ( ) return ( args , parser )
1
python function's arguements from cmd
cosqa-train-13023
def parsed_args(): parser = argparse.ArgumentParser(description="""python runtime functions""", epilog="") parser.add_argument('command',nargs='*', help="Name of the function to run with arguments") args = parser.parse_args() return (args, parser)
def format_result ( input ) : items = list ( iteritems ( input ) ) return OrderedDict ( sorted ( items , key = lambda x : x [ 0 ] ) )
1
create an ordered dictionary from unordered dictionary python
From : http : // stackoverflow . com / questions / 13062300 / convert - a - dict - to - sorted - dict - in - python
cosqa-train-13024
def format_result(input): """From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python """ items = list(iteritems(input)) return OrderedDict(sorted(items, key=lambda x: x[0]))
def interpolate_slice ( slice_rows , slice_cols , interpolator ) : fine_rows = np . arange ( slice_rows . start , slice_rows . stop , slice_rows . step ) fine_cols = np . arange ( slice_cols . start , slice_cols . stop , slice_cols . step ) return interpolator ( fine_cols , fine_rows )
1
python functional style passing array slices
Interpolate the given slice of the larger array .
cosqa-train-13025
def interpolate_slice(slice_rows, slice_cols, interpolator): """Interpolate the given slice of the larger array.""" fine_rows = np.arange(slice_rows.start, slice_rows.stop, slice_rows.step) fine_cols = np.arange(slice_cols.start, slice_cols.stop, slice_cols.step) return interpolator(fine_cols, fine_rows)
def vectorize ( values ) : if isinstance ( values , list ) : return ',' . join ( str ( v ) for v in values ) return values
1
create comma separated list from list python
Takes a value or list of values and returns a single result joined by if necessary .
cosqa-train-13026
def vectorize(values): """ Takes a value or list of values and returns a single result, joined by "," if necessary. """ if isinstance(values, list): return ','.join(str(v) for v in values) return values
def write_str2file ( pathname , astr ) : fname = pathname fhandle = open ( fname , 'wb' ) fhandle . write ( astr ) fhandle . close ( )
1
python fwrite string to file
writes a string to file
cosqa-train-13027
def write_str2file(pathname, astr): """writes a string to file""" fname = pathname fhandle = open(fname, 'wb') fhandle.write(astr) fhandle.close()
def create_conda_env ( sandbox_dir , env_name , dependencies , options = ( ) ) : env_dir = os . path . join ( sandbox_dir , env_name ) cmdline = [ "conda" , "create" , "--yes" , "--copy" , "--quiet" , "-p" , env_dir ] + list ( options ) + dependencies log . info ( "Creating conda environment: " ) log . info ( " command line: %s" , cmdline ) subprocess . check_call ( cmdline , stderr = subprocess . PIPE , stdout = subprocess . PIPE ) log . debug ( "Environment created" ) return env_dir , env_name
1
create conda env in python
Create a conda environment inside the current sandbox for the given list of dependencies and options .
cosqa-train-13028
def create_conda_env(sandbox_dir, env_name, dependencies, options=()): """ Create a conda environment inside the current sandbox for the given list of dependencies and options. Parameters ---------- sandbox_dir : str env_name : str dependencies : list List of conda specs options List of additional options to pass to conda. Things like ["-c", "conda-forge"] Returns ------- (env_dir, env_name) """ env_dir = os.path.join(sandbox_dir, env_name) cmdline = ["conda", "create", "--yes", "--copy", "--quiet", "-p", env_dir] + list(options) + dependencies log.info("Creating conda environment: ") log.info(" command line: %s", cmdline) subprocess.check_call(cmdline, stderr=subprocess.PIPE, stdout=subprocess.PIPE) log.debug("Environment created") return env_dir, env_name
def zeros ( self , name , * * kwargs ) : return self . _write_op ( self . _zeros_nosync , name , * * kwargs )
1
python generate numpy array of zeros
Create an array . Keyword arguments as per : func : zarr . creation . zeros .
cosqa-train-13029
def zeros(self, name, **kwargs): """Create an array. Keyword arguments as per :func:`zarr.creation.zeros`.""" return self._write_op(self._zeros_nosync, name, **kwargs)
def create_conda_env ( sandbox_dir , env_name , dependencies , options = ( ) ) : env_dir = os . path . join ( sandbox_dir , env_name ) cmdline = [ "conda" , "create" , "--yes" , "--copy" , "--quiet" , "-p" , env_dir ] + list ( options ) + dependencies log . info ( "Creating conda environment: " ) log . info ( " command line: %s" , cmdline ) subprocess . check_call ( cmdline , stderr = subprocess . PIPE , stdout = subprocess . PIPE ) log . debug ( "Environment created" ) return env_dir , env_name
1
create conda environment for python 2
Create a conda environment inside the current sandbox for the given list of dependencies and options .
cosqa-train-13030
def create_conda_env(sandbox_dir, env_name, dependencies, options=()): """ Create a conda environment inside the current sandbox for the given list of dependencies and options. Parameters ---------- sandbox_dir : str env_name : str dependencies : list List of conda specs options List of additional options to pass to conda. Things like ["-c", "conda-forge"] Returns ------- (env_dir, env_name) """ env_dir = os.path.join(sandbox_dir, env_name) cmdline = ["conda", "create", "--yes", "--copy", "--quiet", "-p", env_dir] + list(options) + dependencies log.info("Creating conda environment: ") log.info(" command line: %s", cmdline) subprocess.check_call(cmdline, stderr=subprocess.PIPE, stdout=subprocess.PIPE) log.debug("Environment created") return env_dir, env_name
def _rndPointDisposition ( dx , dy ) : x = int ( random . uniform ( - dx , dx ) ) y = int ( random . uniform ( - dy , dy ) ) return ( x , y )
1
python generate random x,y points
Return random disposition point .
cosqa-train-13031
def _rndPointDisposition(dx, dy): """Return random disposition point.""" x = int(random.uniform(-dx, dx)) y = int(random.uniform(-dy, dy)) return (x, y)
def dmap ( fn , record ) : values = ( fn ( v ) for k , v in record . items ( ) ) return dict ( itertools . izip ( record , values ) )
1
create dictionary using list comprehension in python sample
map for a directory
cosqa-train-13032
def dmap(fn, record): """map for a directory""" values = (fn(v) for k, v in record.items()) return dict(itertools.izip(record, values))
def rlognormal ( mu , tau , size = None ) : return np . random . lognormal ( mu , np . sqrt ( 1. / tau ) , size )
1
python generating random variables from a mixture of normal distributions
Return random lognormal variates .
cosqa-train-13033
def rlognormal(mu, tau, size=None): """ Return random lognormal variates. """ return np.random.lognormal(mu, np.sqrt(1. / tau), size)
def create_dir_rec ( path : Path ) : if not path . exists ( ) : Path . mkdir ( path , parents = True , exist_ok = True )
1
create directory recursive in python
Create a folder recursive .
cosqa-train-13034
def create_dir_rec(path: Path): """ Create a folder recursive. :param path: path :type path: ~pathlib.Path """ if not path.exists(): Path.mkdir(path, parents=True, exist_ok=True)
def _get_random_id ( ) : symbols = string . ascii_uppercase + string . ascii_lowercase + string . digits return '' . join ( random . choice ( symbols ) for _ in range ( 15 ) )
1
python genereate random string
Get a random ( i . e . unique ) string identifier
cosqa-train-13035
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 algo_exp ( x , m , t , b ) : return m * np . exp ( - t * x ) + b
1
create exponential function in python
mono - exponential curve .
cosqa-train-13036
def algo_exp(x, m, t, b): """mono-exponential curve.""" return m*np.exp(-t*x)+b
def list_files ( directory ) : return [ f for f in pathlib . Path ( directory ) . iterdir ( ) if f . is_file ( ) and not f . name . startswith ( '.' ) ]
1
python get a list of the files from a directory
Returns all files in a given directory
cosqa-train-13037
def list_files(directory): """Returns all files in a given directory """ return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]
def ensure_index ( self , key , unique = False ) : return self . collection . ensure_index ( key , unique = unique )
1
create mongodb index using python
Wrapper for pymongo . Collection . ensure_index
cosqa-train-13038
def ensure_index(self, key, unique=False): """Wrapper for pymongo.Collection.ensure_index """ return self.collection.ensure_index(key, unique=unique)
def timespan ( start_time ) : timespan = datetime . datetime . now ( ) - start_time timespan_ms = timespan . total_seconds ( ) * 1000 return timespan_ms
1
python get a range of time
Return time in milliseconds from start_time
cosqa-train-13039
def timespan(start_time): """Return time in milliseconds from start_time""" timespan = datetime.datetime.now() - start_time timespan_ms = timespan.total_seconds() * 1000 return timespan_ms
def deskew ( S ) : x = np . zeros ( 3 ) x [ 0 ] = S [ 2 , 1 ] x [ 1 ] = S [ 0 , 2 ] x [ 2 ] = S [ 1 , 0 ] return x
1
create skew symmetric matrix from a vector python
Converts a skew - symmetric cross - product matrix to its corresponding vector . Only works for 3x3 matrices .
cosqa-train-13040
def deskew(S): """Converts a skew-symmetric cross-product matrix to its corresponding vector. Only works for 3x3 matrices. Parameters ---------- S : :obj:`numpy.ndarray` of float A 3x3 skew-symmetric matrix. Returns ------- :obj:`numpy.ndarray` of float A 3-entry vector that corresponds to the given cross product matrix. """ x = np.zeros(3) x[0] = S[2,1] x[1] = S[0,2] x[2] = S[1,0] return x
def get_the_node_dict ( G , name ) : for node in G . nodes ( data = True ) : if node [ 0 ] == name : return node [ 1 ]
0
python get a specific node
Helper function that returns the node data of the node with the name supplied
cosqa-train-13041
def get_the_node_dict(G, name): """ Helper function that returns the node data of the node with the name supplied """ for node in G.nodes(data=True): if node[0] == name: return node[1]
def js_classnameify ( s ) : if not '_' in s : return s return '' . join ( w [ 0 ] . upper ( ) + w [ 1 : ] . lower ( ) for w in s . split ( '_' ) )
1
create valiable name by concatinate strings in python
Makes a classname .
cosqa-train-13042
def js_classnameify(s): """ Makes a classname. """ if not '_' in s: return s return ''.join(w[0].upper() + w[1:].lower() for w in s.split('_'))
def rel_path ( filename ) : return os . path . join ( os . getcwd ( ) , os . path . dirname ( __file__ ) , filename )
1
python get absolute path name
Function that gets relative path to the filename
cosqa-train-13043
def rel_path(filename): """ Function that gets relative path to the filename """ return os.path.join(os.getcwd(), os.path.dirname(__file__), filename)
def install_postgres ( user = None , dbname = None , password = None ) : execute ( pydiploy . django . install_postgres_server , user = user , dbname = dbname , password = password )
1
creating a database engine python posgres
Install Postgres on remote
cosqa-train-13044
def install_postgres(user=None, dbname=None, password=None): """Install Postgres on remote""" execute(pydiploy.django.install_postgres_server, user=user, dbname=dbname, password=password)
def url ( self ) : with switch_window ( self . _browser , self . name ) : return self . _browser . url
0
python get active window url and replace it
The url of this window
cosqa-train-13045
def url(self): """ The url of this window """ with switch_window(self._browser, self.name): return self._browser.url
def recarray ( self ) : return numpy . rec . fromrecords ( self . records , names = self . names )
1
creating a list in python without numpy
Returns data as : class : numpy . recarray .
cosqa-train-13046
def recarray(self): """Returns data as :class:`numpy.recarray`.""" return numpy.rec.fromrecords(self.records, names=self.names)
def uniq ( seq ) : seen = set ( ) return [ x for x in seq if str ( x ) not in seen and not seen . add ( str ( x ) ) ]
0
python get all unique strings of list
Return a copy of seq without duplicates .
cosqa-train-13047
def uniq(seq): """ Return a copy of seq without duplicates. """ seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
def from_bytes ( cls , b ) : im = cls ( ) im . chunks = list ( parse_chunks ( b ) ) im . init ( ) return im
1
creating an image in python from a byte array
Create : class : PNG from raw bytes . : arg bytes b : The raw bytes of the PNG file . : rtype : : class : PNG
cosqa-train-13048
def from_bytes(cls, b): """Create :class:`PNG` from raw bytes. :arg bytes b: The raw bytes of the PNG file. :rtype: :class:`PNG` """ im = cls() im.chunks = list(parse_chunks(b)) im.init() return im
def items ( self ) : return [ ( value_descriptor . name , value_descriptor . number ) for value_descriptor in self . _enum_type . values ]
1
python get all values of enum
Return a list of the ( name value ) pairs of the enum .
cosqa-train-13049
def items(self): """Return a list of the (name, value) pairs of the enum. These are returned in the order they were defined in the .proto file. """ return [(value_descriptor.name, value_descriptor.number) for value_descriptor in self._enum_type.values]
def ensure_hbounds ( self ) : self . cursor . x = min ( max ( 0 , self . cursor . x ) , self . columns - 1 )
1
cursor positioning python windows
Ensure the cursor is within horizontal screen bounds .
cosqa-train-13050
def ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds.""" self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
def current_memory_usage ( ) : import psutil proc = psutil . Process ( os . getpid ( ) ) #meminfo = proc.get_memory_info() meminfo = proc . memory_info ( ) rss = meminfo [ 0 ] # Resident Set Size / Mem Usage vms = meminfo [ 1 ] # Virtual Memory Size / VM Size # NOQA return rss
0
python get amount of ram in computer
Returns this programs current memory usage in bytes
cosqa-train-13051
def current_memory_usage(): """ Returns this programs current memory usage in bytes """ import psutil proc = psutil.Process(os.getpid()) #meminfo = proc.get_memory_info() meminfo = proc.memory_info() rss = meminfo[0] # Resident Set Size / Mem Usage vms = meminfo[1] # Virtual Memory Size / VM Size # NOQA return rss
def double_sha256 ( data ) : return bytes_as_revhex ( hashlib . sha256 ( hashlib . sha256 ( data ) . digest ( ) ) . digest ( ) )
1
custom hash function python
A standard compound hash .
cosqa-train-13052
def double_sha256(data): """A standard compound hash.""" return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())
def get_url_file_name ( url ) : assert isinstance ( url , ( str , _oldstr ) ) return urlparse . urlparse ( url ) . path . split ( '/' ) [ - 1 ]
1
python get basename url
Get the file name from an url Parameters ---------- url : str
cosqa-train-13053
def get_url_file_name(url): """Get the file name from an url Parameters ---------- url : str Returns ------- str The file name """ assert isinstance(url, (str, _oldstr)) return urlparse.urlparse(url).path.split('/')[-1]
def to_json ( value , * * kwargs ) : serial_list = [ val . serialize ( * * kwargs ) if isinstance ( val , HasProperties ) else val for val in value ] return serial_list
1
custom json serialize python tuple
Return a copy of the tuple as a list
cosqa-train-13054
def to_json(value, **kwargs): """Return a copy of the tuple as a list If the tuple contains HasProperties instances, they are serialized. """ serial_list = [ val.serialize(**kwargs) if isinstance(val, HasProperties) else val for val in value ] return serial_list
def from_json ( value , * * kwargs ) : if isinstance ( value , string_types ) : value = value . upper ( ) if value in ( 'TRUE' , 'Y' , 'YES' , 'ON' ) : return True if value in ( 'FALSE' , 'N' , 'NO' , 'OFF' ) : return False if isinstance ( value , int ) : return value raise ValueError ( 'Could not load boolean from JSON: {}' . format ( value ) )
1
python get boolean from json object
Coerces JSON string to boolean
cosqa-train-13055
def from_json(value, **kwargs): """Coerces JSON string to boolean""" if isinstance(value, string_types): value = value.upper() if value in ('TRUE', 'Y', 'YES', 'ON'): return True if value in ('FALSE', 'N', 'NO', 'OFF'): return False if isinstance(value, int): return value raise ValueError('Could not load boolean from JSON: {}'.format(value))
def validate ( self , value , model_instance , * * kwargs ) : self . get_choices_form_class ( ) . validate ( value , model_instance , * * kwargs )
1
custom validator python flaskform
This follows the validate rules for choices_form_class field used .
cosqa-train-13056
def validate(self, value, model_instance, **kwargs): """This follows the validate rules for choices_form_class field used. """ self.get_choices_form_class().validate(value, model_instance, **kwargs)
def to_camel_case ( text ) : split = text . split ( '_' ) return split [ 0 ] + "" . join ( x . title ( ) for x in split [ 1 : ] )
1
python get camel case for text
Convert to camel case .
cosqa-train-13057
def to_camel_case(text): """Convert to camel case. :param str text: :rtype: str :return: """ split = text.split('_') return split[0] + "".join(x.title() for x in split[1:])
def snap_to_beginning_of_week ( day , weekday_start = "Sunday" ) : delta_days = ( ( day . weekday ( ) + 1 ) % 7 ) if weekday_start is "Sunday" else day . weekday ( ) return day - timedelta ( days = delta_days )
0
custom week start day for python weekday
Get the first day of the current week .
cosqa-train-13058
def snap_to_beginning_of_week(day, weekday_start="Sunday"): """ Get the first day of the current week. :param day: The input date to snap. :param weekday_start: Either "Monday" or "Sunday", indicating the first day of the week. :returns: A date representing the first day of the current week. """ delta_days = ((day.weekday() + 1) % 7) if weekday_start is "Sunday" else day.weekday() return day - timedelta(days=delta_days)
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
1
python get clipboard data
Get the clipboard s text on OS X .
cosqa-train-13059
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 cric__decision_tree ( ) : model = sklearn . tree . DecisionTreeClassifier ( random_state = 0 , max_depth = 4 ) # we want to explain the raw probability outputs of the trees model . predict = lambda X : model . predict_proba ( X ) [ : , 1 ] return model
1
customize the output of a decision tree in python
Decision Tree
cosqa-train-13060
def cric__decision_tree(): """ Decision Tree """ model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4) # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
def get_column ( self , X , column ) : if isinstance ( X , pd . DataFrame ) : return X [ column ] . values return X [ : , column ]
1
python get column from a matrix
Return a column of the given matrix .
cosqa-train-13061
def get_column(self, X, column): """Return a column of the given matrix. Args: X: `numpy.ndarray` or `pandas.DataFrame`. column: `int` or `str`. Returns: np.ndarray: Selected column. """ if isinstance(X, pd.DataFrame): return X[column].values return X[:, column]
def data_directory ( ) : package_directory = os . path . abspath ( os . path . dirname ( __file__ ) ) return os . path . join ( package_directory , "data" )
1
data folder path python
Return the absolute path to the directory containing the package data .
cosqa-train-13062
def data_directory(): """Return the absolute path to the directory containing the package data.""" package_directory = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_directory, "data")
def get_free_memory_win ( ) : stat = MEMORYSTATUSEX ( ) ctypes . windll . kernel32 . GlobalMemoryStatusEx ( ctypes . byref ( stat ) ) return int ( stat . ullAvailPhys / 1024 / 1024 )
1
python get computer ram usage
Return current free memory on the machine for windows .
cosqa-train-13063
def get_free_memory_win(): """Return current free memory on the machine for windows. Warning : this script is really not robust Return in MB unit """ stat = MEMORYSTATUSEX() ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) return int(stat.ullAvailPhys / 1024 / 1024)
def start_of_month ( val ) : if type ( val ) == date : val = datetime . fromordinal ( val . toordinal ( ) ) return start_of_day ( val ) . replace ( day = 1 )
1
datetime add a month to a date python
Return a new datetime . datetime object with values that represent a start of a month . : param val : Date to ... : type val : datetime . datetime | datetime . date : rtype : datetime . datetime
cosqa-train-13064
def start_of_month(val): """ Return a new datetime.datetime object with values that represent a start of a month. :param val: Date to ... :type val: datetime.datetime | datetime.date :rtype: datetime.datetime """ if type(val) == date: val = datetime.fromordinal(val.toordinal()) return start_of_day(val).replace(day=1)
def parse_cookies ( self , req , name , field ) : return core . get_value ( req . COOKIES , name , field )
1
python get cookie for request
Pull the value from the cookiejar .
cosqa-train-13065
def parse_cookies(self, req, name, field): """Pull the value from the cookiejar.""" return core.get_value(req.COOKIES, name, field)
def _DateToEpoch ( date ) : tz_zero = datetime . datetime . utcfromtimestamp ( 0 ) diff_sec = int ( ( date - tz_zero ) . total_seconds ( ) ) return diff_sec * 1000000
1
datetime python get seconds from epoch
Converts python datetime to epoch microseconds .
cosqa-train-13066
def _DateToEpoch(date): """Converts python datetime to epoch microseconds.""" tz_zero = datetime.datetime.utcfromtimestamp(0) diff_sec = int((date - tz_zero).total_seconds()) return diff_sec * 1000000
def get_last_commit ( git_path = None ) : if git_path is None : git_path = GIT_PATH line = get_last_commit_line ( git_path ) revision_id = line . split ( ) [ 1 ] return revision_id
1
python get current git branch
Get the HEAD commit SHA1 of repository in current dir .
cosqa-train-13067
def get_last_commit(git_path=None): """ Get the HEAD commit SHA1 of repository in current dir. """ if git_path is None: git_path = GIT_PATH line = get_last_commit_line(git_path) revision_id = line.split()[1] return revision_id
def datetime_local_to_utc ( local ) : timestamp = time . mktime ( local . timetuple ( ) ) return datetime . datetime . utcfromtimestamp ( timestamp )
0
datetime python time to utc
Simple function to convert naive : std : datetime . datetime object containing local time to a naive : std : datetime . datetime object with UTC time .
cosqa-train-13068
def datetime_local_to_utc(local): """ Simple function to convert naive :std:`datetime.datetime` object containing local time to a naive :std:`datetime.datetime` object with UTC time. """ timestamp = time.mktime(local.timetuple()) return datetime.datetime.utcfromtimestamp(timestamp)
def get_current_branch ( ) : cmd = [ "git" , "rev-parse" , "--abbrev-ref" , "HEAD" ] output = subprocess . check_output ( cmd , stderr = subprocess . STDOUT ) return output . strip ( ) . decode ( "utf-8" )
1
python get current git commit
Return the current branch
cosqa-train-13069
def get_current_branch(): """ Return the current branch """ cmd = ["git", "rev-parse", "--abbrev-ref", "HEAD"] output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) return output.strip().decode("utf-8")
def ToDatetime ( self ) : return datetime . utcfromtimestamp ( self . seconds + self . nanos / float ( _NANOS_PER_SECOND ) )
1
datetime python3 removing the microseconds
Converts Timestamp to datetime .
cosqa-train-13070
def ToDatetime(self): """Converts Timestamp to datetime.""" return datetime.utcfromtimestamp( self.seconds + self.nanos / float(_NANOS_PER_SECOND))
def get_current_desktop ( self ) : desktop = ctypes . c_long ( 0 ) _libxdo . xdo_get_current_desktop ( self . _xdo , ctypes . byref ( desktop ) ) return desktop . value
1
python get current users desktop
Get the current desktop . Uses _NET_CURRENT_DESKTOP of the EWMH spec .
cosqa-train-13071
def get_current_desktop(self): """ Get the current desktop. Uses ``_NET_CURRENT_DESKTOP`` of the EWMH spec. """ desktop = ctypes.c_long(0) _libxdo.xdo_get_current_desktop(self._xdo, ctypes.byref(desktop)) return desktop.value
def datetime_to_year_quarter ( dt ) : year = dt . year quarter = int ( math . ceil ( float ( dt . month ) / 3 ) ) return ( year , quarter )
1
datetime to quarter and year python
Args : dt : a datetime Returns : tuple of the datetime s year and quarter
cosqa-train-13072
def datetime_to_year_quarter(dt): """ Args: dt: a datetime Returns: tuple of the datetime's year and quarter """ year = dt.year quarter = int(math.ceil(float(dt.month)/3)) return (year, quarter)
def date_to_timestamp ( date ) : date_tuple = date . timetuple ( ) timestamp = calendar . timegm ( date_tuple ) * 1000 return timestamp
1
python get datetime from timestamp
date to unix timestamp in milliseconds
cosqa-train-13073
def date_to_timestamp(date): """ date to unix timestamp in milliseconds """ date_tuple = date.timetuple() timestamp = calendar.timegm(date_tuple) * 1000 return timestamp
def empty ( self , name , * * kwargs ) : return self . _write_op ( self . _empty_nosync , name , * * kwargs )
1
declaring empty numpy array in python
Create an array . Keyword arguments as per : func : zarr . creation . empty .
cosqa-train-13074
def empty(self, name, **kwargs): """Create an array. Keyword arguments as per :func:`zarr.creation.empty`.""" return self._write_op(self._empty_nosync, name, **kwargs)
def get_best_encoding ( stream ) : rv = getattr ( stream , 'encoding' , None ) or sys . getdefaultencoding ( ) if is_ascii_encoding ( rv ) : return 'utf-8' return rv
1
python get default encoding
Returns the default stream encoding if not found .
cosqa-train-13075
def get_best_encoding(stream): """Returns the default stream encoding if not found.""" rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding() if is_ascii_encoding(rv): return 'utf-8' return rv
def _defaultdict ( dct , fallback = _illegal_character ) : out = defaultdict ( lambda : fallback ) for k , v in six . iteritems ( dct ) : out [ k ] = v return out
1
default value for all keys in a dict python
Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed .
cosqa-train-13076
def _defaultdict(dct, fallback=_illegal_character): """Wraps the given dictionary such that the given fallback function will be called when a nonexistent key is accessed. """ out = defaultdict(lambda: fallback) for k, v in six.iteritems(dct): out[k] = v return out
def parse_domain ( url ) : domain_match = lib . DOMAIN_REGEX . match ( url ) if domain_match : return domain_match . group ( )
0
python get domain from url
parse the domain from the url
cosqa-train-13077
def parse_domain(url): """ parse the domain from the url """ domain_match = lib.DOMAIN_REGEX.match(url) if domain_match: return domain_match.group()
def fromDict ( cls , _dict ) : obj = cls ( ) obj . __dict__ . update ( _dict ) return obj
1
defining constructor of dict in python
Builds instance from dictionary of properties .
cosqa-train-13078
def fromDict(cls, _dict): """ Builds instance from dictionary of properties. """ obj = cls() obj.__dict__.update(_dict) return obj
def get_filetype_icon ( fname ) : ext = osp . splitext ( fname ) [ 1 ] if ext . startswith ( '.' ) : ext = ext [ 1 : ] return get_icon ( "%s.png" % ext , ima . icon ( 'FileIcon' ) )
1
python get file icon from extension
Return file type icon
cosqa-train-13079
def get_filetype_icon(fname): """Return file type icon""" ext = osp.splitext(fname)[1] if ext.startswith('.'): ext = ext[1:] return get_icon( "%s.png" % ext, ima.icon('FileIcon') )
def remove_examples_all ( ) : d = examples_all_dir ( ) if d . exists ( ) : log . debug ( 'remove %s' , d ) d . rmtree ( ) else : log . debug ( 'nothing to remove: %s' , d )
1
delete any file in folder in python
remove arduino / examples / all directory .
cosqa-train-13080
def remove_examples_all(): """remove arduino/examples/all directory. :rtype: None """ d = examples_all_dir() if d.exists(): log.debug('remove %s', d) d.rmtree() else: log.debug('nothing to remove: %s', d)
def get_time ( filename ) : ts = os . stat ( filename ) . st_mtime return datetime . datetime . utcfromtimestamp ( ts )
1
python get file last modified time datetime
Get the modified time for a file as a datetime instance
cosqa-train-13081
def get_time(filename): """ Get the modified time for a file as a datetime instance """ ts = os.stat(filename).st_mtime return datetime.datetime.utcfromtimestamp(ts)
def remove_columns ( self , data , columns ) : for column in columns : if column in data . columns : data = data . drop ( column , axis = 1 ) return data
1
delete columns from data frame in python
This method removes columns in data
cosqa-train-13082
def remove_columns(self, data, columns): """ This method removes columns in data :param data: original Pandas dataframe :param columns: list of columns to remove :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with removed columns :rtype: pandas.DataFrame """ for column in columns: if column in data.columns: data = data.drop(column, axis=1) return data
def guess_media_type ( filepath ) : o = subprocess . check_output ( [ 'file' , '--mime-type' , '-Lb' , filepath ] ) o = o . strip ( ) return o
1
python get file mime type
Returns the media - type of the file at the given filepath
cosqa-train-13083
def guess_media_type(filepath): """Returns the media-type of the file at the given ``filepath``""" o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath]) o = o.strip() return o
def unique ( seq ) : cleaned = [ ] for each in seq : if each not in cleaned : cleaned . append ( each ) return cleaned
1
delete empty elements in list python3
Return the unique elements of a collection even if those elements are unhashable and unsortable like dicts and sets
cosqa-train-13084
def unique(seq): """Return the unique elements of a collection even if those elements are unhashable and unsortable, like dicts and sets""" cleaned = [] for each in seq: if each not in cleaned: cleaned.append(each) return cleaned
def get_file_name ( url ) : return os . path . basename ( urllib . parse . urlparse ( url ) . path ) or 'unknown_name'
1
python get filename according url
Returns file name of file at given url .
cosqa-train-13085
def get_file_name(url): """Returns file name of file at given url.""" return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'
def clear_global ( self ) : vname = self . varname logger . debug ( f'global clearning {vname}' ) if vname in globals ( ) : logger . debug ( 'removing global instance var: {}' . format ( vname ) ) del globals ( ) [ vname ]
1
delete variables from globals python
Clear only any cached global data .
cosqa-train-13086
def clear_global(self): """Clear only any cached global data. """ vname = self.varname logger.debug(f'global clearning {vname}') if vname in globals(): logger.debug('removing global instance var: {}'.format(vname)) del globals()[vname]
def get_hash ( self , handle ) : fpath = self . _fpath_from_handle ( handle ) return DiskStorageBroker . hasher ( fpath )
1
python get hash of file filestorage
Return the hash .
cosqa-train-13087
def get_hash(self, handle): """Return the hash.""" fpath = self._fpath_from_handle(handle) return DiskStorageBroker.hasher(fpath)
def rm_keys_from_dict ( d , keys ) : # Loop for each key given for key in keys : # Is the key in the dictionary? if key in d : try : d . pop ( key , None ) except KeyError : # Not concerned with an error. Keep going. pass return d
1
deleting keys in python dictionaries
Given a dictionary and a key list remove any data in the dictionary with the given keys .
cosqa-train-13088
def rm_keys_from_dict(d, keys): """ Given a dictionary and a key list, remove any data in the dictionary with the given keys. :param dict d: Metadata :param list keys: Keys to be removed :return dict d: Metadata """ # Loop for each key given for key in keys: # Is the key in the dictionary? if key in d: try: d.pop(key, None) except KeyError: # Not concerned with an error. Keep going. pass return d
def get_system_uid ( ) : try : if os . name == 'nt' : return get_nt_system_uid ( ) if sys . platform == 'darwin' : return get_osx_system_uid ( ) except Exception : return get_mac_uid ( ) else : return get_mac_uid ( )
0
python get id of windows
Get a ( probably ) unique ID to identify a system . Used to differentiate votes .
cosqa-train-13089
def get_system_uid(): """Get a (probably) unique ID to identify a system. Used to differentiate votes. """ try: if os.name == 'nt': return get_nt_system_uid() if sys.platform == 'darwin': return get_osx_system_uid() except Exception: return get_mac_uid() else: return get_mac_uid()
def find_le ( a , x ) : i = bs . bisect_right ( a , x ) if i : return i - 1 raise ValueError
1
python get index of lowest value in list
Find rightmost value less than or equal to x .
cosqa-train-13090
def find_le(a, x): """Find rightmost value less than or equal to x.""" i = bs.bisect_right(a, x) if i: return i - 1 raise ValueError
def drop_empty ( rows ) : return zip ( * [ col for col in zip ( * rows ) if bool ( filter ( bool , col [ 1 : ] ) ) ] )
0
detect all empty column python
Transpose the columns into rows remove all of the rows that are empty after the first cell then transpose back . The result is that columns that have a header but no data in the body are removed assuming the header is the first row .
cosqa-train-13091
def drop_empty(rows): """Transpose the columns into rows, remove all of the rows that are empty after the first cell, then transpose back. The result is that columns that have a header but no data in the body are removed, assuming the header is the first row. """ return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])
def get_property_by_name ( pif , name ) : return next ( ( x for x in pif . properties if x . name == name ) , None )
1
python get instance property by name
Get a property by name
cosqa-train-13092
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
def on_press_key ( key , callback , suppress = False ) : return hook_key ( key , lambda e : e . event_type == KEY_UP or callback ( e ) , suppress = suppress )
1
detect any key press python
Invokes callback for KEY_DOWN event related to the given key . For details see hook .
cosqa-train-13093
def on_press_key(key, callback, suppress=False): """ Invokes `callback` for KEY_DOWN event related to the given key. For details see `hook`. """ return hook_key(key, lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress)
def __getitem__ ( self , index ) : row , col = index return self . rows [ row ] [ col ]
1
python get item at an index
Get the item at the given index .
cosqa-train-13094
def __getitem__(self, index): """Get the item at the given index. Index is a tuple of (row, col) """ row, col = index return self.rows[row][col]
def pdf ( x , mu , std ) : return ( 1.0 / ( std * sqrt ( 2 * pi ) ) ) * np . exp ( - ( x - mu ) ** 2 / ( 2 * std ** 2 ) )
1
determine probability distribution of data python
Probability density function ( normal distribution )
cosqa-train-13095
def pdf(x, mu, std): """Probability density function (normal distribution)""" return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))
def get_mtime ( fname ) : try : mtime = os . stat ( fname ) . st_mtime_ns except OSError : # The file might be right in the middle of being written # so sleep time . sleep ( 1 ) mtime = os . stat ( fname ) . st_mtime_ns return mtime
1
python get last file modified
Find the time this file was last modified .
cosqa-train-13096
def get_mtime(fname): """ Find the time this file was last modified. :param fname: File name :return: The last time the file was modified. """ try: mtime = os.stat(fname).st_mtime_ns except OSError: # The file might be right in the middle of being written # so sleep time.sleep(1) mtime = os.stat(fname).st_mtime_ns return mtime
def linregress ( x , y , return_stats = False ) : a1 , a0 , r_value , p_value , stderr = scipy . stats . linregress ( x , y ) retval = a1 , a0 if return_stats : retval += r_value , p_value , stderr return retval
1
determine variable value multi value regression python
linear regression calculation
cosqa-train-13097
def linregress(x, y, return_stats=False): """linear regression calculation Parameters ---- x : independent variable (series) y : dependent variable (series) return_stats : returns statistical values as well if required (bool) Returns ---- list of parameters (and statistics) """ a1, a0, r_value, p_value, stderr = scipy.stats.linregress(x, y) retval = a1, a0 if return_stats: retval += r_value, p_value, stderr return retval
def _get_current_label ( self ) : if len ( self . _last ) == 0 : raise StopIteration return self . _last [ : self . _last . find ( ":" ) ]
1
python get last line of varable
Get the label from the last line read
cosqa-train-13098
def _get_current_label(self): """Get the label from the last line read""" if len(self._last) == 0: raise StopIteration return self._last[:self._last.find(":")]
def is_function ( self ) : if self . is_instance ( ) or self . is_class ( ) : return False return isinstance ( self . callback , ( Callable , classmethod ) )
1
determining if something is a callable python
return True if callback is a vanilla plain jane function
cosqa-train-13099
def is_function(self): """return True if callback is a vanilla plain jane function""" if self.is_instance() or self.is_class(): return False return isinstance(self.callback, (Callable, classmethod))