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 replace ( s , replace ) : for r in replace : s = s . replace ( * r ) return s
1
how to replace string python
Replace multiple values in a string
cosqa-train-14000
def replace(s, replace): """Replace multiple values in a string""" for r in replace: s = s.replace(*r) return s
def set_limits ( self , min_ = None , max_ = None ) : self . _min , self . _max = min_ , max_
1
python setting a max and min value
Sets limits for this config value
cosqa-train-14001
def set_limits(self, min_=None, max_=None): """ Sets limits for this config value If the resulting integer is outside those limits, an exception will be raised :param min_: minima :param max_: maxima """ self._min, self._max = min_, max_
def _replace_nan ( a , val ) : mask = isnull ( a ) return where_method ( val , mask , a ) , mask
0
how to replace values with na in python
replace nan in a by val and returns the replaced array and the nan position
cosqa-train-14002
def _replace_nan(a, val): """ replace nan in a by val, and returns the replaced array and the nan position """ mask = isnull(a) return where_method(val, mask, a), mask
def _int64_feature ( value ) : if not isinstance ( value , list ) : value = [ value ] return tf . train . Feature ( int64_list = tf . train . Int64List ( value = value ) )
0
python setting array elemnt as a sequence tensorflow
Wrapper for inserting int64 features into Example proto .
cosqa-train-14003
def _int64_feature(value): """Wrapper for inserting int64 features into Example proto.""" if not isinstance(value, list): value = [value] return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def restart_program ( ) : python = sys . executable os . execl ( python , python , * sys . argv )
1
how to rerun a program due to user imput python
DOES NOT WORK WELL WITH MOPIDY Hack from https : // www . daniweb . com / software - development / python / code / 260268 / restart - your - python - program to support updating the settings since mopidy is not able to do that yet Restarts the current program Note : this function does not return . Any cleanup action ( like saving data ) must be done before calling this function
cosqa-train-14004
def restart_program(): """ DOES NOT WORK WELL WITH MOPIDY Hack from https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program to support updating the settings, since mopidy is not able to do that yet Restarts the current program Note: this function does not return. Any cleanup action (like saving data) must be done before calling this function """ python = sys.executable os.execl(python, python, * sys.argv)
def main ( argv , version = DEFAULT_VERSION ) : tarball = download_setuptools ( ) _install ( tarball , _build_install_args ( argv ) )
0
python setuptools single core
Install or upgrade setuptools and EasyInstall
cosqa-train-14005
def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" tarball = download_setuptools() _install(tarball, _build_install_args(argv))
def set_scale ( self , scale , no_reset = False ) : return self . scale_to ( * scale [ : 2 ] , no_reset = no_reset )
1
how to rescale 0 to 255 to gray scale image in python
Scale the image in a channel . Also see : meth : zoom_to .
cosqa-train-14006
def set_scale(self, scale, no_reset=False): """Scale the image in a channel. Also see :meth:`zoom_to`. Parameters ---------- scale : tuple of float Scaling factors for the image in the X and Y axes. no_reset : bool Do not reset ``autozoom`` setting. """ return self.scale_to(*scale[:2], no_reset=no_reset)
def format_line ( data , linestyle ) : return linestyle . begin + linestyle . sep . join ( data ) + linestyle . end
0
python shapely line string
Formats a list of elements using the given line style
cosqa-train-14007
def format_line(data, linestyle): """Formats a list of elements using the given line style""" return linestyle.begin + linestyle.sep.join(data) + linestyle.end
def reset ( self ) : self . __iterator , self . __saved = itertools . tee ( self . __saved )
1
how to reset an iterator python
Resets the iterator to the start .
cosqa-train-14008
def reset(self): """ Resets the iterator to the start. Any remaining values in the current iteration are discarded. """ self.__iterator, self.__saved = itertools.tee(self.__saved)
def close ( self ) : if not self . closed : self . closed = True self . _flush ( finish = True ) self . _buffer = None
1
python should you flush before closing a file
Flush the buffer and finalize the file .
cosqa-train-14009
def close(self): """Flush the buffer and finalize the file. When this returns the new file is available for reading. """ if not self.closed: self.closed = True self._flush(finish=True) self._buffer = None
def __init__ ( self , iterable ) : self . _values = [ ] self . _iterable = iterable self . _initialized = False self . _depleted = False self . _offset = 0
0
how to reset iteratable python
Initialize the cycle with some iterable .
cosqa-train-14010
def __init__(self, iterable): """Initialize the cycle with some iterable.""" self._values = [] self._iterable = iterable self._initialized = False self._depleted = False self._offset = 0
def uniq ( seq ) : seen = set ( ) return [ x for x in seq if str ( x ) not in seen and not seen . add ( str ( x ) ) ]
1
python show all the uniques
Return a copy of seq without duplicates .
cosqa-train-14011
def uniq(seq): """ Return a copy of seq without duplicates. """ seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
def restore_default_settings ( ) : global __DEFAULTS __DEFAULTS . CACHE_DIR = defaults . CACHE_DIR __DEFAULTS . SET_SEED = defaults . SET_SEED __DEFAULTS . SEED = defaults . SEED logging . info ( 'Settings reverted to their default values.' )
1
how to reset python setting to default
Restore settings to default values .
cosqa-train-14012
def restore_default_settings(): """ Restore settings to default values. """ global __DEFAULTS __DEFAULTS.CACHE_DIR = defaults.CACHE_DIR __DEFAULTS.SET_SEED = defaults.SET_SEED __DEFAULTS.SEED = defaults.SEED logging.info('Settings reverted to their default values.')
def print_message ( message = None ) : kwargs = { 'stdout' : sys . stdout , 'stderr' : sys . stderr , 'shell' : True } return subprocess . call ( 'echo "{0}"' . format ( message or '' ) , * * kwargs )
1
python show message from subprocess
Print message via subprocess . call function .
cosqa-train-14013
def print_message(message=None): """Print message via ``subprocess.call`` function. This helps to ensure consistent output and avoid situations where print messages actually shown after messages from all inner threads. :param message: Text message to print. """ kwargs = {'stdout': sys.stdout, 'stderr': sys.stderr, 'shell': True} return subprocess.call('echo "{0}"'.format(message or ''), **kwargs)
def horz_dpi ( self ) : pHYs = self . _chunks . pHYs if pHYs is None : return 72 return self . _dpi ( pHYs . units_specifier , pHYs . horz_px_per_unit )
1
how to resize to 300 dpi in pixels python
Integer dots per inch for the width of this image . Defaults to 72 when not present in the file as is often the case .
cosqa-train-14014
def horz_dpi(self): """ Integer dots per inch for the width of this image. Defaults to 72 when not present in the file, as is often the case. """ pHYs = self._chunks.pHYs if pHYs is None: return 72 return self._dpi(pHYs.units_specifier, pHYs.horz_px_per_unit)
def _get_var_from_string ( item ) : modname , varname = _split_mod_var_names ( item ) if modname : mod = __import__ ( modname , globals ( ) , locals ( ) , [ varname ] , - 1 ) return getattr ( mod , varname ) else : return globals ( ) [ varname ]
1
how to resolve a variable inside a string in python
Get resource variable .
cosqa-train-14015
def _get_var_from_string(item): """ Get resource variable. """ modname, varname = _split_mod_var_names(item) if modname: mod = __import__(modname, globals(), locals(), [varname], -1) return getattr(mod, varname) else: return globals()[varname]
def bin_to_int ( string ) : if isinstance ( string , str ) : return struct . unpack ( "b" , string ) [ 0 ] else : return struct . unpack ( "b" , bytes ( [ string ] ) ) [ 0 ]
1
python signed int from bytes
Convert a one element byte string to signed int for python 2 support .
cosqa-train-14016
def bin_to_int(string): """Convert a one element byte string to signed int for python 2 support.""" if isinstance(string, str): return struct.unpack("b", string)[0] else: return struct.unpack("b", bytes([string]))[0]
def segments_to_numpy ( segments ) : segments = numpy . array ( segments , dtype = SEGMENT_DATATYPE , ndmin = 2 ) # each segment in a row segments = segments if SEGMENTS_DIRECTION == 0 else numpy . transpose ( segments ) return segments
0
how to restrict a multi dimensional array output to 3 significant figures in python numpy
given a list of 4 - element tuples transforms it into a numpy array
cosqa-train-14017
def segments_to_numpy(segments): """given a list of 4-element tuples, transforms it into a numpy array""" segments = numpy.array(segments, dtype=SEGMENT_DATATYPE, ndmin=2) # each segment in a row segments = segments if SEGMENTS_DIRECTION == 0 else numpy.transpose(segments) return segments
def view_500 ( request , url = None ) : res = render_to_response ( "500.html" , context_instance = RequestContext ( request ) ) res . status_code = 500 return res
1
python simplehttpserver 404 page
it returns a 500 http response
cosqa-train-14018
def view_500(request, url=None): """ it returns a 500 http response """ res = render_to_response("500.html", context_instance=RequestContext(request)) res.status_code = 500 return res
def search_index_file ( ) : from metapack import Downloader from os import environ return environ . get ( 'METAPACK_SEARCH_INDEX' , Downloader . get_instance ( ) . cache . getsyspath ( 'index.json' ) )
1
how to retrieve index file python
Return the default local index file from the download cache
cosqa-train-14019
def search_index_file(): """Return the default local index file, from the download cache""" from metapack import Downloader from os import environ return environ.get('METAPACK_SEARCH_INDEX', Downloader.get_instance().cache.getsyspath('index.json'))
def _connect ( self , servers ) : self . _do_connect ( servers . split ( ' ' ) ) self . _verify_connection ( verbose = True )
1
python simplest way to connect to server
connect to the given server e . g . : \\ connect localhost : 4200
cosqa-train-14020
def _connect(self, servers): """ connect to the given server, e.g.: \\connect localhost:4200 """ self._do_connect(servers.split(' ')) self._verify_connection(verbose=True)
def get_value ( key , obj , default = missing ) : if isinstance ( key , int ) : return _get_value_for_key ( key , obj , default ) return _get_value_for_keys ( key . split ( '.' ) , obj , default )
1
how to return a key given value in python
Helper for pulling a keyed value off various types of objects
cosqa-train-14021
def get_value(key, obj, default=missing): """Helper for pulling a keyed value off various types of objects""" if isinstance(key, int): return _get_value_for_key(key, obj, default) return _get_value_for_keys(key.split('.'), obj, default)
def singleton ( class_ ) : instances = { } def get_instance ( * args , * * kwargs ) : if class_ not in instances : instances [ class_ ] = class_ ( * args , * * kwargs ) return instances [ class_ ] return get_instance
1
python singleton instance none
Singleton definition .
cosqa-train-14022
def singleton(class_): """Singleton definition. Method 1 from https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python """ instances = {} def get_instance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return get_instance
def getTuple ( self ) : return ( self . x , self . y , self . w , self . h )
1
how to return a rectangle in python
Returns the shape of the region as ( x y w h )
cosqa-train-14023
def getTuple(self): """ Returns the shape of the region as (x, y, w, h) """ return (self.x, self.y, self.w, self.h)
def singleton ( class_ ) : instances = { } def get_instance ( * args , * * kwargs ) : if class_ not in instances : instances [ class_ ] = class_ ( * args , * * kwargs ) return instances [ class_ ] return get_instance
1
python singleton several instances
Singleton definition .
cosqa-train-14024
def singleton(class_): """Singleton definition. Method 1 from https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python """ instances = {} def get_instance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return get_instance
def get_list_index ( lst , index_or_name ) : if isinstance ( index_or_name , six . integer_types ) : return index_or_name return lst . index ( index_or_name )
0
how to return an index from a list location python
Return the index of an element in the list .
cosqa-train-14025
def get_list_index(lst, index_or_name): """ Return the index of an element in the list. Args: lst (list): The list. index_or_name (int or str): The value of the reference element, or directly its numeric index. Returns: (int) The index of the element in the list. """ if isinstance(index_or_name, six.integer_types): return index_or_name return lst.index(index_or_name)
def skip ( self , n ) : try : self . _iter_object . skip ( n ) except AttributeError : for i in range ( 0 , n ) : self . next ( )
1
python skip next loop
Skip the specified number of elements in the list .
cosqa-train-14026
def skip(self, n): """Skip the specified number of elements in the list. If the number skipped is greater than the number of elements in the list, hasNext() becomes false and available() returns zero as there are no more elements to retrieve. arg: n (cardinal): the number of elements to skip *compliance: mandatory -- This method must be implemented.* """ try: self._iter_object.skip(n) except AttributeError: for i in range(0, n): self.next()
def offsets ( self ) : return np . array ( [ self . x_offset , self . y_offset , self . z_offset ] )
0
how to return array inpython
Returns the offsets values of x y z as a numpy array
cosqa-train-14027
def offsets(self): """ Returns the offsets values of x, y, z as a numpy array """ return np.array([self.x_offset, self.y_offset, self.z_offset])
def _skip_frame ( self ) : size = self . read_size ( ) for i in range ( size + 1 ) : line = self . _f . readline ( ) if len ( line ) == 0 : raise StopIteration
1
python skip to beginning of next line in file
Skip a single frame from the trajectory
cosqa-train-14028
def _skip_frame(self): """Skip a single frame from the trajectory""" size = self.read_size() for i in range(size+1): line = self._f.readline() if len(line) == 0: raise StopIteration
def to_camel_case ( text ) : split = text . split ( '_' ) return split [ 0 ] + "" . join ( x . title ( ) for x in split [ 1 : ] )
1
how to return capitalized letter in python
Convert to camel case .
cosqa-train-14029
def to_camel_case(text): """Convert to camel case. :param str text: :rtype: str :return: """ split = text.split('_') return split[0] + "".join(x.title() for x in split[1:])
def euclidean ( c1 , c2 ) : diffs = ( ( i - j ) for i , j in zip ( c1 , c2 ) ) return sum ( x * x for x in diffs )
1
python sklearn calculate the euclidean distance between the two points of each pair
Square of the euclidean distance
cosqa-train-14030
def euclidean(c1, c2): """Square of the euclidean distance""" diffs = ((i - j) for i, j in zip(c1, c2)) return sum(x * x for x in diffs)
def earth_orientation ( date ) : x_p , y_p , s_prime = np . deg2rad ( _earth_orientation ( date ) ) return rot3 ( - s_prime ) @ rot2 ( x_p ) @ rot1 ( y_p )
0
how to rotate a star in python
Earth orientation as a rotating matrix
cosqa-train-14031
def earth_orientation(date): """Earth orientation as a rotating matrix """ x_p, y_p, s_prime = np.deg2rad(_earth_orientation(date)) return rot3(-s_prime) @ rot2(x_p) @ rot1(y_p)
def cluster_kmeans ( data , n_clusters , * * kwargs ) : km = cl . KMeans ( n_clusters , * * kwargs ) kmf = km . fit ( data ) labels = kmf . labels_ return labels , [ np . nan ]
1
python sklearn kmeans transform cluster centers
Identify clusters using K - Means algorithm .
cosqa-train-14032
def cluster_kmeans(data, n_clusters, **kwargs): """ Identify clusters using K - Means algorithm. Parameters ---------- data : array_like array of size [n_samples, n_features]. n_clusters : int The number of clusters expected in the data. Returns ------- dict boolean array for each identified cluster. """ km = cl.KMeans(n_clusters, **kwargs) kmf = km.fit(data) labels = kmf.labels_ return labels, [np.nan]
def round_to_n ( x , n ) : return round ( x , - int ( np . floor ( np . log10 ( x ) ) ) + ( n - 1 ) )
1
how to round sig figs python
Round to sig figs
cosqa-train-14033
def round_to_n(x, n): """ Round to sig figs """ return round(x, -int(np.floor(np.log10(x))) + (n - 1))
def ReverseV2 ( a , axes ) : idxs = tuple ( slice ( None , None , 2 * int ( i not in axes ) - 1 ) for i in range ( len ( a . shape ) ) ) return np . copy ( a [ idxs ] ) ,
1
python slice numpy inverse
Reverse op .
cosqa-train-14034
def ReverseV2(a, axes): """ Reverse op. """ idxs = tuple(slice(None, None, 2 * int(i not in axes) - 1) for i in range(len(a.shape))) return np.copy(a[idxs]),
def runcode ( code ) : for line in code : print ( '# ' + line ) exec ( line , globals ( ) ) print ( '# return ans' ) return ans
1
how to run a code line by line in python
Run the given code line by line with printing as list of lines and return variable ans .
cosqa-train-14035
def runcode(code): """Run the given code line by line with printing, as list of lines, and return variable 'ans'.""" for line in code: print('# '+line) exec(line,globals()) print('# return ans') return ans
def Slice ( a , begin , size ) : return np . copy ( a ) [ [ slice ( * tpl ) for tpl in zip ( begin , begin + size ) ] ] ,
1
python slice to visit list
Slicing op .
cosqa-train-14036
def Slice(a, begin, size): """ Slicing op. """ return np.copy(a)[[slice(*tpl) for tpl in zip(begin, begin+size)]],
def web ( host , port ) : from . webserver . web import get_app get_app ( ) . run ( host = host , port = port )
1
how to run a local webserver useing python
Start web application
cosqa-train-14037
def web(host, port): """Start web application""" from .webserver.web import get_app get_app().run(host=host, port=port)
def set_slug ( apps , schema_editor ) : Event = apps . get_model ( 'spectator_events' , 'Event' ) for e in Event . objects . all ( ) : e . slug = generate_slug ( e . pk ) e . save ( update_fields = [ 'slug' ] )
1
python slug foreign view
Create a slug for each Event already in the DB .
cosqa-train-14038
def set_slug(apps, schema_editor): """ Create a slug for each Event already in the DB. """ Event = apps.get_model('spectator_events', 'Event') for e in Event.objects.all(): e.slug = generate_slug(e.pk) e.save(update_fields=['slug'])
def runcode ( code ) : for line in code : print ( '# ' + line ) exec ( line , globals ( ) ) print ( '# return ans' ) return ans
0
how to run code line by line in python
Run the given code line by line with printing as list of lines and return variable ans .
cosqa-train-14039
def runcode(code): """Run the given code line by line with printing, as list of lines, and return variable 'ans'.""" for line in code: print('# '+line) exec(line,globals()) print('# return ans') return ans
def wait_send ( self , timeout = None ) : self . _send_queue_cleared . clear ( ) self . _send_queue_cleared . wait ( timeout = timeout )
1
python socket send without delay
Wait until all queued messages are sent .
cosqa-train-14040
def wait_send(self, timeout = None): """Wait until all queued messages are sent.""" self._send_queue_cleared.clear() self._send_queue_cleared.wait(timeout = timeout)
def debug_src ( src , pm = False , globs = None ) : testsrc = script_from_examples ( src ) debug_script ( testsrc , pm , globs )
0
how to run doctest python on cmd
Debug a single doctest docstring in argument src
cosqa-train-14041
def debug_src(src, pm=False, globs=None): """Debug a single doctest docstring, in argument `src`'""" testsrc = script_from_examples(src) debug_script(testsrc, pm, globs)
def enable_ssl ( self , * args , * * kwargs ) : if self . handshake_sent : raise SSLError ( 'can only enable SSL before handshake' ) self . secure = True self . sock = ssl . wrap_socket ( self . sock , * args , * * kwargs )
0
python socket ssl set not verify
Transforms the regular socket . socket to an ssl . SSLSocket for secure connections . Any arguments are passed to ssl . wrap_socket : http : // docs . python . org / dev / library / ssl . html#ssl . wrap_socket
cosqa-train-14042
def enable_ssl(self, *args, **kwargs): """ Transforms the regular socket.socket to an ssl.SSLSocket for secure connections. Any arguments are passed to ssl.wrap_socket: http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket """ if self.handshake_sent: raise SSLError('can only enable SSL before handshake') self.secure = True self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)
def save ( variable , filename ) : fileObj = open ( filename , 'wb' ) pickle . dump ( variable , fileObj ) fileObj . close ( )
1
how to save a variable into a file in python
Save variable on given path using Pickle Args : variable : what to save path ( str ) : path of the output
cosqa-train-14043
def save(variable, filename): """Save variable on given path using Pickle Args: variable: what to save path (str): path of the output """ fileObj = open(filename, 'wb') pickle.dump(variable, fileObj) fileObj.close()
def unsort_vector ( data , indices_of_increasing ) : return numpy . array ( [ data [ indices_of_increasing . index ( i ) ] for i in range ( len ( data ) ) ] )
0
python sort a 2d array by first index
Upermutate 1 - D data that is sorted by indices_of_increasing .
cosqa-train-14044
def unsort_vector(data, indices_of_increasing): """Upermutate 1-D data that is sorted by indices_of_increasing.""" return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))])
def save_excel ( self , fd ) : from pylon . io . excel import ExcelWriter ExcelWriter ( self ) . write ( fd )
0
how to save an excel document from python
Saves the case as an Excel spreadsheet .
cosqa-train-14045
def save_excel(self, fd): """ Saves the case as an Excel spreadsheet. """ from pylon.io.excel import ExcelWriter ExcelWriter(self).write(fd)
def _rows_sort ( self , rows ) : return sorted ( rows , key = lambda row : ( row [ self . _key_start_date ] , row [ self . _key_end_date ] ) )
0
python sort by datekey column
Returns a list of rows sorted by start and end date .
cosqa-train-14046
def _rows_sort(self, rows): """ Returns a list of rows sorted by start and end date. :param list[dict[str,T]] rows: The list of rows. :rtype: list[dict[str,T]] """ return sorted(rows, key=lambda row: (row[self._key_start_date], row[self._key_end_date]))
def save ( self , fname ) : with open ( fname , 'wb' ) as f : json . dump ( self , f )
1
how to save dictionary of object to file python
Saves the dictionary in json format : param fname : file to save to
cosqa-train-14047
def save(self, fname): """ Saves the dictionary in json format :param fname: file to save to """ with open(fname, 'wb') as f: json.dump(self, f)
def unique_list_dicts ( dlist , key ) : return list ( dict ( ( val [ key ] , val ) for val in dlist ) . values ( ) )
0
python sort list of dictionaryies duplicate
Return a list of dictionaries which are sorted for only unique entries .
cosqa-train-14048
def unique_list_dicts(dlist, key): """Return a list of dictionaries which are sorted for only unique entries. :param dlist: :param key: :return list: """ return list(dict((val[key], val) for val in dlist).values())
def to_html ( self , write_to ) : page_html = self . get_html ( ) with open ( write_to , "wb" ) as writefile : writefile . write ( page_html . encode ( "utf-8" ) )
0
how to save query results to a file in python
Method to convert the repository list to a search results page and write it to a HTML file .
cosqa-train-14049
def to_html(self, write_to): """Method to convert the repository list to a search results page and write it to a HTML file. :param write_to: File/Path to write the html file to. """ page_html = self.get_html() with open(write_to, "wb") as writefile: writefile.write(page_html.encode("utf-8"))
def sort_data ( x , y ) : xy = sorted ( zip ( x , y ) ) x , y = zip ( * xy ) return x , y
1
python sort the same values
Sort the data .
cosqa-train-14050
def sort_data(x, y): """Sort the data.""" xy = sorted(zip(x, y)) x, y = zip(*xy) return x, y
def get_object_attrs ( obj ) : attrs = [ k for k in dir ( obj ) if not k . startswith ( '__' ) ] if not attrs : attrs = dir ( obj ) return attrs
1
how to see all the fields of an object python
Get the attributes of an object using dir .
cosqa-train-14051
def get_object_attrs(obj): """ Get the attributes of an object using dir. This filters protected attributes """ attrs = [k for k in dir(obj) if not k.startswith('__')] if not attrs: attrs = dir(obj) return attrs
def sort_data ( x , y ) : xy = sorted ( zip ( x , y ) ) x , y = zip ( * xy ) return x , y
0
python sort x,y pair
Sort the data .
cosqa-train-14052
def sort_data(x, y): """Sort the data.""" xy = sorted(zip(x, y)) x, y = zip(*xy) return x, y
def _uniquify ( _list ) : seen = set ( ) result = [ ] for x in _list : if x not in seen : result . append ( x ) seen . add ( x ) return result
1
how to see all the strings in a list that are unique in python
Remove duplicates in a list .
cosqa-train-14053
def _uniquify(_list): """Remove duplicates in a list.""" seen = set() result = [] for x in _list: if x not in seen: result.append(x) seen.add(x) return result
def scipy_sparse_to_spmatrix ( A ) : coo = A . tocoo ( ) SP = spmatrix ( coo . data . tolist ( ) , coo . row . tolist ( ) , coo . col . tolist ( ) , size = A . shape ) return SP
1
python sparse matrix derminate
Efficient conversion from scipy sparse matrix to cvxopt sparse matrix
cosqa-train-14054
def scipy_sparse_to_spmatrix(A): """Efficient conversion from scipy sparse matrix to cvxopt sparse matrix""" coo = A.tocoo() SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape) return SP
def Print ( self , output_writer ) : if self . _filters : output_writer . Write ( 'Filters:\n' ) for file_entry_filter in self . _filters : file_entry_filter . Print ( output_writer )
1
how to see contents of filter object python
Prints a human readable version of the filter .
cosqa-train-14055
def Print(self, output_writer): """Prints a human readable version of the filter. Args: output_writer (CLIOutputWriter): output writer. """ if self._filters: output_writer.Write('Filters:\n') for file_entry_filter in self._filters: file_entry_filter.Print(output_writer)
def build_columns ( self , X , verbose = False ) : return sp . sparse . csc_matrix ( X [ : , self . feature ] [ : , np . newaxis ] )
1
python sparse matrix features name
construct the model matrix columns for the term
cosqa-train-14056
def build_columns(self, X, verbose=False): """construct the model matrix columns for the term Parameters ---------- X : array-like Input dataset with n rows verbose : bool whether to show warnings Returns ------- scipy sparse array with n rows """ return sp.sparse.csc_matrix(X[:, self.feature][:, np.newaxis])
def allsame ( list_ , strict = True ) : if len ( list_ ) == 0 : return True first_item = list_ [ 0 ] return list_all_eq_to ( list_ , first_item , strict )
1
how to see if all items in a list are the same python
checks to see if list is equal everywhere
cosqa-train-14057
def allsame(list_, strict=True): """ checks to see if list is equal everywhere Args: list_ (list): Returns: True if all items in the list are equal """ if len(list_) == 0: return True first_item = list_[0] return list_all_eq_to(list_, first_item, strict)
def partition ( a , sz ) : return [ a [ i : i + sz ] for i in range ( 0 , len ( a ) , sz ) ]
1
python split array into n parts
splits iterables a in equal parts of size sz
cosqa-train-14058
def partition(a, sz): """splits iterables a in equal parts of size sz""" return [a[i:i+sz] for i in range(0, len(a), sz)]
def ensure_dir_exists ( directory ) : if directory and not os . path . exists ( directory ) : os . makedirs ( directory )
1
how to see whether a given folder exists or not, and if not exists create the folder in python
Se asegura de que un directorio exista .
cosqa-train-14059
def ensure_dir_exists(directory): """Se asegura de que un directorio exista.""" if directory and not os.path.exists(directory): os.makedirs(directory)
def split_into_sentences ( s ) : s = re . sub ( r"\s+" , " " , s ) s = re . sub ( r"[\\.\\?\\!]" , "\n" , s ) return s . split ( "\n" )
1
python split each string into a list
Split text into list of sentences .
cosqa-train-14060
def split_into_sentences(s): """Split text into list of sentences.""" s = re.sub(r"\s+", " ", s) s = re.sub(r"[\\.\\?\\!]", "\n", s) return s.split("\n")
def feature_subset ( self , indices ) : if isinstance ( indices , np . ndarray ) : indices = indices . tolist ( ) if not isinstance ( indices , list ) : raise ValueError ( 'Can only index with lists' ) return [ self . features_ [ i ] for i in indices ]
1
how to select subset of features from a dataset + python
Returns some subset of the features . Parameters ---------- indices : : obj : list of : obj : int indices of the features in the list
cosqa-train-14061
def feature_subset(self, indices): """ Returns some subset of the features. Parameters ---------- indices : :obj:`list` of :obj:`int` indices of the features in the list Returns ------- :obj:`list` of :obj:`Feature` """ if isinstance(indices, np.ndarray): indices = indices.tolist() if not isinstance(indices, list): raise ValueError('Can only index with lists') return [self.features_[i] for i in indices]
def tokenize_list ( self , text ) : return [ self . get_record_token ( record ) for record in self . analyze ( text ) ]
0
python split each word in a list
Split a text into separate words .
cosqa-train-14062
def tokenize_list(self, text): """ Split a text into separate words. """ return [self.get_record_token(record) for record in self.analyze(text)]
def _request_modify_dns_record ( self , record ) : return self . _request_internal ( "Modify_DNS_Record" , domain = self . domain , record = record )
1
how to send dns request message in python
Sends Modify_DNS_Record request
cosqa-train-14063
def _request_modify_dns_record(self, record): """Sends Modify_DNS_Record request""" return self._request_internal("Modify_DNS_Record", domain=self.domain, record=record)
def match_paren ( self , tokens , item ) : match , = tokens return self . match ( match , item )
0
python split regx token in parens
Matches a paren .
cosqa-train-14064
def match_paren(self, tokens, item): """Matches a paren.""" match, = tokens return self.match(match, item)
def rewindbody ( self ) : if not self . seekable : raise IOError , "unseekable file" self . fp . seek ( self . startofbody )
1
how to set a file pointer back to the beginning python
Rewind the file to the start of the body ( if seekable ) .
cosqa-train-14065
def rewindbody(self): """Rewind the file to the start of the body (if seekable).""" if not self.seekable: raise IOError, "unseekable file" self.fp.seek(self.startofbody)
def split_into_sentences ( s ) : s = re . sub ( r"\s+" , " " , s ) s = re . sub ( r"[\\.\\?\\!]" , "\n" , s ) return s . split ( "\n" )
1
python split sentence into a list
Split text into list of sentences .
cosqa-train-14066
def split_into_sentences(s): """Split text into list of sentences.""" s = re.sub(r"\s+", " ", s) s = re.sub(r"[\\.\\?\\!]", "\n", s) return s.split("\n")
def web ( host , port ) : from . webserver . web import get_app get_app ( ) . run ( host = host , port = port )
1
how to set a webservice in python
Start web application
cosqa-train-14067
def web(host, port): """Start web application""" from .webserver.web import get_app get_app().run(host=host, port=port)
def _split_str ( s , n ) : length = len ( s ) return [ s [ i : i + n ] for i in range ( 0 , length , n ) ]
1
python split string ever n characters
split string into list of strings by specified number .
cosqa-train-14068
def _split_str(s, n): """ split string into list of strings by specified number. """ length = len(s) return [s[i:i + n] for i in range(0, length, n)]
def _set_axis_limits ( self , which , lims , d , scale , reverse = False ) : setattr ( self . limits , which + 'lims' , lims ) setattr ( self . limits , 'd' + which , d ) setattr ( self . limits , which + 'scale' , scale ) if reverse : setattr ( self . limits , 'reverse_' + which + '_axis' , True ) return
1
how to set axis limits python
Private method for setting axis limits .
cosqa-train-14069
def _set_axis_limits(self, which, lims, d, scale, reverse=False): """Private method for setting axis limits. Sets the axis limits on each axis for an individual plot. Args: which (str): The indicator of which part of the plots to adjust. This currently handles `x` and `y`. lims (len-2 list of floats): The limits for the axis. d (float): Amount to increment by between the limits. scale (str): Scale of the axis. Either `log` or `lin`. reverse (bool, optional): If True, reverse the axis tick marks. Default is False. """ setattr(self.limits, which + 'lims', lims) setattr(self.limits, 'd' + which, d) setattr(self.limits, which + 'scale', scale) if reverse: setattr(self.limits, 'reverse_' + which + '_axis', True) return
def string_to_list ( string , sep = "," , filter_empty = False ) : return [ value . strip ( ) for value in string . split ( sep ) if ( not filter_empty or value ) ]
1
python split string to list empty separator
Transforma una string con elementos separados por sep en una lista .
cosqa-train-14070
def string_to_list(string, sep=",", filter_empty=False): """Transforma una string con elementos separados por `sep` en una lista.""" return [value.strip() for value in string.split(sep) if (not filter_empty or value)]
def save_config_value ( request , response , key , value ) : request . session [ key ] = value response . set_cookie ( key , value , expires = one_year_from_now ( ) ) return response
1
how to set cookies with same name in python
Sets value of key key to value in both session and cookies .
cosqa-train-14071
def save_config_value(request, response, key, value): """Sets value of key `key` to `value` in both session and cookies.""" request.session[key] = value response.set_cookie(key, value, expires=one_year_from_now()) return response
def forceupdate ( self , * args , * * kw ) : self . _update ( False , self . _ON_DUP_OVERWRITE , * args , * * kw )
0
python sql bulk update
Like a bulk : meth : forceput .
cosqa-train-14072
def forceupdate(self, *args, **kw): """Like a bulk :meth:`forceput`.""" self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
def set_xlimits_widgets ( self , set_min = True , set_max = True ) : xmin , xmax = self . tab_plot . ax . get_xlim ( ) if set_min : self . w . x_lo . set_text ( '{0}' . format ( xmin ) ) if set_max : self . w . x_hi . set_text ( '{0}' . format ( xmax ) )
1
how to set the range for the x axis in python
Populate axis limits GUI with current plot values .
cosqa-train-14073
def set_xlimits_widgets(self, set_min=True, set_max=True): """Populate axis limits GUI with current plot values.""" xmin, xmax = self.tab_plot.ax.get_xlim() if set_min: self.w.x_lo.set_text('{0}'.format(xmin)) if set_max: self.w.x_hi.set_text('{0}'.format(xmax))
def graphql_queries_to_json ( * queries ) : rtn = { } for i , query in enumerate ( queries ) : rtn [ "q{}" . format ( i ) ] = query . value return json . dumps ( rtn )
1
python sql query to json
Queries should be a list of GraphQL objects
cosqa-train-14074
def graphql_queries_to_json(*queries): """ Queries should be a list of GraphQL objects """ rtn = {} for i, query in enumerate(queries): rtn["q{}".format(i)] = query.value return json.dumps(rtn)
def text_width ( string , font_name , font_size ) : return stringWidth ( string , fontName = font_name , fontSize = font_size )
1
how to set width in python
Determine with width in pixels of string .
cosqa-train-14075
def text_width(string, font_name, font_size): """Determine with width in pixels of string.""" return stringWidth(string, fontName=font_name, fontSize=font_size)
def table_exists ( cursor , tablename , schema = 'public' ) : query = """ SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = %s AND table_name = %s )""" cursor . execute ( query , ( schema , tablename ) ) res = cursor . fetchone ( ) [ 0 ] return res
1
python sql see if exists
cosqa-train-14076
def table_exists(cursor, tablename, schema='public'): query = """ SELECT EXISTS ( SELECT 1 FROM information_schema.tables WHERE table_schema = %s AND table_name = %s )""" cursor.execute(query, (schema, tablename)) res = cursor.fetchone()[0] return res
def set_xlimits ( self , min = None , max = None ) : self . limits [ 'xmin' ] = min self . limits [ 'xmax' ] = max
0
how to set xlimits in python
Set limits for the x - axis .
cosqa-train-14077
def set_xlimits(self, min=None, max=None): """Set limits for the x-axis. :param min: minimum value to be displayed. If None, it will be calculated. :param max: maximum value to be displayed. If None, it will be calculated. """ self.limits['xmin'] = min self.limits['xmax'] = max
def connect_mysql ( host , port , user , password , database ) : return pymysql . connect ( host = host , port = port , user = user , passwd = password , db = database )
1
python sql server pymssql connection to the database falled for an unknow reasion
Connect to MySQL with retries .
cosqa-train-14078
def connect_mysql(host, port, user, password, database): """Connect to MySQL with retries.""" return pymysql.connect( host=host, port=port, user=user, passwd=password, db=database )
def list_backends ( _ ) : backends = [ b . __name__ for b in available_backends ( ) ] print ( '\n' . join ( backends ) )
1
how to show all libraries on python
List all available backends .
cosqa-train-14079
def list_backends(_): """List all available backends.""" backends = [b.__name__ for b in available_backends()] print('\n'.join(backends))
def insert_many ( self , items ) : return SessionContext . session . execute ( self . insert ( values = [ to_dict ( item , self . c ) for item in items ] ) , ) . rowcount
1
python sqlalchemy batch size postgresql
Insert many items at once into a temporary table .
cosqa-train-14080
def insert_many(self, items): """ Insert many items at once into a temporary table. """ return SessionContext.session.execute( self.insert(values=[ to_dict(item, self.c) for item in items ]), ).rowcount
def _repr ( obj ) : vals = ", " . join ( "{}={!r}" . format ( name , getattr ( obj , name ) ) for name in obj . _attribs ) if vals : t = "{}(name={}, {})" . format ( obj . __class__ . __name__ , obj . name , vals ) else : t = "{}(name={})" . format ( obj . __class__ . __name__ , obj . name ) return t
0
how to show attribute of object in python
Show the received object as precise as possible .
cosqa-train-14081
def _repr(obj): """Show the received object as precise as possible.""" vals = ", ".join("{}={!r}".format( name, getattr(obj, name)) for name in obj._attribs) if vals: t = "{}(name={}, {})".format(obj.__class__.__name__, obj.name, vals) else: t = "{}(name={})".format(obj.__class__.__name__, obj.name) return t
def createdb ( ) : manager . db . engine . echo = True manager . db . create_all ( ) set_alembic_revision ( )
1
python sqlalchemy create tables
Create database tables from sqlalchemy models
cosqa-train-14082
def createdb(): """Create database tables from sqlalchemy models""" manager.db.engine.echo = True manager.db.create_all() set_alembic_revision()
def csvpretty ( csvfile : csvfile = sys . stdin ) : shellish . tabulate ( csv . reader ( csvfile ) )
1
how to show csv output elegantly python
Pretty print a CSV file .
cosqa-train-14083
def csvpretty(csvfile: csvfile=sys.stdin): """ Pretty print a CSV file. """ shellish.tabulate(csv.reader(csvfile))
def get_table_names ( connection ) : cursor = connection . cursor ( ) cursor . execute ( "SELECT name FROM sqlite_master WHERE type == 'table'" ) return [ name for ( name , ) in cursor ]
1
python sqlite get list of tables
Return a list of the table names in the database .
cosqa-train-14084
def get_table_names(connection): """ Return a list of the table names in the database. """ cursor = connection.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type == 'table'") return [name for (name,) in cursor]
def show ( self , title = '' ) : self . render ( title = title ) if self . fig : plt . show ( self . fig )
1
how to show figures in python after plotting
Display Bloch sphere and corresponding data sets .
cosqa-train-14085
def show(self, title=''): """ Display Bloch sphere and corresponding data sets. """ self.render(title=title) if self.fig: plt.show(self.fig)
def truncate_table ( self , tablename ) : self . get ( tablename ) . remove ( ) self . db . commit ( )
1
python sqlite3 delete doesn't delete records
SQLite3 doesn t support direct truncate so we just use delete here
cosqa-train-14086
def truncate_table(self, tablename): """ SQLite3 doesn't support direct truncate, so we just use delete here """ self.get(tablename).remove() self.db.commit()
def add_to_toolbar ( self , toolbar , widget ) : actions = widget . toolbar_actions if actions is not None : add_actions ( toolbar , actions )
1
how to show the toolbar in python
Add widget actions to toolbar
cosqa-train-14087
def add_to_toolbar(self, toolbar, widget): """Add widget actions to toolbar""" actions = widget.toolbar_actions if actions is not None: add_actions(toolbar, actions)
def column_names ( self , table ) : table_info = self . execute ( u'PRAGMA table_info(%s)' % quote ( table ) ) return ( column [ 'name' ] for column in table_info )
0
python sqlite3 query column names
An iterable of column names for a particular table or view .
cosqa-train-14088
def column_names(self, table): """An iterable of column names, for a particular table or view.""" table_info = self.execute( u'PRAGMA table_info(%s)' % quote(table)) return (column['name'] for column in table_info)
def sort_fn_list ( fn_list ) : dt_list = get_dt_list ( fn_list ) fn_list_sort = [ fn for ( dt , fn ) in sorted ( zip ( dt_list , fn_list ) ) ] return fn_list_sort
1
how to sort a list of dates in python
Sort input filename list by datetime
cosqa-train-14089
def sort_fn_list(fn_list): """Sort input filename list by datetime """ dt_list = get_dt_list(fn_list) fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))] return fn_list_sort
def disable_cert_validation ( ) : current_context = ssl . _create_default_https_context ssl . _create_default_https_context = ssl . _create_unverified_context try : yield finally : ssl . _create_default_https_context = current_context
0
python ssl context verify trusted certificate
Context manager to temporarily disable certificate validation in the standard SSL library .
cosqa-train-14090
def disable_cert_validation(): """Context manager to temporarily disable certificate validation in the standard SSL library. Note: This should not be used in production code but is sometimes useful for troubleshooting certificate validation issues. By design, the standard SSL library does not provide a way to disable verification of the server side certificate. However, a patch to disable validation is described by the library developers. This context manager allows applying the patch for specific sections of code. """ current_context = ssl._create_default_https_context ssl._create_default_https_context = ssl._create_unverified_context try: yield finally: ssl._create_default_https_context = current_context
def csort ( objs , key ) : idxs = dict ( ( obj , i ) for ( i , obj ) in enumerate ( objs ) ) return sorted ( objs , key = lambda obj : ( key ( obj ) , idxs [ obj ] ) )
1
how to sort a list of objects in python by a variable
Order - preserving sorting function .
cosqa-train-14091
def csort(objs, key): """Order-preserving sorting function.""" idxs = dict((obj, i) for (i, obj) in enumerate(objs)) return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))
def enable_ssl ( self , * args , * * kwargs ) : if self . handshake_sent : raise SSLError ( 'can only enable SSL before handshake' ) self . secure = True self . sock = ssl . wrap_socket ( self . sock , * args , * * kwargs )
1
python ssl wrapping urllib2 socket
Transforms the regular socket . socket to an ssl . SSLSocket for secure connections . Any arguments are passed to ssl . wrap_socket : http : // docs . python . org / dev / library / ssl . html#ssl . wrap_socket
cosqa-train-14092
def enable_ssl(self, *args, **kwargs): """ Transforms the regular socket.socket to an ssl.SSLSocket for secure connections. Any arguments are passed to ssl.wrap_socket: http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket """ if self.handshake_sent: raise SSLError('can only enable SSL before handshake') self.secure = True self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)
def sort_fn_list ( fn_list ) : dt_list = get_dt_list ( fn_list ) fn_list_sort = [ fn for ( dt , fn ) in sorted ( zip ( dt_list , fn_list ) ) ] return fn_list_sort
1
how to sort date list in python
Sort input filename list by datetime
cosqa-train-14093
def sort_fn_list(fn_list): """Sort input filename list by datetime """ dt_list = get_dt_list(fn_list) fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))] return fn_list_sort
def safe_call ( cls , method , * args ) : return cls . call ( method , * args , safe = True )
1
python static method call staticmethod
Call a remote api method but don t raise if an error occurred .
cosqa-train-14094
def safe_call(cls, method, *args): """ Call a remote api method but don't raise if an error occurred.""" return cls.call(method, *args, safe=True)
def sort_func ( self , key ) : if key == self . _KEYS . VALUE : return 'aaa' if key == self . _KEYS . SOURCE : return 'zzz' return key
1
how to sort regardless of case python
Sorting logic for Quantity objects .
cosqa-train-14095
def sort_func(self, key): """Sorting logic for `Quantity` objects.""" if key == self._KEYS.VALUE: return 'aaa' if key == self._KEYS.SOURCE: return 'zzz' return key
def _read_stdin ( ) : line = sys . stdin . readline ( ) while line : yield line line = sys . stdin . readline ( )
1
python stdin nonblock readline
Generator for reading from standard input in nonblocking mode .
cosqa-train-14096
def _read_stdin(): """ Generator for reading from standard input in nonblocking mode. Other ways of reading from ``stdin`` in python waits, until the buffer is big enough, or until EOF character is sent. This functions yields immediately after each line. """ line = sys.stdin.readline() while line: yield line line = sys.stdin.readline()
def array_dim ( arr ) : dim = [ ] while True : try : dim . append ( len ( arr ) ) arr = arr [ 0 ] except TypeError : return dim
1
how to specify length of an array in python
Return the size of a multidimansional array .
cosqa-train-14097
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 read_stdin ( ) : if sys . stdin . isatty ( ) and sys . stdout . isatty ( ) : print ( '\nReading from stdin until end of file (Ctrl + D)...' ) return sys . stdin . read ( )
0
python stdin read without echo
Read text from stdin and print a helpful message for ttys .
cosqa-train-14098
def read_stdin(): """ Read text from stdin, and print a helpful message for ttys. """ if sys.stdin.isatty() and sys.stdout.isatty(): print('\nReading from stdin until end of file (Ctrl + D)...') return sys.stdin.read()
def get_geoip ( ip ) : reader = geolite2 . reader ( ) ip_data = reader . get ( ip ) or { } return ip_data . get ( 'country' , { } ) . get ( 'iso_code' )
0
how to split a location python geolocator
Lookup country for IP address .
cosqa-train-14099
def get_geoip(ip): """Lookup country for IP address.""" reader = geolite2.reader() ip_data = reader.get(ip) or {} return ip_data.get('country', {}).get('iso_code')