benjamintli/cosqa-llm-filtered-hard-negatives huggingface dataset:
Query: python set domain name

Relevant code:
def _config_win32_domain(self, domain):
        """Configure a Domain registry entry."""
        # we call str() on domain to convert it from unicode to ascii
        self.domain = dns.name.from_text(str(domain))

Similar but not relevant code:
def get_site_name(request):
    """Return the domain:port part of the URL without scheme.
    Eg: facebook.com, 127.0.0.1:8080, etc.
    """
    urlparts = request.urlparts
    return ':'.join([urlparts.hostname, str(urlparts.port)])

Similar but not relevant code:
def _get_local_ip(self):
        """Try to determine the local IP address of the machine."""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

            # Use Google Public DNS server to determine own IP
            sock.connect(('8.8.8.8', 80))

            return sock.getsockname()[0]
        except socket.error:
            try:
                return socket.gethostbyname(socket.gethostname())
            except socket.gaierror:
                return '127.0.0.1'
        finally:
            sock.close()

Similar but not relevant code:
def _clean_name(self, prefix, obj):
        """Create a C variable name with the given prefix based on the name of obj."""
        return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum()))
Query: python set rate limit

Relevant code:
def wait_on_rate_limit(self, value):
        """Enable or disable automatic rate-limit handling."""
        check_type(value, bool, may_be_none=False)
        self._wait_on_rate_limit = value

Similar but not relevant code:
def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1,
                                          catch_exceptions=()):
  """Executes a method until the retry limit is hit or not None is returned."""
  return retry_until_valid_or_limit_reached(
      method, limit, lambda x: x is not None, sleep_s, catch_exceptions)
Query: python set window position

Relevant code:
def set_position(self, x, y, width, height):
        """Set window top-left corner position and size"""
        SetWindowPos(self._hwnd, None, x, y, width, height, ctypes.c_uint(0))

Similar but not relevant code:
def set_cursor_position(self, position):
        """Set cursor position"""
        position = self.get_position(position)
        cursor = self.textCursor()
        cursor.setPosition(position)
        self.setTextCursor(cursor)
        self.ensureCursorVisible()

Similar but not relevant code:
def set_cursor(self, x, y):
        """
        Sets the cursor to the desired position.

        :param x: X position
        :param y: Y position
        """
        curses.curs_set(1)
        self.screen.move(y, x)

Similar but not relevant code:
def restore_scrollbar_position(self):
        """Restoring scrollbar position after main window is visible"""
        scrollbar_pos = self.get_option('scrollbar_position', None)
        if scrollbar_pos is not None:
            self.explorer.treewidget.set_scrollbar_position(scrollbar_pos)

Similar but not relevant code:
def ms_panset(self, viewer, event, data_x, data_y,
                  msg=True):
        """An interactive way to set the pan position.  The location
        (data_x, data_y) will be centered in the window.
        """
        if self.canpan and (event.state == 'down'):
            self._panset(viewer, data_x, data_y, msg=msg)
        return True
Query: how to set precision of a number to 2 decimal places in python

Relevant code:
def round_to_int(number, precision):
    """Round a number to a precision"""
    precision = int(precision)
    rounded = (int(number) + precision / 2) // precision * precision
    return rounded

Similar but not relevant code:
def get_decimal_quantum(precision):
    """Return minimal quantum of a number, as defined by precision."""
    assert isinstance(precision, (int, decimal.Decimal))
    return decimal.Decimal(10) ** (-precision)
Query: python set yaxis log

Relevant code:
def log_y_cb(self, w, val):
        """Toggle linear/log scale for Y-axis."""
        self.tab_plot.logy = val
        self.plot_two_columns()

Similar but not relevant code:
def set_axis_options(self, row, column, text):
        """Set additionnal options as plain text."""

        subplot = self.get_subplot_at(row, column)
        subplot.set_axis_options(text)

Similar but not relevant code:
def set_ylim(self, xlims, dx, xscale, reverse=False):
        """Set y limits for plot.

        This will set the limits for the y axis
        for the specific plot.

        Args:
            ylims (len-2 list of floats): The limits for the axis.
            dy (float): Amount to increment by between the limits.
            yscale (str): Scale of the axis. Either `log` or `lin`.
            reverse (bool, optional): If True, reverse the axis tick marks. Default is False.

        """
        self._set_axis_limits('y', xlims, dx, xscale, reverse)
        return

