Dataset Viewer
Auto-converted to Parquet Duplicate
anchor
stringlengths
16
95
positive
stringlengths
87
6.25k
negative
stringlengths
87
6.4k
1d array in char datatype in python
def _convert_to_array(array_like, dtype): """ Convert Matrix attributes which are array-like or buffer to array. """ if isinstance(array_like, bytes): return np.frombuffer(array_like, dtype=dtype) return np.asarray(array_like, dtype=dtype)
def c_array(ctype, values): """Convert a python string to c array.""" if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype): return (ctype * len(values)).from_buffer_copy(values) return (ctype * len(values))(*values)
1d array in char datatype in python
def _convert_to_array(array_like, dtype): """ Convert Matrix attributes which are array-like or buffer to array. """ if isinstance(array_like, bytes): return np.frombuffer(array_like, dtype=dtype) return np.asarray(array_like, dtype=dtype)
def _numpy_bytes_to_char(arr): """Like netCDF4.stringtochar, but faster and more flexible. """ # ensure the array is contiguous arr = np.array(arr, copy=False, order='C', dtype=np.string_) return arr.reshape(arr.shape + (1,)).view('S1')
1d array in char datatype in python
def _convert_to_array(array_like, dtype): """ Convert Matrix attributes which are array-like or buffer to array. """ if isinstance(array_like, bytes): return np.frombuffer(array_like, dtype=dtype) return np.asarray(array_like, dtype=dtype)
def convert_bytes_to_ints(in_bytes, num): """Convert a byte array into an integer array. The number of bytes forming an integer is defined by num :param in_bytes: the input bytes :param num: the number of bytes per int :return the integer array""" dt = numpy.dtype('>i' + str(num)) return nu...
1d array in char datatype in python
def _convert_to_array(array_like, dtype): """ Convert Matrix attributes which are array-like or buffer to array. """ if isinstance(array_like, bytes): return np.frombuffer(array_like, dtype=dtype) return np.asarray(array_like, dtype=dtype)
def _numpy_char_to_bytes(arr): """Like netCDF4.chartostring, but faster and more flexible. """ # based on: http://stackoverflow.com/a/10984878/809705 arr = np.array(arr, copy=False, order='C') dtype = 'S' + str(arr.shape[-1]) return arr.view(dtype).reshape(arr.shape[:-1])
1d array in char datatype in python
def _convert_to_array(array_like, dtype): """ Convert Matrix attributes which are array-like or buffer to array. """ if isinstance(array_like, bytes): return np.frombuffer(array_like, dtype=dtype) return np.asarray(array_like, dtype=dtype)
def cint8_array_to_numpy(cptr, length): """Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)): return np.fromiter(cptr, dtype=np.int8, count=length) else: raise RuntimeError('Expected int pointer')
python condition non none
def _not(condition=None, **kwargs): """ Return the opposite of input condition. :param condition: condition to process. :result: not condition. :rtype: bool """ result = True if condition is not None: result = not run(condition, **kwargs) return result
def p_if_statement_2(self, p): """if_statement : IF LPAREN expr RPAREN statement ELSE statement""" p[0] = ast.If(predicate=p[3], consequent=p[5], alternative=p[7])
python condition non none
def _not(condition=None, **kwargs): """ Return the opposite of input condition. :param condition: condition to process. :result: not condition. :rtype: bool """ result = True if condition is not None: result = not run(condition, **kwargs) return result
def notin(arg, values): """ Like isin, but checks whether this expression's value(s) are not contained in the passed values. See isin docs for full usage. """ op = ops.NotContains(arg, values) return op.to_expr()
python condition non none
def _not(condition=None, **kwargs): """ Return the opposite of input condition. :param condition: condition to process. :result: not condition. :rtype: bool """ result = True if condition is not None: result = not run(condition, **kwargs) return result
def contains(self, element): """ Ensures :attr:`subject` contains *other*. """ self._run(unittest_case.assertIn, (element, self._subject)) return ChainInspector(self._subject)
accessing a column from a matrix in python
def get_column(self, X, column): """Return a column of the given matrix. Args: X: `numpy.ndarray` or `pandas.DataFrame`. column: `int` or `str`. Returns: np.ndarray: Selected column. """ if isinstance(X, pd.DataFrame): return X[co...
def get_matrix(self): """ Use numpy to create a real matrix object from the data :return: the matrix representation of the fvm """ return np.array([ self.get_row_list(i) for i in range(self.row_count()) ])
accessing a column from a matrix in python
def get_column(self, X, column): """Return a column of the given matrix. Args: X: `numpy.ndarray` or `pandas.DataFrame`. column: `int` or `str`. Returns: np.ndarray: Selected column. """ if isinstance(X, pd.DataFrame): return X[co...
def load_data(filename): """ :rtype : numpy matrix """ data = pandas.read_csv(filename, header=None, delimiter='\t', skiprows=9) return data.as_matrix()
accessing a column from a matrix in python
def get_column(self, X, column): """Return a column of the given matrix. Args: X: `numpy.ndarray` or `pandas.DataFrame`. column: `int` or `str`. Returns: np.ndarray: Selected column. """ if isinstance(X, pd.DataFrame): return X[co...
def trans_from_matrix(matrix): """ Convert a vtk matrix to a numpy.ndarray """ t = np.zeros((4, 4)) for i in range(4): for j in range(4): t[i, j] = matrix.GetElement(i, j) return t
are python strings hashable
def _string_hash(s): """String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).""" h = 5381 for c in s: h = h * 33 + ord(c) return h
def dict_hash(dct): """Return a hash of the contents of a dictionary""" dct_s = json.dumps(dct, sort_keys=True) try: m = md5(dct_s) except TypeError: m = md5(dct_s.encode()) return m.hexdigest()
are python strings hashable
def _string_hash(s): """String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).""" h = 5381 for c in s: h = h * 33 + ord(c) return h
def _hash_the_file(hasher, filename): """Helper function for creating hash functions. See implementation of :func:`dtoolcore.filehasher.shasum` for more usage details. """ BUF_SIZE = 65536 with open(filename, 'rb') as f: buf = f.read(BUF_SIZE) while len(buf) > 0: has...
python create object without class
def create_object(cls, members): """Promise an object of class `cls` with content `members`.""" obj = cls.__new__(cls) obj.__dict__ = members return obj
def load(obj, cls, default_factory): """Create or load an object if necessary. Parameters ---------- obj : `object` or `dict` or `None` cls : `type` default_factory : `function` Returns ------- `object` """ if obj is None: return default_factory() if isinstance(...
python create object without class
def create_object(cls, members): """Promise an object of class `cls` with content `members`.""" obj = cls.__new__(cls) obj.__dict__ = members return obj
def simple_generate(cls, create, **kwargs): """Generate a new instance. The instance will be either 'built' or 'created'. Args: create (bool): whether to 'build' or 'create' the instance. Returns: object: the generated instance """ strategy = en...
python create object without class
def create_object(cls, members): """Promise an object of class `cls` with content `members`.""" obj = cls.__new__(cls) obj.__dict__ = members return obj
def add_object(self, obj): """Add object to local and app environment storage :param obj: Instance of a .NET object """ if obj.top_level_object: if isinstance(obj, DotNetNamespace): self.namespaces[obj.name] = obj self.objects[obj.id] = obj
python create range in steps
def _xxrange(self, start, end, step_count): """Generate n values between start and end.""" _step = (end - start) / float(step_count) return (start + (i * _step) for i in xrange(int(step_count)))
def add_range(self, sequence, begin, end): """Add a read_range primitive""" sequence.parser_tree = parsing.Range(self.value(begin).strip("'"), self.value(end).strip("'")) return True
python create range in steps
def _xxrange(self, start, end, step_count): """Generate n values between start and end.""" _step = (end - start) / float(step_count) return (start + (i * _step) for i in xrange(int(step_count)))
def merge(self, other): """ Merge this range object with another (ranges need not overlap or abut). :returns: a new Range object representing the interval containing both ranges. """ newstart = min(self._start, other.start) newend = max(self._end, other...
assure all true of a list of boolean python
def assert_exactly_one_true(bool_list): """This method asserts that only one value of the provided list is True. :param bool_list: List of booleans to check :return: True if only one value is True, False otherwise """ assert isinstance(bool_list, list) counter = 0 for item in bool_list: ...
def _if(ctx, logical_test, value_if_true=0, value_if_false=False): """ Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE """ return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false
assure all true of a list of boolean python
def assert_exactly_one_true(bool_list): """This method asserts that only one value of the provided list is True. :param bool_list: List of booleans to check :return: True if only one value is True, False otherwise """ assert isinstance(bool_list, list) counter = 0 for item in bool_list: ...
def visit_BoolOp(self, node): """ Return type may come from any boolop operand. """ return sum((self.visit(value) for value in node.values), [])
python creating a dictionary from reading a csv file with dictreader
def csv_to_dicts(file, header=None): """Reads a csv and returns a List of Dicts with keys given by header row.""" with open(file) as csvfile: return [row for row in csv.DictReader(csvfile, fieldnames=header)]
def save_dict_to_file(filename, dictionary): """Saves dictionary as CSV file.""" with open(filename, 'w') as f: writer = csv.writer(f) for k, v in iteritems(dictionary): writer.writerow([str(k), str(v)])
python creating a dictionary from reading a csv file with dictreader
def csv_to_dicts(file, header=None): """Reads a csv and returns a List of Dicts with keys given by header row.""" with open(file) as csvfile: return [row for row in csv.DictReader(csvfile, fieldnames=header)]
def read_dict_from_file(file_path): """ Read a dictionary of strings from a file """ with open(file_path) as file: lines = file.read().splitlines() obj = {} for line in lines: key, value = line.split(':', maxsplit=1) obj[key] = eval(value) return obj
python creating a dictionary from reading a csv file with dictreader
def csv_to_dicts(file, header=None): """Reads a csv and returns a List of Dicts with keys given by header row.""" with open(file) as csvfile: return [row for row in csv.DictReader(csvfile, fieldnames=header)]
def h5ToDict(h5, readH5pyDataset=True): """ Read a hdf5 file into a dictionary """ h = h5py.File(h5, "r") ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset) if readH5pyDataset: h.close() return ret
python creating a dictionary from reading a csv file with dictreader
def csv_to_dicts(file, header=None): """Reads a csv and returns a List of Dicts with keys given by header row.""" with open(file) as csvfile: return [row for row in csv.DictReader(csvfile, fieldnames=header)]
def load(cls, fname): """ Loads the dictionary from json file :param fname: file to load from :return: loaded dictionary """ with open(fname) as f: return Config(**json.load(f))
best way to give file path in python
def relative_path(path): """ Return the given path relative to this file. """ return os.path.join(os.path.dirname(__file__), path)
def get_file_name(url): """Returns file name of file at given url.""" return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name'
bottom 5 rows in python
def table_top_abs(self): """Returns the absolute position of table top""" table_height = np.array([0, 0, self.table_full_size[2]]) return string_to_array(self.floor.get("pos")) + table_height
def top(n, width=WIDTH, style=STYLE): """Prints the top row of a table""" return hrule(n, width, linestyle=STYLES[style].top)
bottom 5 rows in python
def table_top_abs(self): """Returns the absolute position of table top""" table_height = np.array([0, 0, self.table_full_size[2]]) return string_to_array(self.floor.get("pos")) + table_height
def head_and_tail_print(self, n=5): """Display the first and last n elements of a DataFrame.""" from IPython import display display.display(display.HTML(self._head_and_tail_table(n)))
bottom 5 rows in python
def table_top_abs(self): """Returns the absolute position of table top""" table_height = np.array([0, 0, self.table_full_size[2]]) return string_to_array(self.floor.get("pos")) + table_height
def series_table_row_offset(self, series): """ Return the number of rows preceding the data table for *series* in the Excel worksheet. """ title_and_spacer_rows = series.index * 2 data_point_rows = series.data_point_offset return title_and_spacer_rows + data_point...
bottom 5 rows in python
def table_top_abs(self): """Returns the absolute position of table top""" table_height = np.array([0, 0, self.table_full_size[2]]) return string_to_array(self.floor.get("pos")) + table_height
def iter_except_top_row_tcs(self): """Generate each `a:tc` element in non-first rows of range.""" for tr in self._tbl.tr_lst[self._top + 1:self._bottom]: for tc in tr.tc_lst[self._left:self._right]: yield tc
bottom 5 rows in python
def table_top_abs(self): """Returns the absolute position of table top""" table_height = np.array([0, 0, self.table_full_size[2]]) return string_to_array(self.floor.get("pos")) + table_height
def pop_row(self, idr=None, tags=False): """Pops a row, default the last""" idr = idr if idr is not None else len(self.body) - 1 row = self.body.pop(idr) return row if tags else [cell.childs[0] for cell in row]
python cv2 np array to gray scale
def gray2bgr(img): """Convert a grayscale image to BGR image. Args: img (ndarray or str): The input image. Returns: ndarray: The converted BGR image. """ img = img[..., None] if img.ndim == 2 else img out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) return out_img
def normalize(im, invert=False, scale=None, dtype=np.float64): """ Normalize a field to a (min, max) exposure range, default is (0, 255). (min, max) exposure values. Invert the image if requested. """ if dtype not in {np.float16, np.float32, np.float64}: raise ValueError('dtype must be numpy...
python cv2 np array to gray scale
def gray2bgr(img): """Convert a grayscale image to BGR image. Args: img (ndarray or str): The input image. Returns: ndarray: The converted BGR image. """ img = img[..., None] if img.ndim == 2 else img out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) return out_img
def im2mat(I): """Converts and image to matrix (one pixel per line)""" return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))
python cv2 np array to gray scale
def gray2bgr(img): """Convert a grayscale image to BGR image. Args: img (ndarray or str): The input image. Returns: ndarray: The converted BGR image. """ img = img[..., None] if img.ndim == 2 else img out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) return out_img
def smooth_gaussian(image, sigma=1): """Returns Gaussian smoothed image. :param image: numpy array or :class:`jicimagelib.image.Image` :param sigma: standard deviation :returns: :class:`jicimagelib.image.Image` """ return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode="nearest")
python cv2 rotate image 90 degrees
def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA): """ Rotates an image by deg degrees Arguments: deg (float): degree to rotate. """ r,c,*_ = im.shape M = cv2.getRotationMatrix2D((c//2,r//2),deg,1) return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv...
def rotateImage(img, angle): """ querries scipy.ndimage.rotate routine :param img: image to be rotated :param angle: angle to be rotated (radian) :return: rotated image """ imgR = scipy.ndimage.rotate(img, angle, reshape=False) return imgR
python cv2 rotate image 90 degrees
def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA): """ Rotates an image by deg degrees Arguments: deg (float): degree to rotate. """ r,c,*_ = im.shape M = cv2.getRotationMatrix2D((c//2,r//2),deg,1) return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv...
def zoom_cv(x,z): """ Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion. """ if z==0: return x r,c,*_ = x.shape M = cv2.getRotationMatrix2D((c/2,r/2),0,z+1.) return cv2.warpAffine(x,M,(c,r))
python cv2 rotate image 90 degrees
def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA): """ Rotates an image by deg degrees Arguments: deg (float): degree to rotate. """ r,c,*_ = im.shape M = cv2.getRotationMatrix2D((c//2,r//2),deg,1) return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv...
def rotate_point(xorigin, yorigin, x, y, angle): """Rotate the given point by angle """ rotx = (x - xorigin) * np.cos(angle) - (y - yorigin) * np.sin(angle) roty = (x - yorigin) * np.sin(angle) + (y - yorigin) * np.cos(angle) return rotx, roty
python cv2 rotate image 90 degrees
def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA): """ Rotates an image by deg degrees Arguments: deg (float): degree to rotate. """ r,c,*_ = im.shape M = cv2.getRotationMatrix2D((c//2,r//2),deg,1) return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv...
def transform_from_rot_trans(R, t): """Transforation matrix from rotation matrix and translation vector.""" R = R.reshape(3, 3) t = t.reshape(3, 1) return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))
python date parser without format
def parse(self, s): """ Parses a date string formatted like ``YYYY-MM-DD``. """ return datetime.datetime.strptime(s, self.date_format).date()
def parse_json_date(value): """ Parses an ISO8601 formatted datetime from a string value """ if not value: return None return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)
callable title objects in python
def sortable_title(instance): """Uses the default Plone sortable_text index lower-case """ title = plone_sortable_title(instance) if safe_callable(title): title = title() return title.lower()
def _format_title_string(self, title_string): """ format mpv's title """ return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix))
callable title objects in python
def sortable_title(instance): """Uses the default Plone sortable_text index lower-case """ title = plone_sortable_title(instance) if safe_callable(title): title = title() return title.lower()
def show_tip(self, tip=""): """Show tip""" QToolTip.showText(self.mapToGlobal(self.pos()), tip, self)
callable title objects in python
def sortable_title(instance): """Uses the default Plone sortable_text index lower-case """ title = plone_sortable_title(instance) if safe_callable(title): title = title() return title.lower()
def get_title(soup): """Given a soup, pick out a title""" if soup.title: return soup.title.string if soup.h1: return soup.h1.string return ''
callable title objects in python
def sortable_title(instance): """Uses the default Plone sortable_text index lower-case """ title = plone_sortable_title(instance) if safe_callable(title): title = title() return title.lower()
def __getattr__(self, name): """Return wrapper to named api method.""" return functools.partial(self._obj.request, self._api_prefix + name)
can we access img in django python
def show_image(self, key): """Show image (item is a PIL image)""" data = self.model.get_data() data[key].show()
def retrieve_asset(filename): """ Retrieves a non-image asset associated with an entry """ record = model.Image.get(asset_name=filename) if not record: raise http_error.NotFound("File not found") if not record.is_asset: raise http_error.Forbidden() return flask.send_file(record.fil...
can we access img in django python
def show_image(self, key): """Show image (item is a PIL image)""" data = self.model.get_data() data[key].show()
def url_to_image(url): """ Fetch an image from url and convert it into a Pillow Image object """ r = requests.get(url) image = StringIO(r.content) return image
can we access img in django python
def show_image(self, key): """Show image (item is a PIL image)""" data = self.model.get_data() data[key].show()
def get_plain_image_as_widget(self): """Used for generating thumbnails. Does not include overlaid graphics. """ arr = self.getwin_array(order=self.rgb_order) image = self._get_qimage(arr, self.qimg_fmt) return image
center align text python
def center_text(text, width=80): """Center all lines of the text. It is assumed that all lines width is smaller then B{width}, because the line width will not be checked. Args: text (str): Text to wrap. width (int): Maximum number of characters per line. Returns: str: Cent...
def get_margin(length): """Add enough tabs to align in two columns""" if length > 23: margin_left = "\t" chars = 1 elif length > 15: margin_left = "\t\t" chars = 2 elif length > 7: margin_left = "\t\t\t" chars = 3 else: margin_left = "\t\t\t\t"...
center align text python
def center_text(text, width=80): """Center all lines of the text. It is assumed that all lines width is smaller then B{width}, because the line width will not be checked. Args: text (str): Text to wrap. width (int): Maximum number of characters per line. Returns: str: Cent...
def margin(text): r"""Add a margin to both ends of each line in the string. Example: >>> margin('line1\nline2') ' line1 \n line2 ' """ lines = str(text).split('\n') return '\n'.join(' {} '.format(l) for l in lines)
center align text python
def center_text(text, width=80): """Center all lines of the text. It is assumed that all lines width is smaller then B{width}, because the line width will not be checked. Args: text (str): Text to wrap. width (int): Maximum number of characters per line. Returns: str: Cent...
def normalize_text(text, line_len=80, indent=""): """Wrap the text on the given line length.""" return "\n".join( textwrap.wrap( text, width=line_len, initial_indent=indent, subsequent_indent=indent ) )
center align text python
def center_text(text, width=80): """Center all lines of the text. It is assumed that all lines width is smaller then B{width}, because the line width will not be checked. Args: text (str): Text to wrap. width (int): Maximum number of characters per line. Returns: str: Cent...
def dumped(text, level, indent=2): """Put curly brackets round an indented text""" return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n"
change path of log files using python rotatingfilehandler
def timed_rotating_file_handler(name, logname, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False): """ A Bark logging handler logging output to a named file. At intervals specified by the 'when', the file wil...
def set_history_file(self, path): """Set path to history file. "" produces no file.""" if path: self.history = prompt_toolkit.history.FileHistory(fixpath(path)) else: self.history = prompt_toolkit.history.InMemoryHistory()
change path of log files using python rotatingfilehandler
def timed_rotating_file_handler(name, logname, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False): """ A Bark logging handler logging output to a named file. At intervals specified by the 'when', the file wil...
def bin_open(fname: str): """ Returns a file descriptor for a plain text or gzipped file, binary read mode for subprocess interaction. :param fname: The filename to open. :return: File descriptor in binary read mode. """ if fname.endswith(".gz"): return gzip.open(fname, "rb") re...
change path of log files using python rotatingfilehandler
def timed_rotating_file_handler(name, logname, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False): """ A Bark logging handler logging output to a named file. At intervals specified by the 'when', the file wil...
def DeleteLog() -> None: """Delete log file.""" if os.path.exists(Logger.FileName): os.remove(Logger.FileName)
change path of log files using python rotatingfilehandler
def timed_rotating_file_handler(name, logname, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False): """ A Bark logging handler logging output to a named file. At intervals specified by the 'when', the file wil...
def dir_path(dir): """with dir_path(path) to change into a directory.""" old_dir = os.getcwd() os.chdir(dir) yield os.chdir(old_dir)
change path of log files using python rotatingfilehandler
def timed_rotating_file_handler(name, logname, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False): """ A Bark logging handler logging output to a named file. At intervals specified by the 'when', the file wil...
def __init__(self, filename, mode, encoding=None): """Use the specified filename for streamed logging.""" FileHandler.__init__(self, filename, mode, encoding) self.mode = mode self.encoding = encoding
python deter is an invalid keyword
def is_identifier(string): """Check if string could be a valid python identifier :param string: string to be tested :returns: True if string can be a python identifier, False otherwise :rtype: bool """ matched = PYTHON_IDENTIFIER_RE.match(string) return bool(matched) and not keyword.iskeywo...
def check_for_positional_argument(kwargs, name, default=False): """ @type kwargs: dict @type name: str @type default: bool, int, str @return: bool, int """ if name in kwargs: if str(kwargs[name]) == "True": return True elif str(kwargs[name]) == "False": ...
python deter is an invalid keyword
def is_identifier(string): """Check if string could be a valid python identifier :param string: string to be tested :returns: True if string can be a python identifier, False otherwise :rtype: bool """ matched = PYTHON_IDENTIFIER_RE.match(string) return bool(matched) and not keyword.iskeywo...
def check_oneof(**kwargs): """Raise ValueError if more than one keyword argument is not none. Args: kwargs (dict): The keyword arguments sent to the function. Returns: None Raises: ValueError: If more than one entry in kwargs is not none. """ # Sanity check: If no keyword argu...
python deter is an invalid keyword
def is_identifier(string): """Check if string could be a valid python identifier :param string: string to be tested :returns: True if string can be a python identifier, False otherwise :rtype: bool """ matched = PYTHON_IDENTIFIER_RE.match(string) return bool(matched) and not keyword.iskeywo...
def validate_args(**args): """ function to check if input query is not None and set missing arguments to default value """ if not args['query']: print("\nMissing required query argument.") sys.exit() for key in DEFAULTS: if key not in args: args[key] = DEFAULTS[key] return args
python deter is an invalid keyword
def is_identifier(string): """Check if string could be a valid python identifier :param string: string to be tested :returns: True if string can be a python identifier, False otherwise :rtype: bool """ matched = PYTHON_IDENTIFIER_RE.match(string) return bool(matched) and not keyword.iskeywo...
def get_value(self, context): """Run python eval on the input string.""" if self.value: return expressions.eval_string(self.value, context) else: # Empty input raises cryptic EOF syntax err, this more human # friendly raise ValueError('!py string e...
python deter is an invalid keyword
def is_identifier(string): """Check if string could be a valid python identifier :param string: string to be tested :returns: True if string can be a python identifier, False otherwise :rtype: bool """ matched = PYTHON_IDENTIFIER_RE.match(string) return bool(matched) and not keyword.iskeywo...
def _check_valid(key, val, valid): """Helper to check valid options""" if val not in valid: raise ValueError('%s must be one of %s, not "%s"' % (key, valid, val))
python determine whether windows or linux
def _platform_is_windows(platform=sys.platform): """Is the current OS a Windows?""" matched = platform in ('cygwin', 'win32', 'win64') if matched: error_msg = "Windows isn't supported yet" raise OSError(error_msg) return matched
def _get_wow64(): """ Determines if the current process is running in Windows-On-Windows 64 bits. @rtype: bool @return: C{True} of the current process is a 32 bit program running in a 64 bit version of Windows, C{False} if it's either a 32 bit program in a 32 bit Windows or a 64 bit pr...
python determine whether windows or linux
def _platform_is_windows(platform=sys.platform): """Is the current OS a Windows?""" matched = platform in ('cygwin', 'win32', 'win64') if matched: error_msg = "Windows isn't supported yet" raise OSError(error_msg) return matched
def check64bit(current_system="python"): """checks if you are on a 64 bit platform""" if current_system == "python": return sys.maxsize > 2147483647 elif current_system == "os": import platform pm = platform.machine() if pm != ".." and pm.endswith('64'): # recent Python (not...
python determine whether windows or linux
def _platform_is_windows(platform=sys.platform): """Is the current OS a Windows?""" matched = platform in ('cygwin', 'win32', 'win64') if matched: error_msg = "Windows isn't supported yet" raise OSError(error_msg) return matched
def _is_osx_107(): """ :return: A bool if the current machine is running OS X 10.7 """ if sys.platform != 'darwin': return False version = platform.mac_ver()[0] return tuple(map(int, version.split('.')))[0:2] == (10, 7)
check all attributes in an object python
def hasattrs(object, *names): """ 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. :param object: an object that may or may not contain the listed attributes :param n...
def get_methods(*objs): """ Return the names of all callable attributes of an object""" return set( attr for obj in objs for attr in dir(obj) if not attr.startswith('_') and callable(getattr(obj, attr)) )
check equality between arrays python
def numpy_aware_eq(a, b): """Return whether two objects are equal via recursion, using :func:`numpy.array_equal` for comparing numpy arays. """ if isinstance(a, np.ndarray) or isinstance(b, np.ndarray): return np.array_equal(a, b) if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and...
def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
check equality between arrays python
def numpy_aware_eq(a, b): """Return whether two objects are equal via recursion, using :func:`numpy.array_equal` for comparing numpy arays. """ if isinstance(a, np.ndarray) or isinstance(b, np.ndarray): return np.array_equal(a, b) if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and...
def equal(obj1, obj2): """Calculate equality between two (Comparable) objects.""" Comparable.log(obj1, obj2, '==') equality = obj1.equality(obj2) Comparable.log(obj1, obj2, '==', result=equality) return equality
check equality between arrays python
def numpy_aware_eq(a, b): """Return whether two objects are equal via recursion, using :func:`numpy.array_equal` for comparing numpy arays. """ if isinstance(a, np.ndarray) or isinstance(b, np.ndarray): return np.array_equal(a, b) if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and...
def _eq(self, other): """Compare two nodes for equality.""" return (self.type, self.value) == (other.type, other.value)
check if an element is present in python and webdriver
def is_element_present(driver, selector, by=By.CSS_SELECTOR): """ Returns whether the specified element selector is present on the page. @Params driver - the webdriver object (required) selector - the locator that is used (required) by - the method to search for the locator (Default: By.CSS_SELE...
def assert_visible(self, locator, msg=None): """ Hard assert for whether and element is present and visible in the current window/frame :params locator: the locator of the element to search for :params msg: (Optional) msg explaining the difference """ e = driver.find_ele...
check if an element is present in python and webdriver
def is_element_present(driver, selector, by=By.CSS_SELECTOR): """ Returns whether the specified element selector is present on the page. @Params driver - the webdriver object (required) selector - the locator that is used (required) by - the method to search for the locator (Default: By.CSS_SELE...
def is_webdriver_ios(webdriver): """ Check if a web driver if mobile. Args: webdriver (WebDriver): Selenium webdriver. """ browser = webdriver.capabilities['browserName'] if (browser == u('iPhone') or browser == u('iPad')): return T...
check if an element is present in python and webdriver
def is_element_present(driver, selector, by=By.CSS_SELECTOR): """ Returns whether the specified element selector is present on the page. @Params driver - the webdriver object (required) selector - the locator that is used (required) by - the method to search for the locator (Default: By.CSS_SELE...
def _interface_exists(self, interface): """Check whether interface exists.""" ios_cfg = self._get_running_config() parse = HTParser(ios_cfg) itfcs_raw = parse.find_lines("^interface " + interface) return len(itfcs_raw) > 0
check if arg is function python
def is_callable(*p): """ True if all the args are functions and / or subroutines """ import symbols return all(isinstance(x, symbols.FUNCTION) for x in p)
def is_parameter(self): """Whether this is a function parameter.""" return (isinstance(self.scope, CodeFunction) and self in self.scope.parameters)
check if column is object in python
def is_dataframe(obj): """ Returns True if the given object is a Pandas Data Frame. Parameters ---------- obj: instance The object to test whether or not is a Pandas DataFrame. """ try: # This is the best method of type checking from pandas import DataFrame r...
def is_not_null(df: DataFrame, col_name: str) -> bool: """ 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. """ if ( isinstance(df, pd.DataFrame) and col_name in...
check if column is object in python
def is_dataframe(obj): """ Returns True if the given object is a Pandas Data Frame. Parameters ---------- obj: instance The object to test whether or not is a Pandas DataFrame. """ try: # This is the best method of type checking from pandas import DataFrame r...
def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type one that inherits from :class:`Numeric`, such as :class:`Float`, :class:`Decimal`? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Numeric)
check if column is object in python
def is_dataframe(obj): """ Returns True if the given object is a Pandas Data Frame. Parameters ---------- obj: instance The object to test whether or not is a Pandas DataFrame. """ try: # This is the best method of type checking from pandas import DataFrame r...
def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type an integer type? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Integer)
check if column is object in python
def is_dataframe(obj): """ Returns True if the given object is a Pandas Data Frame. Parameters ---------- obj: instance The object to test whether or not is a Pandas DataFrame. """ try: # This is the best method of type checking from pandas import DataFrame r...
def columns_equal(a: Column, b: Column) -> bool: """ Are two SQLAlchemy columns are equal? Checks based on: - column ``name`` - column ``type`` (see :func:`column_types_equal`) - ``nullable`` """ return ( a.name == b.name and column_types_equal(a.type, b.type) and a....
check if column is object in python
def is_dataframe(obj): """ Returns True if the given object is a Pandas Data Frame. Parameters ---------- obj: instance The object to test whether or not is a Pandas DataFrame. """ try: # This is the best method of type checking from pandas import DataFrame r...
def _raise_error_if_column_exists(dataset, column_name = 'dataset', dataset_variable_name = 'dataset', column_name_error_message_name = 'column_name'): """ Check if a column exists in an SFrame with error message. """ err_msg = 'The SFrame {0} must...
python django delete all rows in table
def delete_all_from_db(): """Clear the database. Used for testing and debugging. """ # The models.CASCADE property is set on all ForeignKey fields, so tables can # be deleted in any order without breaking constraints. for model in django.apps.apps.get_models(): model.objects.all().dele...
def drop_all_tables(self): """Drop all tables in the database""" for table_name in self.table_names(): self.execute_sql("DROP TABLE %s" % table_name) self.connection.commit()
python django delete all rows in table
def delete_all_from_db(): """Clear the database. Used for testing and debugging. """ # The models.CASCADE property is set on all ForeignKey fields, so tables can # be deleted in any order without breaking constraints. for model in django.apps.apps.get_models(): model.objects.all().dele...
def destroy(self): """ Destroy the SQLStepQueue tables in the database """ with self._db_conn() as conn: for table_name in self._tables: conn.execute('DROP TABLE IF EXISTS %s' % table_name) return self
python django delete all rows in table
def delete_all_from_db(): """Clear the database. Used for testing and debugging. """ # The models.CASCADE property is set on all ForeignKey fields, so tables can # be deleted in any order without breaking constraints. for model in django.apps.apps.get_models(): model.objects.all().dele...
def remove_non_magic_cols(self): """ Remove all non-MagIC columns from all tables. """ for table_name in self.tables: table = self.tables[table_name] table.remove_non_magic_cols_from_table()
check if number is complex python
def is_complex(dtype): """Returns whether this is a complex floating point type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'is_complex'): return dtype.is_complex return np.issubdtype(np.dtype(dtype), np.complex)
def is_finite(value: Any) -> bool: """Return true if a value is a finite number.""" return isinstance(value, int) or (isinstance(value, float) and isfinite(value))
check if number is complex python
def is_complex(dtype): """Returns whether this is a complex floating point type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'is_complex'): return dtype.is_complex return np.issubdtype(np.dtype(dtype), np.complex)
def isreal(obj): """ Test if the argument is a real number (float or integer). :param obj: Object :type obj: any :rtype: boolean """ return ( (obj is not None) and (not isinstance(obj, bool)) and isinstance(obj, (int, float)) )
check is string is date in python
def is_date(thing): """Checks if the given thing represents a date :param thing: The object to check if it is a date :type thing: arbitrary object :returns: True if we have a date object :rtype: bool """ # known date types date_types = (datetime.datetime, datetime.date...
def is_date_type(cls): """Return True if the class is a date type.""" if not isinstance(cls, type): return False return issubclass(cls, date) and not issubclass(cls, datetime)
check is string is date in python
def is_date(thing): """Checks if the given thing represents a date :param thing: The object to check if it is a date :type thing: arbitrary object :returns: True if we have a date object :rtype: bool """ # known date types date_types = (datetime.datetime, datetime.date...
def is_timestamp(obj): """ Yaml either have automatically converted it to a datetime object or it is a string that will be validated later. """ return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)
python draw a box at random coordinates
def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y)
def point8_to_box(points): """ Args: points: (nx4)x2 Returns: nx4 boxes (x1y1x2y2) """ p = points.reshape((-1, 4, 2)) minxy = p.min(axis=1) # nx2 maxxy = p.max(axis=1) # nx2 return np.concatenate((minxy, maxxy), axis=1)
python draw a box at random coordinates
def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y)
def _draw_lines_internal(self, coords, colour, bg): """Helper to draw lines connecting a set of nodes that are scaled for the Screen.""" for i, (x, y) in enumerate(coords): if i == 0: self._screen.move(x, y) else: self._screen.draw(x, y, colour=col...
python draw a box at random coordinates
def from_rectangle(box): """ Create a vector randomly within the given rectangle. """ x = box.left + box.width * random.uniform(0, 1) y = box.bottom + box.height * random.uniform(0, 1) return Vector(x, y)
def polyline(self, arr): """Draw a set of lines""" for i in range(0, len(arr) - 1): self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1])
check my python path
def launched(): """Test whether the current python environment is the correct lore env. :return: :any:`True` if the environment is launched :rtype: bool """ if not PREFIX: return False return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)
def isPackage(file_path): """ Determine whether or not a given path is a (sub)package or not. """ return (os.path.isdir(file_path) and os.path.isfile(os.path.join(file_path, '__init__.py')))
check my python path
def launched(): """Test whether the current python environment is the correct lore env. :return: :any:`True` if the environment is launched :rtype: bool """ if not PREFIX: return False return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)
def _pip_exists(self): """Returns True if pip exists inside the virtual environment. Can be used as a naive way to verify that the environment is installed.""" return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
check my python path
def launched(): """Test whether the current python environment is the correct lore env. :return: :any:`True` if the environment is launched :rtype: bool """ if not PREFIX: return False return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)
def _is_already_configured(configuration_details): """Returns `True` when alias already in shell config.""" path = Path(configuration_details.path).expanduser() with path.open('r') as shell_config: return configuration_details.content in shell_config.read()
check my python path
def launched(): """Test whether the current python environment is the correct lore env. :return: :any:`True` if the environment is launched :rtype: bool """ if not PREFIX: return False return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)
def isdir(path, **kwargs): """Check if *path* is a directory""" import os.path return os.path.isdir(path, **kwargs)
python elasticsearch bulk index
def update_index(index): """Re-index every document in a named index.""" logger.info("Updating search index: '%s'", index) client = get_client() responses = [] for model in get_index_models(index): logger.info("Updating search index model: '%s'", model.search_doc_type) objects = mode...
def can_elasticsearch(record): """Check if a given record is indexed. :param record: A record object. :returns: If the record is indexed returns `True`, otherwise `False`. """ search = request._methodview.search_class() search = search.get_record(str(record.id)) return search.count() == 1
python elasticsearch bulk index
def update_index(index): """Re-index every document in a named index.""" logger.info("Updating search index: '%s'", index) client = get_client() responses = [] for model in get_index_models(index): logger.info("Updating search index model: '%s'", model.search_doc_type) objects = mode...
def clear_es(): """Clear all indexes in the es core""" # TODO: should receive a catalog slug. ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404]) LOGGER.debug('Elasticsearch: Index cleared')
python elasticsearch bulk index
def update_index(index): """Re-index every document in a named index.""" logger.info("Updating search index: '%s'", index) client = get_client() responses = [] for model in get_index_models(index): logger.info("Updating search index model: '%s'", model.search_doc_type) objects = mode...
def all_documents(index=INDEX_NAME): """ Get all documents from the given index. Returns full Elasticsearch objects so you can get metadata too. """ query = { 'query': { 'match_all': {} } } for result in raw_query(query, index=index): yield result
checking types of elements inside of an 2d array python
def _valid_other_type(x, types): """ Do all elements of x have a type from types? """ return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))
def contains_all(self, array): """Test if `array` is an array of real numbers.""" dtype = getattr(array, 'dtype', None) if dtype is None: dtype = np.result_type(*array) return is_real_dtype(dtype)
checking types of elements inside of an 2d array python
def _valid_other_type(x, types): """ Do all elements of x have a type from types? """ return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))
def is_vector(inp): """ Returns true if the input can be interpreted as a 'true' vector Note ---- Does only check dimensions, not if type is numeric Parameters ---------- inp : numpy.ndarray or something that can be converted into ndarray Returns ------- Boolean True f...
checking types of elements inside of an 2d array python
def _valid_other_type(x, types): """ Do all elements of x have a type from types? """ return all(any(isinstance(el, t) for t in types) for el in np.ravel(x))
def is_int_vector(l): r"""Checks if l is a numpy array of integers """ if isinstance(l, np.ndarray): if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'): return True return False
python equivalent of matlab movmean function
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
def average_gradient(data, *kwargs): """ Compute average gradient norm of an image """ return np.average(np.array(np.gradient(data))**2)
python equivalent of matlab movmean function
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
def hmean_int(a, a_min=5778, a_max=1149851): """ Harmonic mean of an array, returns the closest int """ from scipy.stats import hmean return int(round(hmean(np.clip(a, a_min, a_max))))
python equivalent of matlab movmean function
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
def get_mi_vec(slab): """ Convenience function which returns the unit vector aligned with the miller index. """ mvec = np.cross(slab.lattice.matrix[0], slab.lattice.matrix[1]) return mvec / np.linalg.norm(mvec)
python equivalent of matlab movmean function
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
def _mean_absolute_error(y, y_pred, w): """Calculate the mean absolute error.""" return np.average(np.abs(y_pred - y), weights=w)
python equivalent of matlab movmean function
def _propagate_mean(mean, linop, dist): """Propagate a mean through linear Gaussian transformation.""" return linop.matmul(mean) + dist.mean()[..., tf.newaxis]
def mean(inlist): """ Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist) """ sum = 0 for item in inlist: sum = sum + item return sum / float(len(inlist))
End of preview. Expand in Data Studio

CoSQA Verified Hard Negatives 🔍

Hard negatives for code retrieval, mined and LLM-filtered from the CoSQA dataset. The "verified" label is used loosely — see the caveats below.

What's in here? 📦

Each row contains:

  • anchor — a natural language query (e.g. "how do I reverse a list in python")
  • positive — a code snippet that correctly answers the query ✅
  • negative — a hard negative code snippet that looks similar but probably doesn't answer the query ❌

How was this built? 🏗️

  1. Positives extracted from CoSQA score=1 pairs (~9k query/code pairs)
  2. Hard negatives mined 🧲 using benjamintli/modernbert-cosqa — a ModernBERT-base model fine-tuned on CoSQA — to retrieve the most similar (but not positive) code snippets from the full 20k corpus via FAISS
  3. LLM filtering 🤖 with a Qwen/Qwen3-Coder-Next model — each candidate negative was checked with the prompt "is this code relevant to the query?" and candidates flagged as relevant were removed as likely false negatives

⚠️ Caveats

The LLM verifier achieved ~80% accuracy when tested against known CoSQA positives, meaning roughly 1 in 5 false negatives may slip through into the dataset. The verifier also tends to be conservative, so some valid hard negatives may have been incorrectly filtered out.

This dataset is cleaner than unverified hard negatives, but not perfectly clean. Treat it as a best-effort filter rather than ground truth.

Intended use 🎯

Drop-in training data for bi-encoder code retrieval models using contrastive losses like CachedMultipleNegativesRankingLoss with sentence-transformers:

from datasets import load_dataset
dataset = load_dataset("benjamintli/cosqa-verified-hard-negatives", split="train")
# columns: anchor, positive, negative
Downloads last month
11

Models trained or fine-tuned on benjamintli/cosqa-llm-filtered-hard-negatives

MiniMax H3 Video Generator 20 free credits · Text & image to video Try Free →