benjamintli/cosqa-llm-filtered-hard-negatives huggingface dataset:
Query: call unittest from a script python

Relevant code:
def main(argv=sys.argv, stream=sys.stderr):
    """Entry point for ``tappy`` command."""
    args = parse_args(argv)
    suite = build_suite(args)
    runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)
    result = runner.run(suite)

    return get_status(result)

Similar but not relevant code:
def run(self):
        """
        Runs the unit test framework. Can be overridden to run anything.
        Returns True on passing and False on failure.
        """
        try:
            import nose
            arguments = [sys.argv[0]] + list(self.test_args)
            return nose.run(argv=arguments)
        except ImportError:
            print()
            print("*** Nose library missing. Please install it. ***")
            print()
            raise
Query: python docx add section to each page

Relevant code:
def fill_document(doc):
    """Add a section, a subsection and some text to the document.

    :param doc: the document
    :type doc: :class:`pylatex.document.Document` instance
    """
    with doc.create(Section('A section')):
        doc.append('Some regular text and some ')
        doc.append(italic('italic text. '))

        with doc.create(Subsection('A subsection')):
            doc.append('Also some crazy characters: $&#{}')

Similar but not relevant code:
def Output(self):
    """Output all sections of the page."""
    self.Open()
    self.Header()
    self.Body()
    self.Footer()

Similar but not relevant code:
def layout(self, indent='    '):
		"""This will indent each new tag in the body by given number of spaces."""


		self.__indent(self.head, indent)
		self.__indent(self.meta, indent)
		self.__indent(self.stylesheet, indent)
		self.__indent(self.header, indent)
		self.__indent(self.body, indent, initial=3)
		self.__indent(self.footer, indent)
		self.__indent(self.body_pre_docinfo, indent, initial=3)
		self.__indent(self.docinfo, indent)

Similar but not relevant code:
def indent(block, spaces):
    """ indents paragraphs of text for rst formatting """
    new_block = ''
    for line in block.split('\n'):
        new_block += spaces + line + '\n'
    return new_block

Similar but not relevant code:
def inline_inputs(self):
        """Inline all input latex files references by this document. The
        inlining is accomplished recursively. The document is modified
        in place.
        """
        self.text = texutils.inline(self.text,
                                    os.path.dirname(self._filepath))
        # Remove children
        self._children = {}

Similar but not relevant code:
def indent(self):
        """
        Begins an indented block. Must be used in a 'with' code block.
        All calls to the logger inside of the block will be indented.
        """
        blk = IndentBlock(self, self._indent)
        self._indent += 1
        return blk
Query: python docx number a section

Relevant code:
def fill_document(doc):
    """Add a section, a subsection and some text to the document.

    :param doc: the document
    :type doc: :class:`pylatex.document.Document` instance
    """
    with doc.create(Section('A section')):
        doc.append('Some regular text and some ')
        doc.append(italic('italic text. '))

        with doc.create(Subsection('A subsection')):
            doc.append('Also some crazy characters: $&#{}')

Similar but not relevant code:
def Output(self):
    """Output all sections of the page."""
    self.Open()
    self.Header()
    self.Body()
    self.Footer()

Similar but not relevant code:
def process_docstring(app, what, name, obj, options, lines):
    """React to a docstring event and append contracts to it."""
    # pylint: disable=unused-argument
    # pylint: disable=too-many-arguments
    lines.extend(_format_contracts(what=what, obj=obj))

Similar but not relevant code:
def _put_header(self):
        """ Standard first line in a PDF. """
        self.session._out('%%PDF-%s' % self.pdf_version)
        if self.session.compression:
            self.session.buffer += '%' + chr(235) + chr(236) + chr(237) + chr(238) + "\n"

Similar but not relevant code:
def _generate(self):
        """Parses a file or directory of files into a set of ``Document`` objects."""
        doc_count = 0
        for fp in self.all_files:
            for doc in self._get_docs_for_path(fp):
                yield doc
                doc_count += 1
                if doc_count >= self.max_docs:
                    return

Similar but not relevant code:
def _prt_line_detail(self, prt, line, lnum=""):
        """Print each field and its value."""
        data = zip(self.flds, line.split('\t'))
        txt = ["{:2}) {:13} {}".format(i, hdr, val) for i, (hdr, val) in enumerate(data)]
        prt.write("{LNUM}\n{TXT}\n".format(LNUM=lnum, TXT='\n'.join(txt)))
