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 one_hot_encoding ( input_tensor , num_labels ) : xview = input_tensor . view ( - 1 , 1 ) . to ( torch . long ) onehot = torch . zeros ( xview . size ( 0 ) , num_labels , device = input_tensor . device , dtype = torch . float ) onehot . scatter_ ( 1 , xview , 1 ) return onehot . view ( list ( input_tensor . shape ) + [ - 1 ] )
1
how to one hot encode labels made of tuples python
One - hot encode labels from input
cosqa-train-13900
def one_hot_encoding(input_tensor, num_labels): """ One-hot encode labels from input """ xview = input_tensor.view(-1, 1).to(torch.long) onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float) onehot.scatter_(1, xview, 1) return onehot.view(list(input_tensor.shape) + [-1])
def save_session_to_file ( self , sessionfile ) : pickle . dump ( requests . utils . dict_from_cookiejar ( self . _session . cookies ) , sessionfile )
1
python requests session requestcookiejar persist
Not meant to be used directly use : meth : Instaloader . save_session_to_file .
cosqa-train-13901
def save_session_to_file(self, sessionfile): """Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`.""" pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)
def get_file_string ( filepath ) : with open ( os . path . abspath ( filepath ) ) as f : return f . read ( )
1
how to open a file with a path in python
Get string from file .
cosqa-train-13902
def get_file_string(filepath): """Get string from file.""" with open(os.path.abspath(filepath)) as f: return f.read()
def flat ( l ) : newl = [ ] for i in range ( len ( l ) ) : for j in range ( len ( l [ i ] ) ) : newl . append ( l [ i ] [ j ] ) return newl
0
python reshape flat list to 2d
Returns the flattened version of a 2D list . List - correlate to the a . flat () method of NumPy arrays .
cosqa-train-13903
def flat(l): """ Returns the flattened version of a '2D' list. List-correlate to the a.flat() method of NumPy arrays. Usage: flat(l) """ newl = [] for i in range(len(l)): for j in range(len(l[i])): newl.append(l[i][j]) return newl
def do_serial ( self , p ) : try : self . serial . port = p self . serial . open ( ) print 'Opening serial port: %s' % p except Exception , e : print 'Unable to open serial port: %s' % p
1
how to open a serial port in python
Set the serial port e . g . : / dev / tty . usbserial - A4001ib8
cosqa-train-13904
def do_serial(self, p): """Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8""" try: self.serial.port = p self.serial.open() print 'Opening serial port: %s' % p except Exception, e: print 'Unable to open serial port: %s' % p
def do_restart ( self , line ) : self . bot . _frame = 0 self . bot . _namespace . clear ( ) self . bot . _namespace . update ( self . bot . _initial_namespace )
0
python restart bot discord
Attempt to restart the bot .
cosqa-train-13905
def do_restart(self, line): """ Attempt to restart the bot. """ self.bot._frame = 0 self.bot._namespace.clear() self.bot._namespace.update(self.bot._initial_namespace)
def ReadTif ( tifFile ) : img = Image . open ( tifFile ) img = np . array ( img ) return img
1
how to open image in python and covert to a numpy array
Reads a tif file to a 2D NumPy array
cosqa-train-13906
def ReadTif(tifFile): """Reads a tif file to a 2D NumPy array""" img = Image.open(tifFile) img = np.array(img) return img
def _fill ( self ) : try : self . _head = self . _iterable . next ( ) except StopIteration : self . _head = None
1
python restart iterator from same spot
Advance the iterator without returning the old head .
cosqa-train-13907
def _fill(self): """Advance the iterator without returning the old head.""" try: self._head = self._iterable.next() except StopIteration: self._head = None
def do_serial ( self , p ) : try : self . serial . port = p self . serial . open ( ) print 'Opening serial port: %s' % p except Exception , e : print 'Unable to open serial port: %s' % p
1
how to open the serial port in python
Set the serial port e . g . : / dev / tty . usbserial - A4001ib8
cosqa-train-13908
def do_serial(self, p): """Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8""" try: self.serial.port = p self.serial.open() print 'Opening serial port: %s' % p except Exception, e: print 'Unable to open serial port: %s' % p
def get_previous ( self ) : return BillingCycle . objects . filter ( date_range__lt = self . date_range ) . order_by ( 'date_range' ) . last ( )
0
python retreive earlier project date
Get the billing cycle prior to this one . May return None
cosqa-train-13909
def get_previous(self): """Get the billing cycle prior to this one. May return None""" return BillingCycle.objects.filter(date_range__lt=self.date_range).order_by('date_range').last()
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
1
how to output an object attribute in python
Show the received object as precise as possible .
cosqa-train-13910
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 urlencoded ( body , charset = 'ascii' , * * kwargs ) : return parse_query_string ( text ( body , charset = charset ) , False )
1
python retrieving from a url query string
Converts query strings into native Python objects
cosqa-train-13911
def urlencoded(body, charset='ascii', **kwargs): """Converts query strings into native Python objects""" return parse_query_string(text(body, charset=charset), False)
def __call__ ( self , img ) : return F . pad ( img , self . padding , self . fill , self . padding_mode )
1
how to pad an image python
Args : img ( PIL Image ) : Image to be padded .
cosqa-train-13912
def __call__(self, img): """ Args: img (PIL Image): Image to be padded. Returns: PIL Image: Padded image. """ return F.pad(img, self.padding, self.fill, self.padding_mode)
def INIT_LIST_EXPR ( self , cursor ) : values = [ self . parse_cursor ( child ) for child in list ( cursor . get_children ( ) ) ] return values
1
python return cursor as list
Returns a list of literal values .
cosqa-train-13913
def INIT_LIST_EXPR(self, cursor): """Returns a list of literal values.""" values = [self.parse_cursor(child) for child in list(cursor.get_children())] return values
def parse ( filename ) : with open ( filename ) as f : parser = ASDLParser ( ) return parser . parse ( f . read ( ) )
1
how to parse a python file
Parse ASDL from the given file and return a Module node describing it .
cosqa-train-13914
def parse(filename): """Parse ASDL from the given file and return a Module node describing it.""" with open(filename) as f: parser = ASDLParser() return parser.parse(f.read())
def new_figure_manager_given_figure ( num , figure ) : fig = figure frame = FigureFrameWx ( num , fig ) figmgr = frame . get_figure_manager ( ) if matplotlib . is_interactive ( ) : figmgr . frame . Show ( ) return figmgr
1
python return fig 'figure' object
Create a new figure manager instance for the given figure .
cosqa-train-13915
def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ fig = figure frame = FigureFrameWx(num, fig) figmgr = frame.get_figure_manager() if matplotlib.is_interactive(): figmgr.frame.Show() return figmgr
def seconds ( num ) : now = pytime . time ( ) end = now + num until ( end )
1
how to pause a python loop
Pause for this many seconds
cosqa-train-13916
def seconds(num): """ Pause for this many seconds """ now = pytime.time() end = now + num until(end)
def software_fibonacci ( n ) : a , b = 0 , 1 for i in range ( n ) : a , b = b , a + b return a
1
python returns a function that returns the next fibonacci number
a normal old python function to return the Nth fibonacci number .
cosqa-train-13917
def software_fibonacci(n): """ a normal old python function to return the Nth fibonacci number. """ a, b = 0, 1 for i in range(n): a, b = b, a + b return a
def rand_elem ( seq , n = None ) : return map ( random . choice , repeat ( seq , n ) if n is not None else repeat ( seq ) )
1
how to pick random elemtns from python list
returns a random element from seq n times . If n is None it continues indefinitly
cosqa-train-13918
def rand_elem(seq, n=None): """returns a random element from seq n times. If n is None, it continues indefinitly""" return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))
def reset ( self ) : self . __iterator , self . __saved = itertools . tee ( self . __saved )
1
python reusing an iterator
Resets the iterator to the start .
cosqa-train-13919
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 finish_plot ( ) : plt . legend ( ) plt . grid ( color = '0.7' ) plt . xlabel ( 'x' ) plt . ylabel ( 'y' ) plt . show ( )
1
how to plot from a definition python
Helper for plotting .
cosqa-train-13920
def finish_plot(): """Helper for plotting.""" plt.legend() plt.grid(color='0.7') plt.xlabel('x') plt.ylabel('y') plt.show()
def rgba_bytes_tuple ( self , x ) : return tuple ( int ( u * 255.9999 ) for u in self . rgba_floats_tuple ( x ) )
1
python rgb tuple to colormap
Provides the color corresponding to value x in the form of a tuple ( R G B A ) with int values between 0 and 255 .
cosqa-train-13921
def rgba_bytes_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B,A) with int values between 0 and 255. """ return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))
def push ( h , x ) : h . push ( x ) up ( h , h . size ( ) - 1 )
1
how to pop a node off a stack python
Push a new value into heap .
cosqa-train-13922
def push(h, x): """Push a new value into heap.""" h.push(x) up(h, h.size()-1)
def rotateImage ( img , angle ) : imgR = scipy . ndimage . rotate ( img , angle , reshape = False ) return imgR
1
python rotate image by angle
cosqa-train-13923
def rotateImage(img, angle): """ querries scipy.ndimage.rotate routine :param img: image to be rotated :param angle: angle to be rotated (radian) :return: rotated image """ imgR = scipy.ndimage.rotate(img, angle, reshape=False) return imgR
def print_out ( self , * lst ) : self . print2file ( self . stdout , True , True , * lst )
1
how to print a list in python in the print funvtion
Print list of strings to the predefined stdout .
cosqa-train-13924
def print_out(self, *lst): """ Print list of strings to the predefined stdout. """ self.print2file(self.stdout, True, True, *lst)
def round_to_n ( x , n ) : return round ( x , - int ( np . floor ( np . log10 ( x ) ) ) + ( n - 1 ) )
0
python round a float to n decimals
Round to sig figs
cosqa-train-13925
def round_to_n(x, n): """ Round to sig figs """ return round(x, -int(np.floor(np.log10(x))) + (n - 1))
def handle_exception ( error ) : response = jsonify ( error . to_dict ( ) ) response . status_code = error . status_code return response
0
how to print error from python flask
Simple method for handling exceptions raised by PyBankID .
cosqa-train-13926
def handle_exception(error): """Simple method for handling exceptions raised by `PyBankID`. :param flask_pybankid.FlaskPyBankIDError error: The exception to handle. :return: The exception represented as a dictionary. :rtype: dict """ response = jsonify(error.to_dict()) response.status_code = error.status_code return response
def intround ( value ) : return int ( decimal . Decimal . from_float ( value ) . to_integral_value ( decimal . ROUND_HALF_EVEN ) )
1
python round float to int
Given a float returns a rounded int . Should give the same result on both Py2 / 3
cosqa-train-13927
def intround(value): """Given a float returns a rounded int. Should give the same result on both Py2/3 """ return int(decimal.Decimal.from_float( value).to_integral_value(decimal.ROUND_HALF_EVEN))
def fail_print ( error ) : print ( COLORS . fail , error . message , COLORS . end ) print ( COLORS . fail , error . errors , COLORS . end )
1
how to print error messages python
Print an error in red text . Parameters error ( HTTPError ) Error object to print .
cosqa-train-13928
def fail_print(error): """Print an error in red text. Parameters error (HTTPError) Error object to print. """ print(COLORS.fail, error.message, COLORS.end) print(COLORS.fail, error.errors, COLORS.end)
def round_figures ( x , n ) : return round ( x , int ( n - math . ceil ( math . log10 ( abs ( x ) ) ) ) )
1
python round to 2 significant figures
Returns x rounded to n significant figures .
cosqa-train-13929
def round_figures(x, n): """Returns x rounded to n significant figures.""" return round(x, int(n - math.ceil(math.log10(abs(x)))))
def _prt_line_detail ( self , prt , line , lnum = "" ) : data = zip ( self . flds , line . split ( '\t' ) ) txt = [ "{:2}) {:13} {}" . format ( i , hdr , val ) for i , ( hdr , val ) in enumerate ( data ) ] prt . write ( "{LNUM}\n{TXT}\n" . format ( LNUM = lnum , TXT = '\n' . join ( txt ) ) )
1
how to print fields of a line in python
Print each field and its value .
cosqa-train-13930
def _prt_line_detail(self, prt, line, lnum=""): """Print each field and its value.""" data = zip(self.flds, line.split('\t')) txt = ["{:2}) {:13} {}".format(i, hdr, val) for i, (hdr, val) in enumerate(data)] prt.write("{LNUM}\n{TXT}\n".format(LNUM=lnum, TXT='\n'.join(txt)))
def round_to_float ( number , precision ) : rounded = Decimal ( str ( floor ( ( number + precision / 2 ) // precision ) ) ) * Decimal ( str ( precision ) ) return float ( rounded )
1
python round to precision
Round a float to a precision
cosqa-train-13931
def round_to_float(number, precision): """Round a float to a precision""" rounded = Decimal(str(floor((number + precision / 2) // precision)) ) * Decimal(str(precision)) return float(rounded)
def show_partitioning ( rdd , show = True ) : if show : partitionCount = rdd . getNumPartitions ( ) try : valueCount = rdd . countApprox ( 1000 , confidence = 0.50 ) except : valueCount = - 1 try : name = rdd . name ( ) or None except : pass name = name or "anonymous" logging . info ( "For RDD %s, there are %d partitions with on average %s values" % ( name , partitionCount , int ( valueCount / float ( partitionCount ) ) ) )
1
how to print rdd size in python
Seems to be significantly more expensive on cluster than locally
cosqa-train-13932
def show_partitioning(rdd, show=True): """Seems to be significantly more expensive on cluster than locally""" if show: partitionCount = rdd.getNumPartitions() try: valueCount = rdd.countApprox(1000, confidence=0.50) except: valueCount = -1 try: name = rdd.name() or None except: pass name = name or "anonymous" logging.info("For RDD %s, there are %d partitions with on average %s values" % (name, partitionCount, int(valueCount/float(partitionCount))))
def managepy ( cmd , extra = None ) : extra = extra . split ( ) if extra else [ ] run_django_cli ( [ 'invoke' , cmd ] + extra )
0
python run commands as admin
Run manage . py using this component s specific Django settings
cosqa-train-13933
def managepy(cmd, extra=None): """Run manage.py using this component's specific Django settings""" extra = extra.split() if extra else [] run_django_cli(['invoke', cmd] + extra)
def parse ( self , s ) : return datetime . datetime . strptime ( s , self . date_format ) . date ( )
1
how to process a string into date object python
Parses a date string formatted like YYYY - MM - DD .
cosqa-train-13934
def parse(self, s): """ Parses a date string formatted like ``YYYY-MM-DD``. """ return datetime.datetime.strptime(s, self.date_format).date()
def start ( ) : global app bottle . run ( app , host = conf . WebHost , port = conf . WebPort , debug = conf . WebAutoReload , reloader = conf . WebAutoReload , quiet = conf . WebQuiet )
1
python runserver auto refresh browser
Starts the web server .
cosqa-train-13935
def start(): """Starts the web server.""" global app bottle.run(app, host=conf.WebHost, port=conf.WebPort, debug=conf.WebAutoReload, reloader=conf.WebAutoReload, quiet=conf.WebQuiet)
def _cumprod ( l ) : ret = [ 1 ] for item in l : ret . append ( ret [ - 1 ] * item ) return ret
1
how to produce product of numbers in list python
Cumulative product of a list .
cosqa-train-13936
def _cumprod(l): """Cumulative product of a list. Args: l: a list of integers Returns: a list with one more element (starting with 1) """ ret = [1] for item in l: ret.append(ret[-1] * item) return ret
def server ( port ) : args = [ 'python' , 'manage.py' , 'runserver' ] if port : args . append ( port ) run . main ( args )
0
python runserver set envrionemnt
Start the Django dev server .
cosqa-train-13937
def server(port): """Start the Django dev server.""" args = ['python', 'manage.py', 'runserver'] if port: args.append(port) run.main(args)
def camel_case ( self , snake_case ) : components = snake_case . split ( '_' ) return components [ 0 ] + "" . join ( x . title ( ) for x in components [ 1 : ] )
0
how to produce title case python
Convert snake case to camel case
cosqa-train-13938
def camel_case(self, snake_case): """ Convert snake case to camel case """ components = snake_case.split('_') return components[0] + "".join(x.title() for x in components[1:])
def fixpath ( path ) : return os . path . normpath ( os . path . realpath ( os . path . expanduser ( path ) ) )
1
python safe path name
Uniformly format a path .
cosqa-train-13939
def fixpath(path): """Uniformly format a path.""" return os.path.normpath(os.path.realpath(os.path.expanduser(path)))
def input ( self , prompt , default = None , show_default = True ) : return click . prompt ( prompt , default = default , show_default = show_default )
1
how to prompt an input in python
Provide a command prompt .
cosqa-train-13940
def input(self, prompt, default=None, show_default=True): """Provide a command prompt.""" return click.prompt(prompt, default=default, show_default=show_default)
def replacing_symlink ( source , link_name ) : with make_tmp_name ( link_name ) as tmp_link_name : os . symlink ( source , tmp_link_name ) replace_file_or_dir ( link_name , tmp_link_name )
0
python safe symlink function
Create symlink that overwrites any existing target .
cosqa-train-13941
def replacing_symlink(source, link_name): """Create symlink that overwrites any existing target. """ with make_tmp_name(link_name) as tmp_link_name: os.symlink(source, tmp_link_name) replace_file_or_dir(link_name, tmp_link_name)
def bitsToString ( arr ) : s = array ( 'c' , '.' * len ( arr ) ) for i in xrange ( len ( arr ) ) : if arr [ i ] == 1 : s [ i ] = '*' return s
1
how to put every character in array string python
Returns a string representing a numpy array of 0 s and 1 s
cosqa-train-13942
def bitsToString(arr): """Returns a string representing a numpy array of 0's and 1's""" s = array('c','.'*len(arr)) for i in xrange(len(arr)): if arr[i] == 1: s[i]='*' return s
def save ( variable , filename ) : fileObj = open ( filename , 'wb' ) pickle . dump ( variable , fileObj ) fileObj . close ( )
1
python saving a variable to a text file
Save variable on given path using Pickle Args : variable : what to save path ( str ) : path of the output
cosqa-train-13943
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 home_lib ( home ) : if hasattr ( sys , 'pypy_version_info' ) : lib = 'site-packages' else : lib = os . path . join ( 'lib' , 'python' ) return os . path . join ( home , lib )
0
how to put python libraries in the path of user
Return the lib dir under the home installation scheme
cosqa-train-13944
def home_lib(home): """Return the lib dir under the 'home' installation scheme""" if hasattr(sys, 'pypy_version_info'): lib = 'site-packages' else: lib = os.path.join('lib', 'python') return os.path.join(home, lib)
def draw ( graph , fname ) : ag = networkx . nx_agraph . to_agraph ( graph ) ag . draw ( fname , prog = 'dot' )
1
python saving graph to image file
Draw a graph and save it into a file
cosqa-train-13945
def draw(graph, fname): """Draw a graph and save it into a file""" ag = networkx.nx_agraph.to_agraph(graph) ag.draw(fname, prog='dot')
def _quit ( self , * args ) : self . logger . warn ( 'Bye!' ) sys . exit ( self . exit ( ) )
0
how to quit python
quit crash
cosqa-train-13946
def _quit(self, *args): """ quit crash """ self.logger.warn('Bye!') sys.exit(self.exit())
def _std ( self , x ) : return np . nanstd ( x . values , ddof = self . _ddof )
1
python scipy standard deviation
Compute standard deviation with ddof degrees of freedom
cosqa-train-13947
def _std(self,x): """ Compute standard deviation with ddof degrees of freedom """ return np.nanstd(x.values,ddof=self._ddof)
def _re_raise_as ( NewExc , * args , * * kw ) : etype , val , tb = sys . exc_info ( ) raise NewExc ( * args , * * kw ) , None , tb
0
how to raise a python
Raise a new exception using the preserved traceback of the last one .
cosqa-train-13948
def _re_raise_as(NewExc, *args, **kw): """Raise a new exception using the preserved traceback of the last one.""" etype, val, tb = sys.exc_info() raise NewExc(*args, **kw), None, tb
def aug_sysargv ( cmdstr ) : import shlex argv = shlex . split ( cmdstr ) sys . argv . extend ( argv )
1
python script arguents in vs
DEBUG FUNC modify argv to look like you ran a command
cosqa-train-13949
def aug_sysargv(cmdstr): """ DEBUG FUNC modify argv to look like you ran a command """ import shlex argv = shlex.split(cmdstr) sys.argv.extend(argv)
def get_randomized_guid_sample ( self , item_count ) : dataset = self . get_whitelist ( ) random . shuffle ( dataset ) return dataset [ : item_count ]
1
how to randomize items in a list in python
Fetch a subset of randomzied GUIDs from the whitelist
cosqa-train-13950
def get_randomized_guid_sample(self, item_count): """ Fetch a subset of randomzied GUIDs from the whitelist """ dataset = self.get_whitelist() random.shuffle(dataset) return dataset[:item_count]
def isInteractive ( ) : if sys . stdout . isatty ( ) and os . name != 'nt' : #Hopefully everything but ms supports '\r' try : import threading except ImportError : return False else : return True else : return False
0
python script mode bug interactive mode work
A basic check of if the program is running in interactive mode
cosqa-train-13951
def isInteractive(): """ A basic check of if the program is running in interactive mode """ if sys.stdout.isatty() and os.name != 'nt': #Hopefully everything but ms supports '\r' try: import threading except ImportError: return False else: return True else: return False
def rand_elem ( seq , n = None ) : return map ( random . choice , repeat ( seq , n ) if n is not None else repeat ( seq ) )
1
how to randomly generate elements in python
returns a random element from seq n times . If n is None it continues indefinitly
cosqa-train-13952
def rand_elem(seq, n=None): """returns a random element from seq n times. If n is None, it continues indefinitly""" return map(random.choice, repeat(seq, n) if n is not None else repeat(seq))
def cpp_prog_builder ( build_context , target ) : yprint ( build_context . conf , 'Build CppProg' , target ) workspace_dir = build_context . get_workspace ( 'CppProg' , target . name ) build_cpp ( build_context , target , target . compiler_config , workspace_dir )
1
python script to compile c++ program
Build a C ++ binary executable
cosqa-train-13953
def cpp_prog_builder(build_context, target): """Build a C++ binary executable""" yprint(build_context.conf, 'Build CppProg', target) workspace_dir = build_context.get_workspace('CppProg', target.name) build_cpp(build_context, target, target.compiler_config, workspace_dir)
def read_dict_from_file ( file_path ) : with open ( file_path ) as file : lines = file . read ( ) . splitlines ( ) obj = { } for line in lines : key , value = line . split ( ':' , maxsplit = 1 ) obj [ key ] = eval ( value ) return obj
1
how to read a text file and return a dictionary in python
Read a dictionary of strings from a file
cosqa-train-13954
def read_dict_from_file(file_path): """ Read a dictionary of strings from a file """ with open(file_path) as file: lines = file.read().splitlines() obj = {} for line in lines: key, value = line.split(':', maxsplit=1) obj[key] = eval(value) return obj
def CleanseComments ( line ) : commentpos = line . find ( '//' ) if commentpos != - 1 and not IsCppString ( line [ : commentpos ] ) : line = line [ : commentpos ] . rstrip ( ) # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS . sub ( '' , line )
1
python script to replace c++ comment line
Removes // - comments and single - line C - style / * * / comments .
cosqa-train-13955
def CleanseComments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ commentpos = line.find('//') if commentpos != -1 and not IsCppString(line[:commentpos]): line = line[:commentpos].rstrip() # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
def read_dict_from_file ( file_path ) : with open ( file_path ) as file : lines = file . read ( ) . splitlines ( ) obj = { } for line in lines : key , value = line . split ( ':' , maxsplit = 1 ) obj [ key ] = eval ( value ) return obj
1
how to read a text file in as a dictionary python
Read a dictionary of strings from a file
cosqa-train-13956
def read_dict_from_file(file_path): """ Read a dictionary of strings from a file """ with open(file_path) as file: lines = file.read().splitlines() obj = {} for line in lines: key, value = line.split(':', maxsplit=1) obj[key] = eval(value) return obj
def get_login_credentials ( args ) : if not args . username : args . username = raw_input ( "Enter Username: " ) if not args . password : args . password = getpass . getpass ( "Enter Password: " )
1
python scripts incorporate credentials
Gets the login credentials from the user if not specified while invoking the script .
cosqa-train-13957
def get_login_credentials(args): """ Gets the login credentials from the user, if not specified while invoking the script. @param args: arguments provided to the script. """ if not args.username: args.username = raw_input("Enter Username: ") if not args.password: args.password = getpass.getpass("Enter Password: ")
def read_dict_from_file ( file_path ) : with open ( file_path ) as file : lines = file . read ( ) . splitlines ( ) obj = { } for line in lines : key , value = line . split ( ':' , maxsplit = 1 ) obj [ key ] = eval ( value ) return obj
1
how to read a text file into a dictionary in python
Read a dictionary of strings from a file
cosqa-train-13958
def read_dict_from_file(file_path): """ Read a dictionary of strings from a file """ with open(file_path) as file: lines = file.read().splitlines() obj = {} for line in lines: key, value = line.split(':', maxsplit=1) obj[key] = eval(value) return obj
def timespan ( start_time ) : timespan = datetime . datetime . now ( ) - start_time timespan_ms = timespan . total_seconds ( ) * 1000 return timespan_ms
1
python seconds elapsed to timespan
Return time in milliseconds from start_time
cosqa-train-13959
def timespan(start_time): """Return time in milliseconds from start_time""" timespan = datetime.datetime.now() - start_time timespan_ms = timespan.total_seconds() * 1000 return timespan_ms
def get_code ( module ) : fp = open ( module . path ) try : return compile ( fp . read ( ) , str ( module . name ) , 'exec' ) finally : fp . close ( )
0
how to read compiled python
Compile and return a Module s code object .
cosqa-train-13960
def get_code(module): """ Compile and return a Module's code object. """ fp = open(module.path) try: return compile(fp.read(), str(module.name), 'exec') finally: fp.close()
def selectnotnone ( table , field , complement = False ) : return select ( table , field , lambda v : v is not None , complement = complement )
0
python select at least one column not null
Select rows where the given field is not None .
cosqa-train-13961
def selectnotnone(table, field, complement=False): """Select rows where the given field is not `None`.""" return select(table, field, lambda v: v is not None, complement=complement)
def _read_json_file ( self , json_file ) : self . log . debug ( "Reading '%s' JSON file..." % json_file ) with open ( json_file , 'r' ) as f : return json . load ( f , object_pairs_hook = OrderedDict )
1
how to read json files with multiple object python
Helper function to read JSON file as OrderedDict
cosqa-train-13962
def _read_json_file(self, json_file): """ Helper function to read JSON file as OrderedDict """ self.log.debug("Reading '%s' JSON file..." % json_file) with open(json_file, 'r') as f: return json.load(f, object_pairs_hook=OrderedDict)
def selectnotnone ( table , field , complement = False ) : return select ( table , field , lambda v : v is not None , complement = complement )
1
python select cases that are not null
Select rows where the given field is not None .
cosqa-train-13963
def selectnotnone(table, field, complement=False): """Select rows where the given field is not `None`.""" return select(table, field, lambda v: v is not None, complement=complement)
def read_key ( self , key , bucket_name = None ) : obj = self . get_key ( key , bucket_name ) return obj . get ( ) [ 'Body' ] . read ( ) . decode ( 'utf-8' )
1
how to read s3 files in python with access keys
Reads a key from S3
cosqa-train-13964
def read_key(self, key, bucket_name=None): """ Reads a key from S3 :param key: S3 key that will point to the file :type key: str :param bucket_name: Name of the bucket in which the file is stored :type bucket_name: str """ obj = self.get_key(key, bucket_name) return obj.get()['Body'].read().decode('utf-8')
def selectnotin ( table , field , value , complement = False ) : return select ( table , field , lambda v : v not in value , complement = complement )
1
python select column not in
Select rows where the given field is not a member of the given value .
cosqa-train-13965
def selectnotin(table, field, value, complement=False): """Select rows where the given field is not a member of the given value.""" return select(table, field, lambda v: v not in value, complement=complement)
def wget ( url ) : import urllib . parse request = urllib . request . urlopen ( url ) filestring = request . read ( ) return filestring
1
how to read the file from internet in python
Download the page into a string
cosqa-train-13966
def wget(url): """ Download the page into a string """ import urllib.parse request = urllib.request.urlopen(url) filestring = request.read() return filestring
def get_last ( self , table = None ) : if table is None : table = self . main_table query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table return self . own_cursor . execute ( query ) . fetchone ( )
1
python select last row in mysql
Just the last entry .
cosqa-train-13967
def get_last(self, table=None): """Just the last entry.""" if table is None: table = self.main_table query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table return self.own_cursor.execute(query).fetchone()
def get_active_window ( self ) : app = get_app ( ) try : return self . _active_window_for_cli [ app ] except KeyError : self . _active_window_for_cli [ app ] = self . _last_active_window or self . windows [ 0 ] return self . windows [ 0 ]
1
how to read what the active window is currently with python
The current active : class : . Window .
cosqa-train-13968
def get_active_window(self): """ The current active :class:`.Window`. """ app = get_app() try: return self._active_window_for_cli[app] except KeyError: self._active_window_for_cli[app] = self._last_active_window or self.windows[0] return self.windows[0]
def date ( start , end ) : stime = date_to_timestamp ( start ) etime = date_to_timestamp ( end ) ptime = stime + random . random ( ) * ( etime - stime ) return datetime . date . fromtimestamp ( ptime )
1
python select random date between two dates
Get a random date between two dates
cosqa-train-13969
def date(start, end): """Get a random date between two dates""" stime = date_to_timestamp(start) etime = date_to_timestamp(end) ptime = stime + random.random() * (etime - stime) return datetime.date.fromtimestamp(ptime)
def load_yaml ( filepath ) : with open ( filepath ) as f : txt = f . read ( ) return yaml . load ( txt )
1
how to read yaml file in python
Convenience function for loading yaml - encoded data from disk .
cosqa-train-13970
def load_yaml(filepath): """Convenience function for loading yaml-encoded data from disk.""" with open(filepath) as f: txt = f.read() return yaml.load(txt)
def get_randomized_guid_sample ( self , item_count ) : dataset = self . get_whitelist ( ) random . shuffle ( dataset ) return dataset [ : item_count ]
1
python select random items from sample
Fetch a subset of randomzied GUIDs from the whitelist
cosqa-train-13971
def get_randomized_guid_sample(self, item_count): """ Fetch a subset of randomzied GUIDs from the whitelist """ dataset = self.get_whitelist() random.shuffle(dataset) return dataset[:item_count]
def main ( ) : time . sleep ( 1 ) with Input ( ) as input_generator : for e in input_generator : print ( repr ( e ) )
1
how to record each itteration of an event in python
Ideally we shouldn t lose the first second of events
cosqa-train-13972
def main(): """Ideally we shouldn't lose the first second of events""" time.sleep(1) with Input() as input_generator: for e in input_generator: print(repr(e))
def selectin ( table , field , value , complement = False ) : return select ( table , field , lambda v : v in value , complement = complement )
1
python select rows isin not
Select rows where the given field is a member of the given value .
cosqa-train-13973
def selectin(table, field, value, complement=False): """Select rows where the given field is a member of the given value.""" return select(table, field, lambda v: v in value, complement=complement)
def redirect_output ( fileobj ) : old = sys . stdout sys . stdout = fileobj try : yield fileobj finally : sys . stdout = old
1
how to redirect stdout to a file in python
Redirect standard out to file .
cosqa-train-13974
def redirect_output(fileobj): """Redirect standard out to file.""" old = sys.stdout sys.stdout = fileobj try: yield fileobj finally: sys.stdout = old
def process_kill ( pid , sig = None ) : sig = sig or signal . SIGTERM os . kill ( pid , sig )
1
python send a signal to a process
Send signal to process .
cosqa-train-13975
def process_kill(pid, sig=None): """Send signal to process. """ sig = sig or signal.SIGTERM os.kill(pid, sig)
def append_pdf ( input_pdf : bytes , output_writer : PdfFileWriter ) : append_memory_pdf_to_writer ( input_pdf = input_pdf , writer = output_writer )
1
how to reduce file size with pdfpages in python
Appends a PDF to a pyPDF writer . Legacy interface .
cosqa-train-13976
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter): """ Appends a PDF to a pyPDF writer. Legacy interface. """ append_memory_pdf_to_writer(input_pdf=input_pdf, writer=output_writer)
def _send ( self , data ) : if not self . _sock : self . connect ( ) self . _do_send ( data )
1
python send data to statsd
Send data to statsd .
cosqa-train-13977
def _send(self, data): """Send data to statsd.""" if not self._sock: self.connect() self._do_send(data)
def type ( self ) : if self is FeatureType . TIMESTAMP : return list if self is FeatureType . BBOX : return BBox return dict
1
how to refer to specific types in python
Returns type of the data for the given FeatureType .
cosqa-train-13978
def type(self): """Returns type of the data for the given FeatureType.""" if self is FeatureType.TIMESTAMP: return list if self is FeatureType.BBOX: return BBox return dict
def send ( self , data ) : self . stdin . write ( data ) self . stdin . flush ( )
0
python send input to subprocess
Send data to the child process through .
cosqa-train-13979
def send(self, data): """ Send data to the child process through. """ self.stdin.write(data) self.stdin.flush()
def strip_html ( string , keep_tag_content = False ) : r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r . sub ( '' , string )
1
how to remove all html tags from text in [python
Remove html code contained into the given string .
cosqa-train-13980
def strip_html(string, keep_tag_content=False): """ Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. :rtype: str """ r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r.sub('', string)
def send_post ( self , url , data , remove_header = None ) : return self . send_request ( method = "post" , url = url , data = data , remove_header = remove_header )
1
python send post request without response
Send a POST request
cosqa-train-13981
def send_post(self, url, data, remove_header=None): """ Send a POST request """ return self.send_request(method="post", url=url, data=data, remove_header=remove_header)
def dedupe_list ( seq ) : seen = set ( ) return [ x for x in seq if not ( x in seen or seen . add ( x ) ) ]
1
how to remove all repetition in list python
Utility function to remove duplicates from a list : param seq : The sequence ( list ) to deduplicate : return : A list with original duplicates removed
cosqa-train-13982
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 serialize_me ( self , account , bucket_details ) : return self . dumps ( { "account" : account , "detail" : { "request_parameters" : { "bucket_name" : bucket_details [ "Name" ] , "creation_date" : bucket_details [ "CreationDate" ] . replace ( tzinfo = None , microsecond = 0 ) . isoformat ( ) + "Z" } } } ) . data
1
python serialize aws event data
Serializes the JSON for the Polling Event Model .
cosqa-train-13983
def serialize_me(self, account, bucket_details): """Serializes the JSON for the Polling Event Model. :param account: :param bucket_details: :return: """ return self.dumps({ "account": account, "detail": { "request_parameters": { "bucket_name": bucket_details["Name"], "creation_date": bucket_details["CreationDate"].replace( tzinfo=None, microsecond=0).isoformat() + "Z" } } }).data
def _remove_blank ( l ) : ret = [ ] for i , _ in enumerate ( l ) : if l [ i ] == 0 : break ret . append ( l [ i ] ) return ret
1
how to remove all zeros from a list python
Removes trailing zeros in the list of integers and returns a new list of integers
cosqa-train-13984
def _remove_blank(l): """ Removes trailing zeros in the list of integers and returns a new list of integers""" ret = [] for i, _ in enumerate(l): if l[i] == 0: break ret.append(l[i]) return ret
def stop ( self , reason = None ) : self . logger . info ( 'stopping' ) self . loop . stop ( pyev . EVBREAK_ALL )
0
python service stop event
Shutdown the service with a reason .
cosqa-train-13985
def stop(self, reason=None): """Shutdown the service with a reason.""" self.logger.info('stopping') self.loop.stop(pyev.EVBREAK_ALL)
def remove_instance ( self , item ) : self . instances . remove ( item ) self . remove_item ( item )
1
how to remove an object from list python
Remove instance from model
cosqa-train-13986
def remove_instance(self, item): """Remove `instance` from model""" self.instances.remove(item) self.remove_item(item)
def _session_set ( self , key , value ) : self . session [ self . _session_key ( key ) ] = value
1
python set flask session variable
Saves a value to session .
cosqa-train-13987
def _session_set(self, key, value): """ Saves a value to session. """ self.session[self._session_key(key)] = value
def border ( self ) : border_array = self . bitmap - self . inner . bitmap return Region ( border_array )
1
how to remove border in image in python
Region formed by taking border elements .
cosqa-train-13988
def border(self): """Region formed by taking border elements. :returns: :class:`jicimagelib.region.Region` """ border_array = self.bitmap - self.inner.bitmap return Region(border_array)
def set_json_item ( key , value ) : data = get_json ( ) data [ key ] = value request = get_request ( ) request [ "BODY" ] = json . dumps ( data )
1
python set json value as variable
manipulate json data on the fly
cosqa-train-13989
def set_json_item(key, value): """ manipulate json data on the fly """ data = get_json() data[key] = value request = get_request() request["BODY"] = json.dumps(data)
def clean_df ( df , fill_nan = True , drop_empty_columns = True ) : if fill_nan : df = df . fillna ( value = np . nan ) if drop_empty_columns : df = df . dropna ( axis = 1 , how = 'all' ) return df . sort_index ( )
1
how to remove nan from columns in python
Clean a pandas dataframe by : 1 . Filling empty values with Nan 2 . Dropping columns with all empty values
cosqa-train-13990
def clean_df(df, fill_nan=True, drop_empty_columns=True): """Clean a pandas dataframe by: 1. Filling empty values with Nan 2. Dropping columns with all empty values Args: df: Pandas DataFrame fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN drop_empty_columns (bool): If columns whose values are all empty should be dropped Returns: DataFrame: cleaned DataFrame """ if fill_nan: df = df.fillna(value=np.nan) if drop_empty_columns: df = df.dropna(axis=1, how='all') return df.sort_index()
def _updateTabStopWidth ( self ) : self . setTabStopWidth ( self . fontMetrics ( ) . width ( ' ' * self . _indenter . width ) )
0
python set tab spacing
Update tabstop width after font or indentation changed
cosqa-train-13991
def _updateTabStopWidth(self): """Update tabstop width after font or indentation changed """ self.setTabStopWidth(self.fontMetrics().width(' ' * self._indenter.width))
def dict_keys_without_hyphens ( a_dict ) : return dict ( ( key . replace ( '-' , '_' ) , val ) for key , val in a_dict . items ( ) )
0
how to remove words and create acronyms using python
Return the a new dict with underscores instead of hyphens in keys .
cosqa-train-13992
def dict_keys_without_hyphens(a_dict): """Return the a new dict with underscores instead of hyphens in keys.""" return dict( (key.replace('-', '_'), val) for key, val in a_dict.items())
def empty ( self , start = None , stop = None ) : self . set ( NOT_SET , start = start , stop = stop )
1
python set to rangeindex
Empty the range from start to stop .
cosqa-train-13993
def empty(self, start=None, stop=None): """Empty the range from start to stop. Like delete, but no Error is raised if the entire range isn't mapped. """ self.set(NOT_SET, start=start, stop=stop)
def replace_all ( filepath , searchExp , replaceExp ) : for line in fileinput . input ( filepath , inplace = 1 ) : if searchExp in line : line = line . replace ( searchExp , replaceExp ) sys . stdout . write ( line )
1
how to replace a line in a file using python matching string
Replace all the ocurrences ( in a file ) of a string with another value .
cosqa-train-13994
def replace_all(filepath, searchExp, replaceExp): """ Replace all the ocurrences (in a file) of a string with another value. """ for line in fileinput.input(filepath, inplace=1): if searchExp in line: line = line.replace(searchExp, replaceExp) sys.stdout.write(line)
def _top ( self ) : # Goto top of the list self . top . body . focus_position = 2 if self . compact is False else 0 self . top . keypress ( self . size , "" )
1
python set top most window
g
cosqa-train-13995
def _top(self): """ g """ # Goto top of the list self.top.body.focus_position = 2 if self.compact is False else 0 self.top.keypress(self.size, "")
def replace_all ( filepath , searchExp , replaceExp ) : for line in fileinput . input ( filepath , inplace = 1 ) : if searchExp in line : line = line . replace ( searchExp , replaceExp ) sys . stdout . write ( line )
1
how to replace a specific word in python file handling
Replace all the ocurrences ( in a file ) of a string with another value .
cosqa-train-13996
def replace_all(filepath, searchExp, replaceExp): """ Replace all the ocurrences (in a file) of a string with another value. """ for line in fileinput.input(filepath, inplace=1): if searchExp in line: line = line.replace(searchExp, replaceExp) sys.stdout.write(line)
def move_datetime_year ( dt , direction , num_shifts ) : delta = relativedelta ( years = + num_shifts ) return _move_datetime ( dt , direction , delta )
1
python set year for datetime object
Move datetime 1 year in the chosen direction . unit is a no - op to keep the API the same as the day case
cosqa-train-13997
def move_datetime_year(dt, direction, num_shifts): """ Move datetime 1 year in the chosen direction. unit is a no-op, to keep the API the same as the day case """ delta = relativedelta(years=+num_shifts) return _move_datetime(dt, direction, delta)
def mock_decorator ( * args , * * kwargs ) : def _called_decorator ( dec_func ) : @ wraps ( dec_func ) def _decorator ( * args , * * kwargs ) : return dec_func ( ) return _decorator return _called_decorator
1
how to replace database call of a function in python mock
Mocked decorator needed in the case we need to mock a decorator
cosqa-train-13998
def mock_decorator(*args, **kwargs): """Mocked decorator, needed in the case we need to mock a decorator""" def _called_decorator(dec_func): @wraps(dec_func) def _decorator(*args, **kwargs): return dec_func() return _decorator return _called_decorator
def print_fatal_results ( results , level = 0 ) : print_level ( logger . critical , _RED + "[X] Fatal Error: %s" , level , results . error )
1
python setlevel how to only record error
Print fatal errors that occurred during validation runs .
cosqa-train-13999
def print_fatal_results(results, level=0): """Print fatal errors that occurred during validation runs. """ print_level(logger.critical, _RED + "[X] Fatal Error: %s", level, results.error)