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 add ( self , entity ) : result = self . _http_req ( 'connections' , method = 'POST' , payload = entity ) status = result [ 'status' ] if not status == 201 : raise ServiceRegistryError ( status , "Couldn't add entity" ) self . debug ( 0x01 , result ) return result [ 'decoded' ]
| 1 |
code python add entity function
|
Adds the supplied dict as a new entity
|
cosqa-train-15100
|
def add(self, entity):
"""
Adds the supplied dict as a new entity
"""
result = self._http_req('connections', method='POST', payload=entity)
status = result['status']
if not status==201:
raise ServiceRegistryError(status,"Couldn't add entity")
self.debug(0x01,result)
return result['decoded']
|
def polyline ( self , arr ) : for i in range ( 0 , len ( arr ) - 1 ) : self . line ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] , arr [ i + 1 ] [ 0 ] , arr [ i + 1 ] [ 1 ] )
| 1 |
python draw line through 2d array
|
Draw a set of lines
|
cosqa-train-15101
|
def polyline(self, arr):
"""Draw a set of lines"""
for i in range(0, len(arr) - 1):
self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1])
|
def accel_next ( self , * args ) : if self . get_notebook ( ) . get_current_page ( ) + 1 == self . get_notebook ( ) . get_n_pages ( ) : self . get_notebook ( ) . set_current_page ( 0 ) else : self . get_notebook ( ) . next_page ( ) return True
| 1 |
code to go to the next key without for loop python
|
Callback to go to the next tab . Called by the accel key .
|
cosqa-train-15102
|
def accel_next(self, *args):
"""Callback to go to the next tab. Called by the accel key.
"""
if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():
self.get_notebook().set_current_page(0)
else:
self.get_notebook().next_page()
return True
|
def safe_dump ( data , stream = None , * * kwds ) : return yaml . dump ( data , stream = stream , Dumper = ODYD , * * kwds )
| 0 |
python dump dict yaml not
|
implementation of safe dumper using Ordered Dict Yaml Dumper
|
cosqa-train-15103
|
def safe_dump(data, stream=None, **kwds):
"""implementation of safe dumper using Ordered Dict Yaml Dumper"""
return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)
|
def flatten_list ( l ) : return list ( chain . from_iterable ( repeat ( x , 1 ) if isinstance ( x , str ) else x for x in l ) )
| 0 |
combine python lists into a new list
|
Nested lists to single - level list does not split strings
|
cosqa-train-15104
|
def flatten_list(l):
""" Nested lists to single-level list, does not split strings"""
return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l))
|
def display_pil_image ( im ) : from IPython . core import display b = BytesIO ( ) im . save ( b , format = 'png' ) data = b . getvalue ( ) ip_img = display . Image ( data = data , format = 'png' , embed = True ) return ip_img . _repr_png_ ( )
| 1 |
python dynamic image display
|
Displayhook function for PIL Images rendered as PNG .
|
cosqa-train-15105
|
def display_pil_image(im):
"""Displayhook function for PIL Images, rendered as PNG."""
from IPython.core import display
b = BytesIO()
im.save(b, format='png')
data = b.getvalue()
ip_img = display.Image(data=data, format='png', embed=True)
return ip_img._repr_png_()
|
def process_docstring ( app , what , name , obj , options , lines ) : # pylint: disable=unused-argument # pylint: disable=too-many-arguments lines . extend ( _format_contracts ( what = what , obj = obj ) )
| 0 |
combine raw and docstring in python
|
React to a docstring event and append contracts to it .
|
cosqa-train-15106
|
def process_docstring(app, what, name, obj, options, lines):
"""React to a docstring event and append contracts to it."""
# pylint: disable=unused-argument
# pylint: disable=too-many-arguments
lines.extend(_format_contracts(what=what, obj=obj))
|
def load_member ( fqn ) : modulename , member_name = split_fqn ( fqn ) module = __import__ ( modulename , globals ( ) , locals ( ) , member_name ) return getattr ( module , member_name )
| 1 |
python dynamicly load a method from another python file
|
Loads and returns a class for a given fully qualified name .
|
cosqa-train-15107
|
def load_member(fqn):
"""Loads and returns a class for a given fully qualified name."""
modulename, member_name = split_fqn(fqn)
module = __import__(modulename, globals(), locals(), member_name)
return getattr(module, member_name)
|
def camel_to_underscore ( string ) : string = FIRST_CAP_RE . sub ( r'\1_\2' , string ) return ALL_CAP_RE . sub ( r'\1_\2' , string ) . lower ( )
| 1 |
common double underscore methods in python
|
Convert camelcase to lowercase and underscore .
|
cosqa-train-15108
|
def camel_to_underscore(string):
"""Convert camelcase to lowercase and underscore.
Recipe from http://stackoverflow.com/a/1176023
Args:
string (str): The string to convert.
Returns:
str: The converted string.
"""
string = FIRST_CAP_RE.sub(r'\1_\2', string)
return ALL_CAP_RE.sub(r'\1_\2', string).lower()
|
def encode_list ( dynamizer , value ) : encoded_list = [ ] dict ( map ( dynamizer . raw_encode , value ) ) for v in value : encoded_type , encoded_value = dynamizer . raw_encode ( v ) encoded_list . append ( { encoded_type : encoded_value , } ) return 'L' , encoded_list
| 0 |
python dynamo output list of lists
|
Encode a list for the DynamoDB format
|
cosqa-train-15109
|
def encode_list(dynamizer, value):
""" Encode a list for the DynamoDB format """
encoded_list = []
dict(map(dynamizer.raw_encode, value))
for v in value:
encoded_type, encoded_value = dynamizer.raw_encode(v)
encoded_list.append({
encoded_type: encoded_value,
})
return 'L', encoded_list
|
def basic_word_sim ( word1 , word2 ) : return sum ( [ 1 for c in word1 if c in word2 ] ) / max ( len ( word1 ) , len ( word2 ) )
| 1 |
compare single words for similarity python
|
Simple measure of similarity : Number of letters in common / max length
|
cosqa-train-15110
|
def basic_word_sim(word1, word2):
"""
Simple measure of similarity: Number of letters in common / max length
"""
return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))
|
def datetime_to_ms ( dt ) : seconds = calendar . timegm ( dt . utctimetuple ( ) ) return seconds * 1000 + int ( dt . microsecond / 1000 )
| 0 |
python elapsed time using datetime in minutes
|
Converts a datetime to a millisecond accuracy timestamp
|
cosqa-train-15111
|
def datetime_to_ms(dt):
"""
Converts a datetime to a millisecond accuracy timestamp
"""
seconds = calendar.timegm(dt.utctimetuple())
return seconds * 1000 + int(dt.microsecond / 1000)
|
def intersect ( d1 , d2 ) : return dict ( ( k , d1 [ k ] ) for k in d1 if k in d2 and d1 [ k ] == d2 [ k ] )
| 0 |
comparing identical keys between 2 dictionarys python then returning results
|
Intersect dictionaries d1 and d2 by key * and * value .
|
cosqa-train-15112
|
def intersect(d1, d2):
"""Intersect dictionaries d1 and d2 by key *and* value."""
return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])
|
def add_index_alias ( es , index_name , alias_name ) : es . indices . put_alias ( index = index_name , name = terms_alias )
| 1 |
python elasticsearch change index setting
|
Add index alias to index_name
|
cosqa-train-15113
|
def add_index_alias(es, index_name, alias_name):
"""Add index alias to index_name"""
es.indices.put_alias(index=index_name, name=terms_alias)
|
def compare ( string1 , string2 ) : if len ( string1 ) != len ( string2 ) : return False result = True for c1 , c2 in izip ( string1 , string2 ) : result &= c1 == c2 return result
| 1 |
comparing multiple strings in python
|
Compare two strings while protecting against timing attacks
|
cosqa-train-15114
|
def compare(string1, string2):
"""Compare two strings while protecting against timing attacks
:param str string1: the first string
:param str string2: the second string
:returns: True if the strings are equal, False if not
:rtype: :obj:`bool`
"""
if len(string1) != len(string2):
return False
result = True
for c1, c2 in izip(string1, string2):
result &= c1 == c2
return result
|
def all_documents ( index = INDEX_NAME ) : query = { 'query' : { 'match_all' : { } } } for result in raw_query ( query , index = index ) : yield result
| 1 |
python elasticsearch list indexes
|
Get all documents from the given index .
|
cosqa-train-15115
|
def all_documents(index=INDEX_NAME):
"""
Get all documents from the given index.
Returns full Elasticsearch objects so you can get metadata too.
"""
query = {
'query': {
'match_all': {}
}
}
for result in raw_query(query, index=index):
yield result
|
def is_int ( string ) : try : a = float ( string ) b = int ( a ) except ValueError : return False else : return a == b
| 0 |
comparing string and int in python
|
Checks if a string is an integer . If the string value is an integer return True otherwise return False . Args : string : a string to test .
|
cosqa-train-15116
|
def is_int(string):
"""
Checks if a string is an integer. If the string value is an integer
return True, otherwise return False.
Args:
string: a string to test.
Returns:
boolean
"""
try:
a = float(string)
b = int(a)
except ValueError:
return False
else:
return a == b
|
def all_documents ( index = INDEX_NAME ) : query = { 'query' : { 'match_all' : { } } } for result in raw_query ( query , index = index ) : yield result
| 1 |
python elasticsearch return hits
|
Get all documents from the given index .
|
cosqa-train-15117
|
def all_documents(index=INDEX_NAME):
"""
Get all documents from the given index.
Returns full Elasticsearch objects so you can get metadata too.
"""
query = {
'query': {
'match_all': {}
}
}
for result in raw_query(query, index=index):
yield result
|
def compute_ssim ( image1 , image2 , gaussian_kernel_sigma = 1.5 , gaussian_kernel_width = 11 ) : gaussian_kernel_1d = get_gaussian_kernel ( gaussian_kernel_width , gaussian_kernel_sigma ) return SSIM ( image1 , gaussian_kernel_1d ) . ssim_value ( image2 )
| 1 |
comparison of two image using python sse
|
Computes SSIM .
|
cosqa-train-15118
|
def compute_ssim(image1, image2, gaussian_kernel_sigma=1.5,
gaussian_kernel_width=11):
"""Computes SSIM.
Args:
im1: First PIL Image object to compare.
im2: Second PIL Image object to compare.
Returns:
SSIM float value.
"""
gaussian_kernel_1d = get_gaussian_kernel(
gaussian_kernel_width, gaussian_kernel_sigma)
return SSIM(image1, gaussian_kernel_1d).ssim_value(image2)
|
def add_exec_permission_to ( target_file ) : mode = os . stat ( target_file ) . st_mode os . chmod ( target_file , mode | stat . S_IXUSR )
| 1 |
python enable executable permisions on file
|
Add executable permissions to the file
|
cosqa-train-15119
|
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 get_average_color ( colors ) : c = reduce ( color_reducer , colors ) total = len ( colors ) return tuple ( v / total for v in c )
| 0 |
compute average color value in python
|
Calculate the average color from the list of colors where each color is a 3 - tuple of ( r g b ) values .
|
cosqa-train-15120
|
def get_average_color(colors):
"""Calculate the average color from the list of colors, where each color
is a 3-tuple of (r, g, b) values.
"""
c = reduce(color_reducer, colors)
total = len(colors)
return tuple(v / total for v in c)
|
def set_strict ( self , value ) : assert isinstance ( value , bool ) self . __settings . set_strict ( value )
| 1 |
python enable strict mode
|
Set the strict mode active / disable
|
cosqa-train-15121
|
def set_strict(self, value):
"""
Set the strict mode active/disable
:param value:
:type value: bool
"""
assert isinstance(value, bool)
self.__settings.set_strict(value)
|
def distance_matrix ( trains1 , trains2 , cos , tau ) : return dissimilarity_matrix ( trains1 , trains2 , cos , tau , "distance" )
| 0 |
compute dissimilarity matrix for categorical data python
|
Return the * bipartite * ( rectangular ) distance matrix between the observations in the first and the second list .
|
cosqa-train-15122
|
def distance_matrix(trains1, trains2, cos, tau):
"""
Return the *bipartite* (rectangular) distance matrix between the observations in the first and the second list.
Convenience function; equivalent to ``dissimilarity_matrix(trains1, trains2, cos, tau, "distance")``. Refer to :func:`pymuvr.dissimilarity_matrix` for full documentation.
"""
return dissimilarity_matrix(trains1, trains2, cos, tau, "distance")
|
def get_enum_from_name ( self , enum_name ) : return next ( ( e for e in self . enums if e . name == enum_name ) , None )
| 1 |
python enum get name
|
Return an enum from a name Args : enum_name ( str ) : name of the enum Returns : Enum
|
cosqa-train-15123
|
def get_enum_from_name(self, enum_name):
"""
Return an enum from a name
Args:
enum_name (str): name of the enum
Returns:
Enum
"""
return next((e for e in self.enums if e.name == enum_name), None)
|
def _cal_dist2center ( X , center ) : dmemb2cen = scipy . spatial . distance . cdist ( X , center . reshape ( 1 , X . shape [ 1 ] ) , metric = 'seuclidean' ) return ( np . sum ( dmemb2cen ) )
| 0 |
compute distance from centroid in python
|
Calculate the SSE to the cluster center
|
cosqa-train-15124
|
def _cal_dist2center(X, center):
""" Calculate the SSE to the cluster center
"""
dmemb2cen = scipy.spatial.distance.cdist(X, center.reshape(1,X.shape[1]), metric='seuclidean')
return(np.sum(dmemb2cen))
|
def get_enum_from_name ( self , enum_name ) : return next ( ( e for e in self . enums if e . name == enum_name ) , None )
| 0 |
python enum get names
|
Return an enum from a name Args : enum_name ( str ) : name of the enum Returns : Enum
|
cosqa-train-15125
|
def get_enum_from_name(self, enum_name):
"""
Return an enum from a name
Args:
enum_name (str): name of the enum
Returns:
Enum
"""
return next((e for e in self.enums if e.name == enum_name), None)
|
def accuracy ( conf_matrix ) : total , correct = 0.0 , 0.0 for true_response , guess_dict in conf_matrix . items ( ) : for guess , count in guess_dict . items ( ) : if true_response == guess : correct += count total += count return correct / total
| 0 |
confusion matrix doesn't match accuracy python
|
Given a confusion matrix returns the accuracy . Accuracy Definition : http : // research . ics . aalto . fi / events / eyechallenge2005 / evaluation . shtml
|
cosqa-train-15126
|
def accuracy(conf_matrix):
"""
Given a confusion matrix, returns the accuracy.
Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml
"""
total, correct = 0.0, 0.0
for true_response, guess_dict in conf_matrix.items():
for guess, count in guess_dict.items():
if true_response == guess:
correct += count
total += count
return correct/total
|
def EnumValueName ( self , enum , value ) : return self . enum_types_by_name [ enum ] . values_by_number [ value ] . name
| 1 |
python enum get value by name
|
Returns the string name of an enum value .
|
cosqa-train-15127
|
def EnumValueName(self, enum, value):
"""Returns the string name of an enum value.
This is just a small helper method to simplify a common operation.
Args:
enum: string name of the Enum.
value: int, value of the enum.
Returns:
string name of the enum value.
Raises:
KeyError if either the Enum doesn't exist or the value is not a valid
value for the enum.
"""
return self.enum_types_by_name[enum].values_by_number[value].name
|
def accuracy ( conf_matrix ) : total , correct = 0.0 , 0.0 for true_response , guess_dict in conf_matrix . items ( ) : for guess , count in guess_dict . items ( ) : if true_response == guess : correct += count total += count return correct / total
| 0 |
confusion matrix example code in python
|
Given a confusion matrix returns the accuracy . Accuracy Definition : http : // research . ics . aalto . fi / events / eyechallenge2005 / evaluation . shtml
|
cosqa-train-15128
|
def accuracy(conf_matrix):
"""
Given a confusion matrix, returns the accuracy.
Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml
"""
total, correct = 0.0, 0.0
for true_response, guess_dict in conf_matrix.items():
for guess, count in guess_dict.items():
if true_response == guess:
correct += count
total += count
return correct/total
|
def write_enum ( fo , datum , schema ) : index = schema [ 'symbols' ] . index ( datum ) write_int ( fo , index )
| 0 |
python enum value to enumerator
|
An enum is encoded by a int representing the zero - based position of the symbol in the schema .
|
cosqa-train-15129
|
def write_enum(fo, datum, schema):
"""An enum is encoded by a int, representing the zero-based position of
the symbol in the schema."""
index = schema['symbols'].index(datum)
write_int(fo, index)
|
def confusion_matrix ( self ) : return plot . confusion_matrix ( self . y_true , self . y_pred , self . target_names , ax = _gen_ax ( ) )
| 0 |
confusion matrix visualization python
|
Confusion matrix plot
|
cosqa-train-15130
|
def confusion_matrix(self):
"""Confusion matrix plot
"""
return plot.confusion_matrix(self.y_true, self.y_pred,
self.target_names, ax=_gen_ax())
|
def native_conn ( self ) : if self . __native is None : self . __native = self . _get_connection ( ) return self . __native
| 0 |
connexion get instance python
|
Native connection object .
|
cosqa-train-15131
|
def native_conn(self):
"""Native connection object."""
if self.__native is None:
self.__native = self._get_connection()
return self.__native
|
def raise_os_error ( _errno , path = None ) : msg = "%s: '%s'" % ( strerror ( _errno ) , path ) if path else strerror ( _errno ) raise OSError ( _errno , msg )
| 0 |
python errno already in use
|
Helper for raising the correct exception under Python 3 while still being able to raise the same common exception class in Python 2 . 7 .
|
cosqa-train-15132
|
def raise_os_error(_errno, path=None):
"""
Helper for raising the correct exception under Python 3 while still
being able to raise the same common exception class in Python 2.7.
"""
msg = "%s: '%s'" % (strerror(_errno), path) if path else strerror(_errno)
raise OSError(_errno, msg)
|
def _make_cmd_list ( cmd_list ) : cmd = '' for i in cmd_list : cmd = cmd + '"' + i + '",' cmd = cmd [ : - 1 ] return cmd
| 1 |
construct string with list python
|
Helper function to easily create the proper json formated string from a list of strs : param cmd_list : list of strings : return : str json formatted
|
cosqa-train-15133
|
def _make_cmd_list(cmd_list):
"""
Helper function to easily create the proper json formated string from a list of strs
:param cmd_list: list of strings
:return: str json formatted
"""
cmd = ''
for i in cmd_list:
cmd = cmd + '"' + i + '",'
cmd = cmd[:-1]
return cmd
|
def quote ( s , unsafe = '/' ) : res = s . replace ( '%' , '%25' ) for c in unsafe : res = res . replace ( c , '%' + ( hex ( ord ( c ) ) . upper ( ) ) [ 2 : ] ) return res
| 1 |
python escape percent symbol in format
|
Pass in a dictionary that has unsafe characters as the keys and the percent encoded value as the value .
|
cosqa-train-15134
|
def quote(s, unsafe='/'):
"""Pass in a dictionary that has unsafe characters as the keys, and the percent
encoded value as the value."""
res = s.replace('%', '%25')
for c in unsafe:
res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])
return res
|
def eintr_retry ( exc_type , f , * args , * * kwargs ) : while True : try : return f ( * args , * * kwargs ) except exc_type as exc : if exc . errno != EINTR : raise else : break
| 0 |
continue in try excpet python
|
Calls a function . If an error of the given exception type with interrupted system call ( EINTR ) occurs calls the function again .
|
cosqa-train-15135
|
def eintr_retry(exc_type, f, *args, **kwargs):
"""Calls a function. If an error of the given exception type with
interrupted system call (EINTR) occurs calls the function again.
"""
while True:
try:
return f(*args, **kwargs)
except exc_type as exc:
if exc.errno != EINTR:
raise
else:
break
|
def asynchronous ( function , event ) : thread = Thread ( target = synchronous , args = ( function , event ) ) thread . daemon = True thread . start ( )
| 0 |
python event loop synchronous call
|
Runs the function asynchronously taking care of exceptions .
|
cosqa-train-15136
|
def asynchronous(function, event):
"""
Runs the function asynchronously taking care of exceptions.
"""
thread = Thread(target=synchronous, args=(function, event))
thread.daemon = True
thread.start()
|
def get_number ( s , cast = int ) : import string d = "" . join ( x for x in str ( s ) if x in string . digits ) return cast ( d )
| 0 |
converts a string into a number in python
|
Try to get a number out of a string and cast it .
|
cosqa-train-15137
|
def get_number(s, cast=int):
"""
Try to get a number out of a string, and cast it.
"""
import string
d = "".join(x for x in str(s) if x in string.digits)
return cast(d)
|
def _expand ( self , str , local_vars = { } ) : return ninja_syntax . expand ( str , self . vars , local_vars )
| 1 |
python expandvars non defined
|
Expand $vars in a string .
|
cosqa-train-15138
|
def _expand(self, str, local_vars={}):
"""Expand $vars in a string."""
return ninja_syntax.expand(str, self.vars, local_vars)
|
def str2bytes ( x ) : if type ( x ) is bytes : return x elif type ( x ) is str : return bytes ( [ ord ( i ) for i in x ] ) else : return str2bytes ( str ( x ) )
| 1 |
converty str to bytes python
|
Convert input argument to bytes
|
cosqa-train-15139
|
def str2bytes(x):
"""Convert input argument to bytes"""
if type(x) is bytes:
return x
elif type(x) is str:
return bytes([ ord(i) for i in x ])
else:
return str2bytes(str(x))
|
def end_block ( self ) : self . current_indent -= 1 # If we did not add a new line automatically yet, now it's the time! if not self . auto_added_line : self . writeln ( ) self . auto_added_line = True
| 1 |
python expect indent block
|
Ends an indentation block leaving an empty line afterwards
|
cosqa-train-15140
|
def end_block(self):
"""Ends an indentation block, leaving an empty line afterwards"""
self.current_indent -= 1
# If we did not add a new line automatically yet, now it's the time!
if not self.auto_added_line:
self.writeln()
self.auto_added_line = True
|
def copy ( self ) : return self . __class__ ( self . operations . copy ( ) , self . collection , self . document )
| 1 |
copy without referencing python
|
Return a shallow copy .
|
cosqa-train-15141
|
def copy(self):
"""Return a shallow copy."""
return self.__class__(self.operations.copy(), self.collection, self.document)
|
def tanimoto_coefficient ( a , b ) : return sum ( map ( lambda ( x , y ) : float ( x ) * float ( y ) , zip ( a , b ) ) ) / sum ( [ - sum ( map ( lambda ( x , y ) : float ( x ) * float ( y ) , zip ( a , b ) ) ) , sum ( map ( lambda x : float ( x ) ** 2 , a ) ) , sum ( map ( lambda x : float ( x ) ** 2 , b ) ) ] )
| 0 |
cosine similarity python between users
|
Measured similarity between two points in a multi - dimensional space .
|
cosqa-train-15142
|
def tanimoto_coefficient(a, b):
"""Measured similarity between two points in a multi-dimensional space.
Returns:
1.0 if the two points completely overlap,
0.0 if the two points are infinitely far apart.
"""
return sum(map(lambda (x,y): float(x)*float(y), zip(a,b))) / sum([
-sum(map(lambda (x,y): float(x)*float(y), zip(a,b))),
sum(map(lambda x: float(x)**2, a)),
sum(map(lambda x: float(x)**2, b))])
|
def update ( self , other_dict ) : for key , value in iter_multi_items ( other_dict ) : MultiDict . add ( self , key , value )
| 0 |
python extend dictionary with other dictionary
|
update () extends rather than replaces existing key lists .
|
cosqa-train-15143
|
def update(self, other_dict):
"""update() extends rather than replaces existing key lists."""
for key, value in iter_multi_items(other_dict):
MultiDict.add(self, key, value)
|
def empty_line_count_at_the_end ( self ) : count = 0 for line in self . lines [ : : - 1 ] : if not line or line . isspace ( ) : count += 1 else : break return count
| 1 |
count empty spaces in a line python
|
Return number of empty lines at the end of the document .
|
cosqa-train-15144
|
def empty_line_count_at_the_end(self):
"""
Return number of empty lines at the end of the document.
"""
count = 0
for line in self.lines[::-1]:
if not line or line.isspace():
count += 1
else:
break
return count
|
def update ( self , other_dict ) : for key , value in iter_multi_items ( other_dict ) : MultiDict . add ( self , key , value )
| 0 |
python extending dict using list comprehension
|
update () extends rather than replaces existing key lists .
|
cosqa-train-15145
|
def update(self, other_dict):
"""update() extends rather than replaces existing key lists."""
for key, value in iter_multi_items(other_dict):
MultiDict.add(self, key, value)
|
def num_leaves ( tree ) : if tree . is_leaf : return 1 else : return num_leaves ( tree . left_child ) + num_leaves ( tree . right_child )
| 1 |
count node and children in tree python
|
Determine the number of leaves in a tree
|
cosqa-train-15146
|
def num_leaves(tree):
"""Determine the number of leaves in a tree"""
if tree.is_leaf:
return 1
else:
return num_leaves(tree.left_child) + num_leaves(tree.right_child)
|
def resources ( self ) : return [ self . pdf . getPage ( i ) for i in range ( self . pdf . getNumPages ( ) ) ]
| 1 |
python extract 5 pages at a time from pdf
|
Retrieve contents of each page of PDF
|
cosqa-train-15147
|
def resources(self):
"""Retrieve contents of each page of PDF"""
return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]
|
def count_list ( the_list ) : count = the_list . count result = [ ( item , count ( item ) ) for item in set ( the_list ) ] result . sort ( ) return result
| 1 |
count unique values in a list python
|
Generates a count of the number of times each unique item appears in a list
|
cosqa-train-15148
|
def count_list(the_list):
"""
Generates a count of the number of times each unique item appears in a list
"""
count = the_list.count
result = [(item, count(item)) for item in set(the_list)]
result.sort()
return result
|
def best ( self ) : b = ( - 1e999999 , None ) for k , c in iteritems ( self . counts ) : b = max ( b , ( c , k ) ) return b [ 1 ]
| 0 |
counting the highest number in coloumn using python
|
Returns the element with the highest probability .
|
cosqa-train-15149
|
def best(self):
"""
Returns the element with the highest probability.
"""
b = (-1e999999, None)
for k, c in iteritems(self.counts):
b = max(b, (c, k))
return b[1]
|
def jaccard ( c_1 , c_2 ) : nom = np . intersect1d ( c_1 , c_2 ) . size denom = np . union1d ( c_1 , c_2 ) . size return nom / denom
| 1 |
python fast jaccard similarity
|
Calculates the Jaccard similarity between two sets of nodes . Called by mroc .
|
cosqa-train-15150
|
def jaccard(c_1, c_2):
"""
Calculates the Jaccard similarity between two sets of nodes. Called by mroc.
Inputs: - c_1: Community (set of nodes) 1.
- c_2: Community (set of nodes) 2.
Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.
"""
nom = np.intersect1d(c_1, c_2).size
denom = np.union1d(c_1, c_2).size
return nom/denom
|
def array_dim ( arr ) : dim = [ ] while True : try : dim . append ( len ( arr ) ) arr = arr [ 0 ] except TypeError : return dim
| 1 |
couting length of list in python
|
Return the size of a multidimansional array .
|
cosqa-train-15151
|
def array_dim(arr):
"""Return the size of a multidimansional array.
"""
dim = []
while True:
try:
dim.append(len(arr))
arr = arr[0]
except TypeError:
return dim
|
def stft ( func = None , * * kwparams ) : from numpy . fft import fft , ifft ifft_r = lambda * args : ifft ( * args ) . real return stft . base ( transform = fft , inverse_transform = ifft_r ) ( func , * * kwparams )
| 1 |
python fft from real data
|
Short Time Fourier Transform for real data keeping the full FFT block .
|
cosqa-train-15152
|
def stft(func=None, **kwparams):
"""
Short Time Fourier Transform for real data keeping the full FFT block.
Same to the default STFT strategy, but with new defaults. This is the same
to:
.. code-block:: python
stft.base(transform=numpy.fft.fft,
inverse_transform=lambda *args: numpy.fft.ifft(*args).real)
See ``stft.base`` docs for more.
"""
from numpy.fft import fft, ifft
ifft_r = lambda *args: ifft(*args).real
return stft.base(transform=fft, inverse_transform=ifft_r)(func, **kwparams)
|
def covariance ( self , pt0 , pt1 ) : x = np . array ( [ pt0 [ 0 ] , pt1 [ 0 ] ] ) y = np . array ( [ pt0 [ 1 ] , pt1 [ 1 ] ] ) names = [ "n1" , "n2" ] return self . covariance_matrix ( x , y , names = names ) . x [ 0 , 1 ]
| 1 |
covariance matrix between two vectors in python
|
get the covarince between two points implied by Vario2d
|
cosqa-train-15153
|
def covariance(self,pt0,pt1):
""" get the covarince between two points implied by Vario2d
Parameters
----------
pt0 : (iterable of len 2)
first point x and y
pt1 : (iterable of len 2)
second point x and y
Returns
-------
cov : float
covariance between pt0 and pt1
"""
x = np.array([pt0[0],pt1[0]])
y = np.array([pt0[1],pt1[1]])
names = ["n1","n2"]
return self.covariance_matrix(x,y,names=names).x[0,1]
|
def Output ( self ) : self . Open ( ) self . Header ( ) self . Body ( ) self . Footer ( )
| 1 |
python figure whole page
|
Output all sections of the page .
|
cosqa-train-15154
|
def Output(self):
"""Output all sections of the page."""
self.Open()
self.Header()
self.Body()
self.Footer()
|
def coerce ( self , value ) : if isinstance ( value , dict ) : value = [ value ] if not isiterable_notstring ( value ) : value = [ value ] return [ coerce_single_instance ( self . lookup_field , v ) for v in value ]
| 0 |
covert type of list python
|
Convert from whatever is given to a list of scalars for the lookup_field .
|
cosqa-train-15155
|
def coerce(self, value):
"""Convert from whatever is given to a list of scalars for the lookup_field."""
if isinstance(value, dict):
value = [value]
if not isiterable_notstring(value):
value = [value]
return [coerce_single_instance(self.lookup_field, v) for v in value]
|
def chmod_add_excute ( filename ) : st = os . stat ( filename ) os . chmod ( filename , st . st_mode | stat . S_IEXEC )
| 0 |
python file chmod permission
|
Adds execute permission to file . : param filename : : return :
|
cosqa-train-15156
|
def chmod_add_excute(filename):
"""
Adds execute permission to file.
:param filename:
:return:
"""
st = os.stat(filename)
os.chmod(filename, st.st_mode | stat.S_IEXEC)
|
def unique ( _list ) : ret = [ ] for item in _list : if item not in ret : ret . append ( item ) return ret
| 0 |
craete empty python set
|
Makes the list have unique items only and maintains the order
|
cosqa-train-15157
|
def unique(_list):
"""
Makes the list have unique items only and maintains the order
list(set()) won't provide that
:type _list list
:rtype: list
"""
ret = []
for item in _list:
if item not in ret:
ret.append(item)
return ret
|
def file_writelines_flush_sync ( path , lines ) : fp = open ( path , 'w' ) try : fp . writelines ( lines ) flush_sync_file_object ( fp ) finally : fp . close ( )
| 0 |
python file flush api
|
Fill file at
|
cosqa-train-15158
|
def file_writelines_flush_sync(path, lines):
"""
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
"""
fp = open(path, 'w')
try:
fp.writelines(lines)
flush_sync_file_object(fp)
finally:
fp.close()
|
def __copy__ ( self ) : return self . __class__ . load ( self . dump ( ) , context = self . context )
| 1 |
create a deepcopy of self in python
|
A magic method to implement shallow copy behavior .
|
cosqa-train-15159
|
def __copy__(self):
"""A magic method to implement shallow copy behavior."""
return self.__class__.load(self.dump(), context=self.context)
|
def get_lines ( handle , line ) : for i , l in enumerate ( handle ) : if i == line : return l
| 0 |
python file get index of the line
|
Get zero - indexed line from an open file - like .
|
cosqa-train-15160
|
def get_lines(handle, line):
"""
Get zero-indexed line from an open file-like.
"""
for i, l in enumerate(handle):
if i == line:
return l
|
def mkdir ( dir , enter ) : if not os . path . exists ( dir ) : os . makedirs ( dir )
| 1 |
create a dir in python
|
Create directory with template for topic of the current environment
|
cosqa-train-15161
|
def mkdir(dir, enter):
"""Create directory with template for topic of the current environment
"""
if not os.path.exists(dir):
os.makedirs(dir)
|
def get_time ( filename ) : ts = os . stat ( filename ) . st_mtime return datetime . datetime . utcfromtimestamp ( ts )
| 0 |
python file modified time datetime
|
Get the modified time for a file as a datetime instance
|
cosqa-train-15162
|
def get_time(filename):
"""
Get the modified time for a file as a datetime instance
"""
ts = os.stat(filename).st_mtime
return datetime.datetime.utcfromtimestamp(ts)
|
def write_file ( filename , content ) : print 'Generating {0}' . format ( filename ) with open ( filename , 'wb' ) as out_f : out_f . write ( content )
| 0 |
create a file and write a string to it in python
|
Create the file with the given content
|
cosqa-train-15163
|
def write_file(filename, content):
"""Create the file with the given content"""
print 'Generating {0}'.format(filename)
with open(filename, 'wb') as out_f:
out_f.write(content)
|
def make_file_read_only ( file_path ) : old_permissions = os . stat ( file_path ) . st_mode os . chmod ( file_path , old_permissions & ~ WRITE_PERMISSIONS )
| 0 |
python file not running with permissions set to 644
|
Removes the write permissions for the given file for owner groups and others .
|
cosqa-train-15164
|
def make_file_read_only(file_path):
"""
Removes the write permissions for the given file for owner, groups and others.
:param file_path: The file whose privileges are revoked.
:raise FileNotFoundError: If the given file does not exist.
"""
old_permissions = os.stat(file_path).st_mode
os.chmod(file_path, old_permissions & ~WRITE_PERMISSIONS)
|
def beta_pdf ( x , a , b ) : bc = 1 / beta ( a , b ) fc = x ** ( a - 1 ) sc = ( 1 - x ) ** ( b - 1 ) return bc * fc * sc
| 1 |
create a function for the normal distrubution pdf python
|
Beta distirbution probability density function .
|
cosqa-train-15165
|
def beta_pdf(x, a, b):
"""Beta distirbution probability density function."""
bc = 1 / beta(a, b)
fc = x ** (a - 1)
sc = (1 - x) ** (b - 1)
return bc * fc * sc
|
def file_read ( filename ) : fobj = open ( filename , 'r' ) source = fobj . read ( ) fobj . close ( ) return source
| 0 |
python file open and close
|
Read a file and close it . Returns the file source .
|
cosqa-train-15166
|
def file_read(filename):
"""Read a file and close it. Returns the file source."""
fobj = open(filename,'r');
source = fobj.read();
fobj.close()
return source
|
def list_of_lists_to_dict ( l ) : d = { } for key , val in l : d . setdefault ( key , [ ] ) . append ( val ) return d
| 1 |
create a list to a dictionary python
|
Convert list of key value lists to dict
|
cosqa-train-15167
|
def list_of_lists_to_dict(l):
""" Convert list of key,value lists to dict
[['id', 1], ['id', 2], ['id', 3], ['foo': 4]]
{'id': [1, 2, 3], 'foo': [4]}
"""
d = {}
for key, val in l:
d.setdefault(key, []).append(val)
return d
|
def parse_comments_for_file ( filename ) : return [ parse_comment ( strip_stars ( comment ) , next_line ) for comment , next_line in get_doc_comments ( read_file ( filename ) ) ]
| 1 |
python file with comments
|
Return a list of all parsed comments in a file . Mostly for testing & interactive use .
|
cosqa-train-15168
|
def parse_comments_for_file(filename):
"""
Return a list of all parsed comments in a file. Mostly for testing &
interactive use.
"""
return [parse_comment(strip_stars(comment), next_line)
for comment, next_line in get_doc_comments(read_file(filename))]
|
def rnormal ( mu , tau , size = None ) : return np . random . normal ( mu , 1. / np . sqrt ( tau ) , size )
| 0 |
create a normal distribution in python
|
Random normal variates .
|
cosqa-train-15169
|
def rnormal(mu, tau, size=None):
"""
Random normal variates.
"""
return np.random.normal(mu, 1. / np.sqrt(tau), size)
|
def _fill_array_from_list ( the_list , the_array ) : for i , val in enumerate ( the_list ) : the_array [ i ] = val return the_array
| 0 |
python fill and replace list
|
Fill an array from a list
|
cosqa-train-15170
|
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 force_iterable ( f ) : def wrapper ( * args , * * kwargs ) : r = f ( * args , * * kwargs ) if hasattr ( r , '__iter__' ) : return r else : return [ r ] return wrapper
| 0 |
create an iterable in python
|
Will make any functions return an iterable objects by wrapping its result in a list .
|
cosqa-train-15171
|
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 fillna ( series_or_arr , missing_value = 0.0 ) : if pandas . notnull ( missing_value ) : if isinstance ( series_or_arr , ( numpy . ndarray ) ) : series_or_arr [ numpy . isnan ( series_or_arr ) ] = missing_value else : series_or_arr . fillna ( missing_value , inplace = True ) return series_or_arr
| 1 |
python fill missing values in two columns
|
Fill missing values in pandas objects and numpy arrays .
|
cosqa-train-15172
|
def fillna(series_or_arr, missing_value=0.0):
"""Fill missing values in pandas objects and numpy arrays.
Arguments
---------
series_or_arr : pandas.Series, numpy.ndarray
The numpy array or pandas series for which the missing values
need to be replaced.
missing_value : float, int, str
The value to replace the missing value with. Default 0.0.
Returns
-------
pandas.Series, numpy.ndarray
The numpy array or pandas series with the missing values
filled.
"""
if pandas.notnull(missing_value):
if isinstance(series_or_arr, (numpy.ndarray)):
series_or_arr[numpy.isnan(series_or_arr)] = missing_value
else:
series_or_arr.fillna(missing_value, inplace=True)
return series_or_arr
|
def join_cols ( cols ) : return ", " . join ( [ i for i in cols ] ) if isinstance ( cols , ( list , tuple , set ) ) else cols
| 1 |
create column in python by joining columns
|
Join list of columns into a string for a SQL query
|
cosqa-train-15173
|
def join_cols(cols):
"""Join list of columns into a string for a SQL query"""
return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols
|
def fillna ( series_or_arr , missing_value = 0.0 ) : if pandas . notnull ( missing_value ) : if isinstance ( series_or_arr , ( numpy . ndarray ) ) : series_or_arr [ numpy . isnan ( series_or_arr ) ] = missing_value else : series_or_arr . fillna ( missing_value , inplace = True ) return series_or_arr
| 1 |
python filling missing values with fillna
|
Fill missing values in pandas objects and numpy arrays .
|
cosqa-train-15174
|
def fillna(series_or_arr, missing_value=0.0):
"""Fill missing values in pandas objects and numpy arrays.
Arguments
---------
series_or_arr : pandas.Series, numpy.ndarray
The numpy array or pandas series for which the missing values
need to be replaced.
missing_value : float, int, str
The value to replace the missing value with. Default 0.0.
Returns
-------
pandas.Series, numpy.ndarray
The numpy array or pandas series with the missing values
filled.
"""
if pandas.notnull(missing_value):
if isinstance(series_or_arr, (numpy.ndarray)):
series_or_arr[numpy.isnan(series_or_arr)] = missing_value
else:
series_or_arr.fillna(missing_value, inplace=True)
return series_or_arr
|
def force_iterable ( f ) : def wrapper ( * args , * * kwargs ) : r = f ( * args , * * kwargs ) if hasattr ( r , '__iter__' ) : return r else : return [ r ] return wrapper
| 1 |
create custom iterable python 3
|
Will make any functions return an iterable objects by wrapping its result in a list .
|
cosqa-train-15175
|
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 filter_dict ( d , keys ) : return { k : v for k , v in d . items ( ) if k in keys }
| 1 |
python filter a dict by condition on key
|
Creates a new dict from an existing dict that only has the given keys
|
cosqa-train-15176
|
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 a2s ( a ) : s = np . zeros ( ( 6 , ) , 'f' ) # make the a matrix for i in range ( 3 ) : s [ i ] = a [ i ] [ i ] s [ 3 ] = a [ 0 ] [ 1 ] s [ 4 ] = a [ 1 ] [ 2 ] s [ 5 ] = a [ 0 ] [ 2 ] return s
| 0 |
create matrix using for python
|
convert 3 3 a matrix to 6 element s list ( see Tauxe 1998 )
|
cosqa-train-15177
|
def a2s(a):
"""
convert 3,3 a matrix to 6 element "s" list (see Tauxe 1998)
"""
s = np.zeros((6,), 'f') # make the a matrix
for i in range(3):
s[i] = a[i][i]
s[3] = a[0][1]
s[4] = a[1][2]
s[5] = a[0][2]
return s
|
def str2int ( string_with_int ) : return int ( "" . join ( [ char for char in string_with_int if char in string . digits ] ) or 0 )
| 0 |
python filter integer from string
|
Collect digits from a string
|
cosqa-train-15178
|
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 sp_rand ( m , n , a ) : if m == 0 or n == 0 : return spmatrix ( [ ] , [ ] , [ ] , ( m , n ) ) nnz = min ( max ( 0 , int ( round ( a * m * n ) ) ) , m * n ) nz = matrix ( random . sample ( range ( m * n ) , nnz ) , tc = 'i' ) return spmatrix ( normal ( nnz , 1 ) , nz % m , matrix ( [ int ( ii ) for ii in nz / m ] ) , ( m , n ) )
| 1 |
create random sparse matrix python
|
Generates an mxn sparse d matrix with round ( a * m * n ) nonzeros .
|
cosqa-train-15179
|
def sp_rand(m,n,a):
"""
Generates an mxn sparse 'd' matrix with round(a*m*n) nonzeros.
"""
if m == 0 or n == 0: return spmatrix([], [], [], (m,n))
nnz = min(max(0, int(round(a*m*n))), m*n)
nz = matrix(random.sample(range(m*n), nnz), tc='i')
return spmatrix(normal(nnz,1), nz%m, matrix([int(ii) for ii in nz/m]), (m,n))
|
def filter_dict_by_key ( d , keys ) : return { k : v for k , v in d . items ( ) if k in keys }
| 0 |
python filtering keys in dict
|
Filter the dict * d * to remove keys not in * keys * .
|
cosqa-train-15180
|
def filter_dict_by_key(d, keys):
"""Filter the dict *d* to remove keys not in *keys*."""
return {k: v for k, v in d.items() if k in keys}
|
def prt_nts ( data_nts , prtfmt = None , prt = sys . stdout , nt_fields = None , * * kws ) : prt_txt ( prt , data_nts , prtfmt , nt_fields , * * kws )
| 1 |
create unknown number of names to print in python
|
Print list of namedtuples into a table using prtfmt .
|
cosqa-train-15181
|
def prt_nts(data_nts, prtfmt=None, prt=sys.stdout, nt_fields=None, **kws):
"""Print list of namedtuples into a table using prtfmt."""
prt_txt(prt, data_nts, prtfmt, nt_fields, **kws)
|
def iter_finds ( regex_obj , s ) : if isinstance ( regex_obj , str ) : for m in re . finditer ( regex_obj , s ) : yield m . group ( ) else : for m in regex_obj . finditer ( s ) : yield m . group ( )
| 0 |
python finditer match multiple patterns
|
Generate all matches found within a string for a regex and yield each match as a string
|
cosqa-train-15182
|
def iter_finds(regex_obj, s):
"""Generate all matches found within a string for a regex and yield each match as a string"""
if isinstance(regex_obj, str):
for m in re.finditer(regex_obj, s):
yield m.group()
else:
for m in regex_obj.finditer(s):
yield m.group()
|
def flattened_nested_key_indices ( nested_dict ) : outer_keys , inner_keys = collect_nested_keys ( nested_dict ) combined_keys = list ( sorted ( set ( outer_keys + inner_keys ) ) ) return { k : i for ( i , k ) in enumerate ( combined_keys ) }
| 0 |
creating a dictionary python with keys and outer dictionary
|
Combine the outer and inner keys of nested dictionaries into a single ordering .
|
cosqa-train-15183
|
def flattened_nested_key_indices(nested_dict):
"""
Combine the outer and inner keys of nested dictionaries into a single
ordering.
"""
outer_keys, inner_keys = collect_nested_keys(nested_dict)
combined_keys = list(sorted(set(outer_keys + inner_keys)))
return {k: i for (i, k) in enumerate(combined_keys)}
|
def split_every ( n , iterable ) : items = iter ( iterable ) return itertools . takewhile ( bool , ( list ( itertools . islice ( items , n ) ) for _ in itertools . count ( ) ) )
| 0 |
python first n elements from iterable
|
Returns a generator that spits an iteratable into n - sized chunks . The last chunk may have less than n elements .
|
cosqa-train-15184
|
def split_every(n, iterable):
"""Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have
less than n elements.
See http://stackoverflow.com/a/22919323/503377."""
items = iter(iterable)
return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))
|
def highpass ( cutoff ) : R = thub ( exp ( cutoff - pi ) , 2 ) return ( 1 - R ) / ( 1 + R * z ** - 1 )
| 0 |
creating a low pass filter in python
|
This strategy uses an exponential approximation for cut - off frequency calculation found by matching the one - pole Laplace lowpass filter and mirroring the resulting filter to get a highpass .
|
cosqa-train-15185
|
def highpass(cutoff):
"""
This strategy uses an exponential approximation for cut-off frequency
calculation, found by matching the one-pole Laplace lowpass filter
and mirroring the resulting filter to get a highpass.
"""
R = thub(exp(cutoff - pi), 2)
return (1 - R) / (1 + R * z ** -1)
|
def add_column ( filename , column , formula , force = False ) : columns = parse_formula ( formula ) logger . info ( "Running file: %s" % filename ) logger . debug ( " Reading columns: %s" % columns ) data = fitsio . read ( filename , columns = columns ) logger . debug ( ' Evaluating formula: %s' % formula ) col = eval ( formula ) col = np . asarray ( col , dtype = [ ( column , col . dtype ) ] ) insert_columns ( filename , col , force = force ) return True
| 1 |
python fits add a column
|
Add a column to a FITS file .
|
cosqa-train-15186
|
def add_column(filename,column,formula,force=False):
""" Add a column to a FITS file.
ADW: Could this be replaced by a ftool?
"""
columns = parse_formula(formula)
logger.info("Running file: %s"%filename)
logger.debug(" Reading columns: %s"%columns)
data = fitsio.read(filename,columns=columns)
logger.debug(' Evaluating formula: %s'%formula)
col = eval(formula)
col = np.asarray(col,dtype=[(column,col.dtype)])
insert_columns(filename,col,force=force)
return True
|
def parse_comments_for_file ( filename ) : return [ parse_comment ( strip_stars ( comment ) , next_line ) for comment , next_line in get_doc_comments ( read_file ( filename ) ) ]
| 0 |
creating a python list from file with comments
|
Return a list of all parsed comments in a file . Mostly for testing & interactive use .
|
cosqa-train-15187
|
def parse_comments_for_file(filename):
"""
Return a list of all parsed comments in a file. Mostly for testing &
interactive use.
"""
return [parse_comment(strip_stars(comment), next_line)
for comment, next_line in get_doc_comments(read_file(filename))]
|
def default_static_path ( ) : fdir = os . path . dirname ( __file__ ) return os . path . abspath ( os . path . join ( fdir , '../assets/' ) )
| 1 |
python flask css background relative path
|
Return the path to the javascript bundle
|
cosqa-train-15188
|
def default_static_path():
"""
Return the path to the javascript bundle
"""
fdir = os.path.dirname(__file__)
return os.path.abspath(os.path.join(fdir, '../assets/'))
|
def Timestamp ( year , month , day , hour , minute , second ) : return datetime . datetime ( year , month , day , hour , minute , second )
| 1 |
creating a python object with datetime variables
|
Constructs an object holding a datetime / timestamp value .
|
cosqa-train-15189
|
def Timestamp(year, month, day, hour, minute, second):
"""Constructs an object holding a datetime/timestamp value."""
return datetime.datetime(year, month, day, hour, minute, second)
|
def initialize_api ( flask_app ) : if not flask_restplus : return api = flask_restplus . Api ( version = "1.0" , title = "My Example API" ) api . add_resource ( HelloWorld , "/hello" ) blueprint = flask . Blueprint ( "api" , __name__ , url_prefix = "/api" ) api . init_app ( blueprint ) flask_app . register_blueprint ( blueprint )
| 0 |
python flask for production
|
Initialize an API .
|
cosqa-train-15190
|
def initialize_api(flask_app):
"""Initialize an API."""
if not flask_restplus:
return
api = flask_restplus.Api(version="1.0", title="My Example API")
api.add_resource(HelloWorld, "/hello")
blueprint = flask.Blueprint("api", __name__, url_prefix="/api")
api.init_app(blueprint)
flask_app.register_blueprint(blueprint)
|
def from_json ( cls , json_doc ) : try : d = json . load ( json_doc ) except AttributeError : # catch the read() error d = json . loads ( json_doc ) return cls . from_dict ( d )
| 1 |
creating object from json in python
|
Parse a JSON string and build an entity .
|
cosqa-train-15191
|
def from_json(cls, json_doc):
"""Parse a JSON string and build an entity."""
try:
d = json.load(json_doc)
except AttributeError: # catch the read() error
d = json.loads(json_doc)
return cls.from_dict(d)
|
def logout ( cache ) : cache . set ( flask . session [ 'auth0_key' ] , None ) flask . session . clear ( ) return True
| 1 |
python flask how to clear session data and cookies
|
Logs out the current session by removing it from the cache . This is expected to only occur when a session has
|
cosqa-train-15192
|
def logout(cache):
"""
Logs out the current session by removing it from the cache. This is
expected to only occur when a session has
"""
cache.set(flask.session['auth0_key'], None)
flask.session.clear()
return True
|
async def restart ( request ) : def wait_and_restart ( ) : log . info ( 'Restarting server' ) sleep ( 1 ) os . system ( 'kill 1' ) Thread ( target = wait_and_restart ) . start ( ) return web . json_response ( { "message" : "restarting" } )
| 0 |
cron to restart python killed
|
Returns OK then waits approximately 1 second and restarts container
|
cosqa-train-15193
|
async def restart(request):
"""
Returns OK, then waits approximately 1 second and restarts container
"""
def wait_and_restart():
log.info('Restarting server')
sleep(1)
os.system('kill 1')
Thread(target=wait_and_restart).start()
return web.json_response({"message": "restarting"})
|
def lambda_failure_response ( * args ) : response_data = jsonify ( ServiceErrorResponses . _LAMBDA_FAILURE ) return make_response ( response_data , ServiceErrorResponses . HTTP_STATUS_CODE_502 )
| 0 |
python flask how to return 404
|
Helper function to create a Lambda Failure Response
|
cosqa-train-15194
|
def lambda_failure_response(*args):
"""
Helper function to create a Lambda Failure Response
:return: A Flask Response
"""
response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502)
|
def pointer ( self ) : return ctypes . cast ( ctypes . pointer ( ctypes . c_uint8 . from_buffer ( self . mapping , 0 ) ) , ctypes . c_void_p )
| 0 |
cuda get memory address of variable python
|
Get a ctypes void pointer to the memory mapped region .
|
cosqa-train-15195
|
def pointer(self):
"""Get a ctypes void pointer to the memory mapped region.
:type: ctypes.c_void_p
"""
return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)
|
def cumsum ( inlist ) : newlist = copy . deepcopy ( inlist ) for i in range ( 1 , len ( newlist ) ) : newlist [ i ] = newlist [ i ] + newlist [ i - 1 ] return newlist
| 1 |
cumulative product of a list in python
|
Returns a list consisting of the cumulative sum of the items in the passed list .
|
cosqa-train-15196
|
def cumsum(inlist):
"""
Returns a list consisting of the cumulative sum of the items in the
passed list.
Usage: lcumsum(inlist)
"""
newlist = copy.deepcopy(inlist)
for i in range(1, len(newlist)):
newlist[i] = newlist[i] + newlist[i - 1]
return newlist
|
def handleFlaskPostRequest ( flaskRequest , endpoint ) : if flaskRequest . method == "POST" : return handleHttpPost ( flaskRequest , endpoint ) elif flaskRequest . method == "OPTIONS" : return handleHttpOptions ( ) else : raise exceptions . MethodNotAllowedException ( )
| 1 |
python flask if method is post
|
Handles the specified flask request for one of the POST URLS Invokes the specified endpoint to generate a response .
|
cosqa-train-15197
|
def handleFlaskPostRequest(flaskRequest, endpoint):
"""
Handles the specified flask request for one of the POST URLS
Invokes the specified endpoint to generate a response.
"""
if flaskRequest.method == "POST":
return handleHttpPost(flaskRequest, endpoint)
elif flaskRequest.method == "OPTIONS":
return handleHttpOptions()
else:
raise exceptions.MethodNotAllowedException()
|
def screen_cv2 ( self ) : pil_image = self . screen . convert ( 'RGB' ) cv2_image = np . array ( pil_image ) pil_image . close ( ) # Convert RGB to BGR
cv2_image = cv2_image [ : , : , : : - 1 ] return cv2_image
| 0 |
cv2 python imshow gray screen
|
cv2 Image of current window screen
|
cosqa-train-15198
|
def screen_cv2(self):
"""cv2 Image of current window screen"""
pil_image = self.screen.convert('RGB')
cv2_image = np.array(pil_image)
pil_image.close()
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1]
return cv2_image
|
def init_app ( self , app ) : app . config . from_pyfile ( '{0}.cfg' . format ( app . name ) , silent = True )
| 1 |
python flask init py file
|
Initialize Flask application .
|
cosqa-train-15199
|
def init_app(self, app):
"""Initialize Flask application."""
app.config.from_pyfile('{0}.cfg'.format(app.name), silent=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.