Query: python don't save history

Relevant code:
def update_redirect(self):
        """
            Call it on your own endpoint's to update the back history navigation.
            If you bypass it, the next submit or back will go over it.
        """
        page_history = Stack(session.get("page_history", []))
        page_history.push(request.url)
        session["page_history"] = page_history.to_json()

Similar but not relevant code:
def save(self):
        """save the current session
        override, if session was saved earlier"""
        if self.path:
            self._saveState(self.path)
        else:
            self.saveAs()

Similar but not relevant code:
def save_cache(data, filename):
    """Save cookies to a file."""
    with open(filename, 'wb') as handle:
        pickle.dump(data, handle)

Similar but not relevant code:
def save_session_to_file(self, sessionfile):
        """Not meant to be used directly, use :meth:`Instaloader.save_session_to_file`."""
        pickle.dump(requests.utils.dict_from_cookiejar(self._session.cookies), sessionfile)

Similar but not relevant code:
def after_epoch(self, **_) -> None:
        """Save/override the latest model after every epoch."""
        SaveEvery.save_model(model=self._model, name_suffix=self._OUTPUT_NAME, on_failure=self._on_save_failure)
Query: python dot product implementation

Relevant code:
def dot_product(self, other):
        """ Return the dot product of the given vectors. """
        return self.x * other.x + self.y * other.y

Similar but not relevant code:
def multiply(traj):
    """Sophisticated simulation of multiplication"""
    z=traj.x*traj.y
    traj.f_add_result('z',z=z, comment='I am the product of two reals!')
Query: can i grab each letter in a string python

Relevant code:
def return_letters_from_string(text):
    """Get letters from string only."""
    out = ""
    for letter in text:
        if letter.isalpha():
            out += letter
    return out

Similar but not relevant code:
def tokenize(string):
    """Match and yield all the tokens of the input string."""
    for match in TOKENS_REGEX.finditer(string):
        yield Token(match.lastgroup, match.group().strip(), match.span())

Similar but not relevant code:
def strip_accents(string):
    """
    Strip all the accents from the string
    """
    return u''.join(
        (character for character in unicodedata.normalize('NFD', string)
         if unicodedata.category(character) != 'Mn'))

Similar but not relevant code:
def get_codes(s: Union[str, 'ChainedBase']) -> List[str]:
    """ Grab all escape codes from a string.
        Returns a list of all escape codes.
    """
    return codegrabpat.findall(str(s))
Query: can lists can be nested arbitrarily deep in python

Relevant code:
def flat_list(input_list):
    r"""
    Given a list of nested lists of arbitrary depth, returns a single level or
    'flat' list.

    """
    x = input_list
    if isinstance(x, list):
        return [a for i in x for a in flat_list(i)]
    else:
        return [x]

Similar but not relevant code:
def extend(self, iterable):
        """Extend the list by appending all the items in the given list."""
        return super(Collection, self).extend(
            self._ensure_iterable_is_valid(iterable))

Similar but not relevant code:
def listunion(ListOfLists):
    """
    Take the union of a list of lists.

    Take a Python list of Python lists::

            [[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]

    and return the aggregated list::

            [l11,l12, ..., l21, l22 , ...]

    For a list of two lists, e.g. `[a, b]`, this is like::

            a.extend(b)

    **Parameters**

            **ListOfLists** :  Python list

                    Python list of Python lists.

    **Returns**

            **u** :  Python list

                    Python list created by taking the union of the
                    lists in `ListOfLists`.

    """
    u = []
    for s in ListOfLists:
        if s != None:
            u.extend(s)
    return u
Query: can you open an excel file that python is writing too

Relevant code:
def save_excel(self, fd):
        """ Saves the case as an Excel spreadsheet.
        """
        from pylon.io.excel import ExcelWriter
        ExcelWriter(self).write(fd)

Similar but not relevant code:
def _openpyxl_read_xl(xl_path: str):
    """ Use openpyxl to read an Excel file. """
    try:
        wb = load_workbook(filename=xl_path, read_only=True)
    except:
        raise
    else:
        return wb