Similar but not relevant code:
def add_text(text, x=0.01, y=0.01, axes="gca", draw=True, **kwargs):
    """
    Adds text to the axes at the specified position.

    **kwargs go to the axes.text() function.
    """
    if axes=="gca": axes = _pylab.gca()
    axes.text(x, y, text, transform=axes.transAxes, **kwargs)
    if draw: _pylab.draw()

Similar but not relevant code:
def ylim(self, low, high, index=1):
        """Set yaxis limits.

        Parameters
        ----------
        low : number
        high : number
        index : int, optional

        Returns
        -------
        Chart

        """
        self.layout['yaxis' + str(index)]['range'] = [low, high]
        return self

Similar but not relevant code:
def set_ylimits(self, row, column, min=None, max=None):
        """Set y-axis limits of a subplot.

        :param row,column: specify the subplot.
        :param min: minimal axis value
        :param max: maximum axis value

        """
        subplot = self.get_subplot_at(row, column)
        subplot.set_ylimits(min, max)
Query: python show all variables memory

Relevant code:
def _print_memory(self, memory):
        """Print memory.
        """
        for addr, value in memory.items():
            print("    0x%08x : 0x%08x (%d)" % (addr, value, value))

Similar but not relevant code:
def memory_usage(self, deep=False):
        """
        Memory usage of my values

        Parameters
        ----------
        deep : bool
            Introspect the data deeply, interrogate
            `object` dtypes for system-level memory consumption

        Returns
        -------
        bytes used

        Notes
        -----
        Memory usage does not include memory consumed by elements that
        are not components of the array if deep=False

        See Also
        --------
        numpy.ndarray.nbytes
        """
        return self._codes.nbytes + self.dtype.categories.memory_usage(
            deep=deep)
Query: python similarity between two word list counter

Relevant code:
def basic_word_sim(word1, word2):
    """
    Simple measure of similarity: Number of letters in common / max length
    """
    return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))

Similar but not relevant code:
def jaccard(c_1, c_2):
    """
    Calculates the Jaccard similarity between two sets of nodes. Called by mroc.

    Inputs:  - c_1: Community (set of nodes) 1.
             - c_2: Community (set of nodes) 2.

    Outputs: - jaccard_similarity: The Jaccard similarity of these two communities.
    """
    nom = np.intersect1d(c_1, c_2).size
    denom = np.union1d(c_1, c_2).size
    return nom/denom
Query: how to sort a list by last name in python

Relevant code:
def sort_by_name(self):
        """Sort list elements by name."""
        super(JSSObjectList, self).sort(key=lambda k: k.name)

Similar but not relevant code:
def natural_sort(list_to_sort: Iterable[str]) -> List[str]:
    """
    Sorts a list of strings case insensitively as well as numerically.

    For example: ['a1', 'A2', 'a3', 'A11', 'a22']

    To sort a list in place, don't call this method, which makes a copy. Instead, do this:

    my_list.sort(key=natural_keys)

    :param list_to_sort: the list being sorted
    :return: the list sorted naturally
    """
    return sorted(list_to_sort, key=natural_keys)

Similar but not relevant code:
def sort_fn_list(fn_list):
    """Sort input filename list by datetime
    """
    dt_list = get_dt_list(fn_list)
    fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]
    return fn_list_sort

Similar but not relevant code:
def _rows_sort(self, rows):
        """
        Returns a list of rows sorted by start and end date.

        :param list[dict[str,T]] rows: The list of rows.

        :rtype: list[dict[str,T]]
        """
        return sorted(rows, key=lambda row: (row[self._key_start_date], row[self._key_end_date]))

Similar but not relevant code:
def sort_key(val):
    """Sort key for sorting keys in grevlex order."""
    return numpy.sum((max(val)+1)**numpy.arange(len(val)-1, -1, -1)*val)

