Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
7,500 | def write_point(self, **kw):
assert in kw
self.convert_bool(kw, )
return self.write_tag_with_content(, **kw) | Write a task point to the file::
with writer.write_point(type=PointType.TURN):
writer.write_waypoint(...)
writer.write_observation_zone(...)
# <Point type="Turn"> ... </Point>
Inside the with clause the
:meth:`~aerofiles.xcsoar.Writer.write_wayp... |
7,501 | def getColor(rgb=None, hsv=None):
if _isSequence(rgb) and len(rgb) > 3:
seqcol = []
for sc in rgb:
seqcol.append(getColor(sc))
return seqcol
if str(rgb).isdigit():
rgb = int(rgb)
if hsv:
c = hsv2rgb(hsv)
else:
c = rgb
if _i... | Convert a color or list of colors to (r,g,b) format from many input formats.
:param bool hsv: if set to `True`, rgb is assumed as (hue, saturation, value).
Example:
- RGB = (255, 255, 255), corresponds to white
- rgb = (1,1,1) is white
- hex = #FFFF00 is yellow
- s... |
7,502 | def _get_scope_highlight_color(self):
color = self.editor.sideareas_color
if color.lightness() < 128:
color = drift_color(color, 130)
else:
color = drift_color(color, 105)
return color | Gets the base scope highlight color (derivated from the editor
background)
For lighter themes will be a darker color,
and for darker ones will be a lighter color |
7,503 | def do_macro_block(parser, token):
tag_name, macro_name, args, kwargs = parse_macro_params(token)
kwargs[node.keyword] = node
else:
raise template.TemplateSyntaxError(
... | Function taking parsed template tag
to a MacroBlockNode. |
7,504 | def __setup_taskset(self, affinity, pid=None, args=None):
self.taskset_path = self.get_option(self.SECTION, )
if args:
return [self.taskset_path, , affinity] + args
if pid:
args = "%s -pc %s %s" % (self.taskset_path, affinity, pid)
retcode, stdout, ... | if pid specified: set process w/ pid `pid` CPU affinity to specified `affinity` core(s)
if args specified: modify list of args for Popen to start w/ taskset w/ affinity `affinity` |
7,505 | def case_name_parts(self):
if not self.is_mixed_case():
self.honorific = self.honorific.title() if self.honorific else None
self.nick = self.nick.title() if self.nick else None
if self.first:
self.first = self.first.title()
self.first... | Convert all the parts of the name to the proper case... carefully! |
7,506 | def locator_to_latlong (locator):
locator = locator.upper()
if len(locator) == 5 or len(locator) < 4:
raise ValueError
if ord(locator[0]) > ord() or ord(locator[0]) < ord():
raise ValueError
if ord(locator[1]) > ord() or ord(locator[1]) < ord():
raise ValueError
if ... | converts Maidenhead locator in the corresponding WGS84 coordinates
Args:
locator (string): Locator, either 4 or 6 characters
Returns:
tuple (float, float): Latitude, Longitude
Raises:
ValueError: When called with wrong or invalid input arg
TypeE... |
7,507 | def _reset_server(self, address):
server = self._servers.get(address)
if server:
server.reset()
self._description = self._description.reset_server(address)
self._update_servers() | Clear our pool for a server and mark it Unknown.
Hold the lock when calling this. Does *not* request an immediate check. |
7,508 | def get_charset(request):
content_type = request.META.get(, None)
if content_type:
return extract_charset(content_type) if content_type else None
else:
return None | Extract charset from the content type |
7,509 | def create_hooks(use_tfdbg=False,
use_dbgprofile=False,
dbgprofile_kwargs=None,
use_validation_monitor=False,
validation_monitor_kwargs=None,
use_early_stopping=False,
early_stopping_kwargs=None):
train_hooks = []... | Create train and eval hooks for Experiment. |
7,510 | def add_node(self, binary_descriptor):
try:
node_string = parse_binary_descriptor(binary_descriptor)
except:
self._logger.exception("Error parsing binary node descriptor: %s", binary_descriptor)
return _pack_sgerror(SensorGraphError.INVALID_NODE_STREAM)
... | Add a node to the sensor_graph using a binary node descriptor.
Args:
binary_descriptor (bytes): An encoded binary node descriptor.
Returns:
int: A packed error code. |
7,511 | def flash(message, category=):
flashes = session.get(, [])
flashes.append((category, message))
session[] = flashes
message_flashed.send(current_app._get_current_object(),
message=message, category=category) | Flashes a message to the next request. In order to remove the
flashed message from the session and to display it to the user,
the template has to call :func:`get_flashed_messages`.
.. versionchanged:: 0.3
`category` parameter added.
:param message: the message to be flashed.
:param categor... |
7,512 | def artist_related_artists(self, spotify_id):
route = Route(, , spotify_id=spotify_id)
return self.request(route) | Get related artists for an artist by their ID.
Parameters
----------
spotify_id : str
The spotify_id to search by. |
7,513 | def find_non_contiguous(all_items):
non_contiguous = []
for item in all_items:
if item.slots.count() < 2:
continue
last_slot = None
for slot in item.slots.all().order_by():
if last_slot:
if last_slot.end_time != slot.get_start_tim... | Find any items that have slots that aren't contiguous |
7,514 | def get(self, queue=, no_ack=False, to_dict=False, auto_decode=True):
if not compatibility.is_string(queue):
raise AMQPInvalidArgument()
elif not isinstance(no_ack, bool):
raise AMQPInvalidArgument()
elif self._channel.consumer_tags:
raise AMQPChannel... | Fetch a single message.
:param str queue: Queue name
:param bool no_ack: No acknowledgement needed
:param bool to_dict: Should incoming messages be converted to a
dictionary before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises... |
7,515 | def addcomment(self, comment, private=False):
vals = self.bugzilla.build_update(comment=comment,
comment_private=private)
log.debug("addcomment: update=%s", vals)
return self.bugzilla.update_bugs(self.bug_id, vals) | Add the given comment to this bug. Set private to True to mark this
comment as private. |
7,516 | def _receive_data(self):
result = self.queue.get(block=True)
if hasattr(self.queue, ):
self.queue.task_done()
return result | Gets data from queue |
7,517 | def fcontext_add_or_delete_policy(action, name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
t have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
.. warning::
... | .. versionadded:: 2017.7.0
Adds or deletes the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automat... |
7,518 | def _pys_assert_version(self, line):
if float(line.strip()) > 1.0:
msg = _("File version {version} unsupported (>1.0).").format(
version=line.strip())
raise ValueError(msg) | Asserts pys file version |
7,519 | def _from_dict(cls, _dict):
args = {}
if in _dict:
args[] = DocumentSentimentResults._from_dict(
_dict.get())
if in _dict:
args[] = [
TargetedSentimentResults._from_dict(x)
for x in (_dict.get())
]
... | Initialize a SentimentResult object from a json dictionary. |
7,520 | def update_username(
self,
username: Union[str, None]
) -> bool:
return bool(
self.send(
functions.account.UpdateUsername(
username=username or ""
)
)
) | Use this method to update your own username.
This method only works for users, not bots. Bot usernames must be changed via Bot Support or by recreating
them from scratch using BotFather. To update a channel or supergroup username you can use
:meth:`update_chat_username`.
Args:
... |
7,521 | def pass_rate(self, include_skips=False, include_inconclusive=False, include_retries=True):
total = self.count()
success = self.success_count()
retries = self.retry_count()
try:
if include_inconclusive and include_skips and include_retries:
val = 100.... | Calculate pass rate for tests in this list.
:param include_skips: Boolean, if True skipped tc:s will be included. Default is False
:param include_inconclusive: Boolean, if True inconclusive tc:s will be included.
Default is False.
:param include_retries: Boolean, if True retried tc:s wi... |
7,522 | def get_object_methods(obj):
import utool as ut
attr_list = (getattr(obj, attrname) for attrname in dir(obj))
methods = [attr for attr in attr_list if ut.is_method(attr)]
return methods | Returns all methods belonging to an object instance specified in by the
__dir__ function
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_inspect import * # NOQA
>>> import utool as ut
>>> obj = ut.NiceRepr()
>>> methods1 = ut.get_object_methods()
>>> ut.injec... |
7,523 | def delete(self):
if len(self) == 0:
return 0
mdl = self.getModel()
return mdl.deleter.deleteMultiple(self) | delete - Delete all objects in this list.
@return <int> - Number of objects deleted |
7,524 | def is_muted(what):
state = False
for item in solo:
if item not in what:
state = True
else:
state = False
break
for item in mute:
if item in what:
state = True
break
return state | Checks if a logged event is to be muted for debugging purposes.
Also goes through the solo list - only items in there will be logged!
:param what:
:return: |
7,525 | def get_email(self, email_id):
connection = Connection(self.token)
connection.set_url(self.production, self.EMAILS_ID_URL % email_id)
return connection.get_request() | Get a specific email |
7,526 | def colstack(seq, mode=,returnnaming=False):
assert mode in [,,,], \
AllNames = utils.uniqify(utils.listunion(
[list(l.dtype.names) for l in seq]))
NameList = [(x, [i for i in range(len(seq)) if x in seq[i].dtype.names])
for x in... | Horizontally stack a sequence of numpy ndarrays with structured dtypes
Analog of numpy.hstack for recarrays.
Implemented by the tabarray method
:func:`tabular.tab.tabarray.colstack` which uses
:func:`tabular.tabarray.tab_colstack`.
**Parameters**
**seq** : sequence of numpy ndarra... |
7,527 | def get_weld_obj_id(weld_obj, data):
obj_id = weld_obj.update(data)
if isinstance(data, WeldObject):
obj_id = data.obj_id
weld_obj.dependencies[obj_id] = data
return obj_id | Helper method to update WeldObject with some data.
Parameters
----------
weld_obj : WeldObject
WeldObject to update.
data : numpy.ndarray or WeldObject or str
Data for which to get an id. If str, it is a placeholder or 'str' literal.
Returns
-------
str
The id of th... |
7,528 | def add_extension_if_needed(filepath, ext, check_if_exists=False):
if not filepath.endswith(ext):
filepath += ext
if check_if_exists:
if not os.path.exists(filepath):
err = + filepath
log.error(err)
raise IOError(err)
return filepath | Add the extension ext to fpath if it doesn't have it.
Parameters
----------
filepath: str
File name or path
ext: str
File extension
check_if_exists: bool
Returns
-------
File name or path with extension added, if needed. |
7,529 | def get_mesures(self, mes, debut=None, fin=None, freq=, format=None,
dayfirst=False, brut=False):
def create_index(index, freq):
decalage = 1
_sql = .format(champ_date=champ_date,
... | Récupération des données de mesure.
Paramètres:
mes: Un nom de mesure ou plusieurs séparées par des virgules, une liste
(list, tuple, pandas.Series) de noms
debut: Chaine de caractère ou objet datetime décrivant la date de début.
Défaut=date du jour
fin: Chaine d... |
7,530 | def infer_trading_calendar(factor_idx, prices_idx):
full_idx = factor_idx.union(prices_idx)
traded_weekdays = []
holidays = []
days_of_the_week = [, , , , , , ]
for day, day_str in enumerate(days_of_the_week):
weekday_mask = (full_idx.dayofweek == day)
if not weekda... | Infer the trading calendar from factor and price information.
Parameters
----------
factor_idx : pd.DatetimeIndex
The factor datetimes for which we are computing the forward returns
prices_idx : pd.DatetimeIndex
The prices datetimes associated withthe factor data
Returns
------... |
7,531 | def optimisation_plot(d, overlay_alpha=0.5, **kwargs):
if not hasattr(d, ):
raise ValueError()
out = []
for n, opt in d.opt.items():
if not opt[]:
out.append((None, None))
else:
means = opt[]
stds = opt[]
... | Plot the result of signal_optimise.
`signal_optimiser` must be run first, and the output
stored in the `opt` attribute of the latools.D object.
Parameters
----------
d : latools.D object
A latools data object.
overlay_alpha : float
The opacity of the threshold overlays. Between... |
7,532 | def _set_sharing_keys(self, keys):
if isinstance(keys, str):
keys = {keys}
keys = set(self) if keys is None else set(keys)
fmto_groups = self._fmto_groups
keys.update(chain(*(map(lambda fmto: fmto.key, fmto_groups[key])
for key in keys.int... | Set the keys to share or unshare
Parameters
----------
keys: string or iterable of strings
The iterable may contain formatoptions that shall be shared (or
unshared), or group names of formatoptions to share all
formatoptions of that group (see the :attr:`fmt_... |
7,533 | def _valcache_lookup(self, cache, branch, turn, tick):
if branch in cache:
branc = cache[branch]
try:
if turn in branc and branc[turn].rev_gettable(tick):
return branc[turn][tick]
elif branc.rev_gettable(turn-1):
... | Return the value at the given time in ``cache`` |
7,534 | def class_method(cls, f):
setattr(cls, f.__name__, classmethod(f))
return f | Decorator which dynamically binds class methods to the model for later use. |
7,535 | def monitor(result_queue, broker=None):
if not broker:
broker = get_broker()
name = current_process().name
logger.info(_("{} monitoring at {}").format(name, current_process().pid))
for task in iter(result_queue.get, ):
if task.get(, False):
save_cached(task, bro... | Gets finished tasks from the result queue and saves them to Django
:type result_queue: multiprocessing.Queue |
7,536 | def push_plugin(self, name):
url = self._url(, name)
headers = {}
registry, repo_name = auth.resolve_repository_name(name)
header = auth.get_config_header(self, registry)
if header:
headers[] = header
res = self._post(url, headers=headers)
se... | Push a plugin to the registry.
Args:
name (string): Name of the plugin to upload. The ``:latest``
tag is optional, and is the default if omitted.
Returns:
``True`` if successful |
7,537 | def preprocess_incoming_content(content, encrypt_func, max_size_bytes):
encrypted = encrypt_func(content)
if max_size_bytes != UNLIMITED and len(encrypted) > max_size_bytes:
raise FileTooLarge()
return encrypted | Apply preprocessing steps to file/notebook content that we're going to
write to the database.
Applies ``encrypt_func`` to ``content`` and checks that the result is
smaller than ``max_size_bytes``. |
7,538 | def write_short_ascii(s):
if s is None:
return _NULL_SHORT_STRING
if not isinstance(s, string_types):
raise TypeError(.format(s))
return write_short_bytes(s.encode()) | Encode a Kafka short string which represents text.
:param str s:
Text string (`str` on Python 3, `str` or `unicode` on Python 2) or
``None``. The string will be ASCII-encoded.
:returns: length-prefixed `bytes`
:raises:
`struct.error` for strings longer than 32767 characters |
7,539 | def addEqLink(self, link):
if isinstance(link, EqLink):
self.eqLinks.append(link)
else:
raise TypeError(
% type(link)) | Appends EqLink |
7,540 | def retrieve_value(self, name, default_value=None):
value = self.spine.send_query("retrieveSetting", self.group, name, processes=["kervi-main"])
if value is None:
return default_value
elif isinstance(value, list) and len(value) == 0:
return default_value
... | Retrieve a value from DB |
7,541 | def set_yaxis(self, param, unit=None, label=None):
if unit is None:
unit = self._getParLabelAndUnit(param)[1]
self._yaxis_unit = unit
self._yaxis = self._set_axis(param, unit)
if label is None:
self.ylabel = self._gen_label(param, unit)
else:
... | Sets the value of use on the yaxis
:param param: value to use on the yaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: the unit to scale the values to
:type unit: quantities ... |
7,542 | def head(self, n=None):
if n is None:
rs = self.head(1)
return rs[0] if rs else None
return self.take(n) | Returns the first ``n`` rows.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
:param n: int, default 1. Number of rows to return.
:return: If n is greater than 1, return a list of :class:`... |
7,543 | def __get_nondirect_init(self, init):
crc = init
for i in range(self.Width):
bit = crc & 0x01
if bit:
crc^= self.Poly
crc >>= 1
if bit:
crc |= self.MSB_Mask
return crc & self.Mask | return the non-direct init if the direct algorithm has been selected. |
7,544 | def process_quote(self, data):
for ix, row in data.iterrows():
symbol = row[]
tick = self._tick_dict.get(symbol, None)
if not tick:
tick = TinyQuoteData()
tick.symbol = symbol
self._tick_dict[symbol] = tick
... | 报价推送 |
7,545 | def call_remoteckan(self, *args, **kwargs):
requests_kwargs = kwargs.get(, dict())
credentials = self._get_credentials()
if credentials:
requests_kwargs[] = credentials
kwargs[] = requests_kwargs
apikey = kwargs.get(, self.get_api_key())
kwar... | Calls the remote CKAN
Args:
*args: Arguments to pass to remote CKAN call_action method
**kwargs: Keyword arguments to pass to remote CKAN call_action method
Returns:
Dict: The response from the remote CKAN call_action method |
7,546 | def copy(self, graph):
e = events(graph, self._ctx)
e.clicked = self.clicked
return e | Returns a copy of the event handler, remembering the last node clicked. |
7,547 | def stop(self):
self._hw_virtualization = False
yield from self._stop_ubridge()
yield from self._stop_remote_console()
vm_state = yield from self._get_vm_state()
if vm_state == "running" or vm_state == "paused" or vm_state == "stuck":
if self.acpi_shutdown:
... | Stops this VirtualBox VM. |
7,548 | def tool(self):
htablettool = self._libinput.libinput_event_tablet_tool_get_tool(
self._handle)
return TabletTool(htablettool, self._libinput) | The tool that was in use during this event.
If the caller keeps a reference to a tool, the tool object will
compare equal to the previously obtained tool object.
Note:
Physical tool tracking requires hardware support. If unavailable,
libinput creates one tool per type per tablet. See
`Tracking unique t... |
7,549 | def _sample_batch():
if _sample_probability == 1.0 or random.random() < _sample_probability:
return True
for database in _measurements:
_measurements[database] = _measurements[database][_max_batch_size:]
return False | Determine if a batch should be processed and if not, pop off all of
the pending metrics for that batch.
:rtype: bool |
7,550 | def return_markers(self, state=):
markers = []
try:
all_states = self._read_states()
except ValueError:
return markers
try:
x = all_states[state]
except KeyError:
return markers
markers = []
i_mrk = hsta... | Return all the markers (also called triggers or events).
Returns
-------
list of dict
where each dict contains 'name' as str, 'start' and 'end' as float
in seconds from the start of the recordings, and 'chan' as list of
str with the channels involved (if not ... |
7,551 | def from_Composition(composition):
if not hasattr(composition, ):
return False
result = \
% (composition.title, composition.author, composition.subtitle)
for track in composition.tracks:
result += from_Track(track) +
return result[:-1] | Return the LilyPond equivalent of a Composition in a string. |
7,552 | def dict_factory(cursor, row):
out = {}
for i, col in enumerate(cursor.description):
out[col[0]] = row[i]
return out | Converts the cursor information from a SQLite query to a dictionary.
:param cursor | <sqlite3.Cursor>
row | <sqlite3.Row>
:return {<str> column: <variant> value, ..} |
7,553 | def _render_select(selections):
if not selections:
return
rendered_selections = []
for name, options in selections.items():
if not isinstance(options, list):
options = [options]
original_name = name
for options_dict in options:
name = original... | Render the selection part of a query.
Parameters
----------
selections : dict
Selections for a table
Returns
-------
str
A string for the "select" part of a query
See Also
--------
render_query : Further clarification of `selections` dict formatting |
7,554 | def entrance_beveled(Di, l, angle, method=):
rRennelsIdelchikRennelsRennelsIdelchikIdelchik
if method is None:
method =
if method == :
Cb = (1-angle/90.)*(angle/90.)**(1./(1 + l/Di ))
lbd = 1 + 0.622*(1 - 1.5*Cb*(l/Di)**((1 - (l/Di)**0.25)/2.))
return 0.0696*(1 - Cb*l/Di)*lb... | r'''Returns loss coefficient for a beveled or chamfered entrance to a pipe
flush with the wall of a reservoir. This calculation has two methods
available.
The 'Rennels' and 'Idelchik' methods have similar trends, but the 'Rennels'
formulation is centered around a straight loss coefficient of 0.57, ... |
7,555 | def main(
output_file: str,
entry_point: Optional[str],
console_script: Optional[str],
python: Optional[str],
site_packages: Optional[str],
compressed: bool,
compile_pyc: bool,
extend_pythonpath: bool,
pip_args: List[str],
) -> None:
if not pip_args and not site_packages:
... | Shiv is a command line utility for building fully self-contained Python zipapps
as outlined in PEP 441, but with all their dependencies included! |
7,556 | def _update_rr_ce_entry(self, rec):
if rec.rock_ridge is not None and rec.rock_ridge.dr_entries.ce_record is not None:
celen = rec.rock_ridge.dr_entries.ce_record.len_cont_area
added_block, block, offset = self.pvd.add_rr_ce_entry(celen)
rec.rock_ridge.updat... | An internal method to update the Rock Ridge CE entry for the given
record.
Parameters:
rec - The record to update the Rock Ridge CE entry for (if it exists).
Returns:
The number of additional bytes needed for this Rock Ridge CE entry. |
7,557 | def str_strip(arr, to_strip=None, side=):
if side == :
f = lambda x: x.strip(to_strip)
elif side == :
f = lambda x: x.lstrip(to_strip)
elif side == :
f = lambda x: x.rstrip(to_strip)
else:
raise ValueError()
return _na_map(f, arr) | Strip whitespace (including newlines) from each string in the
Series/Index.
Parameters
----------
to_strip : str or unicode
side : {'left', 'right', 'both'}, default 'both'
Returns
-------
Series or Index |
7,558 | def _build(self, build_method):
logger.info("building image ", self.image)
self.ensure_not_built()
self.temp_dir = tempfile.mkdtemp()
temp_path = os.path.join(self.temp_dir, BUILD_JSON)
try:
with open(temp_path, ) as build_json:
json.dump(self... | build image from provided build_args
:return: BuildResults |
7,559 | def continue_login(self, login_token, **params):
login_params = {
: "clientlogin",
: login_token,
: 1
}
login_params.update(params)
login_doc = self.post(**login_params)
if login_doc[][] != :
raise LoginError.from_doc(logi... | Continues a login that requires an additional step. This is common
for when login requires completing a captcha or supplying a two-factor
authentication token.
:Parameters:
login_token : `str`
A login token generated by the MediaWiki API (and used in a
... |
7,560 | def get_requirements():
requirements_file = os.path.join(os.getcwd(), )
requirements = []
links=[]
try:
with open(requirements_file) as reqfile:
for line in reqfile.readlines():
line = line.strip()
if line.startswith():
continu... | Extract the list of requirements from our requirements.txt.
:rtype: 2-tuple
:returns: Two lists, the first is a list of requirements in the form of
pkgname==version. The second is a list of URIs or VCS checkout strings
which specify the dependency links for obtaining a copy of the
requi... |
7,561 | def ask_captcha(length=4):
captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length))
ask_str( % (captcha), vld=[captcha, captcha.upper()], blk=False) | Prompts the user for a random string. |
7,562 | def get_activities(self, before=None, after=None, limit=None):
if before:
before = self._utc_datetime_to_epoch(before)
if after:
after = self._utc_datetime_to_epoch(after)
params = dict(before=before, after=after)
result_fetcher = functools.partial(sel... | Get activities for authenticated user sorted by newest first.
http://strava.github.io/api/v3/activities/
:param before: Result will start with activities whose start date is
before specified date. (UTC)
:type before: datetime.datetime or str or None
:param afte... |
7,563 | def id(self, value):
i = value.rfind()
if (i > 0):
self.server_and_prefix = value[:i]
self.identifier = value[(i + 1):]
elif (i == 0):
self.server_and_prefix =
self.identifier = value[(i + 1):]
else:
self.server_and_pr... | Split into server_and_prefix and identifier. |
7,564 | def FindModuleDefiningFlag(self, flagname, default=None):
registered_flag = self.FlagDict().get(flagname)
if registered_flag is None:
return default
for module, flags in six.iteritems(self.FlagsByModuleDict()):
for flag in flags:
if (flag.name == registere... | Return the name of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module which registered the flag with this name.
If no such module exists ... |
7,565 | def import_data_to_restful_server(args, content):
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config()
running, _ = check_rest_server_quick(rest_port)
if running:
response = rest_post(import_data_url(rest_port), content, REST_TIME_OUT)
if response and c... | call restful server to import data to the experiment |
7,566 | def run_migrations_online():
engine = engine_from_config(
winchester_config[],
prefix=,
poolclass=pool.NullPool)
connection = engine.connect()
context.configure(
connection=connection,
target_metadata=target_metadata
)
try:
with context.begin_tr... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. |
7,567 | def timing(self, stat, value, tags=None):
self.histogram(stat, value, tags) | Measure a timing for statistical distribution.
Note: timing is a special case of histogram. |
7,568 | def start(self):
result = self.__enter__()
self._active_patches.append(self)
return result | Activate a patch, returning any created mock. |
7,569 | def _get_flavor():
target = op.join("seqcluster", "flavor")
url = "https://github.com/lpantano/seqcluster.git"
if not os.path.exists(target):
subprocess.check_call(["git", "clone","-b", "flavor", "--single-branch", url])
return op.abspath(target) | Download flavor from github |
7,570 | def getService(self, name, auto_execute=True):
if not isinstance(name, basestring):
raise TypeError()
return ServiceProxy(self, name, auto_execute) | Returns a L{ServiceProxy} for the supplied name. Sets up an object that
can have method calls made to it that build the AMF requests.
@rtype: L{ServiceProxy} |
7,571 | def _find_match(self, position):
document = self._text_edit.document()
start_char = document.characterAt(position)
search_char = self._opening_map.get(start_char)
if search_char:
increment = 1
else:
search_char = self._closing_map.get(sta... | Given a valid position in the text document, try to find the
position of the matching bracket. Returns -1 if unsuccessful. |
7,572 | def _split_generators(self, dl_manager):
split_names = list_folders(dl_manager.manual_dir)
split_label_images = {}
for split_name in split_names:
split_dir = os.path.join(dl_manager.manual_dir, split_name)
split_label_images[split_name] = {
label_name: list... | Returns SplitGenerators from the folder names. |
7,573 | def register(self, event_type, callback,
args=None, kwargs=None, details_filter=None,
weak=False):
if not six.callable(callback):
raise ValueError("Event callback must be callable")
if details_filter is not None:
if not six.callable(deta... | Register a callback to be called when event of a given type occurs.
Callback will be called with provided ``args`` and ``kwargs`` and
when event type occurs (or on any event if ``event_type`` equals to
:attr:`.ANY`). It will also get additional keyword argument,
``details``, that will h... |
7,574 | def notify_program_learners(cls, enterprise_customer, program_details, users):
program_name = program_details.get()
program_branding = program_details.get()
program_uuid = program_details.get()
lms_root_url = get_configuration_value_for_site(
enterprise_customer.sit... | Notify learners about a program in which they've been enrolled.
Args:
enterprise_customer: The EnterpriseCustomer being linked to
program_details: Details about the specific program the learners were enrolled in
users: An iterable of the users or pending users who were enrol... |
7,575 | def tm(seq, dna_conc=50, salt_conc=50, parameters=):
breslauersugimotosantalucia96santalucia98cloningcloning_sl98cloning
if parameters == :
params = tm_params.BRESLAUER
elif parameters == :
params = tm_params.SUGIMOTO
elif parameters == :
params = tm_params.SANTALUCIA96
elif ... | Calculate nearest-neighbor melting temperature (Tm).
:param seq: Sequence for which to calculate the tm.
:type seq: coral.DNA
:param dna_conc: DNA concentration in nM.
:type dna_conc: float
:param salt_conc: Salt concentration in mM.
:type salt_conc: float
:param parameters: Nearest-neighbo... |
7,576 | def on_mouse_wheel(self, event):
rotation = event.GetWheelRotation() / event.GetWheelDelta()
if rotation > 0:
zoom = 1.0/(1.1 * rotation)
elif rotation < 0:
zoom = 1.1 * (-rotation)
self.change_zoom(zoom)
self.redraw_map() | handle mouse wheel zoom changes |
7,577 | def del_repo(repo, root=None):
*
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__(root=root).xml.call(, , , alias)
msg = doc.getElementsByTagName()
if doc.getElementsByTagName() and msg:
... | Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias |
7,578 | def update_anomalous_score(self):
products = self._graph.retrieve_products(self)
diffs = [
p.summary.difference(self._graph.retrieve_review(self, p))
for p in products
]
old = self.anomalous_score
try:
self.anomalous_score = np.averag... | Update anomalous score.
New anomalous score is a weighted average of differences
between current summary and reviews. The weights come from credibilities.
Therefore, the new anomalous score of reviewer :math:`p` is as
.. math::
{\\rm anomalous}(r) = \\frac{
\\... |
7,579 | def write(self, more):
if more:
self.output += str(more).upper()
self.output += | Append the Unicode representation of `s` to our output. |
7,580 | def get_lbaas_agent_hosting_loadbalancer(self, loadbalancer, **_params):
return self.get((self.lbaas_loadbalancer_path +
self.LOADBALANCER_HOSTING_AGENT) % loadbalancer,
params=_params) | Fetches a loadbalancer agent hosting a loadbalancer. |
7,581 | def draw_identity_line(ax=None, dynamic=True, **kwargs):
ax = ax or plt.gca()
if not in kwargs and not in kwargs:
kwargs[] = LINE_COLOR
if not in kwargs:
kwargs[] = 0.5
identity, = ax.plot([],[], **kwargs)
def callback(ax):
xlim ... | Draws a 45 degree identity line such that y=x for all points within the
given axes x and y limits. This function also registeres a callback so
that as the figure is modified, the axes are updated and the line remains
drawn correctly.
Parameters
----------
ax : matplotlib Axes, default: None
... |
7,582 | def get_form_language(self, request, obj=None):
if self._has_translatable_parent_model():
return super(TranslatableInlineModelAdmin, self).get_form_language(request, obj=obj)
else:
return self._language(request) | Return the current language for the currently displayed object fields. |
7,583 | def _pname_and_metadata(in_file):
if os.path.isfile(in_file):
with open(in_file) as in_handle:
md, global_vars = _parse_metadata(in_handle)
base = os.path.splitext(os.path.basename(in_file))[0]
md_file = in_file
elif objectstore.is_remote(in_file):
with objectsto... | Retrieve metadata and project name from the input metadata CSV file.
Uses the input file name for the project name and for back compatibility,
accepts the project name as an input, providing no metadata. |
7,584 | def from_response(raw_response):
json_response = raw_response.json()
error_info = json_response["error"]
code = error_info["code"]
try:
error_cls = _error_map[code]
except KeyError:
raise NotImplementedError(
"Unknown error code ... | The Yelp Fusion API returns error messages with a json body
like:
{
'error': {
'code': 'ALL_CAPS_CODE',
'description': 'Human readable description.'
}
}
Some errors may have additional fields. For example, a
validation erro... |
7,585 | def affine(self, func:AffineFunc, *args, **kwargs)->:
"Equivalent to `image.affine_mat = image.affine_mat @ func()`."
m = tensor(func(*args, **kwargs)).to(self.device)
self.affine_mat = self.affine_mat @ m
return self | Equivalent to `image.affine_mat = image.affine_mat @ func()`. |
7,586 | def _fasta_slice(fasta, seqid, start, stop, strand):
_strand = 1 if strand == else -1
return fasta.sequence({: seqid, : start, : stop, \
: _strand}) | Return slice of fasta, given (seqid, start, stop, strand) |
7,587 | def demacronize(string_matrix: List[List[str]]) -> List[List[str]]:
scansion = ScansionConstants()
accent_dropper = str.maketrans(scansion.ACCENTED_VOWELS, scansion.VOWELS)
return [[word.translate(accent_dropper)
for word in sentence]
for sentence in string_matrix] | Transform macronized vowels into normal vowels
:param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return: string_matrix
>>> demacronize([['ōdī', 'et', 'amō',]])
[['odi', 'et', 'amo']] |
7,588 | def destroy(self):
logger.info("Destroying doc: %s" % self.path)
self.fs.rm_rf(self.path)
logger.info("Done") | Delete the document. The *whole* document. There will be no survivors. |
7,589 | def tenengrad(img, ksize=3):
TENG
Gx = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=ksize)
Gy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=ksize)
FM = Gx*Gx + Gy*Gy
mn = cv2.mean(FM)[0]
if np.isnan(mn):
return np.nanmean(FM)
return mn | TENG' algorithm (Krotkov86) |
7,590 | def plot_importance(booster, ax=None, height=0.2,
xlim=None, ylim=None, title=,
xlabel=, ylabel=,
importance_type=, max_num_features=None,
ignore_zero=True, figsize=None, grid=True,
precision=None, **kwargs):
if... | Plot model's feature importances.
Parameters
----------
booster : Booster or LGBMModel
Booster or LGBMModel instance which feature importance should be plotted.
ax : matplotlib.axes.Axes or None, optional (default=None)
Target axes instance.
If None, new figure and axes will be ... |
7,591 | def populate_requirement_set(requirement_set,
args,
options,
finder,
session,
name,
... | Marshal cmd line args into a requirement set. |
7,592 | async def register(self):
url = .format(self.construct_url(API_URL))
params = {: self._api_key}
reg = await self.api_request(url, params)
if reg is None:
self._registered = False
_LOGGER.error()
else:
self._registered = True
... | Register library device id and get initial device list. |
7,593 | def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
group_keys=True, squeeze=False):
from sparklingpandas.groupby import GroupBy
return GroupBy(self, by=by, axis=axis, level=level, as_index=as_index,
sort=sort, group_keys=group_keys, s... | Returns a groupby on the schema rdd. This returns a GroupBy object.
Note that grouping by a column name will be faster than most other
options due to implementation. |
7,594 | def processed(self):
self.processed_tasks += 1
qsize = self.tasks.qsize()
if qsize > 0:
progress(, self.processed_tasks, qsize, len(self.workers))
else:
progress(, self.processed_tasks, len(self.workers)) | Increase the processed task counter and show progress message |
7,595 | def get_families_by_ids(self, family_ids=None):
if family_ids is None:
raise NullArgument()
families = []
for i in family_ids:
family = None
url_path = + str(i)
try:
family = self._get_request(url_path)
except ... | Gets a ``FamilyList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the families
specified in the ``Id`` list, in the order of the list,
including duplicates, or an error results if an ``Id`` in the
supplied list is not found or inaccessible. ... |
7,596 | async def handle(self, record):
if (not self.disabled) and self.filter(record):
await self.callHandlers(record) | Call the handlers for the specified record.
This method is used for unpickled records received from a socket, as
well as those created locally. Logger-level filtering is applied. |
7,597 | def copy_data_from_remote(args, nni_config, trial_content, path_list, host_list, temp_nni_path):
machine_list = nni_config.get_config().get()
machine_dict = {}
local_path_list = []
for machine in machine_list:
machine_dict[machine[]] = {: machine[], : machine[], : machine[]}
for index, ... | use ssh client to copy data from remote machine to local machien |
7,598 | def _integrate(self, time_steps, capture_elements, return_timestamps):
outputs = []
for t2 in time_steps[1:]:
if self.time() in return_timestamps:
outputs.append({key: getattr(self.components, key)() for key in capture_elements})
self._euler_ste... | Performs euler integration
Parameters
----------
time_steps: iterable
the time steps that the integrator progresses over
capture_elements: list
which model elements to capture - uses pysafe names
return_timestamps:
which subset of 'timesteps' ... |
7,599 | def focusInEvent(self, event):
self.focus_changed.emit()
return super(ControlWidget, self).focusInEvent(event) | Reimplement Qt method to send focus change notification |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.