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 extract_alzip ( archive , compression , cmd , verbosity , interactive , outdir ) : return [ cmd , '-d' , outdir , archive ]
0
aws python gzip fails lambda
Extract a ALZIP archive .
cosqa-train-14900
def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir): """Extract a ALZIP archive.""" return [cmd, '-d', outdir, archive]
def html ( header_rows ) : name = 'table%d' % next ( tablecounter ) return HtmlTable ( [ map ( str , row ) for row in header_rows ] , name ) . render ( )
0
python combine multiple html table into one html page
Convert a list of tuples describing a table into a HTML string
cosqa-train-14901
def html(header_rows): """ Convert a list of tuples describing a table into a HTML string """ name = 'table%d' % next(tablecounter) return HtmlTable([map(str, row) for row in header_rows], name).render()
def bytes_base64 ( x ) : if six . PY2 : return base64 . encodestring ( x ) . replace ( '\n' , '' ) return base64 . encodebytes ( bytes_encode ( x ) ) . replace ( b'\n' , b'' )
0
base64 works for python2 but not python3
Turn bytes into base64
cosqa-train-14902
def bytes_base64(x): """Turn bytes into base64""" if six.PY2: return base64.encodestring(x).replace('\n', '') return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'')
def _merge_meta ( model1 , model2 ) : w1 = _get_meta ( model1 ) w2 = _get_meta ( model2 ) return metadata . merge ( w1 , w2 , metadata_conflicts = 'silent' )
1
python combine multiple models
Simple merge of samplesets .
cosqa-train-14903
def _merge_meta(model1, model2): """Simple merge of samplesets.""" w1 = _get_meta(model1) w2 = _get_meta(model2) return metadata.merge(w1, w2, metadata_conflicts='silent')
def paginate ( self , request , offset = 0 , limit = None ) : return self . collection . offset ( offset ) . limit ( limit ) , self . collection . count ( )
1
best way to deal with pagination in python
Paginate queryset .
cosqa-train-14904
def paginate(self, request, offset=0, limit=None): """Paginate queryset.""" return self.collection.offset(offset).limit(limit), self.collection.count()
def _updateItemComboBoxIndex ( self , item , column , num ) : item . _combobox_current_index [ column ] = num item . _combobox_current_value [ column ] = item . _combobox_option_list [ column ] [ num ] [ 0 ]
0
python combobox change value update
Callback for comboboxes : notifies us that a combobox for the given item and column has changed
cosqa-train-14905
def _updateItemComboBoxIndex(self, item, column, num): """Callback for comboboxes: notifies us that a combobox for the given item and column has changed""" item._combobox_current_index[column] = num item._combobox_current_value[column] = item._combobox_option_list[column][num][0]
def multi_pop ( d , * args ) : retval = { } for key in args : if key in d : retval [ key ] = d . pop ( key ) return retval
0
best way to pop many elements from python dict
pops multiple keys off a dict like object
cosqa-train-14906
def multi_pop(d, *args): """ pops multiple keys off a dict like object """ retval = {} for key in args: if key in d: retval[key] = d.pop(key) return retval
def onchange ( self , value ) : log . debug ( 'combo box. selected %s' % value ) self . select_by_value ( value ) return ( value , )
0
python combobox update onclick
Called when a new DropDownItem gets selected .
cosqa-train-14907
def onchange(self, value): """Called when a new DropDownItem gets selected. """ log.debug('combo box. selected %s' % value) self.select_by_value(value) return (value, )
def hidden_cursor ( self ) : self . stream . write ( self . hide_cursor ) try : yield finally : self . stream . write ( self . normal_cursor )
1
black cursor block python
Return a context manager that hides the cursor while inside it and makes it visible on leaving .
cosqa-train-14908
def hidden_cursor(self): """Return a context manager that hides the cursor while inside it and makes it visible on leaving.""" self.stream.write(self.hide_cursor) try: yield finally: self.stream.write(self.normal_cursor)
def clean_whitespace ( string , compact = False ) : for a , b in ( ( '\r\n' , '\n' ) , ( '\r' , '\n' ) , ( '\n\n' , '\n' ) , ( '\t' , ' ' ) , ( ' ' , ' ' ) ) : string = string . replace ( a , b ) if compact : for a , b in ( ( '\n' , ' ' ) , ( '[ ' , '[' ) , ( ' ' , ' ' ) , ( ' ' , ' ' ) , ( ' ' , ' ' ) ) : string = string . replace ( a , b ) return string . strip ( )
1
python compress all whitespace
Return string with compressed whitespace .
cosqa-train-14909
def clean_whitespace(string, compact=False): """Return string with compressed whitespace.""" for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'), ('\t', ' '), (' ', ' ')): string = string.replace(a, b) if compact: for a, b in (('\n', ' '), ('[ ', '['), (' ', ' '), (' ', ' '), (' ', ' ')): string = string.replace(a, b) return string.strip()
def cpp_checker ( code , working_directory ) : return gcc_checker ( code , '.cpp' , [ os . getenv ( 'CXX' , 'g++' ) , '-std=c++0x' ] + INCLUDE_FLAGS , working_directory = working_directory )
0
boost python define c++ functions
Return checker .
cosqa-train-14910
def cpp_checker(code, working_directory): """Return checker.""" return gcc_checker(code, '.cpp', [os.getenv('CXX', 'g++'), '-std=c++0x'] + INCLUDE_FLAGS, working_directory=working_directory)
def clean_whitespace ( string , compact = False ) : for a , b in ( ( '\r\n' , '\n' ) , ( '\r' , '\n' ) , ( '\n\n' , '\n' ) , ( '\t' , ' ' ) , ( ' ' , ' ' ) ) : string = string . replace ( a , b ) if compact : for a , b in ( ( '\n' , ' ' ) , ( '[ ' , '[' ) , ( ' ' , ' ' ) , ( ' ' , ' ' ) , ( ' ' , ' ' ) ) : string = string . replace ( a , b ) return string . strip ( )
1
python compress whitespace from string
Return string with compressed whitespace .
cosqa-train-14911
def clean_whitespace(string, compact=False): """Return string with compressed whitespace.""" for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'), ('\t', ' '), (' ', ' ')): string = string.replace(a, b) if compact: for a, b in (('\n', ' '), ('[ ', '['), (' ', ' '), (' ', ' '), (' ', ' ')): string = string.replace(a, b) return string.strip()
def ver_to_tuple ( value ) : return tuple ( int ( _f ) for _f in re . split ( r'\D+' , value ) if _f )
1
breaking a python string into a tuple
Convert version like string to a tuple of integers .
cosqa-train-14912
def ver_to_tuple(value): """ Convert version like string to a tuple of integers. """ return tuple(int(_f) for _f in re.split(r'\D+', value) if _f)
def vector_distance ( a , b ) : a = np . array ( a ) b = np . array ( b ) return np . linalg . norm ( a - b )
1
python compute euclidean distance between two vectors
The Euclidean distance between two vectors .
cosqa-train-14913
def vector_distance(a, b): """The Euclidean distance between two vectors.""" a = np.array(a) b = np.array(b) return np.linalg.norm(a - b)
def getBuffer ( x ) : b = bytes ( x ) return ( c_ubyte * len ( b ) ) . from_buffer_copy ( bytes ( x ) )
0
buffer from c++ to python
Copy
cosqa-train-14914
def getBuffer(x): """ Copy @x into a (modifiable) ctypes byte array """ b = bytes(x) return (c_ubyte * len(b)).from_buffer_copy(bytes(x))
def compose_all ( tups ) : from . import ast # I weep for humanity return functools . reduce ( lambda x , y : x . compose ( y ) , map ( ast . make_tuple , tups ) , ast . make_tuple ( { } ) )
0
python concatenate string to all items in a list
Compose all given tuples together .
cosqa-train-14915
def compose_all(tups): """Compose all given tuples together.""" from . import ast # I weep for humanity return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))
def _from_bytes ( bytes , byteorder = "big" , signed = False ) : return int . from_bytes ( bytes , byteorder = byteorder , signed = signed )
0
byte indices must be integers or slices, not str python
This is the same functionality as int . from_bytes in python 3
cosqa-train-14916
def _from_bytes(bytes, byteorder="big", signed=False): """This is the same functionality as ``int.from_bytes`` in python 3""" return int.from_bytes(bytes, byteorder=byteorder, signed=signed)
def config_parser_to_dict ( config_parser ) : response = { } for section in config_parser . sections ( ) : for option in config_parser . options ( section ) : response . setdefault ( section , { } ) [ option ] = config_parser . get ( section , option ) return response
0
python configparser to tict
Convert a ConfigParser to a dictionary .
cosqa-train-14917
def config_parser_to_dict(config_parser): """ Convert a ConfigParser to a dictionary. """ response = {} for section in config_parser.sections(): for option in config_parser.options(section): response.setdefault(section, {})[option] = config_parser.get(section, option) return response
def be_array_from_bytes ( fmt , data ) : arr = array . array ( str ( fmt ) , data ) return fix_byteorder ( arr )
0
bytes file to byte array python
Reads an array from bytestring with big - endian data .
cosqa-train-14918
def be_array_from_bytes(fmt, data): """ Reads an array from bytestring with big-endian data. """ arr = array.array(str(fmt), data) return fix_byteorder(arr)
def list_string_to_dict ( string ) : dictionary = { } for idx , c in enumerate ( string ) : dictionary . update ( { c : idx } ) return dictionary
0
python construct a dictionary from string
Inputs [ a b c ] returns { a : 0 b : 1 c : 2 } .
cosqa-train-14919
def list_string_to_dict(string): """Inputs ``['a', 'b', 'c']``, returns ``{'a': 0, 'b': 1, 'c': 2}``.""" dictionary = {} for idx, c in enumerate(string): dictionary.update({c: idx}) return dictionary
def dot ( self , w ) : return sum ( [ x * y for x , y in zip ( self , w ) ] )
1
calculate dot product of two vectors in python
Return the dotproduct between self and another vector .
cosqa-train-14920
def dot(self, w): """Return the dotproduct between self and another vector.""" return sum([x * y for x, y in zip(self, w)])
def fromiterable ( cls , itr ) : x , y , z = itr return cls ( x , y , z )
1
python constructor taking iterable
Initialize from iterable
cosqa-train-14921
def fromiterable(cls, itr): """Initialize from iterable""" x, y, z = itr return cls(x, y, z)
def dot ( self , w ) : return sum ( [ x * y for x , y in zip ( self , w ) ] )
1
calculate dot product of two vectorsin python
Return the dotproduct between self and another vector .
cosqa-train-14922
def dot(self, w): """Return the dotproduct between self and another vector.""" return sum([x * y for x, y in zip(self, w)])
def time2seconds ( t ) : return t . hour * 3600 + t . minute * 60 + t . second + float ( t . microsecond ) / 1e6
0
python conver seconds into hours minutes seconds
Returns seconds since 0h00 .
cosqa-train-14923
def time2seconds(t): """Returns seconds since 0h00.""" return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6
def ln_norm ( x , mu , sigma = 1.0 ) : return np . log ( stats . norm ( loc = mu , scale = sigma ) . pdf ( x ) )
0
calculate log normal distribution in python with only a column variable
Natural log of scipy norm function truncated at zero
cosqa-train-14924
def ln_norm(x, mu, sigma=1.0): """ Natural log of scipy norm function truncated at zero """ return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))
def string_to_float_list ( string_var ) : try : return [ float ( s ) for s in string_var . strip ( '[' ) . strip ( ']' ) . split ( ', ' ) ] except : return [ float ( s ) for s in string_var . strip ( '[' ) . strip ( ']' ) . split ( ',' ) ]
0
python converst list of str to float
Pull comma separated string values out of a text file and converts them to float list
cosqa-train-14925
def string_to_float_list(string_var): """Pull comma separated string values out of a text file and converts them to float list""" try: return [float(s) for s in string_var.strip('[').strip(']').split(', ')] except: return [float(s) for s in string_var.strip('[').strip(']').split(',')]
def md5_string ( s ) : m = hashlib . md5 ( ) m . update ( s ) return str ( m . hexdigest ( ) )
0
calculate md5 of string in python
Shortcut to create md5 hash : param s : : return :
cosqa-train-14926
def md5_string(s): """ Shortcut to create md5 hash :param s: :return: """ m = hashlib.md5() m.update(s) return str(m.hexdigest())
def convolve_gaussian_2d ( image , gaussian_kernel_1d ) : result = scipy . ndimage . filters . correlate1d ( image , gaussian_kernel_1d , axis = 0 ) result = scipy . ndimage . filters . correlate1d ( result , gaussian_kernel_1d , axis = 1 ) return result
0
python convolution with gaussian function
Convolve 2d gaussian .
cosqa-train-14927
def convolve_gaussian_2d(image, gaussian_kernel_1d): """Convolve 2d gaussian.""" result = scipy.ndimage.filters.correlate1d( image, gaussian_kernel_1d, axis=0) result = scipy.ndimage.filters.correlate1d( result, gaussian_kernel_1d, axis=1) return result
def n_choose_k ( n , k ) : return int ( reduce ( MUL , ( Fraction ( n - i , i + 1 ) for i in range ( k ) ) , 1 ) )
1
calculate n choose k python
get the number of quartets as n - choose - k . This is used in equal splits to decide whether a split should be exhaustively sampled or randomly sampled . Edges near tips can be exhaustive while highly nested edges probably have too many quartets
cosqa-train-14928
def n_choose_k(n, k): """ get the number of quartets as n-choose-k. This is used in equal splits to decide whether a split should be exhaustively sampled or randomly sampled. Edges near tips can be exhaustive while highly nested edges probably have too many quartets """ return int(reduce(MUL, (Fraction(n-i, i+1) for i in range(k)), 1))
def __copy__ ( self ) : return self . __class__ . load ( self . dump ( ) , context = self . context )
1
python copy a self in method
A magic method to implement shallow copy behavior .
cosqa-train-14929
def __copy__(self): """A magic method to implement shallow copy behavior.""" return self.__class__.load(self.dump(), context=self.context)
def stddev ( values , meanval = None ) : #from AI: A Modern Appproach if meanval == None : meanval = mean ( values ) return math . sqrt ( sum ( [ ( x - meanval ) ** 2 for x in values ] ) / ( len ( values ) - 1 ) )
1
calculate standard deviation in python ignoring null
The standard deviation of a set of values . Pass in the mean if you already know it .
cosqa-train-14930
def stddev(values, meanval=None): #from AI: A Modern Appproach """The standard deviation of a set of values. Pass in the mean if you already know it.""" if meanval == None: meanval = mean(values) return math.sqrt( sum([(x - meanval)**2 for x in values]) / (len(values)-1) )
def normalize ( self , dt , is_dst = False ) : if dt . tzinfo is self : return dt if dt . tzinfo is None : raise ValueError ( 'Naive time - no tzinfo set' ) return dt . astimezone ( self )
1
python correcting incorrect timezone datetime
Correct the timezone information on the given datetime
cosqa-train-14931
def normalize(self, dt, is_dst=False): """Correct the timezone information on the given datetime""" if dt.tzinfo is self: return dt if dt.tzinfo is None: raise ValueError('Naive time - no tzinfo set') return dt.astimezone(self)
def stderr ( a ) : return np . nanstd ( a ) / np . sqrt ( sum ( np . isfinite ( a ) ) )
1
calculate standard deviation using python
Calculate the standard error of a .
cosqa-train-14932
def stderr(a): """ Calculate the standard error of a. """ return np.nanstd(a) / np.sqrt(sum(np.isfinite(a)))
def inverse ( self ) : invr = np . linalg . inv ( self . affine_matrix ) return SymmOp ( invr )
0
calculating transformation matrix affine python
Returns inverse of transformation .
cosqa-train-14933
def inverse(self): """ Returns inverse of transformation. """ invr = np.linalg.inv(self.affine_matrix) return SymmOp(invr)
def covariance ( self , pt0 , pt1 ) : x = np . array ( [ pt0 [ 0 ] , pt1 [ 0 ] ] ) y = np . array ( [ pt0 [ 1 ] , pt1 [ 1 ] ] ) names = [ "n1" , "n2" ] return self . covariance_matrix ( x , y , names = names ) . x [ 0 , 1 ]
0
python covariance of two arrays
get the covarince between two points implied by Vario2d
cosqa-train-14934
def covariance(self,pt0,pt1): """ get the covarince between two points implied by Vario2d Parameters ---------- pt0 : (iterable of len 2) first point x and y pt1 : (iterable of len 2) second point x and y Returns ------- cov : float covariance between pt0 and pt1 """ x = np.array([pt0[0],pt1[0]]) y = np.array([pt0[1],pt1[1]]) names = ["n1","n2"] return self.covariance_matrix(x,y,names=names).x[0,1]
def fail ( message = None , exit_status = None ) : print ( 'Error:' , message , file = sys . stderr ) sys . exit ( exit_status or 1 )
0
call function with exit in python3
Prints the specified message and exits the program with the specified exit status .
cosqa-train-14935
def fail(message=None, exit_status=None): """Prints the specified message and exits the program with the specified exit status. """ print('Error:', message, file=sys.stderr) sys.exit(exit_status or 1)
def build_parser ( ) : parser = argparse . ArgumentParser ( description = "The IOTile task supervisor" ) parser . add_argument ( '-c' , '--config' , help = "config json with options" ) parser . add_argument ( '-v' , '--verbose' , action = "count" , default = 0 , help = "Increase logging verbosity" ) return parser
0
python create a argparse
Build the script s argument parser .
cosqa-train-14936
def build_parser(): """Build the script's argument parser.""" parser = argparse.ArgumentParser(description="The IOTile task supervisor") parser.add_argument('-c', '--config', help="config json with options") parser.add_argument('-v', '--verbose', action="count", default=0, help="Increase logging verbosity") return parser
def extract_zip ( zip_path , target_folder ) : with zipfile . ZipFile ( zip_path ) as archive : archive . extractall ( target_folder )
1
can i access a zipped folder in python
Extract the content of the zip - file at zip_path into target_folder .
cosqa-train-14937
def extract_zip(zip_path, target_folder): """ Extract the content of the zip-file at `zip_path` into `target_folder`. """ with zipfile.ZipFile(zip_path) as archive: archive.extractall(target_folder)
def get_dt_list ( fn_list ) : dt_list = np . array ( [ fn_getdatetime ( fn ) for fn in fn_list ] ) return dt_list
1
python create a array of datetime
Get list of datetime objects extracted from a filename
cosqa-train-14938
def get_dt_list(fn_list): """Get list of datetime objects, extracted from a filename """ dt_list = np.array([fn_getdatetime(fn) for fn in fn_list]) return dt_list
def ExecuteRaw ( self , position , command ) : self . EnsureGdbPosition ( position [ 0 ] , None , None ) return gdb . execute ( command , to_string = True )
0
can i execute python expression in gdb command line
Send a command string to gdb .
cosqa-train-14939
def ExecuteRaw(self, position, command): """Send a command string to gdb.""" self.EnsureGdbPosition(position[0], None, None) return gdb.execute(command, to_string=True)
def subscribe_to_quorum_channel ( self ) : from dallinger . experiment_server . sockets import chat_backend self . log ( "Bot subscribing to quorum channel." ) chat_backend . subscribe ( self , "quorum" )
0
python create a discord bot tthat pings someone
In case the experiment enforces a quorum listen for notifications before creating Partipant objects .
cosqa-train-14940
def subscribe_to_quorum_channel(self): """In case the experiment enforces a quorum, listen for notifications before creating Partipant objects. """ from dallinger.experiment_server.sockets import chat_backend self.log("Bot subscribing to quorum channel.") chat_backend.subscribe(self, "quorum")
def print_latex ( o ) : if can_print_latex ( o ) : s = latex ( o , mode = 'plain' ) s = s . replace ( '\\dag' , '\\dagger' ) s = s . strip ( '$' ) return '$$%s$$' % s # Fallback to the string printer return None
0
can i put python in latex
A function to generate the latex representation of sympy expressions .
cosqa-train-14941
def print_latex(o): """A function to generate the latex representation of sympy expressions.""" if can_print_latex(o): s = latex(o, mode='plain') s = s.replace('\\dag','\\dagger') s = s.strip('$') return '$$%s$$' % s # Fallback to the string printer return None
def _string_hash ( s ) : h = 5381 for c in s : h = h * 33 + ord ( c ) return h
0
python create a hash from string
String hash ( djb2 ) with consistency between py2 / py3 and persistency between runs ( unlike hash ) .
cosqa-train-14942
def _string_hash(s): """String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).""" h = 5381 for c in s: h = h * 33 + ord(c) return h
def add_to_js ( self , name , var ) : frame = self . page ( ) . mainFrame ( ) frame . addToJavaScriptWindowObject ( name , var )
0
can i use python with javascript
Add an object to Javascript .
cosqa-train-14943
def add_to_js(self, name, var): """Add an object to Javascript.""" frame = self.page().mainFrame() frame.addToJavaScriptWindowObject(name, var)
def force_iterable ( f ) : def wrapper ( * args , * * kwargs ) : r = f ( * args , * * kwargs ) if hasattr ( r , '__iter__' ) : return r else : return [ r ] return wrapper
1
python create an iterable
Will make any functions return an iterable objects by wrapping its result in a list .
cosqa-train-14944
def force_iterable(f): """Will make any functions return an iterable objects by wrapping its result in a list.""" def wrapper(*args, **kwargs): r = f(*args, **kwargs) if hasattr(r, '__iter__'): return r else: return [r] return wrapper
def pause ( self ) : mixer . music . pause ( ) self . pause_time = self . get_time ( ) self . paused = True
1
can python play sounds
Pause the music
cosqa-train-14945
def pause(self): """Pause the music""" mixer.music.pause() self.pause_time = self.get_time() self.paused = True
def trans_from_matrix ( matrix ) : t = np . zeros ( ( 4 , 4 ) ) for i in range ( 4 ) : for j in range ( 4 ) : t [ i , j ] = matrix . GetElement ( i , j ) return t
1
python create array out of matrix
Convert a vtk matrix to a numpy . ndarray
cosqa-train-14946
def trans_from_matrix(matrix): """ Convert a vtk matrix to a numpy.ndarray """ t = np.zeros((4, 4)) for i in range(4): for j in range(4): t[i, j] = matrix.GetElement(i, j) return t
def get_mod_time ( self , path ) : conn = self . get_conn ( ) ftp_mdtm = conn . sendcmd ( 'MDTM ' + path ) time_val = ftp_mdtm [ 4 : ] # time_val optionally has microseconds try : return datetime . datetime . strptime ( time_val , "%Y%m%d%H%M%S.%f" ) except ValueError : return datetime . datetime . strptime ( time_val , '%Y%m%d%H%M%S' )
0
can retrieve command ftp python calculate transfertime
Returns a datetime object representing the last time the file was modified
cosqa-train-14947
def get_mod_time(self, path): """ Returns a datetime object representing the last time the file was modified :param path: remote file path :type path: string """ conn = self.get_conn() ftp_mdtm = conn.sendcmd('MDTM ' + path) time_val = ftp_mdtm[4:] # time_val optionally has microseconds try: return datetime.datetime.strptime(time_val, "%Y%m%d%H%M%S.%f") except ValueError: return datetime.datetime.strptime(time_val, '%Y%m%d%H%M%S')
def to_dataframe ( products ) : try : import pandas as pd except ImportError : raise ImportError ( "to_dataframe requires the optional dependency Pandas." ) return pd . DataFrame . from_dict ( products , orient = 'index' )
0
python create data frame from query results
Return the products from a query response as a Pandas DataFrame with the values in their appropriate Python types .
cosqa-train-14948
def to_dataframe(products): """Return the products from a query response as a Pandas DataFrame with the values in their appropriate Python types. """ try: import pandas as pd except ImportError: raise ImportError("to_dataframe requires the optional dependency Pandas.") return pd.DataFrame.from_dict(products, orient='index')
def restart_program ( ) : python = sys . executable os . execl ( python , python , * sys . argv )
0
can we auto restart a python program
DOES NOT WORK WELL WITH MOPIDY Hack from https : // www . daniweb . com / software - development / python / code / 260268 / restart - your - python - program to support updating the settings since mopidy is not able to do that yet Restarts the current program Note : this function does not return . Any cleanup action ( like saving data ) must be done before calling this function
cosqa-train-14949
def restart_program(): """ DOES NOT WORK WELL WITH MOPIDY Hack from https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program to support updating the settings, since mopidy is not able to do that yet Restarts the current program Note: this function does not return. Any cleanup action (like saving data) must be done before calling this function """ python = sys.executable os.execl(python, python, * sys.argv)
def get_enum_from_name ( self , enum_name ) : return next ( ( e for e in self . enums if e . name == enum_name ) , None )
1
python create enum by name
Return an enum from a name Args : enum_name ( str ) : name of the enum Returns : Enum
cosqa-train-14950
def get_enum_from_name(self, enum_name): """ Return an enum from a name Args: enum_name (str): name of the enum Returns: Enum """ return next((e for e in self.enums if e.name == enum_name), None)
def set_as_object ( self , value ) : self . clear ( ) map = MapConverter . to_map ( value ) self . append ( map )
0
can you add anything to a python map
Sets a new value to map element
cosqa-train-14951
def set_as_object(self, value): """ Sets a new value to map element :param value: a new element or map value. """ self.clear() map = MapConverter.to_map(value) self.append(map)
def construct_from_string ( cls , string ) : if string == cls . name : return cls ( ) raise TypeError ( "Cannot construct a '{}' from " "'{}'" . format ( cls , string ) )
1
python create instance from type intance
Construction from a string raise a TypeError if not possible
cosqa-train-14952
def construct_from_string(cls, string): """ Construction from a string, raise a TypeError if not possible """ if string == cls.name: return cls() raise TypeError("Cannot construct a '{}' from " "'{}'".format(cls, string))
def _update_font_style ( self , font_style ) : toggle_state = font_style & wx . FONTSTYLE_ITALIC == wx . FONTSTYLE_ITALIC self . ToggleTool ( wx . FONTFLAG_ITALIC , toggle_state )
0
can you change fonts in a python buttons
Updates font style widget
cosqa-train-14953
def _update_font_style(self, font_style): """Updates font style widget Parameters ---------- font_style: Integer \tButton down iif font_style == wx.FONTSTYLE_ITALIC """ toggle_state = font_style & wx.FONTSTYLE_ITALIC == wx.FONTSTYLE_ITALIC self.ToggleTool(wx.FONTFLAG_ITALIC, toggle_state)
def string_to_list ( string , sep = "," , filter_empty = False ) : return [ value . strip ( ) for value in string . split ( sep ) if ( not filter_empty or value ) ]
0
python create list from commas delimited string
Transforma una string con elementos separados por sep en una lista .
cosqa-train-14954
def string_to_list(string, sep=",", filter_empty=False): """Transforma una string con elementos separados por `sep` en una lista.""" return [value.strip() for value in string.split(sep) if (not filter_empty or value)]
def _histplot_op ( ax , data , * * kwargs ) : bins = get_bins ( data ) ax . hist ( data , bins = bins , align = "left" , density = True , * * kwargs ) return ax
0
can you use a numpy array as bins in a python histogram
Add a histogram for the data to the axes .
cosqa-train-14955
def _histplot_op(ax, data, **kwargs): """Add a histogram for the data to the axes.""" bins = get_bins(data) ax.hist(data, bins=bins, align="left", density=True, **kwargs) return ax
def _single_page_pdf ( page ) : pdf = Pdf . new ( ) pdf . pages . append ( page ) bio = BytesIO ( ) pdf . save ( bio ) bio . seek ( 0 ) return bio . read ( )
0
python create multipage pdf file
Construct a single page PDF from the provided page in memory
cosqa-train-14956
def _single_page_pdf(page): """Construct a single page PDF from the provided page in memory""" pdf = Pdf.new() pdf.pages.append(page) bio = BytesIO() pdf.save(bio) bio.seek(0) return bio.read()
def norm_vec ( vector ) : assert len ( vector ) == 3 v = np . array ( vector ) return v / np . sqrt ( np . sum ( v ** 2 ) )
0
can you vectorize in python
Normalize the length of a vector to one
cosqa-train-14957
def norm_vec(vector): """Normalize the length of a vector to one""" assert len(vector) == 3 v = np.array(vector) return v/np.sqrt(np.sum(v**2))
def from_json_str ( cls , json_str ) : return cls . from_json ( json . loads ( json_str , cls = JsonDecoder ) )
1
python create object instance from string
Convert json string representation into class instance .
cosqa-train-14958
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 start ( ) : global app bottle . run ( app , host = conf . WebHost , port = conf . WebPort , debug = conf . WebAutoReload , reloader = conf . WebAutoReload , quiet = conf . WebQuiet )
1
cant access python bottle
Starts the web server .
cosqa-train-14959
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 from_bytes ( cls , b ) : im = cls ( ) im . chunks = list ( parse_chunks ( b ) ) im . init ( ) return im
1
python create png from raw bytes
Create : class : PNG from raw bytes . : arg bytes b : The raw bytes of the PNG file . : rtype : : class : PNG
cosqa-train-14960
def from_bytes(cls, b): """Create :class:`PNG` from raw bytes. :arg bytes b: The raw bytes of the PNG file. :rtype: :class:`PNG` """ im = cls() im.chunks = list(parse_chunks(b)) im.init() return im
def start ( ) : global app bottle . run ( app , host = conf . WebHost , port = conf . WebPort , debug = conf . WebAutoReload , reloader = conf . WebAutoReload , quiet = conf . WebQuiet )
0
cant access python bottle server
Starts the web server .
cosqa-train-14961
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 construct_from_string ( cls , string ) : if string == cls . name : return cls ( ) raise TypeError ( "Cannot construct a '{}' from " "'{}'" . format ( cls , string ) )
1
python create type from string
Construction from a string raise a TypeError if not possible
cosqa-train-14962
def construct_from_string(cls, string): """ Construction from a string, raise a TypeError if not possible """ if string == cls.name: return cls() raise TypeError("Cannot construct a '{}' from " "'{}'".format(cls, string))
def safe_setattr ( obj , name , value ) : try : setattr ( obj , name , value ) return True except AttributeError : return False
0
cant set attribute python
Attempt to setattr but catch AttributeErrors .
cosqa-train-14963
def safe_setattr(obj, name, value): """Attempt to setattr but catch AttributeErrors.""" try: setattr(obj, name, value) return True except AttributeError: return False
def add_matplotlib_cmap ( cm , name = None ) : global cmaps cmap = matplotlib_to_ginga_cmap ( cm , name = name ) cmaps [ cmap . name ] = cmap
1
python creating your own colormap
Add a matplotlib colormap .
cosqa-train-14964
def add_matplotlib_cmap(cm, name=None): """Add a matplotlib colormap.""" global cmaps cmap = matplotlib_to_ginga_cmap(cm, name=name) cmaps[cmap.name] = cmap
def camel_to_ ( s ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , s ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
1
capital to highercase converter in python
Convert CamelCase to camel_case
cosqa-train-14965
def camel_to_(s): """ Convert CamelCase to camel_case """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def _tab ( content ) : response = _data_frame ( content ) . to_csv ( index = False , sep = '\t' ) return response
0
python csv to data frame tab delimeter
Helper funcation that converts text - based get response to tab separated values for additional manipulation .
cosqa-train-14966
def _tab(content): """ Helper funcation that converts text-based get response to tab separated values for additional manipulation. """ response = _data_frame(content).to_csv(index=False,sep='\t') return response
def decamelise ( text ) : s = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , text ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s ) . lower ( )
0
capitalize all caps python
Convert CamelCase to lower_and_underscore .
cosqa-train-14967
def decamelise(text): """Convert CamelCase to lower_and_underscore.""" s = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s).lower()
def cint32_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_int32 ) ) : return np . fromiter ( cptr , dtype = np . int32 , count = length ) else : raise RuntimeError ( 'Expected int pointer' )
0
python ctype array to int
Convert a ctypes int pointer array to a numpy array .
cosqa-train-14968
def cint32_array_to_numpy(cptr, length): """Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)): return np.fromiter(cptr, dtype=np.int32, count=length) else: raise RuntimeError('Expected int pointer')
def cartesian_product ( arrays , flat = True , copy = False ) : arrays = np . broadcast_arrays ( * np . ix_ ( * arrays ) ) if flat : return tuple ( arr . flatten ( ) if copy else arr . flat for arr in arrays ) return tuple ( arr . copy ( ) if copy else arr for arr in arrays )
1
cartesian product of lists in python
Efficient cartesian product of a list of 1D arrays returning the expanded array views for each dimensions . By default arrays are flattened which may be controlled with the flat flag . The array views can be turned into regular arrays with the copy flag .
cosqa-train-14969
def cartesian_product(arrays, flat=True, copy=False): """ Efficient cartesian product of a list of 1D arrays returning the expanded array views for each dimensions. By default arrays are flattened, which may be controlled with the flat flag. The array views can be turned into regular arrays with the copy flag. """ arrays = np.broadcast_arrays(*np.ix_(*arrays)) if flat: return tuple(arr.flatten() if copy else arr.flat for arr in arrays) return tuple(arr.copy() if copy else arr for arr in arrays)
def cfloat64_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_double ) ) : return np . fromiter ( cptr , dtype = np . float64 , count = length ) else : raise RuntimeError ( 'Expected double pointer' )
0
python ctypes array to list
Convert a ctypes double pointer array to a numpy array .
cosqa-train-14970
def cfloat64_array_to_numpy(cptr, length): """Convert a ctypes double pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_double)): return np.fromiter(cptr, dtype=np.float64, count=length) else: raise RuntimeError('Expected double pointer')
def to_snake_case ( name ) : s1 = FIRST_CAP_REGEX . sub ( r'\1_\2' , name ) return ALL_CAP_REGEX . sub ( r'\1_\2' , s1 ) . lower ( )
1
case insensitive response in python
Given a name in camelCase return in snake_case
cosqa-train-14971
def to_snake_case(name): """ Given a name in camelCase return in snake_case """ s1 = FIRST_CAP_REGEX.sub(r'\1_\2', name) return ALL_CAP_REGEX.sub(r'\1_\2', s1).lower()
def cleanup_lib ( self ) : if not self . using_openmp : #this if statement is necessary because shared libraries that use #OpenMP will core dump when unloaded, this is a well-known issue with OpenMP logging . debug ( 'unloading shared library' ) _ctypes . dlclose ( self . lib . _handle )
1
python ctypes delete dynamic memory
unload the previously loaded shared library
cosqa-train-14972
def cleanup_lib(self): """ unload the previously loaded shared library """ if not self.using_openmp: #this if statement is necessary because shared libraries that use #OpenMP will core dump when unloaded, this is a well-known issue with OpenMP logging.debug('unloading shared library') _ctypes.dlclose(self.lib._handle)
def _convert_to_array ( array_like , dtype ) : if isinstance ( array_like , bytes ) : return np . frombuffer ( array_like , dtype = dtype ) return np . asarray ( array_like , dtype = dtype )
0
cast array as double python
Convert Matrix attributes which are array - like or buffer to array .
cosqa-train-14973
def _convert_to_array(array_like, dtype): """ Convert Matrix attributes which are array-like or buffer to array. """ if isinstance(array_like, bytes): return np.frombuffer(array_like, dtype=dtype) return np.asarray(array_like, dtype=dtype)
def pointer ( self ) : return ctypes . cast ( ctypes . pointer ( ctypes . c_uint8 . from_buffer ( self . mapping , 0 ) ) , ctypes . c_void_p )
1
python ctypes pointer of pointer
Get a ctypes void pointer to the memory mapped region .
cosqa-train-14974
def pointer(self): """Get a ctypes void pointer to the memory mapped region. :type: ctypes.c_void_p """ return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)
def shape_list ( l , shape , dtype ) : return np . array ( l , dtype = dtype ) . reshape ( shape )
0
casting a list as an array python
Shape a list of lists into the appropriate shape and data type
cosqa-train-14975
def shape_list(l,shape,dtype): """ Shape a list of lists into the appropriate shape and data type """ return np.array(l, dtype=dtype).reshape(shape)
def pointer ( self ) : return ctypes . cast ( ctypes . pointer ( ctypes . c_uint8 . from_buffer ( self . mapping , 0 ) ) , ctypes . c_void_p )
1
python ctypes structure pointer to pointer(self)
Get a ctypes void pointer to the memory mapped region .
cosqa-train-14976
def pointer(self): """Get a ctypes void pointer to the memory mapped region. :type: ctypes.c_void_p """ return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)
def expect_comment_end ( self ) : match = self . _expect_match ( '#}' , COMMENT_END_PATTERN ) self . advance ( match . end ( ) )
1
catch the matched comment in regex in python
Expect a comment end and return the match object .
cosqa-train-14977
def expect_comment_end(self): """Expect a comment end and return the match object. """ match = self._expect_match('#}', COMMENT_END_PATTERN) self.advance(match.end())
def round_corner ( radius , fill ) : corner = Image . new ( 'L' , ( radius , radius ) , 0 ) # (0, 0, 0, 0)) draw = ImageDraw . Draw ( corner ) draw . pieslice ( ( 0 , 0 , radius * 2 , radius * 2 ) , 180 , 270 , fill = fill ) return corner
1
python cut a circle out of an image
Draw a round corner
cosqa-train-14978
def round_corner(radius, fill): """Draw a round corner""" corner = Image.new('L', (radius, radius), 0) # (0, 0, 0, 0)) draw = ImageDraw.Draw(corner) draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill) return corner
def struct2dict ( struct ) : return { x : getattr ( struct , x ) for x in dict ( struct . _fields_ ) . keys ( ) }
1
cffi c struct to python dictionary
convert a ctypes structure to a dictionary
cosqa-train-14979
def struct2dict(struct): """convert a ctypes structure to a dictionary""" return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}
def SetValue ( self , row , col , value ) : self . dataframe . iloc [ row , col ] = value
1
python data frame set value at iat
Set value in the pandas DataFrame
cosqa-train-14980
def SetValue(self, row, col, value): """ Set value in the pandas DataFrame """ self.dataframe.iloc[row, col] = value
def to_identifier ( s ) : if s . startswith ( 'GPS' ) : s = 'Gps' + s [ 3 : ] return '' . join ( [ i . capitalize ( ) for i in s . split ( '_' ) ] ) if '_' in s else s
0
change caps string to proper string + python
Convert snake_case to camel_case .
cosqa-train-14981
def to_identifier(s): """ Convert snake_case to camel_case. """ if s.startswith('GPS'): s = 'Gps' + s[3:] return ''.join([i.capitalize() for i in s.split('_')]) if '_' in s else s
def convert_time_string ( date_str ) : dt , _ , _ = date_str . partition ( "." ) dt = datetime . strptime ( dt , "%Y-%m-%dT%H:%M:%S" ) return dt
1
python date time string to date
Change a date string from the format 2018 - 08 - 15T23 : 55 : 17 into a datetime object
cosqa-train-14982
def convert_time_string(date_str): """ Change a date string from the format 2018-08-15T23:55:17 into a datetime object """ dt, _, _ = date_str.partition(".") dt = datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S") return dt
def strip_columns ( tab ) : for colname in tab . colnames : if tab [ colname ] . dtype . kind in [ 'S' , 'U' ] : tab [ colname ] = np . core . defchararray . strip ( tab [ colname ] )
0
change certain cols dtype in python
Strip whitespace from string columns .
cosqa-train-14983
def strip_columns(tab): """Strip whitespace from string columns.""" for colname in tab.colnames: if tab[colname].dtype.kind in ['S', 'U']: tab[colname] = np.core.defchararray.strip(tab[colname])
def AmericanDateToEpoch ( self , date_str ) : try : epoch = time . strptime ( date_str , "%m/%d/%Y" ) return int ( calendar . timegm ( epoch ) ) * 1000000 except ValueError : return 0
1
python date time string to epoch
Take a US format date and return epoch .
cosqa-train-14984
def AmericanDateToEpoch(self, date_str): """Take a US format date and return epoch.""" try: epoch = time.strptime(date_str, "%m/%d/%Y") return int(calendar.timegm(epoch)) * 1000000 except ValueError: return 0
def load_jsonf ( fpath , encoding ) : with codecs . open ( fpath , encoding = encoding ) as f : return json . load ( f )
0
change encoding of json file python
: param unicode fpath : : param unicode encoding : : rtype : dict | list
cosqa-train-14985
def load_jsonf(fpath, encoding): """ :param unicode fpath: :param unicode encoding: :rtype: dict | list """ with codecs.open(fpath, encoding=encoding) as f: return json.load(f)
def iso_to_datetime ( date ) : chunks = list ( map ( int , date . split ( 'T' ) [ 0 ] . split ( '-' ) ) ) return datetime . datetime ( chunks [ 0 ] , chunks [ 1 ] , chunks [ 2 ] )
0
python date to iso datetime
Convert ISO 8601 time format to datetime format
cosqa-train-14986
def iso_to_datetime(date): """ Convert ISO 8601 time format to datetime format This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g. ``datetime.datetime(2017,9,14,0,0)`` :param date: date in ISO 8601 format :type date: str :return: datetime instance :rtype: datetime """ chunks = list(map(int, date.split('T')[0].split('-'))) return datetime.datetime(chunks[0], chunks[1], chunks[2])
def __repr__ ( self ) : return str ( { 'name' : self . _name , 'watts' : self . _watts , 'type' : self . _output_type , 'id' : self . _integration_id } )
0
change from object to string in python
Returns a stringified representation of this object .
cosqa-train-14987
def __repr__(self): """Returns a stringified representation of this object.""" return str({'name': self._name, 'watts': self._watts, 'type': self._output_type, 'id': self._integration_id})
def weekly ( date = datetime . date . today ( ) ) : return date - datetime . timedelta ( days = date . weekday ( ) )
0
python datetime add weekdays
Weeks start are fixes at Monday for now .
cosqa-train-14988
def weekly(date=datetime.date.today()): """ Weeks start are fixes at Monday for now. """ return date - datetime.timedelta(days=date.weekday())
def classnameify ( s ) : return '' . join ( w if w in ACRONYMS else w . title ( ) for w in s . split ( '_' ) )
0
change letters from a name python
Makes a classname
cosqa-train-14989
def classnameify(s): """ Makes a classname """ return ''.join(w if w in ACRONYMS else w.title() for w in s.split('_'))
def now ( self ) : if self . use_utc : return datetime . datetime . utcnow ( ) else : return datetime . datetime . now ( )
0
python datetime datetime now utc
Return a : py : class : datetime . datetime instance representing the current time .
cosqa-train-14990
def now(self): """ Return a :py:class:`datetime.datetime` instance representing the current time. :rtype: :py:class:`datetime.datetime` """ if self.use_utc: return datetime.datetime.utcnow() else: return datetime.datetime.now()
def _idx_col2rowm ( d ) : if 0 == len ( d ) : return 1 if 1 == len ( d ) : return np . arange ( d [ 0 ] ) # order='F' indicates column-major ordering idx = np . array ( np . arange ( np . prod ( d ) ) ) . reshape ( d , order = 'F' ) . T return idx . flatten ( order = 'F' )
0
change order of columns with index python
Generate indexes to change from col - major to row - major ordering
cosqa-train-14991
def _idx_col2rowm(d): """Generate indexes to change from col-major to row-major ordering""" if 0 == len(d): return 1 if 1 == len(d): return np.arange(d[0]) # order='F' indicates column-major ordering idx = np.array(np.arange(np.prod(d))).reshape(d, order='F').T return idx.flatten(order='F')
def this_week ( ) : since = TODAY + delta ( weekday = MONDAY ( - 1 ) ) until = since + delta ( weeks = 1 ) return Date ( since ) , Date ( until )
0
python datetime get friday for this week
Return start and end date of the current week .
cosqa-train-14992
def this_week(): """ Return start and end date of the current week. """ since = TODAY + delta(weekday=MONDAY(-1)) until = since + delta(weeks=1) return Date(since), Date(until)
def setHSV ( self , pixel , hsv ) : color = conversions . hsv2rgb ( hsv ) self . _set_base ( pixel , color )
0
change pixel color in hsv format opencv python
Set single pixel to HSV tuple
cosqa-train-14993
def setHSV(self, pixel, hsv): """Set single pixel to HSV tuple""" color = conversions.hsv2rgb(hsv) self._set_base(pixel, color)
def parse_timestamp ( timestamp ) : dt = dateutil . parser . parse ( timestamp ) return dt . astimezone ( dateutil . tz . tzutc ( ) )
0
python datetime isotime to localtime
Parse ISO8601 timestamps given by github API .
cosqa-train-14994
def parse_timestamp(timestamp): """Parse ISO8601 timestamps given by github API.""" dt = dateutil.parser.parse(timestamp) return dt.astimezone(dateutil.tz.tzutc())
def tick ( self ) : self . current += 1 if self . current == self . factor : sys . stdout . write ( '+' ) sys . stdout . flush ( ) self . current = 0
0
change progressbar color python
Add one tick to progress bar
cosqa-train-14995
def tick(self): """Add one tick to progress bar""" self.current += 1 if self.current == self.factor: sys.stdout.write('+') sys.stdout.flush() self.current = 0
def datetime_to_timezone ( date , tz = "UTC" ) : if not date . tzinfo : date = date . replace ( tzinfo = timezone ( get_timezone ( ) ) ) return date . astimezone ( timezone ( tz ) )
1
python datetime make timezone aware
convert naive datetime to timezone - aware datetime
cosqa-train-14996
def datetime_to_timezone(date, tz="UTC"): """ convert naive datetime to timezone-aware datetime """ if not date.tzinfo: date = date.replace(tzinfo=timezone(get_timezone())) return date.astimezone(timezone(tz))
def input ( self , prompt , default = None , show_default = True ) : return click . prompt ( prompt , default = default , show_default = show_default )
0
change prompt in python shell
Provide a command prompt .
cosqa-train-14997
def input(self, prompt, default=None, show_default=True): """Provide a command prompt.""" return click.prompt(prompt, default=default, show_default=show_default)
def get_naive ( dt ) : if not dt . tzinfo : return dt if hasattr ( dt , "asdatetime" ) : return dt . asdatetime ( ) return dt . replace ( tzinfo = None )
0
python datetime naive object
Gets a naive datetime from a datetime .
cosqa-train-14998
def get_naive(dt): """Gets a naive datetime from a datetime. datetime_tz objects can't just have tzinfo replaced with None, you need to call asdatetime. Args: dt: datetime object. Returns: datetime object without any timezone information. """ if not dt.tzinfo: return dt if hasattr(dt, "asdatetime"): return dt.asdatetime() return dt.replace(tzinfo=None)
def parse_timestamp ( timestamp ) : dt = dateutil . parser . parse ( timestamp ) return dt . astimezone ( dateutil . tz . tzutc ( ) )
1
python datetime parsing format timezone
Parse ISO8601 timestamps given by github API .
cosqa-train-14999
def parse_timestamp(timestamp): """Parse ISO8601 timestamps given by github API.""" dt = dateutil.parser.parse(timestamp) return dt.astimezone(dateutil.tz.tzutc())