Similar but not relevant code:
def order_by(self, *fields):
        """An alternate to ``sort`` which allows you to specify a list
        of fields and use a leading - (minus) to specify DESCENDING."""
        doc = []
        for field in fields:
            if field.startswith('-'):
                doc.append((field.strip('-'), pymongo.DESCENDING))
            else:
                doc.append((field, pymongo.ASCENDING))
        return self.sort(doc)
Query: python sinc interpolate with extrapolate

Relevant code:
def lin_interp(x, rangeX, rangeY):
    """
    Interpolate linearly variable x in rangeX onto rangeY.
    """
    s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])
    y = rangeY[0] * (1 - s) + rangeY[1] * s
    return y

Similar but not relevant code:
def interpolate_logscale_single(start, end, coefficient):
    """ Cosine interpolation """
    return np.exp(np.log(start) + (np.log(end) - np.log(start)) * coefficient)

Similar but not relevant code:
def value(self, progress_indicator):
        """ Interpolate linearly between start and end """
        return interpolate.interpolate_linear_single(self.initial_value, self.final_value, progress_indicator)

Similar but not relevant code:
def interp(x, xp, *args, **kwargs):
    """Wrap interpolate_1d for deprecated interp."""
    return interpolate_1d(x, xp, *args, **kwargs)

Similar but not relevant code:
def interpolate(f1: float, f2: float, factor: float) -> float:
    """ Linearly interpolate between two float values. """
    return f1 + (f2 - f1) * factor

Similar but not relevant code:
def open01(x, limit=1.e-6):
    """Constrain numbers to (0,1) interval"""
    try:
        return np.array([min(max(y, limit), 1. - limit) for y in x])
    except TypeError:
        return min(max(x, limit), 1. - limit)
Query: python split array into chunks by two variables

Relevant code:
def consecutive(data, stepsize=1):
    """Converts array into chunks with consecutive elements of given step size.
    http://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy
    """
    return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)

Similar but not relevant code:
def group(data, num):
    """ Split data into chunks of num chars each """
    return [data[i:i+num] for i in range(0, len(data), num)]

Similar but not relevant code:
def schunk(string, size):
    """Splits string into n sized chunks."""
    return [string[i:i+size] for i in range(0, len(string), size)]
Query: python split string based on comma into list and remove new line

Relevant code:
def split_multiline(value):
    """Split a multiline string into a list, excluding blank lines."""
    return [element for element in (line.strip() for line in value.split('\n'))
            if element]

Similar but not relevant code:
def split_strings_in_list_retain_spaces(orig_list):
    """
    Function to split every line in a list, and retain spaces for a rejoin
    :param orig_list: Original list
    :return:
        A List with split lines

    """
    temp_list = list()
    for line in orig_list:
        line_split = __re.split(r'(\s+)', line)
        temp_list.append(line_split)

    return temp_list
Query: how to traverse all elements of a 1d numpy array in python

Relevant code:
def length(self):
        """Array of vector lengths"""
        return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)

Similar but not relevant code:
def array(self):
        """
        The underlying array of shape (N, L, I)
        """
        return numpy.array([self[sid].array for sid in sorted(self)])

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 index(m, val):
    """
    Return the indices of all the ``val`` in ``m``
    """
    mm = np.array(m)
    idx_tuple = np.where(mm == val)
    idx = idx_tuple[0].tolist()

    return idx

Similar but not relevant code:
def A(*a):
    """convert iterable object into numpy array"""
    return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]
Query: python sqlalchemy how to insert multiple records

Relevant code:
def insert_many(self, items):
    """
    Insert many items at once into a temporary table.

    """
    return SessionContext.session.execute(
        self.insert(values=[
            to_dict(item, self.c)
            for item in items
        ]),
    ).rowcount

Similar but not relevant code:
def bulk_query(self, query, *multiparams):
        """Bulk insert or update."""

        with self.get_connection() as conn:
            conn.bulk_query(query, *multiparams)

Similar but not relevant code:
def update(table, values, where=(), **kwargs):
    """Convenience wrapper for database UPDATE."""
    where = dict(where, **kwargs).items()
    sql, args = makeSQL("UPDATE", table, values=values, where=where)
    return execute(sql, args).rowcount

