id stringlengths 23 36 | title stringclasses 1
value | text stringlengths 75 104k |
|---|---|---|
leetcode/csn_python_train_152036.txt | def get(tgt,
fun,
tgt_type='glob',
exclude_minion=False):
'''
Get data from the mine based on the target, function and tgt_type
Targets can be matched based on any standard matching system that can be
matched on the master via these keywords:
- glob
- pcre
- grain
... | |
leetcode/csn_python_train_76246.txt | def complex_data(self):
'''
This will cast each byte to an int8 and interpret each byte
as 4 bits real values and 4 bits imag values (RRRRIIII). The data are then
used to create a 3D numpy array of dtype=complex, which is returned.
The shape of the numpy array is N half frames, M subbands, K data ... | |
leetcode/csn_python_train_56414.txt | def xprint(m, *args):
"""Print string to stdout.
Format unicode safely.
"""
if sys.hexversion < 0x3000000:
m = m.decode('utf8')
if args:
m = m % args
if sys.hexversion < 0x3000000:
m = m.encode('utf8')
sys.stdout.write(m)
sys.stdout.write('\n') | |
leetcode/csn_python_train_187450.txt | def update(
self,
filename=None,
batch_id=None,
prev_batch_id=None,
producer=None,
count=None,
):
"""Creates an history model instance.
"""
# TODO: refactor model enforce unique batch_id
# TODO: refactor model to not allow NULLs
... | |
leetcode/csn_python_train_279249.txt | def exception(self, timeout=None):
"""Return a exception raised by the call that the future
represents.
:param timeout: The number of seconds to wait for the exception
if the future has not been completed. None, the default,
sets no limit.
:returns: The exception ... | |
leetcode/csn_python_train_242187.txt | def time_segments_average(X, interval, value_column, time_column):
"""
function that aggregates data in a pandas dataframe by averaging over a given interval.
it starts averaging from the smallest timestamp in the dataframe and ends at the
largest timestamp. assumes the input is time... | |
leetcode/csn_python_train_5181.txt | def build_to_target_size(cls,
target_size,
token_counts,
min_val,
max_val,
max_subtoken_length=None,
reserved_tokens=None,
num_iter... | |
leetcode/csn_python_train_139218.txt | def economic_svd(G, epsilon=sqrt(finfo(float).eps)):
r"""Economic Singular Value Decomposition.
Args:
G (array_like): Matrix to be factorized.
epsilon (float): Threshold on the square root of the eigen values.
Default is ``sqrt(finfo(float).eps)``.
Returns:
... | |
leetcode/csn_python_train_243239.txt | def default(self):
"""Returns the static value that this defaults to."""
if self.MUTABLE:
return copy.deepcopy(self._default)
else:
return self._default | |
leetcode/csn_python_train_323590.txt | def xstep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`.
"""
YU = self.Y - self.U
self.X = np.asarray(sl.cho_solve_ATAI(
self.D, 1.0, self.block_sep0(YU) +
self.D.T.dot(self.block_sep1(YU)), self.lu, self.piv),
dt... | |
leetcode/csn_python_train_113583.txt | def _GenerateSshKey(self, key_type, key_dest):
"""Generate a new SSH key.
Args:
key_type: string, the type of the SSH key.
key_dest: string, a file location to store the SSH key.
"""
# Create a temporary file to save the created RSA keys.
with tempfile.NamedTemporaryFile(prefix=key_type... | |
leetcode/csn_python_train_406208.txt | def warn(message, category=None, stacklevel=1, emitstacklevel=1):
"""Issue a warning, or maybe ignore it or raise an exception.
Duplicate of the standard library warn function except it takes the
following argument:
`emitstacklevel` : default to 1, number of stackframe to consider when
matching th... | |
leetcode/csn_python_train_12403.txt | def read_until(self, delimiter: bytes, max_bytes: int = None) -> Awaitable[bytes]:
"""Asynchronously read until we have found the given delimiter.
The result includes all the data read including the delimiter.
If ``max_bytes`` is not None, the connection will be closed
if more than ``m... | |
leetcode/csn_python_train_295550.txt | def match_best_pdb_chains(pdb1, pdb1_name, pdb2, pdb2_name, cut_off = 60.0, use_seqres_sequences_if_possible = True):
'''A wrapper function for match_pdb_chains. This function only takes the best match. The return
value is a dict mapping
chain_id_in_pdb1 -> None or a tuple (chain_id_in_pdb_2, pe... | |
leetcode/csn_python_train_144775.txt | def regex_group(ctx, text, pattern, group_num):
"""
Tries to match the text with the given pattern and returns the value of matching group
"""
text = conversions.to_string(text, ctx)
pattern = conversions.to_string(pattern, ctx)
group_num = conversions.to_integer(group_num, ctx)
expression ... | |
leetcode/csn_python_train_60369.txt | def sync_dir(self):
""" Report on which direction a synchronization should be done.
:return:
"""
# NOTE: These are ordered so the FILE_TO_RECORD has preference over RECORD_TO_FILE
# if there is a conflict.
if self.exists() and bool(self.size()) and not self.record.size:... | |
leetcode/csn_python_train_397079.txt | def get(self, slug):
"""Get KnwKB.
Url parameters:
- from: filter "mappings from"
- to: filter "mappings to"
- page
- per_page
- match_type: s=substring, e=exact, sw=startswith
- sortby: 'from' or 'to'
"""
kb = api.... | |
leetcode/csn_python_train_308575.txt | def prepare(args):
"""
%prog prepare --rearray_lib=<rearraylibrary> --orig_lib_file=<origlibfile>
Inferred file names
---------------------------------------------
`lookuptblfile` : rearraylibrary.lookup
`rearraylibfile`: rearraylibrary.fasta
Pick sequences from the original library file a... | |
leetcode/csn_python_train_280822.txt | def get_servo_status(self):
""" Get the error status of servo
This function gets the error status (if any) of the servo
Args:
none
Returns:
int: an integer corresponding to the servo status
* refer datasheet
"""
data = []
... | |
leetcode/csn_python_train_86332.txt | def update(self, iterable):
"""Update with an ordered iterable of items.
Args:
iterable: An ordered iterable of items. The relative
order of the items in this iterable will be respected
in the TopoSet (in the absence of cycles).
"""
for pair in ... | |
leetcode/csn_python_train_283670.txt | def removeEverything(toBeRemoved, l):
'''Remove every instance that matches the input from a list
Match with ==, operation, which can be defined in __eq__.
Args:
tobeRemoved (object): the same object you want to remove from the list.
l (list): the llist you want to remove stuff from.
'... | |
leetcode/csn_python_train_42438.txt | def query(self, query):
'''Returns a sequence of objects matching criteria expressed in `query`'''
query = query.copy()
query.key = self._transform(query.key)
return self.child_datastore.query(query) | |
leetcode/csn_python_train_89018.txt | def coerce_many(schema=str):
"""Expect the input to be a sequence of items which conform to `schema`."""
def validate(val):
"""Apply schema check/version to each item."""
return [volup.Coerce(schema)(x) for x in val]
return validate | |
leetcode/csn_python_train_180643.txt | def read(self, max_bytes=1):
"""Read at most `max_bytes` from internal buffer.
Parameters
-----------
max_bytes: int
Maximum number of bytes to read.
Returns
--------
bytes
Bytes extracted from internal buffer. Length may be less
... | |
leetcode/csn_python_train_286308.txt | def parse_link(self, node):
"""
Parses <Link>
@param node: Node containing the <Link> element
@type node: xml.etree.Element
"""
if 'name' in node.lattrib:
name = node.lattrib['name']
else:
self.raise_error('<Link> must specify a name')
... | |
leetcode/csn_python_train_24759.txt | def vm_monitoring(name, call=None):
'''
Returns the monitoring records for a given virtual machine. A VM name must be
supplied.
The monitoring information returned is a list of VM elements. Each VM element
contains the complete dictionary of the VM with the updated information returned
by the p... | |
leetcode/csn_python_train_139843.txt | def get_header(uri):
"""
Pull a FITS header from observation at the given URI
@param uri: The URI of the image in VOSpace.
"""
if uri not in astheaders:
astheaders[uri] = get_hdu(uri, cutout="[1:1,1:1]")[0].header
return astheaders[uri] | |
leetcode/csn_python_train_411270.txt | def cli(ctx, resource):
"""
Displays all locally cached <resource> versions available for installation.
\b
Available resources:
ips (default)
dev_tools
"""
log = logging.getLogger('ipsv.setup')
assert isinstance(ctx, Context)
resource = str(resource).lower()
if res... | |
leetcode/csn_python_train_130896.txt | def validate_average_best_span():
"""Figure 2d? from Friedman."""
N = 200
num_trials = 400
avg = numpy.zeros(N)
for i in range(num_trials):
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82(N=N)
my_smoother = smoother.perform_smooth(
x, y, smoother_cls=s... | |
leetcode/csn_python_train_329580.txt | def compute_hazard_maps(curves, imls, poes):
"""
Given a set of hazard curve poes, interpolate a hazard map at the specified
``poe``.
:param curves:
2D array of floats. Each row represents a curve, where the values
in the row are the PoEs (Probabilities of Exceedance) corresponding to
... | |
leetcode/csn_python_train_211585.txt | def plot_sfs_scaled(*args, **kwargs):
"""Plot a scaled site frequency spectrum.
Parameters
----------
s : array_like, int, shape (n_chromosomes,)
Site frequency spectrum.
yscale : string, optional
Y axis scale.
bins : int or array_like, int, optional
Allele count bins.
... | |
leetcode/csn_python_train_73545.txt | def fprob(dfnum, dfden, F):
"""
Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn
"""
p = betai(0.5 * dfden,... | |
leetcode/csn_python_train_230721.txt | def scanf(format, s=None, collapseWhitespace=True):
"""
scanf supports the following formats:
%c One character
%5c 5 characters
%d, %i int value
%7d, %7i int value with length 7
%f float value
%o octal value
%X, %x hex value
%s ... | |
leetcode/csn_python_train_292767.txt | def get_pty(self, term='vt100', width=80, height=24, width_pixels=0,
height_pixels=0):
"""
Request a pseudo-terminal from the server. This is usually used right
after creating a client channel, to ask the server to provide some
basic terminal semantics for a shell invoke... | |
leetcode/csn_python_train_365397.txt | def getRejectionReasonsItems(self):
"""Return the list of predefined rejection reasons
"""
reasons = self.getRejectionReasons()
if not reasons:
return []
reasons = reasons[0]
keys = filter(lambda key: key != "checkbox", reasons.keys())
return map(lambd... | |
leetcode/csn_python_train_113624.txt | def _RunIpRoute(self, args=None, options=None):
"""Run a command with ip route and return the response.
Args:
args: list, the string ip route command args to execute.
options: dict, the string parameters to append to the ip route command.
Returns:
string, the standard output from the ip ... | |
leetcode/csn_python_train_38149.txt | def ProgramScanner(**kw):
"""Return a prototype Scanner instance for scanning executable
files for static-lib dependencies"""
kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH')
ps = SCons.Scanner.Base(scan, "ProgramScanner", **kw)
return ps | |
leetcode/csn_python_train_408267.txt | def combined_analysis(using):
"""
Combine the analysis in ES with the analysis defined in Python. The one in
Python takes precedence
"""
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
if es_analysis == DOES_NOT_EXIST:
return python_analysis
# we... | |
leetcode/csn_python_train_60146.txt | def update_w(self):
"""Update the attributes of self.widget based on self.flagged.
"""
if self.flagged:
self._w.attr = 'flagged'
self._w.focus_attr = 'flagged focus'
else:
self._w.attr = 'body'
self._w.focus_attr = 'focus' | |
leetcode/csn_python_train_202379.txt | def _has_expired(self):
""" Has this HIT expired yet? """
expired = False
if hasattr(self, 'Expiration'):
now = datetime.datetime.utcnow()
expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ')
expired = (now >= expiration)
else... | |
leetcode/csn_python_train_60978.txt | def ensure_dir_exists(path):
"""Given a file, ensure that the path to the file exists"""
import os
f_dir = os.path.dirname(path)
if not os.path.exists(f_dir):
os.makedirs(f_dir)
return f_dir | |
leetcode/csn_python_train_55210.txt | def get_user_by_email(server_context, email):
"""
Get the user with the provided email. Throws a ValueError if not found.
:param server_context: A LabKey server context. See utils.create_server_context.
:param email:
:return:
"""
url = server_context.build_url(user_controller, 'getUsers.api'... | |
leetcode/csn_python_train_112256.txt | def unpack_log_data(self, log_data, timestamp):
"""Unpack received logging data so it represent real values according
to the configuration in the entry"""
ret_data = {}
data_index = 0
for var in self.variables:
size = LogTocElement.get_size_from_id(var.fetch_as)
... | |
leetcode/csn_python_train_286901.txt | def itake_column(list_, colx):
""" iterator version of get_list_column """
if isinstance(colx, list):
# multi select
return ([row[colx_] for colx_ in colx] for row in list_)
else:
return (row[colx] for row in list_) | |
leetcode/csn_python_train_388977.txt | def _check_model(obj, models=None):
"""Checks object if it's a peewee model and unique."""
return isinstance(obj, type) and issubclass(obj, pw.Model) and hasattr(obj, '_meta') | |
leetcode/csn_python_train_410319.txt | def compute_hash(attributes, ignored_attributes=None):
"""
Computes a hash code for the given dictionary that is safe for persistence round trips
"""
ignored_attributes = list(ignored_attributes) if ignored_attributes else []
tuple_attributes = _convert(attributes.copy(), ignored_attributes)
ha... | |
leetcode/csn_python_train_182230.txt | def ncbi_geneid(self):
"""
Retrieve this feature's NCBI GeneID if it's present.
NCBI GFF3 files contain gene IDs encoded in **Dbxref** attributes
(example: `Dbxref=GeneID:103504972`). This function locates and returns
the GeneID if present, or returns `None` otherwise.
"... | |
leetcode/csn_python_train_358587.txt | def _get_resource_view(self, resource_view):
# type: (Union[ResourceView,Dict]) -> ResourceView
"""Get resource view id
Args:
resource_view (Union[ResourceView,Dict]): ResourceView metadata from a ResourceView object or dictionary
Returns:
ResourceView: Resource... | |
leetcode/csn_python_train_100932.txt | def check_vmware_version(self):
"""
Check VMware version
"""
if sys.platform.startswith("win"):
# look for vmrun.exe using the directory listed in the registry
ws_version = self._find_vmware_version_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation"... | |
leetcode/csn_python_train_320735.txt | def _log_response(response):
"""Log out information about a ``Request`` object.
After calling ``requests.request`` or one of its convenience methods, the
object returned can be passed to this method. If done, information about
the object returned is logged.
:return: Nothing is returned.
"""
... | |
leetcode/csn_python_train_60700.txt | def config(path=None, root=None, db=None):
"""Return the default run_config object for this installation."""
import ambry.run
return ambry.run.load(path=path, root=root, db=db) | |
leetcode/csn_python_train_215821.txt | def used_labels(self):
""" Returns a list of required labels for this instruction
"""
result = []
tmp = self.asm.strip(' \n\r\t')
if not len(tmp) or tmp[0] in ('#', ';'):
return result
try:
tmpLexer = asmlex.lex.lex(object=asmlex.Lexer(), lextab=... | |
leetcode/csn_python_train_200264.txt | def hildatree2dgparentedtree(self):
"""Convert the tree from HILDA's format into a conventional binary tree,
which can be easily converted into output formats like RS3.
"""
def transform(hilda_tree):
"""Transform a HILDA parse tree into a more conventional parse tree.
... | |
leetcode/csn_python_train_266738.txt | def reset(self):
"""Resets the environment, and returns the state.
If it is a single agent environment, it returns that state for that agent. Otherwise, it returns a dict from
agent name to state.
Returns:
tuple or dict: For single agent environment, returns the same as `ste... | |
leetcode/csn_python_train_330366.txt | def connect(tenant=None, user=None, password=None, token=None, is_public=False):
"""
Authenticates user and returns new platform to user.
This is an entry point to start working with Qubell Api.
:rtype: QubellPlatform
:param str tenant: url to tenant, default taken from 'QUBELL_T... | |
leetcode/csn_python_train_255297.txt | def best_fit_plane(self):
"""Fits a plane to the point cloud using least squares.
Returns
-------
:obj:`tuple` of :obj:`numpy.ndarray` of float
A normal vector to and point in the fitted plane.
"""
X = np.c_[self.x_coords, self.y_coords, np.ones(self.num_poin... | |
leetcode/csn_python_train_149113.txt | def list_to_dict(lst, key=None, remove_key=True):
""" convert a list of dicts to a dict with root keys
Parameters
----------
lst : list[dict]
key : str or None
a key contained by all of the dicts
if None use index number string
remove_key : bool
remove key from dicts in ... | |
leetcode/csn_python_train_365286.txt | def get_service_categories(self, restricted=True):
"""Return all service categories in the right order
:param restricted: Client settings restrict categories
:type restricted: bool
:returns: Category catalog results
:rtype: brains
"""
bsc = api.get_tool("bika_set... | |
leetcode/csn_python_train_104414.txt | def _traverse_parent_objs(self, p2cs, goobj_child, goids_seen):
"""Traverse from source GO up parents."""
# Update public(go2obj p2cs), private(goids_seen)
child_id = goobj_child.id
# mark child as seen
goids_seen.add(child_id)
##A self.go2obj[child_id] = goobj_child
... | |
leetcode/csn_python_train_218451.txt | def _delete(self, *args, **kwargs):
'''
delete the post.
'''
_ = kwargs
uid = args[0]
current_infor = MPost.get_by_uid(uid)
if MPost.delete(uid):
tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid'])
MCategory.update_count(c... | |
leetcode/csn_python_train_127198.txt | def block_user_signals(self, name, ignore_error=False):
"""
Temporarily disconnects the user-defined signals for the specified
parameter name.
Note this only affects those connections made with
connect_signal_changed(), and I do not recommend adding new connections
... | |
leetcode/csn_python_train_36862.txt | def demo_paths(self):
"""returns collected demo paths excluding examples
TODO: call super which returns custom paths in descriptor
"""
base_path = os.path.join(self.module.__path__[0], 'demo')
paths = []
if os.path.isdir(base_path):
for item in os.listdir(base... | |
leetcode/csn_python_train_224231.txt | def get_ctype(rtype, cfunc, *args):
""" Call a C function that takes a pointer as its last argument and
return the C object that it contains after the function has finished.
:param rtype: C data type is filled by the function
:param cfunc: C function to call
:param args: Arguments to cal... | |
leetcode/csn_python_train_301221.txt | def async_stmt_check(self, original, loc, tokens):
"""Check for Python 3.5 async for/with."""
return self.check_py("35", "async for/with", original, loc, tokens) | |
leetcode/csn_python_train_18426.txt | def generate(self, references, buffers):
''' Create a JSON representation of this event suitable for sending
to clients.
Args:
references (dict[str, Model]) :
If the event requires references to certain models in order to
function, they may be collect... | |
leetcode/csn_python_train_192938.txt | def container_cdn_command(self, url, container, container_object,
cdn_headers):
"""Command your CDN enabled Container.
:param url:
:param container:
"""
headers, container_uri = self._return_base_data(
url=url,
container=con... | |
leetcode/csn_python_train_216867.txt | def positive_small_integer(anon, obj, field, val):
"""
Returns a positive small random integer (for a Django PositiveSmallIntegerField)
"""
return anon.faker.positive_small_integer(field=field) | |
leetcode/csn_python_train_26920.txt | def get_jids():
'''
Return a list of all job ids
'''
log.debug('sdstack_etcd returner <get_jids> called')
ret = []
client, path = _get_conn(__opts__)
items = client.get('/'.join((path, 'jobs')))
for item in items.children:
if item.dir is True:
jid = str(item.key).spli... | |
leetcode/csn_python_train_139960.txt | def write_source(self, source):
"""
Writes out data for a single source.
"""
if not self._header_written:
observations = [reading.get_observation() for reading in source.get_readings()]
self.write_headers(observations, self.sys_header)
self._write_source(... | |
leetcode/csn_python_train_351623.txt | def reset(self):
""" Add a RESET message to the outgoing queue, send
it and consume all remaining messages.
"""
def fail(metadata):
raise ProtocolError("RESET failed %r" % metadata)
log_debug("[#%04X] C: RESET", self.local_port)
self._append(b"\x0F", respon... | |
leetcode/csn_python_train_138155.txt | def _replace_mvs(row, mv):
"""
Replace Missing Values in the data rows where applicable
:param list row: Row
:return list: Modified row
"""
for idx, v in enumerate(row):
try:
if v.value.lower() in EMPTY or v.value.lower() == mv:
row[idx] = "nan"
el... | |
leetcode/csn_python_train_253172.txt | def Beggs_Brill(m, x, rhol, rhog, mul, mug, sigma, P, D, angle, roughness=0.0,
L=1.0, g=g, acceleration=True):
r'''Calculates the two-phase pressure drop according to the Beggs-Brill
correlation ([1]_, [2]_, [3]_).
Parameters
----------
m : float
Mass flow rate of fluid, [kg... | |
leetcode/csn_python_train_357638.txt | def register(*args, **kwargs):
"""
Creates a registrator that, being called with a function as the only
argument, wraps a function with ``pyws.functions.NativeFunctionAdapter``
and registers it to the server. Arguments are exactly the same as for
``pyws.functions.NativeFunctionAdapter`` except that ... | |
leetcode/csn_python_train_9531.txt | def load_pyproject_toml(self):
# type: () -> None
"""Load the pyproject.toml file.
After calling this routine, all of the attributes related to PEP 517
processing for this requirement have been set. In particular, the
use_pep517 attribute can be used to determine whether we shou... | |
leetcode/csn_python_train_153588.txt | def _is_catch_phrase_valid(self, catch_phrase):
"""
Validates a french catch phrase.
:param catch_phrase: The catch phrase to validate.
"""
for word in self.words_which_should_not_appear_twice:
# Fastest way to check if a piece of word does not appear twice.
... | |
leetcode/csn_python_train_56512.txt | def magic_timeit(setup, stmt, ncalls=None, repeat=3, force_ms=False):
"""Time execution of a Python statement or expression
Usage:\\
%timeit [-n<N> -r<R> [-t|-c]] statement
Time execution of a Python statement or expression using the timeit
module.
Options:
-n<N>: execute the given stateme... | |
leetcode/csn_python_train_367876.txt | def find_additional_properties(instance, schema):
"""
Return the set of additional properties for the given ``instance``.
Weeds out properties that should have been validated by ``properties`` and
/ or ``patternProperties``.
Assumes ``instance`` is dict-like already.
"""
properties = sch... | |
leetcode/csn_python_train_14697.txt | def _update_message_request(self, message):
"""Add row keys and row range to given request message
:type message: class:`data_messages_v2_pb2.ReadRowsRequest`
:param message: The ``ReadRowsRequest`` protobuf
"""
for each in self.row_keys:
message.rows.row_keys.append... | |
leetcode/csn_python_train_376753.txt | def _connectS3(self):
"""
:rtype: S3Connection
"""
s3 = boto.s3.connect_to_region(self.region)
if s3 is None:
raise ValueError("Could not connect to S3. Make sure '%s' is a valid S3 region." %
self.region)
return s3 | |
leetcode/csn_python_train_199544.txt | def censor_background(sample_frame, ntc_samples=['NTC'], margin=log2(10)):
"""Selects rows from the sample data frame that fall `margin` or greater
cycles earlier than the NTC for that target. NTC wells are recognized by
string matching against the Sample column.
:param DataFrame sample_frame: A sample... | |
leetcode/csn_python_train_294987.txt | def sequences_from_fasta(path):
"""
Extract multiple sequences from a FASTA file.
"""
from Bio import SeqIO
return {x.description: x.seq for x in SeqIO.parse(path, 'fasta')} | |
leetcode/csn_python_train_192442.txt | def override_language(self, language):
"""
Context manager to override the instance language.
"""
previous_language = self._linguist.language
self._linguist.language = language
yield
self._linguist.language = previous_language | |
leetcode/csn_python_train_322625.txt | def get_environment(self, fUnicode = None):
"""
Retrieves the environment with wich the program is running.
@note: Duplicated keys are joined using null characters.
To avoid this behavior, call L{get_environment_variables} instead
and convert the results to a dictionary ... | |
leetcode/csn_python_train_112804.txt | def parse_encrypted_response(self, response):
"""
Takes in the encrypted response from the server and decrypts it
:param response: The response that needs to be decrytped
:return: The unencrypted message from the server
"""
content_type = response.headers['Content-Type']... | |
leetcode/csn_python_train_49667.txt | async def set_http_proxy(cls, url: typing.Optional[str]):
"""See `get_http_proxy`."""
await cls.set_config("http_proxy", "" if url is None else url) | |
leetcode/csn_python_train_105924.txt | def selected(self, new):
"""Set selected from list or instance of object or name.
Over-writes existing selection
"""
def preprocess(item):
if isinstance(item, str):
return self.options[item]
return item
items = coerce_to_list(new, preproce... | |
leetcode/csn_python_train_92721.txt | def availability_zone_list(request):
"""Utility method to retrieve a list of availability zones."""
try:
return api.nova.availability_zone_list(request)
except Exception:
exceptions.handle(request,
_('Unable to retrieve Nova availability zones.'))
return [] | |
leetcode/csn_python_train_185451.txt | def bethe_lattice(energy, hopping):
"""Bethe lattice in inf dim density of states"""
energy = np.asarray(energy).clip(-2*hopping, 2*hopping)
return np.sqrt(4*hopping**2 - energy**2) / (2*np.pi*hopping**2) | |
leetcode/csn_python_train_354810.txt | def send_notification(self, title, message, typ=1, url=None, sender=None):
"""
sends message to users private mq exchange
Args:
title:
message:
sender:
url:
typ:
"""
self.created_channels.channel.add_message(
... | |
leetcode/csn_python_train_137488.txt | def _raise_for_status(response):
"""Raises stored :class:`HTTPError`, if one occurred.
This is the :meth:`requests.models.Response.raise_for_status` method,
modified to add the response from Space-Track, if given.
"""
http_error_msg = ''
if 400 <= response.status_code < 500:
http_erro... | |
leetcode/csn_python_train_274212.txt | def create_CTL(fname, tbl_name, col_list, TRUNC_OR_APPEND, delim=','):
"""
create_CTL(fname_control_file, tbl_name, src_file, cols, 'TRUNCATE')
"""
with open(fname, 'w') as ct:
ct.write('LOAD DATA\n')
ct.write(TRUNC_OR_APPEND + '\n')
ct.write('into table ' + tbl_name + '\n')
... | |
leetcode/csn_python_train_384341.txt | def boundingbox(self):
"""Compute the bounding box of the compound.
Returns
-------
mb.Box
The bounding box for this Compound
"""
xyz = self.xyz
return Box(mins=xyz.min(axis=0), maxs=xyz.max(axis=0)) | |
leetcode/csn_python_train_74332.txt | def connect(self):
"""Connect to host
"""
try:
self.client.connect(self.host, username=self.username,
password=self.password, port=self.port,
pkey=self.pkey, timeout=self.timeout)
except sock_gaierror, ex:
rais... | |
leetcode/csn_python_train_187974.txt | def resource_to_url(resource, request=None, quote=False):
"""
Converts the given resource to a URL.
:param request: Request object (required for the host name part of the
URL). If this is not given, the current request is used.
:param bool quote: If set, the URL returned will be quoted.
"""
... | |
leetcode/csn_python_train_25370.txt | def get_vm_config(name, datacenter=None, objects=True, service_instance=None):
'''
Queries and converts the virtual machine properties to the available format
from the schema. If the objects attribute is True the config objects will
have extra properties, like 'object' which will include the
vim.vm.... | |
leetcode/csn_python_train_47396.txt | def _mdens_deriv(self,m):
"""Derivative of the density as a function of m"""
return -2.*self.a2**2*(self.a+2.*m)/m**3/(self.a+m)**3 | |
leetcode/csn_python_train_80462.txt | def get_next_activity(self):
"""Gets the next Activity in this list.
return: (osid.learning.Activity) - the next Activity in this
list. The has_next() method should be used to test that
a next Activity is available before calling this method.
raise: IllegalState... | |
leetcode/csn_python_train_44521.txt | def check_retcode(self, line):
"""
Look for retcode on line line and return return code if found.
:param line: Line to search from
:return: integer return code or -1 if "cmd tasklet init" is found. None if retcode or cmd
tasklet init not found.
"""
retcode = None... | |
leetcode/csn_python_train_323066.txt | def verify(self, subject, signature=None):
"""
Verify a subject with a signature using this key.
:param subject: The subject to verify
:type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID`
:param signature: If the signature is de... | |
leetcode/csn_python_train_18878.txt | def get_bgcolor(self, index):
"""Background color depending on value."""
column = index.column()
if not self.bgcolor_enabled:
return
value = self.get_value(index.row(), column)
if self.max_min_col[column] is None or isna(value):
color = QColor(BACKGROUND_N... |
BRIGHT: leetcode
A format conversion of the standard passage-retrieval setting of
BRIGHT: A Realistic and Challenging Benchmark for Reasoning-Intensive Retrieval,
by the original BRIGHT authors. Source: xlangai/BRIGHT,
pinned to 3066d29c9651a576c8aba4832d249807b181ecae. This is a converted mirror, not an independently annotated dataset.
The original dataset is distributed under CC BY 4.0.
See SOURCE_README.md for the original dataset card and attribution.
| Table | Rows | Columns |
|---|---|---|
| corpus | 413,932 | id, title, text |
| queries | 142 | id, text |
| qrels | 262 | query-id, corpus-id, score |
| exclusions (optional) | 33,485 | query-id, corpus-id |
All published configs use the test split. corpus.text is exactly the original
documents.content; title is empty. Query IDs, document IDs and original examples.query
strings are preserved without normalization. qrels is the unique set of gold_ids pairs,
with binary score 1. Duplicate labels are collapsed; no relevance judgments are added.
Gold reasoning, gold answers, gold_ids_long, generated query rewrites and long_documents
are not part of the converted evaluation inputs.
exclusions contains query-id, corpus-id pairs. Remove these documents from each query's ranking before selecting the top results.
The N/A exclusion sentinel is removed. Excluded IDs and positive IDs are validated against
the corpus and must be disjoint for each query. Keep ignore_identical_ids=false: matching
query/document ID strings alone do not imply a BRIGHT exclusion.
Evaluate each BRIGHT subset against its own complete corpus. Report nDCG@10 per subset and the unweighted mean across the 12 subsets. Record encoder context limits and truncation. The original evaluation code defines the protocol.
Converted with scripts/preprocess/dataset/convert_bright.py in the SPARSE project.
conversion.json records source and output SHA-256 hashes, row counts and validation checks.
- Downloads last month
- 49