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 timed_call ( func , * args , log_level = 'DEBUG' , * * kwargs ) : start = time ( ) r = func ( * args , * * kwargs ) t = time ( ) - start log ( log_level , "Call to '{}' took {:0.6f}s" . format ( func . __name__ , t ) ) return r
| 1 |
how to time function execution in python
|
Logs a function s run time
|
cosqa-train-16300
|
def timed_call(func, *args, log_level='DEBUG', **kwargs):
"""Logs a function's run time
:param func: The function to run
:param args: The args to pass to the function
:param kwargs: The keyword args to pass to the function
:param log_level: The log level at which to print the run time
:return: The function's return value
"""
start = time()
r = func(*args, **kwargs)
t = time() - start
log(log_level, "Call to '{}' took {:0.6f}s".format(func.__name__, t))
return r
|
def _is_image_sequenced ( image ) : try : image . seek ( 1 ) image . seek ( 0 ) result = True except EOFError : result = False return result
| 0 |
python to known whether an image is valid
|
Determine if the image is a sequenced image .
|
cosqa-train-16301
|
def _is_image_sequenced(image):
"""Determine if the image is a sequenced image."""
try:
image.seek(1)
image.seek(0)
result = True
except EOFError:
result = False
return result
|
def sent2features ( sentence , template ) : return [ word2features ( sentence , i , template ) for i in range ( len ( sentence ) ) ]
| 0 |
how to transform list of words to sentences in python
|
extract features in a sentence
|
cosqa-train-16302
|
def sent2features(sentence, template):
""" extract features in a sentence
:type sentence: list of token, each token is a list of tag
"""
return [word2features(sentence, i, template) for i in range(len(sentence))]
|
def _namematcher ( regex ) : matcher = re_compile ( regex ) def match ( target ) : target_name = getattr ( target , '__name__' , '' ) result = matcher . match ( target_name ) return result return match
| 1 |
python to match names
|
Checks if a target name matches with an input regular expression .
|
cosqa-train-16303
|
def _namematcher(regex):
"""Checks if a target name matches with an input regular expression."""
matcher = re_compile(regex)
def match(target):
target_name = getattr(target, '__name__', '')
result = matcher.match(target_name)
return result
return match
|
def _unjsonify ( x , isattributes = False ) : if isattributes : obj = json . loads ( x ) return dict_class ( obj ) return json . loads ( x )
| 1 |
how to turn a json dictionary into a python dictionary
|
Convert JSON string to an ordered defaultdict .
|
cosqa-train-16304
|
def _unjsonify(x, isattributes=False):
"""Convert JSON string to an ordered defaultdict."""
if isattributes:
obj = json.loads(x)
return dict_class(obj)
return json.loads(x)
|
def eglInitialize ( display ) : majorVersion = ( _c_int * 1 ) ( ) minorVersion = ( _c_int * 1 ) ( ) res = _lib . eglInitialize ( display , majorVersion , minorVersion ) if res == EGL_FALSE : raise RuntimeError ( 'Could not initialize' ) return majorVersion [ 0 ] , minorVersion [ 0 ]
| 0 |
python to opengl texture
|
Initialize EGL and return EGL version tuple .
|
cosqa-train-16305
|
def eglInitialize(display):
""" Initialize EGL and return EGL version tuple.
"""
majorVersion = (_c_int*1)()
minorVersion = (_c_int*1)()
res = _lib.eglInitialize(display, majorVersion, minorVersion)
if res == EGL_FALSE:
raise RuntimeError('Could not initialize')
return majorVersion[0], minorVersion[0]
|
def mouse_move_event ( self , event ) : self . example . mouse_position_event ( event . x ( ) , event . y ( ) )
| 0 |
python track mouse location
|
Forward mouse cursor position events to the example
|
cosqa-train-16306
|
def mouse_move_event(self, event):
"""
Forward mouse cursor position events to the example
"""
self.example.mouse_position_event(event.x(), event.y())
|
def list2dict ( lst ) : dic = { } for k , v in lst : dic [ k ] = v return dic
| 0 |
how to turn a list into a dictionary python
|
Takes a list of ( key value ) pairs and turns it into a dict .
|
cosqa-train-16307
|
def list2dict(lst):
"""Takes a list of (key,value) pairs and turns it into a dict."""
dic = {}
for k,v in lst: dic[k] = v
return dic
|
def path_to_list ( pathstr ) : return [ elem for elem in pathstr . split ( os . path . pathsep ) if elem ]
| 1 |
python transfer a string to a list
|
Conver a path string to a list of path elements .
|
cosqa-train-16308
|
def path_to_list(pathstr):
"""Conver a path string to a list of path elements."""
return [elem for elem in pathstr.split(os.path.pathsep) if elem]
|
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 |
how to turn a string into a dict python
|
Parse string into Identity dictionary .
|
cosqa-train-16309
|
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 normalize_enum_constant ( s ) : if s . islower ( ) : return s if s . isupper ( ) : return s . lower ( ) return "" . join ( ch if ch . islower ( ) else "_" + ch . lower ( ) for ch in s ) . strip ( "_" )
| 0 |
python translate enum values to
|
Return enum constant s converted to a canonical snake - case .
|
cosqa-train-16310
|
def normalize_enum_constant(s):
"""Return enum constant `s` converted to a canonical snake-case."""
if s.islower(): return s
if s.isupper(): return s.lower()
return "".join(ch if ch.islower() else "_" + ch.lower() for ch in s).strip("_")
|
def string_to_float_list ( string_var ) : try : return [ float ( s ) for s in string_var . strip ( '[' ) . strip ( ']' ) . split ( ', ' ) ] except : return [ float ( s ) for s in string_var . strip ( '[' ) . strip ( ']' ) . split ( ',' ) ]
| 0 |
how to turn a string list into a float python
|
Pull comma separated string values out of a text file and converts them to float list
|
cosqa-train-16311
|
def string_to_float_list(string_var):
"""Pull comma separated string values out of a text file and converts them to float list"""
try:
return [float(s) for s in string_var.strip('[').strip(']').split(', ')]
except:
return [float(s) for s in string_var.strip('[').strip(']').split(',')]
|
def sf01 ( arr ) : s = arr . shape return arr . swapaxes ( 0 , 1 ) . reshape ( s [ 0 ] * s [ 1 ] , * s [ 2 : ] )
| 0 |
python transpose axis example
|
swap and then flatten axes 0 and 1
|
cosqa-train-16312
|
def sf01(arr):
"""
swap and then flatten axes 0 and 1
"""
s = arr.shape
return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])
|
def to_bytes ( s , encoding = "utf-8" ) : if isinstance ( s , six . binary_type ) : return s if six . PY3 : return bytes ( s , encoding ) return s . encode ( encoding )
| 1 |
how to turn bytes string into bytes in python3
|
Convert a string to bytes .
|
cosqa-train-16313
|
def to_bytes(s, encoding="utf-8"):
"""Convert a string to bytes."""
if isinstance(s, six.binary_type):
return s
if six.PY3:
return bytes(s, encoding)
return s.encode(encoding)
|
def C_dict2array ( C ) : return np . hstack ( [ np . asarray ( C [ k ] ) . ravel ( ) for k in C_keys ] )
| 1 |
python transpose dict to column array
|
Convert an OrderedDict containing C values to a 1D array .
|
cosqa-train-16314
|
def C_dict2array(C):
"""Convert an OrderedDict containing C values to a 1D array."""
return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])
|
def intToBin ( i ) : # divide in two parts (bytes) i1 = i % 256 i2 = int ( i / 256 ) # make string (little endian) return i . to_bytes ( 2 , byteorder = 'little' )
| 1 |
how to turn ints to binary python
|
Integer to two bytes
|
cosqa-train-16315
|
def intToBin(i):
""" Integer to two bytes """
# divide in two parts (bytes)
i1 = i % 256
i2 = int(i / 256)
# make string (little endian)
return i.to_bytes(2, byteorder='little')
|
def size ( self ) : if self is NULL : return 0 return 1 + self . left . size ( ) + self . right . size ( )
| 0 |
python tree count total
|
Recursively find size of a tree . Slow .
|
cosqa-train-16316
|
def size(self):
"""
Recursively find size of a tree. Slow.
"""
if self is NULL:
return 0
return 1 + self.left.size() + self.right.size()
|
def should_skip_logging ( func ) : disabled = strtobool ( request . headers . get ( "x-request-nolog" , "false" ) ) return disabled or getattr ( func , SKIP_LOGGING , False )
| 0 |
how to turn logging off, python
|
Should we skip logging for this handler?
|
cosqa-train-16317
|
def should_skip_logging(func):
"""
Should we skip logging for this handler?
"""
disabled = strtobool(request.headers.get("x-request-nolog", "false"))
return disabled or getattr(func, SKIP_LOGGING, False)
|
def cleanup_nodes ( doc ) : for node in doc . documentElement . childNodes : if node . nodeType == Node . TEXT_NODE and node . nodeValue . isspace ( ) : doc . documentElement . removeChild ( node ) return doc
| 1 |
python trim spaces in xml
|
Remove text nodes containing only whitespace
|
cosqa-train-16318
|
def cleanup_nodes(doc):
"""
Remove text nodes containing only whitespace
"""
for node in doc.documentElement.childNodes:
if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():
doc.documentElement.removeChild(node)
return doc
|
def stdout_to_results ( s ) : results = s . strip ( ) . split ( '\n' ) return [ BenchmarkResult ( * r . split ( ) ) for r in results ]
| 0 |
how to turn output into a list python
|
Turns the multi - line output of a benchmark process into a sequence of BenchmarkResult instances .
|
cosqa-train-16319
|
def stdout_to_results(s):
"""Turns the multi-line output of a benchmark process into
a sequence of BenchmarkResult instances."""
results = s.strip().split('\n')
return [BenchmarkResult(*r.split()) for r in results]
|
def _remove_blank ( l ) : ret = [ ] for i , _ in enumerate ( l ) : if l [ i ] == 0 : break ret . append ( l [ i ] ) return ret
| 1 |
python trim zeros from list
|
Removes trailing zeros in the list of integers and returns a new list of integers
|
cosqa-train-16320
|
def _remove_blank(l):
""" Removes trailing zeros in the list of integers and returns a new list of integers"""
ret = []
for i, _ in enumerate(l):
if l[i] == 0:
break
ret.append(l[i])
return ret
|
def get_neg_infinity ( dtype ) : if issubclass ( dtype . type , ( np . floating , np . integer ) ) : return - np . inf if issubclass ( dtype . type , np . complexfloating ) : return - np . inf - 1j * np . inf return NINF
| 0 |
how to type out negative infinity in python
|
Return an appropriate positive infinity for this dtype .
|
cosqa-train-16321
|
def get_neg_infinity(dtype):
"""Return an appropriate positive infinity for this dtype.
Parameters
----------
dtype : np.dtype
Returns
-------
fill_value : positive infinity value corresponding to this dtype.
"""
if issubclass(dtype.type, (np.floating, np.integer)):
return -np.inf
if issubclass(dtype.type, np.complexfloating):
return -np.inf - 1j * np.inf
return NINF
|
def retry_call ( func , cleanup = lambda : None , retries = 0 , trap = ( ) ) : attempts = count ( ) if retries == float ( 'inf' ) else range ( retries ) for attempt in attempts : try : return func ( ) except trap : cleanup ( ) return func ( )
| 1 |
python try again in a function
|
Given a callable func trap the indicated exceptions for up to retries times invoking cleanup on the exception . On the final attempt allow any exceptions to propagate .
|
cosqa-train-16322
|
def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
"""
Given a callable func, trap the indicated exceptions
for up to 'retries' times, invoking cleanup on the
exception. On the final attempt, allow any exceptions
to propagate.
"""
attempts = count() if retries == float('inf') else range(retries)
for attempt in attempts:
try:
return func()
except trap:
cleanup()
return func()
|
def union ( self , other ) : obj = self . _clone ( ) obj . union_update ( other ) return obj
| 0 |
how to union two set types in python
|
Return a new set which is the union of I { self } and I { other } .
|
cosqa-train-16323
|
def union(self, other):
"""Return a new set which is the union of I{self} and I{other}.
@param other: the other set
@type other: Set object
@rtype: the same type as I{self}
"""
obj = self._clone()
obj.union_update(other)
return obj
|
def set_scrollbars_cb ( self , w , tf ) : scrollbars = 'on' if tf else 'off' self . t_ . set ( scrollbars = scrollbars )
| 0 |
python ttk scrollbar change disabled color
|
This callback is invoked when the user checks the Use Scrollbars box in the preferences pane .
|
cosqa-train-16324
|
def set_scrollbars_cb(self, w, tf):
"""This callback is invoked when the user checks the 'Use Scrollbars'
box in the preferences pane."""
scrollbars = 'on' if tf else 'off'
self.t_.set(scrollbars=scrollbars)
|
def install_from_zip ( url ) : fname = 'tmp.zip' downlad_file ( url , fname ) unzip_file ( fname ) print ( "Removing {}" . format ( fname ) ) os . unlink ( fname )
| 1 |
how to unzip file from url using python
|
Download and unzip from url .
|
cosqa-train-16325
|
def install_from_zip(url):
"""Download and unzip from url."""
fname = 'tmp.zip'
downlad_file(url, fname)
unzip_file(fname)
print("Removing {}".format(fname))
os.unlink(fname)
|
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.' )
| 0 |
python tuple must be str, not tuple shape
|
Check if arguments are tuple type .
|
cosqa-train-16326
|
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 min_values ( args ) : return Interval ( min ( x . low for x in args ) , min ( x . high for x in args ) )
| 0 |
how to use a code to use python's range function without using range
|
Return possible range for min function .
|
cosqa-train-16327
|
def min_values(args):
""" Return possible range for min function. """
return Interval(min(x.low for x in args), min(x.high for x in args))
|
def md_to_text ( content ) : text = None html = markdown . markdown ( content ) if html : text = html_to_text ( content ) return text
| 0 |
python turn a text file into a markdown fiel
|
Converts markdown content to text
|
cosqa-train-16328
|
def md_to_text(content):
""" Converts markdown content to text """
text = None
html = markdown.markdown(content)
if html:
text = html_to_text(content)
return text
|
def unit_ball_L2 ( shape ) : x = tf . Variable ( tf . zeros ( shape ) ) return constrain_L2 ( x )
| 1 |
how to use a tensorflow model in python
|
A tensorflow variable tranfomed to be constrained in a L2 unit ball .
|
cosqa-train-16329
|
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 list_of_dict ( self ) : ret = [ ] for row in self : ret . append ( dict ( [ ( self . _col_names [ i ] , row [ i ] ) for i in range ( len ( self . _col_names ) ) ] ) ) return ReprListDict ( ret , col_names = self . _col_names , col_types = self . _col_types , width_limit = self . _width_limit , digits = self . _digits , convert_unicode = self . _convert_unicode )
| 0 |
python turn resylts of query to dictionary
|
This will convert the data from a list of list to a list of dictionary : return : list of dict
|
cosqa-train-16330
|
def list_of_dict(self):
"""
This will convert the data from a list of list to a list of dictionary
:return: list of dict
"""
ret = []
for row in self:
ret.append(dict([(self._col_names[i], row[i]) for i in
range(len(self._col_names))]))
return ReprListDict(ret, col_names=self._col_names,
col_types=self._col_types,
width_limit=self._width_limit,
digits=self._digits,
convert_unicode=self._convert_unicode)
|
def copy_and_update ( dictionary , update ) : newdict = dictionary . copy ( ) newdict . update ( update ) return newdict
| 0 |
how to use dictionary to replace in python
|
Returns an updated copy of the dictionary without modifying the original
|
cosqa-train-16331
|
def copy_and_update(dictionary, update):
"""Returns an updated copy of the dictionary without modifying the original"""
newdict = dictionary.copy()
newdict.update(update)
return newdict
|
def uri_to_iri_parts ( path , query , fragment ) : path = url_unquote ( path , '%/;?' ) query = url_unquote ( query , '%;/?:@&=+,$#' ) fragment = url_unquote ( fragment , '%;/?:@&=+,$#' ) return path , query , fragment
| 1 |
python turn string into uri format
|
r Converts a URI parts to corresponding IRI parts in a given charset .
|
cosqa-train-16332
|
def uri_to_iri_parts(path, query, fragment):
r"""
Converts a URI parts to corresponding IRI parts in a given charset.
Examples for URI versus IRI:
:param path: The path of URI to convert.
:param query: The query string of URI to convert.
:param fragment: The fragment of URI to convert.
"""
path = url_unquote(path, '%/;?')
query = url_unquote(query, '%;/?:@&=+,$#')
fragment = url_unquote(fragment, '%;/?:@&=+,$#')
return path, query, fragment
|
def _help ( ) : statement = '%s%s' % ( shelp , phelp % ', ' . join ( cntx_ . keys ( ) ) ) print statement . strip ( )
| 0 |
how to use help function on method in python
|
Display both SQLAlchemy and Python help statements
|
cosqa-train-16333
|
def _help():
""" Display both SQLAlchemy and Python help statements """
statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))
print statement.strip()
|
def get_input ( input_func , input_str ) : val = input_func ( "Please enter your {0}: " . format ( input_str ) ) while not val or not len ( val . strip ( ) ) : val = input_func ( "You didn't enter a valid {0}, please try again: " . format ( input_str ) ) return val
| 0 |
how to use input fuction in strings in python
|
Get input from the user given an input function and an input string
|
cosqa-train-16334
|
def get_input(input_func, input_str):
"""
Get input from the user given an input function and an input string
"""
val = input_func("Please enter your {0}: ".format(input_str))
while not val or not len(val.strip()):
val = input_func("You didn't enter a valid {0}, please try again: ".format(input_str))
return val
|
def check_str ( obj ) : if isinstance ( obj , str ) : return obj if isinstance ( obj , float ) : return str ( int ( obj ) ) else : return str ( obj )
| 0 |
python type casting into strng
|
Returns a string for various input types
|
cosqa-train-16335
|
def check_str(obj):
""" Returns a string for various input types """
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj)
|
def str2int ( string_with_int ) : return int ( "" . join ( [ char for char in string_with_int if char in string . digits ] ) or 0 )
| 0 |
how to use isdigit to pick out numbers in a string python
|
Collect digits from a string
|
cosqa-train-16336
|
def str2int(string_with_int):
""" Collect digits from a string """
return int("".join([char for char in string_with_int if char in string.digits]) or 0)
|
def parse_parameter ( value ) : if any ( ( isinstance ( value , float ) , isinstance ( value , int ) , isinstance ( value , bool ) ) ) : return value try : return int ( value ) except ValueError : try : return float ( value ) except ValueError : if value in string_aliases . true_boolean_aliases : return True elif value in string_aliases . false_boolean_aliases : return False else : return str ( value )
| 0 |
python type hinting optional value
|
cosqa-train-16337
|
def parse_parameter(value):
"""
@return: The best approximation of a type of the given value.
"""
if any((isinstance(value, float), isinstance(value, int), isinstance(value, bool))):
return value
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
if value in string_aliases.true_boolean_aliases:
return True
elif value in string_aliases.false_boolean_aliases:
return False
else:
return str(value)
|
|
def notin ( arg , values ) : op = ops . NotContains ( arg , values ) return op . to_expr ( )
| 0 |
how to use isin and notin in python
|
Like isin but checks whether this expression s value ( s ) are not contained in the passed values . See isin docs for full usage .
|
cosqa-train-16338
|
def notin(arg, values):
"""
Like isin, but checks whether this expression's value(s) are not
contained in the passed values. See isin docs for full usage.
"""
op = ops.NotContains(arg, values)
return op.to_expr()
|
def is_timestamp ( instance ) : if not isinstance ( instance , ( int , str ) ) : return True return datetime . fromtimestamp ( int ( instance ) )
| 0 |
python type is not datetime
|
Validates data is a timestamp
|
cosqa-train-16339
|
def is_timestamp(instance):
"""Validates data is a timestamp"""
if not isinstance(instance, (int, str)):
return True
return datetime.fromtimestamp(int(instance))
|
def HttpResponse401 ( request , template = KEY_AUTH_401_TEMPLATE , content = KEY_AUTH_401_CONTENT , content_type = KEY_AUTH_401_CONTENT_TYPE ) : return AccessFailedResponse ( request , template , content , content_type , status = 401 )
| 1 |
how to use python request for 401 error
|
HTTP response for not - authorized access ( status code 403 )
|
cosqa-train-16340
|
def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,
content=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):
"""
HTTP response for not-authorized access (status code 403)
"""
return AccessFailedResponse(request, template, content, content_type, status=401)
|
def subscribe ( self , handler ) : assert callable ( handler ) , "Invalid handler %s" % handler self . handlers . append ( handler )
| 0 |
python unable to add handler
|
Adds a new event handler .
|
cosqa-train-16341
|
def subscribe(self, handler):
"""Adds a new event handler."""
assert callable(handler), "Invalid handler %s" % handler
self.handlers.append(handler)
|
def get_page_text ( self , page ) : url = self . get_page_text_url ( page ) return self . _get_url ( url )
| 0 |
how to use requests in python to get the text of a page
|
Downloads and returns the full text of a particular page in the document .
|
cosqa-train-16342
|
def get_page_text(self, page):
"""
Downloads and returns the full text of a particular page
in the document.
"""
url = self.get_page_text_url(page)
return self._get_url(url)
|
def get_form_bound_field ( form , field_name ) : field = form . fields [ field_name ] field = field . get_bound_field ( form , field_name ) return field
| 0 |
python unboundfield bind to form
|
Intends to get the bound field from the form regarding the field name
|
cosqa-train-16343
|
def get_form_bound_field(form, field_name):
"""
Intends to get the bound field from the form regarding the field name
:param form: Django Form: django form instance
:param field_name: str: name of the field in form instance
:return: Django Form bound field
"""
field = form.fields[field_name]
field = field.get_bound_field(form, field_name)
return field
|
def set_scrollregion ( self , event = None ) : self . canvas . configure ( scrollregion = self . canvas . bbox ( 'all' ) )
| 0 |
how to use scrollbar in canvas using python
|
Set the scroll region on the canvas
|
cosqa-train-16344
|
def set_scrollregion(self, event=None):
""" Set the scroll region on the canvas"""
self.canvas.configure(scrollregion=self.canvas.bbox('all'))
|
def union_overlapping ( intervals ) : disjoint_intervals = [ ] for interval in intervals : if disjoint_intervals and disjoint_intervals [ - 1 ] . overlaps ( interval ) : disjoint_intervals [ - 1 ] = disjoint_intervals [ - 1 ] . union ( interval ) else : disjoint_intervals . append ( interval ) return disjoint_intervals
| 1 |
python union of nonoverlapping intervals
|
Union any overlapping intervals in the given set .
|
cosqa-train-16345
|
def union_overlapping(intervals):
"""Union any overlapping intervals in the given set."""
disjoint_intervals = []
for interval in intervals:
if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):
disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)
else:
disjoint_intervals.append(interval)
return disjoint_intervals
|
def print_latex ( o ) : if can_print_latex ( o ) : s = latex ( o , mode = 'plain' ) s = s . replace ( '\\dag' , '\\dagger' ) s = s . strip ( '$' ) return '$$%s$$' % s # Fallback to the string printer return None
| 0 |
how to write ''or'' sympole in python
|
A function to generate the latex representation of sympy expressions .
|
cosqa-train-16346
|
def print_latex(o):
"""A function to generate the latex representation of sympy
expressions."""
if can_print_latex(o):
s = latex(o, mode='plain')
s = s.replace('\\dag','\\dagger')
s = s.strip('$')
return '$$%s$$' % s
# Fallback to the string printer
return None
|
def flatten_union ( table ) : op = table . op ( ) if isinstance ( op , ops . Union ) : return toolz . concatv ( flatten_union ( op . left ) , [ op . distinct ] , flatten_union ( op . right ) ) return [ table ]
| 1 |
python union table concat
|
Extract all union queries from table .
|
cosqa-train-16347
|
def flatten_union(table):
"""Extract all union queries from `table`.
Parameters
----------
table : TableExpr
Returns
-------
Iterable[Union[TableExpr, bool]]
"""
op = table.op()
if isinstance(op, ops.Union):
return toolz.concatv(
flatten_union(op.left), [op.distinct], flatten_union(op.right)
)
return [table]
|
def comment ( self , s , * * args ) : self . writeln ( s = u'comment "%s"' % s , * * args )
| 1 |
how to write a comment block in python
|
Write GML comment .
|
cosqa-train-16348
|
def comment (self, s, **args):
"""Write GML comment."""
self.writeln(s=u'comment "%s"' % s, **args)
|
def page_title ( step , title ) : with AssertContextManager ( step ) : assert_equals ( world . browser . title , title )
| 0 |
python unit test assert html response
|
Check that the page title matches the given one .
|
cosqa-train-16349
|
def page_title(step, title):
"""
Check that the page title matches the given one.
"""
with AssertContextManager(step):
assert_equals(world.browser.title, title)
|
def setdefault ( obj , field , default ) : setattr ( obj , field , getattr ( obj , field , default ) )
| 0 |
how to write a default value in python
|
Set an object s field to default if it doesn t have a value
|
cosqa-train-16350
|
def setdefault(obj, field, default):
"""Set an object's field to default if it doesn't have a value"""
setattr(obj, field, getattr(obj, field, default))
|
def test ( ) : # pragma: no cover import pytest import os pytest . main ( [ os . path . dirname ( os . path . abspath ( __file__ ) ) ] )
| 1 |
python unit test set pythonpath
|
Execute the unit tests on an installed copy of unyt .
|
cosqa-train-16351
|
def test(): # pragma: no cover
"""Execute the unit tests on an installed copy of unyt.
Note that this function requires pytest to run. If pytest is not
installed this function will raise ImportError.
"""
import pytest
import os
pytest.main([os.path.dirname(os.path.abspath(__file__))])
|
def expect_all ( a , b ) : assert all ( _a == _b for _a , _b in zip_longest ( a , b ) )
| 1 |
python unittest how to assert 2 lists are almost equal
|
\ Asserts that two iterables contain the same values .
|
cosqa-train-16352
|
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 write_str2file ( pathname , astr ) : fname = pathname fhandle = open ( fname , 'wb' ) fhandle . write ( astr ) fhandle . close ( )
| 1 |
how to write a string to a file in python 2
|
writes a string to file
|
cosqa-train-16353
|
def write_str2file(pathname, astr):
"""writes a string to file"""
fname = pathname
fhandle = open(fname, 'wb')
fhandle.write(astr)
fhandle.close()
|
def assert_redirect ( self , response , expected_url = None ) : self . assertIn ( response . status_code , self . redirect_codes , self . _get_redirect_assertion_message ( response ) , ) if expected_url : location_header = response . _headers . get ( 'location' , None ) self . assertEqual ( location_header , ( 'Location' , str ( expected_url ) ) , 'Response should redirect to {0}, but it redirects to {1} instead' . format ( expected_url , location_header [ 1 ] , ) )
| 0 |
python unittest redirect assert failure
|
assertRedirects from Django TestCase follows the redirects chains this assertion does not - which is more like real unit testing
|
cosqa-train-16354
|
def assert_redirect(self, response, expected_url=None):
"""
assertRedirects from Django TestCase follows the redirects chains,
this assertion does not - which is more like real unit testing
"""
self.assertIn(
response.status_code,
self.redirect_codes,
self._get_redirect_assertion_message(response),
)
if expected_url:
location_header = response._headers.get('location', None)
self.assertEqual(
location_header,
('Location', str(expected_url)),
'Response should redirect to {0}, but it redirects to {1} instead'.format(
expected_url,
location_header[1],
)
)
|
def _write_separator ( self ) : tmp = self . _page_width - ( ( 4 * self . __indent_level ) + 2 ) self . _write_line ( '# ' + ( '-' * tmp ) )
| 0 |
how to write on a new line in pythone
|
Inserts a horizontal ( commented ) line tot the generated code .
|
cosqa-train-16355
|
def _write_separator(self):
"""
Inserts a horizontal (commented) line tot the generated code.
"""
tmp = self._page_width - ((4 * self.__indent_level) + 2)
self._write_line('# ' + ('-' * tmp))
|
def __unixify ( self , s ) : return os . path . normpath ( s ) . replace ( os . sep , "/" )
| 0 |
python unixpath names on windows
|
stupid windows . converts the backslash to forwardslash for consistency
|
cosqa-train-16356
|
def __unixify(self, s):
""" stupid windows. converts the backslash to forwardslash for consistency """
return os.path.normpath(s).replace(os.sep, "/")
|
def convert_array ( array ) : out = io . BytesIO ( array ) out . seek ( 0 ) return np . load ( out )
| 0 |
python unpack bytes to numpy
|
Converts an ARRAY string stored in the database back into a Numpy array .
|
cosqa-train-16357
|
def convert_array(array):
"""
Converts an ARRAY string stored in the database back into a Numpy array.
Parameters
----------
array: ARRAY
The array object to be converted back into a Numpy array.
Returns
-------
array
The converted Numpy array.
"""
out = io.BytesIO(array)
out.seek(0)
return np.load(out)
|
def save_excel ( self , fd ) : from pylon . io . excel import ExcelWriter ExcelWriter ( self ) . write ( fd )
| 0 |
how we can save python out put in excel file
|
Saves the case as an Excel spreadsheet .
|
cosqa-train-16358
|
def save_excel(self, fd):
""" Saves the case as an Excel spreadsheet.
"""
from pylon.io.excel import ExcelWriter
ExcelWriter(self).write(fd)
|
def _keys_to_camel_case ( self , obj ) : return dict ( ( to_camel_case ( key ) , value ) for ( key , value ) in obj . items ( ) )
| 0 |
python upcase entire dictionary
|
Make a copy of a dictionary with all keys converted to camel case . This is just calls to_camel_case on each of the keys in the dictionary and returns a new dictionary .
|
cosqa-train-16359
|
def _keys_to_camel_case(self, obj):
"""
Make a copy of a dictionary with all keys converted to camel case. This is just calls to_camel_case on each of the keys in the dictionary and returns a new dictionary.
:param obj: Dictionary to convert keys to camel case.
:return: Dictionary with the input values and all keys in camel case
"""
return dict((to_camel_case(key), value) for (key, value) in obj.items())
|
def top ( n , width = WIDTH , style = STYLE ) : return hrule ( n , width , linestyle = STYLES [ style ] . top )
| 0 |
html table borders using python
|
Prints the top row of a table
|
cosqa-train-16360
|
def top(n, width=WIDTH, style=STYLE):
"""Prints the top row of a table"""
return hrule(n, width, linestyle=STYLES[style].top)
|
def set_global ( node : Node , key : str , value : Any ) : node . node_globals [ key ] = value
| 1 |
python update a global variable from a def
|
Adds passed value to node s globals
|
cosqa-train-16361
|
def set_global(node: Node, key: str, value: Any):
"""Adds passed value to node's globals"""
node.node_globals[key] = value
|
def handle_exception ( error ) : response = jsonify ( error . to_dict ( ) ) response . status_code = error . status_code return response
| 1 |
hwo to return 400 in python flask
|
Simple method for handling exceptions raised by PyBankID .
|
cosqa-train-16362
|
def handle_exception(error):
"""Simple method for handling exceptions raised by `PyBankID`.
:param flask_pybankid.FlaskPyBankIDError error: The exception to handle.
:return: The exception represented as a dictionary.
:rtype: dict
"""
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
|
def update_context ( self , ctx ) : assert isinstance ( ctx , dict ) ctx [ str ( self . context_id ) ] = self . value
| 1 |
python update context with a dict
|
updates the query context with this clauses values
|
cosqa-train-16363
|
def update_context(self, ctx):
""" updates the query context with this clauses values """
assert isinstance(ctx, dict)
ctx[str(self.context_id)] = self.value
|
def get_encoding ( binary ) : try : from chardet import detect except ImportError : LOGGER . error ( "Please install the 'chardet' module" ) sys . exit ( 1 ) encoding = detect ( binary ) . get ( 'encoding' ) return 'iso-8859-1' if encoding == 'CP949' else encoding
| 0 |
identify encoding type python
|
Return the encoding type .
|
cosqa-train-16364
|
def get_encoding(binary):
"""Return the encoding type."""
try:
from chardet import detect
except ImportError:
LOGGER.error("Please install the 'chardet' module")
sys.exit(1)
encoding = detect(binary).get('encoding')
return 'iso-8859-1' if encoding == 'CP949' else encoding
|
def get_url_args ( url ) : url_data = urllib . parse . urlparse ( url ) arg_dict = urllib . parse . parse_qs ( url_data . query ) return arg_dict
| 1 |
python urlparse query paramters
|
Returns a dictionary from a URL params
|
cosqa-train-16365
|
def get_url_args(url):
""" Returns a dictionary from a URL params """
url_data = urllib.parse.urlparse(url)
arg_dict = urllib.parse.parse_qs(url_data.query)
return arg_dict
|
def clear_list_value ( self , value ) : # Don't go any further: this value is empty. if not value : return self . empty_value # Clean empty items if wanted if self . clean_empty : value = [ v for v in value if v ] return value or self . empty_value
| 0 |
if a value in python is empty
|
Clean the argument value to eliminate None or Falsy values if needed .
|
cosqa-train-16366
|
def clear_list_value(self, value):
"""
Clean the argument value to eliminate None or Falsy values if needed.
"""
# Don't go any further: this value is empty.
if not value:
return self.empty_value
# Clean empty items if wanted
if self.clean_empty:
value = [v for v in value if v]
return value or self.empty_value
|
def get_url_file_name ( url ) : assert isinstance ( url , ( str , _oldstr ) ) return urlparse . urlparse ( url ) . path . split ( '/' ) [ - 1 ]
| 0 |
python urlretrieve file name
|
Get the file name from an url Parameters ---------- url : str
|
cosqa-train-16367
|
def get_url_file_name(url):
"""Get the file name from an url
Parameters
----------
url : str
Returns
-------
str
The file name
"""
assert isinstance(url, (str, _oldstr))
return urlparse.urlparse(url).path.split('/')[-1]
|
def table_exists ( cursor , tablename , schema = 'public' ) : query = """
SELECT EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_schema = %s
AND table_name = %s
)""" cursor . execute ( query , ( schema , tablename ) ) res = cursor . fetchone ( ) [ 0 ] return res
| 1 |
if table exists python
|
cosqa-train-16368
|
def table_exists(cursor, tablename, schema='public'):
query = """
SELECT EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_schema = %s
AND table_name = %s
)"""
cursor.execute(query, (schema, tablename))
res = cursor.fetchone()[0]
return res
|
|
def _fill_array_from_list ( the_list , the_array ) : for i , val in enumerate ( the_list ) : the_array [ i ] = val return the_array
| 1 |
python use a function to fill a list
|
Fill an array from a list
|
cosqa-train-16369
|
def _fill_array_from_list(the_list, the_array):
"""Fill an `array` from a `list`"""
for i, val in enumerate(the_list):
the_array[i] = val
return the_array
|
def isString ( s ) : try : return isinstance ( s , unicode ) or isinstance ( s , basestring ) except NameError : return isinstance ( s , str )
| 1 |
if type is str python
|
Convenience method that works with all 2 . x versions of Python to determine whether or not something is stringlike .
|
cosqa-train-16370
|
def isString(s):
"""Convenience method that works with all 2.x versions of Python
to determine whether or not something is stringlike."""
try:
return isinstance(s, unicode) or isinstance(s, basestring)
except NameError:
return isinstance(s, str)
|
def list_formatter ( handler , item , value ) : return u', ' . join ( str ( v ) for v in value )
| 1 |
python use format string with list
|
Format list .
|
cosqa-train-16371
|
def list_formatter(handler, item, value):
"""Format list."""
return u', '.join(str(v) for v in value)
|
def average_gradient ( data , * kwargs ) : return np . average ( np . array ( np . gradient ( data ) ) ** 2 )
| 1 |
image calculate the gradient value python
|
Compute average gradient norm of an image
|
cosqa-train-16372
|
def average_gradient(data, *kwargs):
""" Compute average gradient norm of an image
"""
return np.average(np.array(np.gradient(data))**2)
|
def dfs_recursive ( graph , node , seen ) : seen [ node ] = True for neighbor in graph [ node ] : if not seen [ neighbor ] : dfs_recursive ( graph , neighbor , seen )
| 1 |
implement dfs recursive python
|
DFS detect connected component recursive implementation
|
cosqa-train-16373
|
def dfs_recursive(graph, node, seen):
"""DFS, detect connected component, recursive implementation
:param graph: directed graph in listlist or listdict format
:param int node: to start graph exploration
:param boolean-table seen: will be set true for the connected component
containing node.
:complexity: `O(|V|+|E|)`
"""
seen[node] = True
for neighbor in graph[node]:
if not seen[neighbor]:
dfs_recursive(graph, neighbor, seen)
|
def Proxy ( f ) : def Wrapped ( self , * args ) : return getattr ( self , f ) ( * args ) return Wrapped
| 1 |
python useless super delegation in method
|
A helper to create a proxy method in a class .
|
cosqa-train-16374
|
def Proxy(f):
"""A helper to create a proxy method in a class."""
def Wrapped(self, *args):
return getattr(self, f)(*args)
return Wrapped
|
def bbox ( self ) : return BoundingBox ( self . slices [ 1 ] . start , self . slices [ 1 ] . stop , self . slices [ 0 ] . start , self . slices [ 0 ] . stop )
| 0 |
imshow bounding box python
|
The minimal ~photutils . aperture . BoundingBox for the cutout region with respect to the original ( large ) image .
|
cosqa-train-16375
|
def bbox(self):
"""
The minimal `~photutils.aperture.BoundingBox` for the cutout
region with respect to the original (large) image.
"""
return BoundingBox(self.slices[1].start, self.slices[1].stop,
self.slices[0].start, self.slices[0].stop)
|
def prompt ( * args , * * kwargs ) : try : return click . prompt ( * args , * * kwargs ) except click . Abort : return False
| 0 |
python user meaningful prompts
|
Prompt the user for input and handle any abort exceptions .
|
cosqa-train-16376
|
def prompt(*args, **kwargs):
"""Prompt the user for input and handle any abort exceptions."""
try:
return click.prompt(*args, **kwargs)
except click.Abort:
return False
|
def find_one ( cls , * args , * * kw ) : if len ( args ) == 1 and not isinstance ( args [ 0 ] , Filter ) : args = ( getattr ( cls , cls . __pk__ ) == args [ 0 ] , ) Doc , collection , query , options = cls . _prepare_find ( * args , * * kw ) result = Doc . from_mongo ( collection . find_one ( query , * * options ) ) return result
| 0 |
in mongodb to retrieve from particular document using python
|
Get a single document from the collection this class is bound to . Additional arguments are processed according to _prepare_find prior to passing to PyMongo where positional parameters are interpreted as query fragments parametric keyword arguments combined and other keyword arguments passed along with minor transformation . Automatically calls to_mongo with the retrieved data . https : // api . mongodb . com / python / current / api / pymongo / collection . html#pymongo . collection . Collection . find_one
|
cosqa-train-16377
|
def find_one(cls, *args, **kw):
"""Get a single document from the collection this class is bound to.
Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional
parameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword
arguments passed along with minor transformation.
Automatically calls `to_mongo` with the retrieved data.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one
"""
if len(args) == 1 and not isinstance(args[0], Filter):
args = (getattr(cls, cls.__pk__) == args[0], )
Doc, collection, query, options = cls._prepare_find(*args, **kw)
result = Doc.from_mongo(collection.find_one(query, **options))
return result
|
def generate_user_token ( self , user , salt = None ) : return self . token_serializer . dumps ( str ( user . id ) , salt = salt )
| 0 |
python using uuid as user token
|
Generates a unique token associated to the user
|
cosqa-train-16378
|
def generate_user_token(self, user, salt=None):
"""Generates a unique token associated to the user
"""
return self.token_serializer.dumps(str(user.id), salt=salt)
|
def exp_fit_fun ( x , a , tau , c ) : # pylint: disable=invalid-name return a * np . exp ( - x / tau ) + c
| 1 |
in python fit an exponential
|
Function used to fit the exponential decay .
|
cosqa-train-16379
|
def exp_fit_fun(x, a, tau, c):
"""Function used to fit the exponential decay."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) + c
|
def random_string ( string_length = 10 ) : random = str ( uuid . uuid4 ( ) ) # Convert UUID format to a Python string. random = random . upper ( ) # Make all characters uppercase. random = random . replace ( "-" , "" ) # Remove the UUID '-'. return random [ 0 : string_length ]
| 1 |
python uuid fixed length
|
Returns a random string of length string_length .
|
cosqa-train-16380
|
def random_string(string_length=10):
"""Returns a random string of length string_length."""
random = str(uuid.uuid4()) # Convert UUID format to a Python string.
random = random.upper() # Make all characters uppercase.
random = random.replace("-", "") # Remove the UUID '-'.
return random[0:string_length]
|
def end_index ( self ) : return ( ( self . number - 1 ) * self . paginator . per_page + len ( self . object_list ) )
| 0 |
in python for loop include the last item
|
Returns the 1 - based index of the last object on this page relative to total objects found ( hits ) .
|
cosqa-train-16381
|
def end_index(self):
"""
Returns the 1-based index of the last object on this page,
relative to total objects found (hits).
"""
return ((self.number - 1) * self.paginator.per_page +
len(self.object_list))
|
def bool_str ( string ) : if string not in BOOL_STRS : raise ValueError ( 'Invalid boolean string: "{}"' . format ( string ) ) return True if string == 'true' else False
| 1 |
python validate boolean string
|
Returns a boolean from a string imput of true or false
|
cosqa-train-16382
|
def bool_str(string):
"""Returns a boolean from a string imput of 'true' or 'false'"""
if string not in BOOL_STRS:
raise ValueError('Invalid boolean string: "{}"'.format(string))
return True if string == 'true' else False
|
def quote ( self , s ) : if six . PY2 : from pipes import quote else : from shlex import quote return quote ( s )
| 0 |
include single quotes in string python
|
Return a shell - escaped version of the string s .
|
cosqa-train-16383
|
def quote(self, s):
"""Return a shell-escaped version of the string s."""
if six.PY2:
from pipes import quote
else:
from shlex import quote
return quote(s)
|
def is_valid ( data ) : return bool ( data ) and isinstance ( data , dict ) and bool ( data . get ( "swagger" ) ) and isinstance ( data . get ( 'paths' ) , dict )
| 1 |
python validate dict is json
|
Checks if the input data is a Swagger document
|
cosqa-train-16384
|
def is_valid(data):
"""
Checks if the input data is a Swagger document
:param dict data: Data to be validated
:return: True, if data is a Swagger
"""
return bool(data) and \
isinstance(data, dict) and \
bool(data.get("swagger")) and \
isinstance(data.get('paths'), dict)
|
def ynticks ( self , nticks , index = 1 ) : self . layout [ 'yaxis' + str ( index ) ] [ 'nticks' ] = nticks return self
| 0 |
increase number of axis ticks python
|
Set the number of ticks .
|
cosqa-train-16385
|
def ynticks(self, nticks, index=1):
"""Set the number of ticks."""
self.layout['yaxis' + str(index)]['nticks'] = nticks
return self
|
def __len__ ( self ) : length = 0 for typ , siz , _ in self . format : length += siz return length
| 1 |
python variable for format length
|
This will equal 124 for the V1 database .
|
cosqa-train-16386
|
def __len__(self):
""" This will equal 124 for the V1 database. """
length = 0
for typ, siz, _ in self.format:
length += siz
return length
|
def _set_lastpage ( self ) : self . last_page = ( len ( self . _page_data ) - 1 ) // self . screen . page_size
| 0 |
increase page num python
|
Calculate value of class attribute last_page .
|
cosqa-train-16387
|
def _set_lastpage(self):
"""Calculate value of class attribute ``last_page``."""
self.last_page = (len(self._page_data) - 1) // self.screen.page_size
|
def venv ( ) : try : import virtualenv # NOQA except ImportError : sh ( "%s -m pip install virtualenv" % PYTHON ) if not os . path . isdir ( "venv" ) : sh ( "%s -m virtualenv venv" % PYTHON ) sh ( "venv\\Scripts\\pip install -r %s" % ( REQUIREMENTS_TXT ) )
| 0 |
python venv no directory created
|
Install venv + deps .
|
cosqa-train-16388
|
def venv():
"""Install venv + deps."""
try:
import virtualenv # NOQA
except ImportError:
sh("%s -m pip install virtualenv" % PYTHON)
if not os.path.isdir("venv"):
sh("%s -m virtualenv venv" % PYTHON)
sh("venv\\Scripts\\pip install -r %s" % (REQUIREMENTS_TXT))
|
def ServerLoggingStartupInit ( ) : global LOGGER if local_log : logging . debug ( "Using local LogInit from %s" , local_log ) local_log . LogInit ( ) logging . debug ( "Using local AppLogInit from %s" , local_log ) LOGGER = local_log . AppLogInit ( ) else : LogInit ( ) LOGGER = AppLogInit ( )
| 0 |
initialize logger on start up python
|
Initialize the server logging configuration .
|
cosqa-train-16389
|
def ServerLoggingStartupInit():
"""Initialize the server logging configuration."""
global LOGGER
if local_log:
logging.debug("Using local LogInit from %s", local_log)
local_log.LogInit()
logging.debug("Using local AppLogInit from %s", local_log)
LOGGER = local_log.AppLogInit()
else:
LogInit()
LOGGER = AppLogInit()
|
def init ( ) : print ( yellow ( "# Setting up environment...\n" , True ) ) virtualenv . init ( ) virtualenv . update_requirements ( ) print ( green ( "\n# DONE." , True ) ) print ( green ( "Type " ) + green ( "activate" , True ) + green ( " to enable your virtual environment." ) )
| 0 |
python virtualenv production how to activate
|
Execute init tasks for all components ( virtualenv pip ) .
|
cosqa-train-16390
|
def init():
"""
Execute init tasks for all components (virtualenv, pip).
"""
print(yellow("# Setting up environment...\n", True))
virtualenv.init()
virtualenv.update_requirements()
print(green("\n# DONE.", True))
print(green("Type ") + green("activate", True) + green(" to enable your virtual environment."))
|
def _py2_and_3_joiner ( sep , joinable ) : if ISPY3 : sep = bytes ( sep , DEFAULT_ENCODING ) joined = sep . join ( joinable ) return joined . decode ( DEFAULT_ENCODING ) if ISPY3 else joined
| 0 |
inner join on str in python
|
Allow \ n . join ( ... ) statements to work in Py2 and Py3 . : param sep : : param joinable : : return :
|
cosqa-train-16391
|
def _py2_and_3_joiner(sep, joinable):
"""
Allow '\n'.join(...) statements to work in Py2 and Py3.
:param sep:
:param joinable:
:return:
"""
if ISPY3:
sep = bytes(sep, DEFAULT_ENCODING)
joined = sep.join(joinable)
return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined
|
def csort ( objs , key ) : idxs = dict ( ( obj , i ) for ( i , obj ) in enumerate ( objs ) ) return sorted ( objs , key = lambda obj : ( key ( obj ) , idxs [ obj ] ) )
| 0 |
python way to sort based on object dictionary
|
Order - preserving sorting function .
|
cosqa-train-16392
|
def csort(objs, key):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))
|
def put_text ( self , key , text ) : with open ( key , "w" ) as fh : fh . write ( text )
| 0 |
insert a key to file in python
|
Put the text into the storage associated with the key .
|
cosqa-train-16393
|
def put_text(self, key, text):
"""Put the text into the storage associated with the key."""
with open(key, "w") as fh:
fh.write(text)
|
def destroy_webdriver ( driver ) : # This is some very flaky code in selenium. Hence the retries # and catch-all exceptions try : retry_call ( driver . close , tries = 2 ) except Exception : pass try : driver . quit ( ) except Exception : pass
| 0 |
python webdriver ie unexpectedly exited 2
|
Destroy a driver
|
cosqa-train-16394
|
def destroy_webdriver(driver):
"""
Destroy a driver
"""
# This is some very flaky code in selenium. Hence the retries
# and catch-all exceptions
try:
retry_call(driver.close, tries=2)
except Exception:
pass
try:
driver.quit()
except Exception:
pass
|
def prepend_line ( filepath , line ) : with open ( filepath ) as f : lines = f . readlines ( ) lines . insert ( 0 , line ) with open ( filepath , 'w' ) as f : f . writelines ( lines )
| 0 |
insert a line at the beginning of a file python
|
Rewrite a file adding a line to its beginning .
|
cosqa-train-16395
|
def prepend_line(filepath, line):
"""Rewrite a file adding a line to its beginning.
"""
with open(filepath) as f:
lines = f.readlines()
lines.insert(0, line)
with open(filepath, 'w') as f:
f.writelines(lines)
|
def build_code ( self , lang , body ) : self . out . append ( "```" + lang ) self . build_markdown ( lang , body ) self . out . append ( "```" )
| 0 |
insert python code in markdown
|
Wrap text with markdown specific flavour .
|
cosqa-train-16396
|
def build_code(self, lang, body):
"""Wrap text with markdown specific flavour."""
self.out.append("```" + lang)
self.build_markdown(lang, body)
self.out.append("```")
|
def check_by_selector ( self , selector ) : elem = find_element_by_jquery ( world . browser , selector ) if not elem . is_selected ( ) : elem . click ( )
| 0 |
python webelement checkbox ischecked
|
Check the checkbox matching the CSS selector .
|
cosqa-train-16397
|
def check_by_selector(self, selector):
"""Check the checkbox matching the CSS selector."""
elem = find_element_by_jquery(world.browser, selector)
if not elem.is_selected():
elem.click()
|
def IPYTHON_MAIN ( ) : import pkg_resources runner_frame = inspect . getouterframes ( inspect . currentframe ( ) ) [ - 2 ] return ( getattr ( runner_frame , "function" , None ) == pkg_resources . load_entry_point ( "ipython" , "console_scripts" , "ipython" ) . __name__ )
| 0 |
ironpython python script global name not defined
|
Decide if the Ipython command line is running code .
|
cosqa-train-16398
|
def IPYTHON_MAIN():
"""Decide if the Ipython command line is running code."""
import pkg_resources
runner_frame = inspect.getouterframes(inspect.currentframe())[-2]
return (
getattr(runner_frame, "function", None)
== pkg_resources.load_entry_point("ipython", "console_scripts", "ipython").__name__
)
|
def _checkSize ( self ) : if self . _item_height is not None : sz = min ( self . _max_height_items , self . count ( ) ) * self . _item_height + 5 sz = max ( sz , 20 ) self . setMinimumSize ( 0 , sz ) self . setMaximumSize ( 1000000 , sz ) self . resize ( self . width ( ) , sz )
| 1 |
python widget maximum dimensions
|
Automatically resizes widget to display at most max_height_items items
|
cosqa-train-16399
|
def _checkSize(self):
"""Automatically resizes widget to display at most max_height_items items"""
if self._item_height is not None:
sz = min(self._max_height_items, self.count()) * self._item_height + 5
sz = max(sz, 20)
self.setMinimumSize(0, sz)
self.setMaximumSize(1000000, sz)
self.resize(self.width(), sz)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.