Similar but not relevant code:
def __init__(self, filename, formatting_info=False, handle_ambiguous_date=None):
    """Initialize the ExcelWorkbook instance."""
    super().__init__(filename)
    self.workbook = xlrd.open_workbook(self.filename, formatting_info=formatting_info)
    self.handle_ambiguous_date = handle_ambiguous_date

Similar but not relevant code:
def open_hdf5(filename, mode='r'):
    """Wrapper to open a :class:`h5py.File` from disk, gracefully
    handling a few corner cases
    """
    if isinstance(filename, (h5py.Group, h5py.Dataset)):
        return filename
    if isinstance(filename, FILE_LIKE):
        return h5py.File(filename.name, mode)
    return h5py.File(filename, mode)

Similar but not relevant code:
def _open_text(fname, **kwargs):
    """On Python 3 opens a file in text mode by using fs encoding and
    a proper en/decoding errors handler.
    On Python 2 this is just an alias for open(name, 'rt').
    """
    if PY3:
        kwargs.setdefault('encoding', ENCODING)
        kwargs.setdefault('errors', ENCODING_ERRS)
    return open(fname, "rt", **kwargs)

Similar but not relevant code:
def do_file_show(client, args):
    """Output file contents to stdout"""
    for src_uri in args.uris:
        client.download_file(src_uri, sys.stdout.buffer)

    return True
Query: can you open and parse xml files in python

Relevant code:
def xmltreefromfile(filename):
    """Internal function to read an XML file"""
    try:
        return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))
    except TypeError:
        return ElementTree.parse(filename, ElementTree.XMLParser())

Similar but not relevant code:
def ReadManyFromPath(filepath):
  """Reads a Python object stored in a specified YAML file.

  Args:
    filepath: A filepath to the YAML file.

  Returns:
    A Python data structure corresponding to the YAML in the given file.
  """
  with io.open(filepath, mode="r", encoding="utf-8") as filedesc:
    return ReadManyFromFile(filedesc)

Similar but not relevant code:
def _ParseYamlFromFile(filedesc):
  """Parses given YAML file."""
  content = filedesc.read()
  return yaml.Parse(content) or collections.OrderedDict()
Query: python dump json with custom encoder

Relevant code:
def compress(obj):
    """Outputs json without whitespace."""
    return json.dumps(obj, sort_keys=True, separators=(',', ':'),
                      cls=CustomEncoder)

Similar but not relevant code:
def download_json(local_filename, url, clobber=False):
    """Download the given JSON file, and pretty-print before we output it."""
    with open(local_filename, 'w') as json_file:
        json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': ')))
Query: can you return value from python row number and column name

Relevant code:
def cell(self, rowName, columnName):
        """
        Returns the value of the cell on the given row and column.
        """
        return self.matrix[self.rowIndices[rowName], self.columnIndices[columnName]]

Similar but not relevant code:
def get_column_keys_and_names(table):
    """
    Return a generator of tuples k, c such that k is the name of the python attribute for
    the column and c is the name of the column in the sql table.
    """
    ins = inspect(table)
    return ((k, c.name) for k, c in ins.mapper.c.items())

Similar but not relevant code:
def _get_str_columns(sf):
    """
    Returns a list of names of columns that are string type.
    """
    return [name for name in sf.column_names() if sf[name].dtype == str]

Similar but not relevant code:
def column_names(self, table):
      """An iterable of column names, for a particular table or
      view."""

      table_info = self.execute(
        u'PRAGMA table_info(%s)' % quote(table))
      return (column['name'] for column in table_info)

Similar but not relevant code:
def _get_name(column_like):
    """
    Get the name from a column-like SQLAlchemy expression.

    Works for Columns and Cast expressions.
    """
    if isinstance(column_like, Column):
        return column_like.name
    elif isinstance(column_like, Cast):
        return column_like.clause.name
Query: python dynamic or static typing recomendation

Relevant code:
def convert(self, value, _type):
        """
        Convert instances of textx types and match rules to python types.
        """
        return self.type_convertors.get(_type, lambda x: x)(value)

Similar but not relevant code:
def register_type(cls, name):
    """Register `name` as a type to validate as an instance of class `cls`."""
    x = TypeDefinition(name, (cls,), ())
    Validator.types_mapping[name] = x

