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 get_dimension_array ( array ) : if all ( isinstance ( el , list ) for el in array ) : result = [ len ( array ) , len ( max ( [ x for x in array ] , key = len , ) ) ] # elif array and isinstance(array, list): else : result = [ len ( array ) , 1 ] return result
| 0 |
size dimension of list python
|
Get dimension of an array getting the number of rows and the max num of columns .
|
cosqa-train-16700
|
def get_dimension_array(array):
"""
Get dimension of an array getting the number of rows and the max num of
columns.
"""
if all(isinstance(el, list) for el in array):
result = [len(array), len(max([x for x in array], key=len,))]
# elif array and isinstance(array, list):
else:
result = [len(array), 1]
return result
|
def is_scalar ( value ) : return np . isscalar ( value ) or ( isinstance ( value , np . ndarray ) and ( len ( np . squeeze ( value ) . shape ) == 0 ) )
| 0 |
python 1 element array to scalar
|
Test if the given value is a scalar .
|
cosqa-train-16701
|
def is_scalar(value):
"""Test if the given value is a scalar.
This function also works with memory mapped array values, in contrast to the numpy is_scalar method.
Args:
value: the value to test for being a scalar value
Returns:
boolean: if the given value is a scalar or not
"""
return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))
|
def calculate_size ( name , function ) : data_size = 0 data_size += calculate_size_str ( name ) data_size += calculate_size_data ( function ) return data_size
| 1 |
size limit of a function python
|
Calculates the request payload size
|
cosqa-train-16702
|
def calculate_size(name, function):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_data(function)
return data_size
|
def _transform_triple_numpy ( x ) : return np . array ( [ x . head , x . relation , x . tail ] , dtype = np . int64 )
| 1 |
python 2 dimensional array access with an array
|
Transform triple index into a 1 - D numpy array .
|
cosqa-train-16703
|
def _transform_triple_numpy(x):
"""Transform triple index into a 1-D numpy array."""
return np.array([x.head, x.relation, x.tail], dtype=np.int64)
|
def iget_list_column_slice ( list_ , start = None , stop = None , stride = None ) : if isinstance ( start , slice ) : slice_ = start else : slice_ = slice ( start , stop , stride ) return ( row [ slice_ ] for row in list_ )
| 0 |
slicing in 2d list python
|
iterator version of get_list_column
|
cosqa-train-16704
|
def iget_list_column_slice(list_, start=None, stop=None, stride=None):
""" iterator version of get_list_column """
if isinstance(start, slice):
slice_ = start
else:
slice_ = slice(start, stop, stride)
return (row[slice_] for row in list_)
|
def py3round ( number ) : if abs ( round ( number ) - number ) == 0.5 : return int ( 2.0 * round ( number / 2.0 ) ) return int ( round ( number ) )
| 0 |
python 2 round float
|
Unified rounding in all python versions .
|
cosqa-train-16705
|
def py3round(number):
"""Unified rounding in all python versions."""
if abs(round(number) - number) == 0.5:
return int(2.0 * round(number / 2.0))
return int(round(number))
|
def MatrixSolve ( a , rhs , adj ) : return np . linalg . solve ( a if not adj else _adjoint ( a ) , rhs ) ,
| 1 |
solve power matrix function python
|
Matrix solve op .
|
cosqa-train-16706
|
def MatrixSolve(a, rhs, adj):
"""
Matrix solve op.
"""
return np.linalg.solve(a if not adj else _adjoint(a), rhs),
|
def py3round ( number ) : if abs ( round ( number ) - number ) == 0.5 : return int ( 2.0 * round ( number / 2.0 ) ) return int ( round ( number ) )
| 0 |
python 2 round up float
|
Unified rounding in all python versions .
|
cosqa-train-16707
|
def py3round(number):
"""Unified rounding in all python versions."""
if abs(round(number) - number) == 0.5:
return int(2.0 * round(number / 2.0))
return int(round(number))
|
def naturalsortkey ( s ) : return [ int ( part ) if part . isdigit ( ) else part for part in re . split ( '([0-9]+)' , s ) ]
| 0 |
sort a number by its digits python
|
Natural sort order
|
cosqa-train-16708
|
def naturalsortkey(s):
"""Natural sort order"""
return [int(part) if part.isdigit() else part
for part in re.split('([0-9]+)', s)]
|
def to_dicts ( recarray ) : for rec in recarray : yield dict ( zip ( recarray . dtype . names , rec . tolist ( ) ) )
| 1 |
python 2d array to dict
|
convert record array to a dictionaries
|
cosqa-train-16709
|
def to_dicts(recarray):
"""convert record array to a dictionaries"""
for rec in recarray:
yield dict(zip(recarray.dtype.names, rec.tolist()))
|
def unique_list ( lst ) : uniq = [ ] for item in lst : if item not in uniq : uniq . append ( item ) return uniq
| 0 |
sort and uniq list in python
|
Make a list unique retaining order of initial appearance .
|
cosqa-train-16710
|
def unique_list(lst):
"""Make a list unique, retaining order of initial appearance."""
uniq = []
for item in lst:
if item not in uniq:
uniq.append(item)
return uniq
|
def create_rot2d ( angle ) : ca = math . cos ( angle ) sa = math . sin ( angle ) return np . array ( [ [ ca , - sa ] , [ sa , ca ] ] )
| 1 |
python 2d vector rotate angle
|
Create 2D rotation matrix
|
cosqa-train-16711
|
def create_rot2d(angle):
"""Create 2D rotation matrix"""
ca = math.cos(angle)
sa = math.sin(angle)
return np.array([[ca, -sa], [sa, ca]])
|
def naturalsortkey ( s ) : return [ int ( part ) if part . isdigit ( ) else part for part in re . split ( '([0-9]+)' , s ) ]
| 0 |
sort digits in an integer by digit in python
|
Natural sort order
|
cosqa-train-16712
|
def naturalsortkey(s):
"""Natural sort order"""
return [int(part) if part.isdigit() else part
for part in re.split('([0-9]+)', s)]
|
def command_py2to3 ( args ) : from lib2to3 . main import main sys . exit ( main ( "lib2to3.fixes" , args = args . sources ) )
| 1 |
python 2to3 whole directory
|
Apply 2to3 tool ( Python2 to Python3 conversion tool ) to Python sources .
|
cosqa-train-16713
|
def command_py2to3(args):
"""
Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.
"""
from lib2to3.main import main
sys.exit(main("lib2to3.fixes", args=args.sources))
|
def naturalsortkey ( s ) : return [ int ( part ) if part . isdigit ( ) else part for part in re . split ( '([0-9]+)' , s ) ]
| 0 |
sort digits in an integer in python
|
Natural sort order
|
cosqa-train-16714
|
def naturalsortkey(s):
"""Natural sort order"""
return [int(part) if part.isdigit() else part
for part in re.split('([0-9]+)', s)]
|
def ub_to_str ( string ) : if not isinstance ( string , str ) : if six . PY2 : return str ( string ) else : return string . decode ( ) return string
| 0 |
python 3 cast bytes to str
|
converts py2 unicode / py3 bytestring into str Args : string ( unicode byte_string ) : string to be converted Returns : ( str )
|
cosqa-train-16715
|
def ub_to_str(string):
"""
converts py2 unicode / py3 bytestring into str
Args:
string (unicode, byte_string): string to be converted
Returns:
(str)
"""
if not isinstance(string, str):
if six.PY2:
return str(string)
else:
return string.decode()
return string
|
def sort_by_name ( self ) : super ( JSSObjectList , self ) . sort ( key = lambda k : k . name )
| 0 |
sort list by name python
|
Sort list elements by name .
|
cosqa-train-16716
|
def sort_by_name(self):
"""Sort list elements by name."""
super(JSSObjectList, self).sort(key=lambda k: k.name)
|
def add_exec_permission_to ( target_file ) : mode = os . stat ( target_file ) . st_mode os . chmod ( target_file , mode | stat . S_IXUSR )
| 1 |
python 3 change permission of file chmod
|
Add executable permissions to the file
|
cosqa-train-16717
|
def add_exec_permission_to(target_file):
"""Add executable permissions to the file
:param target_file: the target file whose permission to be changed
"""
mode = os.stat(target_file).st_mode
os.chmod(target_file, mode | stat.S_IXUSR)
|
def _histplot_bins ( column , bins = 100 ) : col_min = np . min ( column ) col_max = np . max ( column ) return range ( col_min , col_max + 2 , max ( ( col_max - col_min ) // bins , 1 ) )
| 1 |
specify bins in python 2d histogram
|
Helper to get bins for histplot .
|
cosqa-train-16718
|
def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))
|
def socket_close ( self ) : if self . sock != NC . INVALID_SOCKET : self . sock . close ( ) self . sock = NC . INVALID_SOCKET
| 1 |
python 3 close socket
|
Close our socket .
|
cosqa-train-16719
|
def socket_close(self):
"""Close our socket."""
if self.sock != NC.INVALID_SOCKET:
self.sock.close()
self.sock = NC.INVALID_SOCKET
|
def schunk ( string , size ) : return [ string [ i : i + size ] for i in range ( 0 , len ( string ) , size ) ]
| 0 |
split a string into 5 equal size chunks in python
|
Splits string into n sized chunks .
|
cosqa-train-16720
|
def schunk(string, size):
"""Splits string into n sized chunks."""
return [string[i:i+size] for i in range(0, len(string), size)]
|
def _dictfetchall ( self , cursor ) : columns = [ col [ 0 ] for col in cursor . description ] return [ dict ( zip ( columns , row ) ) for row in cursor . fetchall ( ) ]
| 0 |
python 3 cursor fetch data as dict
|
Return all rows from a cursor as a dict .
|
cosqa-train-16721
|
def _dictfetchall(self, cursor):
""" Return all rows from a cursor as a dict. """
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]
|
def _split ( string , splitters ) : part = '' for character in string : if character in splitters : yield part part = '' else : part += character yield part
| 1 |
split based on multiple characters in python
|
Splits a string into parts at multiple characters
|
cosqa-train-16722
|
def _split(string, splitters):
"""Splits a string into parts at multiple characters"""
part = ''
for character in string:
if character in splitters:
yield part
part = ''
else:
part += character
yield part
|
def guess_media_type ( filepath ) : o = subprocess . check_output ( [ 'file' , '--mime-type' , '-Lb' , filepath ] ) o = o . strip ( ) return o
| 0 |
python 3 determine mime type of file
|
Returns the media - type of the file at the given filepath
|
cosqa-train-16723
|
def guess_media_type(filepath):
"""Returns the media-type of the file at the given ``filepath``"""
o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath])
o = o.strip()
return o
|
def _split ( string , splitters ) : part = '' for character in string : if character in splitters : yield part part = '' else : part += character yield part
| 0 |
split function in python for every character
|
Splits a string into parts at multiple characters
|
cosqa-train-16724
|
def _split(string, splitters):
"""Splits a string into parts at multiple characters"""
part = ''
for character in string:
if character in splitters:
yield part
part = ''
else:
part += character
yield part
|
def mouse_get_pos ( ) : p = POINT ( ) AUTO_IT . AU3_MouseGetPos ( ctypes . byref ( p ) ) return p . x , p . y
| 0 |
python 3 get mouse position
|
cosqa-train-16725
|
def mouse_get_pos():
"""
:return:
"""
p = POINT()
AUTO_IT.AU3_MouseGetPos(ctypes.byref(p))
return p.x, p.y
|
|
def cleanLines ( source , lineSep = os . linesep ) : stripped = ( line . strip ( lineSep ) for line in source ) return ( line for line in stripped if len ( line ) != 0 )
| 0 |
split lines with no newlines character python
|
: param source : some iterable source ( list file etc ) : param lineSep : string of separators ( chars ) that must be removed : return : list of non empty lines with removed separators
|
cosqa-train-16726
|
def cleanLines(source, lineSep=os.linesep):
"""
:param source: some iterable source (list, file, etc)
:param lineSep: string of separators (chars) that must be removed
:return: list of non empty lines with removed separators
"""
stripped = (line.strip(lineSep) for line in source)
return (line for line in stripped if len(line) != 0)
|
def read_credentials ( fname ) : with open ( fname , 'r' ) as f : username = f . readline ( ) . strip ( '\n' ) password = f . readline ( ) . strip ( '\n' ) return username , password
| 0 |
python 3 get user and password from a file
|
read a simple text file from a private location to get username and password
|
cosqa-train-16727
|
def read_credentials(fname):
"""
read a simple text file from a private location to get
username and password
"""
with open(fname, 'r') as f:
username = f.readline().strip('\n')
password = f.readline().strip('\n')
return username, password
|
def _parse_string_to_list_of_pairs ( s , seconds_to_int = False ) : ret = [ ] for p in [ s . split ( ":" ) for s in re . sub ( "[,.;]" , " " , s ) . split ( ) ] : if len ( p ) != 2 : raise ValueError ( "bad input to _parse_string_to_list_of_pairs %s" % s ) if seconds_to_int : ret . append ( ( p [ 0 ] , int ( p [ 1 ] ) ) ) else : ret . append ( tuple ( p ) ) return ret
| 1 |
split the string into pairs python
|
r Parses a string into a list of pairs .
|
cosqa-train-16728
|
def _parse_string_to_list_of_pairs(s, seconds_to_int=False):
r"""Parses a string into a list of pairs.
In the input string, each pair is separated by a colon, and the delimiters
between pairs are any of " ,.;".
e.g. "rows:32,cols:32"
Args:
s: str to parse.
seconds_to_int: Boolean. If True, then the second elements are returned
as integers; otherwise they are strings.
Returns:
List of tuple pairs.
Raises:
ValueError: Badly formatted string.
"""
ret = []
for p in [s.split(":") for s in re.sub("[,.;]", " ", s).split()]:
if len(p) != 2:
raise ValueError("bad input to _parse_string_to_list_of_pairs %s" % s)
if seconds_to_int:
ret.append((p[0], int(p[1])))
else:
ret.append(tuple(p))
return ret
|
def _get_or_create_stack ( name ) : stack = getattr ( _LOCAL_STACKS , name , None ) if stack is None : stack = [ ] setattr ( _LOCAL_STACKS , name , stack ) return stack
| 1 |
python 3 how to return local variable to global stack
|
Returns a thread local stack uniquified by the given name .
|
cosqa-train-16729
|
def _get_or_create_stack(name):
"""Returns a thread local stack uniquified by the given name."""
stack = getattr(_LOCAL_STACKS, name, None)
if stack is None:
stack = []
setattr(_LOCAL_STACKS, name, stack)
return stack
|
def chunks ( arr , size ) : for i in _range ( 0 , len ( arr ) , size ) : yield arr [ i : i + size ]
| 0 |
splitting an array in python into chunks
|
Splits a list into chunks
|
cosqa-train-16730
|
def chunks(arr, size):
"""Splits a list into chunks
:param arr: list to split
:type arr: :class:`list`
:param size: number of elements in each chunk
:type size: :class:`int`
:return: generator object
:rtype: :class:`generator`
"""
for i in _range(0, len(arr), size):
yield arr[i:i+size]
|
def calling_logger ( height = 1 ) : stack = inspect . stack ( ) height = min ( len ( stack ) - 1 , height ) caller = stack [ height ] scope = caller [ 0 ] . f_globals path = scope [ '__name__' ] if path == '__main__' : path = scope [ '__package__' ] or os . path . basename ( sys . argv [ 0 ] ) return logging . getLogger ( path )
| 0 |
python 3 logging findcaller
|
Obtain a logger for the calling module .
|
cosqa-train-16731
|
def calling_logger(height=1):
""" Obtain a logger for the calling module.
Uses the inspect module to find the name of the calling function and its
position in the module hierarchy. With the optional height argument, logs
for caller's caller, and so forth.
see: http://stackoverflow.com/a/900404/48251
"""
stack = inspect.stack()
height = min(len(stack) - 1, height)
caller = stack[height]
scope = caller[0].f_globals
path = scope['__name__']
if path == '__main__':
path = scope['__package__'] or os.path.basename(sys.argv[0])
return logging.getLogger(path)
|
def callproc ( self , name , params , param_types = None ) : if param_types : placeholders = [ self . sql_writer . typecast ( self . sql_writer . to_placeholder ( ) , t ) for t in param_types ] else : placeholders = [ self . sql_writer . to_placeholder ( ) for p in params ] # TODO: This may be Postgres specific... qs = "select * from {0}({1});" . format ( name , ", " . join ( placeholders ) ) return self . execute ( qs , params ) , params
| 1 |
sql server stored procedure python param out
|
Calls a procedure .
|
cosqa-train-16732
|
def callproc(self, name, params, param_types=None):
"""Calls a procedure.
:param name: the name of the procedure
:param params: a list or tuple of parameters to pass to the procedure.
:param param_types: a list or tuple of type names. If given, each param will be cast via
sql_writers typecast method. This is useful to disambiguate procedure calls
when several parameters are null and therefore cause overload resoluation
issues.
:return: a 2-tuple of (cursor, params)
"""
if param_types:
placeholders = [self.sql_writer.typecast(self.sql_writer.to_placeholder(), t)
for t in param_types]
else:
placeholders = [self.sql_writer.to_placeholder() for p in params]
# TODO: This may be Postgres specific...
qs = "select * from {0}({1});".format(name, ", ".join(placeholders))
return self.execute(qs, params), params
|
def force_iterable ( f ) : def wrapper ( * args , * * kwargs ) : r = f ( * args , * * kwargs ) if hasattr ( r , '__iter__' ) : return r else : return [ r ] return wrapper
| 1 |
python 3 make an iterable
|
Will make any functions return an iterable objects by wrapping its result in a list .
|
cosqa-train-16733
|
def force_iterable(f):
"""Will make any functions return an iterable objects by wrapping its result in a list."""
def wrapper(*args, **kwargs):
r = f(*args, **kwargs)
if hasattr(r, '__iter__'):
return r
else:
return [r]
return wrapper
|
def wipe ( self ) : query = "DELETE FROM {}" . format ( self . __tablename__ ) connection = sqlite3 . connect ( self . sqlite_file ) cursor = connection . cursor ( ) cursor . execute ( query ) connection . commit ( )
| 0 |
sqlite python delete all rows
|
Wipe the store
|
cosqa-train-16734
|
def wipe(self):
""" Wipe the store
"""
query = "DELETE FROM {}".format(self.__tablename__)
connection = sqlite3.connect(self.sqlite_file)
cursor = connection.cursor()
cursor.execute(query)
connection.commit()
|
async def async_input ( prompt ) : print ( prompt , end = '' , flush = True ) return ( await loop . run_in_executor ( None , sys . stdin . readline ) ) . rstrip ( )
| 0 |
python 3 non blocking user input
|
Python s input () is blocking which means the event loop we set above can t be running while we re blocking there . This method will let the loop run while we wait for input .
|
cosqa-train-16735
|
async def async_input(prompt):
"""
Python's ``input()`` is blocking, which means the event loop we set
above can't be running while we're blocking there. This method will
let the loop run while we wait for input.
"""
print(prompt, end='', flush=True)
return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()
|
def loadb ( b ) : assert isinstance ( b , ( bytes , bytearray ) ) return std_json . loads ( b . decode ( 'utf-8' ) )
| 0 |
python 3 object of type 'bytes' is not json serializable
|
Deserialize b ( instance of bytes ) to a Python object .
|
cosqa-train-16736
|
def loadb(b):
"""Deserialize ``b`` (instance of ``bytes``) to a Python object."""
assert isinstance(b, (bytes, bytearray))
return std_json.loads(b.decode('utf-8'))
|
def _heapify_max ( x ) : n = len ( x ) for i in reversed ( range ( n // 2 ) ) : _siftup_max ( x , i )
| 0 |
stack and heap in python 3
|
Transform list into a maxheap in - place in O ( len ( x )) time .
|
cosqa-train-16737
|
def _heapify_max(x):
"""Transform list into a maxheap, in-place, in O(len(x)) time."""
n = len(x)
for i in reversed(range(n//2)):
_siftup_max(x, i)
|
def readCommaList ( fileList ) : names = fileList . split ( ',' ) fileList = [ ] for item in names : fileList . append ( item ) return fileList
| 1 |
python 3 remove commas in list
|
Return a list of the files with the commas removed .
|
cosqa-train-16738
|
def readCommaList(fileList):
""" Return a list of the files with the commas removed. """
names=fileList.split(',')
fileList=[]
for item in names:
fileList.append(item)
return fileList
|
def dumps ( obj ) : return json . dumps ( obj , indent = 4 , sort_keys = True , cls = CustomEncoder )
| 0 |
stack overflow python object to json
|
Outputs json with formatting edits + object handling .
|
cosqa-train-16739
|
def dumps(obj):
"""Outputs json with formatting edits + object handling."""
return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)
|
def _repr_strip ( mystring ) : r = repr ( mystring ) if r . startswith ( "'" ) and r . endswith ( "'" ) : return r [ 1 : - 1 ] else : return r
| 0 |
python 3 strip enclosing quotes from string
|
Returns the string without any initial or final quotes .
|
cosqa-train-16740
|
def _repr_strip(mystring):
"""
Returns the string without any initial or final quotes.
"""
r = repr(mystring)
if r.startswith("'") and r.endswith("'"):
return r[1:-1]
else:
return r
|
def _heapify_max ( x ) : n = len ( x ) for i in reversed ( range ( n // 2 ) ) : _siftup_max ( x , i )
| 0 |
stackoverflow max value python list
|
Transform list into a maxheap in - place in O ( len ( x )) time .
|
cosqa-train-16741
|
def _heapify_max(x):
"""Transform list into a maxheap, in-place, in O(len(x)) time."""
n = len(x)
for i in reversed(range(n//2)):
_siftup_max(x, i)
|
def surface ( self , zdata , * * kwargs ) : self . _configure_3d ( ) surf = scene . SurfacePlot ( z = zdata , * * kwargs ) self . view . add ( surf ) self . view . camera . set_range ( ) return surf
| 1 |
python 3d plot set view to y and z
|
Show a 3D surface plot .
|
cosqa-train-16742
|
def surface(self, zdata, **kwargs):
"""Show a 3D surface plot.
Extra keyword arguments are passed to `SurfacePlot()`.
Parameters
----------
zdata : array-like
A 2D array of the surface Z values.
"""
self._configure_3d()
surf = scene.SurfacePlot(z=zdata, **kwargs)
self.view.add(surf)
self.view.camera.set_range()
return surf
|
def Softsign ( a ) : return np . divide ( a , np . add ( np . abs ( a ) , 1 ) ) ,
| 0 |
standard scaler without negative values python
|
Softsign op .
|
cosqa-train-16743
|
def Softsign(a):
"""
Softsign op.
"""
return np.divide(a, np.add(np.abs(a), 1)),
|
def _encode_gif ( images , fps ) : writer = WholeVideoWriter ( fps ) writer . write_multi ( images ) return writer . finish ( )
| 1 |
python [ng to gif animation
|
Encodes numpy images into gif string .
|
cosqa-train-16744
|
def _encode_gif(images, fps):
"""Encodes numpy images into gif string.
Args:
images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape
`[time, height, width, channels]` where `channels` is 1 or 3.
fps: frames per second of the animation
Returns:
The encoded gif string.
Raises:
IOError: If the ffmpeg command returns an error.
"""
writer = WholeVideoWriter(fps)
writer.write_multi(images)
return writer.finish()
|
def timeout_thread_handler ( timeout , stop_event ) : stop_happened = stop_event . wait ( timeout ) if stop_happened is False : print ( "Killing program due to %f second timeout" % timeout ) os . _exit ( 2 )
| 1 |
stop a python process from inside if a condition is met
|
A background thread to kill the process if it takes too long .
|
cosqa-train-16745
|
def timeout_thread_handler(timeout, stop_event):
"""A background thread to kill the process if it takes too long.
Args:
timeout (float): The number of seconds to wait before killing
the process.
stop_event (Event): An optional event to cleanly stop the background
thread if required during testing.
"""
stop_happened = stop_event.wait(timeout)
if stop_happened is False:
print("Killing program due to %f second timeout" % timeout)
os._exit(2)
|
def main ( idle ) : while True : LOG . debug ( "Sleeping for {0} seconds." . format ( idle ) ) time . sleep ( idle )
| 1 |
python a while loop instead of time sleep
|
Any normal python logic which runs a loop . Can take arguments .
|
cosqa-train-16746
|
def main(idle):
"""Any normal python logic which runs a loop. Can take arguments."""
while True:
LOG.debug("Sleeping for {0} seconds.".format(idle))
time.sleep(idle)
|
def stop_logging ( ) : from . import log logger = logging . getLogger ( "gromacs" ) logger . info ( "GromacsWrapper %s STOPPED logging" , get_version ( ) ) log . clear_handlers ( logger )
| 1 |
stop logging python function name and
|
Stop logging to logfile and console .
|
cosqa-train-16747
|
def stop_logging():
"""Stop logging to logfile and console."""
from . import log
logger = logging.getLogger("gromacs")
logger.info("GromacsWrapper %s STOPPED logging", get_version())
log.clear_handlers(logger)
|
def get_oauth_token ( ) : url = "{0}/token" . format ( DEFAULT_ORIGIN [ "Origin" ] ) r = s . get ( url = url ) return r . json ( ) [ "t" ]
| 0 |
python access token oauth url get
|
Retrieve a simple OAuth Token for use with the local http client .
|
cosqa-train-16748
|
def get_oauth_token():
"""Retrieve a simple OAuth Token for use with the local http client."""
url = "{0}/token".format(DEFAULT_ORIGIN["Origin"])
r = s.get(url=url)
return r.json()["t"]
|
def stop ( self , reason = None ) : self . logger . info ( 'stopping' ) self . loop . stop ( pyev . EVBREAK_ALL )
| 1 |
stop window service python
|
Shutdown the service with a reason .
|
cosqa-train-16749
|
def stop(self, reason=None):
"""Shutdown the service with a reason."""
self.logger.info('stopping')
self.loop.stop(pyev.EVBREAK_ALL)
|
def update ( packages , env = None , user = None ) : packages = ' ' . join ( packages . split ( ',' ) ) cmd = _create_conda_cmd ( 'update' , args = [ packages , '--yes' , '-q' ] , env = env , user = user ) return _execcmd ( cmd , user = user )
| 0 |
python activate conda in cmd
|
Update conda packages in a conda env
|
cosqa-train-16750
|
def update(packages, env=None, user=None):
"""
Update conda packages in a conda env
Attributes
----------
packages: list of packages comma delimited
"""
packages = ' '.join(packages.split(','))
cmd = _create_conda_cmd('update', args=[packages, '--yes', '-q'], env=env, user=user)
return _execcmd(cmd, user=user)
|
def _kw ( keywords ) : r = { } for k , v in keywords : r [ k ] = v return r
| 0 |
storing keywords in dictionaires in python
|
Turn list of keywords into dictionary .
|
cosqa-train-16751
|
def _kw(keywords):
"""Turn list of keywords into dictionary."""
r = {}
for k, v in keywords:
r[k] = v
return r
|
def logv ( msg , * args , * * kwargs ) : if settings . VERBOSE : log ( msg , * args , * * kwargs )
| 0 |
python add a verbose mode
|
Print out a log message only if verbose mode .
|
cosqa-train-16752
|
def logv(msg, *args, **kwargs):
"""
Print out a log message, only if verbose mode.
"""
if settings.VERBOSE:
log(msg, *args, **kwargs)
|
def join ( mapping , bind , values ) : return [ ' ' . join ( [ six . text_type ( v ) for v in values if v is not None ] ) ]
| 1 |
string def python spaces
|
Merge all the strings . Put space between them .
|
cosqa-train-16753
|
def join(mapping, bind, values):
""" Merge all the strings. Put space between them. """
return [' '.join([six.text_type(v) for v in values if v is not None])]
|
def debug ( self , text ) : self . logger . debug ( "{}{}" . format ( self . message_prefix , text ) )
| 0 |
python add custom field to logger formatter
|
Ajout d un message de log de type DEBUG
|
cosqa-train-16754
|
def debug(self, text):
""" Ajout d'un message de log de type DEBUG """
self.logger.debug("{}{}".format(self.message_prefix, text))
|
def _encode_bool ( name , value , dummy0 , dummy1 ) : return b"\x08" + name + ( value and b"\x01" or b"\x00" )
| 0 |
string format boolean escape values python
|
Encode a python boolean ( True / False ) .
|
cosqa-train-16755
|
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 set_as_object ( self , value ) : self . clear ( ) map = MapConverter . to_map ( value ) self . append ( map )
| 0 |
python add element to map
|
Sets a new value to map element
|
cosqa-train-16756
|
def set_as_object(self, value):
"""
Sets a new value to map element
:param value: a new element or map value.
"""
self.clear()
map = MapConverter.to_map(value)
self.append(map)
|
def text_width ( string , font_name , font_size ) : return stringWidth ( string , fontName = font_name , fontSize = font_size )
| 0 |
string height and width in python
|
Determine with width in pixels of string .
|
cosqa-train-16757
|
def text_width(string, font_name, font_size):
"""Determine with width in pixels of string."""
return stringWidth(string, fontName=font_name, fontSize=font_size)
|
def activate ( self ) : add_builtin = self . add_builtin for name , func in self . auto_builtins . iteritems ( ) : add_builtin ( name , func )
| 0 |
python add methods to builtin
|
Store ipython references in the __builtin__ namespace .
|
cosqa-train-16758
|
def activate(self):
"""Store ipython references in the __builtin__ namespace."""
add_builtin = self.add_builtin
for name, func in self.auto_builtins.iteritems():
add_builtin(name, func)
|
def __repr__ ( self ) : strings = [ ] for currItem in self : strings . append ( "%s" % currItem ) return "(%s)" % ( ", " . join ( strings ) )
| 0 |
string representation not printed in list python
|
Return list - lookalike of representation string of objects
|
cosqa-train-16759
|
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 add_to_enum ( self , clsdict ) : super ( XmlMappedEnumMember , self ) . add_to_enum ( clsdict ) self . register_xml_mapping ( clsdict )
| 0 |
python add to emtyp dict
|
Compile XML mappings in addition to base add behavior .
|
cosqa-train-16760
|
def add_to_enum(self, clsdict):
"""
Compile XML mappings in addition to base add behavior.
"""
super(XmlMappedEnumMember, self).add_to_enum(clsdict)
self.register_xml_mapping(clsdict)
|
def get_adjacent_matrix ( self ) : edges = self . edges num_edges = len ( edges ) + 1 adj = np . zeros ( [ num_edges , num_edges ] ) for k in range ( num_edges - 1 ) : adj [ edges [ k ] . L , edges [ k ] . R ] = 1 adj [ edges [ k ] . R , edges [ k ] . L ] = 1 return adj
| 1 |
python adjacency matrix from edge list
|
Get adjacency matrix .
|
cosqa-train-16761
|
def get_adjacent_matrix(self):
"""Get adjacency matrix.
Returns:
:param adj: adjacency matrix
:type adj: np.ndarray
"""
edges = self.edges
num_edges = len(edges) + 1
adj = np.zeros([num_edges, num_edges])
for k in range(num_edges - 1):
adj[edges[k].L, edges[k].R] = 1
adj[edges[k].R, edges[k].L] = 1
return adj
|
def energy_string_to_float ( string ) : energy_re = re . compile ( "(-?\d+\.\d+)" ) return float ( energy_re . match ( string ) . group ( 0 ) )
| 1 |
string to float converter python
|
Convert a string of a calculation energy e . g . - 1 . 2345 eV to a float .
|
cosqa-train-16762
|
def energy_string_to_float( string ):
"""
Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.
Args:
string (str): The string to convert.
Return
(float)
"""
energy_re = re.compile( "(-?\d+\.\d+)" )
return float( energy_re.match( string ).group(0) )
|
def as_dict ( self ) : attrs = vars ( self ) return { key : attrs [ key ] for key in attrs if not key . startswith ( '_' ) }
| 1 |
python all attributes for an object
|
Package up the public attributes as a dict .
|
cosqa-train-16763
|
def as_dict(self):
"""Package up the public attributes as a dict."""
attrs = vars(self)
return {key: attrs[key] for key in attrs if not key.startswith('_')}
|
def do_striptags ( value ) : if hasattr ( value , '__html__' ) : value = value . __html__ ( ) return Markup ( unicode ( value ) ) . striptags ( )
| 1 |
strip dangerous tags python
|
Strip SGML / XML tags and replace adjacent whitespace by one space .
|
cosqa-train-16764
|
def do_striptags(value):
"""Strip SGML/XML tags and replace adjacent whitespace by one space.
"""
if hasattr(value, '__html__'):
value = value.__html__()
return Markup(unicode(value)).striptags()
|
def dictfetchall ( cursor ) : desc = cursor . description return [ dict ( zip ( [ col [ 0 ] for col in desc ] , row ) ) for row in cursor . fetchall ( ) ]
| 0 |
python all the fields of a table database
|
Returns all rows from a cursor as a dict ( rather than a headerless table )
|
cosqa-train-16765
|
def dictfetchall(cursor):
"""Returns all rows from a cursor as a dict (rather than a headerless table)
From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/
"""
desc = cursor.description
return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
|
def text_cleanup ( data , key , last_type ) : if key in data and last_type == STRING_TYPE : data [ key ] = data [ key ] . strip ( ) return data
| 0 |
strip white space in python string
|
I strip extra whitespace off multi - line strings if they are ready to be stripped!
|
cosqa-train-16766
|
def text_cleanup(data, key, last_type):
""" I strip extra whitespace off multi-line strings if they are ready to be stripped!"""
if key in data and last_type == STRING_TYPE:
data[key] = data[key].strip()
return data
|
def isbinary ( * args ) : return all ( map ( lambda c : isnumber ( c ) or isbool ( c ) , args ) )
| 0 |
python and an array of booleans
|
Checks if value can be part of binary / bitwise operations .
|
cosqa-train-16767
|
def isbinary(*args):
"""Checks if value can be part of binary/bitwise operations."""
return all(map(lambda c: isnumber(c) or isbool(c), args))
|
def __run_spark_submit ( lane_yaml , dist_dir , spark_home , spark_args , silent ) : # spark-submit binary cmd = [ 'spark-submit' if spark_home is None else os . path . join ( spark_home , 'bin/spark-submit' ) ] # Supplied spark arguments if spark_args : cmd += spark_args # Packaged App & lane cmd += [ '--py-files' , 'libs.zip,_framework.zip,tasks.zip' , 'main.py' ] cmd += [ '--lane' , lane_yaml ] logging . info ( 'Submitting to Spark' ) logging . debug ( str ( cmd ) ) # Submit devnull = open ( os . devnull , 'w' ) outp = { 'stderr' : STDOUT , 'stdout' : devnull } if silent else { } call ( cmd , cwd = dist_dir , env = MY_ENV , * * outp ) devnull . close ( )
| 1 |
submit python code in pysopark
|
Submits the packaged application to spark using a spark - submit subprocess
|
cosqa-train-16768
|
def __run_spark_submit(lane_yaml, dist_dir, spark_home, spark_args, silent):
"""
Submits the packaged application to spark using a `spark-submit` subprocess
Parameters
----------
lane_yaml (str): Path to the YAML lane definition file
dist_dir (str): Path to the directory where the packaged code is located
spark_args (str): String of any additional spark config args to be passed when submitting
silent (bool): Flag indicating whether job output should be printed to console
"""
# spark-submit binary
cmd = ['spark-submit' if spark_home is None else os.path.join(spark_home, 'bin/spark-submit')]
# Supplied spark arguments
if spark_args:
cmd += spark_args
# Packaged App & lane
cmd += ['--py-files', 'libs.zip,_framework.zip,tasks.zip', 'main.py']
cmd += ['--lane', lane_yaml]
logging.info('Submitting to Spark')
logging.debug(str(cmd))
# Submit
devnull = open(os.devnull, 'w')
outp = {'stderr': STDOUT, 'stdout': devnull} if silent else {}
call(cmd, cwd=dist_dir, env=MY_ENV, **outp)
devnull.close()
|
def angle ( x , y ) : return arccos ( dot ( x , y ) / ( norm ( x ) * norm ( y ) ) ) * 180. / pi
| 0 |
python angle between 3 points
|
Return the angle between vectors a and b in degrees .
|
cosqa-train-16769
|
def angle(x, y):
"""Return the angle between vectors a and b in degrees."""
return arccos(dot(x, y)/(norm(x)*norm(y)))*180./pi
|
def set_title ( self , title , * * kwargs ) : ax = self . get_axes ( ) ax . set_title ( title , * * kwargs )
| 0 |
subplot python matplotlib set title
|
Sets the title on the underlying matplotlib AxesSubplot .
|
cosqa-train-16770
|
def set_title(self, title, **kwargs):
"""Sets the title on the underlying matplotlib AxesSubplot."""
ax = self.get_axes()
ax.set_title(title, **kwargs)
|
def write_login ( collector , image , * * kwargs ) : docker_api = collector . configuration [ "harpoon" ] . docker_api collector . configuration [ "authentication" ] . login ( docker_api , image , is_pushing = True , global_docker = True )
| 1 |
python api docker login denied
|
Login to a docker registry with write permissions
|
cosqa-train-16771
|
def write_login(collector, image, **kwargs):
"""Login to a docker registry with write permissions"""
docker_api = collector.configuration["harpoon"].docker_api
collector.configuration["authentication"].login(docker_api, image, is_pushing=True, global_docker=True)
|
def correspond ( text ) : subproc . stdin . write ( text ) subproc . stdin . flush ( ) return drain ( )
| 0 |
subprocess python stdin write
|
Communicate with the child process without closing stdin .
|
cosqa-train-16772
|
def correspond(text):
"""Communicate with the child process without closing stdin."""
subproc.stdin.write(text)
subproc.stdin.flush()
return drain()
|
def dictapply ( d , fn ) : for k , v in d . items ( ) : if isinstance ( v , dict ) : v = dictapply ( v , fn ) else : d [ k ] = fn ( v ) return d
| 0 |
python apply function all elements in dictonary
|
apply a function to all non - dict values in a dictionary
|
cosqa-train-16773
|
def dictapply(d, fn):
"""
apply a function to all non-dict values in a dictionary
"""
for k, v in d.items():
if isinstance(v, dict):
v = dictapply(v, fn)
else:
d[k] = fn(v)
return d
|
def filter_dict ( d , keys ) : return { k : v for k , v in d . items ( ) if k in keys }
| 1 |
subset dictionary based on keys python
|
Creates a new dict from an existing dict that only has the given keys
|
cosqa-train-16774
|
def filter_dict(d, keys):
"""
Creates a new dict from an existing dict that only has the given keys
"""
return {k: v for k, v in d.items() if k in keys}
|
def dictapply ( d , fn ) : for k , v in d . items ( ) : if isinstance ( v , dict ) : v = dictapply ( v , fn ) else : d [ k ] = fn ( v ) return d
| 1 |
python apply function to dictionary
|
apply a function to all non - dict values in a dictionary
|
cosqa-train-16775
|
def dictapply(d, fn):
"""
apply a function to all non-dict values in a dictionary
"""
for k, v in d.items():
if isinstance(v, dict):
v = dictapply(v, fn)
else:
d[k] = fn(v)
return d
|
def _accumulate ( sequence , func ) : iterator = iter ( sequence ) total = next ( iterator ) yield total for element in iterator : total = func ( total , element ) yield total
| 1 |
sum within a comprehension python
|
Python2 accumulate implementation taken from https : // docs . python . org / 3 / library / itertools . html#itertools . accumulate
|
cosqa-train-16776
|
def _accumulate(sequence, func):
"""
Python2 accumulate implementation taken from
https://docs.python.org/3/library/itertools.html#itertools.accumulate
"""
iterator = iter(sequence)
total = next(iterator)
yield total
for element in iterator:
total = func(total, element)
yield total
|
def _varargs_to_iterable_method ( func ) : def wrapped ( self , iterable , * * kwargs ) : return func ( self , * iterable , * * kwargs ) return wrapped
| 0 |
python apply function to iterable
|
decorator to convert a * args method to one taking a iterable
|
cosqa-train-16777
|
def _varargs_to_iterable_method(func):
"""decorator to convert a *args method to one taking a iterable"""
def wrapped(self, iterable, **kwargs):
return func(self, *iterable, **kwargs)
return wrapped
|
def redirect ( cls , request , response ) : if cls . meta . legacy_redirect : if request . method in ( 'GET' , 'HEAD' , ) : # A SAFE request is allowed to redirect using a 301 response . status = http . client . MOVED_PERMANENTLY else : # All other requests must use a 307 response . status = http . client . TEMPORARY_REDIRECT else : # Modern redirects are allowed. Let's have some fun. # Hopefully you're client supports this. # The RFC explicitly discourages UserAgent sniffing. response . status = http . client . PERMANENT_REDIRECT # Terminate the connection. response . close ( )
| 0 |
syntax for a 303 redirect in python
|
Redirect to the canonical URI for this resource .
|
cosqa-train-16778
|
def redirect(cls, request, response):
"""Redirect to the canonical URI for this resource."""
if cls.meta.legacy_redirect:
if request.method in ('GET', 'HEAD',):
# A SAFE request is allowed to redirect using a 301
response.status = http.client.MOVED_PERMANENTLY
else:
# All other requests must use a 307
response.status = http.client.TEMPORARY_REDIRECT
else:
# Modern redirects are allowed. Let's have some fun.
# Hopefully you're client supports this.
# The RFC explicitly discourages UserAgent sniffing.
response.status = http.client.PERMANENT_REDIRECT
# Terminate the connection.
response.close()
|
def _replace_variables ( data , variables ) : formatter = string . Formatter ( ) return [ formatter . vformat ( item , [ ] , variables ) for item in data ]
| 0 |
python applying format to str in map(str
|
Replace the format variables in all items of data .
|
cosqa-train-16779
|
def _replace_variables(data, variables):
"""Replace the format variables in all items of data."""
formatter = string.Formatter()
return [formatter.vformat(item, [], variables) for item in data]
|
def format_exc ( * exc_info ) : typ , exc , tb = exc_info or sys . exc_info ( ) error = traceback . format_exception ( typ , exc , tb ) return "" . join ( error )
| 0 |
sys exc info python and traceback
|
Show exception with traceback .
|
cosqa-train-16780
|
def format_exc(*exc_info):
"""Show exception with traceback."""
typ, exc, tb = exc_info or sys.exc_info()
error = traceback.format_exception(typ, exc, tb)
return "".join(error)
|
def to_list ( self ) : return [ [ int ( self . table . cell_values [ 0 ] [ 1 ] ) , int ( self . table . cell_values [ 0 ] [ 2 ] ) ] , [ int ( self . table . cell_values [ 1 ] [ 1 ] ) , int ( self . table . cell_values [ 1 ] [ 2 ] ) ] ]
| 0 |
python are lists implemented as array
|
Convert this confusion matrix into a 2x2 plain list of values .
|
cosqa-train-16781
|
def to_list(self):
"""Convert this confusion matrix into a 2x2 plain list of values."""
return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],
[int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]
|
def string_to_identity ( identity_str ) : m = _identity_regexp . match ( identity_str ) result = m . groupdict ( ) log . debug ( 'parsed identity: %s' , result ) return { k : v for k , v in result . items ( ) if v }
| 1 |
take a string and form a dictionary python
|
Parse string into Identity dictionary .
|
cosqa-train-16782
|
def string_to_identity(identity_str):
"""Parse string into Identity dictionary."""
m = _identity_regexp.match(identity_str)
result = m.groupdict()
log.debug('parsed identity: %s', result)
return {k: v for k, v in result.items() if v}
|
def get_tri_area ( pts ) : a , b , c = pts [ 0 ] , pts [ 1 ] , pts [ 2 ] v1 = np . array ( b ) - np . array ( a ) v2 = np . array ( c ) - np . array ( a ) area_tri = abs ( sp . linalg . norm ( sp . cross ( v1 , v2 ) ) / 2 ) return area_tri
| 0 |
python area given 3 points
|
Given a list of coords for 3 points Compute the area of this triangle .
|
cosqa-train-16783
|
def get_tri_area(pts):
"""
Given a list of coords for 3 points,
Compute the area of this triangle.
Args:
pts: [a, b, c] three points
"""
a, b, c = pts[0], pts[1], pts[2]
v1 = np.array(b) - np.array(a)
v2 = np.array(c) - np.array(a)
area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2)
return area_tri
|
def datetime_match ( data , dts ) : dts = dts if islistable ( dts ) else [ dts ] if any ( [ not isinstance ( i , datetime . datetime ) for i in dts ] ) : error_msg = ( "`time` can only be filtered by datetimes" ) raise TypeError ( error_msg ) return data . isin ( dts )
| 0 |
taking datetimes and matching them to another column python
|
matching of datetimes in time columns for data filtering
|
cosqa-train-16784
|
def datetime_match(data, dts):
"""
matching of datetimes in time columns for data filtering
"""
dts = dts if islistable(dts) else [dts]
if any([not isinstance(i, datetime.datetime) for i in dts]):
error_msg = (
"`time` can only be filtered by datetimes"
)
raise TypeError(error_msg)
return data.isin(dts)
|
def register_action ( action ) : sub = _subparsers . add_parser ( action . meta ( 'cmd' ) , help = action . meta ( 'help' ) ) sub . set_defaults ( cmd = action . meta ( 'cmd' ) ) for ( name , arg ) in action . props ( ) . items ( ) : sub . add_argument ( arg . name , arg . flag , * * arg . options ) _actions [ action . meta ( 'cmd' ) ] = action
| 1 |
python argparse custom action parse file
|
Adds an action to the parser cli .
|
cosqa-train-16785
|
def register_action(action):
"""
Adds an action to the parser cli.
:param action(BaseAction): a subclass of the BaseAction class
"""
sub = _subparsers.add_parser(action.meta('cmd'), help=action.meta('help'))
sub.set_defaults(cmd=action.meta('cmd'))
for (name, arg) in action.props().items():
sub.add_argument(arg.name, arg.flag, **arg.options)
_actions[action.meta('cmd')] = action
|
def _uniquify ( _list ) : seen = set ( ) result = [ ] for x in _list : if x not in seen : result . append ( x ) seen . add ( x ) return result
| 0 |
taking out unique values from a python list
|
Remove duplicates in a list .
|
cosqa-train-16786
|
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 parse_command_args ( ) : parser = argparse . ArgumentParser ( description = 'Register PB devices.' ) parser . add_argument ( 'num_pb' , type = int , help = 'Number of PBs devices to register.' ) return parser . parse_args ( )
| 0 |
python argparse no help message
|
Command line parser .
|
cosqa-train-16787
|
def parse_command_args():
"""Command line parser."""
parser = argparse.ArgumentParser(description='Register PB devices.')
parser.add_argument('num_pb', type=int,
help='Number of PBs devices to register.')
return parser.parse_args()
|
def tuple_check ( * args , func = None ) : func = func or inspect . stack ( ) [ 2 ] [ 3 ] for var in args : if not isinstance ( var , ( tuple , collections . abc . Sequence ) ) : name = type ( var ) . __name__ raise TupleError ( f'Function {func} expected tuple, {name} got instead.' )
| 1 |
tell python function to expect tuple
|
Check if arguments are tuple type .
|
cosqa-train-16788
|
def tuple_check(*args, func=None):
"""Check if arguments are tuple type."""
func = func or inspect.stack()[2][3]
for var in args:
if not isinstance(var, (tuple, collections.abc.Sequence)):
name = type(var).__name__
raise TupleError(
f'Function {func} expected tuple, {name} got instead.')
|
def kwargs_to_string ( kwargs ) : outstr = '' for arg in kwargs : outstr += ' -{} {}' . format ( arg , kwargs [ arg ] ) return outstr
| 1 |
python args kwargs to string
|
Given a set of kwargs turns them into a string which can then be passed to a command . : param kwargs : kwargs from a function call . : return : outstr : A string which is if no kwargs were given and the kwargs in string format otherwise .
|
cosqa-train-16789
|
def kwargs_to_string(kwargs):
"""
Given a set of kwargs, turns them into a string which can then be passed to a command.
:param kwargs: kwargs from a function call.
:return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise.
"""
outstr = ''
for arg in kwargs:
outstr += ' -{} {}'.format(arg, kwargs[arg])
return outstr
|
def process_wait ( process , timeout = 0 ) : ret = AUTO_IT . AU3_ProcessWait ( LPCWSTR ( process ) , INT ( timeout ) ) return ret
| 0 |
tell python to pause for secs before running script
|
Pauses script execution until a given process exists . : param process : : param timeout : : return :
|
cosqa-train-16790
|
def process_wait(process, timeout=0):
"""
Pauses script execution until a given process exists.
:param process:
:param timeout:
:return:
"""
ret = AUTO_IT.AU3_ProcessWait(LPCWSTR(process), INT(timeout))
return ret
|
def _most_common ( iterable ) : data = Counter ( iterable ) return max ( data , key = data . __getitem__ )
| 1 |
python array get most common element
|
Returns the most common element in iterable .
|
cosqa-train-16791
|
def _most_common(iterable):
"""Returns the most common element in `iterable`."""
data = Counter(iterable)
return max(data, key=data.__getitem__)
|
def unit_ball_L2 ( shape ) : x = tf . Variable ( tf . zeros ( shape ) ) return constrain_L2 ( x )
| 0 |
tensorflow has no attribute python
|
A tensorflow variable tranfomed to be constrained in a L2 unit ball .
|
cosqa-train-16792
|
def unit_ball_L2(shape):
"""A tensorflow variable tranfomed to be constrained in a L2 unit ball.
EXPERIMENTAL: Do not use for adverserial examples if you need to be confident
they are strong attacks. We are not yet confident in this code.
"""
x = tf.Variable(tf.zeros(shape))
return constrain_L2(x)
|
def expect_all ( a , b ) : assert all ( _a == _b for _a , _b in zip_longest ( a , b ) )
| 0 |
python assert lists are equal
|
\ Asserts that two iterables contain the same values .
|
cosqa-train-16793
|
def expect_all(a, b):
"""\
Asserts that two iterables contain the same values.
"""
assert all(_a == _b for _a, _b in zip_longest(a, b))
|
def transformer_tall_pretrain_lm_tpu_adafactor ( ) : hparams = transformer_tall_pretrain_lm ( ) update_hparams_for_tpu ( hparams ) hparams . max_length = 1024 # For multi-problem on TPU we need it in absolute examples. hparams . batch_size = 8 hparams . multiproblem_vocab_size = 2 ** 16 return hparams
| 0 |
tensorflow python cpu minilab
|
Hparams for transformer on LM pretraining ( with 64k vocab ) on TPU .
|
cosqa-train-16794
|
def transformer_tall_pretrain_lm_tpu_adafactor():
"""Hparams for transformer on LM pretraining (with 64k vocab) on TPU."""
hparams = transformer_tall_pretrain_lm()
update_hparams_for_tpu(hparams)
hparams.max_length = 1024
# For multi-problem on TPU we need it in absolute examples.
hparams.batch_size = 8
hparams.multiproblem_vocab_size = 2**16
return hparams
|
def _assert_is_type ( name , value , value_type ) : if not isinstance ( value , value_type ) : if type ( value_type ) is tuple : types = ', ' . join ( t . __name__ for t in value_type ) raise ValueError ( '{0} must be one of ({1})' . format ( name , types ) ) else : raise ValueError ( '{0} must be {1}' . format ( name , value_type . __name__ ) )
| 0 |
python assert object type
|
Assert that a value must be a given type .
|
cosqa-train-16795
|
def _assert_is_type(name, value, value_type):
"""Assert that a value must be a given type."""
if not isinstance(value, value_type):
if type(value_type) is tuple:
types = ', '.join(t.__name__ for t in value_type)
raise ValueError('{0} must be one of ({1})'.format(name, types))
else:
raise ValueError('{0} must be {1}'
.format(name, value_type.__name__))
|
def is_timestamp ( instance ) : if not isinstance ( instance , ( int , str ) ) : return True return datetime . fromtimestamp ( int ( instance ) )
| 0 |
test datetime validity python
|
Validates data is a timestamp
|
cosqa-train-16796
|
def is_timestamp(instance):
"""Validates data is a timestamp"""
if not isinstance(instance, (int, str)):
return True
return datetime.fromtimestamp(int(instance))
|
def from_array ( cls , arr ) : return cls ( ) . with_columns ( [ ( f , arr [ f ] ) for f in arr . dtype . names ] )
| 0 |
python astropy table np array
|
Convert a structured NumPy array into a Table .
|
cosqa-train-16797
|
def from_array(cls, arr):
"""Convert a structured NumPy array into a Table."""
return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])
|
def is_lazy_iterable ( obj ) : return isinstance ( obj , ( types . GeneratorType , collections . MappingView , six . moves . range , enumerate ) )
| 0 |
test whether a python object is iterable
|
Returns whether * obj * is iterable lazily such as generators range objects etc .
|
cosqa-train-16798
|
def is_lazy_iterable(obj):
"""
Returns whether *obj* is iterable lazily, such as generators, range objects, etc.
"""
return isinstance(obj,
(types.GeneratorType, collections.MappingView, six.moves.range, enumerate))
|
def connection_lost ( self , exc ) : if exc is None : self . log . warning ( 'eof from receiver?' ) else : self . log . warning ( 'Lost connection to receiver: %s' , exc ) self . transport = None if self . _connection_lost_callback : self . _loop . call_soon ( self . _connection_lost_callback )
| 0 |
python asyncio how to detect socket connection lost
|
Called when asyncio . Protocol loses the network connection .
|
cosqa-train-16799
|
def connection_lost(self, exc):
"""Called when asyncio.Protocol loses the network connection."""
if exc is None:
self.log.warning('eof from receiver?')
else:
self.log.warning('Lost connection to receiver: %s', exc)
self.transport = None
if self._connection_lost_callback:
self._loop.call_soon(self._connection_lost_callback)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.