Datasets:

Modalities:
Text
Formats:
json
ArXiv:
Libraries:
Datasets
pandas
License:
code
stringlengths
87
6.4k
docstring_tokens
stringlengths
0
1.41k
label
int64
0
1
code_tokens
stringlengths
60
3.94k
doc
stringlengths
16
98
idx
stringlengths
13
17
def writeBoolean(self, n): """ Writes a Boolean to the stream. """ t = TYPE_BOOL_TRUE if n is False: t = TYPE_BOOL_FALSE self.stream.write(t)
Writes a Boolean to the stream .
0
def writeBoolean ( self , n ) : t = TYPE_BOOL_TRUE if n is False : t = TYPE_BOOL_FALSE self . stream . write ( t )
python code to write bool value 1
cosqa-train-0
def paste(xsel=False): """Returns system clipboard contents.""" selection = "primary" if xsel else "clipboard" try: return subprocess.Popen(["xclip", "-selection", selection, "-o"], stdout=subprocess.PIPE).communicate()[0].decode("utf-8") except OSError as why: raise XclipNotFound
Returns system clipboard contents .
0
def paste ( xsel = False ) : selection = "primary" if xsel else "clipboard" try : return subprocess . Popen ( [ "xclip" , "-selection" , selection , "-o" ] , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ] . decode ( "utf-8" ) except OSError as why : raise XclipNotFound
"python how to manipulate clipboard"
cosqa-train-1
def _format_json(data, theme): """Pretty print a dict as a JSON, with colors if pygments is present.""" output = json.dumps(data, indent=2, sort_keys=True) if pygments and sys.stdout.isatty(): style = get_style_by_name(theme) formatter = Terminal256Formatter(style=style) return pygments.highlight(output, JsonLexer(), formatter) return output
Pretty print a dict as a JSON with colors if pygments is present .
0
def _format_json ( data , theme ) : output = json . dumps ( data , indent = 2 , sort_keys = True ) if pygments and sys . stdout . isatty ( ) : style = get_style_by_name ( theme ) formatter = Terminal256Formatter ( style = style ) return pygments . highlight ( output , JsonLexer ( ) , formatter ) return output
python colored output to html
cosqa-train-2
def create_path(path): """Creates a absolute path in the file system. :param path: The path to be created """ import os if not os.path.exists(path): os.makedirs(path)
Creates a absolute path in the file system .
0
def create_path ( path ) : import os if not os . path . exists ( path ) : os . makedirs ( path )
python "create directory" using "relative path"
cosqa-train-3
def _vector_or_scalar(x, type='row'): """Convert an object to either a scalar or a row or column vector.""" if isinstance(x, (list, tuple)): x = np.array(x) if isinstance(x, np.ndarray): assert x.ndim == 1 if type == 'column': x = x[:, None] return x
Convert an object to either a scalar or a row or column vector .
0
def _vector_or_scalar ( x , type = 'row' ) : if isinstance ( x , ( list , tuple ) ) : x = np . array ( x ) if isinstance ( x , np . ndarray ) : assert x . ndim == 1 if type == 'column' : x = x [ : , None ] return x
python column of an array
cosqa-train-4
def experiment_property(prop): """Get a property of the experiment by name.""" exp = experiment(session) p = getattr(exp, prop) return success_response(field=prop, data=p, request_type=prop)
Get a property of the experiment by name .
0
def experiment_property ( prop ) : exp = experiment ( session ) p = getattr ( exp , prop ) return success_response ( field = prop , data = p , request_type = prop )
python calling a property returns "property object"
cosqa-train-5
def data_from_file(file): """Return (first channel data, sample frequency, sample width) from a .wav file.""" fp = wave.open(file, 'r') data = fp.readframes(fp.getnframes()) channels = fp.getnchannels() freq = fp.getframerate() bits = fp.getsampwidth() # Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32 # bit not supported. data = struct.unpack(('%sh' % fp.getnframes()) * channels, data) # Only use first channel channel1 = [] n = 0 for d in data: if n % channels == 0: channel1.append(d) n += 1 fp.close() return (channel1, freq, bits)
Return ( first channel data sample frequency sample width ) from a . wav file .
0
def data_from_file ( file ) : fp = wave . open ( file , 'r' ) data = fp . readframes ( fp . getnframes ( ) ) channels = fp . getnchannels ( ) freq = fp . getframerate ( ) bits = fp . getsampwidth ( ) # Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32 # bit not supported. data = struct . unpack ( ( '%sh' % fp . getnframes ( ) ) * channels , data ) # Only use first channel channel1 = [ ] n = 0 for d in data : if n % channels == 0 : channel1 . append ( d ) n += 1 fp . close ( ) return ( channel1 , freq , bits )
python combine wav file into one as separate channels
cosqa-train-6
def source_range(start, end, nr_var_dict): """ Given a range of source numbers, as well as a dictionary containing the numbers of each source, returns a dictionary containing tuples of the start and end index for each source variable type. """ return OrderedDict((k, e-s) for k, (s, e) in source_range_tuple(start, end, nr_var_dict).iteritems())
Given a range of source numbers as well as a dictionary containing the numbers of each source returns a dictionary containing tuples of the start and end index for each source variable type .
0
def source_range ( start , end , nr_var_dict ) : return OrderedDict ( ( k , e - s ) for k , ( s , e ) in source_range_tuple ( start , end , nr_var_dict ) . iteritems ( ) )
+how to use range with a dictionary python
cosqa-train-7
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
Return time in milliseconds from start_time
0
def timespan ( start_time ) : timespan = datetime . datetime . now ( ) - start_time timespan_ms = timespan . total_seconds ( ) * 1000 return timespan_ms
python compare timespan to number
cosqa-train-8
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)
Convert Matrix attributes which are array - like or buffer to array .
1
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 )
1d array in char datatype in python
cosqa-train-9
def get_uniques(l): """ Returns a list with no repeated elements. """ result = [] for i in l: if i not in result: result.append(i) return result
Returns a list with no repeated elements .
0
def get_uniques ( l ) : result = [ ] for i in l : if i not in result : result . append ( i ) return result
python comprehension list distinct
cosqa-train-10
def interp(x, xp, *args, **kwargs): """Wrap interpolate_1d for deprecated interp.""" return interpolate_1d(x, xp, *args, **kwargs)
Wrap interpolate_1d for deprecated interp .
0
def interp ( x , xp , * args , * * kwargs ) : return interpolate_1d ( x , xp , * args , * * kwargs )
1d interpolation function python example
cosqa-train-11
def _array2cstr(arr): """ Serializes a numpy array to a compressed base64 string """ out = StringIO() np.save(out, arr) return b64encode(out.getvalue())
Serializes a numpy array to a compressed base64 string
0
def _array2cstr ( arr ) : out = StringIO ( ) np . save ( out , arr ) return b64encode ( out . getvalue ( ) )
python compress array to string
cosqa-train-12
def percentile(values, k): """Find the percentile of a list of values. :param list values: The list of values to find the percentile of :param int k: The percentile to find :rtype: float or int """ if not values: return None values.sort() index = (len(values) * (float(k) / 100)) - 1 return values[int(math.ceil(index))]
Find the percentile of a list of values .
0
def percentile ( values , k ) : if not values : return None values . sort ( ) index = ( len ( values ) * ( float ( k ) / 100 ) ) - 1 return values [ int ( math . ceil ( index ) ) ]
25 and 75 percentile of a list python
cosqa-train-13
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
String hash ( djb2 ) with consistency between py2 / py3 and persistency between runs ( unlike hash ) .
0
def _string_hash ( s ) : h = 5381 for c in s : h = h * 33 + ord ( c ) return h
python compute hash of string
cosqa-train-14
def transform_from_rot_trans(R, t): """Transforation matrix from rotation matrix and translation vector.""" R = R.reshape(3, 3) t = t.reshape(3, 1) return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))
Transforation matrix from rotation matrix and translation vector .
0
def transform_from_rot_trans ( R , t ) : R = R . reshape ( 3 , 3 ) t = t . reshape ( 3 , 1 ) return np . vstack ( ( np . hstack ( [ R , t ] ) , [ 0 , 0 , 0 , 1 ] ) )
3d rotatioin matrix in python
cosqa-train-15
def _encode_bool(name, value, dummy0, dummy1): """Encode a python boolean (True/False).""" return b"\x08" + name + (value and b"\x01" or b"\x00")
Encode a python boolean ( True / False ) .
0
def _encode_bool ( name , value , dummy0 , dummy1 ) : return b"\x08" + name + ( value and b"\x01" or b"\x00" )
python concatenate bool to string
cosqa-train-16
def transform_to_3d(points,normal,z=0): """Project points into 3d from 2d points.""" d = np.cross(normal, (0, 0, 1)) M = rotation_matrix(d) transformed_points = M.dot(points.T).T + z return transformed_points
Project points into 3d from 2d points .
0
def transform_to_3d ( points , normal , z = 0 ) : d = np . cross ( normal , ( 0 , 0 , 1 ) ) M = rotation_matrix ( d ) transformed_points = M . dot ( points . T ) . T + z return transformed_points
3d rotation in python around z axis
cosqa-train-17
def _not(condition=None, **kwargs): """ Return the opposite of input condition. :param condition: condition to process. :result: not condition. :rtype: bool """ result = True if condition is not None: result = not run(condition, **kwargs) return result
Return the opposite of input condition .
1
def _not ( condition = None , * * kwargs ) : result = True if condition is not None : result = not run ( condition , * * kwargs ) return result
python condition non none
cosqa-train-18
def HttpResponse403(request, template=KEY_AUTH_403_TEMPLATE, content=KEY_AUTH_403_CONTENT, content_type=KEY_AUTH_403_CONTENT_TYPE): """ HTTP response for forbidden access (status code 403) """ return AccessFailedResponse(request, template, content, content_type, status=403)
HTTP response for forbidden access ( status code 403 )
0
def HttpResponse403 ( request , template = KEY_AUTH_403_TEMPLATE , content = KEY_AUTH_403_CONTENT , content_type = KEY_AUTH_403_CONTENT_TYPE ) : return AccessFailedResponse ( request , template , content , content_type , status = 403 )
403 code from request python
cosqa-train-19
def items(self, section_name): """:return: list((option, value), ...) pairs of all items in the given section""" return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']
: return : list (( option value ) ... ) pairs of all items in the given section
0
def items ( self , section_name ) : return [ ( k , v ) for k , v in super ( GitConfigParser , self ) . items ( section_name ) if k != '__name__' ]
python configparser get keys in section
cosqa-train-20
def mag(z): """Get the magnitude of a vector.""" if isinstance(z[0], np.ndarray): return np.array(list(map(np.linalg.norm, z))) else: return np.linalg.norm(z)
Get the magnitude of a vector .
0
def mag ( z ) : if isinstance ( z [ 0 ] , np . ndarray ) : return np . array ( list ( map ( np . linalg . norm , z ) ) ) else : return np . linalg . norm ( z )
a array of vector, compute the norm of each vector python
cosqa-train-21
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
Convert a ConfigParser to a dictionary .
0
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
python configparser transfer dict
cosqa-train-22
def __add__(self, other): """Handle the `+` operator.""" return self._handle_type(other)(self.value + other.value)
Handle the + operator .
0
def __add__ ( self , other ) : return self . _handle_type ( other ) ( self . value + other . value )
a+b in python addition code
cosqa-train-23
def connect_mysql(host, port, user, password, database): """Connect to MySQL with retries.""" return pymysql.connect( host=host, port=port, user=user, passwd=password, db=database )
Connect to MySQL with retries .
0
def connect_mysql ( host , port , user , password , database ) : return pymysql . connect ( host = host , port = port , user = user , passwd = password , db = database )
python connect mysql denied password
cosqa-train-24
def get_column(self, X, column): """Return a column of the given matrix. Args: X: `numpy.ndarray` or `pandas.DataFrame`. column: `int` or `str`. Returns: np.ndarray: Selected column. """ if isinstance(X, pd.DataFrame): return X[column].values return X[:, column]
Return a column of the given matrix .
1
def get_column ( self , X , column ) : if isinstance ( X , pd . DataFrame ) : return X [ column ] . values return X [ : , column ]
accessing a column from a matrix in python
cosqa-train-25
def connect(url, username, password): """ Return a connected Bitbucket session """ bb_session = stashy.connect(url, username, password) logger.info('Connected to: %s as %s', url, username) return bb_session
Return a connected Bitbucket session
0
def connect ( url , username , password ) : bb_session = stashy . connect ( url , username , password ) logger . info ( 'Connected to: %s as %s' , url , username ) return bb_session
python connecting to an api with username and password
cosqa-train-26
def add_blank_row(self, label): """ Add a blank row with only an index value to self.df. This is done inplace. """ col_labels = self.df.columns blank_item = pd.Series({}, index=col_labels, name=label) # use .loc to add in place (append won't do that) self.df.loc[blank_item.name] = blank_item return self.df
Add a blank row with only an index value to self . df . This is done inplace .
0
def add_blank_row ( self , label ) : col_labels = self . df . columns blank_item = pd . Series ( { } , index = col_labels , name = label ) # use .loc to add in place (append won't do that) self . df . loc [ blank_item . name ] = blank_item return self . df
add empty series to data frame python
cosqa-train-27
def teardown(self): """ Stop and remove the container if it exists. """ while self._http_clients: self._http_clients.pop().close() if self.created: self.halt()
Stop and remove the container if it exists .
0
def teardown ( self ) : while self . _http_clients : self . _http_clients . pop ( ) . close ( ) if self . created : self . halt ( )
python container pod stuck in terminating
cosqa-train-28
def dumped(text, level, indent=2): """Put curly brackets round an indented text""" return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n"
Put curly brackets round an indented text
0
def dumped ( text , level , indent = 2 ) : return indented ( "{\n%s\n}" % indented ( text , level + 1 , indent ) or "None" , level , indent ) + "\n"
add indentations to code in python
cosqa-train-29
def context(self): """ Create a context manager that ensures code runs within action's context. The action does NOT finish when the context is exited. """ parent = _ACTION_CONTEXT.set(self) try: yield self finally: _ACTION_CONTEXT.reset(parent)
Create a context manager that ensures code runs within action s context .
0
def context ( self ) : parent = _ACTION_CONTEXT . set ( self ) try : yield self finally : _ACTION_CONTEXT . reset ( parent )
python context manager exit
cosqa-train-30
def pformat(object, indent=1, width=80, depth=None): """Format a Python object into a pretty-printed representation.""" return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
Format a Python object into a pretty - printed representation .
0
def pformat ( object , indent = 1 , width = 80 , depth = None ) : return PrettyPrinter ( indent = indent , width = width , depth = depth ) . pformat ( object )
add print depth inpython
cosqa-train-31
def replace_sys_args(new_args): """Temporarily replace sys.argv with current arguments Restores sys.argv upon exit of the context manager. """ # Replace sys.argv arguments # for module import old_args = sys.argv sys.argv = new_args try: yield finally: sys.argv = old_args
Temporarily replace sys . argv with current arguments
0
def replace_sys_args ( new_args ) : # Replace sys.argv arguments # for module import old_args = sys . argv sys . argv = new_args try : yield finally : sys . argv = old_args
python contextmanager temperarily set env
cosqa-train-32
def serialize(obj): """Takes a object and produces a dict-like representation :param obj: the object to serialize """ if isinstance(obj, list): return [serialize(o) for o in obj] return GenericSerializer(ModelProviderImpl()).serialize(obj)
Takes a object and produces a dict - like representation
0
def serialize ( obj ) : if isinstance ( obj , list ) : return [ serialize ( o ) for o in obj ] return GenericSerializer ( ModelProviderImpl ( ) ) . serialize ( obj )
add serializer for type python
cosqa-train-33
def advance_one_line(self): """Advances to next line.""" current_line = self._current_token.line_number while current_line == self._current_token.line_number: self._current_token = ConfigParser.Token(*next(self._token_generator))
Advances to next line .
0
def advance_one_line ( self ) : current_line = self . _current_token . line_number while current_line == self . _current_token . line_number : self . _current_token = ConfigParser . Token ( * next ( self . _token_generator ) )
python continuation on next line
cosqa-train-34
def generate_swagger_html(swagger_static_root, swagger_json_url): """ given a root directory for the swagger statics, and a swagger json path, return back a swagger html designed to use those values. """ tmpl = _get_template("swagger.html") return tmpl.render( swagger_root=swagger_static_root, swagger_json_url=swagger_json_url )
given a root directory for the swagger statics and a swagger json path return back a swagger html designed to use those values .
0
def generate_swagger_html ( swagger_static_root , swagger_json_url ) : tmpl = _get_template ( "swagger.html" ) return tmpl . render ( swagger_root = swagger_static_root , swagger_json_url = swagger_json_url )
add swagger to python django
cosqa-train-35
def do_next(self, args): """Step over the next statement """ self._do_print_from_last_cmd = True self._interp.step_over() return True
Step over the next statement
0
def do_next ( self , args ) : self . _do_print_from_last_cmd = True self . _interp . step_over ( ) return True
python continue executing the next command
cosqa-train-36
def __add__(self,other): """ If the number of columns matches, we can concatenate two LabeldMatrices with the + operator. """ assert self.matrix.shape[1] == other.matrix.shape[1] return LabeledMatrix(np.concatenate([self.matrix,other.matrix],axis=0),self.labels)
If the number of columns matches we can concatenate two LabeldMatrices with the + operator .
0
def __add__ ( self , other ) : assert self . matrix . shape [ 1 ] == other . matrix . shape [ 1 ] return LabeledMatrix ( np . concatenate ( [ self . matrix , other . matrix ] , axis = 0 ) , self . labels )
add two matrix with same shape expect one dim python
cosqa-train-37
def get_line_flux(line_wave, wave, flux, **kwargs): """Interpolated flux at a given wavelength (calls np.interp).""" return np.interp(line_wave, wave, flux, **kwargs)
Interpolated flux at a given wavelength ( calls np . interp ) .
0
def get_line_flux ( line_wave , wave , flux , * * kwargs ) : return np . interp ( line_wave , wave , flux , * * kwargs )
python contourf interpolation method
cosqa-train-38
def send(message, request_context=None, binary=False): """Sends a message to websocket. :param str message: data to send :param request_context: :raises IOError: If unable to send a message. """ if binary: return uwsgi.websocket_send_binary(message, request_context) return uwsgi.websocket_send(message, request_context)
Sends a message to websocket .
0
def send ( message , request_context = None , binary = False ) : if binary : return uwsgi . websocket_send_binary ( message , request_context ) return uwsgi . websocket_send ( message , request_context )
add websocket support to python
cosqa-train-39
def get_number(s, cast=int): """ Try to get a number out of a string, and cast it. """ import string d = "".join(x for x in str(s) if x in string.digits) return cast(d)
Try to get a number out of a string and cast it .
0
def get_number ( s , cast = int ) : import string d = "" . join ( x for x in str ( s ) if x in string . digits ) return cast ( d )
python conver string to number
cosqa-train-40
def get_hline(): """ gets a horiztonal line """ return Window( width=LayoutDimension.exact(1), height=LayoutDimension.exact(1), content=FillControl('-', token=Token.Line))
gets a horiztonal line
0
def get_hline ( ) : return Window ( width = LayoutDimension . exact ( 1 ) , height = LayoutDimension . exact ( 1 ) , content = FillControl ( '-' , token = Token . Line ) )
adding a horxontal line python
cosqa-train-41
def parse_cookies_str(cookies): """ parse cookies str to dict :param cookies: cookies str :type cookies: str :return: cookie dict :rtype: dict """ cookie_dict = {} for record in cookies.split(";"): key, value = record.strip().split("=", 1) cookie_dict[key] = value return cookie_dict
parse cookies str to dict : param cookies : cookies str : type cookies : str : return : cookie dict : rtype : dict
0
def parse_cookies_str ( cookies ) : cookie_dict = { } for record in cookies . split ( ";" ) : key , value = record . strip ( ) . split ( "=" , 1 ) cookie_dict [ key ] = value return cookie_dict
python cookies change to dict
cosqa-train-42
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()
Given a name in camelCase return in snake_case
0
def to_snake_case ( name ) : s1 = FIRST_CAP_REGEX . sub ( r'\1_\2' , name ) return ALL_CAP_REGEX . sub ( r'\1_\2' , s1 ) . lower ( )
alternate uppercase and lower case in python
cosqa-train-43
def populate_obj(obj, attrs): """Populates an object's attributes using the provided dict """ for k, v in attrs.iteritems(): setattr(obj, k, v)
Populates an object s attributes using the provided dict
0
def populate_obj ( obj , attrs ) : for k , v in attrs . iteritems ( ) : setattr ( obj , k , v )
python copy a dict to object attributes
cosqa-train-44
def wordfreq(text, is_filename=False): """Return a dictionary of words and word counts in a string.""" if is_filename: with open(text) as f: text = f.read() freqs = {} for word in text.split(): lword = word.lower() freqs[lword] = freqs.get(lword, 0) + 1 return freqs
Return a dictionary of words and word counts in a string .
0
def wordfreq ( text , is_filename = False ) : if is_filename : with open ( text ) as f : text = f . read ( ) freqs = { } for word in text . split ( ) : lword = word . lower ( ) freqs [ lword ] = freqs . get ( lword , 0 ) + 1 return freqs
analyze the frequency of a word using python
cosqa-train-45
def copyFile(input, output, replace=None): """Copy a file whole from input to output.""" _found = findFile(output) if not _found or (_found and replace): shutil.copy2(input, output)
Copy a file whole from input to output .
0
def copyFile ( input , output , replace = None ) : _found = findFile ( output ) if not _found or ( _found and replace ) : shutil . copy2 ( input , output )
python copy files effeciently
cosqa-train-46
def push(h, x): """Push a new value into heap.""" h.push(x) up(h, h.size()-1)
Push a new value into heap .
0
def push ( h , x ) : h . push ( x ) up ( h , h . size ( ) - 1 )
append last element of the stack in pythong
cosqa-train-47
def yank(event): """ Paste before cursor. """ event.current_buffer.paste_clipboard_data( event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)
Paste before cursor .
0
def yank ( event ) : event . current_buffer . paste_clipboard_data ( event . cli . clipboard . get_data ( ) , count = event . arg , paste_mode = PasteMode . EMACS )
python copy paste clipboard drop
cosqa-train-48
def filter_contour(imageFile, opFile): """ convert an image by applying a contour """ im = Image.open(imageFile) im1 = im.filter(ImageFilter.CONTOUR) im1.save(opFile)
convert an image by applying a contour
0
def filter_contour ( imageFile , opFile ) : im = Image . open ( imageFile ) im1 = im . filter ( ImageFilter . CONTOUR ) im1 . save ( opFile )
apply a filter to an image python
cosqa-train-49
def count(lines): """ Counts the word frequences in a list of sentences. Note: This is a helper function for parallel execution of `Vocabulary.from_text` method. """ words = [w for l in lines for w in l.strip().split()] return Counter(words)
Counts the word frequences in a list of sentences .
0
def count ( lines ) : words = [ w for l in lines for w in l . strip ( ) . split ( ) ] return Counter ( words )
python count number of words in each sentence
cosqa-train-50
def dictapply(d, fn): """ apply a function to all non-dict values in a dictionary """ for k, v in d.items(): if isinstance(v, dict): v = dictapply(v, fn) else: d[k] = fn(v) return d
apply a function to all non - dict values in a dictionary
0
def dictapply ( d , fn ) : for k , v in d . items ( ) : if isinstance ( v , dict ) : v = dictapply ( v , fn ) else : d [ k ] = fn ( v ) return d
apply a function to dictionary python
cosqa-train-51
def count_replica(self, partition): """Return count of replicas of given partition.""" return sum(1 for b in partition.replicas if b in self.brokers)
Return count of replicas of given partition .
0
def count_replica ( self , partition ) : return sum ( 1 for b in partition . replicas if b in self . brokers )
python count partitions of a number
cosqa-train-52
def visit_Name(self, node): """ Get range for parameters for examples or false branching. """ return self.add(node, self.result[node.id])
Get range for parameters for examples or false branching .
0
def visit_Name ( self , node ) : return self . add ( node , self . result [ node . id ] )
apply range to method python
cosqa-train-53
def mkdir(dir, enter): """Create directory with template for topic of the current environment """ if not os.path.exists(dir): os.makedirs(dir)
Create directory with template for topic of the current environment
0
def mkdir ( dir , enter ) : if not os . path . exists ( dir ) : os . makedirs ( dir )
python creat a dir
cosqa-train-54
def qrot(vector, quaternion): """Rotate a 3D vector using quaternion algebra. Implemented by Vladimir Kulikovskiy. Parameters ---------- vector: np.array quaternion: np.array Returns ------- np.array """ t = 2 * np.cross(quaternion[1:], vector) v_rot = vector + quaternion[0] * t + np.cross(quaternion[1:], t) return v_rot
Rotate a 3D vector using quaternion algebra .
0
def qrot ( vector , quaternion ) : t = 2 * np . cross ( quaternion [ 1 : ] , vector ) v_rot = vector + quaternion [ 0 ] * t + np . cross ( quaternion [ 1 : ] , t ) return v_rot
apply rotation on vector along a axis python
cosqa-train-55
def _numpy_char_to_bytes(arr): """Like netCDF4.chartostring, but faster and more flexible. """ # based on: http://stackoverflow.com/a/10984878/809705 arr = np.array(arr, copy=False, order='C') dtype = 'S' + str(arr.shape[-1]) return arr.view(dtype).reshape(arr.shape[:-1])
Like netCDF4 . chartostring but faster and more flexible .
0
def _numpy_char_to_bytes ( arr ) : # based on: http://stackoverflow.com/a/10984878/809705 arr = np . array ( arr , copy = False , order = 'C' ) dtype = 'S' + str ( arr . shape [ - 1 ] ) return arr . view ( dtype ) . reshape ( arr . shape [ : - 1 ] )
python create a numpy of chars
cosqa-train-56
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
String hash ( djb2 ) with consistency between py2 / py3 and persistency between runs ( unlike hash ) .
1
def _string_hash ( s ) : h = 5381 for c in s : h = h * 33 + ord ( c ) return h
are python strings hashable
cosqa-train-57
def csv_to_dicts(file, header=None): """Reads a csv and returns a List of Dicts with keys given by header row.""" with open(file) as csvfile: return [row for row in csv.DictReader(csvfile, fieldnames=header)]
Reads a csv and returns a List of Dicts with keys given by header row .
0
def csv_to_dicts ( file , header = None ) : with open ( file ) as csvfile : return [ row for row in csv . DictReader ( csvfile , fieldnames = header ) ]
python create list of dictionary from csv file no key
cosqa-train-58
def get_tri_area(pts): """ Given a list of coords for 3 points, Compute the area of this triangle. Args: pts: [a, b, c] three points """ a, b, c = pts[0], pts[1], pts[2] v1 = np.array(b) - np.array(a) v2 = np.array(c) - np.array(a) area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2) return area_tri
Given a list of coords for 3 points Compute the area of this triangle .
0
def get_tri_area ( pts ) : a , b , c = pts [ 0 ] , pts [ 1 ] , pts [ 2 ] v1 = np . array ( b ) - np . array ( a ) v2 = np . array ( c ) - np . array ( a ) area_tri = abs ( sp . linalg . norm ( sp . cross ( v1 , v2 ) ) / 2 ) return area_tri
area of a triangle python function
cosqa-train-59
def one_hot(x, size, dtype=np.float32): """Make a n+1 dim one-hot array from n dim int-categorical array.""" return np.array(x[..., np.newaxis] == np.arange(size), dtype)
Make a n + 1 dim one - hot array from n dim int - categorical array .
0
def one_hot ( x , size , dtype = np . float32 ) : return np . array ( x [ ... , np . newaxis ] == np . arange ( size ) , dtype )
python create numpy onehot
cosqa-train-60
def round_to_int(number, precision): """Round a number to a precision""" precision = int(precision) rounded = (int(number) + precision / 2) // precision * precision return rounded
Round a number to a precision
0
def round_to_int ( number , precision ) : precision = int ( precision ) rounded = ( int ( number ) + precision / 2 ) // precision * precision return rounded
around to precision python
cosqa-train-61
def to_unicode_repr( _letter ): """ helpful in situations where browser/app may recognize Unicode encoding in the \u0b8e type syntax but not actual unicode glyph/code-point""" # Python 2-3 compatible return u"u'"+ u"".join( [ u"\\u%04x"%ord(l) for l in _letter ] ) + u"'"
helpful in situations where browser / app may recognize Unicode encoding in the \ u0b8e type syntax but not actual unicode glyph / code - point
0
def to_unicode_repr ( _letter ) : # Python 2-3 compatible return u"u'" + u"" . join ( [ u"\\u%04x" % ord ( l ) for l in _letter ] ) + u"'"
ascii character representation in python 3
cosqa-train-62
def create_path(path): """Creates a absolute path in the file system. :param path: The path to be created """ import os if not os.path.exists(path): os.makedirs(path)
Creates a absolute path in the file system .
0
def create_path ( path ) : import os if not os . path . exists ( path ) : os . makedirs ( path )
python create path pathlib create directory
cosqa-train-63
def string_input(prompt=''): """Python 3 input()/Python 2 raw_input()""" v = sys.version[0] if v == '3': return input(prompt) else: return raw_input(prompt)
Python 3 input () / Python 2 raw_input ()
0
def string_input ( prompt = '' ) : v = sys . version [ 0 ] if v == '3' : return input ( prompt ) else : return raw_input ( prompt )
ask any python 3 question
cosqa-train-64
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')
Convert a ctypes double pointer array to a numpy array .
0
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' )
python create pointer ctypes array
cosqa-train-65
def yn_prompt(msg, default=True): """ Prompts the user for yes or no. """ ret = custom_prompt(msg, ["y", "n"], "y" if default else "n") if ret == "y": return True return False
Prompts the user for yes or no .
0
def yn_prompt ( msg , default = True ) : ret = custom_prompt ( msg , [ "y" , "n" ] , "y" if default else "n" ) if ret == "y" : return True return False
asking user yes or no in python
cosqa-train-66
def _display(self, layout): """launch layouts display""" print(file=self.out) TextWriter().format(layout, self.out)
launch layouts display
0
def _display ( self , layout ) : print ( file = self . out ) TextWriter ( ) . format ( layout , self . out )
python create print text in grid
cosqa-train-67
def assert_list(self, putative_list, expected_type=string_types, key_arg=None): """ :API: public """ return assert_list(putative_list, expected_type, key_arg=key_arg, raise_type=lambda msg: TargetDefinitionException(self, msg))
: API : public
0
def assert_list ( self , putative_list , expected_type = string_types , key_arg = None ) : return assert_list ( putative_list , expected_type , key_arg = key_arg , raise_type = lambda msg : TargetDefinitionException ( self , msg ) )
assert based on part of string in a list python
cosqa-train-68
def assert_exactly_one_true(bool_list): """This method asserts that only one value of the provided list is True. :param bool_list: List of booleans to check :return: True if only one value is True, False otherwise """ assert isinstance(bool_list, list) counter = 0 for item in bool_list: if item: counter += 1 return counter == 1
This method asserts that only one value of the provided list is True .
1
def assert_exactly_one_true ( bool_list ) : assert isinstance ( bool_list , list ) counter = 0 for item in bool_list : if item : counter += 1 return counter == 1
assure all true of a list of boolean python
cosqa-train-69
def _get_random_id(): """ Get a random (i.e., unique) string identifier""" symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.choice(symbols) for _ in range(15))
Get a random ( i . e . unique ) string identifier
0
def _get_random_id ( ) : symbols = string . ascii_uppercase + string . ascii_lowercase + string . digits return '' . join ( random . choice ( symbols ) for _ in range ( 15 ) )
python create unique 5 letter id
cosqa-train-70
async def list(source): """Generate a single list from an asynchronous sequence.""" result = [] async with streamcontext(source) as streamer: async for item in streamer: result.append(item) yield result
Generate a single list from an asynchronous sequence .
0
async def list ( source ) : result = [ ] async with streamcontext ( source ) as streamer : async for item in streamer : result . append ( item ) yield result
async list comprehension python
cosqa-train-71
def _attrprint(d, delimiter=', '): """Print a dictionary of attributes in the DOT format""" return delimiter.join(('"%s"="%s"' % item) for item in sorted(d.items()))
Print a dictionary of attributes in the DOT format
0
def _attrprint ( d , delimiter = ', ' ) : return delimiter . join ( ( '"%s"="%s"' % item ) for item in sorted ( d . items ( ) ) )
attr dot notation python
cosqa-train-72
def get_next_scheduled_time(cron_string): """Calculate the next scheduled time by creating a crontab object with a cron string""" itr = croniter.croniter(cron_string, datetime.utcnow()) return itr.get_next(datetime)
Calculate the next scheduled time by creating a crontab object with a cron string
0
def get_next_scheduled_time ( cron_string ) : itr = croniter . croniter ( cron_string , datetime . utcnow ( ) ) return itr . get_next ( datetime )
python croniter sigle question
cosqa-train-73
def exit(exit_code=0): r"""A function to support exiting from exit hooks. Could also be used to exit from the calling scripts in a thread safe manner. """ core.processExitHooks() if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook sys.stderr.flush() sys.stdout.flush() os._exit(exit_code) #pylint: disable=W0212 sys.exit(exit_code)
r A function to support exiting from exit hooks .
0
def exit ( exit_code = 0 ) : core . processExitHooks ( ) if state . isExitHooked and not hasattr ( sys , 'exitfunc' ) : # The function is called from the exit hook sys . stderr . flush ( ) sys . stdout . flush ( ) os . _exit ( exit_code ) #pylint: disable=W0212 sys . exit ( exit_code )
autoexit python shell after script executed
cosqa-train-74
def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y
Return the dot product of the given vectors .
0
def dot_product ( self , other ) : return self . x * other . x + self . y * other . y
python cross product of two vectors
cosqa-train-75
def reloader_thread(softexit=False): """If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit`` will be used to end the process. """ while RUN_RELOADER: if code_changed(): # force reload if softexit: sys.exit(3) else: os._exit(3) time.sleep(1)
If soft_exit is True we use sys . exit () ; otherwise os_exit will be used to end the process .
0
def reloader_thread ( softexit = False ) : while RUN_RELOADER : if code_changed ( ) : # force reload if softexit : sys . exit ( 3 ) else : os . _exit ( 3 ) time . sleep ( 1 )
automatically restart python program after crash
cosqa-train-76
def list_to_csv(value): """ Converts list to string with comma separated values. For string is no-op. """ if isinstance(value, (list, tuple, set)): value = ",".join(value) return value
Converts list to string with comma separated values . For string is no - op .
0
def list_to_csv ( value ) : if isinstance ( value , ( list , tuple , set ) ) : value = "," . join ( value ) return value
python csv with comma in string
cosqa-train-77
def average(iterator): """Iterative mean.""" count = 0 total = 0 for num in iterator: count += 1 total += num return float(total)/count
Iterative mean .
0
def average ( iterator ) : count = 0 total = 0 for num in iterator : count += 1 total += num return float ( total ) / count
average time python takes to run a for loop
cosqa-train-78
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')
Convert a ctypes int pointer array to a numpy array .
0
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' )
python ctypes array int
cosqa-train-79
def _aws_get_instance_by_tag(region, name, tag, raw): """Get all instances matching a tag.""" client = boto3.session.Session().client('ec2', region) matching_reservations = client.describe_instances(Filters=[{'Name': tag, 'Values': [name]}]).get('Reservations', []) instances = [] [[instances.append(_aws_instance_from_dict(region, instance, raw)) # pylint: disable=expression-not-assigned for instance in reservation.get('Instances')] for reservation in matching_reservations if reservation] return instances
Get all instances matching a tag .
0
def _aws_get_instance_by_tag ( region , name , tag , raw ) : client = boto3 . session . Session ( ) . client ( 'ec2' , region ) matching_reservations = client . describe_instances ( Filters = [ { 'Name' : tag , 'Values' : [ name ] } ] ) . get ( 'Reservations' , [ ] ) instances = [ ] [ [ instances . append ( _aws_instance_from_dict ( region , instance , raw ) ) # pylint: disable=expression-not-assigned for instance in reservation . get ( 'Instances' ) ] for reservation in matching_reservations if reservation ] return instances
aws python boto3 list all ec2 with tags
cosqa-train-80
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')
Convert a ctypes double pointer array to a numpy array .
1
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' )
python ctypes array to pointer
cosqa-train-81
def loganalytics_data_plane_client(cli_ctx, _): """Initialize Log Analytics data client for use with CLI.""" from .vendored_sdks.loganalytics import LogAnalyticsDataClient from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) cred, _, _ = profile.get_login_credentials( resource="https://api.loganalytics.io") return LogAnalyticsDataClient(cred)
Initialize Log Analytics data client for use with CLI .
0
def loganalytics_data_plane_client ( cli_ctx , _ ) : from . vendored_sdks . loganalytics import LogAnalyticsDataClient from azure . cli . core . _profile import Profile profile = Profile ( cli_ctx = cli_ctx ) cred , _ , _ = profile . get_login_credentials ( resource = "https://api.loganalytics.io" ) return LogAnalyticsDataClient ( cred )
azure python use cli session
cosqa-train-82
def cfloat32_array_to_numpy(cptr, length): """Convert a ctypes float pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_float)): return np.fromiter(cptr, dtype=np.float32, count=length) else: raise RuntimeError('Expected float pointer')
Convert a ctypes float pointer array to a numpy array .
0
def cfloat32_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_float ) ) : return np . fromiter ( cptr , dtype = np . float32 , count = length ) else : raise RuntimeError ( 'Expected float pointer' )
python ctypes make float string
cosqa-train-83
def underscore(text): """Converts text that may be camelcased into an underscored format""" return UNDERSCORE[1].sub(r'\1_\2', UNDERSCORE[0].sub(r'\1_\2', text)).lower()
Converts text that may be camelcased into an underscored format
0
def underscore ( text ) : return UNDERSCORE [ 1 ] . sub ( r'\1_\2' , UNDERSCORE [ 0 ] . sub ( r'\1_\2' , text ) ) . lower ( )
before after underscore python
cosqa-train-84
def cint8_array_to_numpy(cptr, length): """Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)): return np.fromiter(cptr, dtype=np.int8, count=length) else: raise RuntimeError('Expected int pointer')
Convert a ctypes int pointer array to a numpy array .
0
def cint8_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_int8 ) ) : return np . fromiter ( cptr , dtype = np . int8 , count = length ) else : raise RuntimeError ( 'Expected int pointer' )
python ctypes pointer from int
cosqa-train-85
def get_stoplist(language): """Returns an built-in stop-list for the language as a set of words.""" file_path = os.path.join("stoplists", "%s.txt" % language) try: stopwords = pkgutil.get_data("justext", file_path) except IOError: raise ValueError( "Stoplist for language '%s' is missing. " "Please use function 'get_stoplists' for complete list of stoplists " "and feel free to contribute by your own stoplist." % language ) return frozenset(w.decode("utf8").lower() for w in stopwords.splitlines())
Returns an built - in stop - list for the language as a set of words .
0
def get_stoplist ( language ) : file_path = os . path . join ( "stoplists" , "%s.txt" % language ) try : stopwords = pkgutil . get_data ( "justext" , file_path ) except IOError : raise ValueError ( "Stoplist for language '%s' is missing. " "Please use function 'get_stoplists' for complete list of stoplists " "and feel free to contribute by your own stoplist." % language ) return frozenset ( w . decode ( "utf8" ) . lower ( ) for w in stopwords . splitlines ( ) )
best stopword list for python
cosqa-train-86
def add_str(window, line_num, str): """ attempt to draw str on screen and ignore errors if they occur """ try: window.addstr(line_num, 0, str) except curses.error: pass
attempt to draw str on screen and ignore errors if they occur
0
def add_str ( window , line_num , str ) : try : window . addstr ( line_num , 0 , str ) except curses . error : pass
python curses addstr returned err
cosqa-train-87
def relative_path(path): """ Return the given path relative to this file. """ return os.path.join(os.path.dirname(__file__), path)
Return the given path relative to this file .
1
def relative_path ( path ) : return os . path . join ( os . path . dirname ( __file__ ) , path )
best way to give file path in python
cosqa-train-88
def dictfetchall(cursor): """Returns all rows from a cursor as a dict (rather than a headerless table) From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/ """ desc = cursor.description return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
Returns all rows from a cursor as a dict ( rather than a headerless table )
0
def dictfetchall ( cursor ) : desc = cursor . description return [ dict ( zip ( [ col [ 0 ] for col in desc ] , row ) ) for row in cursor . fetchall ( ) ]
python cursor fetchall field name
cosqa-train-89
def xmltreefromfile(filename): """Internal function to read an XML file""" try: return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False)) except TypeError: return ElementTree.parse(filename, ElementTree.XMLParser())
Internal function to read an XML file
0
def xmltreefromfile ( filename ) : try : return ElementTree . parse ( filename , ElementTree . XMLParser ( collect_ids = False ) ) except TypeError : return ElementTree . parse ( filename , ElementTree . XMLParser ( ) )
best way to parse xml files in python
cosqa-train-90
def _dictfetchall(self, cursor): """ Return all rows from a cursor as a dict. """ columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ]
Return all rows from a cursor as a dict .
0
def _dictfetchall ( self , cursor ) : columns = [ col [ 0 ] for col in cursor . description ] return [ dict ( zip ( columns , row ) ) for row in cursor . fetchall ( ) ]
python cursor fetchone to dictionary
cosqa-train-91
def beta_pdf(x, a, b): """Beta distirbution probability density function.""" bc = 1 / beta(a, b) fc = x ** (a - 1) sc = (1 - x) ** (b - 1) return bc * fc * sc
Beta distirbution probability density function .
0
def beta_pdf ( x , a , b ) : bc = 1 / beta ( a , b ) fc = x ** ( a - 1 ) sc = ( 1 - x ) ** ( b - 1 ) return bc * fc * sc
beta distribution function graph in python
cosqa-train-92
def filter_out(queryset, setting_name): """ Remove unwanted results from queryset """ kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {}) queryset = queryset.exclude(**kwargs) return queryset
Remove unwanted results from queryset
0
def filter_out ( queryset , setting_name ) : kwargs = helpers . get_settings ( ) . get ( setting_name , { } ) . get ( 'FILTER_OUT' , { } ) queryset = queryset . exclude ( * * kwargs ) return queryset
python custom filter based on extra
cosqa-train-93
def intToBin(i): """ Integer to two bytes """ # divide in two parts (bytes) i1 = i % 256 i2 = int(i / 256) # make string (little endian) return i.to_bytes(2, byteorder='little')
Integer to two bytes
0
def intToBin ( i ) : # divide in two parts (bytes) i1 = i % 256 i2 = int ( i / 256 ) # make string (little endian) return i . to_bytes ( 2 , byteorder = 'little' )
bin as 8 digits python
cosqa-train-94
def listlike(obj): """Is an object iterable like a list (and not a string)?""" return hasattr(obj, "__iter__") \ and not issubclass(type(obj), str)\ and not issubclass(type(obj), unicode)
Is an object iterable like a list ( and not a string ) ?
0
def listlike ( obj ) : return hasattr ( obj , "__iter__" ) and not issubclass ( type ( obj ) , str ) and not issubclass ( type ( obj ) , unicode )
python custom object nonetype
cosqa-train-95
def table_top_abs(self): """Returns the absolute position of table top""" table_height = np.array([0, 0, self.table_full_size[2]]) return string_to_array(self.floor.get("pos")) + table_height
Returns the absolute position of table top
1
def table_top_abs ( self ) : table_height = np . array ( [ 0 , 0 , self . table_full_size [ 2 ] ] ) return string_to_array ( self . floor . get ( "pos" ) ) + table_height
bottom 5 rows in python
cosqa-train-96
def pdf(x, mu, std): """Probability density function (normal distribution)""" return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))
Probability density function ( normal distribution )
0
def pdf ( x , mu , std ) : return ( 1.0 / ( std * sqrt ( 2 * pi ) ) ) * np . exp ( - ( x - mu ) ** 2 / ( 2 * std ** 2 ) )
python custom probability distribution
cosqa-train-97
def bytes_to_c_array(data): """ Make a C array using the given string. """ chars = [ "'{}'".format(encode_escape(i)) for i in decode_escape(data) ] return ', '.join(chars) + ', 0'
Make a C array using the given string .
0
def bytes_to_c_array ( data ) : chars = [ "'{}'" . format ( encode_escape ( i ) ) for i in decode_escape ( data ) ] return ', ' . join ( chars ) + ', 0'
c style array to python
cosqa-train-98
def gray2bgr(img): """Convert a grayscale image to BGR image. Args: img (ndarray or str): The input image. Returns: ndarray: The converted BGR image. """ img = img[..., None] if img.ndim == 2 else img out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) return out_img
Convert a grayscale image to BGR image .
1
def gray2bgr ( img ) : img = img [ ... , None ] if img . ndim == 2 else img out_img = cv2 . cvtColor ( img , cv2 . COLOR_GRAY2BGR ) return out_img
python cv2 np array to gray scale
cosqa-train-99

Downloaded from https://github.com/microsoft/CodeXGLUE/tree/main/Text-Code/NL-code-search-WebQuery

For more details about the dataset collection and usage, please refer to the ACL 2021 paper (https://arxiv.org/abs/2105.13239) and the GitHub repo (https://github.com/Jun-jie-Huang/CoCLR).

Downloads last month
60

Models trained or fine-tuned on gonglinyuan/CoSQA