Similar but not relevant code:
def static_method(cls, f):
        """Decorator which dynamically binds static methods to the model for later use."""
        setattr(cls, f.__name__, staticmethod(f))
        return f

Similar but not relevant code:
def return_type(type_name, formatter=None):
    """Specify that this function returns a typed value.

    Args:
        type_name (str): A type name known to the global typedargs type system
        formatter (str): An optional name of a formatting function specified
            for the type given in type_name.
    """

    def _returns(func):
        annotated(func)
        func.metadata.typed_returnvalue(type_name, formatter)
        return func

    return _returns

Similar but not relevant code:
def _opt_call_from_base_type(self, value):
    """Call _from_base_type() if necessary.

    If the value is a _BaseValue instance, unwrap it and call all
    _from_base_type() methods.  Otherwise, return the value
    unchanged.
    """
    if isinstance(value, _BaseValue):
      value = self._call_from_base_type(value.b_val)
    return value

Similar but not relevant code:
def convert_value(bind, value):
    """ Type casting. """
    type_name = get_type(bind)
    try:
        return typecast.cast(type_name, value)
    except typecast.ConverterError:
        return value
Query: can you set a list to a certain size python

Relevant code:
def _crop_list_to_size(l, size):
    """Make a list a certain size"""
    for x in range(size - len(l)):
        l.append(False)
    for x in range(len(l) - size):
        l.pop()
    return l

Similar but not relevant code:
def chunk_list(l, n):
    """Return `n` size lists from a given list `l`"""
    return [l[i:i + n] for i in range(0, len(l), n)]

Similar but not relevant code:
def pset(iterable=(), pre_size=8):
    """
    Creates a persistent set from iterable. Optionally takes a sizing parameter equivalent to that
    used for :py:func:`pmap`.

    >>> s1 = pset([1, 2, 3, 2])
    >>> s1
    pset([1, 2, 3])
    """
    if not iterable:
        return _EMPTY_PSET

    return PSet._from_iterable(iterable, pre_size=pre_size)

Similar but not relevant code:
def batch(items, size):
    """Batches a list into a list of lists, with sub-lists sized by a specified
    batch size."""
    return [items[x:x + size] for x in xrange(0, len(items), size)]
Query: python dynamically populating dropdown based upon another dropdown selection

Relevant code:
def onchange(self, value):
        """Called when a new DropDownItem gets selected.
        """
        log.debug('combo box. selected %s' % value)
        self.select_by_value(value)
        return (value, )

Similar but not relevant code:
def drag_and_drop(self, droppable):
        """
        Performs drag a element to another elmenet.

        Currently works only on Chrome driver.
        """
        self.scroll_to()
        ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()

Similar but not relevant code:
def popup(self, title, callfn, initialdir=None):
        """Let user select a directory."""
        super(DirectorySelection, self).popup(title, callfn, initialdir)

Similar but not relevant code:
def _updateItemComboBoxIndex(self, item, column, num):
        """Callback for comboboxes: notifies us that a combobox for the given item and column has changed"""
        item._combobox_current_index[column] = num
        item._combobox_current_value[column] = item._combobox_option_list[column][num][0]

Similar but not relevant code:
def OnContextMenu(self, event):
        """Context menu event handler"""

        self.grid.PopupMenu(self.grid.contextmenu)

        event.Skip()
Query: cannont compare tz naive and tz aware timestamps python

Relevant code:
def datetime_from_timestamp(timestamp, content):
    """
    Helper function to add timezone information to datetime,
    so that datetime is comparable to other datetime objects in recent versions
    that now also have timezone information.
    """
    return set_date_tzinfo(
        datetime.fromtimestamp(timestamp),
        tz_name=content.settings.get('TIMEZONE', None))

Similar but not relevant code:
def reload_localzone():
    """Reload the cached localzone. You need to call this if the timezone has changed."""
    global _cache_tz
    _cache_tz = pytz.timezone(get_localzone_name())
    utils.assert_tz_offset(_cache_tz)
    return _cache_tz
Query: cant compare date to none type python

Relevant code:
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)

Similar but not relevant code:
def _is_date_data(self, data_type):
        """Private method for determining if a data record is of type DATE."""
        dt = DATA_TYPES[data_type]
        if isinstance(self.data, dt['type']):
            self.type = data_type.upper()
            self.len = None
            return True