Similar but not relevant code:
def createdb():
    """Create database tables from sqlalchemy models"""
    manager.db.engine.echo = True
    manager.db.create_all()
    set_alembic_revision()

Similar but not relevant code:
def emit_db_sequence_updates(engine):
    """Set database sequence objects to match the source db

       Relevant only when generated from SQLAlchemy connection.
       Needed to avoid subsequent unique key violations after DB build."""

    if engine and engine.name == 'postgresql':
        # not implemented for other RDBMS; necessity unknown
        conn = engine.connect()
        qry = """SELECT 'SELECT last_value FROM ' || n.nspname ||
                         '.' || c.relname || ';' AS qry,
                        n.nspname || '.' || c.relname AS qual_name
                 FROM   pg_namespace n
                 JOIN   pg_class c ON (n.oid = c.relnamespace)
                 WHERE  c.relkind = 'S'"""
        for (qry, qual_name) in list(conn.execute(qry)):
            (lastval, ) = conn.execute(qry).first()
            nextval = int(lastval) + 1
            yield "ALTER SEQUENCE %s RESTART WITH %s;" % (qual_name, nextval)

Similar but not relevant code:
def compile(expr, params=None):
    """
    Force compilation of expression for the SQLite target
    """
    from ibis.sql.alchemy import to_sqlalchemy

    return to_sqlalchemy(expr, dialect.make_context(params=params))
Query: how to use conda env in python code

Relevant code:
def create_conda_env(sandbox_dir, env_name, dependencies, options=()):
    """
    Create a conda environment inside the current sandbox for the given list of dependencies and options.

    Parameters
    ----------
    sandbox_dir : str
    env_name : str
    dependencies : list
        List of conda specs
    options
        List of additional options to pass to conda.  Things like ["-c", "conda-forge"]

    Returns
    -------
    (env_dir, env_name)
    """

    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

Similar but not relevant code:
def docker_environment(env):
    """
    Transform dictionary of environment variables into Docker -e parameters.

    >>> result = docker_environment({'param1': 'val1', 'param2': 'val2'})
    >>> result in ['-e "param1=val1" -e "param2=val2"', '-e "param2=val2" -e "param1=val1"']
    True
    """
    return ' '.join(
        ["-e \"%s=%s\"" % (key, value.replace("$", "\\$").replace("\"", "\\\"").replace("`", "\\`"))
         for key, value in env.items()])

Similar but not relevant code:
def venv():
    """Install venv + deps."""
    try:
        import virtualenv  # NOQA
    except ImportError:
        sh("%s -m pip install virtualenv" % PYTHON)
    if not os.path.isdir("venv"):
        sh("%s -m virtualenv venv" % PYTHON)
    sh("venv\\Scripts\\pip install -r %s" % (REQUIREMENTS_TXT))

Similar but not relevant code:
def activate():
    """
    Usage:
      containment activate
    """
    # This is derived from the clone
    cli = CommandLineInterface()
    cli.ensure_config()
    cli.write_dockerfile()
    cli.build()
    cli.run()
Query: python stack a list of figurea

Relevant code:
def strip_figures(figure):
	"""
	Strips a figure into multiple figures with a trace on each of them

	Parameters:
	-----------
		figure : Figure
			Plotly Figure
	"""
	fig=[]
	for trace in figure['data']:
		fig.append(dict(data=[trace],layout=figure['layout']))
	return fig

Similar but not relevant code:
def stackplot(marray, seconds=None, start_time=None, ylabels=None):
    """
    will plot a stack of traces one above the other assuming
    marray.shape = numRows, numSamples
    """
    tarray = np.transpose(marray)
    stackplot_t(tarray, seconds=seconds, start_time=start_time, ylabels=ylabels)
    plt.show()

Similar but not relevant code:
def computeDelaunayTriangulation(points):
    """ 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.
    """
    siteList = SiteList(points)
    context  = Context()
    context.triangulate = True
    voronoi(siteList,context)
    return context.triangles

