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 fast_exit ( code ) : sys . stdout . flush ( ) sys . stderr . flush ( ) os . _exit ( code )
1
python execute a code after exiting program
Exit without garbage collection this speeds up exit by about 10ms for things like bash completion .
cosqa-train-12900
def fast_exit(code): """Exit without garbage collection, this speeds up exit by about 10ms for things like bash completion. """ sys.stdout.flush() sys.stderr.flush() os._exit(code)
def datetime_local_to_utc ( local ) : timestamp = time . mktime ( local . timetuple ( ) ) return datetime . datetime . utcfromtimestamp ( timestamp )
1
change utc time to relative time python
Simple function to convert naive : std : datetime . datetime object containing local time to a naive : std : datetime . datetime object with UTC time .
cosqa-train-12901
def datetime_local_to_utc(local): """ Simple function to convert naive :std:`datetime.datetime` object containing local time to a naive :std:`datetime.datetime` object with UTC time. """ timestamp = time.mktime(local.timetuple()) return datetime.datetime.utcfromtimestamp(timestamp)
def __exit__ ( self , type , value , traceback ) : if not self . asarfile : return self . asarfile . close ( ) self . asarfile = None
0
python exit a function without returning
When the with statement ends .
cosqa-train-12902
def __exit__(self, type, value, traceback): """When the `with` statement ends.""" if not self.asarfile: return self.asarfile.close() self.asarfile = None
def update_scale ( self , value ) : self . plotter . set_scale ( self . x_slider_group . value , self . y_slider_group . value , self . z_slider_group . value )
1
changing scale in graph python
updates the scale of all actors in the plotter
cosqa-train-12903
def update_scale(self, value): """ updates the scale of all actors in the plotter """ self.plotter.set_scale(self.x_slider_group.value, self.y_slider_group.value, self.z_slider_group.value)
def _quit ( self , * args ) : self . logger . warn ( 'Bye!' ) sys . exit ( self . exit ( ) )
1
python exit message to screen
quit crash
cosqa-train-12904
def _quit(self, *args): """ quit crash """ self.logger.warn('Bye!') sys.exit(self.exit())
def upcaseTokens ( s , l , t ) : return [ tt . upper ( ) for tt in map ( _ustr , t ) ]
1
changing tokens to lower case in python tokenizer
Helper parse action to convert tokens to upper case .
cosqa-train-12905
def upcaseTokens(s,l,t): """Helper parse action to convert tokens to upper case.""" return [ tt.upper() for tt in map(_ustr,t) ]
def _requiredSize ( shape , dtype ) : return math . floor ( np . prod ( np . asarray ( shape , dtype = np . uint64 ) ) * np . dtype ( dtype ) . itemsize )
1
python expected type sized
Determines the number of bytes required to store a NumPy array with the specified shape and datatype .
cosqa-train-12906
def _requiredSize(shape, dtype): """ Determines the number of bytes required to store a NumPy array with the specified shape and datatype. """ return math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)
def class_check ( vector ) : for i in vector : if not isinstance ( i , type ( vector [ 0 ] ) ) : return False return True
1
check element of array in python
Check different items in matrix classes .
cosqa-train-12907
def class_check(vector): """ Check different items in matrix classes. :param vector: input vector :type vector : list :return: bool """ for i in vector: if not isinstance(i, type(vector[0])): return False return True
def indent ( self ) : blk = IndentBlock ( self , self . _indent ) self . _indent += 1 return blk
1
python experencing an indenting block
Begins an indented block . Must be used in a with code block . All calls to the logger inside of the block will be indented .
cosqa-train-12908
def indent(self): """ Begins an indented block. Must be used in a 'with' code block. All calls to the logger inside of the block will be indented. """ blk = IndentBlock(self, self._indent) self._indent += 1 return blk
def _is_iterable ( item ) : return isinstance ( item , collections . Iterable ) and not isinstance ( item , six . string_types )
1
check for iterable that's not a string python
Checks if an item is iterable ( list tuple generator ) but not string
cosqa-train-12909
def _is_iterable(item): """ Checks if an item is iterable (list, tuple, generator), but not string """ return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)
def cpp_checker ( code , working_directory ) : return gcc_checker ( code , '.cpp' , [ os . getenv ( 'CXX' , 'g++' ) , '-std=c++0x' ] + INCLUDE_FLAGS , working_directory = working_directory )
1
python extension c++ gcc flag
Return checker .
cosqa-train-12910
def cpp_checker(code, working_directory): """Return checker.""" return gcc_checker(code, '.cpp', [os.getenv('CXX', 'g++'), '-std=c++0x'] + INCLUDE_FLAGS, working_directory=working_directory)
def is_punctuation ( text ) : return not ( text . lower ( ) in config . AVRO_VOWELS or text . lower ( ) in config . AVRO_CONSONANTS )
1
check for punctuation python
Check if given string is a punctuation
cosqa-train-12911
def is_punctuation(text): """Check if given string is a punctuation""" return not (text.lower() in config.AVRO_VOWELS or text.lower() in config.AVRO_CONSONANTS)
def get_numbers ( s ) : result = map ( int , re . findall ( r'[0-9]+' , unicode ( s ) ) ) return result + [ 1 ] * ( 2 - len ( result ) )
1
python extract all numbers from string
Extracts all integers from a string an return them in a list
cosqa-train-12912
def get_numbers(s): """Extracts all integers from a string an return them in a list""" result = map(int, re.findall(r'[0-9]+', unicode(s))) return result + [1] * (2 - len(result))
def is_number ( obj ) : return isinstance ( obj , ( int , float , np . int_ , np . float_ ) )
1
check if a python object is a number
Check if obj is number .
cosqa-train-12913
def is_number(obj): """Check if obj is number.""" return isinstance(obj, (int, float, np.int_, np.float_))
def get_by ( self , name ) : return next ( ( item for item in self if item . name == name ) , None )
1
python extract elements from a list by name
get element by name
cosqa-train-12914
def get_by(self, name): """get element by name""" return next((item for item in self if item.name == name), None)
def contains_extractor ( document ) : tokens = _get_document_tokens ( document ) features = dict ( ( u'contains({0})' . format ( w ) , True ) for w in tokens ) return features
1
python extract feature words
A basic document feature extractor that returns a dict of words that the document contains .
cosqa-train-12915
def contains_extractor(document): """A basic document feature extractor that returns a dict of words that the document contains.""" tokens = _get_document_tokens(document) features = dict((u'contains({0})'.format(w), True) for w in tokens) return features
def is_integer_array ( val ) : return is_np_array ( val ) and issubclass ( val . dtype . type , np . integer )
1
check if a variable is an array python
Checks whether a variable is a numpy integer array .
cosqa-train-12916
def is_integer_array(val): """ Checks whether a variable is a numpy integer array. Parameters ---------- val The variable to check. Returns ------- bool True if the variable is a numpy integer array. Otherwise False. """ return is_np_array(val) and issubclass(val.dtype.type, np.integer)
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 extract params from url string
Returns a dictionary from a URL params
cosqa-train-12917
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 _check_elements_equal ( lst ) : assert isinstance ( lst , list ) , "Input value must be a list." return not lst or lst . count ( lst [ 0 ] ) == len ( lst )
1
check if all elements in list are equal python
Returns true if all of the elements in the list are equal .
cosqa-train-12918
def _check_elements_equal(lst): """ Returns true if all of the elements in the list are equal. """ assert isinstance(lst, list), "Input value must be a list." return not lst or lst.count(lst[0]) == len(lst)
def _saferound ( value , decimal_places ) : try : f = float ( value ) except ValueError : return '' format = '%%.%df' % decimal_places return format % f
1
python f format string float rounding
Rounds a float value off to the desired precision
cosqa-train-12919
def _saferound(value, decimal_places): """ Rounds a float value off to the desired precision """ try: f = float(value) except ValueError: return '' format = '%%.%df' % decimal_places return format % f
def is_number ( obj ) : return isinstance ( obj , ( int , float , np . int_ , np . float_ ) )
1
check if numeric python issinstance
Check if obj is number .
cosqa-train-12920
def is_number(obj): """Check if obj is number.""" return isinstance(obj, (int, float, np.int_, np.float_))
def get_image_dimension ( self , url ) : w_h = ( None , None ) try : if url . startswith ( '//' ) : url = 'http:' + url data = requests . get ( url ) . content im = Image . open ( BytesIO ( data ) ) w_h = im . size except Exception : logger . warning ( "Error getting image size {}" . format ( url ) , exc_info = True ) return w_h
1
python fast way to get image width and height
Return a tuple that contains ( width height ) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found the tuple will contain None values
cosqa-train-12921
def get_image_dimension(self, url): """ Return a tuple that contains (width, height) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found, the tuple will contain `None` values """ w_h = (None, None) try: if url.startswith('//'): url = 'http:' + url data = requests.get(url).content im = Image.open(BytesIO(data)) w_h = im.size except Exception: logger.warning("Error getting image size {}".format(url), exc_info=True) return w_h
def is_number ( obj ) : return isinstance ( obj , ( int , float , np . int_ , np . float_ ) )
1
check if object is number python
Check if obj is number .
cosqa-train-12922
def is_number(obj): """Check if obj is number.""" return isinstance(obj, (int, float, np.int_, np.float_))
def open ( name = None , fileobj = None , closefd = True ) : return Guesser ( ) . open ( name = name , fileobj = fileobj , closefd = closefd )
1
python fastest way to decompress
Use all decompressor possible to make the stream
cosqa-train-12923
def open(name=None, fileobj=None, closefd=True): """ Use all decompressor possible to make the stream """ return Guesser().open(name=name, fileobj=fileobj, closefd=closefd)
def is_delimiter ( line ) : return bool ( line ) and line [ 0 ] in punctuation and line [ 0 ] * len ( line ) == line
0
check if punctuation in string python
True if a line consists only of a single punctuation character .
cosqa-train-12924
def is_delimiter(line): """ True if a line consists only of a single punctuation character.""" return bool(line) and line[0] in punctuation and line[0]*len(line) == line
def fft_bandpassfilter ( data , fs , lowcut , highcut ) : fft = np . fft . fft ( data ) # n = len(data) # timestep = 1.0 / fs # freq = np.fft.fftfreq(n, d=timestep) bp = fft . copy ( ) # Zero out fft coefficients # bp[10:-10] = 0 # Normalise # bp *= real(fft.dot(fft))/real(bp.dot(bp)) bp *= fft . dot ( fft ) / bp . dot ( bp ) # must multipy by 2 to get the correct amplitude ibp = 12 * np . fft . ifft ( bp ) return ibp
1
python fft remove peak
http : // www . swharden . com / blog / 2009 - 01 - 21 - signal - filtering - with - python / #comment - 16801
cosqa-train-12925
def fft_bandpassfilter(data, fs, lowcut, highcut): """ http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801 """ fft = np.fft.fft(data) # n = len(data) # timestep = 1.0 / fs # freq = np.fft.fftfreq(n, d=timestep) bp = fft.copy() # Zero out fft coefficients # bp[10:-10] = 0 # Normalise # bp *= real(fft.dot(fft))/real(bp.dot(bp)) bp *= fft.dot(fft) / bp.dot(bp) # must multipy by 2 to get the correct amplitude ibp = 12 * np.fft.ifft(bp) return ibp
def is_a_sequence ( var , allow_none = False ) : return isinstance ( var , ( list , tuple ) ) or ( var is None and allow_none )
1
check if pythons string is non null
Returns True if var is a list or a tuple ( but not a string! )
cosqa-train-12926
def is_a_sequence(var, allow_none=False): """ Returns True if var is a list or a tuple (but not a string!) """ return isinstance(var, (list, tuple)) or (var is None and allow_none)
def label_saves ( name ) : plt . legend ( loc = 0 ) plt . ylim ( [ 0 , 1.025 ] ) plt . xlabel ( '$U/D$' , fontsize = 20 ) plt . ylabel ( '$Z$' , fontsize = 20 ) plt . savefig ( name , dpi = 300 , format = 'png' , transparent = False , bbox_inches = 'tight' , pad_inches = 0.05 )
1
python figure add title label size
Labels plots and saves file
cosqa-train-12927
def label_saves(name): """Labels plots and saves file""" plt.legend(loc=0) plt.ylim([0, 1.025]) plt.xlabel('$U/D$', fontsize=20) plt.ylabel('$Z$', fontsize=20) plt.savefig(name, dpi=300, format='png', transparent=False, bbox_inches='tight', pad_inches=0.05)
def _stdin_ready_posix ( ) : infds , outfds , erfds = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return bool ( infds )
1
check if stdout ready for reading python
Return True if there s something to read on stdin ( posix version ) .
cosqa-train-12928
def _stdin_ready_posix(): """Return True if there's something to read on stdin (posix version).""" infds, outfds, erfds = select.select([sys.stdin],[],[],0) return bool(infds)
def calculate_top_margin ( self ) : self . border_top = 5 if self . show_graph_title : self . border_top += self . title_font_size self . border_top += 5 if self . show_graph_subtitle : self . border_top += self . subtitle_font_size
1
python figure left margin
Calculate the margin in pixels above the plot area setting border_top .
cosqa-train-12929
def calculate_top_margin(self): """ Calculate the margin in pixels above the plot area, setting border_top. """ self.border_top = 5 if self.show_graph_title: self.border_top += self.title_font_size self.border_top += 5 if self.show_graph_subtitle: self.border_top += self.subtitle_font_size
def is_same_shape ( self , other_im , check_channels = False ) : if self . height == other_im . height and self . width == other_im . width : if check_channels and self . channels != other_im . channels : return False return True return False
1
check if two images are the same python
Checks if two images have the same height and width ( and optionally channels ) .
cosqa-train-12930
def is_same_shape(self, other_im, check_channels=False): """ Checks if two images have the same height and width (and optionally channels). Parameters ---------- other_im : :obj:`Image` image to compare check_channels : bool whether or not to check equality of the channels Returns ------- bool True if the images are the same shape, False otherwise """ if self.height == other_im.height and self.width == other_im.width: if check_channels and self.channels != other_im.channels: return False return True return False
def axes_off ( ax ) : ax . set_frame_on ( False ) ax . axes . get_yaxis ( ) . set_visible ( False ) ax . axes . get_xaxis ( ) . set_visible ( False )
1
python figure no axes
Get rid of all axis ticks lines etc .
cosqa-train-12931
def axes_off(ax): """Get rid of all axis ticks, lines, etc. """ ax.set_frame_on(False) ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False)
def isstring ( value ) : classes = ( str , bytes ) if pyutils . PY3 else basestring # noqa: F821 return isinstance ( value , classes )
1
check is byte string python
Report whether the given value is a byte or unicode string .
cosqa-train-12932
def isstring(value): """Report whether the given value is a byte or unicode string.""" classes = (str, bytes) if pyutils.PY3 else basestring # noqa: F821 return isinstance(value, classes)
def open_file ( file , mode ) : if hasattr ( file , "read" ) : return file if hasattr ( file , "open" ) : return file . open ( mode ) return open ( file , mode )
1
python file opening modes
Open a file .
cosqa-train-12933
def open_file(file, mode): """Open a file. :arg file: file-like or path-like object. :arg str mode: ``mode`` argument for :func:`open`. """ if hasattr(file, "read"): return file if hasattr(file, "open"): return file.open(mode) return open(file, mode)
def update_hash ( cls , filelike , digest ) : block_size = digest . block_size * 1024 for chunk in iter ( lambda : filelike . read ( block_size ) , b'' ) : digest . update ( chunk )
1
python file reading an efficient block size
Update the digest of a single file in a memory - efficient manner .
cosqa-train-12934
def update_hash(cls, filelike, digest): """Update the digest of a single file in a memory-efficient manner.""" block_size = digest.block_size * 1024 for chunk in iter(lambda: filelike.read(block_size), b''): digest.update(chunk)
def _rectangular ( n ) : for i in n : if len ( i ) != len ( n [ 0 ] ) : return False return True
1
check row of 2d list python
Checks to see if a 2D list is a valid 2D matrix
cosqa-train-12935
def _rectangular(n): """Checks to see if a 2D list is a valid 2D matrix""" for i in n: if len(i) != len(n[0]): return False return True
def nb_to_python ( nb_path ) : exporter = python . PythonExporter ( ) output , resources = exporter . from_filename ( nb_path ) return output
0
python file to ipynb
convert notebook to python script
cosqa-train-12936
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
def memory_used ( self ) : if self . _end_memory : memory_used = self . _end_memory - self . _start_memory return memory_used else : return None
1
check runtime memory of a function in python
To know the allocated memory at function termination .
cosqa-train-12937
def memory_used(self): """To know the allocated memory at function termination. ..versionadded:: 4.1 This property might return None if the function is still running. This function should help to show memory leaks or ram greedy code. """ if self._end_memory: memory_used = self._end_memory - self._start_memory return memory_used else: return None
def filter_list_by_indices ( lst , indices ) : return [ x for i , x in enumerate ( lst ) if i in indices ]
1
python filter based on list index
Return a modified list containing only the indices indicated .
cosqa-train-12938
def filter_list_by_indices(lst, indices): """Return a modified list containing only the indices indicated. Args: lst: Original list of values indices: List of indices to keep from the original list Returns: list: Filtered list of values """ return [x for i, x in enumerate(lst) if i in indices]
def is_numeric_dtype ( dtype ) : dtype = np . dtype ( dtype ) return np . issubsctype ( getattr ( dtype , 'base' , None ) , np . number )
1
check that type is numeric in python
Return True if dtype is a numeric type .
cosqa-train-12939
def is_numeric_dtype(dtype): """Return ``True`` if ``dtype`` is a numeric type.""" dtype = np.dtype(dtype) return np.issubsctype(getattr(dtype, 'base', None), np.number)
def selectin ( table , field , value , complement = False ) : return select ( table , field , lambda v : v in value , complement = complement )
1
python filter column isin
Select rows where the given field is a member of the given value .
cosqa-train-12940
def selectin(table, field, value, complement=False): """Select rows where the given field is a member of the given value.""" return select(table, field, lambda v: v in value, complement=complement)
def _check_surrounded_by_space ( self , tokens , i ) : self . _check_space ( tokens , i , ( _MUST , _MUST ) )
1
check the paranthesis in python
Check that a binary operator is surrounded by exactly one space .
cosqa-train-12941
def _check_surrounded_by_space(self, tokens, i): """Check that a binary operator is surrounded by exactly one space.""" self._check_space(tokens, i, (_MUST, _MUST))
def __init__ ( self , function ) : super ( filter , self ) . __init__ ( ) self . function = function
1
python filter object has no attribute append
function : to be called with each stream element as its only argument
cosqa-train-12942
def __init__(self, function): """function: to be called with each stream element as its only argument """ super(filter, self).__init__() self.function = function
def contains_geometric_info ( var ) : return isinstance ( var , tuple ) and len ( var ) == 2 and all ( isinstance ( val , ( int , float ) ) for val in var )
1
check the variable datatype in python
Check whether the passed variable is a tuple with two floats or integers
cosqa-train-12943
def contains_geometric_info(var): """ Check whether the passed variable is a tuple with two floats or integers """ return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)
def get_own_ip ( ) : sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) try : sock . connect ( ( "8.8.8.8" , 80 ) ) except socket . gaierror : ip_ = "127.0.0.1" else : ip_ = sock . getsockname ( ) [ 0 ] finally : sock . close ( ) return ip_
1
python finding own ip
Get the host s ip number .
cosqa-train-12944
def get_own_ip(): """Get the host's ip number. """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.connect(("8.8.8.8", 80)) except socket.gaierror: ip_ = "127.0.0.1" else: ip_ = sock.getsockname()[0] finally: sock.close() return ip_
def is_valid_regex ( string ) : try : re . compile ( string ) is_valid = True except re . error : is_valid = False return is_valid
0
check valid regex python
Checks whether the re module can compile the given regular expression .
cosqa-train-12945
def is_valid_regex(string): """ Checks whether the re module can compile the given regular expression. Parameters ---------- string: str Returns ------- boolean """ try: re.compile(string) is_valid = True except re.error: is_valid = False return is_valid
def load_library ( version ) : check_version ( version ) module_name = SUPPORTED_LIBRARIES [ version ] lib = sys . modules . get ( module_name ) if lib is None : lib = importlib . import_module ( module_name ) return lib
1
check what libraries are loaded in python
Load the correct module according to the version
cosqa-train-12946
def load_library(version): """ Load the correct module according to the version :type version: ``str`` :param version: the version of the library to be loaded (e.g. '2.6') :rtype: module object """ check_version(version) module_name = SUPPORTED_LIBRARIES[version] lib = sys.modules.get(module_name) if lib is None: lib = importlib.import_module(module_name) return lib
def exp_fit_fun ( x , a , tau , c ) : # pylint: disable=invalid-name return a * np . exp ( - x / tau ) + c
1
python fit exponential decay
Function used to fit the exponential decay .
cosqa-train-12947
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 _is_path ( s ) : if isinstance ( s , string_types ) : try : return op . exists ( s ) except ( OSError , ValueError ) : return False else : return False
1
check whether a given string is a path python
Return whether an object is a path .
cosqa-train-12948
def _is_path(s): """Return whether an object is a path.""" if isinstance(s, string_types): try: return op.exists(s) except (OSError, ValueError): return False else: return False
def fit_linear ( X , y ) : model = linear_model . LinearRegression ( ) model . fit ( X , y ) return model
1
python fit linear regression and plot
Uses OLS to fit the regression .
cosqa-train-12949
def fit_linear(X, y): """ Uses OLS to fit the regression. """ model = linear_model.LinearRegression() model.fit(X, y) return model
def hard_equals ( a , b ) : if type ( a ) != type ( b ) : return False return a == b
1
checking for equivalence in python
Implements the === operator .
cosqa-train-12950
def hard_equals(a, b): """Implements the '===' operator.""" if type(a) != type(b): return False return a == b
def fit_gaussian ( samples , ddof = 0 ) : if len ( samples . shape ) == 1 : return np . mean ( samples ) , np . std ( samples , ddof = ddof ) return np . mean ( samples , axis = 1 ) , np . std ( samples , axis = 1 , ddof = ddof )
1
python fitting 2d gaussian
Calculates the mean and the standard deviation of the given samples .
cosqa-train-12951
def fit_gaussian(samples, ddof=0): """Calculates the mean and the standard deviation of the given samples. Args: samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all values. If two dimensional, we fit the Gaussian for every set of samples over the first dimension. ddof (int): the difference degrees of freedom in the std calculation. See numpy. """ if len(samples.shape) == 1: return np.mean(samples), np.std(samples, ddof=ddof) return np.mean(samples, axis=1), np.std(samples, axis=1, ddof=ddof)
def is_cached ( file_name ) : gml_file_path = join ( join ( expanduser ( '~' ) , OCTOGRID_DIRECTORY ) , file_name ) return isfile ( gml_file_path )
1
checking for python cached
Check if a given file is available in the cache or not
cosqa-train-12952
def is_cached(file_name): """ Check if a given file is available in the cache or not """ gml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name) return isfile(gml_file_path)
def fit_gaussian ( x , y , yerr , p0 ) : try : popt , pcov = curve_fit ( gaussian , x , y , sigma = yerr , p0 = p0 , absolute_sigma = True ) except RuntimeError : return [ 0 ] , [ 0 ] return popt , pcov
1
python fitting gaussian data wieghts
Fit a Gaussian to the data
cosqa-train-12953
def fit_gaussian(x, y, yerr, p0): """ Fit a Gaussian to the data """ try: popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True) except RuntimeError: return [0],[0] return popt, pcov
def remove_unsafe_chars ( text ) : if isinstance ( text , six . string_types ) : text = UNSAFE_RE . sub ( '' , text ) return text
1
clean foreign language characters python text
Remove unsafe unicode characters from a piece of text .
cosqa-train-12954
def remove_unsafe_chars(text): """Remove unsafe unicode characters from a piece of text.""" if isinstance(text, six.string_types): text = UNSAFE_RE.sub('', text) return text
def resize ( self , width , height ) : self . _buffer = QtGui . QImage ( width , height , QtGui . QImage . Format_RGB32 ) QtGui . QWidget . resize ( self , width , height )
0
python fix the size of qwidget
cosqa-train-12955
def resize(self, width, height): """ @summary: override resize function @param width: {int} width of widget @param height: {int} height of widget """ self._buffer = QtGui.QImage(width, height, QtGui.QImage.Format_RGB32) QtGui.QWidget.resize(self, width, height)
def check_by_selector ( self , selector ) : elem = find_element_by_jquery ( world . browser , selector ) if not elem . is_selected ( ) : elem . click ( )
1
click a checkbox in webpage python
Check the checkbox matching the CSS selector .
cosqa-train-12956
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 cleanup ( self , app ) : if hasattr ( self . database . obj , 'close_all' ) : self . database . close_all ( )
1
python flask close database after reques
Close all connections .
cosqa-train-12957
def cleanup(self, app): """Close all connections.""" if hasattr(self.database.obj, 'close_all'): self.database.close_all()
def setup_path ( ) : import os . path import sys if sys . argv [ 0 ] : top_dir = os . path . dirname ( os . path . abspath ( sys . argv [ 0 ] ) ) sys . path = [ os . path . join ( top_dir , "src" ) ] + sys . path pass return
1
cmake python include path windows
Sets up the python include paths to include src
cosqa-train-12958
def setup_path(): """Sets up the python include paths to include src""" import os.path; import sys if sys.argv[0]: top_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path = [os.path.join(top_dir, "src")] + sys.path pass return
def logout ( cache ) : cache . set ( flask . session [ 'auth0_key' ] , None ) flask . session . clear ( ) return True
1
python flask create cookie expiration
Logs out the current session by removing it from the cache . This is expected to only occur when a session has
cosqa-train-12959
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
def handle_request_parsing_error ( err , req , schema , error_status_code , error_headers ) : abort ( error_status_code , errors = err . messages )
1
code 400, message bad request syntax python flask
webargs error handler that uses Flask - RESTful s abort function to return a JSON error response to the client .
cosqa-train-12960
def handle_request_parsing_error(err, req, schema, error_status_code, error_headers): """webargs error handler that uses Flask-RESTful's abort function to return a JSON error response to the client. """ abort(error_status_code, errors=err.messages)
def transpose ( table ) : t = [ ] for i in range ( 0 , len ( table [ 0 ] ) ) : t . append ( [ row [ i ] for row in table ] ) return t
1
code to take the transpose of a matrix in python
transpose matrix
cosqa-train-12961
def transpose(table): """ transpose matrix """ t = [] for i in range(0, len(table[0])): t.append([row[i] for row in table]) return t
def logout ( ) : flogin . logout_user ( ) next = flask . request . args . get ( 'next' ) return flask . redirect ( next or flask . url_for ( "user" ) )
1
python flask redirect to login page
Log out the active user
cosqa-train-12962
def logout(): """ Log out the active user """ flogin.logout_user() next = flask.request.args.get('next') return flask.redirect(next or flask.url_for("user"))
def get_average_length_of_string ( strings ) : if not strings : return 0 return sum ( len ( word ) for word in strings ) / len ( strings )
1
codes to count average of length of words in a given text using python
Computes average length of words
cosqa-train-12963
def get_average_length_of_string(strings): """Computes average length of words :param strings: list of words :return: Average length of word on list """ if not strings: return 0 return sum(len(word) for word in strings) / len(strings)
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
python flask return 401 response
HTTP response for not - authorized access ( status code 403 )
cosqa-train-12964
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 str_dict ( some_dict ) : return { str ( k ) : str ( v ) for k , v in some_dict . items ( ) }
1
coerce to string dictionary value python
Convert dict of ascii str / unicode to dict of str if necessary
cosqa-train-12965
def str_dict(some_dict): """Convert dict of ascii str/unicode to dict of str, if necessary""" return {str(k): str(v) for k, v in some_dict.items()}
def staticdir ( ) : root = os . path . abspath ( os . path . dirname ( __file__ ) ) return os . path . join ( root , "static" )
0
python flask static directory
Return the location of the static data directory .
cosqa-train-12966
def staticdir(): """Return the location of the static data directory.""" root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(root, "static")
def colorbar ( height , length , colormap ) : cbar = np . tile ( np . arange ( length ) * 1.0 / ( length - 1 ) , ( height , 1 ) ) cbar = ( cbar * ( colormap . values . max ( ) - colormap . values . min ( ) ) + colormap . values . min ( ) ) return colormap . colorize ( cbar )
1
colorbar to a colormesh python
Return the channels of a colorbar .
cosqa-train-12967
def colorbar(height, length, colormap): """Return the channels of a colorbar. """ cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1)) cbar = (cbar * (colormap.values.max() - colormap.values.min()) + colormap.values.min()) return colormap.colorize(cbar)
def staticdir ( ) : root = os . path . abspath ( os . path . dirname ( __file__ ) ) return os . path . join ( root , "static" )
0
python flask static folder location on other location
Return the location of the static data directory .
cosqa-train-12968
def staticdir(): """Return the location of the static data directory.""" root = os.path.abspath(os.path.dirname(__file__)) return os.path.join(root, "static")
def sample_colormap ( cmap_name , n_samples ) : colors = [ ] colormap = cm . cmap_d [ cmap_name ] for i in np . linspace ( 0 , 1 , n_samples ) : colors . append ( colormap ( i ) ) return colors
1
colormap based on values python
Sample a colormap from matplotlib
cosqa-train-12969
def sample_colormap(cmap_name, n_samples): """ Sample a colormap from matplotlib """ colors = [] colormap = cm.cmap_d[cmap_name] for i in np.linspace(0, 1, n_samples): colors.append(colormap(i)) return colors
def index ( ) : global productpage table = json2html . convert ( json = json . dumps ( productpage ) , table_attributes = "class=\"table table-condensed table-bordered table-hover\"" ) return render_template ( 'index.html' , serviceTable = table )
1
python flask template table example
Display productpage with normal user and test user buttons
cosqa-train-12970
def index(): """ Display productpage with normal user and test user buttons""" global productpage table = json2html.convert(json = json.dumps(productpage), table_attributes="class=\"table table-condensed table-bordered table-hover\"") return render_template('index.html', serviceTable=table)
def save_image ( pdf_path , img_path , page_num ) : pdf_img = Image ( filename = "{}[{}]" . format ( pdf_path , page_num ) ) with pdf_img . convert ( "png" ) as converted : # Set white background. converted . background_color = Color ( "white" ) converted . alpha_channel = "remove" converted . save ( filename = img_path )
1
combine image to pdf python
cosqa-train-12971
def save_image(pdf_path, img_path, page_num): """ Creates images for a page of the input pdf document and saves it at img_path. :param pdf_path: path to pdf to create images for. :param img_path: path where to save the images. :param page_num: page number to create image from in the pdf file. :return: """ pdf_img = Image(filename="{}[{}]".format(pdf_path, page_num)) with pdf_img.convert("png") as converted: # Set white background. converted.background_color = Color("white") converted.alpha_channel = "remove" converted.save(filename=img_path)
def flatten ( nested ) : flat_return = list ( ) def __inner_flat ( nested , flat ) : for i in nested : __inner_flat ( i , flat ) if isinstance ( i , list ) else flat . append ( i ) return flat __inner_flat ( nested , flat_return ) return flat_return
1
python flat nested list
Return a flatten version of the nested argument
cosqa-train-12972
def flatten(nested): """ Return a flatten version of the nested argument """ flat_return = list() def __inner_flat(nested,flat): for i in nested: __inner_flat(i, flat) if isinstance(i, list) else flat.append(i) return flat __inner_flat(nested,flat_return) return flat_return
def hide ( self ) : if not HidePrevention ( self . window ) . may_hide ( ) : return self . hidden = True self . get_widget ( 'window-root' ) . unstick ( ) self . window . hide ( )
1
command to hide a window in python
Hides the main window of the terminal and sets the visible flag to False .
cosqa-train-12973
def hide(self): """Hides the main window of the terminal and sets the visible flag to False. """ if not HidePrevention(self.window).may_hide(): return self.hidden = True self.get_widget('window-root').unstick() self.window.hide()
def flatten ( nested ) : flat_return = list ( ) def __inner_flat ( nested , flat ) : for i in nested : __inner_flat ( i , flat ) if isinstance ( i , list ) else flat . append ( i ) return flat __inner_flat ( nested , flat_return ) return flat_return
0
python flatten a nested list
Return a flatten version of the nested argument
cosqa-train-12974
def flatten(nested): """ Return a flatten version of the nested argument """ flat_return = list() def __inner_flat(nested,flat): for i in nested: __inner_flat(i, flat) if isinstance(i, list) else flat.append(i) return flat __inner_flat(nested,flat_return) return flat_return
def autoscan ( ) : for port in serial . tools . list_ports . comports ( ) : if is_micropython_usb_device ( port ) : connect_serial ( port [ 0 ] )
1
communicating with serial devices in python
autoscan will check all of the serial ports to see if they have a matching VID : PID for a MicroPython board .
cosqa-train-12975
def autoscan(): """autoscan will check all of the serial ports to see if they have a matching VID:PID for a MicroPython board. """ for port in serial.tools.list_ports.comports(): if is_micropython_usb_device(port): connect_serial(port[0])
def flat_list ( lst ) : if isinstance ( lst , list ) : for item in lst : for i in flat_list ( item ) : yield i else : yield lst
1
python flatten nested doublylinkedlist recursively
This function flatten given nested list . Argument : nested list Returns : flat list
cosqa-train-12976
def flat_list(lst): """This function flatten given nested list. Argument: nested list Returns: flat list """ if isinstance(lst, list): for item in lst: for i in flat_list(item): yield i else: yield lst
def retrieve_by_id ( self , id_ ) : items_with_id = [ item for item in self if item . id == int ( id_ ) ] if len ( items_with_id ) == 1 : return items_with_id [ 0 ] . retrieve ( )
1
comobject get item by id python
Return a JSSObject for the element with ID id_
cosqa-train-12977
def retrieve_by_id(self, id_): """Return a JSSObject for the element with ID id_""" items_with_id = [item for item in self if item.id == int(id_)] if len(items_with_id) == 1: return items_with_id[0].retrieve()
def flatten ( lis ) : new_lis = [ ] for item in lis : if isinstance ( item , collections . Sequence ) and not isinstance ( item , basestring ) : new_lis . extend ( flatten ( item ) ) else : new_lis . append ( item ) return new_lis
1
python flattening nested list
Given a list possibly nested to any level return it flattened .
cosqa-train-12978
def flatten(lis): """Given a list, possibly nested to any level, return it flattened.""" new_lis = [] for item in lis: if isinstance(item, collections.Sequence) and not isinstance(item, basestring): new_lis.extend(flatten(item)) else: new_lis.append(item) return new_lis
def _compile ( pattern , flags ) : return re . compile ( WcParse ( pattern , flags & FLAG_MASK ) . parse ( ) )
1
compile(pattern [, flags]) python
Compile the pattern to regex .
cosqa-train-12979
def _compile(pattern, flags): """Compile the pattern to regex.""" return re.compile(WcParse(pattern, flags & FLAG_MASK).parse())
def round_sig ( x , sig ) : return round ( x , sig - int ( floor ( log10 ( abs ( x ) ) ) ) - 1 )
1
python float to specific number of significant digits
Round the number to the specified number of significant figures
cosqa-train-12980
def round_sig(x, sig): """Round the number to the specified number of significant figures""" return round(x, sig - int(floor(log10(abs(x)))) - 1)
def clean_whitespace ( string , compact = False ) : for a , b in ( ( '\r\n' , '\n' ) , ( '\r' , '\n' ) , ( '\n\n' , '\n' ) , ( '\t' , ' ' ) , ( ' ' , ' ' ) ) : string = string . replace ( a , b ) if compact : for a , b in ( ( '\n' , ' ' ) , ( '[ ' , '[' ) , ( ' ' , ' ' ) , ( ' ' , ' ' ) , ( ' ' , ' ' ) ) : string = string . replace ( a , b ) return string . strip ( )
1
compress multiple white space to single python
Return string with compressed whitespace .
cosqa-train-12981
def clean_whitespace(string, compact=False): """Return string with compressed whitespace.""" for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'), ('\t', ' '), (' ', ' ')): string = string.replace(a, b) if compact: for a, b in (('\n', ' '), ('[ ', '['), (' ', ' '), (' ', ' '), (' ', ' ')): string = string.replace(a, b) return string.strip()
def _convert ( self , image , output = None ) : with Image . open ( image ) as im : width , height = im . size co = CanvasObjects ( ) co . add ( CanvasImg ( image , 1.0 , w = width , h = height ) ) return WatermarkDraw ( co , tempdir = self . tempdir , pagesize = ( width , height ) ) . write ( output )
0
python for images to pdf
Private method for converting a single PNG image to a PDF .
cosqa-train-12982
def _convert(self, image, output=None): """Private method for converting a single PNG image to a PDF.""" with Image.open(image) as im: width, height = im.size co = CanvasObjects() co.add(CanvasImg(image, 1.0, w=width, h=height)) return WatermarkDraw(co, tempdir=self.tempdir, pagesize=(width, height)).write(output)
def cor ( y_true , y_pred ) : y_true , y_pred = _mask_nan ( y_true , y_pred ) return np . corrcoef ( y_true , y_pred ) [ 0 , 1 ]
1
compute correlation for x and y in python
Compute Pearson correlation coefficient .
cosqa-train-12983
def cor(y_true, y_pred): """Compute Pearson correlation coefficient. """ y_true, y_pred = _mask_nan(y_true, y_pred) return np.corrcoef(y_true, y_pred)[0, 1]
def _read_indexlist ( self , name ) : setattr ( self , '_' + name , [ self . _timeline [ int ( i ) ] for i in self . db . lrange ( 'site:{0}' . format ( name ) , 0 , - 1 ) ] )
1
python for index scope
Read a list of indexes .
cosqa-train-12984
def _read_indexlist(self, name): """Read a list of indexes.""" setattr(self, '_' + name, [self._timeline[int(i)] for i in self.db.lrange('site:{0}'.format(name), 0, -1)])
def flush ( self ) : if not self . nostdout : self . stdout . flush ( ) if self . file is not None : self . file . flush ( )
1
python force print to flush
Force commit changes to the file and stdout
cosqa-train-12985
def flush(self): """ Force commit changes to the file and stdout """ if not self.nostdout: self.stdout.flush() if self.file is not None: self.file.flush()
def __add__ ( self , other ) : return concat ( self , other , copy = True , inplace = False )
1
concat two objects in python
Concatenate two InferenceData objects .
cosqa-train-12986
def __add__(self, other): """Concatenate two InferenceData objects.""" return concat(self, other, copy=True, inplace=False)
def visit_Str ( self , node ) : self . result [ node ] = self . builder . NamedType ( pytype_to_ctype ( str ) )
0
python force variabel to type string
Set the pythonic string type .
cosqa-train-12987
def visit_Str(self, node): """ Set the pythonic string type. """ self.result[node] = self.builder.NamedType(pytype_to_ctype(str))
def error_rate ( predictions , labels ) : return 100.0 - ( 100.0 * np . sum ( np . argmax ( predictions , 1 ) == np . argmax ( labels , 1 ) ) / predictions . shape [ 0 ] )
0
confidence interval on predict regression in python
Return the error rate based on dense predictions and 1 - hot labels .
cosqa-train-12988
def error_rate(predictions, labels): """Return the error rate based on dense predictions and 1-hot labels.""" return 100.0 - ( 100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0])
def safe_format ( s , * * kwargs ) : return string . Formatter ( ) . vformat ( s , ( ) , defaultdict ( str , * * kwargs ) )
1
python format string with named args
: type s str
cosqa-train-12989
def safe_format(s, **kwargs): """ :type s str """ return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))
def main ( ctx , connection ) : ctx . obj = Manager ( connection = connection ) ctx . obj . bind ( )
1
connect python to frontend
Command line interface for PyBEL .
cosqa-train-12990
def main(ctx, connection): """Command line interface for PyBEL.""" ctx.obj = Manager(connection=connection) ctx.obj.bind()
def fixed ( ctx , number , decimals = 2 , no_commas = False ) : value = _round ( ctx , number , decimals ) format_str = '{:f}' if no_commas else '{:,f}' return format_str . format ( value )
1
python formatting round to 2 decimals fixed
Formats the given number in decimal format using a period and commas
cosqa-train-12991
def fixed(ctx, number, decimals=2, no_commas=False): """ Formats the given number in decimal format using a period and commas """ value = _round(ctx, number, decimals) format_str = '{:f}' if no_commas else '{:,f}' return format_str.format(value)
def instance_contains ( container , item ) : return item in ( member for _ , member in inspect . getmembers ( container ) )
1
contains method of list in python
Search into instance attributes properties and return values of no - args methods .
cosqa-train-12992
def instance_contains(container, item): """Search into instance attributes, properties and return values of no-args methods.""" return item in (member for _, member in inspect.getmembers(container))
def median ( ls ) : ls = sorted ( ls ) return ls [ int ( floor ( len ( ls ) / 2.0 ) ) ]
1
python formula for median of even numbered list
Takes a list and returns the median .
cosqa-train-12993
def median(ls): """ Takes a list and returns the median. """ ls = sorted(ls) return ls[int(floor(len(ls)/2.0))]
def list_i2str ( ilist ) : slist = [ ] for el in ilist : slist . append ( str ( el ) ) return slist
1
convertir a list into string python
Convert an integer list into a string list .
cosqa-train-12994
def list_i2str(ilist): """ Convert an integer list into a string list. """ slist = [] for el in ilist: slist.append(str(el)) return slist
def RMS_energy ( frames ) : f = frames . flatten ( ) return N . sqrt ( N . mean ( f * f ) )
0
python frame based energy
Computes the RMS energy of frames
cosqa-train-12995
def RMS_energy(frames): """Computes the RMS energy of frames""" f = frames.flatten() return N.sqrt(N.mean(f * f))
def convolve_gaussian_2d ( image , gaussian_kernel_1d ) : result = scipy . ndimage . filters . correlate1d ( image , gaussian_kernel_1d , axis = 0 ) result = scipy . ndimage . filters . correlate1d ( result , gaussian_kernel_1d , axis = 1 ) return result
1
convolve 2d gaussian python
Convolve 2d gaussian .
cosqa-train-12996
def convolve_gaussian_2d(image, gaussian_kernel_1d): """Convolve 2d gaussian.""" result = scipy.ndimage.filters.correlate1d( image, gaussian_kernel_1d, axis=0) result = scipy.ndimage.filters.correlate1d( result, gaussian_kernel_1d, axis=1) return result
def INIT_LIST_EXPR ( self , cursor ) : values = [ self . parse_cursor ( child ) for child in list ( cursor . get_children ( ) ) ] return values
0
python from cursor to list
Returns a list of literal values .
cosqa-train-12997
def INIT_LIST_EXPR(self, cursor): """Returns a list of literal values.""" values = [self.parse_cursor(child) for child in list(cursor.get_children())] return values
def _convert_to_array ( array_like , dtype ) : if isinstance ( array_like , bytes ) : return np . frombuffer ( array_like , dtype = dtype ) return np . asarray ( array_like , dtype = dtype )
0
copy python numpy array poooooaaaaa1
Convert Matrix attributes which are array - like or buffer to array .
cosqa-train-12998
def _convert_to_array(array_like, dtype): """ Convert Matrix attributes which are array-like or buffer to array. """ if isinstance(array_like, bytes): return np.frombuffer(array_like, dtype=dtype) return np.asarray(array_like, dtype=dtype)
def remote_file_exists ( self , url ) : status = requests . head ( url ) . status_code if status != 200 : raise RemoteFileDoesntExist
0
python ftplib check whether file exists
Checks whether the remote file exists .
cosqa-train-12999
def remote_file_exists(self, url): """ Checks whether the remote file exists. :param url: The url that has to be checked. :type url: String :returns: **True** if remote file exists and **False** if it doesn't exist. """ status = requests.head(url).status_code if status != 200: raise RemoteFileDoesntExist