Dataset Preview
Full Screen
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed because of a cast error
Error code:   DatasetGenerationCastError
Exception:    DatasetGenerationCastError
Message:      An error occurred while generating the dataset

All the data files must have the same columns, but at some point there are 1 new columns ({'negative'})

This happened while the json dataset builder was generating data using

hf://datasets/Denis641/CosQa/modified_dataset_train.json (at revision 6d50a1a21de47f97dbf969fc20bb1bfb781c3290)

Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2011, in _prepare_split_single
                  writer.write_table(table)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 585, in write_table
                  pa_table = table_cast(pa_table, self._schema)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2302, in table_cast
                  return cast_table_to_schema(table, schema)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2256, in cast_table_to_schema
                  raise CastError(
              datasets.table.CastError: Couldn't cast
              docstring_tokens: string
              retrieval_idx: int64
              doc: string
              code: string
              idx: string
              negative: string
              label: int64
              code_tokens: string
              to
              {'docstring_tokens': Value(dtype='string', id=None), 'retrieval_idx': Value(dtype='int64', id=None), 'doc': Value(dtype='string', id=None), 'code': Value(dtype='string', id=None), 'idx': Value(dtype='string', id=None), 'label': Value(dtype='int64', id=None), 'code_tokens': Value(dtype='string', id=None)}
              because column names don't match
              
              During handling of the above exception, another exception occurred:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1321, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 935, in convert_to_parquet
                  builder.download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
                  self._download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2013, in _prepare_split_single
                  raise DatasetGenerationCastError.from_cast_error(
              datasets.exceptions.DatasetGenerationCastError: An error occurred while generating the dataset
              
              All the data files must have the same columns, but at some point there are 1 new columns ({'negative'})
              
              This happened while the json dataset builder was generating data using
              
              hf://datasets/Denis641/CosQa/modified_dataset_train.json (at revision 6d50a1a21de47f97dbf969fc20bb1bfb781c3290)
              
              Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

idx
string
doc
string
label
int64
code_tokens
string
docstring_tokens
string
retrieval_idx
int64
code
string
cosqa-train-0
python code to write bool value 1
0
def writeBoolean ( self , n ) : 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): """ Writes a Boolean to the stream. """ t = TYPE_BOOL_TRUE if n is False: t = TYPE_BOOL_FALSE self.stream.write(t)
cosqa-train-1
"python how to manipulate clipboard"
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
Returns system clipboard contents .
1
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
cosqa-train-2
python colored output to html
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
Pretty print a dict as a JSON with colors if pygments is present .
2
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
cosqa-train-3
python "create directory" using "relative path"
0
def create_path ( path ) : import os if not os . path . exists ( path ) : os . makedirs ( path )
Creates a absolute path in the file system .
3
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)
cosqa-train-4
python column of an array
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
Convert an object to either a scalar or a row or column vector .
4
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
cosqa-train-5
python calling a property returns "property object"
0
def experiment_property ( prop ) : 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 .
5
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)
cosqa-train-6
python combine wav file into one as separate channels
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 )
Return ( first channel data sample frequency sample width ) from a . wav file .
6
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)
cosqa-train-7
+how to use range with a dictionary python
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 ( ) )
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 .
7
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())
cosqa-train-8
python compare timespan to number
0
def timespan ( start_time ) : timespan = datetime . datetime . now ( ) - start_time timespan_ms = timespan . total_seconds ( ) * 1000 return timespan_ms
Return time in milliseconds from start_time
8
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
cosqa-train-9
1d array in char datatype in python
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 )
Convert Matrix attributes which are array - like or buffer to array .
9
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)
cosqa-train-10
python comprehension list distinct
0
def get_uniques ( l ) : result = [ ] for i in l : if i not in result : result . append ( i ) return result
Returns a list with no repeated elements .
10
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
cosqa-train-11
1d interpolation function python example
0
def interp ( x , xp , * args , * * kwargs ) : return interpolate_1d ( x , xp , * args , * * kwargs )
Wrap interpolate_1d for deprecated interp .
11
def interp(x, xp, *args, **kwargs): """Wrap interpolate_1d for deprecated interp.""" return interpolate_1d(x, xp, *args, **kwargs)
cosqa-train-12
python compress array to string
0
def _array2cstr ( arr ) : out = StringIO ( ) np . save ( out , arr ) return b64encode ( out . getvalue ( ) )
Serializes a numpy array to a compressed base64 string
12
def _array2cstr(arr): """ Serializes a numpy array to a compressed base64 string """ out = StringIO() np.save(out, arr) return b64encode(out.getvalue())
cosqa-train-13
25 and 75 percentile of a list python
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 ) ) ]
Find the percentile of a list of values .
13
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))]
cosqa-train-14
python compute hash of string
0
def _string_hash ( s ) : 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 ) .
14
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
cosqa-train-15
3d rotatioin matrix in python
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 ] ) )
Transforation matrix from rotation matrix and translation vector .
15
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]))
cosqa-train-16
python concatenate bool to string
0
def _encode_bool ( name , value , dummy0 , dummy1 ) : return b"\x08" + name + ( value and b"\x01" or b"\x00" )
Encode a python boolean ( True / False ) .
16
def _encode_bool(name, value, dummy0, dummy1): """Encode a python boolean (True/False).""" return b"\x08" + name + (value and b"\x01" or b"\x00")
cosqa-train-17
3d rotation in python around z axis
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
Project points into 3d from 2d points .
17
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
cosqa-train-18
python condition non none
1
def _not ( condition = None , * * kwargs ) : result = True if condition is not None : result = not run ( condition , * * kwargs ) return result
Return the opposite of input condition .
18
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
cosqa-train-19
403 code from request python
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 )
HTTP response for forbidden access ( status code 403 )
19
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)
cosqa-train-20
python configparser get keys in section
0
def items ( self , section_name ) : 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
20
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__']
cosqa-train-21
a array of vector, compute the norm of each vector python
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 )
Get the magnitude of a vector .
21
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)
cosqa-train-22
python configparser transfer dict
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
Convert a ConfigParser to a dictionary .
22
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
cosqa-train-23
a+b in python addition code
0
def __add__ ( self , other ) : return self . _handle_type ( other ) ( self . value + other . value )
Handle the + operator .
23
def __add__(self, other): """Handle the `+` operator.""" return self._handle_type(other)(self.value + other.value)
cosqa-train-24
python connect mysql denied password
0
def connect_mysql ( host , port , user , password , database ) : return pymysql . connect ( host = host , port = port , user = user , passwd = password , db = database )
Connect to MySQL with retries .
24
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 )
cosqa-train-25
accessing a column from a matrix in python
1
def get_column ( self , X , column ) : if isinstance ( X , pd . DataFrame ) : return X [ column ] . values return X [ : , column ]
Return a column of the given matrix .
25
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]
cosqa-train-26
python connecting to an api with username and password
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
Return a connected Bitbucket session
26
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
cosqa-train-27
add empty series to data frame python
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 a blank row with only an index value to self . df . This is done inplace .
27
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
cosqa-train-28
python container pod stuck in terminating
0
def teardown ( self ) : while self . _http_clients : self . _http_clients . pop ( ) . close ( ) if self . created : self . halt ( )
Stop and remove the container if it exists .
28
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()
cosqa-train-29
add indentations to code in python
0
def dumped ( text , level , indent = 2 ) : return indented ( "{\n%s\n}" % indented ( text , level + 1 , indent ) or "None" , level , indent ) + "\n"
Put curly brackets round an indented text
29
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"
cosqa-train-30
python context manager exit
0
def context ( self ) : 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 .
30
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)
cosqa-train-31
add print depth inpython
0
def pformat ( object , indent = 1 , width = 80 , depth = None ) : return PrettyPrinter ( indent = indent , width = width , depth = depth ) . pformat ( object )
Format a Python object into a pretty - printed representation .
31
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)
cosqa-train-32
python contextmanager temperarily set env
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
Temporarily replace sys . argv with current arguments
32
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
cosqa-train-33
add serializer for type python
0
def serialize ( obj ) : 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
33
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)
cosqa-train-34
python continuation on 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 ) )
Advances to next line .
34
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))
cosqa-train-35
add swagger to python django
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 )
given a root directory for the swagger statics and a swagger json path return back a swagger html designed to use those values .
35
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 )
cosqa-train-36
python continue executing the next command
0
def do_next ( self , args ) : self . _do_print_from_last_cmd = True self . _interp . step_over ( ) return True
Step over the next statement
36
def do_next(self, args): """Step over the next statement """ self._do_print_from_last_cmd = True self._interp.step_over() return True
cosqa-train-37
add two matrix with same shape expect one dim python
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 )
If the number of columns matches we can concatenate two LabeldMatrices with the + operator .
37
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)
cosqa-train-38
python contourf interpolation method
0
def get_line_flux ( line_wave , wave , flux , * * kwargs ) : return np . interp ( line_wave , wave , flux , * * kwargs )
Interpolated flux at a given wavelength ( calls np . interp ) .
38
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)
cosqa-train-39
add websocket support to python
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 )
Sends a message to websocket .
39
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)
cosqa-train-40
python conver string to number
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 )
Try to get a number out of a string and cast it .
40
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)
cosqa-train-41
adding a horxontal line python
0
def get_hline ( ) : return Window ( width = LayoutDimension . exact ( 1 ) , height = LayoutDimension . exact ( 1 ) , content = FillControl ( '-' , token = Token . Line ) )
gets a horiztonal line
41
def get_hline(): """ gets a horiztonal line """ return Window( width=LayoutDimension.exact(1), height=LayoutDimension.exact(1), content=FillControl('-', token=Token.Line))
cosqa-train-42
python cookies change to 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
parse cookies str to dict : param cookies : cookies str : type cookies : str : return : cookie dict : rtype : dict
42
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
cosqa-train-43
alternate uppercase and lower case in python
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 ( )
Given a name in camelCase return in snake_case
43
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()
cosqa-train-44
python copy a dict to object attributes
0
def populate_obj ( obj , attrs ) : for k , v in attrs . iteritems ( ) : setattr ( obj , k , v )
Populates an object s attributes using the provided dict
44
def populate_obj(obj, attrs): """Populates an object's attributes using the provided dict """ for k, v in attrs.iteritems(): setattr(obj, k, v)
cosqa-train-45
analyze the frequency of a word using python
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
Return a dictionary of words and word counts in a string .
45
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
cosqa-train-46
python copy files effeciently
0
def copyFile ( input , output , replace = None ) : _found = findFile ( output ) if not _found or ( _found and replace ) : shutil . copy2 ( input , output )
Copy a file whole from input to output .
46
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)
cosqa-train-47
append last element of the stack in pythong
0
def push ( h , x ) : h . push ( x ) up ( h , h . size ( ) - 1 )
Push a new value into heap .
47
def push(h, x): """Push a new value into heap.""" h.push(x) up(h, h.size()-1)
cosqa-train-48
python copy paste clipboard drop
0
def yank ( event ) : event . current_buffer . paste_clipboard_data ( event . cli . clipboard . get_data ( ) , count = event . arg , paste_mode = PasteMode . EMACS )
Paste before cursor .
48
def yank(event): """ Paste before cursor. """ event.current_buffer.paste_clipboard_data( event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)
cosqa-train-49
apply a filter to an image python
0
def filter_contour ( imageFile , opFile ) : im = Image . open ( imageFile ) im1 = im . filter ( ImageFilter . CONTOUR ) im1 . save ( opFile )
convert an image by applying a contour
49
def filter_contour(imageFile, opFile): """ convert an image by applying a contour """ im = Image.open(imageFile) im1 = im.filter(ImageFilter.CONTOUR) im1.save(opFile)
cosqa-train-50
python count number of words in each sentence
0
def count ( lines ) : words = [ w for l in lines for w in l . strip ( ) . split ( ) ] return Counter ( words )
Counts the word frequences in a list of sentences .
50
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)
cosqa-train-51
apply a function to dictionary python
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 all non - dict values in a dictionary
51
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
cosqa-train-52
python count partitions of a number
0
def count_replica ( self , partition ) : return sum ( 1 for b in partition . replicas if b in self . brokers )
Return count of replicas of given partition .
52
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)
cosqa-train-53
apply range to method python
0
def visit_Name ( self , node ) : return self . add ( node , self . result [ node . id ] )
Get range for parameters for examples or false branching .
53
def visit_Name(self, node): """ Get range for parameters for examples or false branching. """ return self.add(node, self.result[node.id])
cosqa-train-54
python creat a dir
0
def mkdir ( dir , enter ) : if not os . path . exists ( dir ) : os . makedirs ( dir )
Create directory with template for topic of the current environment
54
def mkdir(dir, enter): """Create directory with template for topic of the current environment """ if not os.path.exists(dir): os.makedirs(dir)
cosqa-train-55
apply rotation on vector along a axis python
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
Rotate a 3D vector using quaternion algebra .
55
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
cosqa-train-56
python create a numpy of chars
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 ] )
Like netCDF4 . chartostring but faster and more flexible .
56
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])
cosqa-train-57
are python strings hashable
1
def _string_hash ( s ) : 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 ) .
14
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
cosqa-train-58
python create list of dictionary from csv file no key
0
def csv_to_dicts ( file , header = None ) : 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 .
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)]
cosqa-train-59
area of a triangle python function
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
Given a list of coords for 3 points Compute the area of this triangle .
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
cosqa-train-60
python create numpy onehot
0
def one_hot ( x , size , dtype = np . float32 ) : return np . array ( x [ ... , np . newaxis ] == np . arange ( size ) , dtype )
Make a n + 1 dim one - hot array from n dim int - categorical array .
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)
cosqa-train-61
around to precision python
0
def round_to_int ( number , precision ) : precision = int ( precision ) rounded = ( int ( number ) + precision / 2 ) // precision * precision return rounded
Round a number to a precision
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
cosqa-dev-66
python create object without class
1
def create_object ( cls , members ) : obj = cls . __new__ ( cls ) obj . __dict__ = members return obj
Promise an object of class cls with content members .
61
def create_object(cls, members): """Promise an object of class `cls` with content `members`.""" obj = cls.__new__(cls) obj.__dict__ = members return obj
cosqa-train-62
ascii character representation in python 3
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"'"
helpful in situations where browser / app may recognize Unicode encoding in the \ u0b8e type syntax but not actual unicode glyph / code - point
62
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"'"
cosqa-train-63
python create path pathlib create directory
0
def create_path ( path ) : import os if not os . path . exists ( path ) : os . makedirs ( path )
Creates a absolute path in the file system .
3
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)
cosqa-train-64
ask any python 3 question
0
def string_input ( prompt = '' ) : v = sys . version [ 0 ] if v == '3' : return input ( prompt ) else : return raw_input ( prompt )
Python 3 input () / Python 2 raw_input ()
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)
cosqa-train-65
python create pointer ctypes 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' )
Convert a ctypes double pointer array to a numpy array .
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')
cosqa-train-66
asking user yes or no in python
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
Prompts the user for yes or no .
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
cosqa-train-67
python create print text in grid
0
def _display ( self , layout ) : print ( file = self . out ) TextWriter ( ) . format ( layout , self . out )
launch layouts display
66
def _display(self, layout): """launch layouts display""" print(file=self.out) TextWriter().format(layout, self.out)
cosqa-train-68
assert based on part of string in a list python
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 ) )
: API : public
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))
cosqa-dev-93
python create range in steps
1
def _xxrange ( self , start , end , step_count ) : _step = ( end - start ) / float ( step_count ) return ( start + ( i * _step ) for i in xrange ( int ( step_count ) ) )
Generate n values between start and end .
68
def _xxrange(self, start, end, step_count): """Generate n values between start and end.""" _step = (end - start) / float(step_count) return (start + (i * _step) for i in xrange(int(step_count)))
cosqa-train-69
assure all true of a list of boolean python
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
This method asserts that only one value of the provided list is True .
69
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
cosqa-train-70
python create unique 5 letter id
0
def _get_random_id ( ) : 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
70
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))
cosqa-train-71
async list comprehension python
0
async def list ( source ) : 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 .
71
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
cosqa-dev-117
python creating a dictionary from reading a csv file with dictreader
1
def csv_to_dicts ( file , header = None ) : 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 .
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)]
cosqa-train-72
attr dot notation python
0
def _attrprint ( d , delimiter = ', ' ) : return delimiter . join ( ( '"%s"="%s"' % item ) for item in sorted ( d . items ( ) ) )
Print a dictionary of attributes in the DOT format
72
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()))
cosqa-train-73
python croniter sigle question
0
def get_next_scheduled_time ( 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
73
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)
cosqa-train-74
autoexit python shell after script executed
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 )
r A function to support exiting from exit hooks .
74
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)
cosqa-train-75
python cross product of two vectors
0
def dot_product ( self , other ) : return self . x * other . x + self . y * other . y
Return the dot product of the given vectors .
75
def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y
cosqa-train-76
automatically restart python program after crash
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 )
If soft_exit is True we use sys . exit () ; otherwise os_exit will be used to end the process .
76
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)
cosqa-train-77
python csv with comma in string
0
def list_to_csv ( value ) : if isinstance ( value , ( list , tuple , set ) ) : value = "," . join ( value ) return value
Converts list to string with comma separated values . For string is no - op .
77
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
cosqa-train-78
average time python takes to run a for loop
0
def average ( iterator ) : count = 0 total = 0 for num in iterator : count += 1 total += num return float ( total ) / count
Iterative mean .
78
def average(iterator): """Iterative mean.""" count = 0 total = 0 for num in iterator: count += 1 total += num return float(total)/count
cosqa-train-79
python ctypes array int
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' )
Convert a ctypes int pointer array to a numpy array .
79
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')
cosqa-train-80
aws python boto3 list all ec2 with tags
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
Get all instances matching a tag .
80
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
cosqa-train-81
python ctypes array to pointer
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' )
Convert a ctypes double pointer array to a numpy array .
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')
cosqa-train-82
azure python use cli session
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 )
Initialize Log Analytics data client for use with CLI .
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)
cosqa-train-83
python ctypes make float string
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' )
Convert a ctypes float pointer array to a numpy array .
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')
cosqa-train-84
before after underscore python
0
def underscore ( text ) : 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
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()
cosqa-train-85
python ctypes pointer from int
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' )
Convert a ctypes int pointer array to a numpy array .
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')
cosqa-train-86
best stopword list for python
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 ( ) )
Returns an built - in stop - list for the language as a set of words .
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())
cosqa-train-87
python curses addstr returned err
0
def add_str ( window , line_num , str ) : try : window . addstr ( line_num , 0 , str ) except curses . error : pass
attempt to draw str on screen and ignore errors if they occur
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
cosqa-train-88
best way to give file path in python
1
def relative_path ( path ) : return os . path . join ( os . path . dirname ( __file__ ) , path )
Return the given path relative to this file .
87
def relative_path(path): """ Return the given path relative to this file. """ return os.path.join(os.path.dirname(__file__), path)
cosqa-train-89
python cursor fetchall field name
0
def dictfetchall ( cursor ) : 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 )
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()]
cosqa-train-90
best way to parse xml files in python
0
def xmltreefromfile ( filename ) : 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
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())
cosqa-train-91
python cursor fetchone to dictionary
0
def _dictfetchall ( self , cursor ) : 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 .
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() ]
cosqa-train-92
beta distribution function graph in python
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 distirbution probability density function .
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
cosqa-train-93
python custom filter based on extra
0
def filter_out ( queryset , setting_name ) : kwargs = helpers . get_settings ( ) . get ( setting_name , { } ) . get ( 'FILTER_OUT' , { } ) queryset = queryset . exclude ( * * kwargs ) return queryset
Remove unwanted results from queryset
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
cosqa-train-94
bin as 8 digits python
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' )
Integer to two bytes
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')
cosqa-train-95
python custom object nonetype
0
def listlike ( obj ) : 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 ) ?
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)
cosqa-train-96
bottom 5 rows in python
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
Returns the absolute position of table top
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
End of preview.

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
30