Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
362,600 | def _tokenize(self, text):
text = self._clean_text(text)
text = self._tokenize_chinese_chars(text)
orig_tokens = self._whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if self.lower:
to... | Tokenizes a piece of text. |
362,601 | def table(self):
if hasattr(self.data, ) and self.data.table_on:
assert_index_sane(self.data.table, len(self.song.tables))
return self.song.tables[self.data.table] | a ```pylsdj.Table``` referencing the instrument's table, or None
if the instrument doesn't have a table |
362,602 | def findPolymorphisms(self, strSeq, strict = False):
arr = self.encode(strSeq)[0]
res = []
if not strict :
for i in range(len(arr)+len(self)) :
if i >= len(arr) or i > len(self) :
break
if arr[i] & self[i] == 0:
res.append(i)
else :
for i in range(len(arr)+len(self)) :
if i >= len... | Compares strSeq with self.sequence.
If not 'strict', this function ignores the cases of matching heterozygocity (ex: for a given position i, strSeq[i] = A and self.sequence[i] = 'A/G'). If 'strict' it returns all positions where strSeq differs self,sequence |
362,603 | def create_stack_template( self,
lambda_arn,
lambda_name,
api_key_required,
iam_authorization,
authorizer,
cors_options=None,
... | Build the entire CF stack.
Just used for the API Gateway, but could be expanded in the future. |
362,604 | def start_app(self, app_id, force_launch=False):
self.logger.info("Starting app %s", app_id)
self.socket_client.receiver_controller.launch_app(app_id, force_launch) | Start an app on the Chromecast. |
362,605 | def get_price(self, **kwargs):
def fmt_p(out):
return pd.DataFrame(out, index=self.symbols)
return self._get_endpoint("price", fmt_p=fmt_p, params=kwargs) | Price
Reference: https://iexcloud.io/docs/api/#price
``1`` per symbol
Returns
-------
float or pandas.DataFrame
Stocks Price endpoint data |
362,606 | def fit(self, X, y, likelihood_args=()):
r
X, y = check_X_y(X, y)
N, _ = X.shape
self.B_ = X.shape[0] / self.batch_size
self.D_ = self.basis.get_dim(X)
likelihood_args = _reshape_likelihood_args(likelihood_args, N)
data = (X, y) + likelihood_ar... | r"""
Learn the parameters of a Bayesian generalized linear model (GLM).
Parameters
----------
X : ndarray
(N, d) array input dataset (N samples, d dimensions).
y : ndarray
(N,) array targets (N samples)
likelihood : Object
A likelihood... |
362,607 | def get_parent_log_ids(self, log_id):
if self._catalog_session is not None:
return self._catalog_session.get_parent_catalog_ids(catalog_id=log_id)
return self._hierarchy_session.get_parents(id_=log_id) | Gets the parent ``Ids`` of the given log.
arg: log_id (osid.id.Id): the ``Id`` of a log
return: (osid.id.IdList) - the parent ``Ids`` of the log
raise: NotFound - ``log_id`` is not found
raise: NullArgument - ``log_id`` is ``null``
raise: OperationFailed - unable to comple... |
362,608 | def from_file(pkg_file):
phys_reader = PhysPkgReader(pkg_file)
content_types = _ContentTypeMap.from_xml(phys_reader.content_types_xml)
pkg_srels = PackageReader._srels_for(phys_reader, PACKAGE_URI)
sparts = PackageReader._load_serialized_parts(
phys_reader, pkg_srels... | Return a |PackageReader| instance loaded with contents of *pkg_file*. |
362,609 | def get_experiment_fn(args):
def get_experiment(output_dir):
schema_path_with_target = os.path.join(args.analysis,
feature_transforms.SCHEMA_FILE)
features_path = os.path.join(args.analysis,
feature_transforms.FEATURES_FILE)
... | Builds the experiment function for learn_runner.run.
Args:
args: the command line args
Returns:
A function that returns a tf.learn experiment object. |
362,610 | def write_gdf(gdf, fname):
gdf_file = open(fname, )
for line in gdf:
for i in np.arange(len(line)):
gdf_file.write(str(line[i]) + )
gdf_file.write()
return None | Fast line-by-line gdf-file write function
Parameters
----------
gdf : numpy.ndarray
Column 0 is gids, columns 1: are values.
fname : str
Path to gdf-file.
Returns
-------
None |
362,611 | def _read_protos(self, size):
_byte = self._read_unpack(4, lilendian=True)
_prot = LINKTYPE.get(_byte)
return _prot | Read next layer protocol type.
Positional arguments:
* size -- int, buffer size
Returns:
* str -- link layer protocol name |
362,612 | def _search_within_pe_warnings(self, matches):
pattern = .join(re.escape(match) for match in matches)
exp = re.compile(pattern)
if any(exp.search(warning) for warning in self.pefile_handle.get_warnings()):
return True
return False | Just encapsulating a search that takes place fairly often |
362,613 | def model_saved(sender, instance,
created,
raw,
using,
**kwargs):
opts = get_opts(instance)
model = .join([opts.app_label, opts.object_name])
action = if created else
distill_model_event(instance, mode... | Automatically triggers "created" and "updated" actions. |
362,614 | def close(self):
if self.mdr is None:
return
exc = (None, None, None)
try:
self.cursor.close()
except:
exc = sys.exc_info()
try:
if self.mdr.__exit__(*exc):
exc = (None, None, None)
except:
... | Release all resources associated with this factory. |
362,615 | async def async_execute(self, command: Command, password: str = ,
timeout: int = EXECUTE_TIMEOUT_SECS) -> Response:
if not self._is_connected:
raise ConnectionError("Client is not connected to the server")
state = {
: command,
: as... | Execute a command and return response.
command: the command instance to be executed
password: if specified, will be used to execute this command (overriding any
global password that may have been assigned to the property)
timeout: maximum number of seconds to wait fo... |
362,616 | def StreamIDNextDownIDToConnectivity(stream_id_array,
next_down_id_array,
out_csv_file):
list_all = []
max_count_upstream = 0
for hydroid in np.sort(stream_id_array):
list_upstreamID = stream_id_array[next_down_... | Creates RAPID connect file from stream_id array and next down id array |
362,617 | def is_forced_retry(self, method, status_code):
if self.method_whitelist and method.upper() not in self.method_whitelist:
return False
return self.status_forcelist and status_code in self.status_forcelist | Is this method/status code retryable? (Based on method/codes whitelists) |
362,618 | def to_zpl(
self, quantity=1, pause_and_cut=0, override_pause=False,
print_mode=, print_orientation=, media_tracking=, **kwargs
):
zpl = [
self.to_zpl_line(**kwargs),
,
% print_mode,
% print_orientation,
% media_trac... | The most basic ZPL to print the GRF. Since ZPL printers are stateful
this may not work and you may need to build your own. |
362,619 | def plotter(path, show, goodFormat):
for module in goodFormat.items():
bins = [0, 40, 50, 60, 70, 80, 90, 100]
out = pd.cut(module[1], bins=bins, include_lowest=True)
ax = out.value_counts().plot.bar(rot=0, color="b", figsize=(10, 6), alpha=0.5,
... | makes some plots
creates binned histograms of the results of each module
(ie count of results in ranges [(0,40), (40, 50), (50,60), (60, 70), (70, 80), (80, 90), (90, 100)])
Arguments:
path {str} -- path to save plots to
show {boolean} -- whether to show plots using python
goodFor... |
362,620 | def check_valid_format(figformat):
fig = plt.figure()
if figformat in list(fig.canvas.get_supported_filetypes().keys()):
logging.info("Nanoplotter: valid output format {}".format(figformat))
return figformat
else:
logging.info("Nanoplotter: invalid output format {}".format(figfo... | Check if the specified figure format is valid.
If format is invalid the default is returned.
Probably installation-dependent |
362,621 | def synchronized(cls, obj=None):
def get_key(f, o):
if o is None:
key = hash(f)
else:
key = hash(o)
return key
def get_lock(f, o):
key = get_key(f, o)
if key not in cls.lock_map:
with c... | synchronize on obj if obj is supplied.
:param obj: the obj to lock on. if none, lock to the function
:return: return of the func. |
362,622 | def post_save_event_listener(sender, instance, created):
if not instance._meta.event_ready:
return
if created:
instance.create_creation_event()
else:
instance.create_update_event()
instance._original = None | Event listener to create creation and update events. |
362,623 | def remote_jupyter_proxy_url(port):
base_url = os.environ[]
host = urllib.parse.urlparse(base_url).netloc
user_url = urllib.parse.urljoin(base_url, service_url_path)
full_url = urllib.parse.urljoin(user_url, proxy_url_path)
return full_url | Callable to configure Bokeh's show method when a proxy must be
configured.
If port is None we're asking about the URL
for the origin header. |
362,624 | def meson_setup():
meson_exe = shutil.which()
ninja_exe = shutil.which()
if not meson_exe or not ninja_exe:
raise FileNotFoundError()
if not (BINDIR / ).is_file():
subprocess.check_call([meson_exe, str(SRCDIR)], cwd=BINDIR)
ret = subprocess.run(ninja_exe, cwd=BINDIR, stderr=s... | attempt to build with Meson + Ninja |
362,625 | def clicked(self, event):
group = event.artist._mt_group
n = event.artist._mt_n
dt = num2date(event.artist._mt_bin)
print("%4i %s events in %s sec beginning at %s"
% (n, group, self.bucketsize, dt.strftime("%b %d %H:%M:%S"))) | Print group name and number of items in bin. |
362,626 | def save_surface_files(note, error, registrations, subject,
no_surf_export, no_reg_export, surface_format, surface_path,
angle_tag, eccen_tag, label_tag, radius_tag, registration_name):
surface_files
if no_surf_export: return {: ()}
surface_format = surface_form... | save_surface_files is the calculator that saves the registration data out as surface files,
which are put back in the registration as the value 'surface_files'. |
362,627 | def _aws_encode_changebatch(o):
change_idx = 0
while change_idx < len(o[]):
o[][change_idx][][] = aws_encode(o[][change_idx][][])
if in o[][change_idx][]:
rr_idx = 0
while rr_idx < len(o[][change_idx][][]):
o[][change_idx][][][rr_idx][] = aws_encode(... | helper method to process a change batch & encode the bits which need encoding. |
362,628 | def set_cmd(name, accepts_value=False):
def decorator(func):
SET_COMMANDS[name] = func
if accepts_value:
SET_COMMANDS_TAKING_VALUE.add(name)
return func
return decorator | Docorator that registers a ':set'-command. |
362,629 | def match_shortname(self, name, filled_args=None):
filled_count = 0
if filled_args is not None:
filled_count = len(filled_args)
possible = [x for x in self.arg_names[filled_count:] if x.startswith(name)]
if len(possible) == 0:
raise ArgumentError("Could... | Try to convert a prefix into a parameter name.
If the result could be ambiguous or there is no matching
parameter, throw an ArgumentError
Args:
name (str): A prefix for a parameter name
filled_args (list): A list of filled positional arguments that will be
... |
362,630 | def source_file(self):
if os.path.exists(self.filename):
return open_source(self.filename)
raise CoverageException(
"No source for code ." % self.filename
) | Return an open file for reading the source of the code unit. |
362,631 | def _call_numpy(self, x):
if self.halfcomplex:
return np.fft.irfftn(x, axes=self.axes)
else:
if self.sign == :
return np.fft.ifftn(x, axes=self.axes)
else:
return (np.fft.fftn(x, axes=self.axes) /
np.pro... | Return ``self(x)`` using numpy.
Parameters
----------
x : `numpy.ndarray`
Input array to be transformed
Returns
-------
out : `numpy.ndarray`
Result of the transform |
362,632 | def _get_lottery_detail_by_id(self, id):
header = .split()
pt = PrettyTable()
pt._set_field_names(header)
url = QUERY_DETAIL_URL.format(id=id)
import requests
content = requests.get(url).text
d = pq(content)
if d():
info ... | 相应彩种历史信息生成
百度详细信息页有两种结构,需要分开处理 |
362,633 | def ToJson(self):
json = {}
json["hash"] = self.Hash.To0xString()
json["size"] = self.Size()
json["version"] = self.Version
json["previousblockhash"] = self.PrevHash.To0xString()
json["merkleroot"] = self.MerkleRoot.To0xString()
json["time"] = self.Timest... | Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict: |
362,634 | def retry_over_time(fun, catch, args=[], kwargs={}, errback=None,
max_retries=None, interval_start=2, interval_step=2, interval_max=30):
retries = 0
interval_range = xrange(interval_start,
interval_max + interval_start,
interval_step)
for... | Retry the function over and over until max retries is exceeded.
For each retry we sleep a for a while before we try again, this interval
is increased for every retry until the max seconds is reached.
:param fun: The function to try
:param catch: Exceptions to catch, can be either tuple or a single
... |
362,635 | def parse_config_file(config_file_path):
extension = os.path.splitext(config_file_path)[1]
if extension == :
raise ValueError("Skipping .pyc file as config")
if extension == :
with open(config_file_path) as config_file:
try:
mapping = json.load(config_file)
except ValueError as e:
... | Parse a configuration file. Currently only supports .json, .py and properties separated by '='
:param config_file_path:
:return: a dict of the configuration properties |
362,636 | def get_template_object(template_file=):
jinja_template_paths_obj = []
if TEMPLATES_PATH:
external_templates = pathlib.Path(TEMPLATES_PATH).expanduser().resolve()
assert os.path.isdir(external_templates), .format(external_templates)
jinja_template_paths_obj.append(external_template... | Retrieve template.
Args:
template_file (str): Name of template file.
Returns:
jinja2.Template: Template ready to render.
Raises:
AssertionError: Configured path for templates does not exist.
:obj:`foremast.exceptions.ForemastTemplateNotFound`: Requested template
... |
362,637 | def fs_obj_query_info(self, path, follow_symlinks):
if not isinstance(path, basestring):
raise TypeError("path can only be an instance of type basestring")
if not isinstance(follow_symlinks, bool):
raise TypeError("follow_symlinks can only be an instance of type bool")
... | Queries information about a file system object (file, directory, etc)
in the guest.
in path of type str
Path to the file system object to gather information about.
Guest path style.
in follow_symlinks of type bool
Information about symbolic links is returned... |
362,638 | def audioread(filename):
try:
if in filename.lower():
fs, signal = wv.read(filename)
elif in filename.lower():
with open(filename, ) as f:
signal = np.fromfile(f, dtype=np.int16)
fs = 333333
else:
raise IOError("Unsupport... | Reads an audio signal from file.
Supported formats : wav
:param filename: filename of the audiofile to load
:type filename: str
:returns: int, numpy.ndarray -- samplerate, array containing the audio signal |
362,639 | def get_template_attributes(template_id, **kwargs):
try:
attrs_i = db.DBSession.query(Attr).filter(TemplateType.template_id==template_id).filter(TypeAttr.type_id==TemplateType.id).filter(Attr.id==TypeAttr.id).all()
log.debug(attrs_i)
return attrs_i
except NoResultFound:
ret... | Get a specific attribute by its ID. |
362,640 | def get_assessment_part(self, assessment_part_id):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
result = collection.find_one(
dict({: ObjectId(self.... | Gets the ``AssessmentPart`` specified by its ``Id``.
arg: assessment_part_id (osid.id.Id): the ``Id`` of the
``AssessmentPart`` to retrieve
return: (osid.assessment.authoring.AssessmentPart) - the
returned ``AssessmentPart``
raise: NotFound - no ``AssessmentP... |
362,641 | def update(self, display_name=None, display_description=None):
return self.manager.update(self, display_name=display_name,
display_description=display_description) | Update the specified values on this snapshot. You may specify one or
more values to update. If no values are specified as non-None, the call
is a no-op; no exception will be raised. |
362,642 | def readline(self, f):
while True:
line = f.readline()
if len(line) == 0:
raise EOFError
line = line[:line.find()]
line = line.strip()
if len(line) > 0:
return line | A helper method that only reads uncommented lines |
362,643 | def register(self, newdata, *args, **kwargs):
kwargs.update(zip(self.meta_names, args))
uncertainty = kwargs[]
variance = kwargs[]
isconstant = kwargs[]
if uncertainty:
for k0, d in uncertainty.iteritems():
for k1, v01 in d.i... | Register data in registry. Meta for each data is specified by positional
or keyword arguments after the new data and consists of the following:
* ``uncertainty`` - Map of uncertainties in percent corresponding to new
keys. The uncertainty keys must be a subset of the new data keys.
* ... |
362,644 | def create_wtd_psf(skydir, ltc, event_class, event_types, dtheta,
egy_bins, cth_bins, fn, nbin=64, npts=1):
egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts))
etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1)
etrue = 10**utils.edge_to_center(np.log10(etrue_bin... | Create an exposure- and dispersion-weighted PSF model for a source
with spectral parameterization ``fn``. The calculation performed
by this method accounts for the influence of energy dispersion on
the PSF.
Parameters
----------
dtheta : `~numpy.ndarray`
egy_bins : `~numpy.ndarray`
... |
362,645 | def to_ipv6(key):
if key[-2:] != :
raise ValueError()
key_bytes = base32.decode(key[:-2])
hash_one = sha512(key_bytes).digest()
hash_two = sha512(hash_one).hexdigest()
return .join([hash_two[i:i+4] for i in range(0, 32, 4)]) | Get IPv6 address from a public key. |
362,646 | def replace_validating_webhook_configuration(self, name, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.replace_validating_webhook_configuration_with_http_info(name, body, **kwargs)
else:
(data) = self.replace_validating_webhook_configuration_with_... | replace the specified ValidatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_validating_webhook_configuration(name, body, async_req=True)
>>> result = thread.get()
... |
362,647 | def read(self, address, size, force=False):
size = self._get_size(size)
assert not issymbolic(size)
if issymbolic(address):
assert solver.check(self.constraints)
logger.debug(f)
try:
solutions = self._try_get_solutions(address, size, ... | Read a stream of potentially symbolic bytes from a potentially symbolic
address
:param address: Where to read from
:param size: How many bytes
:param force: Whether to ignore permissions
:rtype: list |
362,648 | def scan(self, *, items: np.ndarray = None, axis: int = None, layers: Iterable = None, key: str = None, batch_size: int = 8 * 64) -> Iterable[Tuple[int, np.ndarray, loompy.LoomView]]:
if axis is None:
raise ValueError("Axis must be given (0 = rows, 1 = cols)")
if layers is None:
layers = self.layers.keys()... | Scan across one axis and return batches of rows (columns) as LoomView objects
Args
----
items: np.ndarray
the indexes [0, 2, 13, ... ,973] of the rows/cols to include along the axis
OR: boolean mask array giving the rows/cols to include
axis: int
0:rows or 1:cols
batch_size: int
the chuncks retur... |
362,649 | def GetMacAddresses(self):
result = set()
for interface in self.interfaces:
if (interface.mac_address and
interface.mac_address != b"\x00" * len(interface.mac_address)):
result.add(Text(interface.mac_address.human_readable_address))
return sorted(result) | MAC addresses from all interfaces. |
362,650 | def GetPlugins(cls):
for plugin_name, plugin_class in iter(cls._plugin_classes.items()):
yield plugin_name, plugin_class | Retrieves the registered plugins.
Yields:
tuple[str, type]: name and class of the plugin. |
362,651 | async def _send_rtcp_pli(self, media_ssrc):
if self.__rtcp_ssrc is not None:
packet = RtcpPsfbPacket(fmt=RTCP_PSFB_PLI, ssrc=self.__rtcp_ssrc, media_ssrc=media_ssrc)
await self._send_rtcp(packet) | Send an RTCP packet to report picture loss. |
362,652 | def plot(self):
if self.results_table == None:
return "no results found"
else:
bb = self.results_table.sort_values(
by=["ABCD", "ACBD"],
ascending=[False, True],
)
import toyplot
c = t... | return a toyplot barplot of the results table. |
362,653 | def set_exception(self, exception):
if self.done():
raise RuntimeError("set_exception can only be called once.")
self._exception = exception
self._trigger() | Set the result of the future to the given exception.
Args:
exception (:exc:`Exception`): The exception raised. |
362,654 | def post_build(self, p, pay):
p += pay
if self.auxdlen != 0:
print("NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).")
print(" Subsequent Group Records are lost!")
return p | Called implicitly before a packet is sent. |
362,655 | def djfrontend_jquery(version=None):
if version is None:
version = getattr(settings, , DJFRONTEND_JQUERY_DEFAULT)
if getattr(settings, , False):
template =
else:
template = (
<script src="{static}djfrontend/js/jquery/{v}/jquery.min.js"><\/script>\)
... | Returns jQuery JavaScript file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback.
Included in HTML5 Boilerplate. |
362,656 | def iter_module_paths(modules=None):
modules = modules or list(sys.modules.values())
for module in modules:
try:
filename = module.__file__
except (AttributeError, ImportError):
continue
if filename is not None:
abs_filename = os.path.abspath(fi... | Yield paths of all imported modules. |
362,657 | def register_json(self, data):
j = json.loads(data)
self.last_data_timestamp = \
datetime.datetime.utcnow().replace(microsecond=0).isoformat()
try:
for v in j:
self.data[v[self.id_key]] = {}
se... | Register the contents as JSON |
362,658 | def _traverse(self, name, create_missing=False, action=None, value=NO_DEFAULT):
obj = self
segments = self._parse_path(name)
for segment, next_segment in zip(segments, segments[1:] + [None]):
last = next_segment is None
if create_missing:
self._... | Traverse to the item specified by ``name``.
To create missing items on the way to the ``name``d item, pass
``create_missing=True``. This will insert an item for each
missing segment in ``name``. The type and value of item that
will be inserted for a missing segment depends on the *next*... |
362,659 | def wordcount(text):
bannedwords = read_file()
wordcount = {}
separated = separate(text)
for word in separated:
if word not in bannedwords:
if not wordcount.has_key(word):
wordcount[word] = 1
else:
wordcount[word] += 1
return wordc... | Returns the count of the words in a file. |
362,660 | def wfreq2vocab(wfreq_file, output_file, top=None, gt=None, records=1000000, verbosity=2):
cmd = [, , verbosity,
, records]
cmd = [str(x) for x in cmd]
if top:
cmd.extend([,top])
elif gt:
cmd.extend([,gt])
with open(wfreq_file,) as input_f:
... | Takes a a word unigram file, as produced by text2wfreq and converts it to a vocabulary file.
The top parameter allows the user to specify the size of the vocabulary; if the function is called with the parameter top=20000, then the vocabulary will consist of the most common 20,000 words.
The gt parameter... |
362,661 | def _interpolate_stream_track_kick_aA(self):
if hasattr(self,):
return None
dmOs= numpy.array([\
super(streamgapdf,self).meanOmega(da,oned=True,
tdisrupt=self._tdisrupt
... | Build interpolations of the stream track near the impact in action-angle coordinates |
362,662 | def _get_types(func, clsm, slf, clss = None, prop_getter = False,
unspecified_type = Any, infer_defaults = None):
func0 = util._actualfunc(func, prop_getter)
if not slf:
argNames = util.getargnames(util.getargspecs(func0))
if len(argNames) > 0:
if clsm:
... | Helper for get_types and get_member_types. |
362,663 | def show_window_options(self, option=None, g=False):
tmux_args = tuple()
if g:
tmux_args += (,)
if option:
return self.show_window_option(option, g=g)
else:
tmux_args += (,)
cmd = self.cmd(*tmux_args).stdout
... | Return a dict of options for the window.
For familiarity with tmux, the option ``option`` param forwards to
pick a single option, forwarding to :meth:`Window.show_window_option`.
Parameters
----------
option : str, optional
show a single option.
g : str, opt... |
362,664 | def service_name(self):
if hasattr(self, "server_name") and self.server_name:
server_name = self.server_name
else:
server_name = 1
return "{}-{}-{}".format(self.service_prefix,
self.service_owner,
... | Service name inside the Docker Swarm
service_suffix should be a numerical value unique for user
{service_prefix}-{service_owner}-{service_suffix} |
362,665 | def _get_best_indexes(logits, n_best_size):
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if i >= n_best_size:
break
best_indexes.append(index_and_score[i][0])
return best_indexes | Get the n-best logits from a list. |
362,666 | def assert_text_equal(self, selector, value, testid=None, **kwargs):
self.info_log(
"Assert text equal selector(%s) testid(%s)" % (selector, testid)
)
highlight = kwargs.get(
,
BROME_CONFIG[][]
)
self.debug_log("effective highlight: %... | Assert that the element's text is equal to the provided value
Args:
selector (str): the selector used to find the element
value (str): the value that will be compare
with the element.text value
test_id (str): the test_id or a str
Kwargs:
... |
362,667 | def _byteify(input):
if isinstance(input, dict):
return {_byteify(key): _byteify(value) for key, value in input.items()}
elif isinstance(input, list):
return [_byteify(element) for element in input]
elif _PYTHON_3 and isinstance(input, str):
return str(input.encode(, ).decode())... | Force the given input to only use `str` instead of `bytes` or `unicode`.
This works even if the input is a dict, list, |
362,668 | def summarize(logger):
summary = []
for log in logger.get_logs():
thestatus = log.has_error() and log.get_error(False) or
name = log.get_name()
summary.append(name + + thestatus)
return .join(summary) | Creates a short summary on the actions that were logged by the given
Logger.
:type logger: Logger
:param logger: The logger that recorded what happened in the queue.
:rtype: string
:return: A string summarizing the status of every performed task. |
362,669 | def helical_laminar_fd_White(Re, Di, Dc):
r
De = Dean(Re=Re, Di=Di, D=Dc)
fd = friction_laminar(Re)
if De < 11.6:
return fd
return fd/(1. - (1. - (11.6/De)**0.45)**(1./0.45)) | r'''Calculates Darcy friction factor for a fluid flowing inside a curved
pipe such as a helical coil under laminar conditions, using the method of
White [1]_ as shown in [2]_.
.. math::
f_{curved} = f_{\text{straight,laminar}} \left[1 - \left(1-\left(
\frac{11.6}{De}\right)^{0.45}\rig... |
362,670 | def add_child(self, tree):
s children
This tree becomes the added tree
tree.parent = self
self.children.append(tree)
return tree | Add a child to the list of this tree's children
This tree becomes the added tree's parent |
362,671 | def not_modified(cls, errors=None):
if cls.expose_status:
cls.response.content_type =
cls.response._status_line =
return cls(304, None, errors).to_json | Shortcut API for HTTP 304 `Not Modified` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance. |
362,672 | def acquire(self):
if os.path.exists(self.path):
try:
pid = None
with open(self.path, ) as f:
line = f.readline().strip()
pid = int(line)
if not psutil.pid_exists(pid)... | Attempts to acquire a lock for the J-Link lockfile.
If the lockfile exists but does not correspond to an active process,
the lockfile is first removed, before an attempt is made to acquire it.
Args:
self (Jlock): the ``JLock`` instance
Returns:
``True`` if the lock... |
362,673 | def route(bp, *args, **kwargs):
kwargs[] = kwargs.pop(, False)
body = _validate_schema(kwargs.pop(, None))
query = _validate_schema(kwargs.pop(, None))
output = _validate_schema(kwargs.pop(, None))
validate = kwargs.pop(, True)
def decorator(f):
@bp.route(*args, **kwargs)
... | Journey route decorator
Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow.
:param bp: :class:`flask.Blueprint` object
:param args: args to pass along to `Blueprint.route`
:param kwargs:
- :strict_slashes: Enable / disable strict slashes (... |
362,674 | def add_photo_to_observation(observation_id: int, file_object: BinaryIO, access_token: str):
data = {: observation_id}
file_data = {: file_object}
response = requests.post(url="{base_url}/observation_photos".format(base_url=INAT_BASE_URL),
headers=_build_auth_header(access... | Upload a picture and assign it to an existing observation.
:param observation_id: the ID of the observation
:param file_object: a file-like object for the picture. Example: open('/Users/nicolasnoe/vespa.jpg', 'rb')
:param access_token: the access token, as returned by :func:`get_access_token()` |
362,675 | def ndtri(p, name="ndtri"):
with tf.name_scope(name):
p = tf.convert_to_tensor(value=p, name="p")
if dtype_util.as_numpy_dtype(p.dtype) not in [np.float32, np.float64]:
raise TypeError(
"p.dtype=%s is not handled, see docstring for supported types."
% p.dtype)
return _ndtri(p... | The inverse of the CDF of the Normal distribution function.
Returns x such that the area under the pdf from minus infinity to x is equal
to p.
A piece-wise rational approximation is done for the function.
This is a port of the implementation in netlib.
Args:
p: `Tensor` of type `float32`, `float64`.
... |
362,676 | def _write_subset_index_file(options, core_results):
f_path = os.path.join(options[], )
subset_strs = zip(*core_results)[0]
index = np.arange(len(subset_strs)) + 1
df = pd.DataFrame({: subset_strs}, index=index)
df.to_csv(f_path) | Write table giving index of subsets, giving number and subset string |
362,677 | def deserialize_single_input_output(self, transformer, node_path, attributes_map=None):
with open("{}/model.json".format(node_path)) as json_data:
model_j = json.load(json_data)
attributes = model_j[]
for attribute in attributes.keys():
value_k... | :attributes_map: Map of attributes names. For example StandardScaler has `mean_` but is serialized as `mean`
:param transformer: Scikit or Pandas transformer
:param node: bundle.ml node json file
:param model: bundle.ml model json file
:return: Transformer |
362,678 | def curry(f, args_supplied=()):
try:
nargs_required = len(signature(f).parameters)
except ValueError as e:
raise ValueError(str(e) + " (maybe you're trying to curry a built-in?)")
def inner(arg):
new_args_supplied = args_supplied + (arg,)
if len(new_args_suppli... | Takes a function, and then returns a function that takes each argument for the original
function through __call__. You probably shouldn't use this with builtins! Even if it seems
to work with a builtin, it might not work properly in previous versions of Python. |
362,679 | def geolocation_buses(network, session):
if geopandas:
RenpassGISRegion = RenpassGisParameterRegion
region_id = [, , , , , ,
, , , , , ]
query = session.query(RenpassGISRegion.gid,
RenpassGISRegion.u_region... | If geopandas is installed:
Use Geometries of buses x/y(lon/lat) and Polygons
of Countries from RenpassGisParameterRegion
in order to locate the buses
Else:
Use coordinats of buses to locate foreign buses, which is less accurate.
Parameters
----------
network_etrago: : class: `e... |
362,680 | def pool_create(hypervisor, identifier, pool_path):
path = os.path.join(pool_path, identifier)
if not os.path.exists(path):
os.makedirs(path)
xml = POOL_DEFAULT_CONFIG.format(identifier, path)
return hypervisor.storagePoolCreateXML(xml, 0) | Storage pool creation.
The following values are set in the XML configuration:
* name
* target/path
* target/permission/label |
362,681 | def validate (self):
if not os.path.isfile(self.pathname):
self.message.append()
else:
try:
with open(self.pathname, ) as stream:
pass
except IOError:
self.messages.append( % self.pathname)
for line in self.commands:
messages = [ ]
if line.cmd an... | Returns True if this Sequence is valid, False otherwise.
Validation error messages are stored in self.messages. |
362,682 | def spec_fn(spec_dir=):
specs = [f for f in os.listdir(spec_dir)
if os.path.isfile(f) and f.endswith()]
if not specs:
raise exception.SpecFileNotFound()
if len(specs) != 1:
raise exception.MultipleSpecFilesFound()
return specs[0] | Return the filename for a .spec file in this directory. |
362,683 | def download(self, bands, download_dir=None, metadata=False):
super(AWSDownloader, self).validate_bands(bands)
if download_dir is None:
download_dir = DOWNLOAD_DIR
dest_dir = check_create_folder(join(download_dir, self.sceneInfo.name))
downloaded = []
for b... | Download each specified band and metadata. |
362,684 | def add_transition (self, input_symbol, state, action=None, next_state=None):
if next_state is None:
next_state = state
self.state_transitions[(input_symbol, state)] = (action, next_state) | This adds a transition that associates:
(input_symbol, current_state) --> (action, next_state)
The action may be set to None in which case the process() method will
ignore the action and only set the next_state. The next_state may be
set to None in which case the current state ... |
362,685 | def fit(self, X, y=None):
with Timer() as self.fit_time_:
self.estimator.fit(X, y)
C = self.cluster_centers_
self.embedded_centers_ = self.transformer.fit_transform(C)
self.scores_ = self._score_cluste... | Fit the clustering model, computing the centers then embeds the centers
into 2D space using the embedding method specified. |
362,686 | def autoconvert(string):
for fn in (boolify, int, float):
try:
return fn(string)
except ValueError:
pass
return string | Try to convert variables into datatypes. |
362,687 | def now_date(str=False):
if str:
return datetime.datetime.now().strftime("%Y-%m-%d")
return datetime.date.today() | Get the current date. |
362,688 | def resize_contain(image, size, resample=Image.LANCZOS, bg_color=(255, 255, 255, 0)):
img_format = image.format
img = image.copy()
img.thumbnail((size[0], size[1]), resample)
background = Image.new(, (size[0], size[1]), bg_color)
img_position = (
int(math.ceil((size[0] - img.size[0]) / ... | Resize image according to size.
image: a Pillow image instance
size: a list of two integers [width, height] |
362,689 | def get_mount_targets(filesystemid=None,
mounttargetid=None,
keyid=None,
key=None,
profile=None,
region=None,
**kwargs):
my-minion
result = None
client = _get_conn(key=key, ke... | Get all the EFS mount point properties for a specific filesystemid or
the properties for a specific mounttargetid. One or the other must be
specified
filesystemid
(string) - ID of the file system whose mount targets to list
Must be specified if mounttargetid is not
mounttarg... |
362,690 | def _get_value(self, entity):
if entity._projection:
if self._name not in entity._projection:
raise UnprojectedPropertyError(
% (self._name,))
return self._get_user_value(entity) | Internal helper to get the value for this Property from an entity.
For a repeated Property this initializes the value to an empty
list if it is not set. |
362,691 | def get_topology(self, topologyName, callback=None):
if callback:
self.topology_watchers[topologyName].append(callback)
else:
topology_path = self.get_topology_path(topologyName)
with open(topology_path) as f:
data = f.read()
topology = Topology()
topology.ParseFro... | get topology |
362,692 | def p_closed_proposition_list(self, p):
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[4]] | closed_proposition_list : closed_proposition_list SLASH SLASH closed_proposition
| closed_proposition |
362,693 | def prepare(data):
sha = data.get("sha")
tree = data.get("tree")
return {"sha": sha, "tree": tree} | Restructure/prepare data about trees for output. |
362,694 | def _get_subparser(self, path, group_table=None):
group_table = group_table or {}
for length in range(0, len(path)):
parent_path = path[:length]
parent_subparser = self.subparsers.get(tuple(parent_path), None)
if not parent_subparser:
... | For each part of the path, walk down the tree of
subparsers, creating new ones if one doesn't already exist. |
362,695 | def normalize(self,asOf=None,multiplier=100):
if not asOf:
x0=self.ix[0]
else:
x0=self.ix[asOf]
return self/x0*multiplier | Returns a normalized series or DataFrame
Example:
Series.normalize()
Returns: series of DataFrame
Parameters:
-----------
asOf : string
Date format
'2015-02-29'
multiplier : int
Factor by which the results will be adjusted |
362,696 | def get_save_request_from_user(self):
msg = _("There are unsaved changes.\nDo you want to save?")
dlg = GMD.GenericMessageDialog(
self.main_window, msg,
_("Unsaved changes"), wx.YES_NO | wx.ICON_QUESTION | wx.CANCEL)
save_choice = dlg.ShowModal()
dlg.... | Queries user if grid should be saved |
362,697 | def githubWebHookConsumer(self, *args, **kwargs):
return self._makeApiCall(self.funcinfo["githubWebHookConsumer"], *args, **kwargs) | Consume GitHub WebHook
Capture a GitHub event and publish it via pulse, if it's a push,
release or pull request.
This method is ``experimental`` |
362,698 | def generate_matching_datasets(self, data_slug):
matching_datasets = Dataset.objects.filter(
hub_slug=data_slug
).order_by()
if len(matching_datasets) > 0:
return matching_datasets
else:
return None | Return datasets that match data_slug (hub_slug). |
362,699 | def energy(self, hamiltonian):
r
from ..potential import PotentialBase
if isinstance(hamiltonian, PotentialBase):
from ..potential import Hamiltonian
warnings.warn("This function now expects a `Hamiltonian` instance "
"instead of a `PotentialBa... | r"""
The total energy *per unit mass* (e.g., kinetic + potential):
Parameters
----------
hamiltonian : `gala.potential.Hamiltonian`
The Hamiltonian object to evaluate the energy.
Returns
-------
E : :class:`~astropy.units.Quantity`
The to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.