[ { "idx": "cosqa-train-8333", "doc": "python check if a variable is iterable", "code": "def is_iterable_but_not_string(obj):\n \"\"\"\n Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n \"\"\"\n return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "code_tokens": "def is_iterable_but_not_string ( obj ) : return hasattr ( obj , '__iter__' ) and not isinstance ( obj , str ) and not isinstance ( obj , bytes )", "docstring_tokens": "Determine whether or not obj is iterable but not a string ( eg a list set tuple etc ) .", "label": 1, "retrieval_idx": 1640 }, { "idx": "cosqa-train-9660", "doc": "how to prevent a file from modifying python", "code": "def make_file_readable (filename):\n \"\"\"Make file user readable if it is not a link.\"\"\"\n if not os.path.islink(filename):\n util.set_mode(filename, stat.S_IRUSR)", "code_tokens": "def make_file_readable ( filename ) : if not os . path . islink ( filename ) : util . set_mode ( filename , stat . S_IRUSR )", "docstring_tokens": "Make file user readable if it is not a link .", "label": 1, "retrieval_idx": 4294 }, { "idx": "cosqa-train-16056", "doc": "how to make functions that returns a function python", "code": "def apply(filter):\n \"\"\"Manufacture decorator that filters return value with given function.\n\n ``filter``:\n Callable that takes a single parameter.\n \"\"\"\n def decorator(callable):\n return lambda *args, **kwargs: filter(callable(*args, **kwargs))\n return decorator", "code_tokens": "def apply ( filter ) : def decorator ( callable ) : return lambda * args , * * kwargs : filter ( callable ( * args , * * kwargs ) ) return decorator", "docstring_tokens": "Manufacture decorator that filters return value with given function .", "label": 1, "retrieval_idx": 5176 }, { "idx": "cosqa-train-7554", "doc": "how to print without moving cursor python", "code": "def ensure_newline(self):\n \"\"\"\n use before any custom printing when using the progress iter to ensure\n your print statement starts on a new line instead of at the end of a\n progress line\n \"\"\"\n DECTCEM_SHOW = '\\033[?25h' # show cursor\n AT_END = DECTCEM_SHOW + '\\n'\n if not self._cursor_at_newline:\n self.write(AT_END)\n self._cursor_at_newline = True", "code_tokens": "def ensure_newline ( self ) : DECTCEM_SHOW = '\\033[?25h' # show cursor AT_END = DECTCEM_SHOW + '\\n' if not self . _cursor_at_newline : self . write ( AT_END ) self . _cursor_at_newline = True", "docstring_tokens": "use before any custom printing when using the progress iter to ensure your print statement starts on a new line instead of at the end of a progress line", "label": 1, "retrieval_idx": 3812 }, { "idx": "cosqa-train-10709", "doc": "calculate an average in python using the count of an array", "code": "def variance(arr):\n \"\"\"variance of the values, must have 2 or more entries.\n\n :param arr: list of numbers\n :type arr: number[] a number array\n :return: variance\n :rtype: float\n\n \"\"\"\n avg = average(arr)\n return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1)", "code_tokens": "def variance ( arr ) : avg = average ( arr ) return sum ( [ ( float ( x ) - avg ) ** 2 for x in arr ] ) / float ( len ( arr ) - 1 )", "docstring_tokens": "variance of the values must have 2 or more entries .", "label": 1, "retrieval_idx": 2108 }, { "idx": "cosqa-train-11657", "doc": "how to make a 2d array with booleans in python", "code": "def is_bool_matrix(l):\n r\"\"\"Checks if l is a 2D numpy array of bools\n\n \"\"\"\n if isinstance(l, np.ndarray):\n if l.ndim == 2 and (l.dtype == bool):\n return True\n return False", "code_tokens": "def is_bool_matrix ( l ) : if isinstance ( l , np . ndarray ) : if l . ndim == 2 and ( l . dtype == bool ) : return True return False", "docstring_tokens": "r Checks if l is a 2D numpy array of bools", "label": 1, "retrieval_idx": 1574 }, { "idx": "cosqa-train-12916", "doc": "check if a variable is an array python", "code": "def is_integer_array(val):\n \"\"\"\n Checks whether a variable is a numpy integer array.\n\n Parameters\n ----------\n val\n The variable to check.\n\n Returns\n -------\n bool\n True if the variable is a numpy integer array. Otherwise False.\n\n \"\"\"\n return is_np_array(val) and issubclass(val.dtype.type, np.integer)", "code_tokens": "def is_integer_array ( val ) : return is_np_array ( val ) and issubclass ( val . dtype . type , np . integer )", "docstring_tokens": "Checks whether a variable is a numpy integer array .", "label": 1, "retrieval_idx": 2675 }, { "idx": "cosqa-train-12355", "doc": "python 3 remove directory recursively", "code": "def rrmdir(directory):\n \"\"\"\n Recursivly delete a directory\n\n :param directory: directory to remove\n \"\"\"\n for root, dirs, files in os.walk(directory, topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n os.rmdir(os.path.join(root, name))\n os.rmdir(directory)", "code_tokens": "def rrmdir ( directory ) : for root , dirs , files in os . walk ( directory , topdown = False ) : for name in files : os . remove ( os . path . join ( root , name ) ) for name in dirs : os . rmdir ( os . path . join ( root , name ) ) os . rmdir ( directory )", "docstring_tokens": "Recursivly delete a directory", "label": 1, "retrieval_idx": 1013 }, { "idx": "cosqa-train-16936", "doc": "x limit and y limit in python", "code": "def values(self):\n \"\"\"Gets the user enter max and min values of where the \n raster points should appear on the y-axis\n\n :returns: (float, float) -- (min, max) y-values to bound the raster plot by\n \"\"\"\n lower = float(self.lowerSpnbx.value())\n upper = float(self.upperSpnbx.value())\n return (lower, upper)", "code_tokens": "def values ( self ) : lower = float ( self . lowerSpnbx . value ( ) ) upper = float ( self . upperSpnbx . value ( ) ) return ( lower , upper )", "docstring_tokens": "Gets the user enter max and min values of where the raster points should appear on the y - axis", "label": 1, "retrieval_idx": 314 }, { "idx": "cosqa-train-14114", "doc": "python string formatting in list", "code": "def list_formatter(handler, item, value):\n \"\"\"Format list.\"\"\"\n return u', '.join(str(v) for v in value)", "code_tokens": "def list_formatter ( handler , item , value ) : return u', ' . join ( str ( v ) for v in value )", "docstring_tokens": "Format list .", "label": 1, "retrieval_idx": 892 }, { "idx": "cosqa-train-11154", "doc": "get distinct in list python", "code": "def distinct(xs):\n \"\"\"Get the list of distinct values with preserving order.\"\"\"\n # don't use collections.OrderedDict because we do support Python 2.6\n seen = set()\n return [x for x in xs if x not in seen and not seen.add(x)]", "code_tokens": "def distinct ( xs ) : # don't use collections.OrderedDict because we do support Python 2.6 seen = set ( ) return [ x for x in xs if x not in seen and not seen . add ( x ) ]", "docstring_tokens": "Get the list of distinct values with preserving order .", "label": 1, "retrieval_idx": 714 }, { "idx": "cosqa-train-9553", "doc": "python read dot file", "code": "def graph_from_dot_file(path):\n \"\"\"Load graph as defined by a DOT file.\n \n The file is assumed to be in DOT format. It will\n be loaded, parsed and a Dot class will be returned, \n representing the graph.\n \"\"\"\n \n fd = file(path, 'rb')\n data = fd.read()\n fd.close()\n \n return graph_from_dot_data(data)", "code_tokens": "def graph_from_dot_file ( path ) : fd = file ( path , 'rb' ) data = fd . read ( ) fd . close ( ) return graph_from_dot_data ( data )", "docstring_tokens": "Load graph as defined by a DOT file . The file is assumed to be in DOT format . It will be loaded parsed and a Dot class will be returned representing the graph .", "label": 1, "retrieval_idx": 2908 }, { "idx": "cosqa-train-19409", "doc": "traverse all but the last item in a list in python", "code": "def butlast(iterable):\n \"\"\"Yield all items from ``iterable`` except the last one.\n\n >>> list(butlast(['spam', 'eggs', 'ham']))\n ['spam', 'eggs']\n\n >>> list(butlast(['spam']))\n []\n\n >>> list(butlast([]))\n []\n \"\"\"\n iterable = iter(iterable)\n try:\n first = next(iterable)\n except StopIteration:\n return\n for second in iterable:\n yield first\n first = second", "code_tokens": "def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second", "docstring_tokens": "Yield all items from iterable except the last one .", "label": 1, "retrieval_idx": 5721 }, { "idx": "cosqa-train-14561", "doc": "python buffer is smaller than requested size", "code": "def _read_stream_for_size(stream, buf_size=65536):\n \"\"\"Reads a stream discarding the data read and returns its size.\"\"\"\n size = 0\n while True:\n buf = stream.read(buf_size)\n size += len(buf)\n if not buf:\n break\n return size", "code_tokens": "def _read_stream_for_size ( stream , buf_size = 65536 ) : size = 0 while True : buf = stream . read ( buf_size ) size += len ( buf ) if not buf : break return size", "docstring_tokens": "Reads a stream discarding the data read and returns its size .", "label": 1, "retrieval_idx": 3708 }, { "idx": "cosqa-train-19566", "doc": "how to read file from aws s3 using python s3fs", "code": "def s3_get(url: str, temp_file: IO) -> None:\n \"\"\"Pull a file directly from S3.\"\"\"\n s3_resource = boto3.resource(\"s3\")\n bucket_name, s3_path = split_s3_path(url)\n s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "code_tokens": "def s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( \"s3\" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file )", "docstring_tokens": "Pull a file directly from S3 .", "label": 1, "retrieval_idx": 5656 }, { "idx": "cosqa-train-14313", "doc": "python wrapper function for a method", "code": "def Proxy(f):\n \"\"\"A helper to create a proxy method in a class.\"\"\"\n\n def Wrapped(self, *args):\n return getattr(self, f)(*args)\n\n return Wrapped", "code_tokens": "def Proxy ( f ) : def Wrapped ( self , * args ) : return getattr ( self , f ) ( * args ) return Wrapped", "docstring_tokens": "A helper to create a proxy method in a class .", "label": 1, "retrieval_idx": 577 }, { "idx": "cosqa-train-13573", "doc": "how to check value is int or float python", "code": "def is_float(value):\n \"\"\"must be a float\"\"\"\n return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)", "code_tokens": "def is_float ( value ) : return isinstance ( value , float ) or isinstance ( value , int ) or isinstance ( value , np . float64 ) , float ( value )", "docstring_tokens": "must be a float", "label": 1, "retrieval_idx": 772 }, { "idx": "cosqa-train-1140", "doc": "how to join two data frames python", "code": "def cross_join(df1, df2):\n \"\"\"\n Return a dataframe that is a cross between dataframes\n df1 and df2\n\n ref: https://github.com/pydata/pandas/issues/5401\n \"\"\"\n if len(df1) == 0:\n return df2\n\n if len(df2) == 0:\n return df1\n\n # Add as lists so that the new index keeps the items in\n # the order that they are added together\n all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n df1['key'] = 1\n df2['key'] = 1\n return pd.merge(df1, df2, on='key').loc[:, all_columns]", "code_tokens": "def cross_join ( df1 , df2 ) : if len ( df1 ) == 0 : return df2 if len ( df2 ) == 0 : return df1 # Add as lists so that the new index keeps the items in # the order that they are added together all_columns = pd . Index ( list ( df1 . columns ) + list ( df2 . columns ) ) df1 [ 'key' ] = 1 df2 [ 'key' ] = 1 return pd . merge ( df1 , df2 , on = 'key' ) . loc [ : , all_columns ]", "docstring_tokens": "Return a dataframe that is a cross between dataframes df1 and df2", "label": 1, "retrieval_idx": 793 }, { "idx": "cosqa-train-19881", "doc": "how to execute a parser script in python", "code": "def cli_run():\n \"\"\"docstring for argparse\"\"\"\n parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n args = parser.parse_args()\n main(args)", "code_tokens": "def cli_run ( ) : parser = argparse . ArgumentParser ( description = 'Stupidly simple code answers from StackOverflow' ) parser . add_argument ( 'query' , help = \"What's the problem ?\" , type = str , nargs = '+' ) parser . add_argument ( '-t' , '--tags' , help = 'semicolon separated tags -> python;lambda' ) args = parser . parse_args ( ) main ( args )", "docstring_tokens": "docstring for argparse", "label": 1, "retrieval_idx": 5600 }, { "idx": "cosqa-train-1833", "doc": "python add default value", "code": "def setdefault(obj, field, default):\n \"\"\"Set an object's field to default if it doesn't have a value\"\"\"\n setattr(obj, field, getattr(obj, field, default))", "code_tokens": "def setdefault ( obj , field , default ) : setattr ( obj , field , getattr ( obj , field , default ) )", "docstring_tokens": "Set an object s field to default if it doesn t have a value", "label": 1, "retrieval_idx": 1500 }, { "idx": "cosqa-train-9718", "doc": "how to remove empty elements in a list python", "code": "def unique(seq):\n \"\"\"Return the unique elements of a collection even if those elements are\n unhashable and unsortable, like dicts and sets\"\"\"\n cleaned = []\n for each in seq:\n if each not in cleaned:\n cleaned.append(each)\n return cleaned", "code_tokens": "def unique ( seq ) : cleaned = [ ] for each in seq : if each not in cleaned : cleaned . append ( each ) return cleaned", "docstring_tokens": "Return the unique elements of a collection even if those elements are unhashable and unsortable like dicts and sets", "label": 1, "retrieval_idx": 581 }, { "idx": "cosqa-train-18199", "doc": "validating an input is an integer python", "code": "def clean_int(x) -> int:\n \"\"\"\n Returns its parameter as an integer, or raises\n ``django.forms.ValidationError``.\n \"\"\"\n try:\n return int(x)\n except ValueError:\n raise forms.ValidationError(\n \"Cannot convert to integer: {}\".format(repr(x)))", "code_tokens": "def clean_int ( x ) -> int : try : return int ( x ) except ValueError : raise forms . ValidationError ( \"Cannot convert to integer: {}\" . format ( repr ( x ) ) )", "docstring_tokens": "Returns its parameter as an integer or raises django . forms . ValidationError .", "label": 1, "retrieval_idx": 5836 }, { "idx": "cosqa-train-960", "doc": "how to detect if list in python has no elements", "code": "def contains_empty(features):\n \"\"\"Check features data are not empty\n\n :param features: The features data to check.\n :type features: list of numpy arrays.\n\n :return: True if one of the array is empty, False else.\n\n \"\"\"\n if not features:\n return True\n for feature in features:\n if feature.shape[0] == 0:\n return True\n return False", "code_tokens": "def contains_empty ( features ) : if not features : return True for feature in features : if feature . shape [ 0 ] == 0 : return True return False", "docstring_tokens": "Check features data are not empty", "label": 1, "retrieval_idx": 847 }, { "idx": "cosqa-dev-218", "doc": "how to move cursor to the next line in python", "code": "def _go_to_line(editor, line):\n \"\"\"\n Move cursor to this line in the current buffer.\n \"\"\"\n b = editor.application.current_buffer\n b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)", "code_tokens": "def _go_to_line ( editor , line ) : b = editor . application . current_buffer b . cursor_position = b . document . translate_row_col_to_index ( max ( 0 , int ( line ) - 1 ) , 0 )", "docstring_tokens": "Move cursor to this line in the current buffer .", "label": 1, "retrieval_idx": 814 }, { "idx": "cosqa-train-10948", "doc": "definition python nonetype to int", "code": "def test_value(self, value):\n \"\"\"Test if value is an instance of int.\"\"\"\n if not isinstance(value, int):\n raise ValueError('expected int value: ' + str(type(value)))", "code_tokens": "def test_value ( self , value ) : if not isinstance ( value , int ) : raise ValueError ( 'expected int value: ' + str ( type ( value ) ) )", "docstring_tokens": "Test if value is an instance of int .", "label": 1, "retrieval_idx": 4573 }, { "idx": "cosqa-train-19334", "doc": "how to truncate to two decimals in python", "code": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n \"\"\"Truncates a value to a number of decimals places\"\"\"\n return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "code_tokens": "def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )", "docstring_tokens": "Truncates a value to a number of decimals places", "label": 1, "retrieval_idx": 5704 }, { "idx": "cosqa-train-15119", "doc": "python enable executable permisions on file", "code": "def add_exec_permission_to(target_file):\n \"\"\"Add executable permissions to the file\n\n :param target_file: the target file whose permission to be changed\n \"\"\"\n mode = os.stat(target_file).st_mode\n os.chmod(target_file, mode | stat.S_IXUSR)", "code_tokens": "def add_exec_permission_to ( target_file ) : mode = os . stat ( target_file ) . st_mode os . chmod ( target_file , mode | stat . S_IXUSR )", "docstring_tokens": "Add executable permissions to the file", "label": 1, "retrieval_idx": 2659 }, { "idx": "cosqa-train-13474", "doc": "how to calculate manhattan distance in python", "code": "def _manhattan_distance(vec_a, vec_b):\n \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n if len(vec_a) != len(vec_b):\n raise ValueError('len(vec_a) must equal len(vec_b)')\n return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "code_tokens": "def _manhattan_distance ( vec_a , vec_b ) : if len ( vec_a ) != len ( vec_b ) : raise ValueError ( 'len(vec_a) must equal len(vec_b)' ) return sum ( map ( lambda a , b : abs ( a - b ) , vec_a , vec_b ) )", "docstring_tokens": "Return manhattan distance between two lists of numbers .", "label": 1, "retrieval_idx": 1828 }, { "idx": "cosqa-train-18187", "doc": "python longest directed path", "code": "def dag_longest_path(graph, source, target):\n \"\"\"\n Finds the longest path in a dag between two nodes\n \"\"\"\n if source == target:\n return [source]\n allpaths = nx.all_simple_paths(graph, source, target)\n longest_path = []\n for l in allpaths:\n if len(l) > len(longest_path):\n longest_path = l\n return longest_path", "code_tokens": "def dag_longest_path ( graph , source , target ) : if source == target : return [ source ] allpaths = nx . all_simple_paths ( graph , source , target ) longest_path = [ ] for l in allpaths : if len ( l ) > len ( longest_path ) : longest_path = l return longest_path", "docstring_tokens": "Finds the longest path in a dag between two nodes", "label": 1, "retrieval_idx": 5910 }, { "idx": "cosqa-train-7733", "doc": "how to tell what you python path is", "code": "def getpackagepath():\n \"\"\"\n *Get the root path for this python package - used in unit testing code*\n \"\"\"\n moduleDirectory = os.path.dirname(__file__)\n packagePath = os.path.dirname(__file__) + \"/../\"\n\n return packagePath", "code_tokens": "def getpackagepath ( ) : moduleDirectory = os . path . dirname ( __file__ ) packagePath = os . path . dirname ( __file__ ) + \"/../\" return packagePath", "docstring_tokens": "* Get the root path for this python package - used in unit testing code *", "label": 1, "retrieval_idx": 1712 }, { "idx": "cosqa-train-8563", "doc": "bin data into integers python", "code": "def to_bin(data, width):\n \"\"\"\n Convert an unsigned integer to a numpy binary array with the first\n element the MSB and the last element the LSB.\n \"\"\"\n data_str = bin(data & (2**width-1))[2:].zfill(width)\n return [int(x) for x in tuple(data_str)]", "code_tokens": "def to_bin ( data , width ) : data_str = bin ( data & ( 2 ** width - 1 ) ) [ 2 : ] . zfill ( width ) return [ int ( x ) for x in tuple ( data_str ) ]", "docstring_tokens": "Convert an unsigned integer to a numpy binary array with the first element the MSB and the last element the LSB .", "label": 1, "retrieval_idx": 4059 }, { "idx": "cosqa-train-18097", "doc": "how do i cut off leading zeroes in python", "code": "def __remove_trailing_zeros(self, collection):\n \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n index = len(collection) - 1\n while index >= 0 and collection[index] == 0:\n index -= 1\n\n return collection[:index + 1]", "code_tokens": "def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]", "docstring_tokens": "Removes trailing zeroes from indexable collection of numbers", "label": 1, "retrieval_idx": 5636 }, { "idx": "cosqa-train-6367", "doc": "accesing elements in a heap in python", "code": "def fix(h, i):\n \"\"\"Rearrange the heap after the item at position i got updated.\"\"\"\n down(h, i, h.size())\n up(h, i)", "code_tokens": "def fix ( h , i ) : down ( h , i , h . size ( ) ) up ( h , i )", "docstring_tokens": "Rearrange the heap after the item at position i got updated .", "label": 1, "retrieval_idx": 3468 }, { "idx": "cosqa-train-10663", "doc": "auto crop particular object from image in python", "code": "def crop_box(im, box=False, **kwargs):\n \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n if box:\n im = im.crop(box)\n return im", "code_tokens": "def crop_box ( im , box = False , * * kwargs ) : if box : im = im . crop ( box ) return im", "docstring_tokens": "Uses box coordinates to crop an image without resizing it first .", "label": 1, "retrieval_idx": 613 }, { "idx": "cosqa-train-8561", "doc": "bi linear interpolation in python", "code": "def _linear_interpolation(x, X, Y):\n \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n \"\"\"\n return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])", "code_tokens": "def _linear_interpolation ( x , X , Y ) : return ( Y [ 1 ] * ( x - X [ 0 ] ) + Y [ 0 ] * ( X [ 1 ] - x ) ) / ( X [ 1 ] - X [ 0 ] )", "docstring_tokens": "Given two data points [ X Y ] linearly interpolate those at x .", "label": 1, "retrieval_idx": 1490 }, { "idx": "cosqa-train-16893", "doc": "python check for all numeric types", "code": "def is_numeric_dtype(dtype):\n \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n dtype = np.dtype(dtype)\n return np.issubsctype(getattr(dtype, 'base', None), np.number)", "code_tokens": "def is_numeric_dtype ( dtype ) : dtype = np . dtype ( dtype ) return np . issubsctype ( getattr ( dtype , 'base' , None ) , np . number )", "docstring_tokens": "Return True if dtype is a numeric type .", "label": 1, "retrieval_idx": 3424 }, { "idx": "cosqa-train-9999", "doc": "join list of strings with character python", "code": "def delimited(items, character='|'):\n \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n return '|'.join(items) if type(items) in (list, tuple, set) else items", "code_tokens": "def delimited ( items , character = '|' ) : return '|' . join ( items ) if type ( items ) in ( list , tuple , set ) else items", "docstring_tokens": "Returns a character delimited version of the provided list as a Python string", "label": 1, "retrieval_idx": 1295 }, { "idx": "cosqa-train-14154", "doc": "how to use chain with a json file python", "code": "def json_iter (path):\n \"\"\"\n iterator for JSON-per-line in a file pattern\n \"\"\"\n with open(path, 'r') as f:\n for line in f.readlines():\n yield json.loads(line)", "code_tokens": "def json_iter ( path ) : with open ( path , 'r' ) as f : for line in f . readlines ( ) : yield json . loads ( line )", "docstring_tokens": "iterator for JSON - per - line in a file pattern", "label": 1, "retrieval_idx": 983 }, { "idx": "cosqa-train-10533", "doc": "validate credit card number in python using string input", "code": "def is_valid(number):\n \"\"\"determines whether the card number is valid.\"\"\"\n n = str(number)\n if not n.isdigit():\n return False\n return int(n[-1]) == get_check_digit(n[:-1])", "code_tokens": "def is_valid ( number ) : n = str ( number ) if not n . isdigit ( ) : return False return int ( n [ - 1 ] ) == get_check_digit ( n [ : - 1 ] )", "docstring_tokens": "determines whether the card number is valid .", "label": 1, "retrieval_idx": 357 }, { "idx": "cosqa-train-392", "doc": "cython python2 bool function", "code": "def isbinary(*args):\n \"\"\"Checks if value can be part of binary/bitwise operations.\"\"\"\n return all(map(lambda c: isnumber(c) or isbool(c), args))", "code_tokens": "def isbinary ( * args ) : return all ( map ( lambda c : isnumber ( c ) or isbool ( c ) , args ) )", "docstring_tokens": "Checks if value can be part of binary / bitwise operations .", "label": 1, "retrieval_idx": 371 }, { "idx": "cosqa-train-13488", "doc": "python list remove list indices must be", "code": "def rm_empty_indices(*args):\n \"\"\"\n Remove unwanted list indices. First argument is the list\n of indices to remove. Other elements are the lists\n to trim.\n \"\"\"\n rm_inds = args[0]\n\n if not rm_inds:\n return args[1:]\n\n keep_inds = [i for i in range(len(args[1])) if i not in rm_inds]\n\n return [[a[i] for i in keep_inds] for a in args[1:]]", "code_tokens": "def rm_empty_indices ( * args ) : rm_inds = args [ 0 ] if not rm_inds : return args [ 1 : ] keep_inds = [ i for i in range ( len ( args [ 1 ] ) ) if i not in rm_inds ] return [ [ a [ i ] for i in keep_inds ] for a in args [ 1 : ] ]", "docstring_tokens": "Remove unwanted list indices . First argument is the list of indices to remove . Other elements are the lists to trim .", "label": 1, "retrieval_idx": 841 }, { "idx": "cosqa-train-9403", "doc": "how to eliminate instances in python", "code": "def clear_instance(cls):\n \"\"\"unset _instance for this class and singleton parents.\n \"\"\"\n if not cls.initialized():\n return\n for subclass in cls._walk_mro():\n if isinstance(subclass._instance, cls):\n # only clear instances that are instances\n # of the calling class\n subclass._instance = None", "code_tokens": "def clear_instance ( cls ) : if not cls . initialized ( ) : return for subclass in cls . _walk_mro ( ) : if isinstance ( subclass . _instance , cls ) : # only clear instances that are instances # of the calling class subclass . _instance = None", "docstring_tokens": "unset _instance for this class and singleton parents .", "label": 1, "retrieval_idx": 4238 }, { "idx": "cosqa-train-14932", "doc": "calculate standard deviation using python", "code": "def stderr(a):\n \"\"\"\n Calculate the standard error of a.\n \"\"\"\n return np.nanstd(a) / np.sqrt(sum(np.isfinite(a)))", "code_tokens": "def stderr ( a ) : return np . nanstd ( a ) / np . sqrt ( sum ( np . isfinite ( a ) ) )", "docstring_tokens": "Calculate the standard error of a .", "label": 1, "retrieval_idx": 715 }, { "idx": "cosqa-train-12031", "doc": "intialize a list with size and 0 python", "code": "def __init__(self, capacity=10):\n \"\"\"\n Initialize python List with capacity of 10 or user given input.\n Python List type is a dynamic array, so we have to restrict its\n dynamic nature to make it work like a static array.\n \"\"\"\n super().__init__()\n self._array = [None] * capacity\n self._front = 0\n self._rear = 0", "code_tokens": "def __init__ ( self , capacity = 10 ) : super ( ) . __init__ ( ) self . _array = [ None ] * capacity self . _front = 0 self . _rear = 0", "docstring_tokens": "Initialize python List with capacity of 10 or user given input . Python List type is a dynamic array so we have to restrict its dynamic nature to make it work like a static array .", "label": 1, "retrieval_idx": 3243 }, { "idx": "cosqa-train-19288", "doc": "instagram login python requests", "code": "def login(self, user: str, passwd: str) -> None:\n \"\"\"Log in to instagram with given username and password and internally store session object.\n\n :raises InvalidArgumentException: If the provided username does not exist.\n :raises BadCredentialsException: If the provided password is wrong.\n :raises ConnectionException: If connection to Instagram failed.\n :raises TwoFactorAuthRequiredException: First step of 2FA login done, now call :meth:`Instaloader.two_factor_login`.\"\"\"\n self.context.login(user, passwd)", "code_tokens": "def login ( self , user : str , passwd : str ) -> None : self . context . login ( user , passwd )", "docstring_tokens": "Log in to instagram with given username and password and internally store session object .", "label": 1, "retrieval_idx": 6158 }, { "idx": "cosqa-train-6945", "doc": "python image detect shape", "code": "def get_shape(img):\n \"\"\"Return the shape of img.\n\n Paramerers\n -----------\n img:\n\n Returns\n -------\n shape: tuple\n \"\"\"\n if hasattr(img, 'shape'):\n shape = img.shape\n else:\n shape = img.get_data().shape\n return shape", "code_tokens": "def get_shape ( img ) : if hasattr ( img , 'shape' ) : shape = img . shape else : shape = img . get_data ( ) . shape return shape", "docstring_tokens": "Return the shape of img .", "label": 1, "retrieval_idx": 2021 }, { "idx": "cosqa-train-16201", "doc": "how to rotate an array 90 degrees in python", "code": "def rotateImage(image, angle):\n \"\"\"\n rotates a 2d array to a multiple of 90 deg.\n 0 = default\n 1 = 90 deg. cw\n 2 = 180 deg.\n 3 = 90 deg. ccw\n \"\"\"\n image = [list(row) for row in image]\n\n for n in range(angle % 4):\n image = list(zip(*image[::-1]))\n\n return image", "code_tokens": "def rotateImage ( image , angle ) : image = [ list ( row ) for row in image ] for n in range ( angle % 4 ) : image = list ( zip ( * image [ : : - 1 ] ) ) return image", "docstring_tokens": "rotates a 2d array to a multiple of 90 deg . 0 = default 1 = 90 deg . cw 2 = 180 deg . 3 = 90 deg . ccw", "label": 1, "retrieval_idx": 1993 }, { "idx": "cosqa-dev-151", "doc": "python flask deployment static path", "code": "def staticdir():\n \"\"\"Return the location of the static data directory.\"\"\"\n root = os.path.abspath(os.path.dirname(__file__))\n return os.path.join(root, \"static\")", "code_tokens": "def staticdir ( ) : root = os . path . abspath ( os . path . dirname ( __file__ ) ) return os . path . join ( root , \"static\" )", "docstring_tokens": "Return the location of the static data directory .", "label": 1, "retrieval_idx": 1813 }, { "idx": "cosqa-train-10259", "doc": "python 'worksheet' object is not callable", "code": "def add_chart(self, chart, row, col):\n \"\"\"\n Adds a chart to the worksheet at (row, col).\n\n :param xltable.Chart Chart: chart to add to the workbook.\n :param int row: Row to add the chart at.\n \"\"\"\n self.__charts.append((chart, (row, col)))", "code_tokens": "def add_chart ( self , chart , row , col ) : self . __charts . append ( ( chart , ( row , col ) ) )", "docstring_tokens": "Adds a chart to the worksheet at ( row col ) .", "label": 1, "retrieval_idx": 4433 }, { "idx": "cosqa-train-9329", "doc": "how to covert a data set to series in python", "code": "def from_series(cls, series):\n \"\"\"Convert a pandas.Series into an xarray.DataArray.\n\n If the series's index is a MultiIndex, it will be expanded into a\n tensor product of one-dimensional coordinates (filling in missing\n values with NaN). Thus this operation should be the inverse of the\n `to_series` method.\n \"\"\"\n # TODO: add a 'name' parameter\n name = series.name\n df = pd.DataFrame({name: series})\n ds = Dataset.from_dataframe(df)\n return ds[name]", "code_tokens": "def from_series ( cls , series ) : # TODO: add a 'name' parameter name = series . name df = pd . DataFrame ( { name : series } ) ds = Dataset . from_dataframe ( df ) return ds [ name ]", "docstring_tokens": "Convert a pandas . Series into an xarray . DataArray .", "label": 1, "retrieval_idx": 3319 }, { "idx": "cosqa-train-17315", "doc": "python dataset get first 50 rows", "code": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n -> Generator[Any, None, None]:\n \"\"\"\n Generate the first value in each row.\n\n Args:\n cursor: the cursor\n arraysize: split fetches into chunks of this many records\n\n Yields:\n the first value of each row\n \"\"\"\n return (row[0] for row in genrows(cursor, arraysize))", "code_tokens": "def genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )", "docstring_tokens": "Generate the first value in each row .", "label": 1, "retrieval_idx": 5650 }, { "idx": "cosqa-train-18487", "doc": "how to check in python if token is person or not", "code": "def contains(self, token: str) -> bool:\n \"\"\"Return if the token is in the list or not.\"\"\"\n self._validate_token(token)\n return token in self", "code_tokens": "def contains ( self , token : str ) -> bool : self . _validate_token ( token ) return token in self", "docstring_tokens": "Return if the token is in the list or not .", "label": 1, "retrieval_idx": 5789 }, { "idx": "cosqa-train-14368", "doc": "number of standard deviations python from a fit", "code": "def sem(inlist):\n \"\"\"\nReturns the estimated standard error of the mean (sx-bar) of the\nvalues in the passed list. sem = stdev / sqrt(n)\n\nUsage: lsem(inlist)\n\"\"\"\n sd = stdev(inlist)\n n = len(inlist)\n return sd / math.sqrt(n)", "code_tokens": "def sem ( inlist ) : sd = stdev ( inlist ) n = len ( inlist ) return sd / math . sqrt ( n )", "docstring_tokens": "Returns the estimated standard error of the mean ( sx - bar ) of the values in the passed list . sem = stdev / sqrt ( n )", "label": 1, "retrieval_idx": 2315 }, { "idx": "cosqa-train-12504", "doc": "python cgi form get value", "code": "def get(key, default=None):\n \"\"\" return the key from the request\n \"\"\"\n data = get_form() or get_query_string()\n return data.get(key, default)", "code_tokens": "def get ( key , default = None ) : data = get_form ( ) or get_query_string ( ) return data . get ( key , default )", "docstring_tokens": "return the key from the request", "label": 1, "retrieval_idx": 1873 }, { "idx": "cosqa-train-19234", "doc": "python receive **kwargs pass on **kwargs", "code": "def use_kwargs(self, *args, **kwargs) -> typing.Callable:\n \"\"\"Decorator that injects parsed arguments into a view function or method.\n\n Receives the same arguments as `webargs.core.Parser.use_kwargs`.\n\n \"\"\"\n return super().use_kwargs(*args, **kwargs)", "code_tokens": "def use_kwargs ( self , * args , * * kwargs ) -> typing . Callable : return super ( ) . use_kwargs ( * args , * * kwargs )", "docstring_tokens": "Decorator that injects parsed arguments into a view function or method .", "label": 1, "retrieval_idx": 6175 }, { "idx": "cosqa-train-19751", "doc": "python white space check", "code": "def _check_whitespace(string):\n \"\"\"\n Make sure thre is no whitespace in the given string. Will raise a\n ValueError if whitespace is detected\n \"\"\"\n if string.count(' ') + string.count('\\t') + string.count('\\n') > 0:\n raise ValueError(INSTRUCTION_HAS_WHITESPACE)", "code_tokens": "def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\\t' ) + string . count ( '\\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )", "docstring_tokens": "Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected", "label": 1, "retrieval_idx": 5747 }, { "idx": "cosqa-train-7177", "doc": "how to check for eof in python", "code": "def eof(fd):\n \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n b = fd.read(1)\n end = len(b) == 0\n if not end:\n curpos = fd.tell()\n fd.seek(curpos - 1)\n return end", "code_tokens": "def eof ( fd ) : b = fd . read ( 1 ) end = len ( b ) == 0 if not end : curpos = fd . tell ( ) fd . seek ( curpos - 1 ) return end", "docstring_tokens": "Determine if end - of - file is reached for file fd .", "label": 1, "retrieval_idx": 2556 }, { "idx": "cosqa-train-15780", "doc": "how to clear python variables at begining of code", "code": "def clear_globals_reload_modules(self):\n \"\"\"Clears globals and reloads modules\"\"\"\n\n self.code_array.clear_globals()\n self.code_array.reload_modules()\n\n # Clear result cache\n self.code_array.result_cache.clear()", "code_tokens": "def clear_globals_reload_modules ( self ) : self . code_array . clear_globals ( ) self . code_array . reload_modules ( ) # Clear result cache self . code_array . result_cache . clear ( )", "docstring_tokens": "Clears globals and reloads modules", "label": 1, "retrieval_idx": 1680 }, { "idx": "cosqa-train-2985", "doc": "how to check if sql connection is open in python", "code": "def raw_connection_from(engine_or_conn):\n \"\"\"Extract a raw_connection and determine if it should be automatically closed.\n\n Only connections opened by this package will be closed automatically.\n \"\"\"\n if hasattr(engine_or_conn, 'cursor'):\n return engine_or_conn, False\n if hasattr(engine_or_conn, 'connection'):\n return engine_or_conn.connection, False\n return engine_or_conn.raw_connection(), True", "code_tokens": "def raw_connection_from ( engine_or_conn ) : if hasattr ( engine_or_conn , 'cursor' ) : return engine_or_conn , False if hasattr ( engine_or_conn , 'connection' ) : return engine_or_conn . connection , False return engine_or_conn . raw_connection ( ) , True", "docstring_tokens": "Extract a raw_connection and determine if it should be automatically closed .", "label": 1, "retrieval_idx": 2143 }, { "idx": "cosqa-train-8181", "doc": "select rows if a field is null in python", "code": "def selectnone(table, field, complement=False):\n \"\"\"Select rows where the given field is `None`.\"\"\"\n\n return select(table, field, lambda v: v is None, complement=complement)", "code_tokens": "def selectnone ( table , field , complement = False ) : return select ( table , field , lambda v : v is None , complement = complement )", "docstring_tokens": "Select rows where the given field is None .", "label": 1, "retrieval_idx": 670 }, { "idx": "cosqa-train-8055", "doc": "plot remove axis python", "code": "def axes_off(ax):\n \"\"\"Get rid of all axis ticks, lines, etc.\n \"\"\"\n ax.set_frame_on(False)\n ax.axes.get_yaxis().set_visible(False)\n ax.axes.get_xaxis().set_visible(False)", "code_tokens": "def axes_off ( ax ) : ax . set_frame_on ( False ) ax . axes . get_yaxis ( ) . set_visible ( False ) ax . axes . get_xaxis ( ) . set_visible ( False )", "docstring_tokens": "Get rid of all axis ticks lines etc .", "label": 1, "retrieval_idx": 2111 }, { "idx": "cosqa-train-8376", "doc": "python check is object is defined", "code": "def is_defined(self, objtxt, force_import=False):\n \"\"\"Return True if object is defined\"\"\"\n return self.interpreter.is_defined(objtxt, force_import)", "code_tokens": "def is_defined ( self , objtxt , force_import = False ) : return self . interpreter . is_defined ( objtxt , force_import )", "docstring_tokens": "Return True if object is defined", "label": 1, "retrieval_idx": 202 }, { "idx": "cosqa-train-7468", "doc": "python remove characters from query", "code": "def filter_query_string(query):\n \"\"\"\n Return a version of the query string with the _e, _k and _s values\n removed.\n \"\"\"\n return '&'.join([q for q in query.split('&')\n if not (q.startswith('_k=') or q.startswith('_e=') or q.startswith('_s'))])", "code_tokens": "def filter_query_string ( query ) : return '&' . join ( [ q for q in query . split ( '&' ) if not ( q . startswith ( '_k=' ) or q . startswith ( '_e=' ) or q . startswith ( '_s' ) ) ] )", "docstring_tokens": "Return a version of the query string with the _e _k and _s values removed .", "label": 1, "retrieval_idx": 2871 }, { "idx": "cosqa-train-18350", "doc": "python, get timezone info in python", "code": "def get_timezone() -> Tuple[datetime.tzinfo, str]:\n \"\"\"Discover the current time zone and it's standard string representation (for source{d}).\"\"\"\n dt = get_datetime_now().astimezone()\n tzstr = dt.strftime(\"%z\")\n tzstr = tzstr[:-2] + \":\" + tzstr[-2:]\n return dt.tzinfo, tzstr", "code_tokens": "def get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( \"%z\" ) tzstr = tzstr [ : - 2 ] + \":\" + tzstr [ - 2 : ] return dt . tzinfo , tzstr", "docstring_tokens": "Discover the current time zone and it s standard string representation ( for source { d } ) .", "label": 1, "retrieval_idx": 5552 }, { "idx": "cosqa-train-2677", "doc": "python how to replace a string with underscores", "code": "def normalise_string(string):\n \"\"\" Strips trailing whitespace from string, lowercases it and replaces\n spaces with underscores\n \"\"\"\n string = (string.strip()).lower()\n return re.sub(r'\\W+', '_', string)", "code_tokens": "def normalise_string ( string ) : string = ( string . strip ( ) ) . lower ( ) return re . sub ( r'\\W+' , '_' , string )", "docstring_tokens": "Strips trailing whitespace from string lowercases it and replaces spaces with underscores", "label": 1, "retrieval_idx": 1117 }, { "idx": "cosqa-train-12961", "doc": "code to take the transpose of a matrix in python", "code": "def transpose(table):\n \"\"\"\n transpose matrix\n \"\"\"\n t = []\n for i in range(0, len(table[0])):\n t.append([row[i] for row in table])\n return t", "code_tokens": "def transpose ( table ) : t = [ ] for i in range ( 0 , len ( table [ 0 ] ) ) : t . append ( [ row [ i ] for row in table ] ) return t", "docstring_tokens": "transpose matrix", "label": 1, "retrieval_idx": 2681 }, { "idx": "cosqa-train-16940", "doc": "python check if two images are the same", "code": "def is_same_shape(self, other_im, check_channels=False):\n \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n Parameters\n ----------\n other_im : :obj:`Image`\n image to compare\n check_channels : bool\n whether or not to check equality of the channels\n\n Returns\n -------\n bool\n True if the images are the same shape, False otherwise\n \"\"\"\n if self.height == other_im.height and self.width == other_im.width:\n if check_channels and self.channels != other_im.channels:\n return False\n return True\n return False", "code_tokens": "def is_same_shape ( self , other_im , check_channels = False ) : if self . height == other_im . height and self . width == other_im . width : if check_channels and self . channels != other_im . channels : return False return True return False", "docstring_tokens": "Checks if two images have the same height and width ( and optionally channels ) .", "label": 1, "retrieval_idx": 205 }, { "idx": "cosqa-train-12042", "doc": "is string python conditional", "code": "def is_identifier(string):\n \"\"\"Check if string could be a valid python identifier\n\n :param string: string to be tested\n :returns: True if string can be a python identifier, False otherwise\n :rtype: bool\n \"\"\"\n matched = PYTHON_IDENTIFIER_RE.match(string)\n return bool(matched) and not keyword.iskeyword(string)", "code_tokens": "def is_identifier ( string ) : matched = PYTHON_IDENTIFIER_RE . match ( string ) return bool ( matched ) and not keyword . iskeyword ( string )", "docstring_tokens": "Check if string could be a valid python identifier", "label": 1, "retrieval_idx": 167 }, { "idx": "cosqa-train-6684", "doc": "python function to remove headers", "code": "def remove_hop_by_hop_headers(headers):\n \"\"\"Remove all HTTP/1.1 \"Hop-by-Hop\" headers from a list or\n :class:`Headers` object. This operation works in-place.\n\n .. versionadded:: 0.5\n\n :param headers: a list or :class:`Headers` object.\n \"\"\"\n headers[:] = [\n (key, value) for key, value in headers if not is_hop_by_hop_header(key)\n ]", "code_tokens": "def remove_hop_by_hop_headers ( headers ) : headers [ : ] = [ ( key , value ) for key , value in headers if not is_hop_by_hop_header ( key ) ]", "docstring_tokens": "Remove all HTTP / 1 . 1 Hop - by - Hop headers from a list or : class : Headers object . This operation works in - place .", "label": 1, "retrieval_idx": 3548 }, { "idx": "cosqa-train-8524", "doc": "python custom type from list comprehension", "code": "def coerce(self, value):\n \"\"\"Convert from whatever is given to a list of scalars for the lookup_field.\"\"\"\n if isinstance(value, dict):\n value = [value]\n if not isiterable_notstring(value):\n value = [value]\n return [coerce_single_instance(self.lookup_field, v) for v in value]", "code_tokens": "def coerce ( self , value ) : if isinstance ( value , dict ) : value = [ value ] if not isiterable_notstring ( value ) : value = [ value ] return [ coerce_single_instance ( self . lookup_field , v ) for v in value ]", "docstring_tokens": "Convert from whatever is given to a list of scalars for the lookup_field .", "label": 1, "retrieval_idx": 1216 }, { "idx": "cosqa-train-12396", "doc": "returns random number in standardn normal distribution python", "code": "def rlognormal(mu, tau, size=None):\n \"\"\"\n Return random lognormal variates.\n \"\"\"\n\n return np.random.lognormal(mu, np.sqrt(1. / tau), size)", "code_tokens": "def rlognormal ( mu , tau , size = None ) : return np . random . lognormal ( mu , np . sqrt ( 1. / tau ) , size )", "docstring_tokens": "Return random lognormal variates .", "label": 1, "retrieval_idx": 551 }, { "idx": "cosqa-train-10196", "doc": "record training time python", "code": "def on_train_end(self, logs):\n \"\"\" Print training time at end of training \"\"\"\n duration = timeit.default_timer() - self.train_start\n print('done, took {:.3f} seconds'.format(duration))", "code_tokens": "def on_train_end ( self , logs ) : duration = timeit . default_timer ( ) - self . train_start print ( 'done, took {:.3f} seconds' . format ( duration ) )", "docstring_tokens": "Print training time at end of training", "label": 1, "retrieval_idx": 4162 }, { "idx": "cosqa-train-9031", "doc": "python how to get stem of filename", "code": "def guess_title(basename):\n \"\"\" Attempt to guess the title from the filename \"\"\"\n\n base, _ = os.path.splitext(basename)\n return re.sub(r'[ _-]+', r' ', base).title()", "code_tokens": "def guess_title ( basename ) : base , _ = os . path . splitext ( basename ) return re . sub ( r'[ _-]+' , r' ' , base ) . title ( )", "docstring_tokens": "Attempt to guess the title from the filename", "label": 1, "retrieval_idx": 3790 }, { "idx": "cosqa-train-12821", "doc": "python direct all print output to log file", "code": "def log_no_newline(self, msg):\n \"\"\" print the message to the predefined log file without newline \"\"\"\n self.print2file(self.logfile, False, False, msg)", "code_tokens": "def log_no_newline ( self , msg ) : self . print2file ( self . logfile , False , False , msg )", "docstring_tokens": "print the message to the predefined log file without newline", "label": 1, "retrieval_idx": 2091 }, { "idx": "cosqa-train-19736", "doc": "how to get contents fromtext file python", "code": "def read_text_from_file(path: str) -> str:\n \"\"\" Reads text file contents \"\"\"\n with open(path) as text_file:\n content = text_file.read()\n\n return content", "code_tokens": "def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content", "docstring_tokens": "Reads text file contents", "label": 1, "retrieval_idx": 5554 }, { "idx": "cosqa-train-3384", "doc": "how to remove the duplicates in list in python", "code": "def remove_duplicates(lst):\n \"\"\"\n Emulate what a Python ``set()`` does, but keeping the element's order.\n \"\"\"\n dset = set()\n return [l for l in lst if l not in dset and not dset.add(l)]", "code_tokens": "def remove_duplicates ( lst ) : dset = set ( ) return [ l for l in lst if l not in dset and not dset . add ( l ) ]", "docstring_tokens": "Emulate what a Python set () does but keeping the element s order .", "label": 1, "retrieval_idx": 278 }, { "idx": "cosqa-train-7235", "doc": "how to conduct a delaunay triangulation python", "code": "def computeDelaunayTriangulation(points):\n \"\"\" Takes a list of point objects (which must have x and y fields).\n Returns a list of 3-tuples: the indices of the points that form a\n Delaunay triangle.\n \"\"\"\n siteList = SiteList(points)\n context = Context()\n context.triangulate = True\n voronoi(siteList,context)\n return context.triangles", "code_tokens": "def computeDelaunayTriangulation ( points ) : siteList = SiteList ( points ) context = Context ( ) context . triangulate = True voronoi ( siteList , context ) return context . triangles", "docstring_tokens": "Takes a list of point objects ( which must have x and y fields ) . Returns a list of 3 - tuples : the indices of the points that form a Delaunay triangle .", "label": 1, "retrieval_idx": 386 }, { "idx": "cosqa-train-19075", "doc": "python how to check dtype", "code": "def is_string_dtype(arr_or_dtype):\n \"\"\"\n Check whether the provided array or dtype is of the string dtype.\n\n Parameters\n ----------\n arr_or_dtype : array-like\n The array or dtype to check.\n\n Returns\n -------\n boolean\n Whether or not the array or dtype is of the string dtype.\n\n Examples\n --------\n >>> is_string_dtype(str)\n True\n >>> is_string_dtype(object)\n True\n >>> is_string_dtype(int)\n False\n >>>\n >>> is_string_dtype(np.array(['a', 'b']))\n True\n >>> is_string_dtype(pd.Series([1, 2]))\n False\n \"\"\"\n\n # TODO: gh-15585: consider making the checks stricter.\n def condition(dtype):\n return dtype.kind in ('O', 'S', 'U') and not is_period_dtype(dtype)\n return _is_dtype(arr_or_dtype, condition)", "code_tokens": "def is_string_dtype ( arr_or_dtype ) : # TODO: gh-15585: consider making the checks stricter. def condition ( dtype ) : return dtype . kind in ( 'O' , 'S' , 'U' ) and not is_period_dtype ( dtype ) return _is_dtype ( arr_or_dtype , condition )", "docstring_tokens": "Check whether the provided array or dtype is of the string dtype .", "label": 1, "retrieval_idx": 6152 }, { "idx": "cosqa-train-12873", "doc": "cast object of type bytes to string python", "code": "def to_str(obj):\n \"\"\"Attempts to convert given object to a string object\n \"\"\"\n if not isinstance(obj, str) and PY3 and isinstance(obj, bytes):\n obj = obj.decode('utf-8')\n return obj if isinstance(obj, string_types) else str(obj)", "code_tokens": "def to_str ( obj ) : if not isinstance ( obj , str ) and PY3 and isinstance ( obj , bytes ) : obj = obj . decode ( 'utf-8' ) return obj if isinstance ( obj , string_types ) else str ( obj )", "docstring_tokens": "Attempts to convert given object to a string object", "label": 1, "retrieval_idx": 2806 }, { "idx": "cosqa-train-11786", "doc": "python remove repeated elements in list", "code": "def dedupe_list(seq):\n \"\"\"\n Utility function to remove duplicates from a list\n :param seq: The sequence (list) to deduplicate\n :return: A list with original duplicates removed\n \"\"\"\n seen = set()\n return [x for x in seq if not (x in seen or seen.add(x))]", "code_tokens": "def dedupe_list ( seq ) : seen = set ( ) return [ x for x in seq if not ( x in seen or seen . add ( x ) ) ]", "docstring_tokens": "Utility function to remove duplicates from a list : param seq : The sequence ( list ) to deduplicate : return : A list with original duplicates removed", "label": 1, "retrieval_idx": 1450 }, { "idx": "cosqa-train-9779", "doc": "python smooth an array", "code": "def smooth_array(array, amount=1):\n \"\"\"\n\n Returns the nearest-neighbor (+/- amount) smoothed array.\n This does not modify the array or slice off the funny end points.\n\n \"\"\"\n if amount==0: return array\n\n # we have to store the old values in a temp array to keep the\n # smoothing from affecting the smoothing\n new_array = _n.array(array)\n\n for n in range(len(array)):\n new_array[n] = smooth(array, n, amount)\n\n return new_array", "code_tokens": "def smooth_array ( array , amount = 1 ) : if amount == 0 : return array # we have to store the old values in a temp array to keep the # smoothing from affecting the smoothing new_array = _n . array ( array ) for n in range ( len ( array ) ) : new_array [ n ] = smooth ( array , n , amount ) return new_array", "docstring_tokens": "", "label": 1, "retrieval_idx": 2378 }, { "idx": "cosqa-train-19064", "doc": "python dictionary get case insensistive key", "code": "def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]:\n \"\"\"\n Within the dictionary ``d``, find a key that matches (in case-insensitive\n fashion) the key ``k``, and return it (or ``None`` if there isn't one).\n \"\"\"\n for key in d.keys():\n if k.lower() == key.lower():\n return key\n return None", "code_tokens": "def get_case_insensitive_dict_key ( d : Dict , k : str ) -> Optional [ str ] : for key in d . keys ( ) : if k . lower ( ) == key . lower ( ) : return key return None", "docstring_tokens": "Within the dictionary d find a key that matches ( in case - insensitive fashion ) the key k and return it ( or None if there isn t one ) .", "label": 1, "retrieval_idx": 5951 }, { "idx": "cosqa-train-5715", "doc": "key in sorted function python", "code": "def sort_func(self, key):\n \"\"\"Sorting logic for `Quantity` objects.\"\"\"\n if key == self._KEYS.VALUE:\n return 'aaa'\n if key == self._KEYS.SOURCE:\n return 'zzz'\n return key", "code_tokens": "def sort_func ( self , key ) : if key == self . _KEYS . VALUE : return 'aaa' if key == self . _KEYS . SOURCE : return 'zzz' return key", "docstring_tokens": "Sorting logic for Quantity objects .", "label": 1, "retrieval_idx": 3265 }, { "idx": "cosqa-train-12021", "doc": "indexes of sorted list python", "code": "def _index_ordering(redshift_list):\n \"\"\"\n\n :param redshift_list: list of redshifts\n :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n \"\"\"\n redshift_list = np.array(redshift_list)\n sort_index = np.argsort(redshift_list)\n return sort_index", "code_tokens": "def _index_ordering ( redshift_list ) : redshift_list = np . array ( redshift_list ) sort_index = np . argsort ( redshift_list ) return sort_index", "docstring_tokens": "", "label": 1, "retrieval_idx": 2034 }, { "idx": "cosqa-dev-261", "doc": "using color in python printouts", "code": "def cprint(string, fg=None, bg=None, end='\\n', target=sys.stdout):\n \"\"\"Print a colored string to the target handle.\n\n fg and bg specify foreground- and background colors, respectively. The\n remaining keyword arguments are the same as for Python's built-in print\n function. Colors are returned to their defaults before the function\n returns.\n\n \"\"\"\n _color_manager.set_color(fg, bg)\n target.write(string + end)\n target.flush() # Needed for Python 3.x\n _color_manager.set_defaults()", "code_tokens": "def cprint ( string , fg = None , bg = None , end = '\\n' , target = sys . stdout ) : _color_manager . set_color ( fg , bg ) target . write ( string + end ) target . flush ( ) # Needed for Python 3.x _color_manager . set_defaults ( )", "docstring_tokens": "Print a colored string to the target handle .", "label": 1, "retrieval_idx": 1026 }, { "idx": "cosqa-train-18586", "doc": "how to check 2 strings are the same in python", "code": "def indexes_equal(a: Index, b: Index) -> bool:\n \"\"\"\n Are two indexes equal? Checks by comparing ``str()`` versions of them.\n (AM UNSURE IF THIS IS ENOUGH.)\n \"\"\"\n return str(a) == str(b)", "code_tokens": "def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )", "docstring_tokens": "Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )", "label": 1, "retrieval_idx": 5584 }, { "idx": "cosqa-train-14703", "doc": "python check that can open file", "code": "def is_readable(filename):\n \"\"\"Check if file is a regular file and is readable.\"\"\"\n return os.path.isfile(filename) and os.access(filename, os.R_OK)", "code_tokens": "def is_readable ( filename ) : return os . path . isfile ( filename ) and os . access ( filename , os . R_OK )", "docstring_tokens": "Check if file is a regular file and is readable .", "label": 1, "retrieval_idx": 2445 }, { "idx": "cosqa-train-12468", "doc": "python calculate log likelihood normal distributino", "code": "def ln_norm(x, mu, sigma=1.0):\n \"\"\" Natural log of scipy norm function truncated at zero \"\"\"\n return np.log(stats.norm(loc=mu, scale=sigma).pdf(x))", "code_tokens": "def ln_norm ( x , mu , sigma = 1.0 ) : return np . log ( stats . norm ( loc = mu , scale = sigma ) . pdf ( x ) )", "docstring_tokens": "Natural log of scipy norm function truncated at zero", "label": 1, "retrieval_idx": 1336 }, { "idx": "cosqa-train-7115", "doc": "python make directory exists", "code": "def ensure_dir(f):\n \"\"\" Ensure a a file exists and if not make the relevant path \"\"\"\n d = os.path.dirname(f)\n if not os.path.exists(d):\n os.makedirs(d)", "code_tokens": "def ensure_dir ( f ) : d = os . path . dirname ( f ) if not os . path . exists ( d ) : os . makedirs ( d )", "docstring_tokens": "Ensure a a file exists and if not make the relevant path", "label": 1, "retrieval_idx": 3678 }, { "idx": "cosqa-train-13835", "doc": "python redirect stdout on screen and to file", "code": "def redirect_output(fileobj):\n \"\"\"Redirect standard out to file.\"\"\"\n old = sys.stdout\n sys.stdout = fileobj\n try:\n yield fileobj\n finally:\n sys.stdout = old", "code_tokens": "def redirect_output ( fileobj ) : old = sys . stdout sys . stdout = fileobj try : yield fileobj finally : sys . stdout = old", "docstring_tokens": "Redirect standard out to file .", "label": 1, "retrieval_idx": 1485 }, { "idx": "cosqa-train-8422", "doc": "python closing db connection", "code": "def close_database_session(session):\n \"\"\"Close connection with the database\"\"\"\n\n try:\n session.close()\n except OperationalError as e:\n raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])", "code_tokens": "def close_database_session ( session ) : try : session . close ( ) except OperationalError as e : raise DatabaseError ( error = e . orig . args [ 1 ] , code = e . orig . args [ 0 ] )", "docstring_tokens": "Close connection with the database", "label": 1, "retrieval_idx": 4030 }, { "idx": "cosqa-train-13895", "doc": "python request cookie get", "code": "def parse_cookies(self, req, name, field):\n \"\"\"Pull the value from the cookiejar.\"\"\"\n return core.get_value(req.COOKIES, name, field)", "code_tokens": "def parse_cookies ( self , req , name , field ) : return core . get_value ( req . COOKIES , name , field )", "docstring_tokens": "Pull the value from the cookiejar .", "label": 1, "retrieval_idx": 3111 }, { "idx": "cosqa-train-13084", "doc": "delete empty elements in list python3", "code": "def unique(seq):\n \"\"\"Return the unique elements of a collection even if those elements are\n unhashable and unsortable, like dicts and sets\"\"\"\n cleaned = []\n for each in seq:\n if each not in cleaned:\n cleaned.append(each)\n return cleaned", "code_tokens": "def unique ( seq ) : cleaned = [ ] for each in seq : if each not in cleaned : cleaned . append ( each ) return cleaned", "docstring_tokens": "Return the unique elements of a collection even if those elements are unhashable and unsortable like dicts and sets", "label": 1, "retrieval_idx": 581 }, { "idx": "cosqa-train-11101", "doc": "python how to dump to json file", "code": "def save(self, fname):\n \"\"\" Saves the dictionary in json format\n :param fname: file to save to\n \"\"\"\n with open(fname, 'wb') as f:\n json.dump(self, f)", "code_tokens": "def save ( self , fname ) : with open ( fname , 'wb' ) as f : json . dump ( self , f )", "docstring_tokens": "Saves the dictionary in json format : param fname : file to save to", "label": 1, "retrieval_idx": 686 }, { "idx": "cosqa-train-13837", "doc": "python redirect stdout to 2 places", "code": "def redirect_stdout(new_stdout):\n \"\"\"Redirect the stdout\n\n Args:\n new_stdout (io.StringIO): New stdout to use instead\n \"\"\"\n old_stdout, sys.stdout = sys.stdout, new_stdout\n try:\n yield None\n finally:\n sys.stdout = old_stdout", "code_tokens": "def redirect_stdout ( new_stdout ) : old_stdout , sys . stdout = sys . stdout , new_stdout try : yield None finally : sys . stdout = old_stdout", "docstring_tokens": "Redirect the stdout", "label": 1, "retrieval_idx": 1386 }, { "idx": "cosqa-train-16713", "doc": "python 2to3 whole directory", "code": "def command_py2to3(args):\n \"\"\"\n Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n \"\"\"\n from lib2to3.main import main\n sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "code_tokens": "def command_py2to3 ( args ) : from lib2to3 . main import main sys . exit ( main ( \"lib2to3.fixes\" , args = args . sources ) )", "docstring_tokens": "Apply 2to3 tool ( Python2 to Python3 conversion tool ) to Python sources .", "label": 1, "retrieval_idx": 1469 }, { "idx": "cosqa-train-18400", "doc": "python how to skip subsequent lines", "code": "def _skip_section(self):\n \"\"\"Skip a section\"\"\"\n self._last = self._f.readline()\n while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n self._last = self._f.readline()", "code_tokens": "def _skip_section ( self ) : self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : self . _last = self . _f . readline ( )", "docstring_tokens": "Skip a section", "label": 1, "retrieval_idx": 5576 }, { "idx": "cosqa-train-2457", "doc": "python get git branch name", "code": "def get_git_branch(git_path='git'):\n \"\"\"Returns the name of the current git branch\n \"\"\"\n branch_match = call((git_path, 'rev-parse', '--symbolic-full-name', 'HEAD'))\n if branch_match == \"HEAD\":\n return None\n else:\n return os.path.basename(branch_match)", "code_tokens": "def get_git_branch ( git_path = 'git' ) : branch_match = call ( ( git_path , 'rev-parse' , '--symbolic-full-name' , 'HEAD' ) ) if branch_match == \"HEAD\" : return None else : return os . path . basename ( branch_match )", "docstring_tokens": "Returns the name of the current git branch", "label": 1, "retrieval_idx": 1869 }, { "idx": "cosqa-train-6845", "doc": "python how to check if email and password exist", "code": "def check_auth(email, password):\n \"\"\"Check if a username/password combination is valid.\n \"\"\"\n try:\n user = User.get(User.email == email)\n except User.DoesNotExist:\n return False\n return password == user.password", "code_tokens": "def check_auth ( email , password ) : try : user = User . get ( User . email == email ) except User . DoesNotExist : return False return password == user . password", "docstring_tokens": "Check if a username / password combination is valid .", "label": 1, "retrieval_idx": 3593 }, { "idx": "cosqa-train-4863", "doc": "get the date from a string python", "code": "def _read_date_from_string(str1):\n \"\"\"\n Reads the date from a string in the format YYYY/MM/DD and returns\n :class: datetime.date\n \"\"\"\n full_date = [int(x) for x in str1.split('/')]\n return datetime.date(full_date[0], full_date[1], full_date[2])", "code_tokens": "def _read_date_from_string ( str1 ) : full_date = [ int ( x ) for x in str1 . split ( '/' ) ] return datetime . date ( full_date [ 0 ] , full_date [ 1 ] , full_date [ 2 ] )", "docstring_tokens": "Reads the date from a string in the format YYYY / MM / DD and returns : class : datetime . date", "label": 1, "retrieval_idx": 571 }, { "idx": "cosqa-train-13090", "doc": "python get index of lowest value in list", "code": "def find_le(a, x):\n \"\"\"Find rightmost value less than or equal to x.\"\"\"\n i = bs.bisect_right(a, x)\n if i: return i - 1\n raise ValueError", "code_tokens": "def find_le ( a , x ) : i = bs . bisect_right ( a , x ) if i : return i - 1 raise ValueError", "docstring_tokens": "Find rightmost value less than or equal to x .", "label": 1, "retrieval_idx": 612 }, { "idx": "cosqa-train-7948", "doc": "python write lines on new line next", "code": "def write_line(self, line, count=1):\n \"\"\"writes the line and count newlines after the line\"\"\"\n self.write(line)\n self.write_newlines(count)", "code_tokens": "def write_line ( self , line , count = 1 ) : self . write ( line ) self . write_newlines ( count )", "docstring_tokens": "writes the line and count newlines after the line", "label": 1, "retrieval_idx": 2415 }, { "idx": "cosqa-train-5672", "doc": "int to bool in python", "code": "def is_int(value):\n \"\"\"Return `True` if ``value`` is an integer.\"\"\"\n if isinstance(value, bool):\n return False\n try:\n int(value)\n return True\n except (ValueError, TypeError):\n return False", "code_tokens": "def is_int ( value ) : if isinstance ( value , bool ) : return False try : int ( value ) return True except ( ValueError , TypeError ) : return False", "docstring_tokens": "Return True if value is an integer .", "label": 1, "retrieval_idx": 637 }, { "idx": "cosqa-train-13664", "doc": "python numpy array how to return rows not include nan", "code": "def ma(self):\n \"\"\"Represent data as a masked array.\n\n The array is returned with column-first indexing, i.e. for a data file with\n columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .\n\n inf and nan are filtered via :func:`numpy.isfinite`.\n \"\"\"\n a = self.array\n return numpy.ma.MaskedArray(a, mask=numpy.logical_not(numpy.isfinite(a)))", "code_tokens": "def ma ( self ) : a = self . array return numpy . ma . MaskedArray ( a , mask = numpy . logical_not ( numpy . isfinite ( a ) ) )", "docstring_tokens": "Represent data as a masked array .", "label": 1, "retrieval_idx": 861 }, { "idx": "cosqa-train-6638", "doc": "comparing sets python with boolean and set", "code": "def isetdiff_flags(list1, list2):\n \"\"\"\n move to util_iter\n \"\"\"\n set2 = set(list2)\n return (item not in set2 for item in list1)", "code_tokens": "def isetdiff_flags ( list1 , list2 ) : set2 = set ( list2 ) return ( item not in set2 for item in list1 )", "docstring_tokens": "move to util_iter", "label": 1, "retrieval_idx": 281 }, { "idx": "cosqa-train-10449", "doc": "python cast string to custom type", "code": "def text(value, encoding=\"utf-8\", errors=\"strict\"):\n \"\"\"Convert a value to str on Python 3 and unicode on Python 2.\"\"\"\n if isinstance(value, text_type):\n return value\n elif isinstance(value, bytes):\n return text_type(value, encoding, errors)\n else:\n return text_type(value)", "code_tokens": "def text ( value , encoding = \"utf-8\" , errors = \"strict\" ) : if isinstance ( value , text_type ) : return value elif isinstance ( value , bytes ) : return text_type ( value , encoding , errors ) else : return text_type ( value )", "docstring_tokens": "Convert a value to str on Python 3 and unicode on Python 2 .", "label": 1, "retrieval_idx": 4478 }, { "idx": "cosqa-train-11076", "doc": "filter a dictionary in python and only return the key", "code": "def filter_dict(d, keys):\n \"\"\"\n Creates a new dict from an existing dict that only has the given keys\n \"\"\"\n return {k: v for k, v in d.items() if k in keys}", "code_tokens": "def filter_dict ( d , keys ) : return { k : v for k , v in d . items ( ) if k in keys }", "docstring_tokens": "Creates a new dict from an existing dict that only has the given keys", "label": 1, "retrieval_idx": 177 }, { "idx": "cosqa-dev-409", "doc": "datetime to epoch python2", "code": "def _dt_to_epoch(dt):\n \"\"\"Convert datetime to epoch seconds.\"\"\"\n try:\n epoch = dt.timestamp()\n except AttributeError: # py2\n epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n return epoch", "code_tokens": "def _dt_to_epoch ( dt ) : try : epoch = dt . timestamp ( ) except AttributeError : # py2 epoch = ( dt - datetime ( 1970 , 1 , 1 ) ) . total_seconds ( ) return epoch", "docstring_tokens": "Convert datetime to epoch seconds .", "label": 1, "retrieval_idx": 459 }, { "idx": "cosqa-train-11165", "doc": "python how to remove extra spaces in a string", "code": "def sanitize_word(s):\n \"\"\"Remove non-alphanumerical characters from metric word.\n And trim excessive underscores.\n \"\"\"\n s = re.sub('[^\\w-]+', '_', s)\n s = re.sub('__+', '_', s)\n return s.strip('_')", "code_tokens": "def sanitize_word ( s ) : s = re . sub ( '[^\\w-]+' , '_' , s ) s = re . sub ( '__+' , '_' , s ) return s . strip ( '_' )", "docstring_tokens": "Remove non - alphanumerical characters from metric word . And trim excessive underscores .", "label": 1, "retrieval_idx": 2339 }, { "idx": "cosqa-train-14538", "doc": "running python on your webserver", "code": "def web(host, port):\n \"\"\"Start web application\"\"\"\n from .webserver.web import get_app\n get_app().run(host=host, port=port)", "code_tokens": "def web ( host , port ) : from . webserver . web import get_app get_app ( ) . run ( host = host , port = port )", "docstring_tokens": "Start web application", "label": 1, "retrieval_idx": 1338 }, { "idx": "cosqa-train-18581", "doc": "python check if date is valid", "code": "def valid_date(x: str) -> bool:\n \"\"\"\n Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n otherwise return ``False``.\n \"\"\"\n try:\n if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n raise ValueError\n return True\n except ValueError:\n return False", "code_tokens": "def valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False", "docstring_tokens": "Retrun True if x is a valid YYYYMMDD date ; otherwise return False .", "label": 1, "retrieval_idx": 5581 }, { "idx": "cosqa-train-7160", "doc": "python milliseconds delta time to float", "code": "def datetime_delta_to_ms(delta):\n \"\"\"\n Given a datetime.timedelta object, return the delta in milliseconds\n \"\"\"\n delta_ms = delta.days * 24 * 60 * 60 * 1000\n delta_ms += delta.seconds * 1000\n delta_ms += delta.microseconds / 1000\n delta_ms = int(delta_ms)\n return delta_ms", "code_tokens": "def datetime_delta_to_ms ( delta ) : delta_ms = delta . days * 24 * 60 * 60 * 1000 delta_ms += delta . seconds * 1000 delta_ms += delta . microseconds / 1000 delta_ms = int ( delta_ms ) return delta_ms", "docstring_tokens": "Given a datetime . timedelta object return the delta in milliseconds", "label": 1, "retrieval_idx": 2902 }, { "idx": "cosqa-train-13919", "doc": "python reusing an iterator", "code": "def reset(self):\n\t\t\"\"\"\n\t\tResets the iterator to the start.\n\n\t\tAny remaining values in the current iteration are discarded.\n\t\t\"\"\"\n\t\tself.__iterator, self.__saved = itertools.tee(self.__saved)", "code_tokens": "def reset ( self ) : self . __iterator , self . __saved = itertools . tee ( self . __saved )", "docstring_tokens": "Resets the iterator to the start .", "label": 1, "retrieval_idx": 1126 }, { "idx": "cosqa-train-8974", "doc": "finding the median in python 3", "code": "def median_high(data):\n \"\"\"Return the high median of data.\n\n When the number of data points is odd, the middle value is returned.\n When it is even, the larger of the two middle values is returned.\n\n \"\"\"\n data = sorted(data)\n n = len(data)\n if n == 0:\n raise StatisticsError(\"no median for empty data\")\n return data[n // 2]", "code_tokens": "def median_high ( data ) : data = sorted ( data ) n = len ( data ) if n == 0 : raise StatisticsError ( \"no median for empty data\" ) return data [ n // 2 ]", "docstring_tokens": "Return the high median of data .", "label": 1, "retrieval_idx": 1979 }, { "idx": "cosqa-train-11471", "doc": "how to delete the element in list at a particular index in python", "code": "def pop(self, index=-1):\n\t\t\"\"\"Remove and return the item at index.\"\"\"\n\t\tvalue = self._list.pop(index)\n\t\tdel self._dict[value]\n\t\treturn value", "code_tokens": "def pop ( self , index = - 1 ) : value = self . _list . pop ( index ) del self . _dict [ value ] return value", "docstring_tokens": "Remove and return the item at index .", "label": 1, "retrieval_idx": 1019 }, { "idx": "cosqa-train-16297", "doc": "how to test if two files are the same in python", "code": "def is_same_file (filename1, filename2):\n \"\"\"Check if filename1 and filename2 point to the same file object.\n There can be false negatives, ie. the result is False, but it is\n the same file anyway. Reason is that network filesystems can create\n different paths to the same physical file.\n \"\"\"\n if filename1 == filename2:\n return True\n if os.name == 'posix':\n return os.path.samefile(filename1, filename2)\n return is_same_filename(filename1, filename2)", "code_tokens": "def is_same_file ( filename1 , filename2 ) : if filename1 == filename2 : return True if os . name == 'posix' : return os . path . samefile ( filename1 , filename2 ) return is_same_filename ( filename1 , filename2 )", "docstring_tokens": "Check if filename1 and filename2 point to the same file object . There can be false negatives ie . the result is False but it is the same file anyway . Reason is that network filesystems can create different paths to the same physical file .", "label": 1, "retrieval_idx": 2832 }, { "idx": "cosqa-train-8492", "doc": "add a header to a csv in python", "code": "def writeCSV(data, headers, csvFile):\n \"\"\"Write data with column headers to a CSV.\"\"\"\n with open(csvFile, \"wb\") as f:\n writer = csv.writer(f, delimiter=\",\")\n writer.writerow(headers)\n writer.writerows(data)", "code_tokens": "def writeCSV ( data , headers , csvFile ) : with open ( csvFile , \"wb\" ) as f : writer = csv . writer ( f , delimiter = \",\" ) writer . writerow ( headers ) writer . writerows ( data )", "docstring_tokens": "Write data with column headers to a CSV .", "label": 1, "retrieval_idx": 4044 }, { "idx": "cosqa-train-18659", "doc": "python delete logfile still in use", "code": "def DeleteLog() -> None:\n \"\"\"Delete log file.\"\"\"\n if os.path.exists(Logger.FileName):\n os.remove(Logger.FileName)", "code_tokens": "def DeleteLog ( ) -> None : if os . path . exists ( Logger . FileName ) : os . remove ( Logger . FileName )", "docstring_tokens": "Delete log file .", "label": 1, "retrieval_idx": 6095 }, { "idx": "cosqa-train-18736", "doc": "truncate a number after certain amount of decimals in python", "code": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n \"\"\"Truncates a value to a number of decimals places\"\"\"\n return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "code_tokens": "def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )", "docstring_tokens": "Truncates a value to a number of decimals places", "label": 1, "retrieval_idx": 5704 }, { "idx": "cosqa-train-16420", "doc": "join list of empty strings and strings python", "code": "def join(mapping, bind, values):\n \"\"\" Merge all the strings. Put space between them. \"\"\"\n return [' '.join([six.text_type(v) for v in values if v is not None])]", "code_tokens": "def join ( mapping , bind , values ) : return [ ' ' . join ( [ six . text_type ( v ) for v in values if v is not None ] ) ]", "docstring_tokens": "Merge all the strings . Put space between them .", "label": 1, "retrieval_idx": 2587 }, { "idx": "cosqa-train-7507", "doc": "how to make upper and lower case string the same in python", "code": "def clean(some_string, uppercase=False):\n \"\"\"\n helper to clean up an input string\n \"\"\"\n if uppercase:\n return some_string.strip().upper()\n else:\n return some_string.strip().lower()", "code_tokens": "def clean ( some_string , uppercase = False ) : if uppercase : return some_string . strip ( ) . upper ( ) else : return some_string . strip ( ) . lower ( )", "docstring_tokens": "helper to clean up an input string", "label": 1, "retrieval_idx": 3327 }, { "idx": "cosqa-train-14795", "doc": "python count whitespace characters", "code": "def _count_leading_whitespace(text):\n \"\"\"Returns the number of characters at the beginning of text that are whitespace.\"\"\"\n idx = 0\n for idx, char in enumerate(text):\n if not char.isspace():\n return idx\n return idx + 1", "code_tokens": "def _count_leading_whitespace ( text ) : idx = 0 for idx , char in enumerate ( text ) : if not char . isspace ( ) : return idx return idx + 1", "docstring_tokens": "Returns the number of characters at the beginning of text that are whitespace .", "label": 1, "retrieval_idx": 1859 }, { "idx": "cosqa-train-8907", "doc": "does cos and sin in python use degrees or radians", "code": "def cos_sin_deg(deg):\n \"\"\"Return the cosine and sin for the given angle\n in degrees, with special-case handling of multiples\n of 90 for perfect right angles\n \"\"\"\n deg = deg % 360.0\n if deg == 90.0:\n return 0.0, 1.0\n elif deg == 180.0:\n return -1.0, 0\n elif deg == 270.0:\n return 0, -1.0\n rad = math.radians(deg)\n return math.cos(rad), math.sin(rad)", "code_tokens": "def cos_sin_deg ( deg ) : deg = deg % 360.0 if deg == 90.0 : return 0.0 , 1.0 elif deg == 180.0 : return - 1.0 , 0 elif deg == 270.0 : return 0 , - 1.0 rad = math . radians ( deg ) return math . cos ( rad ) , math . sin ( rad )", "docstring_tokens": "Return the cosine and sin for the given angle in degrees with special - case handling of multiples of 90 for perfect right angles", "label": 1, "retrieval_idx": 4132 }, { "idx": "cosqa-train-8140", "doc": "python add to two values", "code": "def __add__(self, other):\n \"\"\"Handle the `+` operator.\"\"\"\n return self._handle_type(other)(self.value + other.value)", "code_tokens": "def __add__ ( self , other ) : return self . _handle_type ( other ) ( self . value + other . value )", "docstring_tokens": "Handle the + operator .", "label": 1, "retrieval_idx": 23 }, { "idx": "cosqa-train-13030", "doc": "create conda environment for python 2", "code": "def create_conda_env(sandbox_dir, env_name, dependencies, options=()):\n \"\"\"\n Create a conda environment inside the current sandbox for the given list of dependencies and options.\n\n Parameters\n ----------\n sandbox_dir : str\n env_name : str\n dependencies : list\n List of conda specs\n options\n List of additional options to pass to conda. Things like [\"-c\", \"conda-forge\"]\n\n Returns\n -------\n (env_dir, env_name)\n \"\"\"\n\n env_dir = os.path.join(sandbox_dir, env_name)\n cmdline = [\"conda\", \"create\", \"--yes\", \"--copy\", \"--quiet\", \"-p\", env_dir] + list(options) + dependencies\n\n log.info(\"Creating conda environment: \")\n log.info(\" command line: %s\", cmdline)\n subprocess.check_call(cmdline, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n log.debug(\"Environment created\")\n\n return env_dir, env_name", "code_tokens": "def create_conda_env ( sandbox_dir , env_name , dependencies , options = ( ) ) : env_dir = os . path . join ( sandbox_dir , env_name ) cmdline = [ \"conda\" , \"create\" , \"--yes\" , \"--copy\" , \"--quiet\" , \"-p\" , env_dir ] + list ( options ) + dependencies log . info ( \"Creating conda environment: \" ) log . info ( \" command line: %s\" , cmdline ) subprocess . check_call ( cmdline , stderr = subprocess . PIPE , stdout = subprocess . PIPE ) log . debug ( \"Environment created\" ) return env_dir , env_name", "docstring_tokens": "Create a conda environment inside the current sandbox for the given list of dependencies and options .", "label": 1, "retrieval_idx": 1839 }, { "idx": "cosqa-train-12628", "doc": "python check two image same", "code": "def is_same_shape(self, other_im, check_channels=False):\n \"\"\" Checks if two images have the same height and width (and optionally channels).\n\n Parameters\n ----------\n other_im : :obj:`Image`\n image to compare\n check_channels : bool\n whether or not to check equality of the channels\n\n Returns\n -------\n bool\n True if the images are the same shape, False otherwise\n \"\"\"\n if self.height == other_im.height and self.width == other_im.width:\n if check_channels and self.channels != other_im.channels:\n return False\n return True\n return False", "code_tokens": "def is_same_shape ( self , other_im , check_channels = False ) : if self . height == other_im . height and self . width == other_im . width : if check_channels and self . channels != other_im . channels : return False return True return False", "docstring_tokens": "Checks if two images have the same height and width ( and optionally channels ) .", "label": 1, "retrieval_idx": 205 }, { "idx": "cosqa-train-9486", "doc": "python prettyprint object with str", "code": "def _get_pretty_string(obj):\n \"\"\"Return a prettier version of obj\n\n Parameters\n ----------\n obj : object\n Object to pretty print\n\n Returns\n -------\n s : str\n Pretty print object repr\n \"\"\"\n sio = StringIO()\n pprint.pprint(obj, stream=sio)\n return sio.getvalue()", "code_tokens": "def _get_pretty_string ( obj ) : sio = StringIO ( ) pprint . pprint ( obj , stream = sio ) return sio . getvalue ( )", "docstring_tokens": "Return a prettier version of obj", "label": 1, "retrieval_idx": 1942 }, { "idx": "cosqa-train-7202", "doc": "python ndarray fast iterate", "code": "def _npiter(arr):\n \"\"\"Wrapper for iterating numpy array\"\"\"\n for a in np.nditer(arr, flags=[\"refs_ok\"]):\n c = a.item()\n if c is not None:\n yield c", "code_tokens": "def _npiter ( arr ) : for a in np . nditer ( arr , flags = [ \"refs_ok\" ] ) : c = a . item ( ) if c is not None : yield c", "docstring_tokens": "Wrapper for iterating numpy array", "label": 1, "retrieval_idx": 3140 }, { "idx": "cosqa-dev-372", "doc": "python2 get value from dict with default value", "code": "def get_value(key, obj, default=missing):\n \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n if isinstance(key, int):\n return _get_value_for_key(key, obj, default)\n return _get_value_for_keys(key.split('.'), obj, default)", "code_tokens": "def get_value ( key , obj , default = missing ) : if isinstance ( key , int ) : return _get_value_for_key ( key , obj , default ) return _get_value_for_keys ( key . split ( '.' ) , obj , default )", "docstring_tokens": "Helper for pulling a keyed value off various types of objects", "label": 1, "retrieval_idx": 2593 }, { "idx": "cosqa-train-11264", "doc": "python iterator of a dictionary", "code": "def itervalues(d, **kw):\n \"\"\"Return an iterator over the values of a dictionary.\"\"\"\n if not PY2:\n return iter(d.values(**kw))\n return d.itervalues(**kw)", "code_tokens": "def itervalues ( d , * * kw ) : if not PY2 : return iter ( d . values ( * * kw ) ) return d . itervalues ( * * kw )", "docstring_tokens": "Return an iterator over the values of a dictionary .", "label": 1, "retrieval_idx": 1287 }, { "idx": "cosqa-train-16023", "doc": "how to load a string file in python", "code": "def load_feature(fname, language):\n \"\"\" Load and parse a feature file. \"\"\"\n\n fname = os.path.abspath(fname)\n feat = parse_file(fname, language)\n return feat", "code_tokens": "def load_feature ( fname , language ) : fname = os . path . abspath ( fname ) feat = parse_file ( fname , language ) return feat", "docstring_tokens": "Load and parse a feature file .", "label": 1, "retrieval_idx": 3282 }, { "idx": "cosqa-train-18625", "doc": "split on multiple tokens python split", "code": "def split(text: str) -> List[str]:\n \"\"\"Split a text into a list of tokens.\n\n :param text: the text to split\n :return: tokens\n \"\"\"\n return [word for word in SEPARATOR.split(text) if word.strip(' \\t')]", "code_tokens": "def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \\t' ) ]", "docstring_tokens": "Split a text into a list of tokens .", "label": 1, "retrieval_idx": 5571 }, { "idx": "cosqa-train-11126", "doc": "generate white noise in python", "code": "def normal_noise(points):\n \"\"\"Init a noise variable.\"\"\"\n return np.random.rand(1) * np.random.randn(points, 1) \\\n + random.sample([2, -2], 1)", "code_tokens": "def normal_noise ( points ) : return np . random . rand ( 1 ) * np . random . randn ( points , 1 ) + random . sample ( [ 2 , - 2 ] , 1 )", "docstring_tokens": "Init a noise variable .", "label": 1, "retrieval_idx": 3344 }, { "idx": "cosqa-train-6655", "doc": "connect to python ftp server host", "code": "def connect(host, port, username, password):\n \"\"\"Connect and login to an FTP server and return ftplib.FTP object.\"\"\"\n # Instantiate ftplib client\n session = ftplib.FTP()\n\n # Connect to host without auth\n session.connect(host, port)\n\n # Authenticate connection\n session.login(username, password)\n return session", "code_tokens": "def connect ( host , port , username , password ) : # Instantiate ftplib client session = ftplib . FTP ( ) # Connect to host without auth session . connect ( host , port ) # Authenticate connection session . login ( username , password ) return session", "docstring_tokens": "Connect and login to an FTP server and return ftplib . FTP object .", "label": 1, "retrieval_idx": 350 }, { "idx": "cosqa-train-17671", "doc": "extract number of channels in an image python", "code": "def numchannels(samples:np.ndarray) -> int:\n \"\"\"\n return the number of channels present in samples\n\n samples: a numpy array as returned by sndread\n\n for multichannel audio, samples is always interleaved,\n meaning that samples[n] returns always a frame, which\n is either a single scalar for mono audio, or an array\n for multichannel audio.\n \"\"\"\n if len(samples.shape) == 1:\n return 1\n else:\n return samples.shape[1]", "code_tokens": "def numchannels ( samples : np . ndarray ) -> int : if len ( samples . shape ) == 1 : return 1 else : return samples . shape [ 1 ]", "docstring_tokens": "return the number of channels present in samples", "label": 1, "retrieval_idx": 5756 }, { "idx": "cosqa-train-17641", "doc": "how to create a sort key in python", "code": "def sort_key(x):\n \"\"\"\n >>> sort_key(('name', ('ROUTE', 'URL')))\n -3\n \"\"\"\n name, (r, u) = x\n return - len(u) + u.count('}') * 100", "code_tokens": "def sort_key ( x ) : name , ( r , u ) = x return - len ( u ) + u . count ( '}' ) * 100", "docstring_tokens": ">>> sort_key (( name ( ROUTE URL ))) - 3", "label": 1, "retrieval_idx": 5890 }, { "idx": "cosqa-train-17962", "doc": "calculate mid points between numbers python", "code": "def _mid(pt1, pt2):\n \"\"\"\n (Point, Point) -> Point\n Return the point that lies in between the two input points.\n \"\"\"\n (x0, y0), (x1, y1) = pt1, pt2\n return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "code_tokens": "def _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 )", "docstring_tokens": "( Point Point ) - > Point Return the point that lies in between the two input points .", "label": 1, "retrieval_idx": 5853 }, { "idx": "cosqa-train-12831", "doc": "call a list of dictinaries data from ajax in python flask", "code": "def convert_ajax_data(self, field_data):\n \"\"\"\n Due to the way Angular organizes it model, when this Form data is sent using Ajax,\n then for this kind of widget, the sent data has to be converted into a format suitable\n for Django's Form validation.\n \"\"\"\n data = [key for key, val in field_data.items() if val]\n return data", "code_tokens": "def convert_ajax_data ( self , field_data ) : data = [ key for key , val in field_data . items ( ) if val ] return data", "docstring_tokens": "Due to the way Angular organizes it model when this Form data is sent using Ajax then for this kind of widget the sent data has to be converted into a format suitable for Django s Form validation .", "label": 1, "retrieval_idx": 4888 }, { "idx": "cosqa-train-10881", "doc": "python function compare length of 2 strings", "code": "def count_string_diff(a,b):\n \"\"\"Return the number of characters in two strings that don't exactly match\"\"\"\n shortest = min(len(a), len(b))\n return sum(a[i] != b[i] for i in range(shortest))", "code_tokens": "def count_string_diff ( a , b ) : shortest = min ( len ( a ) , len ( b ) ) return sum ( a [ i ] != b [ i ] for i in range ( shortest ) )", "docstring_tokens": "Return the number of characters in two strings that don t exactly match", "label": 1, "retrieval_idx": 1824 }, { "idx": "cosqa-train-12311", "doc": "protobuf python dictionary f dictionary", "code": "def MessageToDict(message,\n including_default_value_fields=False,\n preserving_proto_field_name=False):\n \"\"\"Converts protobuf message to a JSON dictionary.\n\n Args:\n message: The protocol buffers message instance to serialize.\n including_default_value_fields: If True, singular primitive fields,\n repeated fields, and map fields will always be serialized. If\n False, only serialize non-empty fields. Singular message fields\n and oneof fields are not affected by this option.\n preserving_proto_field_name: If True, use the original proto field\n names as defined in the .proto file. If False, convert the field\n names to lowerCamelCase.\n\n Returns:\n A dict representation of the JSON formatted protocol buffer message.\n \"\"\"\n printer = _Printer(including_default_value_fields,\n preserving_proto_field_name)\n # pylint: disable=protected-access\n return printer._MessageToJsonObject(message)", "code_tokens": "def MessageToDict ( message , including_default_value_fields = False , preserving_proto_field_name = False ) : printer = _Printer ( including_default_value_fields , preserving_proto_field_name ) # pylint: disable=protected-access return printer . _MessageToJsonObject ( message )", "docstring_tokens": "Converts protobuf message to a JSON dictionary .", "label": 1, "retrieval_idx": 4806 }, { "idx": "cosqa-train-11007", "doc": "python get sort index numpy array", "code": "def argsort_indices(a, axis=-1):\n \"\"\"Like argsort, but returns an index suitable for sorting the\n the original array even if that array is multidimensional\n \"\"\"\n a = np.asarray(a)\n ind = list(np.ix_(*[np.arange(d) for d in a.shape]))\n ind[axis] = a.argsort(axis)\n return tuple(ind)", "code_tokens": "def argsort_indices ( a , axis = - 1 ) : a = np . asarray ( a ) ind = list ( np . ix_ ( * [ np . arange ( d ) for d in a . shape ] ) ) ind [ axis ] = a . argsort ( axis ) return tuple ( ind )", "docstring_tokens": "Like argsort but returns an index suitable for sorting the the original array even if that array is multidimensional", "label": 1, "retrieval_idx": 604 }, { "idx": "cosqa-train-6873", "doc": "python how to lemmatizer", "code": "def register_modele(self, modele: Modele):\n \"\"\" Register a modele onto the lemmatizer\n\n :param modele: Modele to register\n \"\"\"\n self.lemmatiseur._modeles[modele.gr()] = modele", "code_tokens": "def register_modele ( self , modele : Modele ) : self . lemmatiseur . _modeles [ modele . gr ( ) ] = modele", "docstring_tokens": "Register a modele onto the lemmatizer", "label": 1, "retrieval_idx": 662 }, { "idx": "cosqa-train-17967", "doc": "python histogram get number of bins", "code": "def shape(self) -> Tuple[int, ...]:\n \"\"\"Shape of histogram's data.\n\n Returns\n -------\n One-element tuple with the number of bins along each axis.\n \"\"\"\n return tuple(bins.bin_count for bins in self._binnings)", "code_tokens": "def shape ( self ) -> Tuple [ int , ... ] : return tuple ( bins . bin_count for bins in self . _binnings )", "docstring_tokens": "Shape of histogram s data .", "label": 1, "retrieval_idx": 5791 }, { "idx": "cosqa-train-8700", "doc": "check if array contains integer python", "code": "def is_int_vector(l):\n r\"\"\"Checks if l is a numpy array of integers\n\n \"\"\"\n if isinstance(l, np.ndarray):\n if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):\n return True\n return False", "code_tokens": "def is_int_vector ( l ) : if isinstance ( l , np . ndarray ) : if l . ndim == 1 and ( l . dtype . kind == 'i' or l . dtype . kind == 'u' ) : return True return False", "docstring_tokens": "r Checks if l is a numpy array of integers", "label": 1, "retrieval_idx": 1618 }, { "idx": "cosqa-train-10680", "doc": "best way to get key against a value from python dictionary", "code": "def get_key_by_value(dictionary, search_value):\n \"\"\"\n searchs a value in a dicionary and returns the key of the first occurrence\n\n :param dictionary: dictionary to search in\n :param search_value: value to search for\n \"\"\"\n for key, value in dictionary.iteritems():\n if value == search_value:\n return ugettext(key)", "code_tokens": "def get_key_by_value ( dictionary , search_value ) : for key , value in dictionary . iteritems ( ) : if value == search_value : return ugettext ( key )", "docstring_tokens": "searchs a value in a dicionary and returns the key of the first occurrence", "label": 1, "retrieval_idx": 1056 }, { "idx": "cosqa-train-15005", "doc": "python datetime to microseconds since epoch", "code": "def _DateToEpoch(date):\n \"\"\"Converts python datetime to epoch microseconds.\"\"\"\n tz_zero = datetime.datetime.utcfromtimestamp(0)\n diff_sec = int((date - tz_zero).total_seconds())\n return diff_sec * 1000000", "code_tokens": "def _DateToEpoch ( date ) : tz_zero = datetime . datetime . utcfromtimestamp ( 0 ) diff_sec = int ( ( date - tz_zero ) . total_seconds ( ) ) return diff_sec * 1000000", "docstring_tokens": "Converts python datetime to epoch microseconds .", "label": 1, "retrieval_idx": 1707 }, { "idx": "cosqa-train-13836", "doc": "how to know the proxies in a browser python", "code": "def _GetProxies(self):\n \"\"\"Gather a list of proxies to use.\"\"\"\n # Detect proxies from the OS environment.\n result = client_utils.FindProxies()\n\n # Also try to connect directly if all proxies fail.\n result.append(\"\")\n\n # Also try all proxies configured in the config system.\n result.extend(config.CONFIG[\"Client.proxy_servers\"])\n\n return result", "code_tokens": "def _GetProxies ( self ) : # Detect proxies from the OS environment. result = client_utils . FindProxies ( ) # Also try to connect directly if all proxies fail. result . append ( \"\" ) # Also try all proxies configured in the config system. result . extend ( config . CONFIG [ \"Client.proxy_servers\" ] ) return result", "docstring_tokens": "Gather a list of proxies to use .", "label": 1, "retrieval_idx": 5065 }, { "idx": "cosqa-train-17261", "doc": "how to execute async in python", "code": "def _run_sync(self, method: Callable, *args, **kwargs) -> Any:\n \"\"\"\n Utility method to run commands synchronously for testing.\n \"\"\"\n if self.loop.is_running():\n raise RuntimeError(\"Event loop is already running.\")\n\n if not self.is_connected:\n self.loop.run_until_complete(self.connect())\n\n task = asyncio.Task(method(*args, **kwargs), loop=self.loop)\n result = self.loop.run_until_complete(task)\n\n self.loop.run_until_complete(self.quit())\n\n return result", "code_tokens": "def _run_sync ( self , method : Callable , * args , * * kwargs ) -> Any : if self . loop . is_running ( ) : raise RuntimeError ( \"Event loop is already running.\" ) if not self . is_connected : self . loop . run_until_complete ( self . connect ( ) ) task = asyncio . Task ( method ( * args , * * kwargs ) , loop = self . loop ) result = self . loop . run_until_complete ( task ) self . loop . run_until_complete ( self . quit ( ) ) return result", "docstring_tokens": "Utility method to run commands synchronously for testing .", "label": 1, "retrieval_idx": 5681 }, { "idx": "cosqa-train-10906", "doc": "cross validation python without sklearn", "code": "def check_cv(self, y):\n \"\"\"Resolve which cross validation strategy is used.\"\"\"\n y_arr = None\n if self.stratified:\n # Try to convert y to numpy for sklearn's check_cv; if conversion\n # doesn't work, still try.\n try:\n y_arr = to_numpy(y)\n except (AttributeError, TypeError):\n y_arr = y\n\n if self._is_float(self.cv):\n return self._check_cv_float()\n return self._check_cv_non_float(y_arr)", "code_tokens": "def check_cv ( self , y ) : y_arr = None if self . stratified : # Try to convert y to numpy for sklearn's check_cv; if conversion # doesn't work, still try. try : y_arr = to_numpy ( y ) except ( AttributeError , TypeError ) : y_arr = y if self . _is_float ( self . cv ) : return self . _check_cv_float ( ) return self . _check_cv_non_float ( y_arr )", "docstring_tokens": "Resolve which cross validation strategy is used .", "label": 1, "retrieval_idx": 4567 }, { "idx": "cosqa-train-12340", "doc": "remove zeros from a list in python", "code": "def _remove_blank(l):\n \"\"\" Removes trailing zeros in the list of integers and returns a new list of integers\"\"\"\n ret = []\n for i, _ in enumerate(l):\n if l[i] == 0:\n break\n ret.append(l[i])\n return ret", "code_tokens": "def _remove_blank ( l ) : ret = [ ] for i , _ in enumerate ( l ) : if l [ i ] == 0 : break ret . append ( l [ i ] ) return ret", "docstring_tokens": "Removes trailing zeros in the list of integers and returns a new list of integers", "label": 1, "retrieval_idx": 1006 }, { "idx": "cosqa-train-4698", "doc": "python grab every n elements", "code": "def split_every(iterable, n): # TODO: Remove this, or make it return a generator.\n \"\"\"\n A generator of n-length chunks of an input iterable\n \"\"\"\n i = iter(iterable)\n piece = list(islice(i, n))\n while piece:\n yield piece\n piece = list(islice(i, n))", "code_tokens": "def split_every ( iterable , n ) : # TODO: Remove this, or make it return a generator. i = iter ( iterable ) piece = list ( islice ( i , n ) ) while piece : yield piece piece = list ( islice ( i , n ) )", "docstring_tokens": "A generator of n - length chunks of an input iterable", "label": 1, "retrieval_idx": 2914 }, { "idx": "cosqa-dev-537", "doc": "how to do dot product vectors in python", "code": "def dot_v3(v, w):\n \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n return sum([x * y for x, y in zip(v, w)])", "code_tokens": "def dot_v3 ( v , w ) : return sum ( [ x * y for x , y in zip ( v , w ) ] )", "docstring_tokens": "Return the dotproduct of two vectors .", "label": 1, "retrieval_idx": 871 }, { "idx": "cosqa-train-2408", "doc": "python garbage collector how to delete unnecessary", "code": "def detach_all(self):\n \"\"\"\n Detach from all tracked classes and objects.\n Restore the original constructors and cleanse the tracking lists.\n \"\"\"\n self.detach_all_classes()\n self.objects.clear()\n self.index.clear()\n self._keepalive[:] = []", "code_tokens": "def detach_all ( self ) : self . detach_all_classes ( ) self . objects . clear ( ) self . index . clear ( ) self . _keepalive [ : ] = [ ]", "docstring_tokens": "Detach from all tracked classes and objects . Restore the original constructors and cleanse the tracking lists .", "label": 1, "retrieval_idx": 1842 }, { "idx": "cosqa-train-12597", "doc": "python check if row contains none", "code": "def is_valid_row(cls, row):\n \"\"\"Indicates whether or not the given row contains valid data.\"\"\"\n for k in row.keys():\n if row[k] is None:\n return False\n return True", "code_tokens": "def is_valid_row ( cls , row ) : for k in row . keys ( ) : if row [ k ] is None : return False return True", "docstring_tokens": "Indicates whether or not the given row contains valid data .", "label": 1, "retrieval_idx": 1620 }, { "idx": "cosqa-train-13988", "doc": "how to remove border in image in python", "code": "def border(self):\n \"\"\"Region formed by taking border elements.\n\n :returns: :class:`jicimagelib.region.Region`\n \"\"\"\n\n border_array = self.bitmap - self.inner.bitmap\n return Region(border_array)", "code_tokens": "def border ( self ) : border_array = self . bitmap - self . inner . bitmap return Region ( border_array )", "docstring_tokens": "Region formed by taking border elements .", "label": 1, "retrieval_idx": 3568 }, { "idx": "cosqa-train-11754", "doc": "python regex substitute from dictionary", "code": "def substitute(dict_, source):\n \"\"\" Perform re.sub with the patterns in the given dict\n Args:\n dict_: {pattern: repl}\n source: str\n \"\"\"\n d_esc = (re.escape(k) for k in dict_.keys())\n pattern = re.compile('|'.join(d_esc))\n return pattern.sub(lambda x: dict_[x.group()], source)", "code_tokens": "def substitute ( dict_ , source ) : d_esc = ( re . escape ( k ) for k in dict_ . keys ( ) ) pattern = re . compile ( '|' . join ( d_esc ) ) return pattern . sub ( lambda x : dict_ [ x . group ( ) ] , source )", "docstring_tokens": "Perform re . sub with the patterns in the given dict Args : dict_ : { pattern : repl } source : str", "label": 1, "retrieval_idx": 4713 }, { "idx": "cosqa-train-10463", "doc": "python change directory decorate", "code": "def change_dir(directory):\n \"\"\"\n Wraps a function to run in a given directory.\n\n \"\"\"\n def cd_decorator(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n org_path = os.getcwd()\n os.chdir(directory)\n func(*args, **kwargs)\n os.chdir(org_path)\n return wrapper\n return cd_decorator", "code_tokens": "def change_dir ( directory ) : def cd_decorator ( func ) : @ wraps ( func ) def wrapper ( * args , * * kwargs ) : org_path = os . getcwd ( ) os . chdir ( directory ) func ( * args , * * kwargs ) os . chdir ( org_path ) return wrapper return cd_decorator", "docstring_tokens": "Wraps a function to run in a given directory .", "label": 1, "retrieval_idx": 2811 }, { "idx": "cosqa-train-7461", "doc": "python register a service", "code": "def register_service(self, service):\n \"\"\"\n Register service into the system. Called by Services.\n \"\"\"\n if service not in self.services:\n self.services.append(service)", "code_tokens": "def register_service ( self , service ) : if service not in self . services : self . services . append ( service )", "docstring_tokens": "Register service into the system . Called by Services .", "label": 1, "retrieval_idx": 3784 }, { "idx": "cosqa-train-16042", "doc": "how to make a str all lowercasein python", "code": "def to_camel(s):\n \"\"\"\n :param string s: under_scored string to be CamelCased\n :return: CamelCase version of input\n :rtype: str\n \"\"\"\n # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)", "code_tokens": "def to_camel ( s ) : # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups return re . sub ( r'_([a-zA-Z])' , lambda m : m . group ( 1 ) . upper ( ) , '_' + s )", "docstring_tokens": ": param string s : under_scored string to be CamelCased : return : CamelCase version of input : rtype : str", "label": 1, "retrieval_idx": 3683 }, { "idx": "cosqa-train-1815", "doc": "python 3 slice function", "code": "def Slice(a, begin, size):\n \"\"\"\n Slicing op.\n \"\"\"\n return np.copy(a)[[slice(*tpl) for tpl in zip(begin, begin+size)]],", "code_tokens": "def Slice ( a , begin , size ) : return np . copy ( a ) [ [ slice ( * tpl ) for tpl in zip ( begin , begin + size ) ] ] ,", "docstring_tokens": "Slicing op .", "label": 1, "retrieval_idx": 1486 }, { "idx": "cosqa-train-10647", "doc": "apply a list of functions python", "code": "def compose(*funcs):\n \"\"\"compose a list of functions\"\"\"\n return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)", "code_tokens": "def compose ( * funcs ) : return lambda x : reduce ( lambda v , f : f ( v ) , reversed ( funcs ) , x )", "docstring_tokens": "compose a list of functions", "label": 1, "retrieval_idx": 1578 }, { "idx": "cosqa-train-11306", "doc": "how to add size on the python", "code": "def calculate_size(name, replace_existing_values):\n \"\"\" Calculates the request payload size\"\"\"\n data_size = 0\n data_size += calculate_size_str(name)\n data_size += BOOLEAN_SIZE_IN_BYTES\n return data_size", "code_tokens": "def calculate_size ( name , replace_existing_values ) : data_size = 0 data_size += calculate_size_str ( name ) data_size += BOOLEAN_SIZE_IN_BYTES return data_size", "docstring_tokens": "Calculates the request payload size", "label": 1, "retrieval_idx": 4632 }, { "idx": "cosqa-train-13579", "doc": "how to clear a frame in python", "code": "def reset(self):\n \"\"\"Reset analyzer state\n \"\"\"\n self.prevframe = None\n self.wasmoving = False\n self.t0 = 0\n self.ismoving = False", "code_tokens": "def reset ( self ) : self . prevframe = None self . wasmoving = False self . t0 = 0 self . ismoving = False", "docstring_tokens": "Reset analyzer state", "label": 1, "retrieval_idx": 2156 }, { "idx": "cosqa-train-7228", "doc": "python not (condition1 and condition2)", "code": "def _not(condition=None, **kwargs):\n \"\"\"\n Return the opposite of input condition.\n\n :param condition: condition to process.\n\n :result: not condition.\n :rtype: bool\n \"\"\"\n\n result = True\n\n if condition is not None:\n result = not run(condition, **kwargs)\n\n return result", "code_tokens": "def _not ( condition = None , * * kwargs ) : result = True if condition is not None : result = not run ( condition , * * kwargs ) return result", "docstring_tokens": "Return the opposite of input condition .", "label": 1, "retrieval_idx": 18 }, { "idx": "cosqa-train-2086", "doc": "python check valid attribute names", "code": "def _validate_key(self, key):\n \"\"\"Returns a boolean indicating if the attribute name is valid or not\"\"\"\n return not any([key.startswith(i) for i in self.EXCEPTIONS])", "code_tokens": "def _validate_key ( self , key ) : return not any ( [ key . startswith ( i ) for i in self . EXCEPTIONS ] )", "docstring_tokens": "Returns a boolean indicating if the attribute name is valid or not", "label": 1, "retrieval_idx": 1653 }, { "idx": "cosqa-train-6783", "doc": "python get the date of creation of file", "code": "def get_creation_datetime(filepath):\n \"\"\"\n Get the date that a file was created.\n\n Parameters\n ----------\n filepath : str\n\n Returns\n -------\n creation_datetime : datetime.datetime or None\n \"\"\"\n if platform.system() == 'Windows':\n return datetime.fromtimestamp(os.path.getctime(filepath))\n else:\n stat = os.stat(filepath)\n try:\n return datetime.fromtimestamp(stat.st_birthtime)\n except AttributeError:\n # We're probably on Linux. No easy way to get creation dates here,\n # so we'll settle for when its content was last modified.\n return None", "code_tokens": "def get_creation_datetime ( filepath ) : if platform . system ( ) == 'Windows' : return datetime . fromtimestamp ( os . path . getctime ( filepath ) ) else : stat = os . stat ( filepath ) try : return datetime . fromtimestamp ( stat . st_birthtime ) except AttributeError : # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. return None", "docstring_tokens": "Get the date that a file was created .", "label": 1, "retrieval_idx": 3577 }, { "idx": "cosqa-train-3720", "doc": "make values as strings in a list in python", "code": "def vectorize(values):\n \"\"\"\n Takes a value or list of values and returns a single result, joined by \",\"\n if necessary.\n \"\"\"\n if isinstance(values, list):\n return ','.join(str(v) for v in values)\n return values", "code_tokens": "def vectorize ( values ) : if isinstance ( values , list ) : return ',' . join ( str ( v ) for v in values ) return values", "docstring_tokens": "Takes a value or list of values and returns a single result joined by if necessary .", "label": 1, "retrieval_idx": 2504 }, { "idx": "cosqa-train-18863", "doc": "how to check if memory leak in python program", "code": "def memory_full():\n \"\"\"Check if the memory is too full for further caching.\"\"\"\n current_process = psutil.Process(os.getpid())\n return (current_process.memory_percent() >\n config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)", "code_tokens": "def memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )", "docstring_tokens": "Check if the memory is too full for further caching .", "label": 1, "retrieval_idx": 5684 }, { "idx": "cosqa-train-8196", "doc": "python assert data type check if array type", "code": "def _assert_is_type(name, value, value_type):\n \"\"\"Assert that a value must be a given type.\"\"\"\n if not isinstance(value, value_type):\n if type(value_type) is tuple:\n types = ', '.join(t.__name__ for t in value_type)\n raise ValueError('{0} must be one of ({1})'.format(name, types))\n else:\n raise ValueError('{0} must be {1}'\n .format(name, value_type.__name__))", "code_tokens": "def _assert_is_type ( name , value , value_type ) : if not isinstance ( value , value_type ) : if type ( value_type ) is tuple : types = ', ' . join ( t . __name__ for t in value_type ) raise ValueError ( '{0} must be one of ({1})' . format ( name , types ) ) else : raise ValueError ( '{0} must be {1}' . format ( name , value_type . __name__ ) )", "docstring_tokens": "Assert that a value must be a given type .", "label": 1, "retrieval_idx": 1519 }, { "idx": "cosqa-train-18243", "doc": "how to check column value is null python", "code": "def is_not_null(df: DataFrame, col_name: str) -> bool:\n \"\"\"\n Return ``True`` if the given DataFrame has a column of the given\n name (string), and there exists at least one non-NaN value in that\n column; return ``False`` otherwise.\n \"\"\"\n if (\n isinstance(df, pd.DataFrame)\n and col_name in df.columns\n and df[col_name].notnull().any()\n ):\n return True\n else:\n return False", "code_tokens": "def is_not_null ( df : DataFrame , col_name : str ) -> bool : if ( isinstance ( df , pd . DataFrame ) and col_name in df . columns and df [ col_name ] . notnull ( ) . any ( ) ) : return True else : return False", "docstring_tokens": "Return True if the given DataFrame has a column of the given name ( string ) and there exists at least one non - NaN value in that column ; return False otherwise .", "label": 1, "retrieval_idx": 5659 }, { "idx": "cosqa-train-5613", "doc": "python sql server query date to datetime object", "code": "def from_pydatetime(cls, pydatetime):\n \"\"\"\n Creates sql datetime2 object from Python datetime object\n ignoring timezone\n @param pydatetime: Python datetime object\n @return: sql datetime2 object\n \"\"\"\n return cls(date=Date.from_pydate(pydatetime.date),\n time=Time.from_pytime(pydatetime.time))", "code_tokens": "def from_pydatetime ( cls , pydatetime ) : return cls ( date = Date . from_pydate ( pydatetime . date ) , time = Time . from_pytime ( pydatetime . time ) )", "docstring_tokens": "Creates sql datetime2 object from Python datetime object ignoring timezone", "label": 1, "retrieval_idx": 2647 }, { "idx": "cosqa-train-11293", "doc": "python json print tree", "code": "def prettyprint(d):\n \"\"\"Print dicttree in Json-like format. keys are sorted\n \"\"\"\n print(json.dumps(d, sort_keys=True, \n indent=4, separators=(\",\" , \": \")))", "code_tokens": "def prettyprint ( d ) : print ( json . dumps ( d , sort_keys = True , indent = 4 , separators = ( \",\" , \": \" ) ) )", "docstring_tokens": "Print dicttree in Json - like format . keys are sorted", "label": 1, "retrieval_idx": 2227 }, { "idx": "cosqa-train-15992", "doc": "how to give x axis limits in python plot", "code": "def set_xlimits(self, row, column, min=None, max=None):\n \"\"\"Set x-axis limits of a subplot.\n\n :param row,column: specify the subplot.\n :param min: minimal axis value\n :param max: maximum axis value\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.set_xlimits(min, max)", "code_tokens": "def set_xlimits ( self , row , column , min = None , max = None ) : subplot = self . get_subplot_at ( row , column ) subplot . set_xlimits ( min , max )", "docstring_tokens": "Set x - axis limits of a subplot .", "label": 1, "retrieval_idx": 3455 }, { "idx": "cosqa-dev-183", "doc": "compute l2 norm in python", "code": "def l2_norm(params):\n \"\"\"Computes l2 norm of params by flattening them into a vector.\"\"\"\n flattened, _ = flatten(params)\n return np.dot(flattened, flattened)", "code_tokens": "def l2_norm ( params ) : flattened , _ = flatten ( params ) return np . dot ( flattened , flattened )", "docstring_tokens": "Computes l2 norm of params by flattening them into a vector .", "label": 1, "retrieval_idx": 3651 }, { "idx": "cosqa-train-13850", "doc": "how to log a variable without knowing its type in python", "code": "def info(self, text):\n\t\t\"\"\" Ajout d'un message de log de type INFO \"\"\"\n\t\tself.logger.info(\"{}{}\".format(self.message_prefix, text))", "code_tokens": "def info ( self , text ) : self . logger . info ( \"{}{}\" . format ( self . message_prefix , text ) )", "docstring_tokens": "Ajout d un message de log de type INFO", "label": 1, "retrieval_idx": 3865 }, { "idx": "cosqa-train-18125", "doc": "python map, delete key", "code": "def __remove_method(m: lmap.Map, key: T) -> lmap.Map:\n \"\"\"Swap the methods atom to remove method with key.\"\"\"\n return m.dissoc(key)", "code_tokens": "def __remove_method ( m : lmap . Map , key : T ) -> lmap . Map : return m . dissoc ( key )", "docstring_tokens": "Swap the methods atom to remove method with key .", "label": 1, "retrieval_idx": 5911 }, { "idx": "cosqa-train-10987", "doc": "dictionarry type from python to c++", "code": "def struct2dict(struct):\n \"\"\"convert a ctypes structure to a dictionary\"\"\"\n return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}", "code_tokens": "def struct2dict ( struct ) : return { x : getattr ( struct , x ) for x in dict ( struct . _fields_ ) . keys ( ) }", "docstring_tokens": "convert a ctypes structure to a dictionary", "label": 1, "retrieval_idx": 3597 }, { "idx": "cosqa-train-10674", "doc": "axes3d view setting python 3", "code": "def plot3d_init(fignum):\n \"\"\"\n initializes 3D plot\n \"\"\"\n from mpl_toolkits.mplot3d import Axes3D\n fig = plt.figure(fignum)\n ax = fig.add_subplot(111, projection='3d')\n return ax", "code_tokens": "def plot3d_init ( fignum ) : from mpl_toolkits . mplot3d import Axes3D fig = plt . figure ( fignum ) ax = fig . add_subplot ( 111 , projection = '3d' ) return ax", "docstring_tokens": "initializes 3D plot", "label": 1, "retrieval_idx": 3693 }, { "idx": "cosqa-train-15321", "doc": "python get month start and end date by month and year", "code": "def get_month_start_end_day():\n \"\"\"\n Get the month start date a nd end date\n \"\"\"\n t = date.today()\n n = mdays[t.month]\n return (date(t.year, t.month, 1), date(t.year, t.month, n))", "code_tokens": "def get_month_start_end_day ( ) : t = date . today ( ) n = mdays [ t . month ] return ( date ( t . year , t . month , 1 ) , date ( t . year , t . month , n ) )", "docstring_tokens": "Get the month start date a nd end date", "label": 1, "retrieval_idx": 405 }, { "idx": "cosqa-train-16144", "doc": "python set that can take repeats", "code": "def delete_duplicates(seq):\n \"\"\"\n Remove duplicates from an iterable, preserving the order.\n\n Args:\n seq: Iterable of various type.\n\n Returns:\n list: List of unique objects.\n\n \"\"\"\n seen = set()\n seen_add = seen.add\n return [x for x in seq if not (x in seen or seen_add(x))]", "code_tokens": "def delete_duplicates ( seq ) : seen = set ( ) seen_add = seen . add return [ x for x in seq if not ( x in seen or seen_add ( x ) ) ]", "docstring_tokens": "Remove duplicates from an iterable preserving the order .", "label": 1, "retrieval_idx": 394 }, { "idx": "cosqa-train-15205", "doc": "python flask request get form name", "code": "def parse_form(self, req, name, field):\n \"\"\"Pull a form value from the request.\"\"\"\n return get_value(req.body_arguments, name, field)", "code_tokens": "def parse_form ( self , req , name , field ) : return get_value ( req . body_arguments , name , field )", "docstring_tokens": "Pull a form value from the request .", "label": 1, "retrieval_idx": 1464 }, { "idx": "cosqa-train-343", "doc": "python for comprehension sum", "code": "def _accumulate(sequence, func):\n \"\"\"\n Python2 accumulate implementation taken from\n https://docs.python.org/3/library/itertools.html#itertools.accumulate\n \"\"\"\n iterator = iter(sequence)\n total = next(iterator)\n yield total\n for element in iterator:\n total = func(total, element)\n yield total", "code_tokens": "def _accumulate ( sequence , func ) : iterator = iter ( sequence ) total = next ( iterator ) yield total for element in iterator : total = func ( total , element ) yield total", "docstring_tokens": "Python2 accumulate implementation taken from https : // docs . python . org / 3 / library / itertools . html#itertools . accumulate", "label": 1, "retrieval_idx": 325 }, { "idx": "cosqa-train-8679", "doc": "python draw image frombyte array", "code": "def from_bytes(cls, b):\n\t\t\"\"\"Create :class:`PNG` from raw bytes.\n\t\t\n\t\t:arg bytes b: The raw bytes of the PNG file.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\tim = cls()\n\t\tim.chunks = list(parse_chunks(b))\n\t\tim.init()\n\t\treturn im", "code_tokens": "def from_bytes ( cls , b ) : im = cls ( ) im . chunks = list ( parse_chunks ( b ) ) im . init ( ) return im", "docstring_tokens": "Create : class : PNG from raw bytes . : arg bytes b : The raw bytes of the PNG file . : rtype : : class : PNG", "label": 1, "retrieval_idx": 907 }, { "idx": "cosqa-train-13081", "doc": "python get file last modified time datetime", "code": "def get_time(filename):\n\t\"\"\"\n\tGet the modified time for a file as a datetime instance\n\t\"\"\"\n\tts = os.stat(filename).st_mtime\n\treturn datetime.datetime.utcfromtimestamp(ts)", "code_tokens": "def get_time ( filename ) : ts = os . stat ( filename ) . st_mtime return datetime . datetime . utcfromtimestamp ( ts )", "docstring_tokens": "Get the modified time for a file as a datetime instance", "label": 1, "retrieval_idx": 1794 }, { "idx": "cosqa-train-8766", "doc": "python first line from file", "code": "def getfirstline(file, default):\n \"\"\"\n Returns the first line of a file.\n \"\"\"\n with open(file, 'rb') as fh:\n content = fh.readlines()\n if len(content) == 1:\n return content[0].decode('utf-8').strip('\\n')\n\n return default", "code_tokens": "def getfirstline ( file , default ) : with open ( file , 'rb' ) as fh : content = fh . readlines ( ) if len ( content ) == 1 : return content [ 0 ] . decode ( 'utf-8' ) . strip ( '\\n' ) return default", "docstring_tokens": "Returns the first line of a file .", "label": 1, "retrieval_idx": 971 }, { "idx": "cosqa-train-12454", "doc": "python break list into batches of 50", "code": "def batch(items, size):\n \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n batch size.\"\"\"\n return [items[x:x + size] for x in xrange(0, len(items), size)]", "code_tokens": "def batch ( items , size ) : return [ items [ x : x + size ] for x in xrange ( 0 , len ( items ) , size ) ]", "docstring_tokens": "Batches a list into a list of lists with sub - lists sized by a specified batch size .", "label": 1, "retrieval_idx": 654 }, { "idx": "cosqa-train-9774", "doc": "how to see all python versions", "code": "def all_versions(req):\n \"\"\"Get all versions of req from PyPI.\"\"\"\n import requests\n url = \"https://pypi.python.org/pypi/\" + req + \"/json\"\n return tuple(requests.get(url).json()[\"releases\"].keys())", "code_tokens": "def all_versions ( req ) : import requests url = \"https://pypi.python.org/pypi/\" + req + \"/json\" return tuple ( requests . get ( url ) . json ( ) [ \"releases\" ] . keys ( ) )", "docstring_tokens": "Get all versions of req from PyPI .", "label": 1, "retrieval_idx": 4321 }, { "idx": "cosqa-train-9835", "doc": "how to sort a list in alphabetic order python", "code": "def natural_sort(list, key=lambda s:s):\n \"\"\"\n Sort the list into natural alphanumeric order.\n \"\"\"\n def get_alphanum_key_func(key):\n convert = lambda text: int(text) if text.isdigit() else text\n return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))]\n sort_key = get_alphanum_key_func(key)\n list.sort(key=sort_key)", "code_tokens": "def natural_sort ( list , key = lambda s : s ) : def get_alphanum_key_func ( key ) : convert = lambda text : int ( text ) if text . isdigit ( ) else text return lambda s : [ convert ( c ) for c in re . split ( '([0-9]+)' , key ( s ) ) ] sort_key = get_alphanum_key_func ( key ) list . sort ( key = sort_key )", "docstring_tokens": "Sort the list into natural alphanumeric order .", "label": 1, "retrieval_idx": 4334 }, { "idx": "cosqa-train-12074", "doc": "python test path exists", "code": "def _pip_exists(self):\n \"\"\"Returns True if pip exists inside the virtual environment. Can be\n used as a naive way to verify that the environment is installed.\"\"\"\n return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "code_tokens": "def _pip_exists ( self ) : return os . path . isfile ( os . path . join ( self . path , 'bin' , 'pip' ) )", "docstring_tokens": "Returns True if pip exists inside the virtual environment . Can be used as a naive way to verify that the environment is installed .", "label": 1, "retrieval_idx": 239 }, { "idx": "cosqa-train-14676", "doc": "python check if object has attribute and if it is not none", "code": "def hasattrs(object, *names):\n \"\"\"\n Takes in an object and a variable length amount of named attributes,\n and checks to see if the object has each property. If any of the\n attributes are missing, this returns false.\n\n :param object: an object that may or may not contain the listed attributes\n :param names: a variable amount of attribute names to check for\n :return: True if the object contains each named attribute, false otherwise\n \"\"\"\n for name in names:\n if not hasattr(object, name):\n return False\n return True", "code_tokens": "def hasattrs ( object , * names ) : for name in names : if not hasattr ( object , name ) : return False return True", "docstring_tokens": "Takes in an object and a variable length amount of named attributes and checks to see if the object has each property . If any of the attributes are missing this returns false .", "label": 1, "retrieval_idx": 178 }, { "idx": "cosqa-train-18994", "doc": "changing from list to string in python", "code": "def list_to_str(list, separator=','):\n \"\"\"\n >>> list = [0, 0, 7]\n >>> list_to_str(list)\n '0,0,7'\n \"\"\"\n list = [str(x) for x in list]\n return separator.join(list)", "code_tokens": "def list_to_str ( list , separator = ',' ) : list = [ str ( x ) for x in list ] return separator . join ( list )", "docstring_tokens": ">>> list = [ 0 0 7 ] >>> list_to_str ( list ) 0 0 7", "label": 1, "retrieval_idx": 5700 }, { "idx": "cosqa-train-18856", "doc": "easy way to check is a boolean has changed in python", "code": "def needs_check(self):\n \"\"\"\n Check if enough time has elapsed to perform a check().\n\n If this time has elapsed, a state change check through\n has_state_changed() should be performed and eventually a sync().\n\n :rtype: boolean\n \"\"\"\n if self.lastcheck is None:\n return True\n return time.time() - self.lastcheck >= self.ipchangedetection_sleep", "code_tokens": "def needs_check ( self ) : if self . lastcheck is None : return True return time . time ( ) - self . lastcheck >= self . ipchangedetection_sleep", "docstring_tokens": "Check if enough time has elapsed to perform a check () .", "label": 1, "retrieval_idx": 6125 }, { "idx": "cosqa-train-11191", "doc": "get result from cursor python", "code": "def execute(self, cmd, *args, **kwargs):\n \"\"\" Execute the SQL command and return the data rows as tuples\n \"\"\"\n self.cursor.execute(cmd, *args, **kwargs)", "code_tokens": "def execute ( self , cmd , * args , * * kwargs ) : self . cursor . execute ( cmd , * args , * * kwargs )", "docstring_tokens": "Execute the SQL command and return the data rows as tuples", "label": 1, "retrieval_idx": 4611 }, { "idx": "cosqa-train-8861", "doc": "python get current loggers", "code": "def _get_loggers():\n \"\"\"Return list of Logger classes.\"\"\"\n from .. import loader\n modules = loader.get_package_modules('logger')\n return list(loader.get_plugins(modules, [_Logger]))", "code_tokens": "def _get_loggers ( ) : from . . import loader modules = loader . get_package_modules ( 'logger' ) return list ( loader . get_plugins ( modules , [ _Logger ] ) )", "docstring_tokens": "Return list of Logger classes .", "label": 1, "retrieval_idx": 1928 }, { "idx": "cosqa-train-9435", "doc": "python parse date strptime day of month no padd", "code": "def parse(self, s):\n \"\"\"\n Parses a date string formatted like ``YYYY-MM-DD``.\n \"\"\"\n return datetime.datetime.strptime(s, self.date_format).date()", "code_tokens": "def parse ( self , s ) : return datetime . datetime . strptime ( s , self . date_format ) . date ( )", "docstring_tokens": "Parses a date string formatted like YYYY - MM - DD .", "label": 1, "retrieval_idx": 107 }, { "idx": "cosqa-train-16197", "doc": "how to return the type of an object in python", "code": "def is_integer(obj):\n \"\"\"Is this an integer.\n\n :param object obj:\n :return:\n \"\"\"\n if PYTHON3:\n return isinstance(obj, int)\n return isinstance(obj, (int, long))", "code_tokens": "def is_integer ( obj ) : if PYTHON3 : return isinstance ( obj , int ) return isinstance ( obj , ( int , long ) )", "docstring_tokens": "Is this an integer .", "label": 1, "retrieval_idx": 2128 }, { "idx": "cosqa-train-7375", "doc": "how to get the first and last index of element in list python", "code": "def bisect_index(a, x):\n \"\"\" Find the leftmost index of an element in a list using binary search.\n\n Parameters\n ----------\n a: list\n A sorted list.\n x: arbitrary\n The element.\n\n Returns\n -------\n int\n The index.\n\n \"\"\"\n i = bisect.bisect_left(a, x)\n if i != len(a) and a[i] == x:\n return i\n raise ValueError", "code_tokens": "def bisect_index ( a , x ) : i = bisect . bisect_left ( a , x ) if i != len ( a ) and a [ i ] == x : return i raise ValueError", "docstring_tokens": "Find the leftmost index of an element in a list using binary search .", "label": 1, "retrieval_idx": 1588 }, { "idx": "cosqa-train-13709", "doc": "how to get a document in a collection using mongoengine api server in python", "code": "def find_one(cls, *args, **kw):\n\t\t\"\"\"Get a single document from the collection this class is bound to.\n\t\t\n\t\tAdditional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional\n\t\tparameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword\n\t\targuments passed along with minor transformation.\n\t\t\n\t\tAutomatically calls `to_mongo` with the retrieved data.\n\t\t\n\t\thttps://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one\n\t\t\"\"\"\n\t\t\n\t\tif len(args) == 1 and not isinstance(args[0], Filter):\n\t\t\targs = (getattr(cls, cls.__pk__) == args[0], )\n\t\t\n\t\tDoc, collection, query, options = cls._prepare_find(*args, **kw)\n\t\tresult = Doc.from_mongo(collection.find_one(query, **options))\n\t\t\n\t\treturn result", "code_tokens": "def find_one ( cls , * args , * * kw ) : if len ( args ) == 1 and not isinstance ( args [ 0 ] , Filter ) : args = ( getattr ( cls , cls . __pk__ ) == args [ 0 ] , ) Doc , collection , query , options = cls . _prepare_find ( * args , * * kw ) result = Doc . from_mongo ( collection . find_one ( query , * * options ) ) return result", "docstring_tokens": "Get a single document from the collection this class is bound to . Additional arguments are processed according to _prepare_find prior to passing to PyMongo where positional parameters are interpreted as query fragments parametric keyword arguments combined and other keyword arguments passed along with minor transformation . Automatically calls to_mongo with the retrieved data . https : // api . mongodb . com / python / current / api / pymongo / collection . html#pymongo . collection . Collection . find_one", "label": 1, "retrieval_idx": 4414 }, { "idx": "cosqa-train-13133", "doc": "doctype html parse python", "code": "def parse(text, showToc=True):\n\t\"\"\"Returns HTML from MediaWiki markup\"\"\"\n\tp = Parser(show_toc=showToc)\n\treturn p.parse(text)", "code_tokens": "def parse ( text , showToc = True ) : p = Parser ( show_toc = showToc ) return p . parse ( text )", "docstring_tokens": "Returns HTML from MediaWiki markup", "label": 1, "retrieval_idx": 4798 }, { "idx": "cosqa-train-13001", "doc": "python full screen adjust to the screen", "code": "def update_screen(self):\n \"\"\"Refresh the screen. You don't need to override this except to update only small portins of the screen.\"\"\"\n self.clock.tick(self.FPS)\n pygame.display.update()", "code_tokens": "def update_screen ( self ) : self . clock . tick ( self . FPS ) pygame . display . update ( )", "docstring_tokens": "Refresh the screen . You don t need to override this except to update only small portins of the screen .", "label": 1, "retrieval_idx": 1913 }, { "idx": "cosqa-train-7669", "doc": "how to set default values in dict python", "code": "def setDictDefaults (d, defaults):\n \"\"\"Sets all defaults for the given dictionary to those contained in a\n second defaults dictionary. This convenience method calls:\n\n d.setdefault(key, value)\n\n for each key and value in the given defaults dictionary.\n \"\"\"\n for key, val in defaults.items():\n d.setdefault(key, val)\n\n return d", "code_tokens": "def setDictDefaults ( d , defaults ) : for key , val in defaults . items ( ) : d . setdefault ( key , val ) return d", "docstring_tokens": "Sets all defaults for the given dictionary to those contained in a second defaults dictionary . This convenience method calls :", "label": 1, "retrieval_idx": 3846 }, { "idx": "cosqa-train-11996", "doc": "image segmentation kmeans python", "code": "def region_from_segment(image, segment):\n \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n x, y, w, h = segment\n return image[y:y + h, x:x + w]", "code_tokens": "def region_from_segment ( image , segment ) : x , y , w , h = segment return image [ y : y + h , x : x + w ]", "docstring_tokens": "given a segment ( rectangle ) and an image returns it s corresponding subimage", "label": 1, "retrieval_idx": 941 }, { "idx": "cosqa-train-14675", "doc": "test for empty python dictionary", "code": "def _clean_dict(target_dict, whitelist=None):\n \"\"\" Convenience function that removes a dicts keys that have falsy values\n \"\"\"\n assert isinstance(target_dict, dict)\n return {\n ustr(k).strip(): ustr(v).strip()\n for k, v in target_dict.items()\n if v not in (None, Ellipsis, [], (), \"\")\n and (not whitelist or k in whitelist)\n }", "code_tokens": "def _clean_dict ( target_dict , whitelist = None ) : assert isinstance ( target_dict , dict ) return { ustr ( k ) . strip ( ) : ustr ( v ) . strip ( ) for k , v in target_dict . items ( ) if v not in ( None , Ellipsis , [ ] , ( ) , \"\" ) and ( not whitelist or k in whitelist ) }", "docstring_tokens": "Convenience function that removes a dicts keys that have falsy values", "label": 1, "retrieval_idx": 695 }, { "idx": "cosqa-train-11364", "doc": "python logging rotating file handler by date", "code": "def timed_rotating_file_handler(name, logname, filename, when='h',\n interval=1, backupCount=0,\n encoding=None, delay=False, utc=False):\n \"\"\"\n A Bark logging handler logging output to a named file. At\n intervals specified by the 'when', the file will be rotated, under\n control of 'backupCount'.\n\n Similar to logging.handlers.TimedRotatingFileHandler.\n \"\"\"\n\n return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(\n filename, when=when, interval=interval, backupCount=backupCount,\n encoding=encoding, delay=delay, utc=utc))", "code_tokens": "def timed_rotating_file_handler ( name , logname , filename , when = 'h' , interval = 1 , backupCount = 0 , encoding = None , delay = False , utc = False ) : return wrap_log_handler ( logging . handlers . TimedRotatingFileHandler ( filename , when = when , interval = interval , backupCount = backupCount , encoding = encoding , delay = delay , utc = utc ) )", "docstring_tokens": "A Bark logging handler logging output to a named file . At intervals specified by the when the file will be rotated under control of backupCount .", "label": 1, "retrieval_idx": 166 }, { "idx": "cosqa-dev-382", "doc": "python get type of values in a columns", "code": "def _get_column_types(self, data):\n \"\"\"Get a list of the data types for each column in *data*.\"\"\"\n columns = list(zip_longest(*data))\n return [self._get_column_type(column) for column in columns]", "code_tokens": "def _get_column_types ( self , data ) : columns = list ( zip_longest ( * data ) ) return [ self . _get_column_type ( column ) for column in columns ]", "docstring_tokens": "Get a list of the data types for each column in * data * .", "label": 1, "retrieval_idx": 461 }, { "idx": "cosqa-train-14453", "doc": "remove from index object in python", "code": "def delete_index(self):\n \"\"\"\n Delete the index, if it exists.\n \"\"\"\n es = self._init_connection()\n if es.indices.exists(index=self.index):\n es.indices.delete(index=self.index)", "code_tokens": "def delete_index ( self ) : es = self . _init_connection ( ) if es . indices . exists ( index = self . index ) : es . indices . delete ( index = self . index )", "docstring_tokens": "Delete the index if it exists .", "label": 1, "retrieval_idx": 5167 }, { "idx": "cosqa-train-10228", "doc": "plot linear regression python on existing plot", "code": "def _linear_seaborn_(self, label=None, style=None, opts=None):\n \"\"\"\n Returns a Seaborn linear regression plot\n \"\"\"\n xticks, yticks = self._get_ticks(opts)\n try:\n fig = sns.lmplot(self.x, self.y, data=self.df)\n fig = self._set_with_height(fig, opts)\n return fig\n except Exception as e:\n self.err(e, self.linear_,\n \"Can not draw linear regression chart\")", "code_tokens": "def _linear_seaborn_ ( self , label = None , style = None , opts = None ) : xticks , yticks = self . _get_ticks ( opts ) try : fig = sns . lmplot ( self . x , self . y , data = self . df ) fig = self . _set_with_height ( fig , opts ) return fig except Exception as e : self . err ( e , self . linear_ , \"Can not draw linear regression chart\" )", "docstring_tokens": "Returns a Seaborn linear regression plot", "label": 1, "retrieval_idx": 3277 }, { "idx": "cosqa-train-6824", "doc": "python gzip decompress stream", "code": "def load_streams(chunks):\n \"\"\"\n Given a gzipped stream of data, yield streams of decompressed data.\n \"\"\"\n chunks = peekable(chunks)\n while chunks:\n if six.PY3:\n dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16)\n else:\n dc = zlib.decompressobj(zlib.MAX_WBITS | 16)\n yield load_stream(dc, chunks)\n if dc.unused_data:\n chunks = peekable(itertools.chain((dc.unused_data,), chunks))", "code_tokens": "def load_streams ( chunks ) : chunks = peekable ( chunks ) while chunks : if six . PY3 : dc = zlib . decompressobj ( wbits = zlib . MAX_WBITS | 16 ) else : dc = zlib . decompressobj ( zlib . MAX_WBITS | 16 ) yield load_stream ( dc , chunks ) if dc . unused_data : chunks = peekable ( itertools . chain ( ( dc . unused_data , ) , chunks ) )", "docstring_tokens": "Given a gzipped stream of data yield streams of decompressed data .", "label": 1, "retrieval_idx": 3586 }, { "idx": "cosqa-train-8526", "doc": "python cut string by length", "code": "def split_len(s, length):\n \"\"\"split string *s* into list of strings no longer than *length*\"\"\"\n return [s[i:i+length] for i in range(0, len(s), length)]", "code_tokens": "def split_len ( s , length ) : return [ s [ i : i + length ] for i in range ( 0 , len ( s ) , length ) ]", "docstring_tokens": "split string * s * into list of strings no longer than * length *", "label": 1, "retrieval_idx": 3224 }, { "idx": "cosqa-train-8781", "doc": "converter string to json python", "code": "def json(body, charset='utf-8', **kwargs):\n \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n return json_converter.loads(text(body, charset=charset))", "code_tokens": "def json ( body , charset = 'utf-8' , * * kwargs ) : return json_converter . loads ( text ( body , charset = charset ) )", "docstring_tokens": "Takes JSON formatted data converting it into native Python objects", "label": 1, "retrieval_idx": 2057 }, { "idx": "cosqa-train-11211", "doc": "python image margin padding", "code": "def __call__(self, img):\n \"\"\"\n Args:\n img (PIL Image): Image to be padded.\n\n Returns:\n PIL Image: Padded image.\n \"\"\"\n return F.pad(img, self.padding, self.fill, self.padding_mode)", "code_tokens": "def __call__ ( self , img ) : return F . pad ( img , self . padding , self . fill , self . padding_mode )", "docstring_tokens": "Args : img ( PIL Image ) : Image to be padded .", "label": 1, "retrieval_idx": 2553 }, { "idx": "cosqa-train-8082", "doc": "remove item from series python", "code": "def remove_series(self, series):\n \"\"\"Removes a :py:class:`.Series` from the chart.\n\n :param Series series: The :py:class:`.Series` to remove.\n :raises ValueError: if you try to remove the last\\\n :py:class:`.Series`.\"\"\"\n\n if len(self.all_series()) == 1:\n raise ValueError(\"Cannot remove last series from %s\" % str(self))\n self._all_series.remove(series)\n series._chart = None", "code_tokens": "def remove_series ( self , series ) : if len ( self . all_series ( ) ) == 1 : raise ValueError ( \"Cannot remove last series from %s\" % str ( self ) ) self . _all_series . remove ( series ) series . _chart = None", "docstring_tokens": "Removes a : py : class : . Series from the chart .", "label": 1, "retrieval_idx": 1100 }, { "idx": "cosqa-train-4463", "doc": "check if address is valid python", "code": "def is_valid_ipv6(ip_str):\n \"\"\"\n Check the validity of an IPv6 address\n \"\"\"\n try:\n socket.inet_pton(socket.AF_INET6, ip_str)\n except socket.error:\n return False\n return True", "code_tokens": "def is_valid_ipv6 ( ip_str ) : try : socket . inet_pton ( socket . AF_INET6 , ip_str ) except socket . error : return False return True", "docstring_tokens": "Check the validity of an IPv6 address", "label": 1, "retrieval_idx": 1249 }, { "idx": "cosqa-train-12359", "doc": "replace multiple things in a string python", "code": "def multi_replace(instr, search_list=[], repl_list=None):\n \"\"\"\n Does a string replace with a list of search and replacements\n\n TODO: rename\n \"\"\"\n repl_list = [''] * len(search_list) if repl_list is None else repl_list\n for ser, repl in zip(search_list, repl_list):\n instr = instr.replace(ser, repl)\n return instr", "code_tokens": "def multi_replace ( instr , search_list = [ ] , repl_list = None ) : repl_list = [ '' ] * len ( search_list ) if repl_list is None else repl_list for ser , repl in zip ( search_list , repl_list ) : instr = instr . replace ( ser , repl ) return instr", "docstring_tokens": "Does a string replace with a list of search and replacements", "label": 1, "retrieval_idx": 1023 }, { "idx": "cosqa-train-13512", "doc": "python logging format brace bracket", "code": "def format(self, record, *args, **kwargs):\n \"\"\"\n Format a message in the log\n\n Act like the normal format, but indent anything that is a\n newline within the message.\n\n \"\"\"\n return logging.Formatter.format(\n self, record, *args, **kwargs).replace('\\n', '\\n' + ' ' * 8)", "code_tokens": "def format ( self , record , * args , * * kwargs ) : return logging . Formatter . format ( self , record , * args , * * kwargs ) . replace ( '\\n' , '\\n' + ' ' * 8 )", "docstring_tokens": "Format a message in the log", "label": 1, "retrieval_idx": 748 }, { "idx": "cosqa-train-16237", "doc": "python strip new lines while reading file", "code": "def get_stripped_file_lines(filename):\n \"\"\"\n Return lines of a file with whitespace removed\n \"\"\"\n try:\n lines = open(filename).readlines()\n except FileNotFoundError:\n fatal(\"Could not open file: {!r}\".format(filename))\n\n return [line.strip() for line in lines]", "code_tokens": "def get_stripped_file_lines ( filename ) : try : lines = open ( filename ) . readlines ( ) except FileNotFoundError : fatal ( \"Could not open file: {!r}\" . format ( filename ) ) return [ line . strip ( ) for line in lines ]", "docstring_tokens": "Return lines of a file with whitespace removed", "label": 1, "retrieval_idx": 3099 }, { "idx": "cosqa-train-13661", "doc": "how to determine the index of an object on a list python", "code": "def find_geom(geom, geoms):\n \"\"\"\n Returns the index of a geometry in a list of geometries avoiding\n expensive equality checks of `in` operator.\n \"\"\"\n for i, g in enumerate(geoms):\n if g is geom:\n return i", "code_tokens": "def find_geom ( geom , geoms ) : for i , g in enumerate ( geoms ) : if g is geom : return i", "docstring_tokens": "Returns the index of a geometry in a list of geometries avoiding expensive equality checks of in operator .", "label": 1, "retrieval_idx": 1272 }, { "idx": "cosqa-train-9723", "doc": "how to remove repeated numbers in a list in python", "code": "def dedupe_list(seq):\n \"\"\"\n Utility function to remove duplicates from a list\n :param seq: The sequence (list) to deduplicate\n :return: A list with original duplicates removed\n \"\"\"\n seen = set()\n return [x for x in seq if not (x in seen or seen.add(x))]", "code_tokens": "def dedupe_list ( seq ) : seen = set ( ) return [ x for x in seq if not ( x in seen or seen . add ( x ) ) ]", "docstring_tokens": "Utility function to remove duplicates from a list : param seq : The sequence ( list ) to deduplicate : return : A list with original duplicates removed", "label": 1, "retrieval_idx": 1450 }, { "idx": "cosqa-train-17563", "doc": "reversing a dictionary in python", "code": "def inverted_dict(d):\n \"\"\"Return a dict with swapped keys and values\n\n >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}\n True\n \"\"\"\n return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))", "code_tokens": "def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )", "docstring_tokens": "Return a dict with swapped keys and values", "label": 1, "retrieval_idx": 5553 }, { "idx": "cosqa-train-10714", "doc": "python disable output buffer", "code": "def disable_stdout_buffering():\n \"\"\"This turns off stdout buffering so that outputs are immediately\n materialized and log messages show up before the program exits\"\"\"\n stdout_orig = sys.stdout\n sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\n # NOTE(brandyn): This removes the original stdout\n return stdout_orig", "code_tokens": "def disable_stdout_buffering ( ) : stdout_orig = sys . stdout sys . stdout = os . fdopen ( sys . stdout . fileno ( ) , 'w' , 0 ) # NOTE(brandyn): This removes the original stdout return stdout_orig", "docstring_tokens": "This turns off stdout buffering so that outputs are immediately materialized and log messages show up before the program exits", "label": 1, "retrieval_idx": 2887 }, { "idx": "cosqa-train-15275", "doc": "python get an unique id", "code": "def generate_unique_host_id():\n \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n instances running at the same time.\"\"\"\n host = \".\".join(reversed(socket.gethostname().split(\".\")))\n pid = os.getpid()\n return \"%s.%d\" % (host, pid)", "code_tokens": "def generate_unique_host_id ( ) : host = \".\" . join ( reversed ( socket . gethostname ( ) . split ( \".\" ) ) ) pid = os . getpid ( ) return \"%s.%d\" % ( host , pid )", "docstring_tokens": "Generate a unique ID that is somewhat guaranteed to be unique among all instances running at the same time .", "label": 1, "retrieval_idx": 335 }, { "idx": "cosqa-train-13510", "doc": "python logging create blank line", "code": "def write(self, text):\n \"\"\"Write text. An additional attribute terminator with a value of\n None is added to the logging record to indicate that StreamHandler\n should not add a newline.\"\"\"\n self.logger.log(self.loglevel, text, extra={'terminator': None})", "code_tokens": "def write ( self , text ) : self . logger . log ( self . loglevel , text , extra = { 'terminator' : None } )", "docstring_tokens": "Write text . An additional attribute terminator with a value of None is added to the logging record to indicate that StreamHandler should not add a newline .", "label": 1, "retrieval_idx": 2097 }, { "idx": "cosqa-train-238", "doc": "check specific header in python", "code": "def required_header(header):\n \"\"\"Function that verify if the header parameter is a essential header\n\n :param header: A string represented a header\n :returns: A boolean value that represent if the header is required\n \"\"\"\n if header in IGNORE_HEADERS:\n return False\n\n if header.startswith('HTTP_') or header == 'CONTENT_TYPE':\n return True\n\n return False", "code_tokens": "def required_header ( header ) : if header in IGNORE_HEADERS : return False if header . startswith ( 'HTTP_' ) or header == 'CONTENT_TYPE' : return True return False", "docstring_tokens": "Function that verify if the header parameter is a essential header", "label": 1, "retrieval_idx": 233 }, { "idx": "cosqa-train-11148", "doc": "get common values in a dictionary python", "code": "def compare(dicts):\n \"\"\"Compare by iteration\"\"\"\n\n common_members = {}\n common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts))\n for k in common_keys:\n common_members[k] = list(\n reduce(lambda x, y: x & y, [set(d[k]) for d in dicts]))\n\n return common_members", "code_tokens": "def compare ( dicts ) : common_members = { } common_keys = reduce ( lambda x , y : x & y , map ( dict . keys , dicts ) ) for k in common_keys : common_members [ k ] = list ( reduce ( lambda x , y : x & y , [ set ( d [ k ] ) for d in dicts ] ) ) return common_members", "docstring_tokens": "Compare by iteration", "label": 1, "retrieval_idx": 522 }, { "idx": "cosqa-train-1105", "doc": "python random permutation of a set", "code": "def endless_permutations(N, random_state=None):\n \"\"\"\n Generate an endless sequence of random integers from permutations of the\n set [0, ..., N).\n\n If we call this N times, we will sweep through the entire set without\n replacement, on the (N+1)th call a new permutation will be created, etc.\n\n Parameters\n ----------\n N: int\n the length of the set\n random_state: int or RandomState, optional\n random seed\n\n Yields\n ------\n int:\n a random int from the set [0, ..., N)\n \"\"\"\n generator = check_random_state(random_state)\n while True:\n batch_inds = generator.permutation(N)\n for b in batch_inds:\n yield b", "code_tokens": "def endless_permutations ( N , random_state = None ) : generator = check_random_state ( random_state ) while True : batch_inds = generator . permutation ( N ) for b in batch_inds : yield b", "docstring_tokens": "Generate an endless sequence of random integers from permutations of the set [ 0 ... N ) .", "label": 1, "retrieval_idx": 957 }, { "idx": "cosqa-train-4145", "doc": "unhasable type list in python to replace with a hashable list", "code": "def dedupe_list(l):\n \"\"\"Remove duplicates from a list preserving the order.\n\n We might be tempted to use the list(set(l)) idiom, but it doesn't preserve\n the order, which hinders testability and does not work for lists with\n unhashable elements.\n \"\"\"\n result = []\n\n for el in l:\n if el not in result:\n result.append(el)\n\n return result", "code_tokens": "def dedupe_list ( l ) : result = [ ] for el in l : if el not in result : result . append ( el ) return result", "docstring_tokens": "Remove duplicates from a list preserving the order .", "label": 1, "retrieval_idx": 721 }, { "idx": "cosqa-train-13164", "doc": "python get variable by name locals globals", "code": "def getvariable(name):\n \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n import inspect\n fr = inspect.currentframe()\n try:\n while fr:\n fr = fr.f_back\n vars = fr.f_locals\n if name in vars:\n return vars[name]\n except:\n pass\n return None", "code_tokens": "def getvariable ( name ) : import inspect fr = inspect . currentframe ( ) try : while fr : fr = fr . f_back vars = fr . f_locals if name in vars : return vars [ name ] except : pass return None", "docstring_tokens": "Get the value of a local variable somewhere in the call stack .", "label": 1, "retrieval_idx": 1793 }, { "idx": "cosqa-train-14068", "doc": "python split string ever n characters", "code": "def _split_str(s, n):\n \"\"\"\n split string into list of strings by specified number.\n \"\"\"\n length = len(s)\n return [s[i:i + n] for i in range(0, length, n)]", "code_tokens": "def _split_str ( s , n ) : length = len ( s ) return [ s [ i : i + n ] for i in range ( 0 , length , n ) ]", "docstring_tokens": "split string into list of strings by specified number .", "label": 1, "retrieval_idx": 424 }, { "idx": "cosqa-train-13524", "doc": "python logging set verbosity", "code": "def set_verbosity(verbosity):\n \"\"\"Banana banana\n \"\"\"\n Logger._verbosity = min(max(0, WARNING - verbosity), 2)\n debug(\"Verbosity set to %d\" % (WARNING - Logger._verbosity), 'logging')", "code_tokens": "def set_verbosity ( verbosity ) : Logger . _verbosity = min ( max ( 0 , WARNING - verbosity ) , 2 ) debug ( \"Verbosity set to %d\" % ( WARNING - Logger . _verbosity ) , 'logging' )", "docstring_tokens": "Banana banana", "label": 1, "retrieval_idx": 5020 }, { "idx": "cosqa-train-10334", "doc": "set a pixel python", "code": "def setPixel(self, x, y, color):\n \"\"\"Set the pixel at (x,y) to the integers in sequence 'color'.\"\"\"\n return _fitz.Pixmap_setPixel(self, x, y, color)", "code_tokens": "def setPixel ( self , x , y , color ) : return _fitz . Pixmap_setPixel ( self , x , y , color )", "docstring_tokens": "Set the pixel at ( x y ) to the integers in sequence color .", "label": 1, "retrieval_idx": 1518 }, { "idx": "cosqa-train-6757", "doc": "discover file extension python", "code": "def _get_compiled_ext():\n \"\"\"Official way to get the extension of compiled files (.pyc or .pyo)\"\"\"\n for ext, mode, typ in imp.get_suffixes():\n if typ == imp.PY_COMPILED:\n return ext", "code_tokens": "def _get_compiled_ext ( ) : for ext , mode , typ in imp . get_suffixes ( ) : if typ == imp . PY_COMPILED : return ext", "docstring_tokens": "Official way to get the extension of compiled files ( . pyc or . pyo )", "label": 1, "retrieval_idx": 523 }, { "idx": "cosqa-train-12848", "doc": "python draw line in control", "code": "def hline(self, x, y, width, color):\n \"\"\"Draw a horizontal line up to a given length.\"\"\"\n self.rect(x, y, width, 1, color, fill=True)", "code_tokens": "def hline ( self , x , y , width , color ) : self . rect ( x , y , width , 1 , color , fill = True )", "docstring_tokens": "Draw a horizontal line up to a given length .", "label": 1, "retrieval_idx": 225 }, { "idx": "cosqa-train-19534", "doc": "python check if a valid date", "code": "def valid_date(x: str) -> bool:\n \"\"\"\n Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n otherwise return ``False``.\n \"\"\"\n try:\n if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n raise ValueError\n return True\n except ValueError:\n return False", "code_tokens": "def valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False", "docstring_tokens": "Retrun True if x is a valid YYYYMMDD date ; otherwise return False .", "label": 1, "retrieval_idx": 5581 }, { "idx": "cosqa-train-421", "doc": "delete spaces and non number terms from a string python", "code": "def detokenize(s):\n \"\"\" Detokenize a string by removing spaces before punctuation.\"\"\"\n print(s)\n s = re.sub(\"\\s+([;:,\\.\\?!])\", \"\\\\1\", s)\n s = re.sub(\"\\s+(n't)\", \"\\\\1\", s)\n return s", "code_tokens": "def detokenize ( s ) : print ( s ) s = re . sub ( \"\\s+([;:,\\.\\?!])\" , \"\\\\1\" , s ) s = re . sub ( \"\\s+(n't)\" , \"\\\\1\" , s ) return s", "docstring_tokens": "Detokenize a string by removing spaces before punctuation .", "label": 1, "retrieval_idx": 398 }, { "idx": "cosqa-train-8663", "doc": "python django foreach list to str with ,", "code": "def commajoin_as_strings(iterable):\n \"\"\" Join the given iterable with ',' \"\"\"\n return _(u',').join((six.text_type(i) for i in iterable))", "code_tokens": "def commajoin_as_strings ( iterable ) : return _ ( u',' ) . join ( ( six . text_type ( i ) for i in iterable ) )", "docstring_tokens": "Join the given iterable with", "label": 1, "retrieval_idx": 160 }, { "idx": "cosqa-train-6516", "doc": "python django postgres flow", "code": "def install_postgres(user=None, dbname=None, password=None):\n \"\"\"Install Postgres on remote\"\"\"\n execute(pydiploy.django.install_postgres_server,\n user=user, dbname=dbname, password=password)", "code_tokens": "def install_postgres ( user = None , dbname = None , password = None ) : execute ( pydiploy . django . install_postgres_server , user = user , dbname = dbname , password = password )", "docstring_tokens": "Install Postgres on remote", "label": 1, "retrieval_idx": 3451 }, { "idx": "cosqa-train-11518", "doc": "how to filter an image using a mask in python", "code": "def filter_greys_using_image(image, target):\n \"\"\"Filter out any values in target not in image\n\n :param image: image containing values to appear in filtered image\n :param target: the image to filter\n :rtype: 2d :class:`numpy.ndarray` containing only value in image\n and with the same dimensions as target\n\n \"\"\"\n maskbase = numpy.array(range(256), dtype=numpy.uint8)\n mask = numpy.where(numpy.in1d(maskbase, numpy.unique(image)), maskbase, 0)\n return mask[target]", "code_tokens": "def filter_greys_using_image ( image , target ) : maskbase = numpy . array ( range ( 256 ) , dtype = numpy . uint8 ) mask = numpy . where ( numpy . in1d ( maskbase , numpy . unique ( image ) ) , maskbase , 0 ) return mask [ target ]", "docstring_tokens": "Filter out any values in target not in image : param image : image containing values to appear in filtered image : param target : the image to filter : rtype : 2d : class : numpy . ndarray containing only value in image and with the same dimensions as target", "label": 1, "retrieval_idx": 3528 }, { "idx": "cosqa-train-7105", "doc": "python longest consecutive ones group", "code": "def longest_run_1d(arr):\n \"\"\"Return the length of the longest consecutive run of identical values.\n\n Parameters\n ----------\n arr : bool array\n Input array\n\n Returns\n -------\n int\n Length of longest run.\n \"\"\"\n v, rl = rle_1d(arr)[:2]\n return np.where(v, rl, 0).max()", "code_tokens": "def longest_run_1d ( arr ) : v , rl = rle_1d ( arr ) [ : 2 ] return np . where ( v , rl , 0 ) . max ( )", "docstring_tokens": "Return the length of the longest consecutive run of identical values .", "label": 1, "retrieval_idx": 1368 }, { "idx": "cosqa-train-18157", "doc": "python parsing yaml file", "code": "def load_yaml(yaml_file: str) -> Any:\n \"\"\"\n Load YAML from file.\n\n :param yaml_file: path to YAML file\n :return: content of the YAML as dict/list\n \"\"\"\n with open(yaml_file, 'r') as file:\n return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader)", "code_tokens": "def load_yaml ( yaml_file : str ) -> Any : with open ( yaml_file , 'r' ) as file : return ruamel . yaml . load ( file , ruamel . yaml . RoundTripLoader )", "docstring_tokens": "Load YAML from file .", "label": 1, "retrieval_idx": 6002 }, { "idx": "cosqa-train-6748", "doc": "python get list of methods on object", "code": "def get_methods(*objs):\n \"\"\" Return the names of all callable attributes of an object\"\"\"\n return set(\n attr\n for obj in objs\n for attr in dir(obj)\n if not attr.startswith('_') and callable(getattr(obj, attr))\n )", "code_tokens": "def get_methods ( * objs ) : return set ( attr for obj in objs for attr in dir ( obj ) if not attr . startswith ( '_' ) and callable ( getattr ( obj , attr ) ) )", "docstring_tokens": "Return the names of all callable attributes of an object", "label": 1, "retrieval_idx": 385 }, { "idx": "cosqa-train-7245", "doc": "how to covert a string column to a float in python", "code": "def comma_converter(float_string):\n \"\"\"Convert numbers to floats whether the decimal point is '.' or ','\"\"\"\n trans_table = maketrans(b',', b'.')\n return float(float_string.translate(trans_table))", "code_tokens": "def comma_converter ( float_string ) : trans_table = maketrans ( b',' , b'.' ) return float ( float_string . translate ( trans_table ) )", "docstring_tokens": "Convert numbers to floats whether the decimal point is . or", "label": 1, "retrieval_idx": 736 }, { "idx": "cosqa-train-18041", "doc": "printing data type off all columns in data frame in python", "code": "def dtypes(self):\n \"\"\"Returns all column names and their data types as a list.\n\n >>> df.dtypes\n [('age', 'int'), ('name', 'string')]\n \"\"\"\n return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "code_tokens": "def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]", "docstring_tokens": "Returns all column names and their data types as a list .", "label": 1, "retrieval_idx": 5803 }, { "idx": "cosqa-train-19641", "doc": "multiply matrix with different constant in python", "code": "def __rmatmul__(self, other):\n \"\"\"\n Matrix multiplication using binary `@` operator in Python>=3.5.\n \"\"\"\n return self.T.dot(np.transpose(other)).T", "code_tokens": "def __rmatmul__ ( self , other ) : return self . T . dot ( np . transpose ( other ) ) . T", "docstring_tokens": "Matrix multiplication using binary", "label": 1, "retrieval_idx": 5730 }, { "idx": "cosqa-train-17955", "doc": "permutations in python with three arguements", "code": "def product(*args, **kwargs):\n \"\"\" Yields all permutations with replacement:\n list(product(\"cat\", repeat=2)) => \n [(\"c\", \"c\"), \n (\"c\", \"a\"), \n (\"c\", \"t\"), \n (\"a\", \"c\"), \n (\"a\", \"a\"), \n (\"a\", \"t\"), \n (\"t\", \"c\"), \n (\"t\", \"a\"), \n (\"t\", \"t\")]\n \"\"\"\n p = [[]]\n for iterable in map(tuple, args) * kwargs.get(\"repeat\", 1):\n p = [x + [y] for x in p for y in iterable]\n for p in p:\n yield tuple(p)", "code_tokens": "def product ( * args , * * kwargs ) : p = [ [ ] ] for iterable in map ( tuple , args ) * kwargs . get ( \"repeat\" , 1 ) : p = [ x + [ y ] for x in p for y in iterable ] for p in p : yield tuple ( p )", "docstring_tokens": "Yields all permutations with replacement : list ( product ( cat repeat = 2 )) = > [ ( c c ) ( c a ) ( c t ) ( a c ) ( a a ) ( a t ) ( t c ) ( t a ) ( t t ) ]", "label": 1, "retrieval_idx": 5967 }, { "idx": "cosqa-train-8365", "doc": "type not equal to string python", "code": "def validate_string(option, value):\n \"\"\"Validates that 'value' is an instance of `basestring` for Python 2\n or `str` for Python 3.\n \"\"\"\n if isinstance(value, string_type):\n return value\n raise TypeError(\"Wrong type for %s, value must be \"\n \"an instance of %s\" % (option, string_type.__name__))", "code_tokens": "def validate_string ( option , value ) : if isinstance ( value , string_type ) : return value raise TypeError ( \"Wrong type for %s, value must be \" \"an instance of %s\" % ( option , string_type . __name__ ) )", "docstring_tokens": "Validates that value is an instance of basestring for Python 2 or str for Python 3 .", "label": 1, "retrieval_idx": 2584 }, { "idx": "cosqa-train-16072", "doc": "how to modify print function in python", "code": "def _show(self, message, indent=0, enable_verbose=True): # pragma: no cover\n \"\"\"Message printer.\n \"\"\"\n if enable_verbose:\n print(\" \" * indent + message)", "code_tokens": "def _show ( self , message , indent = 0 , enable_verbose = True ) : # pragma: no cover if enable_verbose : print ( \" \" * indent + message )", "docstring_tokens": "Message printer .", "label": 1, "retrieval_idx": 1030 }, { "idx": "cosqa-train-17475", "doc": "using dot file with python graphviz", "code": "def cmd_dot(conf: Config):\n \"\"\"Print out a neat targets dependency tree based on requested targets.\n\n Use graphviz to render the dot file, e.g.:\n\n > ybt dot :foo :bar | dot -Tpng -o graph.png\n \"\"\"\n build_context = BuildContext(conf)\n populate_targets_graph(build_context, conf)\n if conf.output_dot_file is None:\n write_dot(build_context, conf, sys.stdout)\n else:\n with open(conf.output_dot_file, 'w') as out_file:\n write_dot(build_context, conf, out_file)", "code_tokens": "def cmd_dot ( conf : Config ) : build_context = BuildContext ( conf ) populate_targets_graph ( build_context , conf ) if conf . output_dot_file is None : write_dot ( build_context , conf , sys . stdout ) else : with open ( conf . output_dot_file , 'w' ) as out_file : write_dot ( build_context , conf , out_file )", "docstring_tokens": "Print out a neat targets dependency tree based on requested targets .", "label": 1, "retrieval_idx": 5811 }, { "idx": "cosqa-train-4947", "doc": "python lamba filter with or", "code": "def BROADCAST_FILTER_NOT(func):\n \"\"\"\n Composes the passed filters into an and-joined filter.\n \"\"\"\n return lambda u, command, *args, **kwargs: not func(u, command, *args, **kwargs)", "code_tokens": "def BROADCAST_FILTER_NOT ( func ) : return lambda u , command , * args , * * kwargs : not func ( u , command , * args , * * kwargs )", "docstring_tokens": "Composes the passed filters into an and - joined filter .", "label": 1, "retrieval_idx": 2927 }, { "idx": "cosqa-train-8712", "doc": "check index mongod python", "code": "def ensure_index(self, key, unique=False):\n \"\"\"Wrapper for pymongo.Collection.ensure_index\n \"\"\"\n return self.collection.ensure_index(key, unique=unique)", "code_tokens": "def ensure_index ( self , key , unique = False ) : return self . collection . ensure_index ( key , unique = unique )", "docstring_tokens": "Wrapper for pymongo . Collection . ensure_index", "label": 1, "retrieval_idx": 3314 }, { "idx": "cosqa-train-16025", "doc": "how to load data from url with python", "code": "def get(url):\n \"\"\"Recieving the JSON file from uulm\"\"\"\n response = urllib.request.urlopen(url)\n data = response.read()\n data = data.decode(\"utf-8\")\n data = json.loads(data)\n return data", "code_tokens": "def get ( url ) : response = urllib . request . urlopen ( url ) data = response . read ( ) data = data . decode ( \"utf-8\" ) data = json . loads ( data ) return data", "docstring_tokens": "Recieving the JSON file from uulm", "label": 1, "retrieval_idx": 1410 }, { "idx": "cosqa-train-14666", "doc": "python check if field exists in sql table", "code": "def column_exists(cr, table, column):\n \"\"\" Check whether a certain column exists \"\"\"\n cr.execute(\n 'SELECT count(attname) FROM pg_attribute '\n 'WHERE attrelid = '\n '( SELECT oid FROM pg_class WHERE relname = %s ) '\n 'AND attname = %s',\n (table, column))\n return cr.fetchone()[0] == 1", "code_tokens": "def column_exists ( cr , table , column ) : cr . execute ( 'SELECT count(attname) FROM pg_attribute ' 'WHERE attrelid = ' '( SELECT oid FROM pg_class WHERE relname = %s ) ' 'AND attname = %s' , ( table , column ) ) return cr . fetchone ( ) [ 0 ] == 1", "docstring_tokens": "Check whether a certain column exists", "label": 1, "retrieval_idx": 2194 }, { "idx": "cosqa-train-14312", "doc": "matplotlib python remove ticks", "code": "def clear_matplotlib_ticks(self, axis=\"both\"):\n \"\"\"Clears the default matplotlib ticks.\"\"\"\n ax = self.get_axes()\n plotting.clear_matplotlib_ticks(ax=ax, axis=axis)", "code_tokens": "def clear_matplotlib_ticks ( self , axis = \"both\" ) : ax = self . get_axes ( ) plotting . clear_matplotlib_ticks ( ax = ax , axis = axis )", "docstring_tokens": "Clears the default matplotlib ticks .", "label": 1, "retrieval_idx": 788 }, { "idx": "cosqa-train-8391", "doc": "using aparser from python shell", "code": "def build_parser():\n \"\"\"Build argument parsers.\"\"\"\n\n parser = argparse.ArgumentParser(\"Release packages to pypi\")\n parser.add_argument('--check', '-c', action=\"store_true\", help=\"Do a dry run without uploading\")\n parser.add_argument('component', help=\"The component to release as component-version\")\n return parser", "code_tokens": "def build_parser ( ) : parser = argparse . ArgumentParser ( \"Release packages to pypi\" ) parser . add_argument ( '--check' , '-c' , action = \"store_true\" , help = \"Do a dry run without uploading\" ) parser . add_argument ( 'component' , help = \"The component to release as component-version\" ) return parser", "docstring_tokens": "Build argument parsers .", "label": 1, "retrieval_idx": 1508 }, { "idx": "cosqa-train-9068", "doc": "python how to retrieve an anchor tag", "code": "def get_anchor_href(markup):\n \"\"\"\n Given HTML markup, return a list of hrefs for each anchor tag.\n \"\"\"\n soup = BeautifulSoup(markup, 'lxml')\n return ['%s' % link.get('href') for link in soup.find_all('a')]", "code_tokens": "def get_anchor_href ( markup ) : soup = BeautifulSoup ( markup , 'lxml' ) return [ '%s' % link . get ( 'href' ) for link in soup . find_all ( 'a' ) ]", "docstring_tokens": "Given HTML markup return a list of hrefs for each anchor tag .", "label": 1, "retrieval_idx": 4158 }, { "idx": "cosqa-train-15011", "doc": "python decode and print base64 string", "code": "def toBase64(s):\n \"\"\"Represent string / bytes s as base64, omitting newlines\"\"\"\n if isinstance(s, str):\n s = s.encode(\"utf-8\")\n return binascii.b2a_base64(s)[:-1]", "code_tokens": "def toBase64 ( s ) : if isinstance ( s , str ) : s = s . encode ( \"utf-8\" ) return binascii . b2a_base64 ( s ) [ : - 1 ]", "docstring_tokens": "Represent string / bytes s as base64 omitting newlines", "label": 1, "retrieval_idx": 554 }, { "idx": "cosqa-train-12325", "doc": "python 2to 3 script", "code": "def command_py2to3(args):\n \"\"\"\n Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n \"\"\"\n from lib2to3.main import main\n sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "code_tokens": "def command_py2to3 ( args ) : from lib2to3 . main import main sys . exit ( main ( \"lib2to3.fixes\" , args = args . sources ) )", "docstring_tokens": "Apply 2to3 tool ( Python2 to Python3 conversion tool ) to Python sources .", "label": 1, "retrieval_idx": 1469 }, { "idx": "cosqa-dev-272", "doc": "adding noise to images python", "code": "def shot_noise(x, severity=1):\n \"\"\"Shot noise corruption to images.\n\n Args:\n x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].\n severity: integer, severity of corruption.\n\n Returns:\n numpy array, image with uint8 pixels in [0,255]. Added shot noise.\n \"\"\"\n c = [60, 25, 12, 5, 3][severity - 1]\n x = np.array(x) / 255.\n x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n return around_and_astype(x_clip)", "code_tokens": "def shot_noise ( x , severity = 1 ) : c = [ 60 , 25 , 12 , 5 , 3 ] [ severity - 1 ] x = np . array ( x ) / 255. x_clip = np . clip ( np . random . poisson ( x * c ) / float ( c ) , 0 , 1 ) * 255 return around_and_astype ( x_clip )", "docstring_tokens": "Shot noise corruption to images .", "label": 1, "retrieval_idx": 1396 }, { "idx": "cosqa-train-10428", "doc": "sum results of a query python sqlalchemy", "code": "def get_count(self, query):\n \"\"\"\n Returns a number of query results. This is faster than .count() on the query\n \"\"\"\n count_q = query.statement.with_only_columns(\n [func.count()]).order_by(None)\n count = query.session.execute(count_q).scalar()\n return count", "code_tokens": "def get_count ( self , query ) : count_q = query . statement . with_only_columns ( [ func . count ( ) ] ) . order_by ( None ) count = query . session . execute ( count_q ) . scalar ( ) return count", "docstring_tokens": "Returns a number of query results . This is faster than . count () on the query", "label": 1, "retrieval_idx": 2396 }, { "idx": "cosqa-train-10679", "doc": "python default value if null", "code": "def safe_int(val, default=None):\n \"\"\"\n Returns int() of val if val is not convertable to int use default\n instead\n\n :param val:\n :param default:\n \"\"\"\n\n try:\n val = int(val)\n except (ValueError, TypeError):\n val = default\n\n return val", "code_tokens": "def safe_int ( val , default = None ) : try : val = int ( val ) except ( ValueError , TypeError ) : val = default return val", "docstring_tokens": "Returns int () of val if val is not convertable to int use default instead", "label": 1, "retrieval_idx": 2494 }, { "idx": "cosqa-train-15392", "doc": "first few lines of a file python print", "code": "def head(filename, n=10):\n \"\"\" prints the top `n` lines of a file \"\"\"\n with freader(filename) as fr:\n for _ in range(n):\n print(fr.readline().strip())", "code_tokens": "def head ( filename , n = 10 ) : with freader ( filename ) as fr : for _ in range ( n ) : print ( fr . readline ( ) . strip ( ) )", "docstring_tokens": "prints the top n lines of a file", "label": 1, "retrieval_idx": 1073 }, { "idx": "cosqa-train-11258", "doc": "how do i tell something to print 6 lines in the paragraph in python", "code": "def erase_lines(n=1):\n \"\"\" Erases n lines from the screen and moves the cursor up to follow\n \"\"\"\n for _ in range(n):\n print(codes.cursor[\"up\"], end=\"\")\n print(codes.cursor[\"eol\"], end=\"\")", "code_tokens": "def erase_lines ( n = 1 ) : for _ in range ( n ) : print ( codes . cursor [ \"up\" ] , end = \"\" ) print ( codes . cursor [ \"eol\" ] , end = \"\" )", "docstring_tokens": "Erases n lines from the screen and moves the cursor up to follow", "label": 1, "retrieval_idx": 783 }, { "idx": "cosqa-train-10604", "doc": "3 dimension convolution of cnn with python numpy", "code": "def conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)", "code_tokens": "def conv1x1 ( in_planes , out_planes , stride = 1 ) : return nn . Conv2d ( in_planes , out_planes , kernel_size = 1 , stride = stride , bias = False )", "docstring_tokens": "1x1 convolution", "label": 1, "retrieval_idx": 1075 }, { "idx": "cosqa-train-12643", "doc": "using mask in images python", "code": "def inpaint(self):\n \"\"\" Replace masked-out elements in an array using an iterative image inpainting algorithm. \"\"\"\n\n import inpaint\n filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)\n self.raster_data = np.ma.masked_invalid(filled)", "code_tokens": "def inpaint ( self ) : import inpaint filled = inpaint . replace_nans ( np . ma . filled ( self . raster_data , np . NAN ) . astype ( np . float32 ) , 3 , 0.01 , 2 ) self . raster_data = np . ma . masked_invalid ( filled )", "docstring_tokens": "Replace masked - out elements in an array using an iterative image inpainting algorithm .", "label": 1, "retrieval_idx": 1803 }, { "idx": "cosqa-train-18628", "doc": "python flatten dict items", "code": "def flatten_multidict(multidict):\n \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n return dict([(key, value if len(value) > 1 else value[0])\n for (key, value) in multidict.iterlists()])", "code_tokens": "def flatten_multidict ( multidict ) : return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] )", "docstring_tokens": "Return flattened dictionary from MultiDict .", "label": 1, "retrieval_idx": 5724 }, { "idx": "cosqa-train-14216", "doc": "incorrect header check python", "code": "def required_header(header):\n \"\"\"Function that verify if the header parameter is a essential header\n\n :param header: A string represented a header\n :returns: A boolean value that represent if the header is required\n \"\"\"\n if header in IGNORE_HEADERS:\n return False\n\n if header.startswith('HTTP_') or header == 'CONTENT_TYPE':\n return True\n\n return False", "code_tokens": "def required_header ( header ) : if header in IGNORE_HEADERS : return False if header . startswith ( 'HTTP_' ) or header == 'CONTENT_TYPE' : return True return False", "docstring_tokens": "Function that verify if the header parameter is a essential header", "label": 1, "retrieval_idx": 233 }, { "idx": "cosqa-train-17647", "doc": "how to get domain from url netloc python", "code": "def url_host(url: str) -> str:\n \"\"\"\n Parses hostname from URL.\n :param url: URL\n :return: hostname\n \"\"\"\n from urllib.parse import urlparse\n res = urlparse(url)\n return res.netloc.split(':')[0] if res.netloc else ''", "code_tokens": "def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''", "docstring_tokens": "Parses hostname from URL . : param url : URL : return : hostname", "label": 1, "retrieval_idx": 5694 }, { "idx": "cosqa-train-7100", "doc": "how to add noise to an image using python", "code": "def shot_noise(x, severity=1):\n \"\"\"Shot noise corruption to images.\n\n Args:\n x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].\n severity: integer, severity of corruption.\n\n Returns:\n numpy array, image with uint8 pixels in [0,255]. Added shot noise.\n \"\"\"\n c = [60, 25, 12, 5, 3][severity - 1]\n x = np.array(x) / 255.\n x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n return around_and_astype(x_clip)", "code_tokens": "def shot_noise ( x , severity = 1 ) : c = [ 60 , 25 , 12 , 5 , 3 ] [ severity - 1 ] x = np . array ( x ) / 255. x_clip = np . clip ( np . random . poisson ( x * c ) / float ( c ) , 0 , 1 ) * 255 return around_and_astype ( x_clip )", "docstring_tokens": "Shot noise corruption to images .", "label": 1, "retrieval_idx": 1396 }, { "idx": "cosqa-train-18082", "doc": "python csv read numpy array", "code": "def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array\n \"\"\"Convert a CSV object to a numpy array.\n\n Args:\n string_like (str): CSV string.\n dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the\n contents of each column, individually. This argument can only be used to\n 'upcast' the array. For downcasting, use the .astype(t) method.\n Returns:\n (np.array): numpy array\n \"\"\"\n stream = StringIO(string_like)\n return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "code_tokens": "def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )", "docstring_tokens": "Convert a CSV object to a numpy array .", "label": 1, "retrieval_idx": 5746 }, { "idx": "cosqa-train-19043", "doc": "implement a tree python", "code": "def debugTreePrint(node,pfx=\"->\"):\n \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n print pfx,node.item\n for c in node.children:\n debugTreePrint(c,\" \"+pfx)", "code_tokens": "def debugTreePrint ( node , pfx = \"->\" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , \" \" + pfx )", "docstring_tokens": "Purely a debugging aid : Ascii - art picture of a tree descended from node", "label": 1, "retrieval_idx": 5626 }, { "idx": "cosqa-train-12281", "doc": "print attributes of object in python", "code": "def _repr(obj):\n \"\"\"Show the received object as precise as possible.\"\"\"\n vals = \", \".join(\"{}={!r}\".format(\n name, getattr(obj, name)) for name in obj._attribs)\n if vals:\n t = \"{}(name={}, {})\".format(obj.__class__.__name__, obj.name, vals)\n else:\n t = \"{}(name={})\".format(obj.__class__.__name__, obj.name)\n return t", "code_tokens": "def _repr ( obj ) : vals = \", \" . join ( \"{}={!r}\" . format ( name , getattr ( obj , name ) ) for name in obj . _attribs ) if vals : t = \"{}(name={}, {})\" . format ( obj . __class__ . __name__ , obj . name , vals ) else : t = \"{}(name={})\" . format ( obj . __class__ . __name__ , obj . name ) return t", "docstring_tokens": "Show the received object as precise as possible .", "label": 1, "retrieval_idx": 1533 }, { "idx": "cosqa-train-14786", "doc": "vs code python default indentation", "code": "def dumped(text, level, indent=2):\n \"\"\"Put curly brackets round an indented text\"\"\"\n return indented(\"{\\n%s\\n}\" % indented(text, level + 1, indent) or \"None\", level, indent) + \"\\n\"", "code_tokens": "def dumped ( text , level , indent = 2 ) : return indented ( \"{\\n%s\\n}\" % indented ( text , level + 1 , indent ) or \"None\" , level , indent ) + \"\\n\"", "docstring_tokens": "Put curly brackets round an indented text", "label": 1, "retrieval_idx": 29 }, { "idx": "cosqa-train-7938", "doc": "python word similarity sementic", "code": "def basic_word_sim(word1, word2):\n \"\"\"\n Simple measure of similarity: Number of letters in common / max length\n \"\"\"\n return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))", "code_tokens": "def basic_word_sim ( word1 , word2 ) : return sum ( [ 1 for c in word1 if c in word2 ] ) / max ( len ( word1 ) , len ( word2 ) )", "docstring_tokens": "Simple measure of similarity : Number of letters in common / max length", "label": 1, "retrieval_idx": 1901 }, { "idx": "cosqa-train-11713", "doc": "python read json iterate", "code": "def json_iter (path):\n \"\"\"\n iterator for JSON-per-line in a file pattern\n \"\"\"\n with open(path, 'r') as f:\n for line in f.readlines():\n yield json.loads(line)", "code_tokens": "def json_iter ( path ) : with open ( path , 'r' ) as f : for line in f . readlines ( ) : yield json . loads ( line )", "docstring_tokens": "iterator for JSON - per - line in a file pattern", "label": 1, "retrieval_idx": 983 }, { "idx": "cosqa-train-3566", "doc": "python subplot not able to set xticklabels", "code": "def show_xticklabels(self, row, column):\n \"\"\"Show the x-axis tick labels for a subplot.\n\n :param row,column: specify the subplot.\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.show_xticklabels()", "code_tokens": "def show_xticklabels ( self , row , column ) : subplot = self . get_subplot_at ( row , column ) subplot . show_xticklabels ( )", "docstring_tokens": "Show the x - axis tick labels for a subplot .", "label": 1, "retrieval_idx": 944 }, { "idx": "cosqa-train-9696", "doc": "how to read an image file into python using its path", "code": "def load_image(fname):\n \"\"\" read an image from file - PIL doesnt close nicely \"\"\"\n with open(fname, \"rb\") as f:\n i = Image.open(fname)\n #i.load()\n return i", "code_tokens": "def load_image ( fname ) : with open ( fname , \"rb\" ) as f : i = Image . open ( fname ) #i.load() return i", "docstring_tokens": "read an image from file - PIL doesnt close nicely", "label": 1, "retrieval_idx": 2485 }, { "idx": "cosqa-train-6417", "doc": "argparse python add subparser to subparser", "code": "def set_subparsers_args(self, *args, **kwargs):\n \"\"\"\n Sets args and kwargs that are passed when creating a subparsers group\n in an argparse.ArgumentParser i.e. when calling\n argparser.ArgumentParser.add_subparsers\n \"\"\"\n self.subparsers_args = args\n self.subparsers_kwargs = kwargs", "code_tokens": "def set_subparsers_args ( self , * args , * * kwargs ) : self . subparsers_args = args self . subparsers_kwargs = kwargs", "docstring_tokens": "Sets args and kwargs that are passed when creating a subparsers group in an argparse . ArgumentParser i . e . when calling argparser . ArgumentParser . add_subparsers", "label": 1, "retrieval_idx": 2613 }, { "idx": "cosqa-train-12336", "doc": "remove white spaces from string in python", "code": "def strip_spaces(s):\n \"\"\" Strip excess spaces from a string \"\"\"\n return u\" \".join([c for c in s.split(u' ') if c])", "code_tokens": "def strip_spaces ( s ) : return u\" \" . join ( [ c for c in s . split ( u' ' ) if c ] )", "docstring_tokens": "Strip excess spaces from a string", "label": 1, "retrieval_idx": 366 }, { "idx": "cosqa-train-10020", "doc": "python utc time to local time", "code": "def datetime_local_to_utc(local):\n \"\"\"\n Simple function to convert naive :std:`datetime.datetime` object containing\n local time to a naive :std:`datetime.datetime` object with UTC time.\n \"\"\"\n timestamp = time.mktime(local.timetuple())\n return datetime.datetime.utcfromtimestamp(timestamp)", "code_tokens": "def datetime_local_to_utc ( local ) : timestamp = time . mktime ( local . timetuple ( ) ) return datetime . datetime . utcfromtimestamp ( timestamp )", "docstring_tokens": "Simple function to convert naive : std : datetime . datetime object containing local time to a naive : std : datetime . datetime object with UTC time .", "label": 1, "retrieval_idx": 737 }, { "idx": "cosqa-train-17470", "doc": "python check for files edited within time", "code": "def has_changed (filename):\n \"\"\"Check if filename has changed since the last check. If this\n is the first check, assume the file is changed.\"\"\"\n key = os.path.abspath(filename)\n mtime = get_mtime(key)\n if key not in _mtime_cache:\n _mtime_cache[key] = mtime\n return True\n return mtime > _mtime_cache[key]", "code_tokens": "def has_changed ( filename ) : key = os . path . abspath ( filename ) mtime = get_mtime ( key ) if key not in _mtime_cache : _mtime_cache [ key ] = mtime return True return mtime > _mtime_cache [ key ]", "docstring_tokens": "Check if filename has changed since the last check . If this is the first check assume the file is changed .", "label": 1, "retrieval_idx": 5690 }, { "idx": "cosqa-train-18570", "doc": "python pprint a long string", "code": "def _short_repr(obj):\n \"\"\"Helper function returns a truncated repr() of an object.\"\"\"\n stringified = pprint.saferepr(obj)\n if len(stringified) > 200:\n return '%s... (%d bytes)' % (stringified[:200], len(stringified))\n return stringified", "code_tokens": "def _short_repr ( obj ) : stringified = pprint . saferepr ( obj ) if len ( stringified ) > 200 : return '%s... (%d bytes)' % ( stringified [ : 200 ] , len ( stringified ) ) return stringified", "docstring_tokens": "Helper function returns a truncated repr () of an object .", "label": 1, "retrieval_idx": 5740 }, { "idx": "cosqa-train-2358", "doc": "close window python gui", "code": "def closing_plugin(self, cancelable=False):\n \"\"\"Perform actions before parent main window is closed\"\"\"\n self.dialog_manager.close_all()\n self.shell.exit_interpreter()\n return True", "code_tokens": "def closing_plugin ( self , cancelable = False ) : self . dialog_manager . close_all ( ) self . shell . exit_interpreter ( ) return True", "docstring_tokens": "Perform actions before parent main window is closed", "label": 1, "retrieval_idx": 141 }, { "idx": "cosqa-train-11705", "doc": "python read file json with", "code": "def open_json(file_name):\n \"\"\"\n returns json contents as string\n \"\"\"\n with open(file_name, \"r\") as json_data:\n data = json.load(json_data)\n return data", "code_tokens": "def open_json ( file_name ) : with open ( file_name , \"r\" ) as json_data : data = json . load ( json_data ) return data", "docstring_tokens": "returns json contents as string", "label": 1, "retrieval_idx": 977 }, { "idx": "cosqa-train-11645", "doc": "how to load and execute a sql file in python", "code": "def _get_sql(filename):\n \"\"\"Returns the contents of the sql file from the given ``filename``.\"\"\"\n with open(os.path.join(SQL_DIR, filename), 'r') as f:\n return f.read()", "code_tokens": "def _get_sql ( filename ) : with open ( os . path . join ( SQL_DIR , filename ) , 'r' ) as f : return f . read ( )", "docstring_tokens": "Returns the contents of the sql file from the given filename .", "label": 1, "retrieval_idx": 1052 }, { "idx": "cosqa-train-12052", "doc": "iterate over file names in directory python", "code": "def directory_files(path):\n \"\"\"Yield directory file names.\"\"\"\n\n for entry in os.scandir(path):\n if not entry.name.startswith('.') and entry.is_file():\n yield entry.name", "code_tokens": "def directory_files ( path ) : for entry in os . scandir ( path ) : if not entry . name . startswith ( '.' ) and entry . is_file ( ) : yield entry . name", "docstring_tokens": "Yield directory file names .", "label": 1, "retrieval_idx": 665 }, { "idx": "cosqa-train-1387", "doc": "how to sort the columns in python in data frame", "code": "def sort_data(data, cols):\n \"\"\"Sort `data` rows and order columns\"\"\"\n return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)", "code_tokens": "def sort_data ( data , cols ) : return data . sort_values ( cols ) [ cols + [ 'value' ] ] . reset_index ( drop = True )", "docstring_tokens": "Sort data rows and order columns", "label": 1, "retrieval_idx": 1180 }, { "idx": "cosqa-train-12240", "doc": "opencv resize keep ratio python", "code": "def scale_min(im, targ, interpolation=cv2.INTER_AREA):\n \"\"\" Scale the image so that the smallest axis is of size targ.\n\n Arguments:\n im (array): image\n targ (int): target size\n \"\"\"\n r,c,*_ = im.shape\n ratio = targ/min(r,c)\n sz = (scale_to(c, ratio, targ), scale_to(r, ratio, targ))\n return cv2.resize(im, sz, interpolation=interpolation)", "code_tokens": "def scale_min ( im , targ , interpolation = cv2 . INTER_AREA ) : r , c , * _ = im . shape ratio = targ / min ( r , c ) sz = ( scale_to ( c , ratio , targ ) , scale_to ( r , ratio , targ ) ) return cv2 . resize ( im , sz , interpolation = interpolation )", "docstring_tokens": "Scale the image so that the smallest axis is of size targ .", "label": 1, "retrieval_idx": 4795 }, { "idx": "cosqa-train-13591", "doc": "how to concatenate output in same file python", "code": "def build_output(self, fout):\n \"\"\"Squash self.out into string.\n\n Join every line in self.out with a new line and write the\n result to the output file.\n \"\"\"\n fout.write('\\n'.join([s for s in self.out]))", "code_tokens": "def build_output ( self , fout ) : fout . write ( '\\n' . join ( [ s for s in self . out ] ) )", "docstring_tokens": "Squash self . out into string .", "label": 1, "retrieval_idx": 688 }, { "idx": "cosqa-train-15027", "doc": "check file size in python", "code": "def get_file_size(filename):\n \"\"\"\n Get the file size of a given file\n\n :param filename: string: pathname of a file\n :return: human readable filesize\n \"\"\"\n if os.path.isfile(filename):\n return convert_size(os.path.getsize(filename))\n return None", "code_tokens": "def get_file_size ( filename ) : if os . path . isfile ( filename ) : return convert_size ( os . path . getsize ( filename ) ) return None", "docstring_tokens": "Get the file size of a given file", "label": 1, "retrieval_idx": 288 }, { "idx": "cosqa-train-4411", "doc": "cast timestamp datatype python", "code": "def timestamp_to_datetime(timestamp):\n \"\"\"Convert an ARF timestamp to a datetime.datetime object (naive local time)\"\"\"\n from datetime import datetime, timedelta\n obj = datetime.fromtimestamp(timestamp[0])\n return obj + timedelta(microseconds=int(timestamp[1]))", "code_tokens": "def timestamp_to_datetime ( timestamp ) : from datetime import datetime , timedelta obj = datetime . fromtimestamp ( timestamp [ 0 ] ) return obj + timedelta ( microseconds = int ( timestamp [ 1 ] ) )", "docstring_tokens": "Convert an ARF timestamp to a datetime . datetime object ( naive local time )", "label": 1, "retrieval_idx": 1263 }, { "idx": "cosqa-train-7635", "doc": "python setcurrentindex qcombobox changing the index, but not the value", "code": "def _updateItemComboBoxIndex(self, item, column, num):\n \"\"\"Callback for comboboxes: notifies us that a combobox for the given item and column has changed\"\"\"\n item._combobox_current_index[column] = num\n item._combobox_current_value[column] = item._combobox_option_list[column][num][0]", "code_tokens": "def _updateItemComboBoxIndex ( self , item , column , num ) : item . _combobox_current_index [ column ] = num item . _combobox_current_value [ column ] = item . _combobox_option_list [ column ] [ num ] [ 0 ]", "docstring_tokens": "Callback for comboboxes : notifies us that a combobox for the given item and column has changed", "label": 1, "retrieval_idx": 3358 }, { "idx": "cosqa-train-19137", "doc": "python enum not json serializable", "code": "def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:\n \"\"\"\n Converts an ``dict`` to a ``Enum``.\n \"\"\"\n return enum_class[d['name']]", "code_tokens": "def dict_to_enum_fn ( d : Dict [ str , Any ] , enum_class : Type [ Enum ] ) -> Enum : return enum_class [ d [ 'name' ] ]", "docstring_tokens": "Converts an dict to a Enum .", "label": 1, "retrieval_idx": 5688 }, { "idx": "cosqa-train-578", "doc": "python how to check if method is overload", "code": "def _is_override(meta, method):\n \"\"\"Checks whether given class or instance method has been marked\n with the ``@override`` decorator.\n \"\"\"\n from taipan.objective.modifiers import _OverriddenMethod\n return isinstance(method, _OverriddenMethod)", "code_tokens": "def _is_override ( meta , method ) : from taipan . objective . modifiers import _OverriddenMethod return isinstance ( method , _OverriddenMethod )", "docstring_tokens": "Checks whether given class or instance method has been marked with the", "label": 1, "retrieval_idx": 531 }, { "idx": "cosqa-train-2783", "doc": "python iterate through queryset", "code": "def _unordered_iterator(self):\n \"\"\"\n Return the value of each QuerySet, but also add the '#' property to each\n return item.\n \"\"\"\n for i, qs in zip(self._queryset_idxs, self._querysets):\n for item in qs:\n setattr(item, '#', i)\n yield item", "code_tokens": "def _unordered_iterator ( self ) : for i , qs in zip ( self . _queryset_idxs , self . _querysets ) : for item in qs : setattr ( item , '#' , i ) yield item", "docstring_tokens": "Return the value of each QuerySet but also add the # property to each return item .", "label": 1, "retrieval_idx": 2051 }, { "idx": "cosqa-train-7247", "doc": "how to create a char array in python ctypes", "code": "def cfloat64_array_to_numpy(cptr, length):\n \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\n if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):\n return np.fromiter(cptr, dtype=np.float64, count=length)\n else:\n raise RuntimeError('Expected double pointer')", "code_tokens": "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' )", "docstring_tokens": "Convert a ctypes double pointer array to a numpy array .", "label": 1, "retrieval_idx": 64 }, { "idx": "cosqa-train-16947", "doc": "python get last occurrence in string", "code": "def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore\n \"\"\"\n Returns the index of the earliest occurence of an item from a list in a string\n\n Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3\n \"\"\"\n start = len(txt) + 1\n for item in str_list:\n if start > txt.find(item) > -1:\n start = txt.find(item)\n return start if len(txt) + 1 > start > -1 else -1", "code_tokens": "def find_first_in_list ( txt : str , str_list : [ str ] ) -> int : # type: ignore start = len ( txt ) + 1 for item in str_list : if start > txt . find ( item ) > - 1 : start = txt . find ( item ) return start if len ( txt ) + 1 > start > - 1 else - 1", "docstring_tokens": "Returns the index of the earliest occurence of an item from a list in a string", "label": 1, "retrieval_idx": 5545 }, { "idx": "cosqa-train-7636", "doc": "how to round a float to an int in python", "code": "def intround(value):\n \"\"\"Given a float returns a rounded int. Should give the same result on\n both Py2/3\n \"\"\"\n\n return int(decimal.Decimal.from_float(\n value).to_integral_value(decimal.ROUND_HALF_EVEN))", "code_tokens": "def intround ( value ) : return int ( decimal . Decimal . from_float ( value ) . to_integral_value ( decimal . ROUND_HALF_EVEN ) )", "docstring_tokens": "Given a float returns a rounded int . Should give the same result on both Py2 / 3", "label": 1, "retrieval_idx": 323 }, { "idx": "cosqa-train-9101", "doc": "get mouse coordinates python", "code": "def mouse_get_pos():\n \"\"\"\n\n :return:\n \"\"\"\n p = POINT()\n AUTO_IT.AU3_MouseGetPos(ctypes.byref(p))\n return p.x, p.y", "code_tokens": "def mouse_get_pos ( ) : p = POINT ( ) AUTO_IT . AU3_MouseGetPos ( ctypes . byref ( p ) ) return p . x , p . y", "docstring_tokens": "", "label": 1, "retrieval_idx": 3715 }, { "idx": "cosqa-train-9369", "doc": "how to delete python paths", "code": "def delete_all_eggs(self):\n \"\"\" delete all the eggs in the directory specified \"\"\"\n path_to_delete = os.path.join(self.egg_directory, \"lib\", \"python\")\n if os.path.exists(path_to_delete):\n shutil.rmtree(path_to_delete)", "code_tokens": "def delete_all_eggs ( self ) : path_to_delete = os . path . join ( self . egg_directory , \"lib\" , \"python\" ) if os . path . exists ( path_to_delete ) : shutil . rmtree ( path_to_delete )", "docstring_tokens": "delete all the eggs in the directory specified", "label": 1, "retrieval_idx": 145 }, { "idx": "cosqa-train-10769", "doc": "python every time take n items from list using yield", "code": "def split_every(n, iterable):\n \"\"\"Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have\n less than n elements.\n\n See http://stackoverflow.com/a/22919323/503377.\"\"\"\n items = iter(iterable)\n return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))", "code_tokens": "def split_every ( n , iterable ) : items = iter ( iterable ) return itertools . takewhile ( bool , ( list ( itertools . islice ( items , n ) ) for _ in itertools . count ( ) ) )", "docstring_tokens": "Returns a generator that spits an iteratable into n - sized chunks . The last chunk may have less than n elements .", "label": 1, "retrieval_idx": 663 }, { "idx": "cosqa-train-7158", "doc": "python method objects by name", "code": "def FindMethodByName(self, name):\n \"\"\"Searches for the specified method, and returns its descriptor.\"\"\"\n for method in self.methods:\n if name == method.name:\n return method\n return None", "code_tokens": "def FindMethodByName ( self , name ) : for method in self . methods : if name == method . name : return method return None", "docstring_tokens": "Searches for the specified method and returns its descriptor .", "label": 1, "retrieval_idx": 1374 }, { "idx": "cosqa-dev-1", "doc": "python split strings into list of lines", "code": "def split_multiline(value):\n \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n return [element for element in (line.strip() for line in value.split('\\n'))\n if element]", "code_tokens": "def split_multiline ( value ) : return [ element for element in ( line . strip ( ) for line in value . split ( '\\n' ) ) if element ]", "docstring_tokens": "Split a multiline string into a list excluding blank lines .", "label": 1, "retrieval_idx": 2133 }, { "idx": "cosqa-train-11225", "doc": "python index for first column name", "code": "def _get_col_index(name):\n \"\"\"Convert column name to index.\"\"\"\n\n index = string.ascii_uppercase.index\n col = 0\n for c in name.upper():\n col = col * 26 + index(c) + 1\n return col", "code_tokens": "def _get_col_index ( name ) : index = string . ascii_uppercase . index col = 0 for c in name . upper ( ) : col = col * 26 + index ( c ) + 1 return col", "docstring_tokens": "Convert column name to index .", "label": 1, "retrieval_idx": 4617 }, { "idx": "cosqa-train-19344", "doc": "python memoryview to structure", "code": "def memory_read(self, start_position: int, size: int) -> memoryview:\n \"\"\"\n Read and return a view of ``size`` bytes from memory starting at ``start_position``.\n \"\"\"\n return self._memory.read(start_position, size)", "code_tokens": "def memory_read ( self , start_position : int , size : int ) -> memoryview : return self . _memory . read ( start_position , size )", "docstring_tokens": "Read and return a view of size bytes from memory starting at start_position .", "label": 1, "retrieval_idx": 6189 }, { "idx": "cosqa-train-13411", "doc": "how do i clear python cache", "code": "def purge_cache(self, object_type):\n \"\"\" Purge the named cache of all values. If no cache exists for object_type, nothing is done \"\"\"\n if object_type in self.mapping:\n cache = self.mapping[object_type]\n log.debug(\"Purging [{}] cache of {} values.\".format(object_type, len(cache)))\n cache.purge()", "code_tokens": "def purge_cache ( self , object_type ) : if object_type in self . mapping : cache = self . mapping [ object_type ] log . debug ( \"Purging [{}] cache of {} values.\" . format ( object_type , len ( cache ) ) ) cache . purge ( )", "docstring_tokens": "Purge the named cache of all values . If no cache exists for object_type nothing is done", "label": 1, "retrieval_idx": 5001 }, { "idx": "cosqa-train-8828", "doc": "creating a leap year function in python returning true or false", "code": "def _is_leap_year(year):\n \"\"\"Determine if a year is leap year.\n\n Parameters\n ----------\n year : numeric\n\n Returns\n -------\n isleap : array of bools\n \"\"\"\n isleap = ((np.mod(year, 4) == 0) &\n ((np.mod(year, 100) != 0) | (np.mod(year, 400) == 0)))\n return isleap", "code_tokens": "def _is_leap_year ( year ) : isleap = ( ( np . mod ( year , 4 ) == 0 ) & ( ( np . mod ( year , 100 ) != 0 ) | ( np . mod ( year , 400 ) == 0 ) ) ) return isleap", "docstring_tokens": "Determine if a year is leap year .", "label": 1, "retrieval_idx": 1475 }, { "idx": "cosqa-train-12428", "doc": "python automate entering of credentials", "code": "def get_login_credentials(args):\n \"\"\"\n Gets the login credentials from the user, if not specified while invoking\n the script.\n @param args: arguments provided to the script.\n \"\"\"\n if not args.username:\n args.username = raw_input(\"Enter Username: \")\n if not args.password:\n args.password = getpass.getpass(\"Enter Password: \")", "code_tokens": "def get_login_credentials ( args ) : if not args . username : args . username = raw_input ( \"Enter Username: \" ) if not args . password : args . password = getpass . getpass ( \"Enter Password: \" )", "docstring_tokens": "Gets the login credentials from the user if not specified while invoking the script .", "label": 1, "retrieval_idx": 3994 }, { "idx": "cosqa-train-13351", "doc": "python if list of items is in line", "code": "def isin(elems, line):\n \"\"\"Check if an element from a list is in a string.\n\n :type elems: list\n :type line: str\n\n \"\"\"\n found = False\n for e in elems:\n if e in line.lower():\n found = True\n break\n return found", "code_tokens": "def isin ( elems , line ) : found = False for e in elems : if e in line . lower ( ) : found = True break return found", "docstring_tokens": "Check if an element from a list is in a string .", "label": 1, "retrieval_idx": 648 }, { "idx": "cosqa-train-18899", "doc": "python how to multiply matrix", "code": "def __rmatmul__(self, other):\n \"\"\"\n Matrix multiplication using binary `@` operator in Python>=3.5.\n \"\"\"\n return self.T.dot(np.transpose(other)).T", "code_tokens": "def __rmatmul__ ( self , other ) : return self . T . dot ( np . transpose ( other ) ) . T", "docstring_tokens": "Matrix multiplication using binary", "label": 1, "retrieval_idx": 5730 }, { "idx": "cosqa-train-18302", "doc": "turn string to a list in python", "code": "def _str_to_list(value, separator):\n \"\"\"Convert a string to a list with sanitization.\"\"\"\n value_list = [item.strip() for item in value.split(separator)]\n value_list_sanitized = builtins.list(filter(None, value_list))\n if len(value_list_sanitized) > 0:\n return value_list_sanitized\n else:\n raise ValueError('Invalid list variable.')", "code_tokens": "def _str_to_list ( value , separator ) : value_list = [ item . strip ( ) for item in value . split ( separator ) ] value_list_sanitized = builtins . list ( filter ( None , value_list ) ) if len ( value_list_sanitized ) > 0 : return value_list_sanitized else : raise ValueError ( 'Invalid list variable.' )", "docstring_tokens": "Convert a string to a list with sanitization .", "label": 1, "retrieval_idx": 5723 }, { "idx": "cosqa-train-9146", "doc": "graph corresponding to the adjacency matrix python", "code": "def get_adjacent_matrix(self):\n \"\"\"Get adjacency matrix.\n\n Returns:\n :param adj: adjacency matrix\n :type adj: np.ndarray\n \"\"\"\n edges = self.edges\n num_edges = len(edges) + 1\n adj = np.zeros([num_edges, num_edges])\n\n for k in range(num_edges - 1):\n adj[edges[k].L, edges[k].R] = 1\n adj[edges[k].R, edges[k].L] = 1\n\n return adj", "code_tokens": "def get_adjacent_matrix ( self ) : edges = self . edges num_edges = len ( edges ) + 1 adj = np . zeros ( [ num_edges , num_edges ] ) for k in range ( num_edges - 1 ) : adj [ edges [ k ] . L , edges [ k ] . R ] = 1 adj [ edges [ k ] . R , edges [ k ] . L ] = 1 return adj", "docstring_tokens": "Get adjacency matrix .", "label": 1, "retrieval_idx": 2149 }, { "idx": "cosqa-train-918", "doc": "python most frequent element multidimension", "code": "def _gcd_array(X):\n \"\"\"\n Return the largest real value h such that all elements in x are integer\n multiples of h.\n \"\"\"\n greatest_common_divisor = 0.0\n for x in X:\n greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n return greatest_common_divisor", "code_tokens": "def _gcd_array ( X ) : greatest_common_divisor = 0.0 for x in X : greatest_common_divisor = _gcd ( greatest_common_divisor , x ) return greatest_common_divisor", "docstring_tokens": "Return the largest real value h such that all elements in x are integer multiples of h .", "label": 1, "retrieval_idx": 302 }, { "idx": "cosqa-train-11708", "doc": "how to move a row up in python", "code": "def move_up(lines=1, file=sys.stdout):\n \"\"\" Move the cursor up a number of lines.\n\n Esc[ValueA:\n Moves the cursor up by the specified number of lines without changing\n columns. If the cursor is already on the top line, ANSI.SYS ignores\n this sequence.\n \"\"\"\n move.up(lines).write(file=file)", "code_tokens": "def move_up ( lines = 1 , file = sys . stdout ) : move . up ( lines ) . write ( file = file )", "docstring_tokens": "Move the cursor up a number of lines .", "label": 1, "retrieval_idx": 2129 }, { "idx": "cosqa-train-12867", "doc": "capture output of python pprint into a file", "code": "def py(self, output):\n \"\"\"Output data as a nicely-formatted python data structure\"\"\"\n import pprint\n pprint.pprint(output, stream=self.outfile)", "code_tokens": "def py ( self , output ) : import pprint pprint . pprint ( output , stream = self . outfile )", "docstring_tokens": "Output data as a nicely - formatted python data structure", "label": 1, "retrieval_idx": 925 }, { "idx": "cosqa-train-13054", "doc": "custom json serialize python tuple", "code": "def to_json(value, **kwargs):\n \"\"\"Return a copy of the tuple as a list\n\n If the tuple contains HasProperties instances, they are serialized.\n \"\"\"\n serial_list = [\n val.serialize(**kwargs) if isinstance(val, HasProperties)\n else val for val in value\n ]\n return serial_list", "code_tokens": "def to_json ( value , * * kwargs ) : serial_list = [ val . serialize ( * * kwargs ) if isinstance ( val , HasProperties ) else val for val in value ] return serial_list", "docstring_tokens": "Return a copy of the tuple as a list", "label": 1, "retrieval_idx": 4919 }, { "idx": "cosqa-train-885", "doc": "how to code tables in python using latex", "code": "def get_latex_table(self, parameters=None, transpose=False, caption=None,\n label=\"tab:model_params\", hlines=True, blank_fill=\"--\"): # pragma: no cover\n \"\"\" Generates a LaTeX table from parameter summaries.\n\n Parameters\n ----------\n parameters : list[str], optional\n A list of what parameters to include in the table. By default, includes all parameters\n transpose : bool, optional\n Defaults to False, which gives each column as a parameter, each chain (framework)\n as a row. You can swap it so that you have a parameter each row and a framework\n each column by setting this to True\n caption : str, optional\n If you want to generate a caption for the table through Python, use this.\n Defaults to an empty string\n label : str, optional\n If you want to generate a label for the table through Python, use this.\n Defaults to an empty string\n hlines : bool, optional\n Inserts ``\\\\hline`` before and after the header, and at the end of table.\n blank_fill : str, optional\n If a framework does not have a particular parameter, will fill that cell of\n the table with this string.\n\n Returns\n -------\n str\n the LaTeX table.\n \"\"\"\n if parameters is None:\n parameters = self.parent._all_parameters\n for p in parameters:\n assert isinstance(p, str), \\\n \"Generating a LaTeX table requires all parameters have labels\"\n num_parameters = len(parameters)\n num_chains = len(self.parent.chains)\n fit_values = self.get_summary(squeeze=False)\n if label is None:\n label = \"\"\n if caption is None:\n caption = \"\"\n\n end_text = \" \\\\\\\\ \\n\"\n if transpose:\n column_text = \"c\" * (num_chains + 1)\n else:\n column_text = \"c\" * (num_parameters + 1)\n\n center_text = \"\"\n hline_text = \"\\\\hline\\n\"\n if hlines:\n center_text += hline_text + \"\\t\\t\"\n if transpose:\n center_text += \" & \".join([\"Parameter\"] + [c.name for c in self.parent.chains]) + end_text\n if hlines:\n center_text += \"\\t\\t\" + hline_text\n for p in parameters:\n arr = [\"\\t\\t\" + p]\n for chain_res in fit_values:\n if p in chain_res:\n arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n else:\n arr.append(blank_fill)\n center_text += \" & \".join(arr) + end_text\n else:\n center_text += \" & \".join([\"Model\"] + parameters) + end_text\n if hlines:\n center_text += \"\\t\\t\" + hline_text\n for name, chain_res in zip([c.name for c in self.parent.chains], fit_values):\n arr = [\"\\t\\t\" + name]\n for p in parameters:\n if p in chain_res:\n arr.append(self.get_parameter_text(*chain_res[p], wrap=True))\n else:\n arr.append(blank_fill)\n center_text += \" & \".join(arr) + end_text\n if hlines:\n center_text += \"\\t\\t\" + hline_text\n final_text = get_latex_table_frame(caption, label) % (column_text, center_text)\n\n return final_text", "code_tokens": "def get_latex_table ( self , parameters = None , transpose = False , caption = None , label = \"tab:model_params\" , hlines = True , blank_fill = \"--\" ) : # pragma: no cover if parameters is None : parameters = self . parent . _all_parameters for p in parameters : assert isinstance ( p , str ) , \"Generating a LaTeX table requires all parameters have labels\" num_parameters = len ( parameters ) num_chains = len ( self . parent . chains ) fit_values = self . get_summary ( squeeze = False ) if label is None : label = \"\" if caption is None : caption = \"\" end_text = \" \\\\\\\\ \\n\" if transpose : column_text = \"c\" * ( num_chains + 1 ) else : column_text = \"c\" * ( num_parameters + 1 ) center_text = \"\" hline_text = \"\\\\hline\\n\" if hlines : center_text += hline_text + \"\\t\\t\" if transpose : center_text += \" & \" . join ( [ \"Parameter\" ] + [ c . name for c in self . parent . chains ] ) + end_text if hlines : center_text += \"\\t\\t\" + hline_text for p in parameters : arr = [ \"\\t\\t\" + p ] for chain_res in fit_values : if p in chain_res : arr . append ( self . get_parameter_text ( * chain_res [ p ] , wrap = True ) ) else : arr . append ( blank_fill ) center_text += \" & \" . join ( arr ) + end_text else : center_text += \" & \" . join ( [ \"Model\" ] + parameters ) + end_text if hlines : center_text += \"\\t\\t\" + hline_text for name , chain_res in zip ( [ c . name for c in self . parent . chains ] , fit_values ) : arr = [ \"\\t\\t\" + name ] for p in parameters : if p in chain_res : arr . append ( self . get_parameter_text ( * chain_res [ p ] , wrap = True ) ) else : arr . append ( blank_fill ) center_text += \" & \" . join ( arr ) + end_text if hlines : center_text += \"\\t\\t\" + hline_text final_text = get_latex_table_frame ( caption , label ) % ( column_text , center_text ) return final_text", "docstring_tokens": "Generates a LaTeX table from parameter summaries .", "label": 1, "retrieval_idx": 789 }, { "idx": "cosqa-train-9080", "doc": "python how to show help", "code": "def _help():\n \"\"\" Display both SQLAlchemy and Python help statements \"\"\"\n\n statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))\n print statement.strip()", "code_tokens": "def _help ( ) : statement = '%s%s' % ( shelp , phelp % ', ' . join ( cntx_ . keys ( ) ) ) print statement . strip ( )", "docstring_tokens": "Display both SQLAlchemy and Python help statements", "label": 1, "retrieval_idx": 2266 }, { "idx": "cosqa-train-10090", "doc": "max heap insert python", "code": "def heappush_max(heap, item):\n \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n heap.append(item)\n _siftdown_max(heap, 0, len(heap) - 1)", "code_tokens": "def heappush_max ( heap , item ) : heap . append ( item ) _siftdown_max ( heap , 0 , len ( heap ) - 1 )", "docstring_tokens": "Push item onto heap maintaining the heap invariant .", "label": 1, "retrieval_idx": 508 }, { "idx": "cosqa-train-9261", "doc": "how to check for duplicate characters in a python string", "code": "def first_unique_char(s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if (len(s) == 1):\n return 0\n ban = []\n for i in range(len(s)):\n if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:\n return i\n else:\n ban.append(s[i])\n return -1", "code_tokens": "def first_unique_char ( s ) : if ( len ( s ) == 1 ) : return 0 ban = [ ] for i in range ( len ( s ) ) : if all ( s [ i ] != s [ k ] for k in range ( i + 1 , len ( s ) ) ) == True and s [ i ] not in ban : return i else : ban . append ( s [ i ] ) return - 1", "docstring_tokens": ": type s : str : rtype : int", "label": 1, "retrieval_idx": 3503 }, { "idx": "cosqa-train-15810", "doc": "how to correct socket not define error in python", "code": "def pick_unused_port(self):\n \"\"\" Pick an unused port. There is a slight chance that this wont work. \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind(('127.0.0.1', 0))\n _, port = s.getsockname()\n s.close()\n return port", "code_tokens": "def pick_unused_port ( self ) : s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) s . bind ( ( '127.0.0.1' , 0 ) ) _ , port = s . getsockname ( ) s . close ( ) return port", "docstring_tokens": "Pick an unused port . There is a slight chance that this wont work .", "label": 1, "retrieval_idx": 2379 }, { "idx": "cosqa-train-4418", "doc": "python draft4validator validate schema", "code": "def validate(self):\n \"\"\"Validate the configuration file.\"\"\"\n validator = Draft4Validator(self.SCHEMA)\n if not validator.is_valid(self.config):\n for err in validator.iter_errors(self.config):\n LOGGER.error(str(err.message))\n validator.validate(self.config)", "code_tokens": "def validate ( self ) : validator = Draft4Validator ( self . SCHEMA ) if not validator . is_valid ( self . config ) : for err in validator . iter_errors ( self . config ) : LOGGER . error ( str ( err . message ) ) validator . validate ( self . config )", "docstring_tokens": "Validate the configuration file .", "label": 1, "retrieval_idx": 2808 }, { "idx": "cosqa-train-11185", "doc": "get number of rows in output of sql query in python", "code": "def count_rows(self, table, cols='*'):\n \"\"\"Get the number of rows in a particular table.\"\"\"\n query = 'SELECT COUNT({0}) FROM {1}'.format(join_cols(cols), wrap(table))\n result = self.fetch(query)\n return result if result is not None else 0", "code_tokens": "def count_rows ( self , table , cols = '*' ) : query = 'SELECT COUNT({0}) FROM {1}' . format ( join_cols ( cols ) , wrap ( table ) ) result = self . fetch ( query ) return result if result is not None else 0", "docstring_tokens": "Get the number of rows in a particular table .", "label": 1, "retrieval_idx": 4609 }, { "idx": "cosqa-train-6382", "doc": "add index support objects python", "code": "def to_index(self, index_type, index_name, includes=None):\n \"\"\" Create an index field from this field \"\"\"\n return IndexField(self.name, self.data_type, index_type, index_name, includes)", "code_tokens": "def to_index ( self , index_type , index_name , includes = None ) : return IndexField ( self . name , self . data_type , index_type , index_name , includes )", "docstring_tokens": "Create an index field from this field", "label": 1, "retrieval_idx": 3472 }, { "idx": "cosqa-train-17114", "doc": "make python tuple from list of strings", "code": "def _parse_tuple_string(argument):\n \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n if isinstance(argument, str):\n return tuple(int(p.strip()) for p in argument.split(','))\n return argument", "code_tokens": "def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument", "docstring_tokens": "Return a tuple from parsing a b c d - > ( a b c d )", "label": 1, "retrieval_idx": 5669 }, { "idx": "cosqa-train-11447", "doc": "how to create a variable containing multiple figures python", "code": "def strip_figures(figure):\n\t\"\"\"\n\tStrips a figure into multiple figures with a trace on each of them\n\n\tParameters:\n\t-----------\n\t\tfigure : Figure\n\t\t\tPlotly Figure\n\t\"\"\"\n\tfig=[]\n\tfor trace in figure['data']:\n\t\tfig.append(dict(data=[trace],layout=figure['layout']))\n\treturn fig", "code_tokens": "def strip_figures ( figure ) : fig = [ ] for trace in figure [ 'data' ] : fig . append ( dict ( data = [ trace ] , layout = figure [ 'layout' ] ) ) return fig", "docstring_tokens": "Strips a figure into multiple figures with a trace on each of them", "label": 1, "retrieval_idx": 1715 }, { "idx": "cosqa-train-14293", "doc": "python validate url invalid characters", "code": "def url_syntax_check(url): # pragma: no cover\n \"\"\"\n Check the syntax of the given URL.\n\n :param url: The URL to check the syntax for.\n :type url: str\n\n :return: The syntax validity.\n :rtype: bool\n\n .. warning::\n If an empty or a non-string :code:`url` is given, we return :code:`None`.\n \"\"\"\n\n if url and isinstance(url, str):\n # The given URL is not empty nor None.\n # and\n # * The given URL is a string.\n\n # We silently load the configuration.\n load_config(True)\n\n return Check(url).is_url_valid()\n\n # We return None, there is nothing to check.\n return None", "code_tokens": "def url_syntax_check ( url ) : # pragma: no cover if url and isinstance ( url , str ) : # The given URL is not empty nor None. # and # * The given URL is a string. # We silently load the configuration. load_config ( True ) return Check ( url ) . is_url_valid ( ) # We return None, there is nothing to check. return None", "docstring_tokens": "Check the syntax of the given URL .", "label": 1, "retrieval_idx": 4006 }, { "idx": "cosqa-train-8457", "doc": "python compare float of number to integer", "code": "def _check_for_int(x):\n \"\"\"\n This is a compatibility function that takes a C{float} and converts it to an\n C{int} if the values are equal.\n \"\"\"\n try:\n y = int(x)\n except (OverflowError, ValueError):\n pass\n else:\n # There is no way in AMF0 to distinguish between integers and floats\n if x == x and y == x:\n return y\n\n return x", "code_tokens": "def _check_for_int ( x ) : try : y = int ( x ) except ( OverflowError , ValueError ) : pass else : # There is no way in AMF0 to distinguish between integers and floats if x == x and y == x : return y return x", "docstring_tokens": "This is a compatibility function that takes a C { float } and converts it to an C { int } if the values are equal .", "label": 1, "retrieval_idx": 289 }, { "idx": "cosqa-train-11585", "doc": "python pdb see stack", "code": "def set_trace():\n \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "code_tokens": "def set_trace ( ) : # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py pdb . Pdb ( stdout = sys . __stdout__ ) . set_trace ( sys . _getframe ( ) . f_back )", "docstring_tokens": "Start a Pdb instance at the calling frame with stdout routed to sys . __stdout__ .", "label": 1, "retrieval_idx": 900 }, { "idx": "cosqa-train-7568", "doc": "how to raise a number to a power in python 3", "code": "def _power(ctx, number, power):\n \"\"\"\n Returns the result of a number raised to a power\n \"\"\"\n return decimal_pow(conversions.to_decimal(number, ctx), conversions.to_decimal(power, ctx))", "code_tokens": "def _power ( ctx , number , power ) : return decimal_pow ( conversions . to_decimal ( number , ctx ) , conversions . to_decimal ( power , ctx ) )", "docstring_tokens": "Returns the result of a number raised to a power", "label": 1, "retrieval_idx": 3816 }, { "idx": "cosqa-train-7677", "doc": "how to set width of bar in horizontal bar chart python", "code": "def _change_height(self, ax, new_value):\n \"\"\"Make bars in horizontal bar chart thinner\"\"\"\n for patch in ax.patches:\n current_height = patch.get_height()\n diff = current_height - new_value\n\n # we change the bar height\n patch.set_height(new_value)\n\n # we recenter the bar\n patch.set_y(patch.get_y() + diff * .5)", "code_tokens": "def _change_height ( self , ax , new_value ) : for patch in ax . patches : current_height = patch . get_height ( ) diff = current_height - new_value # we change the bar height patch . set_height ( new_value ) # we recenter the bar patch . set_y ( patch . get_y ( ) + diff * .5 )", "docstring_tokens": "Make bars in horizontal bar chart thinner", "label": 1, "retrieval_idx": 1996 }, { "idx": "cosqa-train-14814", "doc": "writing javascript in python for webpage", "code": "def add_to_js(self, name, var):\n \"\"\"Add an object to Javascript.\"\"\"\n frame = self.page().mainFrame()\n frame.addToJavaScriptWindowObject(name, var)", "code_tokens": "def add_to_js ( self , name , var ) : frame = self . page ( ) . mainFrame ( ) frame . addToJavaScriptWindowObject ( name , var )", "docstring_tokens": "Add an object to Javascript .", "label": 1, "retrieval_idx": 128 }, { "idx": "cosqa-train-9979", "doc": "python two vector multiply", "code": "def dot_v2(vec1, vec2):\n \"\"\"Return the dot product of two vectors\"\"\"\n\n return vec1.x * vec2.x + vec1.y * vec2.y", "code_tokens": "def dot_v2 ( vec1 , vec2 ) : return vec1 . x * vec2 . x + vec1 . y * vec2 . y", "docstring_tokens": "Return the dot product of two vectors", "label": 1, "retrieval_idx": 3581 }, { "idx": "cosqa-train-12860", "doc": "python dynamically read args in functions", "code": "def parsed_args():\n parser = argparse.ArgumentParser(description=\"\"\"python runtime functions\"\"\", epilog=\"\")\n parser.add_argument('command',nargs='*',\n help=\"Name of the function to run with arguments\")\n args = parser.parse_args()\n return (args, parser)", "code_tokens": "def parsed_args ( ) : parser = argparse . ArgumentParser ( description = \"\"\"python runtime functions\"\"\" , epilog = \"\" ) parser . add_argument ( 'command' , nargs = '*' , help = \"Name of the function to run with arguments\" ) args = parser . parse_args ( ) return ( args , parser )", "docstring_tokens": "", "label": 1, "retrieval_idx": 3283 }, { "idx": "cosqa-train-8681", "doc": "python draw line with scope and intercept", "code": "def vline(self, x, y, height, color):\n \"\"\"Draw a vertical line up to a given length.\"\"\"\n self.rect(x, y, 1, height, color, fill=True)", "code_tokens": "def vline ( self , x , y , height , color ) : self . rect ( x , y , 1 , height , color , fill = True )", "docstring_tokens": "Draw a vertical line up to a given length .", "label": 1, "retrieval_idx": 3875 }, { "idx": "cosqa-train-13176", "doc": "python good way to load a yaml file", "code": "def load_yaml(filepath):\n \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n with open(filepath) as f:\n txt = f.read()\n return yaml.load(txt)", "code_tokens": "def load_yaml ( filepath ) : with open ( filepath ) as f : txt = f . read ( ) return yaml . load ( txt )", "docstring_tokens": "Convenience function for loading yaml - encoded data from disk .", "label": 1, "retrieval_idx": 1096 }, { "idx": "cosqa-train-15044", "doc": "python detect if a file is a symbolic link", "code": "def is_symlink(self):\n \"\"\"\n Whether this path is a symbolic link.\n \"\"\"\n try:\n return S_ISLNK(self.lstat().st_mode)\n except OSError as e:\n if e.errno != ENOENT:\n raise\n # Path doesn't exist\n return False", "code_tokens": "def is_symlink ( self ) : try : return S_ISLNK ( self . lstat ( ) . st_mode ) except OSError as e : if e . errno != ENOENT : raise # Path doesn't exist return False", "docstring_tokens": "Whether this path is a symbolic link .", "label": 1, "retrieval_idx": 1607 }, { "idx": "cosqa-train-10452", "doc": "test if multiple variables are none python", "code": "def _not_none(items):\n \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n if not isinstance(items, (tuple, list)):\n items = (items,)\n return all(item is not _none for item in items)", "code_tokens": "def _not_none ( items ) : if not isinstance ( items , ( tuple , list ) ) : items = ( items , ) return all ( item is not _none for item in items )", "docstring_tokens": "Whether the item is a placeholder or contains a placeholder .", "label": 1, "retrieval_idx": 208 }, { "idx": "cosqa-train-18500", "doc": "delete a column in python db", "code": "def drop_column(self, tablename: str, fieldname: str) -> int:\n \"\"\"Drops (deletes) a column from an existing table.\"\"\"\n sql = \"ALTER TABLE {} DROP COLUMN {}\".format(tablename, fieldname)\n log.info(sql)\n return self.db_exec_literal(sql)", "code_tokens": "def drop_column ( self , tablename : str , fieldname : str ) -> int : sql = \"ALTER TABLE {} DROP COLUMN {}\" . format ( tablename , fieldname ) log . info ( sql ) return self . db_exec_literal ( sql )", "docstring_tokens": "Drops ( deletes ) a column from an existing table .", "label": 1, "retrieval_idx": 6069 }, { "idx": "cosqa-train-8600", "doc": "calculate the eigen values in python", "code": "def center_eigenvalue_diff(mat):\n \"\"\"Compute the eigvals of mat and then find the center eigval difference.\"\"\"\n N = len(mat)\n evals = np.sort(la.eigvals(mat))\n diff = np.abs(evals[N/2] - evals[N/2-1])\n return diff", "code_tokens": "def center_eigenvalue_diff ( mat ) : N = len ( mat ) evals = np . sort ( la . eigvals ( mat ) ) diff = np . abs ( evals [ N / 2 ] - evals [ N / 2 - 1 ] ) return diff", "docstring_tokens": "Compute the eigvals of mat and then find the center eigval difference .", "label": 1, "retrieval_idx": 445 }, { "idx": "cosqa-train-19250", "doc": "python read adb devices", "code": "def list_adb_devices_by_usb_id():\n \"\"\"List the usb id of all android devices connected to the computer that\n are detected by adb.\n\n Returns:\n A list of strings that are android device usb ids. Empty if there's\n none.\n \"\"\"\n out = adb.AdbProxy().devices(['-l'])\n clean_lines = new_str(out, 'utf-8').strip().split('\\n')\n results = []\n for line in clean_lines:\n tokens = line.strip().split()\n if len(tokens) > 2 and tokens[1] == 'device':\n results.append(tokens[2])\n return results", "code_tokens": "def list_adb_devices_by_usb_id ( ) : out = adb . AdbProxy ( ) . devices ( [ '-l' ] ) clean_lines = new_str ( out , 'utf-8' ) . strip ( ) . split ( '\\n' ) results = [ ] for line in clean_lines : tokens = line . strip ( ) . split ( ) if len ( tokens ) > 2 and tokens [ 1 ] == 'device' : results . append ( tokens [ 2 ] ) return results", "docstring_tokens": "List the usb id of all android devices connected to the computer that are detected by adb .", "label": 1, "retrieval_idx": 6061 }, { "idx": "cosqa-train-5000", "doc": "how to capitalize only the first letter of a string in python", "code": "def to_capitalized_camel_case(snake_case_string):\n \"\"\"\n Convert a string from snake case to camel case with the first letter capitalized. For example, \"some_var\"\n would become \"SomeVar\".\n\n :param snake_case_string: Snake-cased string to convert to camel case.\n :returns: Camel-cased version of snake_case_string.\n \"\"\"\n parts = snake_case_string.split('_')\n return ''.join([i.title() for i in parts])", "code_tokens": "def to_capitalized_camel_case ( snake_case_string ) : parts = snake_case_string . split ( '_' ) return '' . join ( [ i . title ( ) for i in parts ] )", "docstring_tokens": "Convert a string from snake case to camel case with the first letter capitalized . For example some_var would become SomeVar .", "label": 1, "retrieval_idx": 1625 }, { "idx": "cosqa-train-6678", "doc": "python function that takes a string and returns an int", "code": "def get_number(s, cast=int):\n \"\"\"\n Try to get a number out of a string, and cast it.\n \"\"\"\n import string\n d = \"\".join(x for x in str(s) if x in string.digits)\n return cast(d)", "code_tokens": "def get_number ( s , cast = int ) : import string d = \"\" . join ( x for x in str ( s ) if x in string . digits ) return cast ( d )", "docstring_tokens": "Try to get a number out of a string and cast it .", "label": 1, "retrieval_idx": 40 }, { "idx": "cosqa-train-15687", "doc": "python lookup and add idiom", "code": "def _import(module, cls):\n \"\"\"\n A messy way to import library-specific classes.\n TODO: I should really make a factory class or something, but I'm lazy.\n Plus, factories remind me a lot of java...\n \"\"\"\n global Scanner\n\n try:\n cls = str(cls)\n mod = __import__(str(module), globals(), locals(), [cls], 1)\n Scanner = getattr(mod, cls)\n except ImportError:\n pass", "code_tokens": "def _import ( module , cls ) : global Scanner try : cls = str ( cls ) mod = __import__ ( str ( module ) , globals ( ) , locals ( ) , [ cls ] , 1 ) Scanner = getattr ( mod , cls ) except ImportError : pass", "docstring_tokens": "A messy way to import library - specific classes . TODO : I should really make a factory class or something but I m lazy . Plus factories remind me a lot of java ...", "label": 1, "retrieval_idx": 3089 }, { "idx": "cosqa-train-17221", "doc": "python elementtree delete namespace", "code": "def recClearTag(element):\n \"\"\"Applies maspy.xml.clearTag() to the tag attribute of the \"element\" and\n recursively to all child elements.\n\n :param element: an :instance:`xml.etree.Element`\n \"\"\"\n children = element.getchildren()\n if len(children) > 0:\n for child in children:\n recClearTag(child)\n element.tag = clearTag(element.tag)", "code_tokens": "def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )", "docstring_tokens": "Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .", "label": 1, "retrieval_idx": 5570 }, { "idx": "cosqa-train-10541", "doc": "what can you store in a python session", "code": "def save_session(self, sid, session, namespace=None):\n \"\"\"Store the user session for a client.\n\n The only difference with the :func:`socketio.Server.save_session`\n method is that when the ``namespace`` argument is not given the\n namespace associated with the class is used.\n \"\"\"\n return self.server.save_session(\n sid, session, namespace=namespace or self.namespace)", "code_tokens": "def save_session ( self , sid , session , namespace = None ) : return self . server . save_session ( sid , session , namespace = namespace or self . namespace )", "docstring_tokens": "Store the user session for a client .", "label": 1, "retrieval_idx": 1242 }, { "idx": "cosqa-train-10553", "doc": "wrapping python as a wrapper", "code": "def library(func):\n \"\"\"\n A decorator for providing a unittest with a library and have it called only\n once.\n \"\"\"\n @wraps(func)\n def wrapped(*args, **kwargs):\n \"\"\"Transparent wrapper.\"\"\"\n return func(*args, **kwargs)\n SINGLES.append(wrapped)\n return wrapped", "code_tokens": "def library ( func ) : @ wraps ( func ) def wrapped ( * args , * * kwargs ) : \"\"\"Transparent wrapper.\"\"\" return func ( * args , * * kwargs ) SINGLES . append ( wrapped ) return wrapped", "docstring_tokens": "A decorator for providing a unittest with a library and have it called only once .", "label": 1, "retrieval_idx": 4501 }, { "idx": "cosqa-train-10858", "doc": "configure a list of characters into a string python", "code": "def delimited(items, character='|'):\n \"\"\"Returns a character delimited version of the provided list as a Python string\"\"\"\n return '|'.join(items) if type(items) in (list, tuple, set) else items", "code_tokens": "def delimited ( items , character = '|' ) : return '|' . join ( items ) if type ( items ) in ( list , tuple , set ) else items", "docstring_tokens": "Returns a character delimited version of the provided list as a Python string", "label": 1, "retrieval_idx": 1295 }, { "idx": "cosqa-train-7049", "doc": "python list of self variables", "code": "def vars_(self):\n \"\"\" Returns symbol instances corresponding to variables\n of the current scope.\n \"\"\"\n return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var]", "code_tokens": "def vars_ ( self ) : return [ x for x in self [ self . current_scope ] . values ( ) if x . class_ == CLASS . var ]", "docstring_tokens": "Returns symbol instances corresponding to variables of the current scope .", "label": 1, "retrieval_idx": 3654 }, { "idx": "cosqa-train-9857", "doc": "how to stop streaming data python", "code": "def stop(self):\n \"\"\"Stop stream.\"\"\"\n if self.stream and self.stream.session.state != STATE_STOPPED:\n self.stream.stop()", "code_tokens": "def stop ( self ) : if self . stream and self . stream . session . state != STATE_STOPPED : self . stream . stop ( )", "docstring_tokens": "Stop stream .", "label": 1, "retrieval_idx": 4342 }, { "idx": "cosqa-train-6411", "doc": "python create remote file ssh", "code": "def send_file(self, local_path, remote_path, user='root', unix_mode=None):\n \"\"\"Upload a local file on the remote host.\n \"\"\"\n self.enable_user(user)\n return self.ssh_pool.send_file(user, local_path, remote_path, unix_mode=unix_mode)", "code_tokens": "def send_file ( self , local_path , remote_path , user = 'root' , unix_mode = None ) : self . enable_user ( user ) return self . ssh_pool . send_file ( user , local_path , remote_path , unix_mode = unix_mode )", "docstring_tokens": "Upload a local file on the remote host .", "label": 1, "retrieval_idx": 2924 }, { "idx": "cosqa-train-13354", "doc": "get the first value in a series python", "code": "def reduce_fn(x):\n \"\"\"\n Aggregation function to get the first non-zero value.\n \"\"\"\n values = x.values if pd and isinstance(x, pd.Series) else x\n for v in values:\n if not is_nan(v):\n return v\n return np.NaN", "code_tokens": "def reduce_fn ( x ) : values = x . values if pd and isinstance ( x , pd . Series ) else x for v in values : if not is_nan ( v ) : return v return np . NaN", "docstring_tokens": "Aggregation function to get the first non - zero value .", "label": 1, "retrieval_idx": 621 }, { "idx": "cosqa-train-6848", "doc": "fetch a variable from its name + python", "code": "def _get_var_from_string(item):\n \"\"\" Get resource variable. \"\"\"\n modname, varname = _split_mod_var_names(item)\n if modname:\n mod = __import__(modname, globals(), locals(), [varname], -1)\n return getattr(mod, varname)\n else:\n return globals()[varname]", "code_tokens": "def _get_var_from_string ( item ) : modname , varname = _split_mod_var_names ( item ) if modname : mod = __import__ ( modname , globals ( ) , locals ( ) , [ varname ] , - 1 ) return getattr ( mod , varname ) else : return globals ( ) [ varname ]", "docstring_tokens": "Get resource variable .", "label": 1, "retrieval_idx": 3596 }, { "idx": "cosqa-train-15681", "doc": "how to change dimensions of a window in python", "code": "def setwinsize(self, rows, cols):\n \"\"\"Set the terminal window size of the child tty.\n \"\"\"\n self._winsize = (rows, cols)\n self.pty.set_size(cols, rows)", "code_tokens": "def setwinsize ( self , rows , cols ) : self . _winsize = ( rows , cols ) self . pty . set_size ( cols , rows )", "docstring_tokens": "Set the terminal window size of the child tty .", "label": 1, "retrieval_idx": 2629 }, { "idx": "cosqa-train-7234", "doc": "python numpy array fix dtype", "code": "def dict_to_numpy_array(d):\n \"\"\"\n Convert a dict of 1d array to a numpy recarray\n \"\"\"\n return fromarrays(d.values(), np.dtype([(str(k), v.dtype) for k, v in d.items()]))", "code_tokens": "def dict_to_numpy_array ( d ) : return fromarrays ( d . values ( ) , np . dtype ( [ ( str ( k ) , v . dtype ) for k , v in d . items ( ) ] ) )", "docstring_tokens": "Convert a dict of 1d array to a numpy recarray", "label": 1, "retrieval_idx": 1583 }, { "idx": "cosqa-train-10130", "doc": "python3 extending an empty diff results in none type", "code": "def default_diff(latest_config, current_config):\n \"\"\"Determine if two revisions have actually changed.\"\"\"\n # Pop off the fields we don't care about:\n pop_no_diff_fields(latest_config, current_config)\n\n diff = DeepDiff(\n latest_config,\n current_config,\n ignore_order=True\n )\n return diff", "code_tokens": "def default_diff ( latest_config , current_config ) : # Pop off the fields we don't care about: pop_no_diff_fields ( latest_config , current_config ) diff = DeepDiff ( latest_config , current_config , ignore_order = True ) return diff", "docstring_tokens": "Determine if two revisions have actually changed .", "label": 1, "retrieval_idx": 4047 }, { "idx": "cosqa-train-12663", "doc": "windows cmd python display width", "code": "def get_width():\n \"\"\"Get terminal width\"\"\"\n # Get terminal size\n ws = struct.pack(\"HHHH\", 0, 0, 0, 0)\n ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws)\n lines, columns, x, y = struct.unpack(\"HHHH\", ws)\n width = min(columns * 39 // 40, columns - 2)\n return width", "code_tokens": "def get_width ( ) : # Get terminal size ws = struct . pack ( \"HHHH\" , 0 , 0 , 0 , 0 ) ws = fcntl . ioctl ( sys . stdout . fileno ( ) , termios . TIOCGWINSZ , ws ) lines , columns , x , y = struct . unpack ( \"HHHH\" , ws ) width = min ( columns * 39 // 40 , columns - 2 ) return width", "docstring_tokens": "Get terminal width", "label": 1, "retrieval_idx": 1907 }, { "idx": "cosqa-train-17053", "doc": "top values in list python", "code": "def top(self, topn=10):\n \"\"\"\n Get a list of the top ``topn`` features in this :class:`.Feature`\\.\n\n Examples\n --------\n\n .. code-block:: python\n\n >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])\n >>> myFeature.top(1)\n [('trapezoid', 5)]\n\n Parameters\n ----------\n topn : int\n\n Returns\n -------\n list\n \"\"\"\n return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]", "code_tokens": "def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]", "docstring_tokens": "Get a list of the top topn features in this : class : . Feature \\ .", "label": 1, "retrieval_idx": 5556 }, { "idx": "cosqa-train-16531", "doc": "md5 value of a file python", "code": "def get_file_md5sum(path):\n \"\"\"Calculate the MD5 hash for a file.\"\"\"\n with open(path, 'rb') as fh:\n h = str(hashlib.md5(fh.read()).hexdigest())\n return h", "code_tokens": "def get_file_md5sum ( path ) : with open ( path , 'rb' ) as fh : h = str ( hashlib . md5 ( fh . read ( ) ) . hexdigest ( ) ) return h", "docstring_tokens": "Calculate the MD5 hash for a file .", "label": 1, "retrieval_idx": 1881 }, { "idx": "cosqa-train-2363", "doc": "code to create folders in python", "code": "def mkdir(dir, enter):\n \"\"\"Create directory with template for topic of the current environment\n\n \"\"\"\n\n if not os.path.exists(dir):\n os.makedirs(dir)", "code_tokens": "def mkdir ( dir , enter ) : if not os . path . exists ( dir ) : os . makedirs ( dir )", "docstring_tokens": "Create directory with template for topic of the current environment", "label": 1, "retrieval_idx": 54 }, { "idx": "cosqa-train-17907", "doc": "python check if certain length of input equals something", "code": "def check_lengths(*arrays):\n \"\"\"\n tool to ensure input and output data have the same number of samples\n\n Parameters\n ----------\n *arrays : iterable of arrays to be checked\n\n Returns\n -------\n None\n \"\"\"\n lengths = [len(array) for array in arrays]\n if len(np.unique(lengths)) > 1:\n raise ValueError('Inconsistent data lengths: {}'.format(lengths))", "code_tokens": "def check_lengths ( * arrays ) : lengths = [ len ( array ) for array in arrays ] if len ( np . unique ( lengths ) ) > 1 : raise ValueError ( 'Inconsistent data lengths: {}' . format ( lengths ) )", "docstring_tokens": "tool to ensure input and output data have the same number of samples", "label": 1, "retrieval_idx": 5934 }, { "idx": "cosqa-train-15552", "doc": "python iterate chunks of string", "code": "def generate_chunks(string, num_chars):\n \"\"\"Yield num_chars-character chunks from string.\"\"\"\n for start in range(0, len(string), num_chars):\n yield string[start:start+num_chars]", "code_tokens": "def generate_chunks ( string , num_chars ) : for start in range ( 0 , len ( string ) , num_chars ) : yield string [ start : start + num_chars ]", "docstring_tokens": "Yield num_chars - character chunks from string .", "label": 1, "retrieval_idx": 5338 }, { "idx": "cosqa-train-15711", "doc": "how to check datatype in data frame in python", "code": "def _validate_pos(df):\n \"\"\"Validates the returned positional object\n \"\"\"\n assert isinstance(df, pd.DataFrame)\n assert [\"seqname\", \"position\", \"strand\"] == df.columns.tolist()\n assert df.position.dtype == np.dtype(\"int64\")\n assert df.strand.dtype == np.dtype(\"O\")\n assert df.seqname.dtype == np.dtype(\"O\")\n return df", "code_tokens": "def _validate_pos ( df ) : assert isinstance ( df , pd . DataFrame ) assert [ \"seqname\" , \"position\" , \"strand\" ] == df . columns . tolist ( ) assert df . position . dtype == np . dtype ( \"int64\" ) assert df . strand . dtype == np . dtype ( \"O\" ) assert df . seqname . dtype == np . dtype ( \"O\" ) return df", "docstring_tokens": "Validates the returned positional object", "label": 1, "retrieval_idx": 740 }, { "idx": "cosqa-train-6730", "doc": "python get first object in a list", "code": "def findfirst(f, coll):\n \"\"\"Return first occurrence matching f, otherwise None\"\"\"\n result = list(dropwhile(f, coll))\n return result[0] if result else None", "code_tokens": "def findfirst ( f , coll ) : result = list ( dropwhile ( f , coll ) ) return result [ 0 ] if result else None", "docstring_tokens": "Return first occurrence matching f otherwise None", "label": 1, "retrieval_idx": 598 }, { "idx": "cosqa-train-4464", "doc": "python extract all numbers in a string", "code": "def get_numbers(s):\n \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n result = map(int, re.findall(r'[0-9]+', unicode(s)))\n return result + [1] * (2 - len(result))", "code_tokens": "def get_numbers ( s ) : result = map ( int , re . findall ( r'[0-9]+' , unicode ( s ) ) ) return result + [ 1 ] * ( 2 - len ( result ) )", "docstring_tokens": "Extracts all integers from a string an return them in a list", "label": 1, "retrieval_idx": 2828 }, { "idx": "cosqa-train-7906", "doc": "python unittest assert not raises", "code": "def assert_is_not(expected, actual, message=None, extra=None):\n \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n assert expected is not actual, _assert_fail_message(\n message, expected, actual, \"is\", extra\n )", "code_tokens": "def assert_is_not ( expected , actual , message = None , extra = None ) : assert expected is not actual , _assert_fail_message ( message , expected , actual , \"is\" , extra )", "docstring_tokens": "Raises an AssertionError if expected is actual .", "label": 1, "retrieval_idx": 1307 }, { "idx": "cosqa-train-16444", "doc": "python zmq check if connected", "code": "def start(self, test_connection=True):\n \"\"\"Starts connection to server if not existent.\n\n NO-OP if connection is already established.\n Makes ping-pong test as well if desired.\n\n \"\"\"\n if self._context is None:\n self._logger.debug('Starting Client')\n self._context = zmq.Context()\n self._poll = zmq.Poller()\n self._start_socket()\n if test_connection:\n self.test_ping()", "code_tokens": "def start ( self , test_connection = True ) : if self . _context is None : self . _logger . debug ( 'Starting Client' ) self . _context = zmq . Context ( ) self . _poll = zmq . Poller ( ) self . _start_socket ( ) if test_connection : self . test_ping ( )", "docstring_tokens": "Starts connection to server if not existent .", "label": 1, "retrieval_idx": 5466 }, { "idx": "cosqa-train-17529", "doc": "using string to generate datetime date in python", "code": "def get_from_gnucash26_date(date_str: str) -> date:\n \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n date_format = \"%Y%m%d\"\n result = datetime.strptime(date_str, date_format).date()\n return result", "code_tokens": "def get_from_gnucash26_date ( date_str : str ) -> date : date_format = \"%Y%m%d\" result = datetime . strptime ( date_str , date_format ) . date ( ) return result", "docstring_tokens": "Creates a datetime from GnuCash 2 . 6 date string", "label": 1, "retrieval_idx": 5766 }, { "idx": "cosqa-train-19388", "doc": "python list comprehension flatten", "code": "def flatten_list(l: List[list]) -> list:\n \"\"\" takes a list of lists, l and returns a flat list\n \"\"\"\n return [v for inner_l in l for v in inner_l]", "code_tokens": "def flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]", "docstring_tokens": "takes a list of lists l and returns a flat list", "label": 1, "retrieval_idx": 5705 }, { "idx": "cosqa-train-8434", "doc": "python code remove duplicate labels", "code": "def get_labels(labels):\n \"\"\"Create unique labels.\"\"\"\n label_u = unique_labels(labels)\n label_u_line = [i + \"_line\" for i in label_u]\n return label_u, label_u_line", "code_tokens": "def get_labels ( labels ) : label_u = unique_labels ( labels ) label_u_line = [ i + \"_line\" for i in label_u ] return label_u , label_u_line", "docstring_tokens": "Create unique labels .", "label": 1, "retrieval_idx": 4033 }, { "idx": "cosqa-train-13389", "doc": "heatmap python set the axis limits", "code": "def set_mlimits(self, row, column, min=None, max=None):\n \"\"\"Set limits for the point meta (colormap).\n\n Point meta values outside this range will be clipped.\n\n :param min: value for start of the colormap.\n :param max: value for end of the colormap.\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.set_mlimits(min, max)", "code_tokens": "def set_mlimits ( self , row , column , min = None , max = None ) : subplot = self . get_subplot_at ( row , column ) subplot . set_mlimits ( min , max )", "docstring_tokens": "Set limits for the point meta ( colormap ) .", "label": 1, "retrieval_idx": 4994 }, { "idx": "cosqa-train-19863", "doc": "rotate between items in a list python", "code": "def iprotate(l, steps=1):\n r\"\"\"Like rotate, but modifies `l` in-place.\n\n >>> l = [1,2,3]\n >>> iprotate(l) is l\n True\n >>> l\n [2, 3, 1]\n >>> iprotate(iprotate(l, 2), -3)\n [1, 2, 3]\n\n \"\"\"\n if len(l):\n steps %= len(l)\n if steps:\n firstPart = l[:steps]\n del l[:steps]\n l.extend(firstPart)\n return l", "code_tokens": "def iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l", "docstring_tokens": "r Like rotate but modifies l in - place .", "label": 1, "retrieval_idx": 5735 }, { "idx": "cosqa-train-15897", "doc": "how to exclude item from index python", "code": "def _remove_from_index(index, obj):\n \"\"\"Removes object ``obj`` from the ``index``.\"\"\"\n try:\n index.value_map[indexed_value(index, obj)].remove(obj.id)\n except KeyError:\n pass", "code_tokens": "def _remove_from_index ( index , obj ) : try : index . value_map [ indexed_value ( index , obj ) ] . remove ( obj . id ) except KeyError : pass", "docstring_tokens": "Removes object obj from the index .", "label": 1, "retrieval_idx": 2482 }, { "idx": "cosqa-train-5961", "doc": "remove punctuation and stop words python nltk", "code": "def wordify(text):\n \"\"\"Generate a list of words given text, removing punctuation.\n\n Parameters\n ----------\n text : unicode\n A piece of english text.\n\n Returns\n -------\n words : list\n List of words.\n \"\"\"\n stopset = set(nltk.corpus.stopwords.words('english'))\n tokens = nltk.WordPunctTokenizer().tokenize(text)\n return [w for w in tokens if w not in stopset]", "code_tokens": "def wordify ( text ) : stopset = set ( nltk . corpus . stopwords . words ( 'english' ) ) tokens = nltk . WordPunctTokenizer ( ) . tokenize ( text ) return [ w for w in tokens if w not in stopset ]", "docstring_tokens": "Generate a list of words given text removing punctuation .", "label": 1, "retrieval_idx": 844 }, { "idx": "cosqa-train-6180", "doc": "strip spaces from columns in python", "code": "def strip_columns(tab):\n \"\"\"Strip whitespace from string columns.\"\"\"\n for colname in tab.colnames:\n if tab[colname].dtype.kind in ['S', 'U']:\n tab[colname] = np.core.defchararray.strip(tab[colname])", "code_tokens": "def strip_columns ( tab ) : for colname in tab . colnames : if tab [ colname ] . dtype . kind in [ 'S' , 'U' ] : tab [ colname ] = np . core . defchararray . strip ( tab [ colname ] )", "docstring_tokens": "Strip whitespace from string columns .", "label": 1, "retrieval_idx": 1437 }, { "idx": "cosqa-train-17060", "doc": "python datetime get last month number", "code": "def get_last_day_of_month(t: datetime) -> int:\n \"\"\"\n Returns day number of the last day of the month\n :param t: datetime\n :return: int\n \"\"\"\n tn = t + timedelta(days=32)\n tn = datetime(year=tn.year, month=tn.month, day=1)\n tt = tn - timedelta(hours=1)\n return tt.day", "code_tokens": "def get_last_day_of_month ( t : datetime ) -> int : tn = t + timedelta ( days = 32 ) tn = datetime ( year = tn . year , month = tn . month , day = 1 ) tt = tn - timedelta ( hours = 1 ) return tt . day", "docstring_tokens": "Returns day number of the last day of the month : param t : datetime : return : int", "label": 1, "retrieval_idx": 5645 }, { "idx": "cosqa-train-8210", "doc": "python assertassert no description", "code": "def assert_is_not(expected, actual, message=None, extra=None):\n \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n assert expected is not actual, _assert_fail_message(\n message, expected, actual, \"is\", extra\n )", "code_tokens": "def assert_is_not ( expected , actual , message = None , extra = None ) : assert expected is not actual , _assert_fail_message ( message , expected , actual , \"is\" , extra )", "docstring_tokens": "Raises an AssertionError if expected is actual .", "label": 1, "retrieval_idx": 1307 }, { "idx": "cosqa-train-13784", "doc": "python program calculating angle from two points", "code": "def angle_between_vectors(x, y):\n \"\"\" Compute the angle between vector x and y \"\"\"\n dp = dot_product(x, y)\n if dp == 0:\n return 0\n xm = magnitude(x)\n ym = magnitude(y)\n return math.acos(dp / (xm*ym)) * (180. / math.pi)", "code_tokens": "def angle_between_vectors ( x , y ) : dp = dot_product ( x , y ) if dp == 0 : return 0 xm = magnitude ( x ) ym = magnitude ( y ) return math . acos ( dp / ( xm * ym ) ) * ( 180. / math . pi )", "docstring_tokens": "Compute the angle between vector x and y", "label": 1, "retrieval_idx": 1665 }, { "idx": "cosqa-train-7686", "doc": "python split iterable into batches", "code": "def ibatch(iterable, size):\n \"\"\"Yield a series of batches from iterable, each size elements long.\"\"\"\n source = iter(iterable)\n while True:\n batch = itertools.islice(source, size)\n yield itertools.chain([next(batch)], batch)", "code_tokens": "def ibatch ( iterable , size ) : source = iter ( iterable ) while True : batch = itertools . islice ( source , size ) yield itertools . chain ( [ next ( batch ) ] , batch )", "docstring_tokens": "Yield a series of batches from iterable each size elements long .", "label": 1, "retrieval_idx": 2638 }, { "idx": "cosqa-train-2587", "doc": "easy python decompiler invalid pys file", "code": "def disassemble_file(filename, outstream=None):\n \"\"\"\n disassemble Python byte-code file (.pyc)\n\n If given a Python source file (\".py\") file, we'll\n try to find the corresponding compiled object.\n \"\"\"\n filename = check_object_path(filename)\n (version, timestamp, magic_int, co, is_pypy,\n source_size) = load_module(filename)\n if type(co) == list:\n for con in co:\n disco(version, con, outstream)\n else:\n disco(version, co, outstream, is_pypy=is_pypy)\n co = None", "code_tokens": "def disassemble_file ( filename , outstream = None ) : filename = check_object_path ( filename ) ( version , timestamp , magic_int , co , is_pypy , source_size ) = load_module ( filename ) if type ( co ) == list : for con in co : disco ( version , con , outstream ) else : disco ( version , co , outstream , is_pypy = is_pypy ) co = None", "docstring_tokens": "disassemble Python byte - code file ( . pyc )", "label": 1, "retrieval_idx": 1951 }, { "idx": "cosqa-train-6620", "doc": "close stdin subprocess python", "code": "def _finish(self):\n \"\"\"\n Closes and waits for subprocess to exit.\n \"\"\"\n if self._process.returncode is None:\n self._process.stdin.flush()\n self._process.stdin.close()\n self._process.wait()\n self.closed = True", "code_tokens": "def _finish ( self ) : if self . _process . returncode is None : self . _process . stdin . flush ( ) self . _process . stdin . close ( ) self . _process . wait ( ) self . closed = True", "docstring_tokens": "Closes and waits for subprocess to exit .", "label": 1, "retrieval_idx": 3531 }, { "idx": "cosqa-train-3852", "doc": "remove a value from all keys in a dictionary python", "code": "def _delete_keys(dct, keys):\n \"\"\"Returns a copy of dct without `keys` keys\n \"\"\"\n c = deepcopy(dct)\n assert isinstance(keys, list)\n for k in keys:\n c.pop(k)\n return c", "code_tokens": "def _delete_keys ( dct , keys ) : c = deepcopy ( dct ) assert isinstance ( keys , list ) for k in keys : c . pop ( k ) return c", "docstring_tokens": "Returns a copy of dct without keys keys", "label": 1, "retrieval_idx": 2569 }, { "idx": "cosqa-train-4324", "doc": "assertion error python how to solve", "code": "def process_instance(self, instance):\n self.log.debug(\"e = mc^2\")\n self.log.info(\"About to fail..\")\n self.log.warning(\"Failing.. soooon..\")\n self.log.critical(\"Ok, you're done.\")\n assert False, \"\"\"ValidateFailureMock was destined to fail..\n\nHere's some extended information about what went wrong.\n\nIt has quite the long string associated with it, including\na few newlines and a list.\n\n- Item 1\n- Item 2\n\n\"\"\"", "code_tokens": "def process_instance ( self , instance ) : self . log . debug ( \"e = mc^2\" ) self . log . info ( \"About to fail..\" ) self . log . warning ( \"Failing.. soooon..\" ) self . log . critical ( \"Ok, you're done.\" ) assert False , \"\"\"ValidateFailureMock was destined to fail..\n\nHere's some extended information about what went wrong.\n\nIt has quite the long string associated with it, including\na few newlines and a list.\n\n- Item 1\n- Item 2\n\n\"\"\"", "docstring_tokens": "", "label": 1, "retrieval_idx": 2102 }, { "idx": "cosqa-train-17009", "doc": "python remove words from sentences in a list", "code": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n \"\"\"Remove empty utterances from a list of utterances\n Args:\n utterances: The list of utterance we are processing\n \"\"\"\n return [utter for utter in utterances if utter.text.strip() != \"\"]", "code_tokens": "def remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != \"\" ]", "docstring_tokens": "Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing", "label": 1, "retrieval_idx": 5557 }, { "idx": "cosqa-train-9177", "doc": "python iterate over many regex sub", "code": "def _sub_patterns(patterns, text):\n \"\"\"\n Apply re.sub to bunch of (pattern, repl)\n \"\"\"\n for pattern, repl in patterns:\n text = re.sub(pattern, repl, text)\n return text", "code_tokens": "def _sub_patterns ( patterns , text ) : for pattern , repl in patterns : text = re . sub ( pattern , repl , text ) return text", "docstring_tokens": "Apply re . sub to bunch of ( pattern repl )", "label": 1, "retrieval_idx": 773 }, { "idx": "cosqa-train-11440", "doc": "python multiindex get index freeze", "code": "def validate_multiindex(self, obj):\n \"\"\"validate that we can store the multi-index; reset and return the\n new object\n \"\"\"\n levels = [l if l is not None else \"level_{0}\".format(i)\n for i, l in enumerate(obj.index.names)]\n try:\n return obj.reset_index(), levels\n except ValueError:\n raise ValueError(\"duplicate names/columns in the multi-index when \"\n \"storing as a table\")", "code_tokens": "def validate_multiindex ( self , obj ) : levels = [ l if l is not None else \"level_{0}\" . format ( i ) for i , l in enumerate ( obj . index . names ) ] try : return obj . reset_index ( ) , levels except ValueError : raise ValueError ( \"duplicate names/columns in the multi-index when \" \"storing as a table\" )", "docstring_tokens": "validate that we can store the multi - index ; reset and return the new object", "label": 1, "retrieval_idx": 998 }, { "idx": "cosqa-train-9977", "doc": "python two range union", "code": "def __or__(self, other):\n \"\"\"Return the union of two RangeSets as a new RangeSet.\n\n (I.e. all elements that are in either set.)\n \"\"\"\n if not isinstance(other, set):\n return NotImplemented\n return self.union(other)", "code_tokens": "def __or__ ( self , other ) : if not isinstance ( other , set ) : return NotImplemented return self . union ( other )", "docstring_tokens": "Return the union of two RangeSets as a new RangeSet .", "label": 1, "retrieval_idx": 3372 }, { "idx": "cosqa-train-15226", "doc": "decode object to bytes python", "code": "def _decode(self, obj, context):\n \"\"\"\n Get the python representation of the obj\n \"\"\"\n return b''.join(map(int2byte, [c + 0x60 for c in bytearray(obj)])).decode(\"utf8\")", "code_tokens": "def _decode ( self , obj , context ) : return b'' . join ( map ( int2byte , [ c + 0x60 for c in bytearray ( obj ) ] ) ) . decode ( \"utf8\" )", "docstring_tokens": "Get the python representation of the obj", "label": 1, "retrieval_idx": 4067 }, { "idx": "cosqa-train-14266", "doc": "limit float decimals in python", "code": "def roundClosestValid(val, res, decimals=None):\n \"\"\" round to closest resolution \"\"\"\n if decimals is None and \".\" in str(res):\n decimals = len(str(res).split('.')[1])\n\n return round(round(val / res) * res, decimals)", "code_tokens": "def roundClosestValid ( val , res , decimals = None ) : if decimals is None and \".\" in str ( res ) : decimals = len ( str ( res ) . split ( '.' ) [ 1 ] ) return round ( round ( val / res ) * res , decimals )", "docstring_tokens": "round to closest resolution", "label": 1, "retrieval_idx": 3832 }, { "idx": "cosqa-train-17640", "doc": "delete an element from set python", "code": "def remove_once(gset, elem):\n \"\"\"Remove the element from a set, lists or dict.\n \n >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n >>> print L, S, D\n [] set([]) {}\n\n Returns the element if it was removed. Raises one of the exceptions in \n :obj:`RemoveError` otherwise.\n \"\"\"\n remove = getattr(gset, 'remove', None)\n if remove is not None: remove(elem)\n else: del gset[elem]\n return elem", "code_tokens": "def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem", "docstring_tokens": "Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}", "label": 1, "retrieval_idx": 5741 }, { "idx": "cosqa-train-12232", "doc": "object id in python equivalent in golang", "code": "def generate_id(self, obj):\n \"\"\"Generate unique document id for ElasticSearch.\"\"\"\n object_type = type(obj).__name__.lower()\n return '{}_{}'.format(object_type, self.get_object_id(obj))", "code_tokens": "def generate_id ( self , obj ) : object_type = type ( obj ) . __name__ . lower ( ) return '{}_{}' . format ( object_type , self . get_object_id ( obj ) )", "docstring_tokens": "Generate unique document id for ElasticSearch .", "label": 1, "retrieval_idx": 4302 }, { "idx": "cosqa-train-18797", "doc": "python create dictionary with keys and no values", "code": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n \"\"\"\n Return a new copied dictionary without the keys with ``None`` values from\n the given Mapping object.\n \"\"\"\n return {k: v for k, v in obj.items() if v is not None}", "code_tokens": "def clean_map ( obj : Mapping [ Any , Any ] ) -> Mapping [ Any , Any ] : return { k : v for k , v in obj . items ( ) if v is not None }", "docstring_tokens": "Return a new copied dictionary without the keys with None values from the given Mapping object .", "label": 1, "retrieval_idx": 5748 }, { "idx": "cosqa-train-6195", "doc": "python check if directory is writable", "code": "def _writable_dir(path):\n \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n return os.path.isdir(path) and os.access(path, os.W_OK)", "code_tokens": "def _writable_dir ( path ) : return os . path . isdir ( path ) and os . access ( path , os . W_OK )", "docstring_tokens": "Whether path is a directory to which the user has write access .", "label": 1, "retrieval_idx": 651 }, { "idx": "cosqa-train-15054", "doc": "python df change type", "code": "def _to_corrected_pandas_type(dt):\n \"\"\"\n When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.\n This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.\n \"\"\"\n import numpy as np\n if type(dt) == ByteType:\n return np.int8\n elif type(dt) == ShortType:\n return np.int16\n elif type(dt) == IntegerType:\n return np.int32\n elif type(dt) == FloatType:\n return np.float32\n else:\n return None", "code_tokens": "def _to_corrected_pandas_type ( dt ) : import numpy as np if type ( dt ) == ByteType : return np . int8 elif type ( dt ) == ShortType : return np . int16 elif type ( dt ) == IntegerType : return np . int32 elif type ( dt ) == FloatType : return np . float32 else : return None", "docstring_tokens": "When converting Spark SQL records to Pandas DataFrame the inferred data type may be wrong . This method gets the corrected data type for Pandas if that type may be inferred uncorrectly .", "label": 1, "retrieval_idx": 170 }, { "idx": "cosqa-train-11747", "doc": "how to put json in file python", "code": "def save(self, fname):\n \"\"\" Saves the dictionary in json format\n :param fname: file to save to\n \"\"\"\n with open(fname, 'wb') as f:\n json.dump(self, f)", "code_tokens": "def save ( self , fname ) : with open ( fname , 'wb' ) as f : json . dump ( self , f )", "docstring_tokens": "Saves the dictionary in json format : param fname : file to save to", "label": 1, "retrieval_idx": 686 }, { "idx": "cosqa-train-14568", "doc": "set a rect to a variable python", "code": "def setRect(self, rect):\n\t\t\"\"\"\n\t\tSets the window bounds from a tuple of (x,y,w,h)\n\t\t\"\"\"\n\t\tself.x, self.y, self.w, self.h = rect", "code_tokens": "def setRect ( self , rect ) : self . x , self . y , self . w , self . h = rect", "docstring_tokens": "Sets the window bounds from a tuple of ( x y w h )", "label": 1, "retrieval_idx": 5190 }, { "idx": "cosqa-train-16821", "doc": "python borderless table via format function", "code": "def adapter(data, headers, **kwargs):\n \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n keys = ('sep_title', 'sep_character', 'sep_length')\n return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "code_tokens": "def adapter ( data , headers , * * kwargs ) : keys = ( 'sep_title' , 'sep_character' , 'sep_length' ) return vertical_table ( data , headers , * * filter_dict_by_key ( kwargs , keys ) )", "docstring_tokens": "Wrap vertical table in a function for TabularOutputFormatter .", "label": 1, "retrieval_idx": 2196 }, { "idx": "cosqa-train-16226", "doc": "how to select region in array python", "code": "def select_from_array(cls, array, identifier):\n \"\"\"Return a region from a numpy array.\n \n :param array: :class:`numpy.ndarray`\n :param identifier: value representing the region to select in the array\n :returns: :class:`jicimagelib.region.Region`\n \"\"\"\n\n base_array = np.zeros(array.shape)\n array_coords = np.where(array == identifier)\n base_array[array_coords] = 1\n\n return cls(base_array)", "code_tokens": "def select_from_array ( cls , array , identifier ) : base_array = np . zeros ( array . shape ) array_coords = np . where ( array == identifier ) base_array [ array_coords ] = 1 return cls ( base_array )", "docstring_tokens": "Return a region from a numpy array . : param array : : class : numpy . ndarray : param identifier : value representing the region to select in the array : returns : : class : jicimagelib . region . Region", "label": 1, "retrieval_idx": 3783 }, { "idx": "cosqa-train-9169", "doc": "python is not not none", "code": "def less_strict_bool(x):\n \"\"\"Idempotent and None-safe version of strict_bool.\"\"\"\n if x is None:\n return False\n elif x is True or x is False:\n return x\n else:\n return strict_bool(x)", "code_tokens": "def less_strict_bool ( x ) : if x is None : return False elif x is True or x is False : return x else : return strict_bool ( x )", "docstring_tokens": "Idempotent and None - safe version of strict_bool .", "label": 1, "retrieval_idx": 908 }, { "idx": "cosqa-train-12818", "doc": "python dir is writable", "code": "def is_writable_by_others(filename):\n \"\"\"Check if file or directory is world writable.\"\"\"\n mode = os.stat(filename)[stat.ST_MODE]\n return mode & stat.S_IWOTH", "code_tokens": "def is_writable_by_others ( filename ) : mode = os . stat ( filename ) [ stat . ST_MODE ] return mode & stat . S_IWOTH", "docstring_tokens": "Check if file or directory is world writable .", "label": 1, "retrieval_idx": 3186 }, { "idx": "cosqa-train-12797", "doc": "behave python element not visible", "code": "def show(self):\n \"\"\" Ensure the widget is shown.\n Calling this method will also set the widget visibility to True.\n \"\"\"\n self.visible = True\n if self.proxy_is_active:\n self.proxy.ensure_visible()", "code_tokens": "def show ( self ) : self . visible = True if self . proxy_is_active : self . proxy . ensure_visible ( )", "docstring_tokens": "Ensure the widget is shown . Calling this method will also set the widget visibility to True .", "label": 1, "retrieval_idx": 4884 }, { "idx": "cosqa-train-2191", "doc": "python detect change of slope", "code": "def click_estimate_slope():\n \"\"\"\n Takes two clicks and returns the slope.\n\n Right-click aborts.\n \"\"\"\n\n c1 = _pylab.ginput()\n if len(c1)==0:\n return None\n\n c2 = _pylab.ginput()\n if len(c2)==0:\n return None\n\n return (c1[0][1]-c2[0][1])/(c1[0][0]-c2[0][0])", "code_tokens": "def click_estimate_slope ( ) : c1 = _pylab . ginput ( ) if len ( c1 ) == 0 : return None c2 = _pylab . ginput ( ) if len ( c2 ) == 0 : return None return ( c1 [ 0 ] [ 1 ] - c2 [ 0 ] [ 1 ] ) / ( c1 [ 0 ] [ 0 ] - c2 [ 0 ] [ 0 ] )", "docstring_tokens": "Takes two clicks and returns the slope .", "label": 1, "retrieval_idx": 1724 }, { "idx": "cosqa-train-7844", "doc": "python tkinter unchecking checkbutton change variable", "code": "def checkbox_uncheck(self, force_check=False):\n \"\"\"\n Wrapper to uncheck a checkbox\n \"\"\"\n if self.get_attribute('checked'):\n self.click(force_click=force_check)", "code_tokens": "def checkbox_uncheck ( self , force_check = False ) : if self . get_attribute ( 'checked' ) : self . click ( force_click = force_check )", "docstring_tokens": "Wrapper to uncheck a checkbox", "label": 1, "retrieval_idx": 1582 }, { "idx": "cosqa-train-11288", "doc": "python json dumps numpy key", "code": "def deserialize_ndarray_npy(d):\n \"\"\"\n Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's\n :obj:`save` function.\n\n Args:\n d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created\n using :obj:`numpy.save`.\n\n Returns:\n An :obj:`ndarray` object.\n \"\"\"\n with io.BytesIO() as f:\n f.write(json.loads(d['npy']).encode('latin-1'))\n f.seek(0)\n return np.load(f)", "code_tokens": "def deserialize_ndarray_npy ( d ) : with io . BytesIO ( ) as f : f . write ( json . loads ( d [ 'npy' ] ) . encode ( 'latin-1' ) ) f . seek ( 0 ) return np . load ( f )", "docstring_tokens": "Deserializes a JSONified : obj : numpy . ndarray that was created using numpy s : obj : save function .", "label": 1, "retrieval_idx": 231 }, { "idx": "cosqa-train-11349", "doc": "how to change python input to upper case", "code": "def clean(some_string, uppercase=False):\n \"\"\"\n helper to clean up an input string\n \"\"\"\n if uppercase:\n return some_string.strip().upper()\n else:\n return some_string.strip().lower()", "code_tokens": "def clean ( some_string , uppercase = False ) : if uppercase : return some_string . strip ( ) . upper ( ) else : return some_string . strip ( ) . lower ( )", "docstring_tokens": "helper to clean up an input string", "label": 1, "retrieval_idx": 3327 }, { "idx": "cosqa-train-13590", "doc": "python minidom html to dict", "code": "def tag_to_dict(html):\n \"\"\"Extract tag's attributes into a `dict`.\"\"\"\n\n element = document_fromstring(html).xpath(\"//html/body/child::*\")[0]\n attributes = dict(element.attrib)\n attributes[\"text\"] = element.text_content()\n return attributes", "code_tokens": "def tag_to_dict ( html ) : element = document_fromstring ( html ) . xpath ( \"//html/body/child::*\" ) [ 0 ] attributes = dict ( element . attrib ) attributes [ \"text\" ] = element . text_content ( ) return attributes", "docstring_tokens": "Extract tag s attributes into a dict .", "label": 1, "retrieval_idx": 5031 }, { "idx": "cosqa-train-11787", "doc": "how to remove punctuation and special charachhters in python", "code": "def slugify(s, delimiter='-'):\n \"\"\"\n Normalize `s` into ASCII and replace non-word characters with `delimiter`.\n \"\"\"\n s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')\n return RE_SLUG.sub(delimiter, s).strip(delimiter).lower()", "code_tokens": "def slugify ( s , delimiter = '-' ) : s = unicodedata . normalize ( 'NFKD' , to_unicode ( s ) ) . encode ( 'ascii' , 'ignore' ) . decode ( 'ascii' ) return RE_SLUG . sub ( delimiter , s ) . strip ( delimiter ) . lower ( )", "docstring_tokens": "Normalize s into ASCII and replace non - word characters with delimiter .", "label": 1, "retrieval_idx": 4718 }, { "idx": "cosqa-train-12625", "doc": "update figure in python to show change", "code": "def OnUpdateFigurePanel(self, event):\n \"\"\"Redraw event handler for the figure panel\"\"\"\n\n if self.updating:\n return\n\n self.updating = True\n self.figure_panel.update(self.get_figure(self.code))\n self.updating = False", "code_tokens": "def OnUpdateFigurePanel ( self , event ) : if self . updating : return self . updating = True self . figure_panel . update ( self . get_figure ( self . code ) ) self . updating = False", "docstring_tokens": "Redraw event handler for the figure panel", "label": 1, "retrieval_idx": 1999 }, { "idx": "cosqa-dev-398", "doc": "python hashlib of entire file", "code": "def _hash_the_file(hasher, filename):\n \"\"\"Helper function for creating hash functions.\n\n See implementation of :func:`dtoolcore.filehasher.shasum`\n for more usage details.\n \"\"\"\n BUF_SIZE = 65536\n with open(filename, 'rb') as f:\n buf = f.read(BUF_SIZE)\n while len(buf) > 0:\n hasher.update(buf)\n buf = f.read(BUF_SIZE)\n return hasher", "code_tokens": "def _hash_the_file ( hasher , filename ) : BUF_SIZE = 65536 with open ( filename , 'rb' ) as f : buf = f . read ( BUF_SIZE ) while len ( buf ) > 0 : hasher . update ( buf ) buf = f . read ( BUF_SIZE ) return hasher", "docstring_tokens": "Helper function for creating hash functions .", "label": 1, "retrieval_idx": 5995 }, { "idx": "cosqa-train-9109", "doc": "get processing power from other devices in python", "code": "def get_power(self):\n \"\"\"Check if the device is on.\"\"\"\n power = (yield from self.handle_int(self.API.get('power')))\n return bool(power)", "code_tokens": "def get_power ( self ) : power = ( yield from self . handle_int ( self . API . get ( 'power' ) ) ) return bool ( power )", "docstring_tokens": "Check if the device is on .", "label": 1, "retrieval_idx": 4170 }, { "idx": "cosqa-train-13087", "doc": "python get hash of file filestorage", "code": "def get_hash(self, handle):\n \"\"\"Return the hash.\"\"\"\n fpath = self._fpath_from_handle(handle)\n return DiskStorageBroker.hasher(fpath)", "code_tokens": "def get_hash ( self , handle ) : fpath = self . _fpath_from_handle ( handle ) return DiskStorageBroker . hasher ( fpath )", "docstring_tokens": "Return the hash .", "label": 1, "retrieval_idx": 4926 }, { "idx": "cosqa-train-19257", "doc": "how to detect number of cpu cores in python", "code": "def cpu_count() -> int:\n \"\"\"Returns the number of processors on this machine.\"\"\"\n if multiprocessing is None:\n return 1\n try:\n return multiprocessing.cpu_count()\n except NotImplementedError:\n pass\n try:\n return os.sysconf(\"SC_NPROCESSORS_CONF\")\n except (AttributeError, ValueError):\n pass\n gen_log.error(\"Could not detect number of processors; assuming 1\")\n return 1", "code_tokens": "def cpu_count ( ) -> int : if multiprocessing is None : return 1 try : return multiprocessing . cpu_count ( ) except NotImplementedError : pass try : return os . sysconf ( \"SC_NPROCESSORS_CONF\" ) except ( AttributeError , ValueError ) : pass gen_log . error ( \"Could not detect number of processors; assuming 1\" ) return 1", "docstring_tokens": "Returns the number of processors on this machine .", "label": 1, "retrieval_idx": 5653 }, { "idx": "cosqa-train-7630", "doc": "how to return the index of a number in a list python", "code": "def is_in(self, search_list, pair):\n \"\"\"\n If pair is in search_list, return the index. Otherwise return -1\n \"\"\"\n index = -1\n for nr, i in enumerate(search_list):\n if(np.all(i == pair)):\n return nr\n return index", "code_tokens": "def is_in ( self , search_list , pair ) : index = - 1 for nr , i in enumerate ( search_list ) : if ( np . all ( i == pair ) ) : return nr return index", "docstring_tokens": "If pair is in search_list return the index . Otherwise return - 1", "label": 1, "retrieval_idx": 2444 }, { "idx": "cosqa-train-15644", "doc": "python list of all objects", "code": "def getAllTriples(self):\n \"\"\"Returns:\n\n list of tuples : Each tuple holds a subject, predicate, object triple\n\n \"\"\"\n return [(str(s), str(p), str(o)) for s, p, o in self]", "code_tokens": "def getAllTriples ( self ) : return [ ( str ( s ) , str ( p ) , str ( o ) ) for s , p , o in self ]", "docstring_tokens": "Returns :", "label": 1, "retrieval_idx": 5351 }, { "idx": "cosqa-train-15556", "doc": "python iterate regex matches", "code": "def iter_finds(regex_obj, s):\n \"\"\"Generate all matches found within a string for a regex and yield each match as a string\"\"\"\n if isinstance(regex_obj, str):\n for m in re.finditer(regex_obj, s):\n yield m.group()\n else:\n for m in regex_obj.finditer(s):\n yield m.group()", "code_tokens": "def iter_finds ( regex_obj , s ) : if isinstance ( regex_obj , str ) : for m in re . finditer ( regex_obj , s ) : yield m . group ( ) else : for m in regex_obj . finditer ( s ) : yield m . group ( )", "docstring_tokens": "Generate all matches found within a string for a regex and yield each match as a string", "label": 1, "retrieval_idx": 326 }, { "idx": "cosqa-train-6760", "doc": "python get rid of comments in json string", "code": "def strip_comments(string, comment_symbols=frozenset(('#', '//'))):\n \"\"\"Strip comments from json string.\n\n :param string: A string containing json with comments started by comment_symbols.\n :param comment_symbols: Iterable of symbols that start a line comment (default # or //).\n :return: The string with the comments removed.\n \"\"\"\n lines = string.splitlines()\n for k in range(len(lines)):\n for symbol in comment_symbols:\n lines[k] = strip_comment_line_with_symbol(lines[k], start=symbol)\n return '\\n'.join(lines)", "code_tokens": "def strip_comments ( string , comment_symbols = frozenset ( ( '#' , '//' ) ) ) : lines = string . splitlines ( ) for k in range ( len ( lines ) ) : for symbol in comment_symbols : lines [ k ] = strip_comment_line_with_symbol ( lines [ k ] , start = symbol ) return '\\n' . join ( lines )", "docstring_tokens": "Strip comments from json string .", "label": 1, "retrieval_idx": 3569 }, { "idx": "cosqa-train-19008", "doc": "python code to check if line in file exists", "code": "def is_line_in_file(filename: str, line: str) -> bool:\n \"\"\"\n Detects whether a line is present within a file.\n\n Args:\n filename: file to check\n line: line to search for (as an exact match)\n \"\"\"\n assert \"\\n\" not in line\n with open(filename, \"r\") as file:\n for fileline in file:\n if fileline == line:\n return True\n return False", "code_tokens": "def is_line_in_file ( filename : str , line : str ) -> bool : assert \"\\n\" not in line with open ( filename , \"r\" ) as file : for fileline in file : if fileline == line : return True return False", "docstring_tokens": "Detects whether a line is present within a file .", "label": 1, "retrieval_idx": 5707 }, { "idx": "cosqa-train-17655", "doc": "python thread spawn async", "code": "async def async_run(self) -> None:\n \"\"\"\n Asynchronously run the worker, does not close connections. Useful when testing.\n \"\"\"\n self.main_task = self.loop.create_task(self.main())\n await self.main_task", "code_tokens": "async def async_run ( self ) -> None : self . main_task = self . loop . create_task ( self . main ( ) ) await self . main_task", "docstring_tokens": "Asynchronously run the worker does not close connections . Useful when testing .", "label": 1, "retrieval_idx": 5728 }, { "idx": "cosqa-train-12713", "doc": "python \"not is none\" \"is not none\"", "code": "def _not_none(items):\n \"\"\"Whether the item is a placeholder or contains a placeholder.\"\"\"\n if not isinstance(items, (tuple, list)):\n items = (items,)\n return all(item is not _none for item in items)", "code_tokens": "def _not_none ( items ) : if not isinstance ( items , ( tuple , list ) ) : items = ( items , ) return all ( item is not _none for item in items )", "docstring_tokens": "Whether the item is a placeholder or contains a placeholder .", "label": 1, "retrieval_idx": 208 }, { "idx": "cosqa-train-10777", "doc": "check if attribute exists python", "code": "def has_attribute(module_name, attribute_name):\n \"\"\"Is this attribute present?\"\"\"\n init_file = '%s/__init__.py' % module_name\n return any(\n [attribute_name in init_line for init_line in open(init_file).readlines()]\n )", "code_tokens": "def has_attribute ( module_name , attribute_name ) : init_file = '%s/__init__.py' % module_name return any ( [ attribute_name in init_line for init_line in open ( init_file ) . readlines ( ) ] )", "docstring_tokens": "Is this attribute present?", "label": 1, "retrieval_idx": 1239 }, { "idx": "cosqa-train-7485", "doc": "python remove non printing characters", "code": "def drop_bad_characters(text):\n \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n also any whitespace characters that aren't space.\n\n :arg str text: the text to fix\n\n :returns: text with all bad characters dropped\n\n \"\"\"\n # Strip all non-ascii and non-printable characters\n text = ''.join([c for c in text if c in ALLOWED_CHARS])\n return text", "code_tokens": "def drop_bad_characters ( text ) : # Strip all non-ascii and non-printable characters text = '' . join ( [ c for c in text if c in ALLOWED_CHARS ] ) return text", "docstring_tokens": "Takes a text and drops all non - printable and non - ascii characters and also any whitespace characters that aren t space .", "label": 1, "retrieval_idx": 1217 }, { "idx": "cosqa-train-13755", "doc": "python pool imap mutltiple argements", "code": "def imapchain(*a, **kwa):\n \"\"\" Like map but also chains the results. \"\"\"\n\n imap_results = map( *a, **kwa )\n return itertools.chain( *imap_results )", "code_tokens": "def imapchain ( * a , * * kwa ) : imap_results = map ( * a , * * kwa ) return itertools . chain ( * imap_results )", "docstring_tokens": "Like map but also chains the results .", "label": 1, "retrieval_idx": 3696 }, { "idx": "cosqa-train-6799", "doc": "drop column if all column values are nan in python", "code": "def clean_df(df, fill_nan=True, drop_empty_columns=True):\n \"\"\"Clean a pandas dataframe by:\n 1. Filling empty values with Nan\n 2. Dropping columns with all empty values\n\n Args:\n df: Pandas DataFrame\n fill_nan (bool): If any empty values (strings, None, etc) should be replaced with NaN\n drop_empty_columns (bool): If columns whose values are all empty should be dropped\n\n Returns:\n DataFrame: cleaned DataFrame\n\n \"\"\"\n if fill_nan:\n df = df.fillna(value=np.nan)\n if drop_empty_columns:\n df = df.dropna(axis=1, how='all')\n return df.sort_index()", "code_tokens": "def clean_df ( df , fill_nan = True , drop_empty_columns = True ) : if fill_nan : df = df . fillna ( value = np . nan ) if drop_empty_columns : df = df . dropna ( axis = 1 , how = 'all' ) return df . sort_index ( )", "docstring_tokens": "Clean a pandas dataframe by : 1 . Filling empty values with Nan 2 . Dropping columns with all empty values", "label": 1, "retrieval_idx": 2333 }, { "idx": "cosqa-train-12555", "doc": "python check if end of file reached", "code": "def eof(fd):\n \"\"\"Determine if end-of-file is reached for file fd.\"\"\"\n b = fd.read(1)\n end = len(b) == 0\n if not end:\n curpos = fd.tell()\n fd.seek(curpos - 1)\n return end", "code_tokens": "def eof ( fd ) : b = fd . read ( 1 ) end = len ( b ) == 0 if not end : curpos = fd . tell ( ) fd . seek ( curpos - 1 ) return end", "docstring_tokens": "Determine if end - of - file is reached for file fd .", "label": 1, "retrieval_idx": 2556 }, { "idx": "cosqa-train-14576", "doc": "set table widget cell width python", "code": "def table_width(self):\n \"\"\"Return the width of the table including padding and borders.\"\"\"\n outer_widths = max_dimensions(self.table_data, self.padding_left, self.padding_right)[2]\n outer_border = 2 if self.outer_border else 0\n inner_border = 1 if self.inner_column_border else 0\n return table_width(outer_widths, outer_border, inner_border)", "code_tokens": "def table_width ( self ) : outer_widths = max_dimensions ( self . table_data , self . padding_left , self . padding_right ) [ 2 ] outer_border = 2 if self . outer_border else 0 inner_border = 1 if self . inner_column_border else 0 return table_width ( outer_widths , outer_border , inner_border )", "docstring_tokens": "Return the width of the table including padding and borders .", "label": 1, "retrieval_idx": 2671 }, { "idx": "cosqa-train-9012", "doc": "from json to obejct python", "code": "def json(body, charset='utf-8', **kwargs):\n \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n return json_converter.loads(text(body, charset=charset))", "code_tokens": "def json ( body , charset = 'utf-8' , * * kwargs ) : return json_converter . loads ( text ( body , charset = charset ) )", "docstring_tokens": "Takes JSON formatted data converting it into native Python objects", "label": 1, "retrieval_idx": 2057 }, { "idx": "cosqa-train-8054", "doc": "redis python get list length", "code": "def llen(self, name):\n \"\"\"\n Returns the length of the list.\n\n :param name: str the name of the redis key\n :return: Future()\n \"\"\"\n with self.pipe as pipe:\n return pipe.llen(self.redis_key(name))", "code_tokens": "def llen ( self , name ) : with self . pipe as pipe : return pipe . llen ( self . redis_key ( name ) )", "docstring_tokens": "Returns the length of the list .", "label": 1, "retrieval_idx": 3940 }, { "idx": "cosqa-train-14439", "doc": "proxy setup for python", "code": "def _prepare_proxy(self, conn):\n \"\"\"\n Establish tunnel connection early, because otherwise httplib\n would improperly set Host: header to proxy's IP:port.\n \"\"\"\n conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n conn.connect()", "code_tokens": "def _prepare_proxy ( self , conn ) : conn . set_tunnel ( self . _proxy_host , self . port , self . proxy_headers ) conn . connect ( )", "docstring_tokens": "Establish tunnel connection early because otherwise httplib would improperly set Host : header to proxy s IP : port .", "label": 1, "retrieval_idx": 2519 }, { "idx": "cosqa-train-12630", "doc": "python check type equals to", "code": "def is_value_type_valid_for_exact_conditions(self, value):\n \"\"\" Method to validate if the value is valid for exact match type evaluation.\n\n Args:\n value: Value to validate.\n\n Returns:\n Boolean: True if value is a string, boolean, or number. Otherwise False.\n \"\"\"\n # No need to check for bool since bool is a subclass of int\n if isinstance(value, string_types) or isinstance(value, (numbers.Integral, float)):\n return True\n\n return False", "code_tokens": "def is_value_type_valid_for_exact_conditions ( self , value ) : # No need to check for bool since bool is a subclass of int if isinstance ( value , string_types ) or isinstance ( value , ( numbers . Integral , float ) ) : return True return False", "docstring_tokens": "Method to validate if the value is valid for exact match type evaluation .", "label": 1, "retrieval_idx": 3056 }, { "idx": "cosqa-train-9617", "doc": "python remove none values from a list", "code": "def filter_none(list_of_points):\n \"\"\"\n \n :param list_of_points: \n :return: list_of_points with None's removed\n \"\"\"\n remove_elementnone = filter(lambda p: p is not None, list_of_points)\n remove_sublistnone = filter(lambda p: not contains_none(p), remove_elementnone)\n return list(remove_sublistnone)", "code_tokens": "def filter_none ( list_of_points ) : remove_elementnone = filter ( lambda p : p is not None , list_of_points ) remove_sublistnone = filter ( lambda p : not contains_none ( p ) , remove_elementnone ) return list ( remove_sublistnone )", "docstring_tokens": ": param list_of_points : : return : list_of_points with None s removed", "label": 1, "retrieval_idx": 1219 }, { "idx": "cosqa-train-9776", "doc": "how to see all variables in python", "code": "def caller_locals():\n \"\"\"Get the local variables in the caller's frame.\"\"\"\n import inspect\n frame = inspect.currentframe()\n try:\n return frame.f_back.f_back.f_locals\n finally:\n del frame", "code_tokens": "def caller_locals ( ) : import inspect frame = inspect . currentframe ( ) try : return frame . f_back . f_back . f_locals finally : del frame", "docstring_tokens": "Get the local variables in the caller s frame .", "label": 1, "retrieval_idx": 4156 }, { "idx": "cosqa-train-8493", "doc": "python create a filter with cutoff frequency", "code": "def fft_bandpassfilter(data, fs, lowcut, highcut):\n \"\"\"\n http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801\n \"\"\"\n fft = np.fft.fft(data)\n # n = len(data)\n # timestep = 1.0 / fs\n # freq = np.fft.fftfreq(n, d=timestep)\n bp = fft.copy()\n\n # Zero out fft coefficients\n # bp[10:-10] = 0\n\n # Normalise\n # bp *= real(fft.dot(fft))/real(bp.dot(bp))\n\n bp *= fft.dot(fft) / bp.dot(bp)\n\n # must multipy by 2 to get the correct amplitude\n ibp = 12 * np.fft.ifft(bp)\n return ibp", "code_tokens": "def fft_bandpassfilter ( data , fs , lowcut , highcut ) : fft = np . fft . fft ( data ) # n = len(data) # timestep = 1.0 / fs # freq = np.fft.fftfreq(n, d=timestep) bp = fft . copy ( ) # Zero out fft coefficients # bp[10:-10] = 0 # Normalise # bp *= real(fft.dot(fft))/real(bp.dot(bp)) bp *= fft . dot ( fft ) / bp . dot ( bp ) # must multipy by 2 to get the correct amplitude ibp = 12 * np . fft . ifft ( bp ) return ibp", "docstring_tokens": "http : // www . swharden . com / blog / 2009 - 01 - 21 - signal - filtering - with - python / #comment - 16801", "label": 1, "retrieval_idx": 1552 }, { "idx": "cosqa-train-17070", "doc": "python shuffle columns of a matrix", "code": "def _reshuffle(mat, shape):\n \"\"\"Reshuffle the indicies of a bipartite matrix A[ij,kl] -> A[lj,ki].\"\"\"\n return np.reshape(\n np.transpose(np.reshape(mat, shape), (3, 1, 2, 0)),\n (shape[3] * shape[1], shape[0] * shape[2]))", "code_tokens": "def _reshuffle ( mat , shape ) : return np . reshape ( np . transpose ( np . reshape ( mat , shape ) , ( 3 , 1 , 2 , 0 ) ) , ( shape [ 3 ] * shape [ 1 ] , shape [ 0 ] * shape [ 2 ] ) )", "docstring_tokens": "Reshuffle the indicies of a bipartite matrix A [ ij kl ] - > A [ lj ki ] .", "label": 1, "retrieval_idx": 5652 }, { "idx": "cosqa-train-12756", "doc": "python delete all listswith similar name", "code": "def distinct(l):\n \"\"\"\n Return a list where the duplicates have been removed.\n\n Args:\n l (list): the list to filter.\n\n Returns:\n list: the same list without duplicates.\n \"\"\"\n seen = set()\n seen_add = seen.add\n return (_ for _ in l if not (_ in seen or seen_add(_)))", "code_tokens": "def distinct ( l ) : seen = set ( ) seen_add = seen . add return ( _ for _ in l if not ( _ in seen or seen_add ( _ ) ) )", "docstring_tokens": "Return a list where the duplicates have been removed .", "label": 1, "retrieval_idx": 2294 }, { "idx": "cosqa-train-14531", "doc": "round numbers in array to nearest whole python", "code": "def round_array(array_in):\n \"\"\"\n arr_out = round_array(array_in)\n\n Rounds an array and recasts it to int. Also works on scalars.\n \"\"\"\n if isinstance(array_in, ndarray):\n return np.round(array_in).astype(int)\n else:\n return int(np.round(array_in))", "code_tokens": "def round_array ( array_in ) : if isinstance ( array_in , ndarray ) : return np . round ( array_in ) . astype ( int ) else : return int ( np . round ( array_in ) )", "docstring_tokens": "arr_out = round_array ( array_in )", "label": 1, "retrieval_idx": 1487 }, { "idx": "cosqa-train-12901", "doc": "change utc time to relative time python", "code": "def datetime_local_to_utc(local):\n \"\"\"\n Simple function to convert naive :std:`datetime.datetime` object containing\n local time to a naive :std:`datetime.datetime` object with UTC time.\n \"\"\"\n timestamp = time.mktime(local.timetuple())\n return datetime.datetime.utcfromtimestamp(timestamp)", "code_tokens": "def datetime_local_to_utc ( local ) : timestamp = time . mktime ( local . timetuple ( ) ) return datetime . datetime . utcfromtimestamp ( timestamp )", "docstring_tokens": "Simple function to convert naive : std : datetime . datetime object containing local time to a naive : std : datetime . datetime object with UTC time .", "label": 1, "retrieval_idx": 737 }, { "idx": "cosqa-train-9276", "doc": "how to check if file is not empty python", "code": "def file_empty(fp):\n \"\"\"Determine if a file is empty or not.\"\"\"\n # for python 2 we need to use a homemade peek()\n if six.PY2:\n contents = fp.read()\n fp.seek(0)\n return not bool(contents)\n\n else:\n return not fp.peek()", "code_tokens": "def file_empty ( fp ) : # for python 2 we need to use a homemade peek() if six . PY2 : contents = fp . read ( ) fp . seek ( 0 ) return not bool ( contents ) else : return not fp . peek ( )", "docstring_tokens": "Determine if a file is empty or not .", "label": 1, "retrieval_idx": 286 }, { "idx": "cosqa-train-10655", "doc": "area of a triangle using python", "code": "def get_tri_area(pts):\n \"\"\"\n Given a list of coords for 3 points,\n Compute the area of this triangle.\n\n Args:\n pts: [a, b, c] three points\n \"\"\"\n a, b, c = pts[0], pts[1], pts[2]\n v1 = np.array(b) - np.array(a)\n v2 = np.array(c) - np.array(a)\n area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2)\n return area_tri", "code_tokens": "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", "docstring_tokens": "Given a list of coords for 3 points Compute the area of this triangle .", "label": 1, "retrieval_idx": 58 }, { "idx": "cosqa-train-13534", "doc": "python make a copy not reference", "code": "def copy(obj):\n def copy(self):\n \"\"\"\n Copy self to a new object.\n \"\"\"\n from copy import deepcopy\n\n return deepcopy(self)\n obj.copy = copy\n return obj", "code_tokens": "def copy ( obj ) : def copy ( self ) : \"\"\"\n Copy self to a new object.\n \"\"\" from copy import deepcopy return deepcopy ( self ) obj . copy = copy return obj", "docstring_tokens": "", "label": 1, "retrieval_idx": 1395 }, { "idx": "cosqa-train-4709", "doc": "python heappush max heap", "code": "def _heapify_max(x):\n \"\"\"Transform list into a maxheap, in-place, in O(len(x)) time.\"\"\"\n n = len(x)\n for i in reversed(range(n//2)):\n _siftup_max(x, i)", "code_tokens": "def _heapify_max ( x ) : n = len ( x ) for i in reversed ( range ( n // 2 ) ) : _siftup_max ( x , i )", "docstring_tokens": "Transform list into a maxheap in - place in O ( len ( x )) time .", "label": 1, "retrieval_idx": 511 }, { "idx": "cosqa-train-5880", "doc": "pythonreturn json file from a function", "code": "def information(filename):\n \"\"\"Returns the file exif\"\"\"\n check_if_this_file_exist(filename)\n filename = os.path.abspath(filename)\n result = get_json(filename)\n result = result[0]\n return result", "code_tokens": "def information ( filename ) : check_if_this_file_exist ( filename ) filename = os . path . abspath ( filename ) result = get_json ( filename ) result = result [ 0 ] return result", "docstring_tokens": "Returns the file exif", "label": 1, "retrieval_idx": 2145 }, { "idx": "cosqa-train-12563", "doc": "python check if file can be opened", "code": "def is_readable(filename):\n \"\"\"Check if file is a regular file and is readable.\"\"\"\n return os.path.isfile(filename) and os.access(filename, os.R_OK)", "code_tokens": "def is_readable ( filename ) : return os . path . isfile ( filename ) and os . access ( filename , os . R_OK )", "docstring_tokens": "Check if file is a regular file and is readable .", "label": 1, "retrieval_idx": 2445 }, { "idx": "cosqa-train-17092", "doc": "python lastworking day of month", "code": "def get_last_weekday_in_month(year, month, weekday):\n \"\"\"Get the last weekday in a given month. e.g:\n\n >>> # the last monday in Jan 2013\n >>> Calendar.get_last_weekday_in_month(2013, 1, MON)\n datetime.date(2013, 1, 28)\n \"\"\"\n day = date(year, month, monthrange(year, month)[1])\n while True:\n if day.weekday() == weekday:\n break\n day = day - timedelta(days=1)\n return day", "code_tokens": "def get_last_weekday_in_month ( year , month , weekday ) : day = date ( year , month , monthrange ( year , month ) [ 1 ] ) while True : if day . weekday ( ) == weekday : break day = day - timedelta ( days = 1 ) return day", "docstring_tokens": "Get the last weekday in a given month . e . g :", "label": 1, "retrieval_idx": 5667 }, { "idx": "cosqa-train-19483", "doc": "how to get the maximum cell in one row in python", "code": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n \"\"\"\n Takes a list of rows and a column name and returns a list containing a single row (dict from\n columns to cells) that has the maximum numerical value in the given column. We return a list\n instead of a single dict to be consistent with the return type of ``select`` and\n ``all_rows``.\n \"\"\"\n if not rows:\n return []\n value_row_pairs = [(row.values[column.name], row) for row in rows]\n if not value_row_pairs:\n return []\n # Returns a list containing the row with the max cell value.\n return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "code_tokens": "def argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]", "docstring_tokens": "Takes a list of rows and a column name and returns a list containing a single row ( dict from columns to cells ) that has the maximum numerical value in the given column . We return a list instead of a single dict to be consistent with the return type of select and all_rows .", "label": 1, "retrieval_idx": 5799 }, { "idx": "cosqa-train-12296", "doc": "redefine the range in python", "code": "def negate(self):\n \"\"\"Reverse the range\"\"\"\n self.from_value, self.to_value = self.to_value, self.from_value\n self.include_lower, self.include_upper = self.include_upper, self.include_lower", "code_tokens": "def negate ( self ) : self . from_value , self . to_value = self . to_value , self . from_value self . include_lower , self . include_upper = self . include_upper , self . include_lower", "docstring_tokens": "Reverse the range", "label": 1, "retrieval_idx": 1685 }, { "idx": "cosqa-train-11045", "doc": "escape percent sign in python", "code": "def quote(s, unsafe='/'):\n \"\"\"Pass in a dictionary that has unsafe characters as the keys, and the percent\n encoded value as the value.\"\"\"\n res = s.replace('%', '%25')\n for c in unsafe:\n res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])\n return res", "code_tokens": "def quote ( s , unsafe = '/' ) : res = s . replace ( '%' , '%25' ) for c in unsafe : res = res . replace ( c , '%' + ( hex ( ord ( c ) ) . upper ( ) ) [ 2 : ] ) return res", "docstring_tokens": "Pass in a dictionary that has unsafe characters as the keys and the percent encoded value as the value .", "label": 1, "retrieval_idx": 905 }, { "idx": "cosqa-train-12263", "doc": "plot kde over histogram python", "code": "def plot_kde(data, ax, title=None, color='r', fill_bt=True):\n \"\"\"\n Plot a smoothed (by kernel density estimate) histogram.\n :type data: numpy array\n :param data: An array containing the data to be plotted\n\n :type ax: matplotlib.Axes\n :param ax: The Axes object to draw to\n\n :type title: str\n :param title: The plot title\n\n :type color: str\n :param color: The color of the histogram line and fill. Note that the fill\n will be plotted with an alpha of 0.35.\n\n :type fill_bt: bool\n :param fill_bt: Specify whether to fill the area beneath the histogram line\n \"\"\"\n if isinstance(data, list):\n data = np.asarray(data)\n e = kde.KDEUnivariate(data.astype(np.float))\n e.fit()\n ax.plot(e.support, e.density, color=color, alpha=0.9, linewidth=2.25)\n if fill_bt:\n ax.fill_between(e.support, e.density, alpha=.35, zorder=1,\n antialiased=True, color=color)\n if title is not None:\n t = ax.set_title(title)\n t.set_y(1.05)", "code_tokens": "def plot_kde ( data , ax , title = None , color = 'r' , fill_bt = True ) : if isinstance ( data , list ) : data = np . asarray ( data ) e = kde . KDEUnivariate ( data . astype ( np . float ) ) e . fit ( ) ax . plot ( e . support , e . density , color = color , alpha = 0.9 , linewidth = 2.25 ) if fill_bt : ax . fill_between ( e . support , e . density , alpha = .35 , zorder = 1 , antialiased = True , color = color ) if title is not None : t = ax . set_title ( title ) t . set_y ( 1.05 )", "docstring_tokens": "Plot a smoothed ( by kernel density estimate ) histogram . : type data : numpy array : param data : An array containing the data to be plotted", "label": 1, "retrieval_idx": 4630 }, { "idx": "cosqa-train-17585", "doc": "normalize to 1 in python", "code": "def normalize(numbers):\n \"\"\"Multiply each number by a constant such that the sum is 1.0\n >>> normalize([1,2,1])\n [0.25, 0.5, 0.25]\n \"\"\"\n total = float(sum(numbers))\n return [n / total for n in numbers]", "code_tokens": "def normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]", "docstring_tokens": "Multiply each number by a constant such that the sum is 1 . 0 >>> normalize ( [ 1 2 1 ] ) [ 0 . 25 0 . 5 0 . 25 ]", "label": 1, "retrieval_idx": 5632 }, { "idx": "cosqa-train-11245", "doc": "python interpolate between different coordinate matrices", "code": "def _linearInterpolationTransformMatrix(matrix1, matrix2, value):\n \"\"\" Linear, 'oldstyle' interpolation of the transform matrix.\"\"\"\n return tuple(_interpolateValue(matrix1[i], matrix2[i], value) for i in range(len(matrix1)))", "code_tokens": "def _linearInterpolationTransformMatrix ( matrix1 , matrix2 , value ) : return tuple ( _interpolateValue ( matrix1 [ i ] , matrix2 [ i ] , value ) for i in range ( len ( matrix1 ) ) )", "docstring_tokens": "Linear oldstyle interpolation of the transform matrix .", "label": 1, "retrieval_idx": 1274 }, { "idx": "cosqa-train-14554", "doc": "see properties of an object python", "code": "def get_public_members(obj):\n \"\"\"\n Retrieves a list of member-like objects (members or properties) that are\n publically exposed.\n\n :param obj: The object to probe.\n :return: A list of strings.\n \"\"\"\n return {attr: getattr(obj, attr) for attr in dir(obj)\n if not attr.startswith(\"_\")\n and not hasattr(getattr(obj, attr), '__call__')}", "code_tokens": "def get_public_members ( obj ) : return { attr : getattr ( obj , attr ) for attr in dir ( obj ) if not attr . startswith ( \"_\" ) and not hasattr ( getattr ( obj , attr ) , '__call__' ) }", "docstring_tokens": "Retrieves a list of member - like objects ( members or properties ) that are publically exposed .", "label": 1, "retrieval_idx": 433 }, { "idx": "cosqa-train-11387", "doc": "how to check if sprites collide in python", "code": "def check_player_collision(self):\n \"\"\"Check to see if we are colliding with the player.\"\"\"\n player_tiles = r.TileMapManager.active_map.grab_collisions(self.char.coords)\n enemy_tiles = r.TileMapManager.active_map.grab_collisions(self.coords)\n\n #Check to see if any of the tiles are the same. If so, there is a collision.\n for ptile in player_tiles:\n for etile in enemy_tiles:\n if r.TileMapManager.active_map.pixels_to_tiles(ptile.coords) == r.TileMapManager.active_map.pixels_to_tiles(etile.coords):\n return True\n\n return False", "code_tokens": "def check_player_collision ( self ) : player_tiles = r . TileMapManager . active_map . grab_collisions ( self . char . coords ) enemy_tiles = r . TileMapManager . active_map . grab_collisions ( self . coords ) #Check to see if any of the tiles are the same. If so, there is a collision. for ptile in player_tiles : for etile in enemy_tiles : if r . TileMapManager . active_map . pixels_to_tiles ( ptile . coords ) == r . TileMapManager . active_map . pixels_to_tiles ( etile . coords ) : return True return False", "docstring_tokens": "Check to see if we are colliding with the player .", "label": 1, "retrieval_idx": 4646 }, { "idx": "cosqa-train-15249", "doc": "python function get all objects of certain type", "code": "def get_object_or_child_by_type(self, *types):\n \"\"\" Get object if child already been read or get child.\n\n Use this method for fast access to objects in case of static configurations.\n\n :param types: requested object types.\n :return: all children of the specified types.\n \"\"\"\n\n objects = self.get_objects_or_children_by_type(*types)\n return objects[0] if any(objects) else None", "code_tokens": "def get_object_or_child_by_type ( self , * types ) : objects = self . get_objects_or_children_by_type ( * types ) return objects [ 0 ] if any ( objects ) else None", "docstring_tokens": "Get object if child already been read or get child .", "label": 1, "retrieval_idx": 4577 }, { "idx": "cosqa-train-7142", "doc": "how to cast an object as a float python", "code": "def _tofloat(obj):\n \"\"\"Convert to float if object is a float string.\"\"\"\n if \"inf\" in obj.lower().strip():\n return obj\n try:\n return int(obj)\n except ValueError:\n try:\n return float(obj)\n except ValueError:\n return obj", "code_tokens": "def _tofloat ( obj ) : if \"inf\" in obj . lower ( ) . strip ( ) : return obj try : return int ( obj ) except ValueError : try : return float ( obj ) except ValueError : return obj", "docstring_tokens": "Convert to float if object is a float string .", "label": 1, "retrieval_idx": 2120 }, { "idx": "cosqa-train-1141", "doc": "python redis close conn", "code": "def exit(self):\n \"\"\"\n Closes the connection\n \"\"\"\n self.pubsub.unsubscribe()\n self.client.connection_pool.disconnect()\n\n logger.info(\"Connection to Redis closed\")", "code_tokens": "def exit ( self ) : self . pubsub . unsubscribe ( ) self . client . connection_pool . disconnect ( ) logger . info ( \"Connection to Redis closed\" )", "docstring_tokens": "Closes the connection", "label": 1, "retrieval_idx": 985 }, { "idx": "cosqa-train-6492", "doc": "python dialog box to specify folder", "code": "def ask_folder(message='Select folder.', default='', title=''):\n \"\"\"\n A dialog to get a directory name.\n Returns the name of a directory, or None if user chose to cancel.\n If the \"default\" argument specifies a directory name, and that\n directory exists, then the dialog box will start with that directory.\n\n :param message: message to be displayed.\n :param title: window title\n :param default: default folder path\n :rtype: None or string\n \"\"\"\n return backend_api.opendialog(\"ask_folder\", dict(message=message, default=default, title=title))", "code_tokens": "def ask_folder ( message = 'Select folder.' , default = '' , title = '' ) : return backend_api . opendialog ( \"ask_folder\" , dict ( message = message , default = default , title = title ) )", "docstring_tokens": "A dialog to get a directory name . Returns the name of a directory or None if user chose to cancel . If the default argument specifies a directory name and that directory exists then the dialog box will start with that directory .", "label": 1, "retrieval_idx": 3504 }, { "idx": "cosqa-train-11163", "doc": "python how to remove docstrings from compiled code", "code": "def debug_src(src, pm=False, globs=None):\n \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n testsrc = script_from_examples(src)\n debug_script(testsrc, pm, globs)", "code_tokens": "def debug_src ( src , pm = False , globs = None ) : testsrc = script_from_examples ( src ) debug_script ( testsrc , pm , globs )", "docstring_tokens": "Debug a single doctest docstring in argument src", "label": 1, "retrieval_idx": 586 }, { "idx": "cosqa-train-12144", "doc": "math normalize a matrix python", "code": "def v_normalize(v):\n \"\"\"\n Normalizes the given vector.\n \n The vector given may have any number of dimensions.\n \"\"\"\n vmag = v_magnitude(v)\n return [ v[i]/vmag for i in range(len(v)) ]", "code_tokens": "def v_normalize ( v ) : vmag = v_magnitude ( v ) return [ v [ i ] / vmag for i in range ( len ( v ) ) ]", "docstring_tokens": "Normalizes the given vector . The vector given may have any number of dimensions .", "label": 1, "retrieval_idx": 2497 }, { "idx": "cosqa-train-5909", "doc": "passing functions as argumetns python", "code": "def def_linear(fun):\n \"\"\"Flags that a function is linear wrt all args\"\"\"\n defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:\n fun(*subval(args, argnum, g), **kwargs))", "code_tokens": "def def_linear ( fun ) : defjvp_argnum ( fun , lambda argnum , g , ans , args , kwargs : fun ( * subval ( args , argnum , g ) , * * kwargs ) )", "docstring_tokens": "Flags that a function is linear wrt all args", "label": 1, "retrieval_idx": 1433 }, { "idx": "cosqa-train-1982", "doc": "to get the next line in python", "code": "def __next__(self):\n \"\"\"\n\n :return: a pair (1-based line number in the input, row)\n \"\"\"\n # Retrieve the row, thereby incrementing the line number:\n row = super(UnicodeReaderWithLineNumber, self).__next__()\n return self.lineno + 1, row", "code_tokens": "def __next__ ( self ) : # Retrieve the row, thereby incrementing the line number: row = super ( UnicodeReaderWithLineNumber , self ) . __next__ ( ) return self . lineno + 1 , row", "docstring_tokens": "", "label": 1, "retrieval_idx": 1590 }, { "idx": "cosqa-train-17749", "doc": "get table column names from database python", "code": "def get_column_names(engine: Engine, tablename: str) -> List[str]:\n \"\"\"\n Get all the database column names for the specified table.\n \"\"\"\n return [info.name for info in gen_columns_info(engine, tablename)]", "code_tokens": "def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]", "docstring_tokens": "Get all the database column names for the specified table .", "label": 1, "retrieval_idx": 5550 }, { "idx": "cosqa-train-14056", "doc": "python sparse matrix features name", "code": "def build_columns(self, X, verbose=False):\n \"\"\"construct the model matrix columns for the term\n\n Parameters\n ----------\n X : array-like\n Input dataset with n rows\n\n verbose : bool\n whether to show warnings\n\n Returns\n -------\n scipy sparse array with n rows\n \"\"\"\n return sp.sparse.csc_matrix(X[:, self.feature][:, np.newaxis])", "code_tokens": "def build_columns ( self , X , verbose = False ) : return sp . sparse . csc_matrix ( X [ : , self . feature ] [ : , np . newaxis ] )", "docstring_tokens": "construct the model matrix columns for the term", "label": 1, "retrieval_idx": 5103 }, { "idx": "cosqa-train-2483", "doc": "python get objectthat called a function", "code": "def __get__(self, obj, objtype):\n \"\"\" Support instance methods \"\"\"\n import functools\n return functools.partial(self.__call__, obj)", "code_tokens": "def __get__ ( self , obj , objtype ) : import functools return functools . partial ( self . __call__ , obj )", "docstring_tokens": "Support instance methods", "label": 1, "retrieval_idx": 1889 }, { "idx": "cosqa-train-12420", "doc": "python async function update state", "code": "def async_update(self, event):\n \"\"\"New event for light.\n\n Check that state is part of event.\n Signal that light has updated state.\n \"\"\"\n self.update_attr(event.get('state', {}))\n super().async_update(event)", "code_tokens": "def async_update ( self , event ) : self . update_attr ( event . get ( 'state' , { } ) ) super ( ) . async_update ( event )", "docstring_tokens": "New event for light .", "label": 1, "retrieval_idx": 4822 }, { "idx": "cosqa-train-14688", "doc": "python check if variable is float, int, boolean", "code": "def is_float(value):\n \"\"\"must be a float\"\"\"\n return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)", "code_tokens": "def is_float ( value ) : return isinstance ( value , float ) or isinstance ( value , int ) or isinstance ( value , np . float64 ) , float ( value )", "docstring_tokens": "must be a float", "label": 1, "retrieval_idx": 772 }, { "idx": "cosqa-train-10097", "doc": "maximum list depth python", "code": "def maxlevel(lst):\n \"\"\"Return maximum nesting depth\"\"\"\n maxlev = 0\n def f(lst, level):\n nonlocal maxlev\n if isinstance(lst, list):\n level += 1\n maxlev = max(level, maxlev)\n for item in lst:\n f(item, level)\n f(lst, 0)\n return maxlev", "code_tokens": "def maxlevel ( lst ) : maxlev = 0 def f ( lst , level ) : nonlocal maxlev if isinstance ( lst , list ) : level += 1 maxlev = max ( level , maxlev ) for item in lst : f ( item , level ) f ( lst , 0 ) return maxlev", "docstring_tokens": "Return maximum nesting depth", "label": 1, "retrieval_idx": 3040 }, { "idx": "cosqa-train-12491", "doc": "ssis check if python is still running in vackground", "code": "def inside_softimage():\n \"\"\"Returns a boolean indicating if the code is executed inside softimage.\"\"\"\n try:\n import maya\n return False\n except ImportError:\n pass\n try:\n from win32com.client import Dispatch as disp\n disp('XSI.Application')\n return True\n except:\n return False", "code_tokens": "def inside_softimage ( ) : try : import maya return False except ImportError : pass try : from win32com . client import Dispatch as disp disp ( 'XSI.Application' ) return True except : return False", "docstring_tokens": "Returns a boolean indicating if the code is executed inside softimage .", "label": 1, "retrieval_idx": 1617 }, { "idx": "cosqa-train-894", "doc": "python max length of one line", "code": "def _multiline_width(multiline_s, line_width_fn=len):\n \"\"\"Visible width of a potentially multiline content.\"\"\"\n return max(map(line_width_fn, re.split(\"[\\r\\n]\", multiline_s)))", "code_tokens": "def _multiline_width ( multiline_s , line_width_fn = len ) : return max ( map ( line_width_fn , re . split ( \"[\\r\\n]\" , multiline_s ) ) )", "docstring_tokens": "Visible width of a potentially multiline content .", "label": 1, "retrieval_idx": 733 }, { "idx": "cosqa-train-13783", "doc": "how to get thousands of http requests asynchronously python", "code": "def _async_requests(urls):\n \"\"\"\n Sends multiple non-blocking requests. Returns\n a list of responses.\n\n :param urls:\n List of urls\n \"\"\"\n session = FuturesSession(max_workers=30)\n futures = [\n session.get(url)\n for url in urls\n ]\n return [ future.result() for future in futures ]", "code_tokens": "def _async_requests ( urls ) : session = FuturesSession ( max_workers = 30 ) futures = [ session . get ( url ) for url in urls ] return [ future . result ( ) for future in futures ]", "docstring_tokens": "Sends multiple non - blocking requests . Returns a list of responses .", "label": 1, "retrieval_idx": 5055 }, { "idx": "cosqa-train-9543", "doc": "python range function stack overflow", "code": "def LinSpace(start, stop, num):\n \"\"\"\n Linspace op.\n \"\"\"\n return np.linspace(start, stop, num=num, dtype=np.float32),", "code_tokens": "def LinSpace ( start , stop , num ) : return np . linspace ( start , stop , num = num , dtype = np . float32 ) ,", "docstring_tokens": "Linspace op .", "label": 1, "retrieval_idx": 3124 }, { "idx": "cosqa-train-4634", "doc": "python get last record in file", "code": "def last(self):\n \"\"\"Get the last object in file.\"\"\"\n # End of file\n self.__file.seek(0, 2)\n\n # Get the last struct\n data = self.get(self.length - 1)\n\n return data", "code_tokens": "def last ( self ) : # End of file self . __file . seek ( 0 , 2 ) # Get the last struct data = self . get ( self . length - 1 ) return data", "docstring_tokens": "Get the last object in file .", "label": 1, "retrieval_idx": 585 }, { "idx": "cosqa-train-2994", "doc": "python network activity log on and log off", "code": "def logout(self):\n \"\"\"\n Logout from the remote server.\n \"\"\"\n self.client.write('exit\\r\\n')\n self.client.read_all()\n self.client.close()", "code_tokens": "def logout ( self ) : self . client . write ( 'exit\\r\\n' ) self . client . read_all ( ) self . client . close ( )", "docstring_tokens": "Logout from the remote server .", "label": 1, "retrieval_idx": 2148 }, { "idx": "cosqa-train-806", "doc": "python list get index with default", "code": "def list_get(l, idx, default=None):\n \"\"\"\n Get from a list with an optional default value.\n \"\"\"\n try:\n if l[idx]:\n return l[idx]\n else:\n return default\n except IndexError:\n return default", "code_tokens": "def list_get ( l , idx , default = None ) : try : if l [ idx ] : return l [ idx ] else : return default except IndexError : return default", "docstring_tokens": "Get from a list with an optional default value .", "label": 1, "retrieval_idx": 719 }, { "idx": "cosqa-train-12002", "doc": "in a random generate sequence in python how do you retain a function", "code": "def sometimesish(fn):\n \"\"\"\n Has a 50/50 chance of calling a function\n \"\"\"\n def wrapped(*args, **kwargs):\n if random.randint(1, 2) == 1:\n return fn(*args, **kwargs)\n\n return wrapped", "code_tokens": "def sometimesish ( fn ) : def wrapped ( * args , * * kwargs ) : if random . randint ( 1 , 2 ) == 1 : return fn ( * args , * * kwargs ) return wrapped", "docstring_tokens": "Has a 50 / 50 chance of calling a function", "label": 1, "retrieval_idx": 1398 }, { "idx": "cosqa-train-16219", "doc": "python strictredis redis password", "code": "def get_connection(self, host, port, db):\n \"\"\"\n Returns a ``StrictRedis`` connection instance.\n \"\"\"\n return redis.StrictRedis(\n host=host,\n port=port,\n db=db,\n decode_responses=True\n )", "code_tokens": "def get_connection ( self , host , port , db ) : return redis . StrictRedis ( host = host , port = port , db = db , decode_responses = True )", "docstring_tokens": "Returns a StrictRedis connection instance .", "label": 1, "retrieval_idx": 5420 }, { "idx": "cosqa-train-8635", "doc": "python dict to key string and value stirng", "code": "def stringify_dict_contents(dct):\n \"\"\"Turn dict keys and values into native strings.\"\"\"\n return {\n str_if_nested_or_str(k): str_if_nested_or_str(v)\n for k, v in dct.items()\n }", "code_tokens": "def stringify_dict_contents ( dct ) : return { str_if_nested_or_str ( k ) : str_if_nested_or_str ( v ) for k , v in dct . items ( ) }", "docstring_tokens": "Turn dict keys and values into native strings .", "label": 1, "retrieval_idx": 1389 }, { "idx": "cosqa-dev-474", "doc": "python update minify js file", "code": "def minify(path):\n \"\"\"\n Load a javascript file and minify.\n\n Parameters\n ------------\n path: str, path of resource\n \"\"\"\n\n if 'http' in path:\n data = requests.get(path).content.decode(\n 'ascii', errors='ignore')\n else:\n with open(path, 'rb') as f:\n # some of these assholes use unicode spaces -_-\n data = f.read().decode('ascii',\n errors='ignore')\n # don't re- minify\n if '.min.' in path:\n return data\n\n try:\n return jsmin.jsmin(data)\n except BaseException:\n return data", "code_tokens": "def minify ( path ) : if 'http' in path : data = requests . get ( path ) . content . decode ( 'ascii' , errors = 'ignore' ) else : with open ( path , 'rb' ) as f : # some of these assholes use unicode spaces -_- data = f . read ( ) . decode ( 'ascii' , errors = 'ignore' ) # don't re- minify if '.min.' in path : return data try : return jsmin . jsmin ( data ) except BaseException : return data", "docstring_tokens": "Load a javascript file and minify .", "label": 1, "retrieval_idx": 4779 }, { "idx": "cosqa-train-13641", "doc": "how to deifne a rotation in python", "code": "def earth_orientation(date):\n \"\"\"Earth orientation as a rotating matrix\n \"\"\"\n\n x_p, y_p, s_prime = np.deg2rad(_earth_orientation(date))\n return rot3(-s_prime) @ rot2(x_p) @ rot1(y_p)", "code_tokens": "def earth_orientation ( date ) : x_p , y_p , s_prime = np . deg2rad ( _earth_orientation ( date ) ) return rot3 ( - s_prime ) @ rot2 ( x_p ) @ rot1 ( y_p )", "docstring_tokens": "Earth orientation as a rotating matrix", "label": 1, "retrieval_idx": 5040 }, { "idx": "cosqa-train-6704", "doc": "python get average volume of audio", "code": "def calc_volume(self, sample: np.ndarray):\n \"\"\"Find the RMS of the audio\"\"\"\n return sqrt(np.mean(np.square(sample)))", "code_tokens": "def calc_volume ( self , sample : np . ndarray ) : return sqrt ( np . mean ( np . square ( sample ) ) )", "docstring_tokens": "Find the RMS of the audio", "label": 1, "retrieval_idx": 1914 }, { "idx": "cosqa-train-9805", "doc": "python split words in to list", "code": "def tokenize_list(self, text):\n \"\"\"\n Split a text into separate words.\n \"\"\"\n return [self.get_record_token(record) for record in self.analyze(text)]", "code_tokens": "def tokenize_list ( self , text ) : return [ self . get_record_token ( record ) for record in self . analyze ( text ) ]", "docstring_tokens": "Split a text into separate words .", "label": 1, "retrieval_idx": 1576 }, { "idx": "cosqa-train-8973", "doc": "python how check int or float", "code": "def is_float(value):\n \"\"\"must be a float\"\"\"\n return isinstance(value, float) or isinstance(value, int) or isinstance(value, np.float64), float(value)", "code_tokens": "def is_float ( value ) : return isinstance ( value , float ) or isinstance ( value , int ) or isinstance ( value , np . float64 ) , float ( value )", "docstring_tokens": "must be a float", "label": 1, "retrieval_idx": 772 }, { "idx": "cosqa-train-14810", "doc": "write file python change text color", "code": "def _write_color_colorama (fp, text, color):\n \"\"\"Colorize text with given color.\"\"\"\n foreground, background, style = get_win_color(color)\n colorama.set_console(foreground=foreground, background=background,\n style=style)\n fp.write(text)\n colorama.reset_console()", "code_tokens": "def _write_color_colorama ( fp , text , color ) : foreground , background , style = get_win_color ( color ) colorama . set_console ( foreground = foreground , background = background , style = style ) fp . write ( text ) colorama . reset_console ( )", "docstring_tokens": "Colorize text with given color .", "label": 1, "retrieval_idx": 1347 }, { "idx": "cosqa-train-15315", "doc": "python get location of min/max", "code": "def values(self):\n \"\"\"Gets the user enter max and min values of where the \n raster points should appear on the y-axis\n\n :returns: (float, float) -- (min, max) y-values to bound the raster plot by\n \"\"\"\n lower = float(self.lowerSpnbx.value())\n upper = float(self.upperSpnbx.value())\n return (lower, upper)", "code_tokens": "def values ( self ) : lower = float ( self . lowerSpnbx . value ( ) ) upper = float ( self . upperSpnbx . value ( ) ) return ( lower , upper )", "docstring_tokens": "Gets the user enter max and min values of where the raster points should appear on the y - axis", "label": 1, "retrieval_idx": 314 }, { "idx": "cosqa-train-8953", "doc": "extract words from documents python", "code": "def contains_extractor(document):\n \"\"\"A basic document feature extractor that returns a dict of words that the\n document contains.\"\"\"\n tokens = _get_document_tokens(document)\n features = dict((u'contains({0})'.format(w), True) for w in tokens)\n return features", "code_tokens": "def contains_extractor ( document ) : tokens = _get_document_tokens ( document ) features = dict ( ( u'contains({0})' . format ( w ) , True ) for w in tokens ) return features", "docstring_tokens": "A basic document feature extractor that returns a dict of words that the document contains .", "label": 1, "retrieval_idx": 1969 }, { "idx": "cosqa-train-10594", "doc": "python \"binary string\" to int", "code": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "code_tokens": "def _from_bytes ( bytes , byteorder = \"big\" , signed = False ) : return int . from_bytes ( bytes , byteorder = byteorder , signed = signed )", "docstring_tokens": "This is the same functionality as int . from_bytes in python 3", "label": 1, "retrieval_idx": 1205 }, { "idx": "cosqa-dev-311", "doc": "python return index of object in a list", "code": "def get_list_index(lst, index_or_name):\n \"\"\"\n Return the index of an element in the list.\n\n Args:\n lst (list): The list.\n index_or_name (int or str): The value of the reference element, or directly its numeric index.\n\n Returns:\n (int) The index of the element in the list.\n \"\"\"\n if isinstance(index_or_name, six.integer_types):\n return index_or_name\n\n return lst.index(index_or_name)", "code_tokens": "def get_list_index ( lst , index_or_name ) : if isinstance ( index_or_name , six . integer_types ) : return index_or_name return lst . index ( index_or_name )", "docstring_tokens": "Return the index of an element in the list .", "label": 1, "retrieval_idx": 456 }, { "idx": "cosqa-train-10017", "doc": "l2 norm for array python", "code": "def l2_norm(arr):\n \"\"\"\n The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n dot product of the vector.\n \"\"\"\n arr = np.asarray(arr)\n return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))", "code_tokens": "def l2_norm ( arr ) : arr = np . asarray ( arr ) return np . sqrt ( np . dot ( arr . ravel ( ) . squeeze ( ) , arr . ravel ( ) . squeeze ( ) ) )", "docstring_tokens": "The l2 norm of an array is is defined as : sqrt ( ||x|| ) where ||x|| is the dot product of the vector .", "label": 1, "retrieval_idx": 2471 }, { "idx": "cosqa-train-7309", "doc": "how to fill linterrepter python", "code": "def register(linter):\n \"\"\"Register the reporter classes with the linter.\"\"\"\n linter.register_reporter(TextReporter)\n linter.register_reporter(ParseableTextReporter)\n linter.register_reporter(VSTextReporter)\n linter.register_reporter(ColorizedTextReporter)", "code_tokens": "def register ( linter ) : linter . register_reporter ( TextReporter ) linter . register_reporter ( ParseableTextReporter ) linter . register_reporter ( VSTextReporter ) linter . register_reporter ( ColorizedTextReporter )", "docstring_tokens": "Register the reporter classes with the linter .", "label": 1, "retrieval_idx": 3726 }, { "idx": "cosqa-train-18031", "doc": "how to check datatype of column in python", "code": "def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool:\n \"\"\"\n Is the SQLAlchemy column type one that inherits from :class:`Numeric`,\n such as :class:`Float`, :class:`Decimal`?\n \"\"\"\n coltype = _coltype_to_typeengine(coltype)\n return isinstance(coltype, sqltypes.Numeric)", "code_tokens": "def is_sqlatype_numeric ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . Numeric )", "docstring_tokens": "Is the SQLAlchemy column type one that inherits from : class : Numeric such as : class : Float : class : Decimal ?", "label": 1, "retrieval_idx": 5933 }, { "idx": "cosqa-train-11241", "doc": "python interactive window python is not defined", "code": "def isInteractive():\n \"\"\"\n A basic check of if the program is running in interactive mode\n \"\"\"\n if sys.stdout.isatty() and os.name != 'nt':\n #Hopefully everything but ms supports '\\r'\n try:\n import threading\n except ImportError:\n return False\n else:\n return True\n else:\n return False", "code_tokens": "def isInteractive ( ) : if sys . stdout . isatty ( ) and os . name != 'nt' : #Hopefully everything but ms supports '\\r' try : import threading except ImportError : return False else : return True else : return False", "docstring_tokens": "A basic check of if the program is running in interactive mode", "label": 1, "retrieval_idx": 133 }, { "idx": "cosqa-train-13064", "doc": "datetime add a month to a date python", "code": "def start_of_month(val):\n \"\"\"\n Return a new datetime.datetime object with values that represent\n a start of a month.\n :param val: Date to ...\n :type val: datetime.datetime | datetime.date\n :rtype: datetime.datetime\n \"\"\"\n if type(val) == date:\n val = datetime.fromordinal(val.toordinal())\n return start_of_day(val).replace(day=1)", "code_tokens": "def start_of_month ( val ) : if type ( val ) == date : val = datetime . fromordinal ( val . toordinal ( ) ) return start_of_day ( val ) . replace ( day = 1 )", "docstring_tokens": "Return a new datetime . datetime object with values that represent a start of a month . : param val : Date to ... : type val : datetime . datetime | datetime . date : rtype : datetime . datetime", "label": 1, "retrieval_idx": 113 }, { "idx": "cosqa-dev-487", "doc": "python correlation pearson coefficient", "code": "def cor(y_true, y_pred):\n \"\"\"Compute Pearson correlation coefficient.\n \"\"\"\n y_true, y_pred = _mask_nan(y_true, y_pred)\n return np.corrcoef(y_true, y_pred)[0, 1]", "code_tokens": "def cor ( y_true , y_pred ) : y_true , y_pred = _mask_nan ( y_true , y_pred ) return np . corrcoef ( y_true , y_pred ) [ 0 , 1 ]", "docstring_tokens": "Compute Pearson correlation coefficient .", "label": 1, "retrieval_idx": 2560 }, { "idx": "cosqa-train-11248", "doc": "how do i mae the cursor on python skinny again", "code": "def hidden_cursor(self):\n \"\"\"Return a context manager that hides the cursor while inside it and\n makes it visible on leaving.\"\"\"\n self.stream.write(self.hide_cursor)\n try:\n yield\n finally:\n self.stream.write(self.normal_cursor)", "code_tokens": "def hidden_cursor ( self ) : self . stream . write ( self . hide_cursor ) try : yield finally : self . stream . write ( self . normal_cursor )", "docstring_tokens": "Return a context manager that hides the cursor while inside it and makes it visible on leaving .", "label": 1, "retrieval_idx": 241 }, { "idx": "cosqa-train-10454", "doc": "test the number of characters in python list", "code": "def token_list_len(tokenlist):\n \"\"\"\n Return the amount of characters in this token list.\n\n :param tokenlist: List of (token, text) or (token, text, mouse_handler)\n tuples.\n \"\"\"\n ZeroWidthEscape = Token.ZeroWidthEscape\n return sum(len(item[1]) for item in tokenlist if item[0] != ZeroWidthEscape)", "code_tokens": "def token_list_len ( tokenlist ) : ZeroWidthEscape = Token . ZeroWidthEscape return sum ( len ( item [ 1 ] ) for item in tokenlist if item [ 0 ] != ZeroWidthEscape )", "docstring_tokens": "Return the amount of characters in this token list .", "label": 1, "retrieval_idx": 4479 }, { "idx": "cosqa-train-6061", "doc": "sent urlencoded payload in python", "code": "def urlencoded(body, charset='ascii', **kwargs):\n \"\"\"Converts query strings into native Python objects\"\"\"\n return parse_query_string(text(body, charset=charset), False)", "code_tokens": "def urlencoded ( body , charset = 'ascii' , * * kwargs ) : return parse_query_string ( text ( body , charset = charset ) , False )", "docstring_tokens": "Converts query strings into native Python objects", "label": 1, "retrieval_idx": 2540 }, { "idx": "cosqa-train-16146", "doc": "python setuptools command not found", "code": "def main(argv, version=DEFAULT_VERSION):\n \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n tarball = download_setuptools()\n _install(tarball, _build_install_args(argv))", "code_tokens": "def main ( argv , version = DEFAULT_VERSION ) : tarball = download_setuptools ( ) _install ( tarball , _build_install_args ( argv ) )", "docstring_tokens": "Install or upgrade setuptools and EasyInstall", "label": 1, "retrieval_idx": 3203 }, { "idx": "cosqa-train-8518", "doc": "python ctypes load dll dependancies", "code": "def _windowsLdmodTargets(target, source, env, for_signature):\n \"\"\"Get targets for loadable modules.\"\"\"\n return _dllTargets(target, source, env, for_signature, 'LDMODULE')", "code_tokens": "def _windowsLdmodTargets ( target , source , env , for_signature ) : return _dllTargets ( target , source , env , for_signature , 'LDMODULE' )", "docstring_tokens": "Get targets for loadable modules .", "label": 1, "retrieval_idx": 4052 }, { "idx": "cosqa-train-18790", "doc": "python create dictionray from a list of keys", "code": "def encode_list(key, list_):\n # type: (str, Iterable) -> Dict[str, str]\n \"\"\"\n Converts a list into a space-separated string and puts it in a dictionary\n\n :param key: Dictionary key to store the list\n :param list_: A list of objects\n :return: A dictionary key->string or an empty dictionary\n \"\"\"\n if not list_:\n return {}\n return {key: \" \".join(str(i) for i in list_)}", "code_tokens": "def encode_list ( key , list_ ) : # type: (str, Iterable) -> Dict[str, str] if not list_ : return { } return { key : \" \" . join ( str ( i ) for i in list_ ) }", "docstring_tokens": "Converts a list into a space - separated string and puts it in a dictionary", "label": 1, "retrieval_idx": 5769 }, { "idx": "cosqa-train-6682", "doc": "python function to reduce image size", "code": "def resize_by_area(img, size):\n \"\"\"image resize function used by quite a few image problems.\"\"\"\n return tf.to_int64(\n tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA))", "code_tokens": "def resize_by_area ( img , size ) : return tf . to_int64 ( tf . image . resize_images ( img , [ size , size ] , tf . image . ResizeMethod . AREA ) )", "docstring_tokens": "image resize function used by quite a few image problems .", "label": 1, "retrieval_idx": 1466 }, { "idx": "cosqa-train-15174", "doc": "python filling missing values with fillna", "code": "def fillna(series_or_arr, missing_value=0.0):\n \"\"\"Fill missing values in pandas objects and numpy arrays.\n\n Arguments\n ---------\n series_or_arr : pandas.Series, numpy.ndarray\n The numpy array or pandas series for which the missing values\n need to be replaced.\n missing_value : float, int, str\n The value to replace the missing value with. Default 0.0.\n\n Returns\n -------\n pandas.Series, numpy.ndarray\n The numpy array or pandas series with the missing values\n filled.\n \"\"\"\n\n if pandas.notnull(missing_value):\n if isinstance(series_or_arr, (numpy.ndarray)):\n series_or_arr[numpy.isnan(series_or_arr)] = missing_value\n else:\n series_or_arr.fillna(missing_value, inplace=True)\n\n return series_or_arr", "code_tokens": "def fillna ( series_or_arr , missing_value = 0.0 ) : if pandas . notnull ( missing_value ) : if isinstance ( series_or_arr , ( numpy . ndarray ) ) : series_or_arr [ numpy . isnan ( series_or_arr ) ] = missing_value else : series_or_arr . fillna ( missing_value , inplace = True ) return series_or_arr", "docstring_tokens": "Fill missing values in pandas objects and numpy arrays .", "label": 1, "retrieval_idx": 4722 }, { "idx": "cosqa-train-7243", "doc": "how to count the number of objects in python", "code": "def get_size(objects):\n \"\"\"Compute the total size of all elements in objects.\"\"\"\n res = 0\n for o in objects:\n try:\n res += _getsizeof(o)\n except AttributeError:\n print(\"IGNORING: type=%s; o=%s\" % (str(type(o)), str(o)))\n return res", "code_tokens": "def get_size ( objects ) : res = 0 for o in objects : try : res += _getsizeof ( o ) except AttributeError : print ( \"IGNORING: type=%s; o=%s\" % ( str ( type ( o ) ) , str ( o ) ) ) return res", "docstring_tokens": "Compute the total size of all elements in objects .", "label": 1, "retrieval_idx": 713 }, { "idx": "cosqa-train-10565", "doc": "python cmd get dynamically added do methods to show up in help", "code": "def do_help(self, arg):\n \"\"\"\n Show help on all commands.\n \"\"\"\n print(self.response_prompt, file=self.stdout)\n return cmd.Cmd.do_help(self, arg)", "code_tokens": "def do_help ( self , arg ) : print ( self . response_prompt , file = self . stdout ) return cmd . Cmd . do_help ( self , arg )", "docstring_tokens": "Show help on all commands .", "label": 1, "retrieval_idx": 4504 }, { "idx": "cosqa-train-2927", "doc": "how to change a dictionary to a numy array in python", "code": "def C_dict2array(C):\n \"\"\"Convert an OrderedDict containing C values to a 1D array.\"\"\"\n return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])", "code_tokens": "def C_dict2array ( C ) : return np . hstack ( [ np . asarray ( C [ k ] ) . ravel ( ) for k in C_keys ] )", "docstring_tokens": "Convert an OrderedDict containing C values to a 1D array .", "label": 1, "retrieval_idx": 879 } ]