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 A ( * a ) : return np . array ( a [ 0 ] ) if len ( a ) == 1 else [ np . array ( o ) for o in a ]
1
how to access array of arrays in python
convert iterable object into numpy array
cosqa-train-15600
def A(*a): """convert iterable object into numpy array""" return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]
def loadb ( b ) : assert isinstance ( b , ( bytes , bytearray ) ) return std_json . loads ( b . decode ( 'utf-8' ) )
0
python json loads expects string or buffer
Deserialize b ( instance of bytes ) to a Python object .
cosqa-train-15601
def loadb(b): """Deserialize ``b`` (instance of ``bytes``) to a Python object.""" assert isinstance(b, (bytes, bytearray)) return std_json.loads(b.decode('utf-8'))
def next ( self ) : # File-like object. result = self . readline ( ) if result == self . _empty_buffer : raise StopIteration return result
0
how to account for reading a file and the line is empty in python
This is to support iterators over a file - like object .
cosqa-train-15602
def next (self): # File-like object. """This is to support iterators over a file-like object. """ result = self.readline() if result == self._empty_buffer: raise StopIteration return result
def _time_to_json ( value ) : if isinstance ( value , datetime . time ) : value = value . isoformat ( ) return value
0
python json stringify datetime
Coerce value to an JSON - compatible representation .
cosqa-train-15603
def _time_to_json(value): """Coerce 'value' to an JSON-compatible representation.""" if isinstance(value, datetime.time): value = value.isoformat() return value
def setup ( ) : print ( "Simple drive" ) board . set_pin_mode ( L_CTRL_1 , Constants . OUTPUT ) board . set_pin_mode ( L_CTRL_2 , Constants . OUTPUT ) board . set_pin_mode ( PWM_L , Constants . PWM ) board . set_pin_mode ( R_CTRL_1 , Constants . OUTPUT ) board . set_pin_mode ( R_CTRL_2 , Constants . OUTPUT ) board . set_pin_mode ( PWM_R , Constants . PWM )
0
how to activate a pin in python
Setup pins
cosqa-train-15604
def setup(): """Setup pins""" print("Simple drive") board.set_pin_mode(L_CTRL_1, Constants.OUTPUT) board.set_pin_mode(L_CTRL_2, Constants.OUTPUT) board.set_pin_mode(PWM_L, Constants.PWM) board.set_pin_mode(R_CTRL_1, Constants.OUTPUT) board.set_pin_mode(R_CTRL_2, Constants.OUTPUT) board.set_pin_mode(PWM_R, Constants.PWM)
def task_property_present_predicate ( service , task , prop ) : try : response = get_service_task ( service , task ) except Exception as e : pass return ( response is not None ) and ( prop in response )
0
python json try element exists
True if the json_element passed is present for the task specified .
cosqa-train-15605
def task_property_present_predicate(service, task, prop): """ True if the json_element passed is present for the task specified. """ try: response = get_service_task(service, task) except Exception as e: pass return (response is not None) and (prop in response)
def set_color ( self , fg = None , bg = None , intensify = False , target = sys . stdout ) : raise NotImplementedError
1
how to add a background color to python code
Set foreground - and background colors and intensity .
cosqa-train-15606
def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout): """Set foreground- and background colors and intensity.""" raise NotImplementedError
def validate ( payload , schema ) : v = jsonschema . Draft4Validator ( schema , format_checker = jsonschema . FormatChecker ( ) ) error_list = [ ] for error in v . iter_errors ( payload ) : message = error . message location = '/' + '/' . join ( [ str ( c ) for c in error . absolute_path ] ) error_list . append ( message + ' at ' + location ) return error_list
0
python jsonschema how to list all schema errors
Validate payload against schema returning an error list .
cosqa-train-15607
def validate(payload, schema): """Validate `payload` against `schema`, returning an error list. jsonschema provides lots of information in it's errors, but it can be a bit of work to extract all the information. """ v = jsonschema.Draft4Validator( schema, format_checker=jsonschema.FormatChecker()) error_list = [] for error in v.iter_errors(payload): message = error.message location = '/' + '/'.join([str(c) for c in error.absolute_path]) error_list.append(message + ' at ' + location) return error_list
def normal_noise ( points ) : return np . random . rand ( 1 ) * np . random . randn ( points , 1 ) + random . sample ( [ 2 , - 2 ] , 1 )
0
how to add a little noise to data in python
Init a noise variable .
cosqa-train-15608
def normal_noise(points): """Init a noise variable.""" return np.random.rand(1) * np.random.randn(points, 1) \ + random.sample([2, -2], 1)
def go_to_line ( self , line ) : cursor = self . textCursor ( ) cursor . setPosition ( self . document ( ) . findBlockByNumber ( line - 1 ) . position ( ) ) self . setTextCursor ( cursor ) return True
0
python jump to line number
Moves the text cursor to given line .
cosqa-train-15609
def go_to_line(self, line): """ Moves the text cursor to given line. :param line: Line to go to. :type line: int :return: Method success. :rtype: bool """ cursor = self.textCursor() cursor.setPosition(self.document().findBlockByNumber(line - 1).position()) self.setTextCursor(cursor) return True
def _write_color_ansi ( fp , text , color ) : fp . write ( esc_ansicolor ( color ) ) fp . write ( text ) fp . write ( AnsiReset )
0
how to add ansii font to python
Colorize text with given color .
cosqa-train-15610
def _write_color_ansi (fp, text, color): """Colorize text with given color.""" fp.write(esc_ansicolor(color)) fp.write(text) fp.write(AnsiReset)
def drop_trailing_zeros ( num ) : txt = '%f' % ( num ) txt = txt . rstrip ( '0' ) if txt . endswith ( '.' ) : txt = txt [ : - 1 ] return txt
0
python keep trailing zero
Drops the trailing zeros in a float that is printed .
cosqa-train-15611
def drop_trailing_zeros(num): """ Drops the trailing zeros in a float that is printed. """ txt = '%f' %(num) txt = txt.rstrip('0') if txt.endswith('.'): txt = txt[:-1] return txt
def weekly ( date = datetime . date . today ( ) ) : return date - datetime . timedelta ( days = date . weekday ( ) )
0
how to add five days on today's date in python
Weeks start are fixes at Monday for now .
cosqa-train-15612
def weekly(date=datetime.date.today()): """ Weeks start are fixes at Monday for now. """ return date - datetime.timedelta(days=date.weekday())
def kill_process_children ( pid ) : if sys . platform == "darwin" : kill_process_children_osx ( pid ) elif sys . platform == "linux" : kill_process_children_unix ( pid ) else : pass
0
python kill all child process of parent
Find and kill child processes of a process .
cosqa-train-15613
def kill_process_children(pid): """Find and kill child processes of a process. :param pid: PID of parent process (process ID) :return: Nothing """ if sys.platform == "darwin": kill_process_children_osx(pid) elif sys.platform == "linux": kill_process_children_unix(pid) else: pass
def setLib ( self , lib ) : for name , item in lib . items ( ) : self . font . lib [ name ] = item
1
how to add fonts in python
Copy the lib items into our font .
cosqa-train-15614
def setLib(self, lib): """ Copy the lib items into our font. """ for name, item in lib.items(): self.font.lib[name] = item
def kill_process ( process ) : logger = logging . getLogger ( 'xenon' ) logger . info ( 'Terminating Xenon-GRPC server.' ) os . kill ( process . pid , signal . SIGINT ) process . wait ( )
0
python kill pid on remote server thru pexpect
Kill the process group associated with the given process . ( posix )
cosqa-train-15615
def kill_process(process): """Kill the process group associated with the given process. (posix)""" logger = logging.getLogger('xenon') logger.info('Terminating Xenon-GRPC server.') os.kill(process.pid, signal.SIGINT) process.wait()
def __init__ ( self , filename , mode , encoding = None ) : FileHandler . __init__ ( self , filename , mode , encoding ) self . mode = mode self . encoding = encoding
1
how to add log file name in stream handler in python
Use the specified filename for streamed logging .
cosqa-train-15616
def __init__(self, filename, mode, encoding=None): """Use the specified filename for streamed logging.""" FileHandler.__init__(self, filename, mode, encoding) self.mode = mode self.encoding = encoding
def kill_process ( process ) : logger = logging . getLogger ( 'xenon' ) logger . info ( 'Terminating Xenon-GRPC server.' ) os . kill ( process . pid , signal . SIGINT ) process . wait ( )
1
python kill process by inode
Kill the process group associated with the given process . ( posix )
cosqa-train-15617
def kill_process(process): """Kill the process group associated with the given process. (posix)""" logger = logging.getLogger('xenon') logger.info('Terminating Xenon-GRPC server.') os.kill(process.pid, signal.SIGINT) process.wait()
def install_postgres ( user = None , dbname = None , password = None ) : execute ( pydiploy . django . install_postgres_server , user = user , dbname = dbname , password = password )
0
how to add postgres libraries to python
Install Postgres on remote
cosqa-train-15618
def install_postgres(user=None, dbname=None, password=None): """Install Postgres on remote""" execute(pydiploy.django.install_postgres_server, user=user, dbname=dbname, password=password)
def register_plugin ( self ) : self . main . restore_scrollbar_position . connect ( self . restore_scrollbar_position ) self . main . add_dockwidget ( self )
1
how to add scrollbar to frame in python
Register plugin in Spyder s main window
cosqa-train-15619
def register_plugin(self): """Register plugin in Spyder's main window""" self.main.restore_scrollbar_position.connect( self.restore_scrollbar_position) self.main.add_dockwidget(self)
def l2_norm ( arr ) : arr = np . asarray ( arr ) return np . sqrt ( np . dot ( arr . ravel ( ) . squeeze ( ) , arr . ravel ( ) . squeeze ( ) ) )
0
python l2 norm of vector
The l2 norm of an array is is defined as : sqrt ( ||x|| ) where ||x|| is the dot product of the vector .
cosqa-train-15620
def l2_norm(arr): """ The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the dot product of the vector. """ arr = np.asarray(arr) return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))
def append_text ( self , txt ) : with open ( self . fullname , "a" ) as myfile : myfile . write ( txt )
1
how to add something to a text file in python
adds a line of text to a file
cosqa-train-15621
def append_text(self, txt): """ adds a line of text to a file """ with open(self.fullname, "a") as myfile: myfile.write(txt)
def download_file_from_bucket ( self , bucket , file_path , key ) : with open ( file_path , 'wb' ) as data : self . __s3 . download_fileobj ( bucket , key , data ) return file_path
1
python lambda boto3 get file from filename from s3
Download file from S3 Bucket
cosqa-train-15622
def download_file_from_bucket(self, bucket, file_path, key): """ Download file from S3 Bucket """ with open(file_path, 'wb') as data: self.__s3.download_fileobj(bucket, key, data) return file_path
def _pad ( self , text ) : top_bottom = ( "\n" * self . _padding ) + " " right_left = " " * self . _padding * self . PAD_WIDTH return top_bottom + right_left + text + right_left + top_bottom
0
how to allign something to the middle in python
Pad the text .
cosqa-train-15623
def _pad(self, text): """Pad the text.""" top_bottom = ("\n" * self._padding) + " " right_left = " " * self._padding * self.PAD_WIDTH return top_bottom + right_left + text + right_left + top_bottom
def make_lambda ( call ) : empty_args = ast . arguments ( args = [ ] , vararg = None , kwarg = None , defaults = [ ] ) return ast . Lambda ( args = empty_args , body = call )
0
python lambda functions two paramaters
Wrap an AST Call node to lambda expression node . call : ast . Call node
cosqa-train-15624
def make_lambda(call): """Wrap an AST Call node to lambda expression node. call: ast.Call node """ empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[]) return ast.Lambda(args=empty_args, body=call)
def robust_int ( v ) : if isinstance ( v , int ) : return v if isinstance ( v , float ) : return int ( v ) v = str ( v ) . replace ( ',' , '' ) if not v : return None return int ( v )
0
how to allow integer to except decimal as input python
Parse an int robustly ignoring commas and other cruft .
cosqa-train-15625
def robust_int(v): """Parse an int robustly, ignoring commas and other cruft. """ if isinstance(v, int): return v if isinstance(v, float): return int(v) v = str(v).replace(',', '') if not v: return None return int(v)
def get_tail ( self ) : node = self . head last_node = self . head while node is not None : last_node = node node = node . next_node return last_node
0
python last elements head
Gets tail
cosqa-train-15626
def get_tail(self): """Gets tail :return: Tail of linked list """ node = self.head last_node = self.head while node is not None: last_node = node node = node.next_node return last_node
def AddAccuracy ( model , softmax , label ) : accuracy = brew . accuracy ( model , [ softmax , label ] , "accuracy" ) return accuracy
0
how to append the prediction to the inference set python panda
Adds an accuracy op to the model
cosqa-train-15627
def AddAccuracy(model, softmax, label): """Adds an accuracy op to the model""" accuracy = brew.accuracy(model, [softmax, label], "accuracy") return accuracy
def end_index ( self ) : paginator = self . paginator # Special case for the last page because there can be orphans. if self . number == paginator . num_pages : return paginator . count return ( self . number - 1 ) * paginator . per_page + paginator . first_page
0
python last item in index
Return the 1 - based index of the last item on this page .
cosqa-train-15628
def end_index(self): """Return the 1-based index of the last item on this page.""" paginator = self.paginator # Special case for the last page because there can be orphans. if self.number == paginator.num_pages: return paginator.count return (self.number - 1) * paginator.per_page + paginator.first_page
def append ( self , item ) : print ( item ) super ( MyList , self ) . append ( item )
0
how to append to list in python at front!
append item and print it to stdout
cosqa-train-15629
def append(self, item): """ append item and print it to stdout """ print(item) super(MyList, self).append(item)
def xyz2lonlat ( x , y , z ) : lon = xu . rad2deg ( xu . arctan2 ( y , x ) ) lat = xu . rad2deg ( xu . arctan2 ( z , xu . sqrt ( x ** 2 + y ** 2 ) ) ) return lon , lat
0
python lat lng to xy
Convert cartesian to lon lat .
cosqa-train-15630
def xyz2lonlat(x, y, z): """Convert cartesian to lon lat.""" lon = xu.rad2deg(xu.arctan2(y, x)) lat = xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2))) return lon, lat
def filter_contour ( imageFile , opFile ) : im = Image . open ( imageFile ) im1 = im . filter ( ImageFilter . CONTOUR ) im1 . save ( opFile )
0
how to apply filter to image in python
convert an image by applying a contour
cosqa-train-15631
def filter_contour(imageFile, opFile): """ convert an image by applying a contour """ im = Image.open(imageFile) im1 = im.filter(ImageFilter.CONTOUR) im1.save(opFile)
def make_coord_dict ( coord ) : return dict ( z = int_if_exact ( coord . zoom ) , x = int_if_exact ( coord . column ) , y = int_if_exact ( coord . row ) , )
1
python lat long coordinates to dictionary
helper function to make a dict from a coordinate for logging
cosqa-train-15632
def make_coord_dict(coord): """helper function to make a dict from a coordinate for logging""" return dict( z=int_if_exact(coord.zoom), x=int_if_exact(coord.column), y=int_if_exact(coord.row), )
def dictapply ( d , fn ) : for k , v in d . items ( ) : if isinstance ( v , dict ) : v = dictapply ( v , fn ) else : d [ k ] = fn ( v ) return d
0
how to apply multiple dictionaries python
apply a function to all non - dict values in a dictionary
cosqa-train-15633
def dictapply(d, fn): """ apply a function to all non-dict values in a dictionary """ for k, v in d.items(): if isinstance(v, dict): v = dictapply(v, fn) else: d[k] = fn(v) return d
def tree_predict ( x , root , proba = False , regression = False ) : if isinstance ( root , Leaf ) : if proba : return root . probabilities elif regression : return root . mean else : return root . most_frequent if root . question . match ( x ) : return tree_predict ( x , root . true_branch , proba = proba , regression = regression ) else : return tree_predict ( x , root . false_branch , proba = proba , regression = regression )
0
python leaf values predict
Predicts a probabilities / value / label for the sample x .
cosqa-train-15634
def tree_predict(x, root, proba=False, regression=False): """Predicts a probabilities/value/label for the sample x. """ if isinstance(root, Leaf): if proba: return root.probabilities elif regression: return root.mean else: return root.most_frequent if root.question.match(x): return tree_predict(x, root.true_branch, proba=proba, regression=regression) else: return tree_predict(x, root.false_branch, proba=proba, regression=regression)
def load_files ( files ) : for py_file in files : LOG . debug ( "exec %s" , py_file ) execfile ( py_file , globals ( ) , locals ( ) )
1
how to automatically execute python files
Load and execute a python file .
cosqa-train-15635
def load_files(files): """Load and execute a python file.""" for py_file in files: LOG.debug("exec %s", py_file) execfile(py_file, globals(), locals())
def minimise_xyz ( xyz ) : x , y , z = xyz m = max ( min ( x , y ) , min ( max ( x , y ) , z ) ) return ( x - m , y - m , z - m )
0
python limit x y z range
Minimise an ( x y z ) coordinate .
cosqa-train-15636
def minimise_xyz(xyz): """Minimise an (x, y, z) coordinate.""" x, y, z = xyz m = max(min(x, y), min(max(x, y), z)) return (x-m, y-m, z-m)
def download_file ( save_path , file_url ) : r = requests . get ( file_url ) # create HTTP response object with open ( save_path , 'wb' ) as f : f . write ( r . content ) return save_path
1
how to automatically save a download in python
Download file from http url link
cosqa-train-15637
def download_file(save_path, file_url): """ Download file from http url link """ r = requests.get(file_url) # create HTTP response object with open(save_path, 'wb') as f: f.write(r.content) return save_path
def stop ( pid ) : if psutil . pid_exists ( pid ) : try : p = psutil . Process ( pid ) p . kill ( ) except Exception : pass
0
python linux kill process by pid
Shut down a specific process .
cosqa-train-15638
def stop(pid): """Shut down a specific process. Args: pid: the pid of the process to shutdown. """ if psutil.pid_exists(pid): try: p = psutil.Process(pid) p.kill() except Exception: pass
def variance ( arr ) : avg = average ( arr ) return sum ( [ ( float ( x ) - avg ) ** 2 for x in arr ] ) / float ( len ( arr ) - 1 )
0
how to average values of an array python
variance of the values must have 2 or more entries .
cosqa-train-15639
def variance(arr): """variance of the values, must have 2 or more entries. :param arr: list of numbers :type arr: number[] a number array :return: variance :rtype: float """ avg = average(arr) return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)
def dedupe_list ( seq ) : seen = set ( ) return [ x for x in seq if not ( x in seen or seen . add ( x ) ) ]
1
python list drop duplicate and keep the original sequence
Utility function to remove duplicates from a list : param seq : The sequence ( list ) to deduplicate : return : A list with original duplicates removed
cosqa-train-15640
def dedupe_list(seq): """ Utility function to remove duplicates from a list :param seq: The sequence (list) to deduplicate :return: A list with original duplicates removed """ seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
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 build sorting on object in python
Order - preserving sorting function .
cosqa-train-15641
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 get_by ( self , name ) : return next ( ( item for item in self if item . name == name ) , None )
0
python list element access by name
get element by name
cosqa-train-15642
def get_by(self, name): """get element by name""" return next((item for item in self if item.name == name), None)
def should_be_hidden_as_cause ( exc ) : # reduced traceback in case of HasWrongType (instance_of checks) from valid8 . validation_lib . types import HasWrongType , IsWrongType return isinstance ( exc , ( HasWrongType , IsWrongType ) )
0
how to bypass a nonetype error in python
Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error
cosqa-train-15643
def should_be_hidden_as_cause(exc): """ Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error """ # reduced traceback in case of HasWrongType (instance_of checks) from valid8.validation_lib.types import HasWrongType, IsWrongType return isinstance(exc, (HasWrongType, IsWrongType))
def getAllTriples ( self ) : return [ ( str ( s ) , str ( p ) , str ( o ) ) for s , p , o in self ]
1
python list of all objects
Returns :
cosqa-train-15644
def getAllTriples(self): """Returns: list of tuples : Each tuple holds a subject, predicate, object triple """ return [(str(s), str(p), str(o)) for s, p, o in self]
def _calculate_distance ( latlon1 , latlon2 ) : lat1 , lon1 = latlon1 lat2 , lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np . sin ( dlat / 2 ) ** 2 + np . cos ( lat1 ) * np . cos ( lat2 ) * ( np . sin ( dlon / 2 ) ) ** 2 c = 2 * np . pi * R * np . arctan2 ( np . sqrt ( a ) , np . sqrt ( 1 - a ) ) / 180 return c
0
how to calculate distance between two lat long in python
Calculates the distance between two points on earth .
cosqa-train-15645
def _calculate_distance(latlon1, latlon2): """Calculates the distance between two points on earth. """ lat1, lon1 = latlon1 lat2, lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2 c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180 return c
def items ( cls ) : return [ cls . PRECIPITATION , cls . WIND , cls . TEMPERATURE , cls . PRESSURE ]
0
python list of enum values
All values for this enum : return : list of tuples
cosqa-train-15646
def items(cls): """ All values for this enum :return: list of tuples """ return [ cls.PRECIPITATION, cls.WIND, cls.TEMPERATURE, cls.PRESSURE ]
def dot_v3 ( v , w ) : return sum ( [ x * y for x , y in zip ( v , w ) ] )
1
how to calculate dot product of two vectors in python
Return the dotproduct of two vectors .
cosqa-train-15647
def dot_v3(v, w): """Return the dotproduct of two vectors.""" return sum([x * y for x, y in zip(v, w)])
def from_json_list ( cls , api_client , data ) : return [ cls . from_json ( api_client , item ) for item in data ]
0
python list of json to list of objects
Convert a list of JSON values to a list of models
cosqa-train-15648
def from_json_list(cls, api_client, data): """Convert a list of JSON values to a list of models """ return [cls.from_json(api_client, item) for item in data]
def center_eigenvalue_diff ( mat ) : N = len ( mat ) evals = np . sort ( la . eigvals ( mat ) ) diff = np . abs ( evals [ N / 2 ] - evals [ N / 2 - 1 ] ) return diff
0
how to calculate eigenvalues eigen vector function in python
Compute the eigvals of mat and then find the center eigval difference .
cosqa-train-15649
def center_eigenvalue_diff(mat): """Compute the eigvals of mat and then find the center eigval difference.""" N = len(mat) evals = np.sort(la.eigvals(mat)) diff = np.abs(evals[N/2] - evals[N/2-1]) return diff
def getPrimeFactors ( n ) : lo = [ 1 ] n2 = n // 2 k = 2 for k in range ( 2 , n2 + 1 ) : if ( n // k ) * k == n : lo . append ( k ) return lo + [ n , ]
0
python list of prime factors
Get all the prime factor of given integer
cosqa-train-15650
def getPrimeFactors(n): """ Get all the prime factor of given integer @param n integer @return list [1, ..., n] """ lo = [1] n2 = n // 2 k = 2 for k in range(2, n2 + 1): if (n // k)*k == n: lo.append(k) return lo + [n, ]
def euclidean ( c1 , c2 ) : diffs = ( ( i - j ) for i , j in zip ( c1 , c2 ) ) return sum ( x * x for x in diffs )
0
how to calculate euclidean distance between 2 points in python
Square of the euclidean distance
cosqa-train-15651
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 chunk_list ( l , n ) : return [ l [ i : i + n ] for i in range ( 0 , len ( l ) , n ) ]
1
python list populated with n lists
Return n size lists from a given list l
cosqa-train-15652
def chunk_list(l, n): """Return `n` size lists from a given list `l`""" return [l[i:i + n] for i in range(0, len(l), n)]
def mag ( z ) : if isinstance ( z [ 0 ] , np . ndarray ) : return np . array ( list ( map ( np . linalg . norm , z ) ) ) else : return np . linalg . norm ( z )
1
how to calculate the magnitude of a vector inpython with numpy
Get the magnitude of a vector .
cosqa-train-15653
def mag(z): """Get the magnitude of a vector.""" if isinstance(z[0], np.ndarray): return np.array(list(map(np.linalg.norm, z))) else: return np.linalg.norm(z)
def dump_nparray ( self , obj , class_name = numpy_ndarray_class_name ) : return { "$" + class_name : self . _json_convert ( obj . tolist ( ) ) }
0
python list to nparray
numpy . ndarray dumper .
cosqa-train-15654
def dump_nparray(self, obj, class_name=numpy_ndarray_class_name): """ ``numpy.ndarray`` dumper. """ return {"$" + class_name: self._json_convert(obj.tolist())}
def add_to_js ( self , name , var ) : frame = self . page ( ) . mainFrame ( ) frame . addToJavaScriptWindowObject ( name , var )
1
how to call a javascript variable in html with python
Add an object to Javascript .
cosqa-train-15655
def add_to_js(self, name, var): """Add an object to Javascript.""" frame = self.page().mainFrame() frame.addToJavaScriptWindowObject(name, var)
def list2string ( inlist , delimit = ' ' ) : stringlist = [ makestr ( _ ) for _ in inlist ] return string . join ( stringlist , delimit )
1
python list to string without using join
Converts a 1D list to a single long string for file output using the string . join function .
cosqa-train-15656
def list2string (inlist,delimit=' '): """ Converts a 1D list to a single long string for file output, using the string.join function. Usage: list2string (inlist,delimit=' ') Returns: the string created from inlist """ stringlist = [makestr(_) for _ in inlist] return string.join(stringlist,delimit)
def _call ( callable_obj , arg_names , namespace ) : arguments = { arg_name : getattr ( namespace , arg_name ) for arg_name in arg_names } return callable_obj ( * * arguments )
0
how to call multiple functions with one set of args in python
Actually calls the callable with the namespace parsed from the command line .
cosqa-train-15657
def _call(callable_obj, arg_names, namespace): """Actually calls the callable with the namespace parsed from the command line. Args: callable_obj: a callable object arg_names: name of the function arguments namespace: the namespace object parsed from the command line """ arguments = {arg_name: getattr(namespace, arg_name) for arg_name in arg_names} return callable_obj(**arguments)
def from_json_str ( cls , json_str ) : return cls . from_json ( json . loads ( json_str , cls = JsonDecoder ) )
1
python load a string as json
Convert json string representation into class instance .
cosqa-train-15658
def from_json_str(cls, json_str): """Convert json string representation into class instance. Args: json_str: json representation as string. Returns: New instance of the class with data loaded from json string. """ return cls.from_json(json.loads(json_str, cls=JsonDecoder))
def eval_script ( self , expr ) : ret = self . conn . issue_command ( "Evaluate" , expr ) return json . loads ( "[%s]" % ret ) [ 0 ]
0
how to call python script server side method from javascript
Evaluates a piece of Javascript in the context of the current page and returns its value .
cosqa-train-15659
def eval_script(self, expr): """ Evaluates a piece of Javascript in the context of the current page and returns its value. """ ret = self.conn.issue_command("Evaluate", expr) return json.loads("[%s]" % ret)[0]
def main ( args = sys . argv ) : parser = create_optparser ( args [ 0 ] ) return cli ( parser . parse_args ( args [ 1 : ] ) )
0
python load argparser from json
main entry point for the jardiff CLI
cosqa-train-15660
def main(args=sys.argv): """ main entry point for the jardiff CLI """ parser = create_optparser(args[0]) return cli(parser.parse_args(args[1:]))
def fn_min ( self , a , axis = None ) : return numpy . nanmin ( self . _to_ndarray ( a ) , axis = axis )
1
how to call the minimum value of apython array
Return the minimum of an array ignoring any NaNs .
cosqa-train-15661
def fn_min(self, a, axis=None): """ Return the minimum of an array, ignoring any NaNs. :param a: The array. :return: The minimum value of the array. """ return numpy.nanmin(self._to_ndarray(a), axis=axis)
def load ( obj , cls , default_factory ) : if obj is None : return default_factory ( ) if isinstance ( obj , dict ) : return cls . load ( obj ) return obj
1
python load default value based on type
Create or load an object if necessary .
cosqa-train-15662
def load(obj, cls, default_factory): """Create or load an object if necessary. Parameters ---------- obj : `object` or `dict` or `None` cls : `type` default_factory : `function` Returns ------- `object` """ if obj is None: return default_factory() if isinstance(obj, dict): return cls.load(obj) return obj
def open_json ( file_name ) : with open ( file_name , "r" ) as json_data : data = json . load ( json_data ) return data
1
python load json data from file
returns json contents as string
cosqa-train-15663
def open_json(file_name): """ returns json contents as string """ with open(file_name, "r") as json_data: data = json.load(json_data) return data
def load ( cls , fname ) : with open ( fname ) as f : content = f . readlines ( ) return Flow . from_json ( '' . join ( content ) )
1
python load json from file mac
Loads the flow from a JSON file .
cosqa-train-15664
def load(cls, fname): """ Loads the flow from a JSON file. :param fname: the file to load :type fname: str :return: the flow :rtype: Flow """ with open(fname) as f: content = f.readlines() return Flow.from_json(''.join(content))
def camel_case_from_underscores ( string ) : components = string . split ( '_' ) string = '' for component in components : string += component [ 0 ] . upper ( ) + component [ 1 : ] return string
0
how to capitalize first letter in string in python
generate a CamelCase string from an underscore_string .
cosqa-train-15665
def camel_case_from_underscores(string): """generate a CamelCase string from an underscore_string.""" components = string.split('_') string = '' for component in components: string += component[0].upper() + component[1:] return string
def load_graph_from_rdf ( fname ) : print ( "reading RDF from " + fname + "...." ) store = Graph ( ) store . parse ( fname , format = "n3" ) print ( "Loaded " + str ( len ( store ) ) + " tuples" ) return store
1
python loadr rds file
reads an RDF file into a graph
cosqa-train-15666
def load_graph_from_rdf(fname): """ reads an RDF file into a graph """ print("reading RDF from " + fname + "....") store = Graph() store.parse(fname, format="n3") print("Loaded " + str(len(store)) + " tuples") return store
def mixedcase ( path ) : words = path . split ( '_' ) return words [ 0 ] + '' . join ( word . title ( ) for word in words [ 1 : ] )
0
how to capitalize first word in python
Removes underscores and capitalizes the neighbouring character
cosqa-train-15667
def mixedcase(path): """Removes underscores and capitalizes the neighbouring character""" words = path.split('_') return words[0] + ''.join(word.title() for word in words[1:])
def read_raw ( data_path ) : with open ( data_path , 'rb' ) as f : data = pickle . load ( f ) return data
1
python loadrawdata by relative path
Parameters ---------- data_path : str
cosqa-train-15668
def read_raw(data_path): """ Parameters ---------- data_path : str """ with open(data_path, 'rb') as f: data = pickle.load(f) return data
def mixedcase ( path ) : words = path . split ( '_' ) return words [ 0 ] + '' . join ( word . title ( ) for word in words [ 1 : ] )
0
how to capitalize one word in a string python
Removes underscores and capitalizes the neighbouring character
cosqa-train-15669
def mixedcase(path): """Removes underscores and capitalizes the neighbouring character""" words = path.split('_') return words[0] + ''.join(word.title() for word in words[1:])
def bisect_index ( a , x ) : i = bisect . bisect_left ( a , x ) if i != len ( a ) and a [ i ] == x : return i raise ValueError
0
python locate index of list elements in list
Find the leftmost index of an element in a list using binary search .
cosqa-train-15670
def bisect_index(a, x): """ Find the leftmost index of an element in a list using binary search. Parameters ---------- a: list A sorted list. x: arbitrary The element. Returns ------- int The index. """ i = bisect.bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError
def to_binary ( s , encoding = 'utf8' ) : if PY3 : # pragma: no cover return s if isinstance ( s , binary_type ) else binary_type ( s , encoding = encoding ) return binary_type ( s )
1
how to cast a string to bytes in python
Portable cast function .
cosqa-train-15671
def to_binary(s, encoding='utf8'): """Portable cast function. In python 2 the ``str`` function which is used to coerce objects to bytes does not accept an encoding argument, whereas python 3's ``bytes`` function requires one. :param s: object to be converted to binary_type :return: binary_type instance, representing s. """ if PY3: # pragma: no cover return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding) return binary_type(s)
def find_console_handler ( logger ) : for handler in logger . handlers : if ( isinstance ( handler , logging . StreamHandler ) and handler . stream == sys . stderr ) : return handler
1
python logging check if handler exist
Return a stream handler if it exists .
cosqa-train-15672
def find_console_handler(logger): """Return a stream handler, if it exists.""" for handler in logger.handlers: if (isinstance(handler, logging.StreamHandler) and handler.stream == sys.stderr): return handler
def _datetime_to_date ( arg ) : _arg = parse ( arg ) if isinstance ( _arg , datetime . datetime ) : _arg = _arg . date ( ) return _arg
0
how to cast as datetime python
convert datetime / str to date : param arg : : return :
cosqa-train-15673
def _datetime_to_date(arg): """ convert datetime/str to date :param arg: :return: """ _arg = parse(arg) if isinstance(_arg, datetime.datetime): _arg = _arg.date() return _arg
def __enter__ ( self ) : self . logger = logging . getLogger ( 'pip.download' ) self . logger . addFilter ( self )
0
python logging filter self
Enable the download log filter .
cosqa-train-15674
def __enter__(self): """Enable the download log filter.""" self.logger = logging.getLogger('pip.download') self.logger.addFilter(self)
def update_dict ( obj , dict , attributes ) : for attribute in attributes : if hasattr ( obj , attribute ) and getattr ( obj , attribute ) is not None : dict [ attribute ] = getattr ( obj , attribute )
1
how to change attributes python objects
Update dict with fields from obj . attributes .
cosqa-train-15675
def update_dict(obj, dict, attributes): """Update dict with fields from obj.attributes. :param obj: the object updated into dict :param dict: the result dictionary :param attributes: a list of attributes belonging to obj """ for attribute in attributes: if hasattr(obj, attribute) and getattr(obj, attribute) is not None: dict[attribute] = getattr(obj, attribute)
def clog ( color ) : logger = log ( color ) return lambda msg : logger ( centralize ( msg ) . rstrip ( ) )
0
python logging format center justify
Same to log but this one centralizes the message first .
cosqa-train-15676
def clog(color): """Same to ``log``, but this one centralizes the message first.""" logger = log(color) return lambda msg: logger(centralize(msg).rstrip())
def _normalize_numpy_indices ( i ) : if isinstance ( i , np . ndarray ) : if i . dtype == bool : i = tuple ( j . tolist ( ) for j in i . nonzero ( ) ) elif i . dtype == int : i = i . tolist ( ) return i
0
how to change boolean indexer to numerical in python
Normalize the index in case it is a numpy integer or boolean array .
cosqa-train-15677
def _normalize_numpy_indices(i): """Normalize the index in case it is a numpy integer or boolean array.""" if isinstance(i, np.ndarray): if i.dtype == bool: i = tuple(j.tolist() for j in i.nonzero()) elif i.dtype == int: i = i.tolist() return i
def format ( self , record , * args , * * kwargs ) : return logging . Formatter . format ( self , record , * args , * * kwargs ) . replace ( '\n' , '\n' + ' ' * 8 )
0
python logging format example
Format a message in the log
cosqa-train-15678
def format(self, record, *args, **kwargs): """ Format a message in the log Act like the normal format, but indent anything that is a newline within the message. """ return logging.Formatter.format( self, record, *args, **kwargs).replace('\n', '\n' + ' ' * 8)
def convert_types ( cls , value ) : if isinstance ( value , decimal . Decimal ) : return float ( value ) else : return value
0
how to change columng data type to int or float in python
Takes a value from MSSQL and converts it to a value that s safe for JSON / Google Cloud Storage / BigQuery .
cosqa-train-15679
def convert_types(cls, value): """ Takes a value from MSSQL, and converts it to a value that's safe for JSON/Google Cloud Storage/BigQuery. """ if isinstance(value, decimal.Decimal): return float(value) else: return value
def _get_loggers ( ) : from . . import loader modules = loader . get_package_modules ( 'logger' ) return list ( loader . get_plugins ( modules , [ _Logger ] ) )
0
python logging get all child loggers
Return list of Logger classes .
cosqa-train-15680
def _get_loggers(): """Return list of Logger classes.""" from .. import loader modules = loader.get_package_modules('logger') return list(loader.get_plugins(modules, [_Logger]))
def setwinsize ( self , rows , cols ) : self . _winsize = ( rows , cols ) self . pty . set_size ( cols , rows )
1
how to change dimensions of a window in python
Set the terminal window size of the child tty .
cosqa-train-15681
def setwinsize(self, rows, cols): """Set the terminal window size of the child tty. """ self._winsize = (rows, cols) self.pty.set_size(cols, rows)
def log_no_newline ( self , msg ) : self . print2file ( self . logfile , False , False , msg )
0
python logging no file generated
print the message to the predefined log file without newline
cosqa-train-15682
def log_no_newline(self, msg): """ print the message to the predefined log file without newline """ self.print2file(self.logfile, False, False, msg)
def format_time ( time ) : h , r = divmod ( time / 1000 , 3600 ) m , s = divmod ( r , 60 ) return "%02d:%02d:%02d" % ( h , m , s )
1
how to change format of time on python
Formats the given time into HH : MM : SS
cosqa-train-15683
def format_time(time): """ Formats the given time into HH:MM:SS """ h, r = divmod(time / 1000, 3600) m, s = divmod(r, 60) return "%02d:%02d:%02d" % (h, m, s)
def as_tuple ( self , value ) : if isinstance ( value , list ) : value = tuple ( value ) return value
0
how to change from list to tuple in python
Utility function which converts lists to tuples .
cosqa-train-15684
def as_tuple(self, value): """Utility function which converts lists to tuples.""" if isinstance(value, list): value = tuple(value) return value
def is_bool_matrix ( l ) : if isinstance ( l , np . ndarray ) : if l . ndim == 2 and ( l . dtype == bool ) : return True return False
0
python logical boolean numpy arrays
r Checks if l is a 2D numpy array of bools
cosqa-train-15685
def is_bool_matrix(l): r"""Checks if l is a 2D numpy array of bools """ if isinstance(l, np.ndarray): if l.ndim == 2 and (l.dtype == bool): return True return False
def set_index ( self , index ) : for df in self . get_DataFrame ( data = True , with_population = False ) : df . index = index
0
how to change index of data frame python
Sets the pd dataframe index of all dataframes in the system to index
cosqa-train-15686
def set_index(self, index): """ Sets the pd dataframe index of all dataframes in the system to index """ for df in self.get_DataFrame(data=True, with_population=False): df.index = index
def _import ( module , cls ) : global Scanner try : cls = str ( cls ) mod = __import__ ( str ( module ) , globals ( ) , locals ( ) , [ cls ] , 1 ) Scanner = getattr ( mod , cls ) except ImportError : pass
1
python lookup and add idiom
A messy way to import library - specific classes . TODO : I should really make a factory class or something but I m lazy . Plus factories remind me a lot of java ...
cosqa-train-15687
def _import(module, cls): """ A messy way to import library-specific classes. TODO: I should really make a factory class or something, but I'm lazy. Plus, factories remind me a lot of java... """ global Scanner try: cls = str(cls) mod = __import__(str(module), globals(), locals(), [cls], 1) Scanner = getattr(mod, cls) except ImportError: pass
def set_executable ( filename ) : st = os . stat ( filename ) os . chmod ( filename , st . st_mode | stat . S_IEXEC )
1
how to change isexecutable using python
Set the exectuable bit on the given filename
cosqa-train-15688
def set_executable(filename): """Set the exectuable bit on the given filename""" st = os.stat(filename) os.chmod(filename, st.st_mode | stat.S_IEXEC)
def get_obj ( ref ) : oid = int ( ref ) return server . id2ref . get ( oid ) or server . id2obj [ oid ]
1
python lookup memory of a object
Get object from string reference .
cosqa-train-15689
def get_obj(ref): """Get object from string reference.""" oid = int(ref) return server.id2ref.get(oid) or server.id2obj[oid]
def forward ( self , step ) : x = self . pos_x + math . cos ( math . radians ( self . rotation ) ) * step y = self . pos_y + math . sin ( math . radians ( self . rotation ) ) * step prev_brush_state = self . brush_on self . brush_on = True self . move ( x , y ) self . brush_on = prev_brush_state
0
how to change position for turtle python
Move the turtle forward .
cosqa-train-15690
def forward(self, step): """Move the turtle forward. :param step: Integer. Distance to move forward. """ x = self.pos_x + math.cos(math.radians(self.rotation)) * step y = self.pos_y + math.sin(math.radians(self.rotation)) * step prev_brush_state = self.brush_on self.brush_on = True self.move(x, y) self.brush_on = prev_brush_state
def polyline ( self , arr ) : for i in range ( 0 , len ( arr ) - 1 ) : self . line ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] , arr [ i + 1 ] [ 0 ] , arr [ i + 1 ] [ 1 ] )
0
python loop through array and dynamically plot line
Draw a set of lines
cosqa-train-15691
def polyline(self, arr): """Draw a set of lines""" for i in range(0, len(arr) - 1): self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1])
def _to_java_object_rdd ( rdd ) : rdd = rdd . _reserialize ( AutoBatchedSerializer ( PickleSerializer ( ) ) ) return rdd . ctx . _jvm . org . apache . spark . mllib . api . python . SerDe . pythonToJava ( rdd . _jrdd , True )
0
how to change python tuple into rdd
Return a JavaRDD of Object by unpickling
cosqa-train-15692
def _to_java_object_rdd(rdd): """ Return a JavaRDD of Object by unpickling It will convert each Python object into Java object by Pyrolite, whenever the RDD is serialized in batch or not. """ rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer())) return rdd.ctx._jvm.org.apache.spark.mllib.api.python.SerDe.pythonToJava(rdd._jrdd, True)
def mock_add_spec ( self , spec , spec_set = False ) : self . _mock_add_spec ( spec , spec_set ) self . _mock_set_magics ( )
0
python magicmock any args
Add a spec to a mock . spec can either be an object or a list of strings . Only attributes on the spec can be fetched as attributes from the mock .
cosqa-train-15693
def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) self._mock_set_magics()
def screen ( self , width , height , colorDepth ) : screenEvent = ScreenEvent ( ) screenEvent . width . value = width screenEvent . height . value = height screenEvent . colorDepth . value = colorDepth self . rec ( screenEvent )
0
how to change screen resolution python
cosqa-train-15694
def screen(self, width, height, colorDepth): """ @summary: record resize event of screen (maybe first event) @param width: {int} width of screen @param height: {int} height of screen @param colorDepth: {int} colorDepth """ screenEvent = ScreenEvent() screenEvent.width.value = width screenEvent.height.value = height screenEvent.colorDepth.value = colorDepth self.rec(screenEvent)
def get_subject ( self , msg ) : text , encoding = decode_header ( msg [ 'subject' ] ) [ - 1 ] try : text = text . decode ( encoding ) # If it's already decoded, ignore error except AttributeError : pass return text
0
python mail subject decode
Extracts the subject line from an EmailMessage object .
cosqa-train-15695
def get_subject(self, msg): """Extracts the subject line from an EmailMessage object.""" text, encoding = decode_header(msg['subject'])[-1] try: text = text.decode(encoding) # If it's already decoded, ignore error except AttributeError: pass return text
def to_list ( var ) : if var is None : return [ ] if isinstance ( var , str ) : var = var . split ( '\n' ) elif not isinstance ( var , list ) : try : var = list ( var ) except TypeError : raise ValueError ( "{} cannot be converted to the list." . format ( var ) ) return var
0
how to change string into list in python
Checks if given value is a list tries to convert if it is not .
cosqa-train-15696
def to_list(var): """Checks if given value is a list, tries to convert, if it is not.""" if var is None: return [] if isinstance(var, str): var = var.split('\n') elif not isinstance(var, list): try: var = list(var) except TypeError: raise ValueError("{} cannot be converted to the list.".format(var)) return var
def iflatten ( L ) : for sublist in L : if hasattr ( sublist , '__iter__' ) : for item in iflatten ( sublist ) : yield item else : yield sublist
0
python make a list flat
Iterative flatten .
cosqa-train-15697
def iflatten(L): """Iterative flatten.""" for sublist in L: if hasattr(sublist, '__iter__'): for item in iflatten(sublist): yield item else: yield sublist
def to_str ( s ) : if isinstance ( s , bytes ) : s = s . decode ( 'utf-8' ) elif not isinstance ( s , str ) : s = str ( s ) return s
0
how to change string type using python
Convert bytes and non - string into Python 3 str
cosqa-train-15698
def to_str(s): """ Convert bytes and non-string into Python 3 str """ if isinstance(s, bytes): s = s.decode('utf-8') elif not isinstance(s, str): s = str(s) return s
def wait_run_in_executor ( func , * args , * * kwargs ) : loop = asyncio . get_event_loop ( ) future = loop . run_in_executor ( None , functools . partial ( func , * args , * * kwargs ) ) yield from asyncio . wait ( [ future ] ) return future . result ( )
0
python make blocking function to async
Run blocking code in a different thread and wait for the result .
cosqa-train-15699
def wait_run_in_executor(func, *args, **kwargs): """ Run blocking code in a different thread and wait for the result. :param func: Run this function in a different thread :param args: Parameters of the function :param kwargs: Keyword parameters of the function :returns: Return the result of the function """ loop = asyncio.get_event_loop() future = loop.run_in_executor(None, functools.partial(func, *args, **kwargs)) yield from asyncio.wait([future]) return future.result()