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 accuracy ( self ) : sub_observed = np . array ( [ self . observed . metadata [ i ] for i in self . observed . arr ] ) return float ( ( self . model_predictions ( ) == sub_observed ) . sum ( ) ) / self . data_size
| 0 |
decision tree for the data with all the categorical data in python
|
Calculates the accuracy of the tree by comparing the model predictions to the dataset ( TP + TN ) / ( TP + TN + FP + FN ) == ( T / ( T + F ))
|
cosqa-train-400
|
def accuracy(self):
"""
Calculates the accuracy of the tree by comparing
the model predictions to the dataset
(TP + TN) / (TP + TN + FP + FN) == (T / (T + F))
"""
sub_observed = np.array([self.observed.metadata[i] for i in self.observed.arr])
return float((self.model_predictions() == sub_observed).sum()) / self.data_size
|
def cli ( yamlfile , format , context ) : print ( JSONLDGenerator ( yamlfile , format ) . serialize ( context = context ) )
| 0 |
python generate code from json schema definition
|
Generate JSONLD file from biolink schema
|
cosqa-train-401
|
def cli(yamlfile, format, context):
""" Generate JSONLD file from biolink schema """
print(JSONLDGenerator(yamlfile, format).serialize(context=context))
|
def double_sha256 ( data ) : return bytes_as_revhex ( hashlib . sha256 ( hashlib . sha256 ( data ) . digest ( ) ) . digest ( ) )
| 0 |
declaring a hash in python
|
A standard compound hash .
|
cosqa-train-402
|
def double_sha256(data):
"""A standard compound hash."""
return bytes_as_revhex(hashlib.sha256(hashlib.sha256(data).digest()).digest())
|
def get_cantons ( self ) : return sorted ( list ( set ( [ location . canton for location in self . get_locations ( ) . values ( ) ] ) ) )
| 0 |
python generate list of cononants
|
Return the list of unique cantons sorted by name .
|
cosqa-train-403
|
def get_cantons(self):
"""
Return the list of unique cantons, sorted by name.
"""
return sorted(list(set([
location.canton for location in self.get_locations().values()
])))
|
def get_default_args ( func ) : args , varargs , keywords , defaults = getargspec_no_self ( func ) return dict ( zip ( args [ - len ( defaults ) : ] , defaults ) )
| 0 |
default function arg in python
|
returns a dictionary of arg_name : default_values for the input function
|
cosqa-train-404
|
def get_default_args(func):
"""
returns a dictionary of arg_name:default_values for the input function
"""
args, varargs, keywords, defaults = getargspec_no_self(func)
return dict(zip(args[-len(defaults):], defaults))
|
def get_method_name ( method ) : name = get_object_name ( method ) if name . startswith ( "__" ) and not name . endswith ( "__" ) : name = "_{0}{1}" . format ( get_object_name ( method . im_class ) , name ) return name
| 0 |
python generate method name
|
Returns given method name .
|
cosqa-train-405
|
def get_method_name(method):
"""
Returns given method name.
:param method: Method to retrieve the name.
:type method: object
:return: Method name.
:rtype: unicode
"""
name = get_object_name(method)
if name.startswith("__") and not name.endswith("__"):
name = "_{0}{1}".format(get_object_name(method.im_class), name)
return name
|
def _add_default_arguments ( parser ) : parser . add_argument ( '-c' , '--config' , action = 'store' , dest = 'config' , help = 'Path to the configuration file' ) parser . add_argument ( '-f' , '--foreground' , action = 'store_true' , dest = 'foreground' , help = 'Run the application interactively' )
| 0 |
default value in argparse python
|
Add the default arguments to the parser .
|
cosqa-train-406
|
def _add_default_arguments(parser):
"""Add the default arguments to the parser.
:param argparse.ArgumentParser parser: The argument parser
"""
parser.add_argument('-c', '--config', action='store', dest='config',
help='Path to the configuration file')
parser.add_argument('-f', '--foreground', action='store_true', dest='foreground',
help='Run the application interactively')
|
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 |
python get all callables from an object
|
Return the names of all callable attributes of an object
|
cosqa-train-407
|
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))
)
|
def add_blank_row ( self , label ) : col_labels = self . df . columns blank_item = pd . Series ( { } , index = col_labels , name = label ) # use .loc to add in place (append won't do that) self . df . loc [ blank_item . name ] = blank_item return self . df
| 1 |
define an empty column in a data frame in python
|
Add a blank row with only an index value to self . df . This is done inplace .
|
cosqa-train-408
|
def add_blank_row(self, label):
"""
Add a blank row with only an index value to self.df.
This is done inplace.
"""
col_labels = self.df.columns
blank_item = pd.Series({}, index=col_labels, name=label)
# use .loc to add in place (append won't do that)
self.df.loc[blank_item.name] = blank_item
return self.df
|
def items ( self , section_name ) : return [ ( k , v ) for k , v in super ( GitConfigParser , self ) . items ( section_name ) if k != '__name__' ]
| 0 |
python get all keys in a section configparser
|
: return : list (( option value ) ... ) pairs of all items in the given section
|
cosqa-train-409
|
def items(self, section_name):
""":return: list((option, value), ...) pairs of all items in the given section"""
return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']
|
def computeDelaunayTriangulation ( points ) : siteList = SiteList ( points ) context = Context ( ) context . triangulate = True voronoi ( siteList , context ) return context . triangles
| 0 |
delaunay triangulation polygon python
|
Takes a list of point objects ( which must have x and y fields ) . Returns a list of 3 - tuples : the indices of the points that form a Delaunay triangle .
|
cosqa-train-410
|
def computeDelaunayTriangulation(points):
""" Takes a list of point objects (which must have x and y fields).
Returns a list of 3-tuples: the indices of the points that form a
Delaunay triangle.
"""
siteList = SiteList(points)
context = Context()
context.triangulate = True
voronoi(siteList,context)
return context.triangles
|
def get_keys_from_class ( cc ) : return [ prop . name for prop in cc . properties . values ( ) if 'key' in prop . qualifiers ]
| 0 |
python get all keys in object
|
Return list of the key property names for a class
|
cosqa-train-411
|
def get_keys_from_class(cc):
"""Return list of the key property names for a class """
return [prop.name for prop in cc.properties.values() \
if 'key' in prop.qualifiers]
|
def rm ( venv_name ) : inenv = InenvManager ( ) venv = inenv . get_venv ( venv_name ) click . confirm ( "Delete dir {}" . format ( venv . path ) ) shutil . rmtree ( venv . path )
| 0 |
delete a python virtual env
|
Removes the venv by name
|
cosqa-train-412
|
def rm(venv_name):
""" Removes the venv by name """
inenv = InenvManager()
venv = inenv.get_venv(venv_name)
click.confirm("Delete dir {}".format(venv.path))
shutil.rmtree(venv.path)
|
def columns ( self ) : res = [ col [ 'name' ] for col in self . column_definitions ] res . extend ( [ col [ 'name' ] for col in self . foreign_key_definitions ] ) return res
| 0 |
python get all the function names in this model
|
Return names of all the addressable columns ( including foreign keys ) referenced in user supplied model
|
cosqa-train-413
|
def columns(self):
"""Return names of all the addressable columns (including foreign keys) referenced in user supplied model"""
res = [col['name'] for col in self.column_definitions]
res.extend([col['name'] for col in self.foreign_key_definitions])
return res
|
def remove_non_magic_cols ( self ) : for table_name in self . tables : table = self . tables [ table_name ] table . remove_non_magic_cols_from_table ( )
| 0 |
delete all columns except one in python
|
Remove all non - MagIC columns from all tables .
|
cosqa-train-414
|
def remove_non_magic_cols(self):
"""
Remove all non-MagIC columns from all tables.
"""
for table_name in self.tables:
table = self.tables[table_name]
table.remove_non_magic_cols_from_table()
|
def get_obj ( ref ) : oid = int ( ref ) return server . id2ref . get ( oid ) or server . id2obj [ oid ]
| 0 |
python get an objects id
|
Get object from string reference .
|
cosqa-train-415
|
def get_obj(ref):
"""Get object from string reference."""
oid = int(ref)
return server.id2ref.get(oid) or server.id2obj[oid]
|
def _split_comma_separated ( string ) : return set ( text . strip ( ) for text in string . split ( ',' ) if text . strip ( ) )
| 1 |
delete commas from a string python
|
Return a set of strings .
|
cosqa-train-416
|
def _split_comma_separated(string):
"""Return a set of strings."""
return set(text.strip() for text in string.split(',') if text.strip())
|
def angle ( x0 , y0 , x1 , y1 ) : return degrees ( atan2 ( y1 - y0 , x1 - x0 ) )
| 0 |
python get angle from x, y
|
Returns the angle between two points .
|
cosqa-train-417
|
def angle(x0, y0, x1, y1):
""" Returns the angle between two points.
"""
return degrees(atan2(y1-y0, x1-x0))
|
def delete_duplicates ( seq ) : seen = set ( ) seen_add = seen . add return [ x for x in seq if not ( x in seen or seen_add ( x ) ) ]
| 0 |
delete duplicates in an array python
|
Remove duplicates from an iterable preserving the order .
|
cosqa-train-418
|
def delete_duplicates(seq):
"""
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
def guess_extension ( amimetype , normalize = False ) : ext = _mimes . guess_extension ( amimetype ) if ext and normalize : # Normalize some common magic mis-interpreation ext = { '.asc' : '.txt' , '.obj' : '.bin' } . get ( ext , ext ) from invenio . legacy . bibdocfile . api_normalizer import normalize_format return normalize_format ( ext ) return ext
| 0 |
python get appropriate extension for file
|
Tries to guess extension for a mimetype .
|
cosqa-train-419
|
def guess_extension(amimetype, normalize=False):
"""
Tries to guess extension for a mimetype.
@param amimetype: name of a mimetype
@time amimetype: string
@return: the extension
@rtype: string
"""
ext = _mimes.guess_extension(amimetype)
if ext and normalize:
# Normalize some common magic mis-interpreation
ext = {'.asc': '.txt', '.obj': '.bin'}.get(ext, ext)
from invenio.legacy.bibdocfile.api_normalizer import normalize_format
return normalize_format(ext)
return ext
|
def reset ( ) : shutil . rmtree ( session [ 'img_input_dir' ] ) shutil . rmtree ( session [ 'img_output_dir' ] ) session . clear ( ) return jsonify ( ok = 'true' )
| 0 |
delete flask data in python
|
Delete the session and clear temporary directories
|
cosqa-train-420
|
def reset():
"""Delete the session and clear temporary directories
"""
shutil.rmtree(session['img_input_dir'])
shutil.rmtree(session['img_output_dir'])
session.clear()
return jsonify(ok='true')
|
def detokenize ( s ) : print ( s ) s = re . sub ( "\s+([;:,\.\?!])" , "\\1" , s ) s = re . sub ( "\s+(n't)" , "\\1" , s ) return s
| 1 |
delete spaces and non number terms from a string python
|
Detokenize a string by removing spaces before punctuation .
|
cosqa-train-421
|
def detokenize(s):
""" Detokenize a string by removing spaces before punctuation."""
print(s)
s = re.sub("\s+([;:,\.\?!])", "\\1", s)
s = re.sub("\s+(n't)", "\\1", s)
return s
|
def get_colors ( img ) : w , h = img . size return [ color [ : 3 ] for count , color in img . convert ( 'RGB' ) . getcolors ( w * h ) ]
| 0 |
python get colors in image
|
Returns a list of all the image s colors .
|
cosqa-train-422
|
def get_colors(img):
"""
Returns a list of all the image's colors.
"""
w, h = img.size
return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)]
|
def memory ( ) : mem_info = dict ( ) for k , v in psutil . virtual_memory ( ) . _asdict ( ) . items ( ) : mem_info [ k ] = int ( v ) return mem_info
| 0 |
python get current process memory
|
Determine memory specifications of the machine .
|
cosqa-train-423
|
def memory():
"""Determine memory specifications of the machine.
Returns
-------
mem_info : dictonary
Holds the current values for the total, free and used memory of the system.
"""
mem_info = dict()
for k, v in psutil.virtual_memory()._asdict().items():
mem_info[k] = int(v)
return mem_info
|
def check_precomputed_distance_matrix ( X ) : tmp = X . copy ( ) tmp [ np . isinf ( tmp ) ] = 1 check_array ( tmp )
| 0 |
delete zeros in sparse matrix python
|
Perform check_array ( X ) after removing infinite values ( numpy . inf ) from the given distance matrix .
|
cosqa-train-424
|
def check_precomputed_distance_matrix(X):
"""Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.
"""
tmp = X.copy()
tmp[np.isinf(tmp)] = 1
check_array(tmp)
|
def calculate_month ( birth_date ) : year = int ( birth_date . strftime ( '%Y' ) ) month = int ( birth_date . strftime ( '%m' ) ) + ( ( int ( year / 100 ) - 14 ) % 5 ) * 20 return month
| 0 |
python get day number of month
|
Calculates and returns a month number basing on PESEL standard .
|
cosqa-train-425
|
def calculate_month(birth_date):
"""
Calculates and returns a month number basing on PESEL standard.
"""
year = int(birth_date.strftime('%Y'))
month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20
return month
|
def linedelimited ( inlist , delimiter ) : outstr = '' for item in inlist : if type ( item ) != StringType : item = str ( item ) outstr = outstr + item + delimiter outstr = outstr [ 0 : - 1 ] return outstr
| 0 |
delimit list by tabs in python
|
Returns a string composed of elements in inlist with each element separated by delimiter . Used by function writedelimited . Use \ t for tab - delimiting .
|
cosqa-train-426
|
def linedelimited (inlist,delimiter):
"""
Returns a string composed of elements in inlist, with each element
separated by 'delimiter.' Used by function writedelimited. Use '\t'
for tab-delimiting.
Usage: linedelimited (inlist,delimiter)
"""
outstr = ''
for item in inlist:
if type(item) != StringType:
item = str(item)
outstr = outstr + item + delimiter
outstr = outstr[0:-1]
return outstr
|
def get_month_start_end_day ( ) : t = date . today ( ) n = mdays [ t . month ] return ( date ( t . year , t . month , 1 ) , date ( t . year , t . month , n ) )
| 0 |
python get days in month
|
Get the month start date a nd end date
|
cosqa-train-427
|
def get_month_start_end_day():
"""
Get the month start date a nd end date
"""
t = date.today()
n = mdays[t.month]
return (date(t.year, t.month, 1), date(t.year, t.month, n))
|
def dequeue ( self , block = True ) : return self . queue . get ( block , self . queue_get_timeout )
| 0 |
dequeue check for item python
|
Dequeue a record and return item .
|
cosqa-train-428
|
def dequeue(self, block=True):
"""Dequeue a record and return item."""
return self.queue.get(block, self.queue_get_timeout)
|
def return_value ( self , * args , * * kwargs ) : self . _called ( ) return self . _return_value ( * args , * * kwargs )
| 0 |
python get decorated function's value
|
Extracts the real value to be returned from the wrapping callable .
|
cosqa-train-429
|
def return_value(self, *args, **kwargs):
"""Extracts the real value to be returned from the wrapping callable.
:return: The value the double should return when called.
"""
self._called()
return self._return_value(*args, **kwargs)
|
def get_best_encoding ( stream ) : rv = getattr ( stream , 'encoding' , None ) or sys . getdefaultencoding ( ) if is_ascii_encoding ( rv ) : return 'utf-8' return rv
| 0 |
detect char encoding python
|
Returns the default stream encoding if not found .
|
cosqa-train-430
|
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 relpath ( self ) : cwd = self . __class__ ( os . getcwdu ( ) ) return cwd . relpathto ( self )
| 0 |
python get directory of self
|
Return this path as a relative path based from the current working directory .
|
cosqa-train-431
|
def relpath(self):
""" Return this path as a relative path,
based from the current working directory.
"""
cwd = self.__class__(os.getcwdu())
return cwd.relpathto(self)
|
def we_are_in_lyon ( ) : import socket try : hostname = socket . gethostname ( ) ip = socket . gethostbyname ( hostname ) except socket . gaierror : return False return ip . startswith ( "134.158." )
| 0 |
detect is host in in the network python
|
Check if we are on a Lyon machine
|
cosqa-train-432
|
def we_are_in_lyon():
"""Check if we are on a Lyon machine"""
import socket
try:
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
except socket.gaierror:
return False
return ip.startswith("134.158.")
|
def _calculate_distance ( latlon1 , latlon2 ) : lat1 , lon1 = latlon1 lat2 , lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np . sin ( dlat / 2 ) ** 2 + np . cos ( lat1 ) * np . cos ( lat2 ) * ( np . sin ( dlon / 2 ) ) ** 2 c = 2 * np . pi * R * np . arctan2 ( np . sqrt ( a ) , np . sqrt ( 1 - a ) ) / 180 return c
| 0 |
python get distance between two lat lon
|
Calculates the distance between two points on earth .
|
cosqa-train-433
|
def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c
|
def is_callable ( * p ) : import symbols return all ( isinstance ( x , symbols . FUNCTION ) for x in p )
| 0 |
determine if passed variable a function python
|
True if all the args are functions and / or subroutines
|
cosqa-train-434
|
def is_callable(*p):
""" True if all the args are functions and / or subroutines
"""
import symbols
return all(isinstance(x, symbols.FUNCTION) for x in p)
|
def eqstr ( a , b ) : return bool ( libspice . eqstr_c ( stypes . stringToCharP ( a ) , stypes . stringToCharP ( b ) ) )
| 0 |
determine whether two strings are the same python
|
Determine whether two strings are equivalent .
|
cosqa-train-435
|
def eqstr(a, b):
"""
Determine whether two strings are equivalent.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html
:param a: Arbitrary character string.
:type a: str
:param b: Arbitrary character string.
:type b: str
:return: True if A and B are equivalent.
:rtype: bool
"""
return bool(libspice.eqstr_c(stypes.stringToCharP(a), stypes.stringToCharP(b)))
|
def get_by ( self , name ) : return next ( ( item for item in self if item . name == name ) , None )
| 0 |
python get element by name
|
get element by name
|
cosqa-train-436
|
def get_by(self, name):
"""get element by name"""
return next((item for item in self if item.name == name), None)
|
def validate ( self , * args , * * kwargs ) : # pylint: disable=arguments-differ return super ( ParameterValidator , self ) . _validate ( * args , * * kwargs )
| 0 |
dictionary schema validation python
|
Validate a parameter dict against a parameter schema from an ocrd - tool . json
|
cosqa-train-437
|
def validate(self, *args, **kwargs): # pylint: disable=arguments-differ
"""
Validate a parameter dict against a parameter schema from an ocrd-tool.json
Args:
obj (dict):
schema (dict):
"""
return super(ParameterValidator, self)._validate(*args, **kwargs)
|
def get_parent_dir ( name ) : parent_dir = os . path . dirname ( os . path . dirname ( name ) ) if parent_dir : return parent_dir return os . path . abspath ( '.' )
| 0 |
python get file parent path name
|
Get the parent directory of a filename .
|
cosqa-train-438
|
def get_parent_dir(name):
"""Get the parent directory of a filename."""
parent_dir = os.path.dirname(os.path.dirname(name))
if parent_dir:
return parent_dir
return os.path.abspath('.')
|
def me ( self ) : return self . guild . me if self . guild is not None else self . bot . user
| 0 |
discord bot python mention user
|
Similar to : attr : . Guild . me except it may return the : class : . ClientUser in private message contexts .
|
cosqa-train-439
|
def me(self):
"""Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts."""
return self.guild.me if self.guild is not None else self.bot.user
|
def get_size_in_bytes ( self , handle ) : fpath = self . _fpath_from_handle ( handle ) return os . stat ( fpath ) . st_size
| 0 |
python get file size in gb
|
Return the size in bytes .
|
cosqa-train-440
|
def get_size_in_bytes(self, handle):
"""Return the size in bytes."""
fpath = self._fpath_from_handle(handle)
return os.stat(fpath).st_size
|
def show_guestbook ( ) : cursor = flask . g . db . execute ( 'SELECT name, message FROM entry ORDER BY id DESC;' ) entries = [ { 'name' : row [ 0 ] , 'message' : row [ 1 ] } for row in cursor . fetchall ( ) ] return jinja2 . Template ( LAYOUT ) . render ( entries = entries )
| 0 |
display table in html now reflaticing data only blanck box using python flask'
|
Returns all existing guestbook records .
|
cosqa-train-441
|
def show_guestbook():
"""Returns all existing guestbook records."""
cursor = flask.g.db.execute(
'SELECT name, message FROM entry ORDER BY id DESC;')
entries = [{'name': row[0], 'message': row[1]} for row in cursor.fetchall()]
return jinja2.Template(LAYOUT).render(entries=entries)
|
def get_month_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( day = 1 )
| 0 |
python get first date month
|
Returns the first day of the given month .
|
cosqa-train-442
|
def get_month_start(day=None):
"""Returns the first day of the given month."""
day = add_timezone(day or datetime.date.today())
return day.replace(day=1)
|
def rank ( idx , dim ) : idxm = multi_index ( idx , dim ) out = 0 while idxm [ - 1 : ] == ( 0 , ) : out += 1 idxm = idxm [ : - 1 ] return out
| 1 |
display the count of index in adjacent position python
|
Calculate the index rank according to Bertran s notation .
|
cosqa-train-443
|
def rank(idx, dim):
"""Calculate the index rank according to Bertran's notation."""
idxm = multi_index(idx, dim)
out = 0
while idxm[-1:] == (0,):
out += 1
idxm = idxm[:-1]
return out
|
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
| 0 |
python get git lastest commit
|
Get the HEAD commit SHA1 of repository in current dir .
|
cosqa-train-444
|
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 csvpretty ( csvfile : csvfile = sys . stdin ) : shellish . tabulate ( csv . reader ( csvfile ) )
| 0 |
displaying tabular data stream python
|
Pretty print a CSV file .
|
cosqa-train-445
|
def csvpretty(csvfile: csvfile=sys.stdin):
""" Pretty print a CSV file. """
shellish.tabulate(csv.reader(csvfile))
|
def array_dim ( arr ) : dim = [ ] while True : try : dim . append ( len ( arr ) ) arr = arr [ 0 ] except TypeError : return dim
| 0 |
python get length of array]
|
Return the size of a multidimansional array .
|
cosqa-train-446
|
def array_dim(arr):
"""Return the size of a multidimansional array.
"""
dim = []
while True:
try:
dim.append(len(arr))
arr = arr[0]
except TypeError:
return dim
|
def _split_str ( s , n ) : length = len ( s ) return [ s [ i : i + n ] for i in range ( 0 , length , n ) ]
| 0 |
divide the string into n parts in python
|
split string into list of strings by specified number .
|
cosqa-train-447
|
def _split_str(s, n):
"""
split string into list of strings by specified number.
"""
length = len(s)
return [s[i:i + n] for i in range(0, length, n)]
|
def qsize ( self ) : self . mutex . acquire ( ) n = self . _qsize ( ) self . mutex . release ( ) return n
| 0 |
python get length of queue
|
Return the approximate size of the queue ( not reliable! ) .
|
cosqa-train-448
|
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n
|
def is_static ( self , filename ) : if self . staticpaths is None : # We're not using static file support return False for path in self . staticpaths : if filename . startswith ( path ) : return True return False
| 0 |
django python check if static file exists
|
Check if a file is a static file ( which should be copied rather than compiled using Jinja2 ) .
|
cosqa-train-449
|
def is_static(self, filename):
"""Check if a file is a static file (which should be copied, rather
than compiled using Jinja2).
A file is considered static if it lives in any of the directories
specified in ``staticpaths``.
:param filename: the name of the file to check
"""
if self.staticpaths is None:
# We're not using static file support
return False
for path in self.staticpaths:
if filename.startswith(path):
return True
return False
|
def items ( self ) : return [ ( value_descriptor . name , value_descriptor . number ) for value_descriptor in self . _enum_type . values ]
| 0 |
python get list of enum names
|
Return a list of the ( name value ) pairs of the enum .
|
cosqa-train-450
|
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 serve_static ( request , path , insecure = False , * * kwargs ) : # Follow the same logic Django uses for determining access to the # static-serving view. if not django_settings . DEBUG and not insecure : raise ImproperlyConfigured ( "The staticfiles view can only be used in " "debug mode or if the --insecure " "option of 'runserver' is used" ) if not settings . PIPELINE_ENABLED and settings . PIPELINE_COLLECTOR_ENABLED : # Collect only the requested file, in order to serve the result as # fast as possible. This won't interfere with the template tags in any # way, as those will still cause Django to collect all media. default_collector . collect ( request , files = [ path ] ) return serve ( request , path , document_root = django_settings . STATIC_ROOT , * * kwargs )
| 0 |
django static files in templates working but not in python code
|
Collect and serve static files .
|
cosqa-train-451
|
def serve_static(request, path, insecure=False, **kwargs):
"""Collect and serve static files.
This view serves up static files, much like Django's
:py:func:`~django.views.static.serve` view, with the addition that it
collects static files first (if enabled). This allows images, fonts, and
other assets to be served up without first loading a page using the
``{% javascript %}`` or ``{% stylesheet %}`` template tags.
You can use this view by adding the following to any :file:`urls.py`::
urlpatterns += static('static/', view='pipeline.views.serve_static')
"""
# Follow the same logic Django uses for determining access to the
# static-serving view.
if not django_settings.DEBUG and not insecure:
raise ImproperlyConfigured("The staticfiles view can only be used in "
"debug mode or if the --insecure "
"option of 'runserver' is used")
if not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED:
# Collect only the requested file, in order to serve the result as
# fast as possible. This won't interfere with the template tags in any
# way, as those will still cause Django to collect all media.
default_collector.collect(request, files=[path])
return serve(request, path, document_root=django_settings.STATIC_ROOT,
**kwargs)
|
def items ( cls ) : return [ cls . PRECIPITATION , cls . WIND , cls . TEMPERATURE , cls . PRESSURE ]
| 0 |
python get list of enum values
|
All values for this enum : return : list of tuples
|
cosqa-train-452
|
def items(cls):
"""
All values for this enum
:return: list of tuples
"""
return [
cls.PRECIPITATION,
cls.WIND,
cls.TEMPERATURE,
cls.PRESSURE
]
|
def go_to_new_line ( self ) : self . stdkey_end ( False , False ) self . insert_text ( self . get_line_separator ( ) )
| 0 |
do i press enter or tab to start new line in python
|
Go to the end of the current line and create a new line
|
cosqa-train-453
|
def go_to_new_line(self):
"""Go to the end of the current line and create a new line"""
self.stdkey_end(False, False)
self.insert_text(self.get_line_separator())
|
def get_font_list ( ) : font_map = pangocairo . cairo_font_map_get_default ( ) font_list = [ f . get_name ( ) for f in font_map . list_families ( ) ] font_list . sort ( ) return font_list
| 0 |
python get list of fonts
|
Returns a sorted list of all system font names
|
cosqa-train-454
|
def get_font_list():
"""Returns a sorted list of all system font names"""
font_map = pangocairo.cairo_font_map_get_default()
font_list = [f.get_name() for f in font_map.list_families()]
font_list.sort()
return font_list
|
def has_parent ( self , term ) : for parent in self . parents : if parent . item_id == term or parent . has_parent ( term ) : return True return False
| 1 |
does a tree node have parent node associated with it using python
|
Return True if this GO object has a parent GO ID .
|
cosqa-train-455
|
def has_parent(self, term):
"""Return True if this GO object has a parent GO ID."""
for parent in self.parents:
if parent.item_id == term or parent.has_parent(term):
return True
return False
|
def unique_list_dicts ( dlist , key ) : return list ( dict ( ( val [ key ] , val ) for val in dlist ) . values ( ) )
| 0 |
python get list of values sorted by dict key
|
Return a list of dictionaries which are sorted for only unique entries .
|
cosqa-train-456
|
def unique_list_dicts(dlist, key):
"""Return a list of dictionaries which are sorted for only unique entries.
:param dlist:
:param key:
:return list:
"""
return list(dict((val[key], val) for val in dlist).values())
|
def invalidate_cache ( cpu , address , size ) : cache = cpu . instruction_cache for offset in range ( size ) : if address + offset in cache : del cache [ address + offset ]
| 0 |
does python automatically deallocate memory
|
remove decoded instruction from instruction cache
|
cosqa-train-457
|
def invalidate_cache(cpu, address, size):
""" remove decoded instruction from instruction cache """
cache = cpu.instruction_cache
for offset in range(size):
if address + offset in cache:
del cache[address + offset]
|
def _get_local_ip ( ) : return set ( [ x [ 4 ] [ 0 ] for x in socket . getaddrinfo ( socket . gethostname ( ) , 80 , socket . AF_INET ) ] ) . pop ( )
| 0 |
python get local ipa address
|
Get the local ip of this device
|
cosqa-train-458
|
def _get_local_ip():
"""
Get the local ip of this device
:return: Ip of this computer
:rtype: str
"""
return set([x[4][0] for x in socket.getaddrinfo(
socket.gethostname(),
80,
socket.AF_INET
)]).pop()
|
def keys_to_snake_case ( camel_case_dict ) : return dict ( ( to_snake_case ( key ) , value ) for ( key , value ) in camel_case_dict . items ( ) )
| 0 |
does python do camelcase
|
Make a copy of a dictionary with all keys converted to snake case . This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary .
|
cosqa-train-459
|
def keys_to_snake_case(camel_case_dict):
"""
Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on
each of the keys in the dictionary and returns a new dictionary.
:param camel_case_dict: Dictionary with the keys to convert.
:type camel_case_dict: Dictionary.
:return: Dictionary with the keys converted to snake case.
"""
return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())
|
def get_public_members ( obj ) : return { attr : getattr ( obj , attr ) for attr in dir ( obj ) if not attr . startswith ( "_" ) and not hasattr ( getattr ( obj , attr ) , '__call__' ) }
| 0 |
python get methods and properties of an object
|
Retrieves a list of member - like objects ( members or properties ) that are publically exposed .
|
cosqa-train-460
|
def get_public_members(obj):
"""
Retrieves a list of member-like objects (members or properties) that are
publically exposed.
:param obj: The object to probe.
:return: A list of strings.
"""
return {attr: getattr(obj, attr) for attr in dir(obj)
if not attr.startswith("_")
and not hasattr(getattr(obj, attr), '__call__')}
|
def timer ( ) : if sys . platform == "win32" : default_timer = time . clock else : default_timer = time . time return default_timer ( )
| 0 |
does python have a built in timer
|
Timer used for calculate time elapsed
|
cosqa-train-461
|
def timer():
"""
Timer used for calculate time elapsed
"""
if sys.platform == "win32":
default_timer = time.clock
else:
default_timer = time.time
return default_timer()
|
def last_day ( year = _year , month = _month ) : last_day = calendar . monthrange ( year , month ) [ 1 ] return datetime . date ( year = year , month = month , day = last_day )
| 0 |
python get month last date
|
get the current month s last day : param year : default to current year : param month : default to current month : return : month s last day
|
cosqa-train-462
|
def last_day(year=_year, month=_month):
"""
get the current month's last day
:param year: default to current year
:param month: default to current month
:return: month's last day
"""
last_day = calendar.monthrange(year, month)[1]
return datetime.date(year=year, month=month, day=last_day)
|
def unit_tangent ( self , t ) : dseg = self . derivative ( t ) return dseg / abs ( dseg )
| 0 |
does python have an inverse tangent function
|
returns the unit tangent vector of the segment at t ( centered at the origin and expressed as a complex number ) .
|
cosqa-train-463
|
def unit_tangent(self, t):
"""returns the unit tangent vector of the segment at t (centered at
the origin and expressed as a complex number)."""
dseg = self.derivative(t)
return dseg/abs(dseg)
|
def get_obj_cols ( df ) : obj_cols = [ ] for idx , dt in enumerate ( df . dtypes ) : if dt == 'object' or is_category ( dt ) : obj_cols . append ( df . columns . values [ idx ] ) return obj_cols
| 0 |
python get object columns for dataset
|
Returns names of object columns in the DataFrame .
|
cosqa-train-464
|
def get_obj_cols(df):
"""
Returns names of 'object' columns in the DataFrame.
"""
obj_cols = []
for idx, dt in enumerate(df.dtypes):
if dt == 'object' or is_category(dt):
obj_cols.append(df.columns.values[idx])
return obj_cols
|
def match_aspect_to_viewport ( self ) : viewport = self . viewport self . aspect = float ( viewport . width ) / viewport . height
| 0 |
double the pixels without changing the aspect ration python
|
Updates Camera . aspect to match the viewport s aspect ratio .
|
cosqa-train-465
|
def match_aspect_to_viewport(self):
"""Updates Camera.aspect to match the viewport's aspect ratio."""
viewport = self.viewport
self.aspect = float(viewport.width) / viewport.height
|
def get_property_by_name ( pif , name ) : return next ( ( x for x in pif . properties if x . name == name ) , None )
| 1 |
python get object property by name
|
Get a property by name
|
cosqa-train-466
|
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 us2mc ( string ) : return re . sub ( r'_([a-z])' , lambda m : ( m . group ( 1 ) . upper ( ) ) , string )
| 1 |
double underscore function python
|
Transform an underscore_case string to a mixedCase string
|
cosqa-train-467
|
def us2mc(string):
"""Transform an underscore_case string to a mixedCase string"""
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
|
def _uniquify ( _list ) : seen = set ( ) result = [ ] for x in _list : if x not in seen : result . append ( x ) seen . add ( x ) return result
| 0 |
python get only unique values from list
|
Remove duplicates in a list .
|
cosqa-train-468
|
def _uniquify(_list):
"""Remove duplicates in a list."""
seen = set()
result = []
for x in _list:
if x not in seen:
result.append(x)
seen.add(x)
return result
|
def fmt_duration ( secs ) : return ' ' . join ( fmt . human_duration ( secs , 0 , precision = 2 , short = True ) . strip ( ) . split ( ) )
| 0 |
duration format in python django
|
Format a duration in seconds .
|
cosqa-train-469
|
def fmt_duration(secs):
"""Format a duration in seconds."""
return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())
|
def get_module_path ( modname ) : return osp . abspath ( osp . dirname ( sys . modules [ modname ] . __file__ ) )
| 0 |
python get path of a function
|
Return module * modname * base path
|
cosqa-train-470
|
def get_module_path(modname):
"""Return module *modname* base path"""
return osp.abspath(osp.dirname(sys.modules[modname].__file__))
|
def np_hash ( a ) : if a is None : return hash ( None ) # Ensure that hashes are equal whatever the ordering in memory (C or # Fortran) a = np . ascontiguousarray ( a ) # Compute the digest and return a decimal int return int ( hashlib . sha1 ( a . view ( a . dtype ) ) . hexdigest ( ) , 16 )
| 0 |
efficient way to calculate a checksum of an array in python
|
Return a hash of a NumPy array .
|
cosqa-train-471
|
def np_hash(a):
"""Return a hash of a NumPy array."""
if a is None:
return hash(None)
# Ensure that hashes are equal whatever the ordering in memory (C or
# Fortran)
a = np.ascontiguousarray(a)
# Compute the digest and return a decimal int
return int(hashlib.sha1(a.view(a.dtype)).hexdigest(), 16)
|
def get ( s , delimiter = '' , format = "diacritical" ) : return delimiter . join ( _pinyin_generator ( u ( s ) , format = format ) )
| 0 |
python get pinyin from characters python
|
Return pinyin of string the string must be unicode
|
cosqa-train-472
|
def get(s, delimiter='', format="diacritical"):
"""Return pinyin of string, the string must be unicode
"""
return delimiter.join(_pinyin_generator(u(s), format=format))
|
def center_eigenvalue_diff ( mat ) : N = len ( mat ) evals = np . sort ( la . eigvals ( mat ) ) diff = np . abs ( evals [ N / 2 ] - evals [ N / 2 - 1 ] ) return diff
| 0 |
eigen values calculation in python
|
Compute the eigvals of mat and then find the center eigval difference .
|
cosqa-train-473
|
def center_eigenvalue_diff(mat):
"""Compute the eigvals of mat and then find the center eigval difference."""
N = len(mat)
evals = np.sort(la.eigvals(mat))
diff = np.abs(evals[N/2] - evals[N/2-1])
return diff
|
def get_property_by_name ( pif , name ) : return next ( ( x for x in pif . properties if x . name == name ) , None )
| 0 |
python get property value by name
|
Get a property by name
|
cosqa-train-474
|
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 center_eigenvalue_diff ( mat ) : N = len ( mat ) evals = np . sort ( la . eigvals ( mat ) ) diff = np . abs ( evals [ N / 2 ] - evals [ N / 2 - 1 ] ) return diff
| 1 |
eigen values of gradients of images, python
|
Compute the eigvals of mat and then find the center eigval difference .
|
cosqa-train-475
|
def center_eigenvalue_diff(mat):
"""Compute the eigvals of mat and then find the center eigval difference."""
N = len(mat)
evals = np.sort(la.eigvals(mat))
diff = np.abs(evals[N/2] - evals[N/2-1])
return diff
|
def get_file_size ( fileobj ) : currpos = fileobj . tell ( ) fileobj . seek ( 0 , 2 ) total_size = fileobj . tell ( ) fileobj . seek ( currpos ) return total_size
| 0 |
python get size of an open file
|
Returns the size of a file - like object .
|
cosqa-train-476
|
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 center_eigenvalue_diff ( mat ) : N = len ( mat ) evals = np . sort ( la . eigvals ( mat ) ) diff = np . abs ( evals [ N / 2 ] - evals [ N / 2 - 1 ] ) return diff
| 0 |
eigenvalues of a matrix in python code
|
Compute the eigvals of mat and then find the center eigval difference .
|
cosqa-train-477
|
def center_eigenvalue_diff(mat):
"""Compute the eigvals of mat and then find the center eigval difference."""
N = len(mat)
evals = np.sort(la.eigvals(mat))
diff = np.abs(evals[N/2] - evals[N/2-1])
return diff
|
def array_bytes ( array ) : return np . product ( array . shape ) * np . dtype ( array . dtype ) . itemsize
| 0 |
python get size of cytpes array in memory
|
Estimates the memory of the supplied array in bytes
|
cosqa-train-478
|
def array_bytes(array):
""" Estimates the memory of the supplied array in bytes """
return np.product(array.shape)*np.dtype(array.dtype).itemsize
|
def clear_es ( ) : # TODO: should receive a catalog slug. ESHypermap . es . indices . delete ( ESHypermap . index_name , ignore = [ 400 , 404 ] ) LOGGER . debug ( 'Elasticsearch: Index cleared' )
| 0 |
elasticsearch delete by query python
|
Clear all indexes in the es core
|
cosqa-train-479
|
def clear_es():
"""Clear all indexes in the es core"""
# TODO: should receive a catalog slug.
ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404])
LOGGER.debug('Elasticsearch: Index cleared')
|
def get_idx_rect ( index_list ) : rows , cols = list ( zip ( * [ ( i . row ( ) , i . column ( ) ) for i in index_list ] ) ) return ( min ( rows ) , max ( rows ) , min ( cols ) , max ( cols ) )
| 0 |
python get specific indexes list
|
Extract the boundaries from a list of indexes
|
cosqa-train-480
|
def get_idx_rect(index_list):
"""Extract the boundaries from a list of indexes"""
rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))
return ( min(rows), max(rows), min(cols), max(cols) )
|
def _get_node_parent ( self , age , pos ) : return self . nodes [ age ] [ int ( pos / self . comp ) ]
| 1 |
elementtree get parent python
|
Get the parent node of node whch is located in tree s node list .
|
cosqa-train-481
|
def _get_node_parent(self, age, pos):
"""Get the parent node of node, whch is located in tree's node list.
Returns:
object: The parent node.
"""
return self.nodes[age][int(pos / self.comp)]
|
def __repr__ ( self ) : strings = [ ] for currItem in self : strings . append ( "%s" % currItem ) return "(%s)" % ( ", " . join ( strings ) )
| 0 |
python get str rep of object
|
Return list - lookalike of representation string of objects
|
cosqa-train-482
|
def __repr__(self):
"""Return list-lookalike of representation string of objects"""
strings = []
for currItem in self:
strings.append("%s" % currItem)
return "(%s)" % (", ".join(strings))
|
def dedup_list ( l ) : dedup = set ( ) return [ x for x in l if not ( x in dedup or dedup . add ( x ) ) ]
| 1 |
eliminate duplicate entries python list
|
Given a list ( l ) will removing duplicates from the list preserving the original order of the list . Assumes that the list entrie are hashable .
|
cosqa-train-483
|
def dedup_list(l):
"""Given a list (l) will removing duplicates from the list,
preserving the original order of the list. Assumes that
the list entrie are hashable."""
dedup = set()
return [ x for x in l if not (x in dedup or dedup.add(x))]
|
def tf2 ( ) : # Import the `tf` compat API from this file and check if it's already TF 2.0. if tf . __version__ . startswith ( '2.' ) : return tf elif hasattr ( tf , 'compat' ) and hasattr ( tf . compat , 'v2' ) : # As a fallback, try `tensorflow.compat.v2` if it's defined. return tf . compat . v2 raise ImportError ( 'cannot import tensorflow 2.0 API' )
| 0 |
python get tensorflow ver
|
Provide the root module of a TF - 2 . 0 API for use within TensorBoard .
|
cosqa-train-484
|
def tf2():
"""Provide the root module of a TF-2.0 API for use within TensorBoard.
Returns:
The root module of a TF-2.0 API, if available.
Raises:
ImportError: if a TF-2.0 API is not available.
"""
# Import the `tf` compat API from this file and check if it's already TF 2.0.
if tf.__version__.startswith('2.'):
return tf
elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'):
# As a fallback, try `tensorflow.compat.v2` if it's defined.
return tf.compat.v2
raise ImportError('cannot import tensorflow 2.0 API')
|
def split_addresses ( email_string_list ) : return [ f for f in [ s . strip ( ) for s in email_string_list . split ( "," ) ] if f ]
| 0 |
email strto list python
|
Converts a string containing comma separated email addresses into a list of email addresses .
|
cosqa-train-485
|
def split_addresses(email_string_list):
"""
Converts a string containing comma separated email addresses
into a list of email addresses.
"""
return [f for f in [s.strip() for s in email_string_list.split(",")] if f]
|
def size ( ) : try : assert os != 'nt' and sys . stdout . isatty ( ) rows , columns = os . popen ( 'stty size' , 'r' ) . read ( ) . split ( ) except ( AssertionError , AttributeError , ValueError ) : # in case of failure, use dimensions of a full screen 13" laptop rows , columns = DEFAULT_HEIGHT , DEFAULT_WIDTH return int ( rows ) , int ( columns )
| 1 |
python get the char width number of shell window
|
Determines the height and width of the console window
|
cosqa-train-486
|
def size():
"""Determines the height and width of the console window
Returns:
tuple of int: The height in lines, then width in characters
"""
try:
assert os != 'nt' and sys.stdout.isatty()
rows, columns = os.popen('stty size', 'r').read().split()
except (AssertionError, AttributeError, ValueError):
# in case of failure, use dimensions of a full screen 13" laptop
rows, columns = DEFAULT_HEIGHT, DEFAULT_WIDTH
return int(rows), int(columns)
|
def _encode_bool ( name , value , dummy0 , dummy1 ) : return b"\x08" + name + ( value and b"\x01" or b"\x00" )
| 0 |
encode boolean to binary python
|
Encode a python boolean ( True / False ) .
|
cosqa-train-487
|
def _encode_bool(name, value, dummy0, dummy1):
"""Encode a python boolean (True/False)."""
return b"\x08" + name + (value and b"\x01" or b"\x00")
|
def get_list_index ( lst , index_or_name ) : if isinstance ( index_or_name , six . integer_types ) : return index_or_name return lst . index ( index_or_name )
| 0 |
python get the index of a list item
|
Return the index of an element in the list .
|
cosqa-train-488
|
def get_list_index(lst, index_or_name):
"""
Return the index of an element in the list.
Args:
lst (list): The list.
index_or_name (int or str): The value of the reference element, or directly its numeric index.
Returns:
(int) The index of the element in the list.
"""
if isinstance(index_or_name, six.integer_types):
return index_or_name
return lst.index(index_or_name)
|
def write_enum ( fo , datum , schema ) : index = schema [ 'symbols' ] . index ( datum ) write_int ( fo , index )
| 1 |
enum en python definicion
|
An enum is encoded by a int representing the zero - based position of the symbol in the schema .
|
cosqa-train-489
|
def write_enum(fo, datum, schema):
"""An enum is encoded by a int, representing the zero-based position of
the symbol in the schema."""
index = schema['symbols'].index(datum)
write_int(fo, index)
|
def get_bottomrect_idx ( self , pos ) : for i , r in enumerate ( self . link_bottom_rects ) : if r . Contains ( pos ) : return i return - 1
| 0 |
python get the index of top va;ie
|
Determine if cursor is on bottom right corner of a hot spot .
|
cosqa-train-490
|
def get_bottomrect_idx(self, pos):
""" Determine if cursor is on bottom right corner of a hot spot."""
for i, r in enumerate(self.link_bottom_rects):
if r.Contains(pos):
return i
return -1
|
def _dt_to_epoch ( dt ) : try : epoch = dt . timestamp ( ) except AttributeError : # py2 epoch = ( dt - datetime ( 1970 , 1 , 1 ) ) . total_seconds ( ) return epoch
| 0 |
epoch for datetime python
|
Convert datetime to epoch seconds .
|
cosqa-train-491
|
def _dt_to_epoch(dt):
"""Convert datetime to epoch seconds."""
try:
epoch = dt.timestamp()
except AttributeError: # py2
epoch = (dt - datetime(1970, 1, 1)).total_seconds()
return epoch
|
def table_top_abs ( self ) : table_height = np . array ( [ 0 , 0 , self . table_full_size [ 2 ] ] ) return string_to_array ( self . floor . get ( "pos" ) ) + table_height
| 0 |
python get top three row index
|
Returns the absolute position of table top
|
cosqa-train-492
|
def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height
|
def plot_epsilon_residuals ( self ) : fig = plt . figure ( ) ax = fig . add_subplot ( 111 ) ax . scatter ( range ( self . epsilon . size ) , self . epsilon , c = 'k' , marker = '*' ) ax . axhline ( y = 0.0 ) plt . show ( )
| 0 |
epsilon in plot in python
|
Plots the epsilon residuals for the variogram fit .
|
cosqa-train-493
|
def plot_epsilon_residuals(self):
"""Plots the epsilon residuals for the variogram fit."""
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(range(self.epsilon.size), self.epsilon, c='k', marker='*')
ax.axhline(y=0.0)
plt.show()
|
def get_property_by_name ( pif , name ) : return next ( ( x for x in pif . properties if x . name == name ) , None )
| 0 |
python get type of property by name
|
Get a property by name
|
cosqa-train-494
|
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 image_set_aspect ( aspect = 1.0 , axes = "gca" ) : if axes is "gca" : axes = _pylab . gca ( ) e = axes . get_images ( ) [ 0 ] . get_extent ( ) axes . set_aspect ( abs ( ( e [ 1 ] - e [ 0 ] ) / ( e [ 3 ] - e [ 2 ] ) ) / aspect )
| 0 |
equal aspect plot in python with large different axes ranges
|
sets the aspect ratio of the current zoom level of the imshow image
|
cosqa-train-495
|
def image_set_aspect(aspect=1.0, axes="gca"):
"""
sets the aspect ratio of the current zoom level of the imshow image
"""
if axes is "gca": axes = _pylab.gca()
e = axes.get_images()[0].get_extent()
axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect)
|
def forceupdate ( self , * args , * * kw ) : self . _update ( False , self . _ON_DUP_OVERWRITE , * args , * * kw )
| 0 |
es bulk update python
|
Like a bulk : meth : forceput .
|
cosqa-train-496
|
def forceupdate(self, *args, **kw):
"""Like a bulk :meth:`forceput`."""
self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
|
def get_nt_system_uid ( ) : try : import _winreg as winreg except ImportError : import winreg lm = winreg . ConnectRegistry ( None , winreg . HKEY_LOCAL_MACHINE ) try : key = winreg . OpenKey ( lm , r"Software\Microsoft\Cryptography" ) try : return winreg . QueryValueEx ( key , "MachineGuid" ) [ 0 ] finally : key . Close ( ) finally : lm . Close ( )
| 0 |
python get uid on windows
|
Get the MachineGuid from HKEY_LOCAL_MACHINE \ Software \ Microsoft \ Cryptography \ MachineGuid
|
cosqa-train-497
|
def get_nt_system_uid():
"""Get the MachineGuid from
HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\MachineGuid
"""
try:
import _winreg as winreg
except ImportError:
import winreg
lm = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
try:
key = winreg.OpenKey(lm, r"Software\Microsoft\Cryptography")
try:
return winreg.QueryValueEx(key, "MachineGuid")[0]
finally:
key.Close()
finally:
lm.Close()
|
def get_element_with_id ( self , id ) : # Should we maintain a hashmap of ids to make this more efficient? Probably overkill. # TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.) return next ( ( el for el in self . elements if el . id == id ) , None )
| 0 |
python get url element by id
|
Return the element with the specified ID .
|
cosqa-train-498
|
def get_element_with_id(self, id):
"""Return the element with the specified ID."""
# Should we maintain a hashmap of ids to make this more efficient? Probably overkill.
# TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.)
return next((el for el in self.elements if el.id == id), None)
|
def vector_distance ( a , b ) : a = np . array ( a ) b = np . array ( b ) return np . linalg . norm ( a - b )
| 0 |
euclidean distance between two vectors python
|
The Euclidean distance between two vectors .
|
cosqa-train-499
|
def vector_distance(a, b):
"""The Euclidean distance between two vectors."""
a = np.array(a)
b = np.array(b)
return np.linalg.norm(a - b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.