Similar but not relevant code:
def activate_subplot(numPlot):
    """Make subplot *numPlot* active on the canvas.

    Use this if a simple ``subplot(numRows, numCols, numPlot)``
    overwrites the subplot instead of activating it.
    """
    # see http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg07156.html
    from pylab import gcf, axes
    numPlot -= 1  # index is 0-based, plots are 1-based
    return axes(gcf().get_axes()[numPlot])

Similar but not relevant code:
def new_figure_manager_given_figure(num, figure):
    """
    Create a new figure manager instance for the given figure.
    """
    fig = figure
    frame = FigureFrameWx(num, fig)
    figmgr = frame.get_figure_manager()
    if matplotlib.is_interactive():
        figmgr.frame.Show()

    return figmgr

Similar but not relevant code:
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)))
Query: python standard deviation not accept float number

Relevant code:
def weighted_std(values, weights):
    """ Calculate standard deviation weighted by errors """
    average = np.average(values, weights=weights)
    variance = np.average((values-average)**2, weights=weights)
    return np.sqrt(variance)

Similar but not relevant code:
def standard_deviation(numbers):
    """Return standard deviation."""
    numbers = list(numbers)
    if not numbers:
        return 0
    mean = sum(numbers) / len(numbers)
    return (sum((n - mean) ** 2 for n in numbers) /
            len(numbers)) ** .5

Similar but not relevant code:
def _std(self,x):
        """
        Compute standard deviation with ddof degrees of freedom
        """
        return np.nanstd(x.values,ddof=self._ddof)

Similar but not relevant code:
def circstd(dts, axis=2):
    """Circular standard deviation"""
    R = np.abs(np.exp(1.0j * dts).mean(axis=axis))
    return np.sqrt(-2.0 * np.log(R))

Similar but not relevant code:
def gaussian_distribution(mean, stdev, num_pts=50):
    """ get an x and y numpy.ndarray that spans the +/- 4
    standard deviation range of a gaussian distribution with
    a given mean and standard deviation. useful for plotting

    Parameters
    ----------
    mean : float
        the mean of the distribution
    stdev : float
        the standard deviation of the distribution
    num_pts : int
        the number of points in the returned ndarrays.
        Default is 50

    Returns
    -------
    x : numpy.ndarray
        the x-values of the distribution
    y : numpy.ndarray
        the y-values of the distribution

    """
    xstart = mean - (4.0 * stdev)
    xend = mean + (4.0 * stdev)
    x = np.linspace(xstart,xend,num_pts)
    y = (1.0/np.sqrt(2.0*np.pi*stdev*stdev)) * np.exp(-1.0 * ((x - mean)**2)/(2.0*stdev*stdev))
    return x,y
Query: how to use python 3 interactive mode

Relevant code:
def isInteractive():
    """
    A basic check of if the program is running in interactive mode
    """
    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

Similar but not relevant code:
def determine_interactive(self):
		"""Determine whether we're in an interactive shell.
		Sets interactivity off if appropriate.
		cf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process
		"""
		try:
			if not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):
				self.interactive = 0
				return False
		except Exception:
			self.interactive = 0
			return False
		if self.interactive == 0:
			return False
		return True

Similar but not relevant code:
def is_interactive(self):
        """ Determine if the user requested interactive mode.
        """
        # The Python interpreter sets sys.flags correctly, so use them!
        if sys.flags.interactive:
            return True

        # IPython does not set sys.flags when -i is specified, so first
        # check it if it is already imported.
        if '__IPYTHON__' not in dir(six.moves.builtins):
            return False

        # Then we check the application singleton and determine based on
        # a variable it sets.
        try:
            from IPython.config.application import Application as App
            return App.initialized() and App.instance().interact
        except (ImportError, AttributeError):
            return False

Similar but not relevant code:
def page_guiref(arg_s=None):
    """Show a basic reference about the GUI Console."""
    from IPython.core import page
    page.page(gui_reference, auto_html=True)

Similar but not relevant code:
def demo(quiet, shell, speed, prompt, commentecho):
    """Run a demo doitlive session."""
    run(
        DEMO,
        shell=shell,
        speed=speed,
        test_mode=TESTING,
        prompt_template=prompt,
        quiet=quiet,
        commentecho=commentecho,
    )