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 rewrap ( s , width = COLS ) : s = ' ' . join ( [ l . strip ( ) for l in s . strip ( ) . split ( '\n' ) ] ) return '\n' . join ( textwrap . wrap ( s , width ) )
1
fixed width text in python
Join all lines from input string and wrap it at specified width
cosqa-train-15400
def rewrap(s, width=COLS): """ Join all lines from input string and wrap it at specified width """ s = ' '.join([l.strip() for l in s.strip().split('\n')]) return '\n'.join(textwrap.wrap(s, width))
def lower_ext ( abspath ) : fname , ext = os . path . splitext ( abspath ) return fname + ext . lower ( )
0
python how to change file extension nicely
Convert file extension to lowercase .
cosqa-train-15401
def lower_ext(abspath): """Convert file extension to lowercase. """ fname, ext = os.path.splitext(abspath) return fname + ext.lower()
def flatten ( nested ) : flat_return = list ( ) def __inner_flat ( nested , flat ) : for i in nested : __inner_flat ( i , flat ) if isinstance ( i , list ) else flat . append ( i ) return flat __inner_flat ( nested , flat_return ) return flat_return
1
flatten by nesting depth python
Return a flatten version of the nested argument
cosqa-train-15402
def flatten(nested): """ Return a flatten version of the nested argument """ flat_return = list() def __inner_flat(nested,flat): for i in nested: __inner_flat(i, flat) if isinstance(i, list) else flat.append(i) return flat __inner_flat(nested,flat_return) return flat_return
def is_valid_url ( url ) : pieces = urlparse ( url ) return all ( [ pieces . scheme , pieces . netloc ] )
0
python how to check a url is validate
Checks if a given string is an url
cosqa-train-15403
def is_valid_url(url): """Checks if a given string is an url""" pieces = urlparse(url) return all([pieces.scheme, pieces.netloc])
def enable_writes ( self ) : self . write_buffer = [ ] self . flush_lock = threading . RLock ( ) self . flush_thread = FlushThread ( self . max_batch_time , self . _flush_writes )
1
flushing the print queue in python multiprocessing
Restores the state of the batched queue for writing .
cosqa-train-15404
def enable_writes(self): """Restores the state of the batched queue for writing.""" self.write_buffer = [] self.flush_lock = threading.RLock() self.flush_thread = FlushThread(self.max_batch_time, self._flush_writes)
def find_lt ( a , x ) : i = bisect . bisect_left ( a , x ) if i : return a [ i - 1 ] raise ValueError
0
python how to check for the smallest item in a list
Find rightmost value less than x
cosqa-train-15405
def find_lt(a, x): """Find rightmost value less than x""" i = bisect.bisect_left(a, x) if i: return a[i-1] raise ValueError
def normalize_value ( text ) : result = text . replace ( '\n' , ' ' ) result = re . subn ( '[ ]{2,}' , ' ' , result ) [ 0 ] return result
1
for line python deletes spaces
This removes newlines and multiple spaces from a string .
cosqa-train-15406
def normalize_value(text): """ This removes newlines and multiple spaces from a string. """ result = text.replace('\n', ' ') result = re.subn('[ ]{2,}', ' ', result)[0] return result
def has_overlaps ( self ) : sorted_list = sorted ( self ) for i in range ( 0 , len ( sorted_list ) - 1 ) : if sorted_list [ i ] . overlaps ( sorted_list [ i + 1 ] ) : return True return False
0
python how to check if at least one item overlaps in two lists
: returns : True if one or more range in the list overlaps with another : rtype : bool
cosqa-train-15407
def has_overlaps(self): """ :returns: True if one or more range in the list overlaps with another :rtype: bool """ sorted_list = sorted(self) for i in range(0, len(sorted_list) - 1): if sorted_list[i].overlaps(sorted_list[i + 1]): return True return False
def __call__ ( self , _ ) : if self . iter % self . step == 0 : self . pbar . update ( self . step ) self . iter += 1
0
for loop python progress bar
Update the progressbar .
cosqa-train-15408
def __call__(self, _): """Update the progressbar.""" if self.iter % self.step == 0: self.pbar.update(self.step) self.iter += 1
def has_attribute ( module_name , attribute_name ) : init_file = '%s/__init__.py' % module_name return any ( [ attribute_name in init_line for init_line in open ( init_file ) . readlines ( ) ] )
0
python how to check if attribute exist
Is this attribute present?
cosqa-train-15409
def has_attribute(module_name, attribute_name): """Is this attribute present?""" init_file = '%s/__init__.py' % module_name return any( [attribute_name in init_line for init_line in open(init_file).readlines()] )
def combine ( self , a , b ) : for l in ( a , b ) : for x in l : yield x
0
for loop with two iterators python
A generator that combines two iterables .
cosqa-train-15410
def combine(self, a, b): """A generator that combines two iterables.""" for l in (a, b): for x in l: yield x
def is_serializable ( obj ) : if inspect . isclass ( obj ) : return Serializable . is_serializable_type ( obj ) return isinstance ( obj , Serializable ) or hasattr ( obj , '_asdict' )
1
python how to check if object is seriniable
Return True if the given object conforms to the Serializable protocol .
cosqa-train-15411
def is_serializable(obj): """Return `True` if the given object conforms to the Serializable protocol. :rtype: bool """ if inspect.isclass(obj): return Serializable.is_serializable_type(obj) return isinstance(obj, Serializable) or hasattr(obj, '_asdict')
def _delete_local ( self , filename ) : if os . path . exists ( filename ) : os . remove ( filename )
1
force removing a file python
Deletes the specified file from the local filesystem .
cosqa-train-15412
def _delete_local(self, filename): """Deletes the specified file from the local filesystem.""" if os.path.exists(filename): os.remove(filename)
def clear ( ) : if sys . platform . startswith ( "win" ) : call ( "cls" , shell = True ) else : call ( "clear" , shell = True )
1
python how to clear the shell
Clears the console .
cosqa-train-15413
def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True)
def login ( self , username , password = None , token = None ) : self . session . basic_auth ( username , password )
0
forcing python rest api for authentication to create django session
Login user for protected API calls .
cosqa-train-15414
def login(self, username, password=None, token=None): """Login user for protected API calls.""" self.session.basic_auth(username, password)
def bit_clone ( bits ) : new = BitSet ( bits . size ) new . ior ( bits ) return new
1
python how to clone object
Clone a bitset
cosqa-train-15415
def bit_clone( bits ): """ Clone a bitset """ new = BitSet( bits.size ) new.ior( bits ) return new
def get_year_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( month = 1 ) . replace ( day = 1 )
1
form a date column in python using existing year month columns
Returns January 1 of the given year .
cosqa-train-15416
def get_year_start(day=None): """Returns January 1 of the given year.""" day = add_timezone(day or datetime.date.today()) return day.replace(month=1).replace(day=1)
def feature_union_concat ( Xs , nsamples , weights ) : if any ( x is FIT_FAILURE for x in Xs ) : return FIT_FAILURE Xs = [ X if w is None else X * w for X , w in zip ( Xs , weights ) if X is not None ] if not Xs : return np . zeros ( ( nsamples , 0 ) ) if any ( sparse . issparse ( f ) for f in Xs ) : return sparse . hstack ( Xs ) . tocsr ( ) return np . hstack ( Xs )
0
python how to combine sparce matrix with other features
Apply weights and concatenate outputs from a FeatureUnion
cosqa-train-15417
def feature_union_concat(Xs, nsamples, weights): """Apply weights and concatenate outputs from a FeatureUnion""" if any(x is FIT_FAILURE for x in Xs): return FIT_FAILURE Xs = [X if w is None else X * w for X, w in zip(Xs, weights) if X is not None] if not Xs: return np.zeros((nsamples, 0)) if any(sparse.issparse(f) for f in Xs): return sparse.hstack(Xs).tocsr() return np.hstack(Xs)
def fixed ( ctx , number , decimals = 2 , no_commas = False ) : value = _round ( ctx , number , decimals ) format_str = '{:f}' if no_commas else '{:,f}' return format_str . format ( value )
1
format float with two decimals python
Formats the given number in decimal format using a period and commas
cosqa-train-15418
def fixed(ctx, number, decimals=2, no_commas=False): """ Formats the given number in decimal format using a period and commas """ value = _round(ctx, number, decimals) format_str = '{:f}' if no_commas else '{:,f}' return format_str.format(value)
def from_pb ( cls , pb ) : obj = cls . _from_pb ( pb ) obj . _pb = pb return obj
0
python how to copy protobuf
Instantiate the object from a protocol buffer .
cosqa-train-15419
def from_pb(cls, pb): """Instantiate the object from a protocol buffer. Args: pb (protobuf) Save a reference to the protocol buffer on the object. """ obj = cls._from_pb(pb) obj._pb = pb return obj
def _get_wow64 ( ) : # Try to determine if the debugger itself is running on WOW64. # On error assume False. if bits == 64 : wow64 = False else : try : wow64 = IsWow64Process ( GetCurrentProcess ( ) ) except Exception : wow64 = False return wow64
1
python how to determine whether i am on windows
Determines if the current process is running in Windows - On - Windows 64 bits .
cosqa-train-15420
def _get_wow64(): """ Determines if the current process is running in Windows-On-Windows 64 bits. @rtype: bool @return: C{True} of the current process is a 32 bit program running in a 64 bit version of Windows, C{False} if it's either a 32 bit program in a 32 bit Windows or a 64 bit program in a 64 bit Windows. """ # Try to determine if the debugger itself is running on WOW64. # On error assume False. if bits == 64: wow64 = False else: try: wow64 = IsWow64Process( GetCurrentProcess() ) except Exception: wow64 = False return wow64
def get_lons_from_cartesian ( x__ , y__ ) : return rad2deg ( arccos ( x__ / sqrt ( x__ ** 2 + y__ ** 2 ) ) ) * sign ( y__ )
0
formula for latitude and longtitude x y coordinate python
Get longitudes from cartesian coordinates .
cosqa-train-15421
def get_lons_from_cartesian(x__, y__): """Get longitudes from cartesian coordinates. """ return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)
def _repr ( obj ) : vals = ", " . join ( "{}={!r}" . format ( name , getattr ( obj , name ) ) for name in obj . _attribs ) if vals : t = "{}(name={}, {})" . format ( obj . __class__ . __name__ , obj . name , vals ) else : t = "{}(name={})" . format ( obj . __class__ . __name__ , obj . name ) return t
1
python how to display object attributes
Show the received object as precise as possible .
cosqa-train-15422
def _repr(obj): """Show the received object as precise as possible.""" vals = ", ".join("{}={!r}".format( name, getattr(obj, name)) for name in obj._attribs) if vals: t = "{}(name={}, {})".format(obj.__class__.__name__, obj.name, vals) else: t = "{}(name={})".format(obj.__class__.__name__, obj.name) return t
def stft ( func = None , * * kwparams ) : from numpy . fft import fft , ifft ifft_r = lambda * args : ifft ( * args ) . real return stft . base ( transform = fft , inverse_transform = ifft_r ) ( func , * * kwparams )
0
python how to fft
Short Time Fourier Transform for real data keeping the full FFT block .
cosqa-train-15423
def stft(func=None, **kwparams): """ Short Time Fourier Transform for real data keeping the full FFT block. Same to the default STFT strategy, but with new defaults. This is the same to: .. code-block:: python stft.base(transform=numpy.fft.fft, inverse_transform=lambda *args: numpy.fft.ifft(*args).real) See ``stft.base`` docs for more. """ from numpy.fft import fft, ifft ifft_r = lambda *args: ifft(*args).real return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)
def set_timeout ( scope , timeout ) : conn = scope . get ( '__connection__' ) conn . set_timeout ( int ( timeout [ 0 ] ) ) return True
1
python how to for different key set different session timeout
Defines the time after which Exscript fails if it does not receive a prompt from the remote host .
cosqa-train-15424
def set_timeout(scope, timeout): """ Defines the time after which Exscript fails if it does not receive a prompt from the remote host. :type timeout: int :param timeout: The timeout in seconds. """ conn = scope.get('__connection__') conn.set_timeout(int(timeout[0])) return True
def _stdin_ ( p ) : _v = sys . version [ 0 ] return input ( p ) if _v is '3' else raw_input ( p )
0
function to take user input in python3
Takes input from user . Works for Python 2 and 3 .
cosqa-train-15425
def _stdin_(p): """Takes input from user. Works for Python 2 and 3.""" _v = sys.version[0] return input(p) if _v is '3' else raw_input(p)
def _get_printable_columns ( columns , row ) : if not columns : return row # Extract the column values, in the order specified. return tuple ( row [ c ] for c in columns )
1
python how to format print into columns and rows
Return only the part of the row which should be printed .
cosqa-train-15426
def _get_printable_columns(columns, row): """Return only the part of the row which should be printed. """ if not columns: return row # Extract the column values, in the order specified. return tuple(row[c] for c in columns)
def _stdin_ ( p ) : _v = sys . version [ 0 ] return input ( p ) if _v is '3' else raw_input ( p )
0
function used to get user input in python3
Takes input from user . Works for Python 2 and 3 .
cosqa-train-15427
def _stdin_(p): """Takes input from user. Works for Python 2 and 3.""" _v = sys.version[0] return input(p) if _v is '3' else raw_input(p)
def _send_file ( self , filename ) : # pylint: disable=E1101 ftp = ftplib . FTP ( host = self . host ) ftp . login ( user = self . user , passwd = self . password ) ftp . set_pasv ( True ) ftp . storbinary ( "STOR %s" % os . path . basename ( filename ) , file ( filename , 'rb' ) )
1
python how to ftp a file
Sends a file via FTP .
cosqa-train-15428
def _send_file(self, filename): """ Sends a file via FTP. """ # pylint: disable=E1101 ftp = ftplib.FTP(host=self.host) ftp.login(user=self.user, passwd=self.password) ftp.set_pasv(True) ftp.storbinary("STOR %s" % os.path.basename(filename), file(filename, 'rb'))
def many_until1 ( these , term ) : first = [ these ( ) ] these_results , term_result = many_until ( these , term ) return ( first + these_results , term_result )
0
function with multiple returns python
Like many_until but must consume at least one of these .
cosqa-train-15429
def many_until1(these, term): """Like many_until but must consume at least one of these. """ first = [these()] these_results, term_result = many_until(these, term) return (first + these_results, term_result)
def write_file ( filename , content ) : print 'Generating {0}' . format ( filename ) with open ( filename , 'wb' ) as out_f : out_f . write ( content )
1
python how to generate a file
Create the file with the given content
cosqa-train-15430
def write_file(filename, content): """Create the file with the given content""" print 'Generating {0}'.format(filename) with open(filename, 'wb') as out_f: out_f.write(content)
def smooth_gaussian ( image , sigma = 1 ) : return scipy . ndimage . filters . gaussian_filter ( image , sigma = sigma , mode = "nearest" )
0
gaussian filter from 2d gaussian function in python
Returns Gaussian smoothed image .
cosqa-train-15431
def smooth_gaussian(image, sigma=1): """Returns Gaussian smoothed image. :param image: numpy array or :class:`jicimagelib.image.Image` :param sigma: standard deviation :returns: :class:`jicimagelib.image.Image` """ return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode="nearest")
def uniform_noise ( points ) : return np . random . rand ( 1 ) * np . random . uniform ( points , 1 ) + random . sample ( [ 2 , - 2 ] , 1 )
0
python how to generate brown noise
Init a uniform noise variable .
cosqa-train-15432
def uniform_noise(points): """Init a uniform noise variable.""" return np.random.rand(1) * np.random.uniform(points, 1) \ + random.sample([2, -2], 1)
def _uniqueid ( n = 30 ) : return '' . join ( random . SystemRandom ( ) . choice ( string . ascii_uppercase + string . ascii_lowercase ) for _ in range ( n ) )
1
generate 100 unique random numbers in python
Return a unique string with length n .
cosqa-train-15433
def _uniqueid(n=30): """Return a unique string with length n. :parameter int N: number of character in the uniqueid :return: the uniqueid :rtype: str """ return ''.join(random.SystemRandom().choice( string.ascii_uppercase + string.ascii_lowercase) for _ in range(n))
def get_var ( self , name ) : for var in self . vars : if var . name == name : return var else : raise ValueError
1
python how to get a variable's name
Returns the variable set with the given name .
cosqa-train-15434
def get_var(self, name): """ Returns the variable set with the given name. """ for var in self.vars: if var.name == name: return var else: raise ValueError
def daterange ( start_date , end_date ) : for n in range ( int ( ( end_date - start_date ) . days ) ) : yield start_date + timedelta ( n )
1
generate a range of date python datetime
Yield one date per day from starting date to ending date .
cosqa-train-15435
def daterange(start_date, end_date): """ Yield one date per day from starting date to ending date. Args: start_date (date): starting date. end_date (date): ending date. Yields: date: a date for each day within the range. """ for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n)
def get_property ( self , filename ) : with open ( self . filepath ( filename ) ) as f : return f . read ( ) . strip ( )
1
python how to get file property
Opens the file and reads the value
cosqa-train-15436
def get_property(self, filename): """Opens the file and reads the value""" with open(self.filepath(filename)) as f: return f.read().strip()
def generate ( env ) : cplusplus . generate ( env ) env [ 'CXX' ] = 'CC' env [ 'CXXFLAGS' ] = SCons . Util . CLVar ( '-LANG:std' ) env [ 'SHCXX' ] = '$CXX' env [ 'SHOBJSUFFIX' ] = '.o' env [ 'STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME' ] = 1
0
generate c++ with python
Add Builders and construction variables for SGI MIPS C ++ to an Environment .
cosqa-train-15437
def generate(env): """Add Builders and construction variables for SGI MIPS C++ to an Environment.""" cplusplus.generate(env) env['CXX'] = 'CC' env['CXXFLAGS'] = SCons.Util.CLVar('-LANG:std') env['SHCXX'] = '$CXX' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
def convert_2_utc ( self , datetime_ , timezone ) : datetime_ = self . tz_mapper [ timezone ] . localize ( datetime_ ) return datetime_ . astimezone ( pytz . UTC )
0
python how to get utc offset from a datetime object
convert to datetime to UTC offset .
cosqa-train-15438
def convert_2_utc(self, datetime_, timezone): """convert to datetime to UTC offset.""" datetime_ = self.tz_mapper[timezone].localize(datetime_) return datetime_.astimezone(pytz.UTC)
def money ( min = 0 , max = 10 ) : value = random . choice ( range ( min * 100 , max * 100 ) ) return "%1.2f" % ( float ( value ) / 100 )
0
generate random float between 1 and 15 python
Return a str of decimal with two digits after a decimal mark .
cosqa-train-15439
def money(min=0, max=10): """Return a str of decimal with two digits after a decimal mark.""" value = random.choice(range(min * 100, max * 100)) return "%1.2f" % (float(value) / 100)
def get_uniques ( l ) : result = [ ] for i in l : if i not in result : result . append ( i ) return result
0
python how to make a list of strings unique
Returns a list with no repeated elements .
cosqa-train-15440
def get_uniques(l): """ Returns a list with no repeated elements. """ result = [] for i in l: if i not in result: result.append(i) return result
def uniqueID ( size = 6 , chars = string . ascii_uppercase + string . digits ) : return '' . join ( random . choice ( chars ) for x in xrange ( size ) )
0
generate random guid in python
A quick and dirty way to get a unique string
cosqa-train-15441
def uniqueID(size=6, chars=string.ascii_uppercase + string.digits): """A quick and dirty way to get a unique string""" return ''.join(random.choice(chars) for x in xrange(size))
def asMaskedArray ( self ) : return ma . masked_array ( data = self . data , mask = self . mask , fill_value = self . fill_value )
1
python how to make a masked array
Creates converts to a masked array
cosqa-train-15442
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 sha1 ( s ) : h = hashlib . new ( 'sha1' ) h . update ( s ) return h . hexdigest ( )
1
generate sha1 from string python
Returns a sha1 of the given string
cosqa-train-15443
def sha1(s): """ Returns a sha1 of the given string """ h = hashlib.new('sha1') h.update(s) return h.hexdigest()
def _weighted_selection ( l , n ) : cuml = [ ] items = [ ] total_weight = 0.0 for weight , item in l : total_weight += weight cuml . append ( total_weight ) items . append ( item ) return [ items [ bisect . bisect ( cuml , random . random ( ) * total_weight ) ] for _ in range ( n ) ]
1
python how to make of random list with different weights
Selects n random elements from a list of ( weight item ) tuples . Based on code snippet by Nick Johnson
cosqa-train-15444
def _weighted_selection(l, n): """ Selects n random elements from a list of (weight, item) tuples. Based on code snippet by Nick Johnson """ cuml = [] items = [] total_weight = 0.0 for weight, item in l: total_weight += weight cuml.append(total_weight) items.append(item) return [items[bisect.bisect(cuml, random.random()*total_weight)] for _ in range(n)]
def flattened_nested_key_indices ( nested_dict ) : outer_keys , inner_keys = collect_nested_keys ( nested_dict ) combined_keys = list ( sorted ( set ( outer_keys + inner_keys ) ) ) return { k : i for ( i , k ) in enumerate ( combined_keys ) }
0
generating key in a nested dictionary in python 3
Combine the outer and inner keys of nested dictionaries into a single ordering .
cosqa-train-15445
def flattened_nested_key_indices(nested_dict): """ Combine the outer and inner keys of nested dictionaries into a single ordering. """ outer_keys, inner_keys = collect_nested_keys(nested_dict) combined_keys = list(sorted(set(outer_keys + inner_keys))) return {k: i for (i, k) in enumerate(combined_keys)}
def move_to_start ( self , column_label ) : self . _columns . move_to_end ( column_label , last = False ) return self
0
python how to move a column to the end
Move a column to the first in order .
cosqa-train-15446
def move_to_start(self, column_label): """Move a column to the first in order.""" self._columns.move_to_end(column_label, last=False) return self
def list_apis ( awsclient ) : client_api = awsclient . get_client ( 'apigateway' ) apis = client_api . get_rest_apis ( ) [ 'items' ] for api in apis : print ( json2table ( api ) )
0
get a list of all aws workspaces python
List APIs in account .
cosqa-train-15447
def list_apis(awsclient): """List APIs in account.""" client_api = awsclient.get_client('apigateway') apis = client_api.get_rest_apis()['items'] for api in apis: print(json2table(api))
def normalize_array ( lst ) : np_arr = np . array ( lst ) x_normalized = np_arr / np_arr . max ( axis = 0 ) return list ( x_normalized )
0
python how to normalize array
Normalizes list
cosqa-train-15448
def normalize_array(lst): """Normalizes list :param lst: Array of floats :return: Normalized (in [0, 1]) input array """ np_arr = np.array(lst) x_normalized = np_arr / np_arr.max(axis=0) return list(x_normalized)
def files_changed ( ) : with chdir ( get_root ( ) ) : result = run_command ( 'git diff --name-only master...' , capture = 'out' ) changed_files = result . stdout . splitlines ( ) # Remove empty lines return [ f for f in changed_files if f ]
0
get a list of all files changed by git in python
Return the list of file changed in the current branch compared to master
cosqa-train-15449
def files_changed(): """ Return the list of file changed in the current branch compared to `master` """ with chdir(get_root()): result = run_command('git diff --name-only master...', capture='out') changed_files = result.stdout.splitlines() # Remove empty lines return [f for f in changed_files if f]
def prettyprint ( d ) : print ( json . dumps ( d , sort_keys = True , indent = 4 , separators = ( "," , ": " ) ) )
0
python how to print dict as json
Print dicttree in Json - like format . keys are sorted
cosqa-train-15450
def prettyprint(d): """Print dicttree in Json-like format. keys are sorted """ print(json.dumps(d, sort_keys=True, indent=4, separators=("," , ": ")))
def from_string ( cls , s ) : for num , text in cls . _STATUS2STR . items ( ) : if text == s : return cls ( num ) else : raise ValueError ( "Wrong string %s" % s )
1
get a state from a string python
Return a Status instance from its string representation .
cosqa-train-15451
def from_string(cls, s): """Return a `Status` instance from its string representation.""" for num, text in cls._STATUS2STR.items(): if text == s: return cls(num) else: raise ValueError("Wrong string %s" % s)
def _get_name ( column_like ) : if isinstance ( column_like , Column ) : return column_like . name elif isinstance ( column_like , Cast ) : return column_like . clause . name
0
python how to reference colummn name
Get the name from a column - like SQLAlchemy expression .
cosqa-train-15452
def _get_name(column_like): """ Get the name from a column-like SQLAlchemy expression. Works for Columns and Cast expressions. """ if isinstance(column_like, Column): return column_like.name elif isinstance(column_like, Cast): return column_like.clause.name
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
get all table names in python
Return a list of the table names in the database .
cosqa-train-15453
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 _reload ( self , force = False ) : self . _config_map = dict ( ) self . _registered_env_keys = set ( ) self . __reload_sources ( force ) self . __load_environment_keys ( ) self . verify ( ) self . _clear_memoization ( )
0
python how to reload automatic
Reloads the configuration from the file and environment variables . Useful if using os . environ instead of this class set_env method or if the underlying configuration file is changed externally .
cosqa-train-15454
def _reload(self, force=False): """Reloads the configuration from the file and environment variables. Useful if using `os.environ` instead of this class' `set_env` method, or if the underlying configuration file is changed externally. """ self._config_map = dict() self._registered_env_keys = set() self.__reload_sources(force) self.__load_environment_keys() self.verify() self._clear_memoization()
def commits_with_message ( message ) : output = log ( "--grep '%s'" % message , oneline = True , quiet = True ) lines = output . splitlines ( ) return [ l . split ( ' ' , 1 ) [ 0 ] for l in lines ]
1
get commits by branch python
All commits with that message ( in current branch )
cosqa-train-15455
def commits_with_message(message): """All commits with that message (in current branch)""" output = log("--grep '%s'" % message, oneline=True, quiet=True) lines = output.splitlines() return [l.split(' ', 1)[0] for l in lines]
def replaceNewlines ( string , newlineChar ) : if newlineChar in string : segments = string . split ( newlineChar ) string = "" for segment in segments : string += segment return string
1
python how to replace line breaks in string
There s probably a way to do this with string functions but I was lazy . Replace all instances of \ r or \ n in a string with something else .
cosqa-train-15456
def replaceNewlines(string, newlineChar): """There's probably a way to do this with string functions but I was lazy. Replace all instances of \r or \n in a string with something else.""" if newlineChar in string: segments = string.split(newlineChar) string = "" for segment in segments: string += segment return string
def get_grid_spatial_dimensions ( self , variable ) : data = self . open_dataset ( self . service ) . variables [ variable . variable ] dimensions = list ( data . dimensions ) return data . shape [ dimensions . index ( variable . x_dimension ) ] , data . shape [ dimensions . index ( variable . y_dimension ) ]
0
get dimensions of python variable
Returns ( width height ) for the given variable
cosqa-train-15457
def get_grid_spatial_dimensions(self, variable): """Returns (width, height) for the given variable""" data = self.open_dataset(self.service).variables[variable.variable] dimensions = list(data.dimensions) return data.shape[dimensions.index(variable.x_dimension)], data.shape[dimensions.index(variable.y_dimension)]
def test ( ) : import unittest tests = unittest . TestLoader ( ) . discover ( 'tests' ) unittest . TextTestRunner ( verbosity = 2 ) . run ( tests )
0
python how to run unittest
Run the unit tests .
cosqa-train-15458
def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests)
def distinct ( xs ) : # don't use collections.OrderedDict because we do support Python 2.6 seen = set ( ) return [ x for x in xs if x not in seen and not seen . add ( x ) ]
0
get distinct list in python
Get the list of distinct values with preserving order .
cosqa-train-15459
def distinct(xs): """Get the list of distinct values with preserving order.""" # don't use collections.OrderedDict because we do support Python 2.6 seen = set() return [x for x in xs if x not in seen and not seen.add(x)]
def autozoom ( self , n = None ) : if n == None : for p in self . plot_widgets : p . autoRange ( ) else : self . plot_widgets [ n ] . autoRange ( ) return self
1
python how to scale a plot to a specific range
Auto - scales the axes to fit all the data in plot index n . If n == None auto - scale everyone .
cosqa-train-15460
def autozoom(self, n=None): """ Auto-scales the axes to fit all the data in plot index n. If n == None, auto-scale everyone. """ if n==None: for p in self.plot_widgets: p.autoRange() else: self.plot_widgets[n].autoRange() return self
def horz_dpi ( self ) : pHYs = self . _chunks . pHYs if pHYs is None : return 72 return self . _dpi ( pHYs . units_specifier , pHYs . horz_px_per_unit )
0
get dpi of image in python
Integer dots per inch for the width of this image . Defaults to 72 when not present in the file as is often the case .
cosqa-train-15461
def horz_dpi(self): """ Integer dots per inch for the width of this image. Defaults to 72 when not present in the file, as is often the case. """ pHYs = self._chunks.pHYs if pHYs is None: return 72 return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit)
def _selectItem ( self , index ) : self . _selectedIndex = index self . setCurrentIndex ( self . model ( ) . createIndex ( index , 0 ) )
1
python how to select a list index object
Select item in the list
cosqa-train-15462
def _selectItem(self, index): """Select item in the list """ self._selectedIndex = index self.setCurrentIndex(self.model().createIndex(index, 0))
def get_abi3_suffix ( ) : for suffix , _ , _ in ( s for s in imp . get_suffixes ( ) if s [ 2 ] == imp . C_EXTENSION ) : if '.abi3' in suffix : # Unix return suffix elif suffix == '.pyd' : # Windows return suffix
0
get file extension python
Return the file extension for an abi3 - compliant Extension ()
cosqa-train-15463
def get_abi3_suffix(): """Return the file extension for an abi3-compliant Extension()""" for suffix, _, _ in (s for s in imp.get_suffixes() if s[2] == imp.C_EXTENSION): if '.abi3' in suffix: # Unix return suffix elif suffix == '.pyd': # Windows return suffix
def print_env_info ( key , out = sys . stderr ) : value = os . getenv ( key ) if value is not None : print ( key , "=" , repr ( value ) , file = out )
1
python how to show environment variables
If given environment key is defined print it out .
cosqa-train-15464
def print_env_info(key, out=sys.stderr): """If given environment key is defined, print it out.""" value = os.getenv(key) if value is not None: print(key, "=", repr(value), file=out)
def get_file_size ( fileobj ) : currpos = fileobj . tell ( ) fileobj . seek ( 0 , 2 ) total_size = fileobj . tell ( ) fileobj . seek ( currpos ) return total_size
1
get file size after opening python
Returns the size of a file - like object .
cosqa-train-15465
def get_file_size(fileobj): """ Returns the size of a file-like object. """ currpos = fileobj.tell() fileobj.seek(0, 2) total_size = fileobj.tell() fileobj.seek(currpos) return total_size
def Sum ( a , axis , keep_dims ) : return np . sum ( a , axis = axis if not isinstance ( axis , np . ndarray ) else tuple ( axis ) , keepdims = keep_dims ) ,
0
python how to sum across an axis
Sum reduction op .
cosqa-train-15466
def Sum(a, axis, keep_dims): """ Sum reduction op. """ return np.sum(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis), keepdims=keep_dims),
def get_winfunc ( libname , funcname , restype = None , argtypes = ( ) , _libcache = { } ) : if libname not in _libcache : _libcache [ libname ] = windll . LoadLibrary ( libname ) func = getattr ( _libcache [ libname ] , funcname ) func . argtypes = argtypes func . restype = restype return func
0
get function from dll python ctypes
Retrieve a function from a library / DLL and set the data types .
cosqa-train-15467
def get_winfunc(libname, funcname, restype=None, argtypes=(), _libcache={}): """Retrieve a function from a library/DLL, and set the data types.""" if libname not in _libcache: _libcache[libname] = windll.LoadLibrary(libname) func = getattr(_libcache[libname], funcname) func.argtypes = argtypes func.restype = restype return func
def contains_empty ( features ) : if not features : return True for feature in features : if feature . shape [ 0 ] == 0 : return True return False
1
python how to tell if array empty
Check features data are not empty
cosqa-train-15468
def contains_empty(features): """Check features data are not empty :param features: The features data to check. :type features: list of numpy arrays. :return: True if one of the array is empty, False else. """ if not features: return True for feature in features: if feature.shape[0] == 0: return True return False
def _get_gid ( name ) : if getgrnam is None or name is None : return None try : result = getgrnam ( name ) except KeyError : result = None if result is not None : return result [ 2 ] return None
0
get group name based off gid python
Returns a gid given a group name .
cosqa-train-15469
def _get_gid(name): """Returns a gid, given a group name.""" if getgrnam is None or name is None: return None try: result = getgrnam(name) except KeyError: result = None if result is not None: return result[2] return None
def terminate ( self ) : # Tear down the Pailgun TCPServer. if self . pailgun : self . pailgun . server_close ( ) super ( PailgunService , self ) . terminate ( )
1
python how to terminate a thrad
Override of PantsService . terminate () that cleans up when the Pailgun server is terminated .
cosqa-train-15470
def terminate(self): """Override of PantsService.terminate() that cleans up when the Pailgun server is terminated.""" # Tear down the Pailgun TCPServer. if self.pailgun: self.pailgun.server_close() super(PailgunService, self).terminate()
def retrieve_by_id ( self , id_ ) : items_with_id = [ item for item in self if item . id == int ( id_ ) ] if len ( items_with_id ) == 1 : return items_with_id [ 0 ] . retrieve ( )
0
get html elements by id python requests
Return a JSSObject for the element with ID id_
cosqa-train-15471
def retrieve_by_id(self, id_): """Return a JSSObject for the element with ID id_""" items_with_id = [item for item in self if item.id == int(id_)] if len(items_with_id) == 1: return items_with_id[0].retrieve()
def is_same_dict ( d1 , d2 ) : for k , v in d1 . items ( ) : if isinstance ( v , dict ) : is_same_dict ( v , d2 [ k ] ) else : assert d1 [ k ] == d2 [ k ] for k , v in d2 . items ( ) : if isinstance ( v , dict ) : is_same_dict ( v , d1 [ k ] ) else : assert d1 [ k ] == d2 [ k ]
1
python how to test two dictionary identical
Test two dictionary is equal on values . ( ignore order )
cosqa-train-15472
def is_same_dict(d1, d2): """Test two dictionary is equal on values. (ignore order) """ for k, v in d1.items(): if isinstance(v, dict): is_same_dict(v, d2[k]) else: assert d1[k] == d2[k] for k, v in d2.items(): if isinstance(v, dict): is_same_dict(v, d1[k]) else: assert d1[k] == d2[k]
def series_index ( self , series ) : for idx , s in enumerate ( self ) : if series is s : return idx raise ValueError ( 'series not in chart data object' )
0
get index in series python
Return the integer index of * series * in this sequence .
cosqa-train-15473
def series_index(self, series): """ Return the integer index of *series* in this sequence. """ for idx, s in enumerate(self): if series is s: return idx raise ValueError('series not in chart data object')
def object_as_dict ( obj ) : return { c . key : getattr ( obj , c . key ) for c in inspect ( obj ) . mapper . column_attrs }
0
python how to view all attributes of an object
Turn an SQLAlchemy model into a dict of field names and values .
cosqa-train-15474
def object_as_dict(obj): """Turn an SQLAlchemy model into a dict of field names and values. Based on https://stackoverflow.com/a/37350445/1579058 """ return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs}
def _find_first_of ( line , substrings ) : starts = ( ( line . find ( i ) , i ) for i in substrings ) found = [ ( i , sub ) for i , sub in starts if i != - 1 ] if found : return min ( found ) else : return - 1 , None
1
get index of line containing substring python
Find earliest occurrence of one of substrings in line .
cosqa-train-15475
def _find_first_of(line, substrings): """Find earliest occurrence of one of substrings in line. Returns pair of index and found substring, or (-1, None) if no occurrences of any of substrings were found in line. """ starts = ((line.find(i), i) for i in substrings) found = [(i, sub) for i, sub in starts if i != -1] if found: return min(found) else: return -1, None
def retrieve_by_id ( self , id_ ) : items_with_id = [ item for item in self if item . id == int ( id_ ) ] if len ( items_with_id ) == 1 : return items_with_id [ 0 ] . retrieve ( )
0
python html get by id
Return a JSSObject for the element with ID id_
cosqa-train-15476
def retrieve_by_id(self, id_): """Return a JSSObject for the element with ID id_""" items_with_id = [item for item in self if item.id == int(id_)] if len(items_with_id) == 1: return items_with_id[0].retrieve()
def get_substring_idxs ( substr , string ) : return [ match . start ( ) for match in re . finditer ( substr , string ) ]
0
get indices of all substring in string python
Return a list of indexes of substr . If substr not found list is empty .
cosqa-train-15477
def get_substring_idxs(substr, string): """ Return a list of indexes of substr. If substr not found, list is empty. Arguments: substr (str): Substring to match. string (str): String to match in. Returns: list of int: Start indices of substr. """ return [match.start() for match in re.finditer(substr, string)]
def _get_url ( url ) : try : data = HTTP_SESSION . get ( url , stream = True ) data . raise_for_status ( ) except requests . exceptions . RequestException as exc : raise FetcherException ( exc ) return data
0
python http get without redirect
Retrieve requested URL
cosqa-train-15478
def _get_url(url): """Retrieve requested URL""" try: data = HTTP_SESSION.get(url, stream=True) data.raise_for_status() except requests.exceptions.RequestException as exc: raise FetcherException(exc) return data
def get_last_id ( self , cur , table = 'reaction' ) : cur . execute ( "SELECT seq FROM sqlite_sequence WHERE name='{0}'" . format ( table ) ) result = cur . fetchone ( ) if result is not None : id = result [ 0 ] else : id = 0 return id
0
get last insert id mysql python
Get the id of the last written row in table
cosqa-train-15479
def get_last_id(self, cur, table='reaction'): """ Get the id of the last written row in table Parameters ---------- cur: database connection().cursor() object table: str 'reaction', 'publication', 'publication_system', 'reaction_system' Returns: id """ cur.execute("SELECT seq FROM sqlite_sequence WHERE name='{0}'" .format(table)) result = cur.fetchone() if result is not None: id = result[0] else: id = 0 return id
def unapostrophe ( text ) : text = re . sub ( r'[%s]s?$' % '' . join ( APOSTROPHES ) , '' , text ) return text
0
python hyphen and apostrophe in string
Strip apostrophe and s from the end of a string .
cosqa-train-15480
def unapostrophe(text): """Strip apostrophe and 's' from the end of a string.""" text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text) return text
def tail ( self , n = 10 ) : with cython_context ( ) : return SArray ( _proxy = self . __proxy__ . tail ( n ) )
0
get last n row in python
Get an SArray that contains the last n elements in the SArray .
cosqa-train-15481
def tail(self, n=10): """ Get an SArray that contains the last n elements in the SArray. Parameters ---------- n : int The number of elements to fetch Returns ------- out : SArray A new SArray which contains the last n rows of the current SArray. """ with cython_context(): return SArray(_proxy=self.__proxy__.tail(n))
def open_as_pillow ( filename ) : with __sys_open ( filename , 'rb' ) as f : data = BytesIO ( f . read ( ) ) return Image . open ( data )
0
python i opened a file for writing but erased it
This way can delete file immediately
cosqa-train-15482
def open_as_pillow(filename): """ This way can delete file immediately """ with __sys_open(filename, 'rb') as f: data = BytesIO(f.read()) return Image.open(data)
def get_methods ( * objs ) : return set ( attr for obj in objs for attr in dir ( obj ) if not attr . startswith ( '_' ) and callable ( getattr ( obj , attr ) ) )
0
get methods present in object python
Return the names of all callable attributes of an object
cosqa-train-15483
def get_methods(*objs): """ Return the names of all callable attributes of an object""" return set( attr for obj in objs for attr in dir(obj) if not attr.startswith('_') and callable(getattr(obj, attr)) )
async def i2c_write_request ( self , command ) : device_address = int ( command [ 0 ] ) params = command [ 1 ] params = [ int ( i ) for i in params ] await self . core . i2c_write_request ( device_address , params )
1
python i2c send 2 bytes
This method performs an I2C write at a given I2C address : param command : { method : i2c_write_request params : [ I2C_DEVICE_ADDRESS [ DATA_TO_WRITE ]] } : returns : No return message .
cosqa-train-15484
async def i2c_write_request(self, command): """ This method performs an I2C write at a given I2C address, :param command: {"method": "i2c_write_request", "params": [I2C_DEVICE_ADDRESS, [DATA_TO_WRITE]]} :returns:No return message. """ device_address = int(command[0]) params = command[1] params = [int(i) for i in params] await self.core.i2c_write_request(device_address, params)
def object_as_dict ( obj ) : return { c . key : getattr ( obj , c . key ) for c in inspect ( obj ) . mapper . column_attrs }
1
get object fields in a dict in python
Turn an SQLAlchemy model into a dict of field names and values .
cosqa-train-15485
def object_as_dict(obj): """Turn an SQLAlchemy model into a dict of field names and values. Based on https://stackoverflow.com/a/37350445/1579058 """ return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs}
def has_field ( mc , field_name ) : try : mc . _meta . get_field ( field_name ) except FieldDoesNotExist : return False return True
0
python if a field exist
detect if a model has a given field has
cosqa-train-15486
def has_field(mc, field_name): """ detect if a model has a given field has :param field_name: :param mc: :return: """ try: mc._meta.get_field(field_name) except FieldDoesNotExist: return False return True
def call_out ( command ) : # start external command process p = subprocess . Popen ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) # get outputs out , _ = p . communicate ( ) return p . returncode , out . strip ( )
0
get output of stdout subprocess python
Run the given command ( with shell = False ) and return a tuple of ( int returncode str output ) . Strip the output of enclosing whitespace .
cosqa-train-15487
def call_out(command): """ Run the given command (with shell=False) and return a tuple of (int returncode, str output). Strip the output of enclosing whitespace. """ # start external command process p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # get outputs out, _ = p.communicate() return p.returncode, out.strip()
def _check_conversion ( key , valid_dict ) : if key not in valid_dict and key not in valid_dict . values ( ) : # Only show users the nice string values keys = [ v for v in valid_dict . keys ( ) if isinstance ( v , string_types ) ] raise ValueError ( 'value must be one of %s, not %s' % ( keys , key ) ) return valid_dict [ key ] if key in valid_dict else key
0
python if is not a dict key
Check for existence of key in dict return value or raise error
cosqa-train-15488
def _check_conversion(key, valid_dict): """Check for existence of key in dict, return value or raise error""" if key not in valid_dict and key not in valid_dict.values(): # Only show users the nice string values keys = [v for v in valid_dict.keys() if isinstance(v, string_types)] raise ValueError('value must be one of %s, not %s' % (keys, key)) return valid_dict[key] if key in valid_dict else key
def GetPythonLibraryDirectoryPath ( ) : path = sysconfig . get_python_lib ( True ) _ , _ , path = path . rpartition ( sysconfig . PREFIX ) if path . startswith ( os . sep ) : path = path [ 1 : ] return path
1
get path of libary python
Retrieves the Python library directory path .
cosqa-train-15489
def GetPythonLibraryDirectoryPath(): """Retrieves the Python library directory path.""" path = sysconfig.get_python_lib(True) _, _, path = path.rpartition(sysconfig.PREFIX) if path.startswith(os.sep): path = path[1:] return path
def ismatch ( text , pattern ) : if hasattr ( pattern , 'search' ) : return pattern . search ( text ) is not None else : return pattern in text if Config . options . case_sensitive else pattern . lower ( ) in text . lower ( )
1
python if matches text
Test whether text contains string or matches regex .
cosqa-train-15490
def ismatch(text, pattern): """Test whether text contains string or matches regex.""" if hasattr(pattern, 'search'): return pattern.search(text) is not None else: return pattern in text if Config.options.case_sensitive \ else pattern.lower() in text.lower()
def get_pid_list ( ) : pids = [ int ( x ) for x in os . listdir ( '/proc' ) if x . isdigit ( ) ] return pids
0
get process list using python linux
Returns a list of PIDs currently running on the system .
cosqa-train-15491
def get_pid_list(): """Returns a list of PIDs currently running on the system.""" pids = [int(x) for x in os.listdir('/proc') if x.isdigit()] return pids
def file_found ( filename , force ) : if os . path . exists ( filename ) and not force : logger . info ( "Found %s; skipping..." % filename ) return True else : return False
0
python if no file is found
Check if a file exists
cosqa-train-15492
def file_found(filename,force): """Check if a file exists""" if os.path.exists(filename) and not force: logger.info("Found %s; skipping..."%filename) return True else: return False
def static_get_type_attr ( t , name ) : for type_ in t . mro ( ) : try : return vars ( type_ ) [ name ] except KeyError : pass raise AttributeError ( name )
1
get proto type name python
Get a type attribute statically circumventing the descriptor protocol .
cosqa-train-15493
def static_get_type_attr(t, name): """ Get a type attribute statically, circumventing the descriptor protocol. """ for type_ in t.mro(): try: return vars(type_)[name] except KeyError: pass raise AttributeError(name)
def starts_with_prefix_in_list ( text , prefixes ) : for prefix in prefixes : if text . startswith ( prefix ) : return True return False
0
python if string has prefix
Return True if the given string starts with one of the prefixes in the given list otherwise return False .
cosqa-train-15494
def starts_with_prefix_in_list(text, prefixes): """ Return True if the given string starts with one of the prefixes in the given list, otherwise return False. Arguments: text (str): Text to check for prefixes. prefixes (list): List of prefixes to check for. Returns: bool: True if the given text starts with any of the given prefixes, otherwise False. """ for prefix in prefixes: if text.startswith(prefix): return True return False
def GetPythonLibraryDirectoryPath ( ) : path = sysconfig . get_python_lib ( True ) _ , _ , path = path . rpartition ( sysconfig . PREFIX ) if path . startswith ( os . sep ) : path = path [ 1 : ] return path
1
get python config dir
Retrieves the Python library directory path .
cosqa-train-15495
def GetPythonLibraryDirectoryPath(): """Retrieves the Python library directory path.""" path = sysconfig.get_python_lib(True) _, _, path = path.rpartition(sysconfig.PREFIX) if path.startswith(os.sep): path = path[1:] return path
def from_string ( cls , string ) : # find enum value for attr in dir ( cls ) : value = getattr ( cls , attr ) if value == string : return value # if not found, log warning and return the value passed in logger . warning ( "{} is not a valid enum value for {}." . format ( string , cls . __name__ ) ) return string
0
python if string in enum
Simply logs a warning if the desired enum value is not found .
cosqa-train-15496
def from_string(cls, string): """ Simply logs a warning if the desired enum value is not found. :param string: :return: """ # find enum value for attr in dir(cls): value = getattr(cls, attr) if value == string: return value # if not found, log warning and return the value passed in logger.warning("{} is not a valid enum value for {}.".format(string, cls.__name__)) return string
def rm_empty_indices ( * args ) : rm_inds = args [ 0 ] if not rm_inds : return args [ 1 : ] keep_inds = [ i for i in range ( len ( args [ 1 ] ) ) if i not in rm_inds ] return [ [ a [ i ] for i in keep_inds ] for a in args [ 1 : ] ]
1
get rid of indices in python list
Remove unwanted list indices . First argument is the list of indices to remove . Other elements are the lists to trim .
cosqa-train-15497
def rm_empty_indices(*args): """ Remove unwanted list indices. First argument is the list of indices to remove. Other elements are the lists to trim. """ rm_inds = args[0] if not rm_inds: return args[1:] keep_inds = [i for i in range(len(args[1])) if i not in rm_inds] return [[a[i] for i in keep_inds] for a in args[1:]]
def _to_numeric ( val ) : if isinstance ( val , ( int , float , datetime . datetime , datetime . timedelta ) ) : return val return float ( val )
0
python if value is string or number
Helper function for conversion of various data types into numeric representation .
cosqa-train-15498
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 readwav ( filename ) : from scipy . io . wavfile import read as readwav samplerate , signal = readwav ( filename ) return signal , samplerate
0
get samplerate from wav file in python
Read a WAV file and returns the data and sample rate
cosqa-train-15499
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