Similar but not relevant code:
def is_value_type_valid_for_exact_conditions(self, value):
    """ Method to validate if the value is valid for exact match type evaluation.

    Args:
      value: Value to validate.

    Returns:
      Boolean: True if value is a string, boolean, or number. Otherwise False.
    """
    # 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

Similar but not relevant code:
def is_equal_strings_ignore_case(first, second):
    """The function compares strings ignoring case"""
    if first and second:
        return first.upper() == second.upper()
    else:
        return not (first or second)

Similar but not relevant code:
def __cmp__(self, other):
        """Comparsion not implemented."""
        # Stops python 2 from allowing comparsion of arbitrary objects
        raise TypeError('unorderable types: {}, {}'
                        ''.format(self.__class__.__name__, type(other)))
Query: python each element in the array

Relevant code:
def arr_to_vector(arr):
    """Reshape a multidimensional array to a vector.
    """
    dim = array_dim(arr)
    tmp_arr = []
    for n in range(len(dim) - 1):
        for inner in arr:
            for i in inner:
                tmp_arr.append(i)
        arr = tmp_arr
        tmp_arr = []
    return arr

Similar but not relevant code:
def array(self):
        """
        return the underlying numpy array
        """
        return np.arange(self.start, self.stop, self.step)

Similar but not relevant code:
def layer_with(self, sample: np.ndarray, value: int) -> np.ndarray:
        """Create an identical 2d array where the second row is filled with value"""
        b = np.full((2, len(sample)), value, dtype=float)
        b[0] = sample
        return b
Query: python edit pdf access permissions

Relevant code:
def has_edit_permission(self, request):
        """ Can edit this object """
        return request.user.is_authenticated and request.user.is_active and request.user.is_staff

Similar but not relevant code:
def security(self):
        """Print security object information for a pdf document"""
        return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}

Similar but not relevant code:
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):
    """
    Appends a PDF to a pyPDF writer. Legacy interface.
    """
    append_memory_pdf_to_writer(input_pdf=input_pdf,
                                writer=output_writer)

Similar but not relevant code:
def perform_permissions_check(self, user, obj, perms):
        """ Performs the permission check. """
        return self.request.forum_permission_handler.can_download_files(obj, user)

Similar but not relevant code:
def resources(self):
        """Retrieve contents of each page of PDF"""
        return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())]

Similar but not relevant code:
def _single_page_pdf(page):
    """Construct a single page PDF from the provided page in memory"""
    pdf = Pdf.new()
    pdf.pages.append(page)
    bio = BytesIO()
    pdf.save(bio)
    bio.seek(0)
    return bio.read()
Query: capitalize element in list function python

Relevant code:
def _snake_to_camel_case(value):
    """Convert snake case string to camel case."""
    words = value.split("_")
    return words[0] + "".join(map(str.capitalize, words[1:]))

Similar but not relevant code:
def capitalize(string):
    """Capitalize a sentence.

    Parameters
    ----------
    string : `str`
        String to capitalize.

    Returns
    -------
    `str`
        Capitalized string.

    Examples
    --------
    >>> capitalize('worD WORD WoRd')
    'Word word word'
    """
    if not string:
        return string
    if len(string) == 1:
        return string.upper()
    return string[0].upper() + string[1:].lower()

Similar but not relevant code:
def fmt_camel(name):
    """
    Converts name to lower camel case. Words are identified by capitalization,
    dashes, and underscores.
    """
    words = split_words(name)
    assert len(words) > 0
    first = words.pop(0).lower()
    return first + ''.join([word.capitalize() for word in words])

Similar but not relevant code:
def camelcase2list(s, lower=False):
    """Converts a camelcase string to a list."""
    s = re.findall(r'([A-Z][a-z0-9]+)', s)
    return [w.lower() for w in s] if lower else s
Query: python edit pf access permissions

Relevant code:
def has_edit_permission(self, request):
        """ Can edit this object """
        return request.user.is_authenticated and request.user.is_active and request.user.is_staff

Similar but not relevant code:
def perform_permissions_check(self, user, obj, perms):
        """ Performs the permission check. """
        return self.request.forum_permission_handler.can_download_files(obj, user)