Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
337,700 | def rank_for_in(self, leaderboard_name, member):
member_score = self.score_for_in(leaderboard_name, member)
if self.order == self.ASC:
try:
return self.redis_connection.zrank(
self._ties_leaderboard_key(leaderboard_name), str(float(member_score)))... | Retrieve the rank for a member in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name.
@return the rank for a member in the leaderboard. |
337,701 | def dre_dtau(self, pars):
r
self._set_parameters(pars)
num1 = self.c * self.w * self.otc1 * np.cos(self.ang)
term1 = num1/self.denom
num2a = self.otc * np.cos(self.ang)
num2b = 1 + num2a
denom2 = self.denom ** 2
term2 = num2b / denom2
... | r"""
:math:Add formula |
337,702 | def build_inception_graph(self):
image_str_tensor = tf.placeholder(tf.string, shape=[None])
image = tf.map_fn(
_util.decode_and_resize, image_str_tensor, back_prop=False, dtype=tf.uint8)
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
image... | Builds an inception graph and add the necessary input & output tensors.
To use other Inception models modify this file. Also preprocessing must be
modified accordingly.
See tensorflow/contrib/slim/python/slim/nets/inception_v3.py for
details about InceptionV3.
Returns:
input_jpeg: A... |
337,703 | def from_dict(cls, entries, **kwargs):
from dask.base import tokenize
cat = cls(**kwargs)
cat._entries = entries
cat._tok = tokenize(kwargs, entries)
return cat | Create Catalog from the given set of entries
Parameters
----------
entries : dict-like
A mapping of name:entry which supports dict-like functionality,
e.g., is derived from ``collections.abc.Mapping``.
kwargs : passed on the constructor
Things like me... |
337,704 | def create_character(skin, hair, top, pants):
dtype = skin.dtype
hair_mask = tf.cast(hair[..., -1:] <= 0, dtype)
top_mask = tf.cast(top[..., -1:] <= 0, dtype)
pants_mask = tf.cast(pants[..., -1:] <= 0, dtype)
char = (skin * hair_mask) + hair
char = (char * top_mask) + top
char = (char * pants_mask) + p... | Creates a character sprite from a set of attribute sprites. |
337,705 | def start(self):
print("Starting debug client cwd: {}".format(os.getcwd()))
print("Sys path: {}".format(sys.path))
self.hotswap = Hotswapper(debug=False)
if self.mode == :
self.server.start(self)
else:
self.client.start(self) | Start the dev session. Attempt to use tornado first, then try
twisted |
337,706 | def config_filter_lines(parent_regex, child_regex, source=):
r*^interfaceip address*^interfaceshutdown
config_txt = __salt__[](source=source)[][source]
return __salt__[](config=config_txt,
parent_regex=parent_regex,
... | r'''
.. versionadded:: 2019.2.0
Return a list of detailed matches, for the configuration blocks (parent-child
relationship) whose parent respects the regular expressions configured via
the ``parent_regex`` argument, and the child matches the ``child_regex``
regular expression. The result is a list ... |
337,707 | def find_lines(config=None, config_path=None, regex=None, saltenv=):
*ip address
lines = find_objects(config=config,
config_path=config_path,
regex=regex,
saltenv=saltenv)
return [line.text for line in lines] | Return all the lines (as text) that match the expression in the ``regex``
argument.
config
The configuration sent as text.
.. note::
This argument is ignored when ``config_path`` is specified.
config_path
The absolute or remote path to the file with the configuration t... |
337,708 | def _check_ver(pyver, op, wanted):
2.7.15gt2.72.7.15gt2.7.152.7.15ge2.7.152.7.15eq2.7.15
pyver = distutils.version.LooseVersion(pyver)
wanted = distutils.version.LooseVersion(wanted)
return getattr(operator, .format(op))(pyver, wanted) | >>> _check_ver('2.7.15', 'gt', '2.7')
True
>>> _check_ver('2.7.15', 'gt', '2.7.15')
False
>>> _check_ver('2.7.15', 'ge', '2.7.15')
True
>>> _check_ver('2.7.15', 'eq', '2.7.15')
True |
337,709 | def rate_limit(self, rate_limit):
self._rate_limit = bool(rate_limit)
self._rate_limit_last_call = None
self.clear_memoized() | Turn on or off rate limiting |
337,710 | def join_or_die(self):
if self._phase_desc.options.timeout_s is not None:
self.join(self._phase_desc.options.timeout_s)
else:
self.join(DEFAULT_PHASE_TIMEOUT_S)
if isinstance(self._phase_execution_outcome, PhaseExecutionOutcome):
return self._phase_execution_outcome
... | Wait for thread to finish, returning a PhaseExecutionOutcome instance. |
337,711 | def get_inventory_of_component(self, component):
self.oem_init()
if component == :
return self._get_zero_fru()
self.init_sdr()
for fruid in self._sdr.fru:
if self._sdr.fru[fruid].fru_name == component:
return self._oem.process_fru(fru.FRU(... | Retrieve inventory of a component
Retrieve detailed inventory information for only the requested
component. |
337,712 | def filter(func, data):
out = []
for r in data:
if func(r):
out.append(r)
return out | Parameter <func> must be a single-argument
function that takes a sequence (i.e.,
a sample point) and returns a boolean. This procedure calls <func> on
each element in <data> and returns a list comprising elements for
which <func> returns True.
>>> data = [[1,5], [2,10], [3,13], [4,16]]
... chart_data.filter(lambda... |
337,713 | def save_attributes(self, request_envelope, attributes):
try:
table = self.dynamodb.Table(self.table_name)
partition_key_val = self.partition_keygen(request_envelope)
table.put_item(
Item={self.partition_key_name: partition_key_val,
... | Saves attributes to table in Dynamodb resource.
Saves the attributes into Dynamodb table. Raises
PersistenceException if table doesn't exist or ``put_item`` fails
on the table.
:param request_envelope: Request Envelope passed during skill
invocation
:type request_en... |
337,714 | def course_discovery_api_client(user, catalog_url):
if JwtBuilder is None:
raise NotConnectedToOpenEdX(
_("To get a Catalog API client, this package must be "
"installed in an Open edX environment.")
)
jwt = JwtBuilder.create_jwt_for_user(user)
return EdxRestA... | Return a Course Discovery API client setup with authentication for the specified user. |
337,715 | def stringify_device_meta(device_object):
try:
if isinstance(device_object[][][], dict):
device_object[][][] =\
json.dumps(device_object[][][])
except ValueError as err:
print("stringify: {0}".format(err))
return device_object | Input: Portals device object.
Output: The same device object with the device meta
converted to a python string. |
337,716 | def set_overcloud_passwords(self, parameters, parsed_args):
undercloud_ceilometer_snmpd_password = utils.get_config_value(
"auth", "undercloud_ceilometer_snmpd_password")
self.passwords = passwords = utils.generate_overcloud_passwords()
ceilometer_pass = passwords[]
... | Add passwords to the parameters dictionary
:param parameters: A dictionary for the passwords to be added to
:type parameters: dict |
337,717 | def JMS_to_Fierz_chrom(C, qq):
if qq[0] in dflav:
s = dflav[qq[0]]
b = dflav[qq[1]]
return {
+ qq : C[][s, b],
+ qq : C[][s, b],
+ qq : C[][b, s].conj(),
+ qq : C[][b, s].conj()
}
else:
u... | From JMS to chromomagnetic Fierz basis for Class V.
qq should be of the form 'sb', 'ds' etc. |
337,718 | def handle_input(self, event):
self.update_timeval()
self.events = []
code = self._get_event_key_code(event)
if code in self.codes:
new_code = self.codes[code]
else:
new_code = 0
event_type = self._get_event_type(event)
value = se... | Process they keyboard input. |
337,719 | def versioned_workdir(self):
versioned_workdir = os.path.join(self.workdir, self.implementation_version_slug())
safe_mkdir(versioned_workdir)
return versioned_workdir | The Task.workdir suffixed with a fingerprint of the Task implementation version.
When choosing whether to store values directly in `self.workdir` or below it in
the directory returned by this property, you should generally prefer this value.
:API: public |
337,720 | def restart():
python = sys.executable
os.execl(python, python, * sys.argv) | Restart the application the same way it was started
:returns: None
:rtype: None
:raises: SystemExit |
337,721 | def close(self):
with self._lock:
for server in self._servers.values():
server.close()
self._description = self._description.reset()
self._update_servers()
self._opened = False
if self._publish_tp:
... | Clear pools and terminate monitors. Topology reopens on demand. |
337,722 | def remove(self, items):
items = coerce_to_list(items)
new_options = {k: v for k, v in self.options.items() if v not in items}
self.widget.options = new_options
self.widget.param.trigger() | Remove items from options |
337,723 | def on_props_activated(self, menu_item):
tree_paths = self.iconview.get_selected_items()
if not tree_paths:
dialog = FolderPropertyDialog(self, self.app, self.parent.path)
dialog.run()
dialog.destroy()
else:
for tree_path in tree_paths:
... | 显示选中的文件或者当前目录的属性 |
337,724 | def compactTable(self, login, tableName, startRow, endRow, iterators, flush, wait):
self.send_compactTable(login, tableName, startRow, endRow, iterators, flush, wait)
self.recv_compactTable() | Parameters:
- login
- tableName
- startRow
- endRow
- iterators
- flush
- wait |
337,725 | def add_edge(self, p_from, p_to, p_id=None):
if not self.has_edge(p_from, p_to):
if not self.has_node(p_from):
self.add_node(p_from)
if not self.has_node(p_to):
self.add_node(p_to)
self._edges[p_from].add(p_to)
self._edge... | Adds an edge to the graph. The nodes will be added if they don't exist.
The p_id is the id of the edge, if the client wishes to maintain this. |
337,726 | def mean(self, name, **kwargs):
return np.mean(self.get(name,**kwargs)) | Mean of the distribution. |
337,727 | def _feature_guess(im, rad, minmass=None, use_tp=False, trim_edge=False):
if minmass is None:
else:
guess, mass = initializers.local_max_featuring(
im, radius=rad, minmass=minmass, trim_edge=trim_edge)
npart = guess.shape[0]
inds = np.argsort(mass)[::-... | Workhorse of feature_guess |
337,728 | def endpoint_name(self, endpoint_name):
if endpoint_name is None:
raise ValueError("Invalid value for `endpoint_name`, must not be `None`")
if endpoint_name is not None and not re.search(, endpoint_name):
raise ValueError("Invalid value for `endpoint_name`, must be a fol... | Sets the endpoint_name of this PreSharedKey.
The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.
:param endpoint_name: The endpoint_name of this PreSharedKey.
:type: str |
337,729 | def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None:
_debug("rename", self, dn, new_rdn, new_base_dn)
split_dn = tldap.dn.str2dn(dn)
split_newrdn = tldap.dn.str2dn(new_rdn)
assert(len(split_newrdn) == 1)
rdn = tldap.dn.... | rename a dn in the ldap database; see ldap module. doesn't return a
result if transactions enabled. |
337,730 | def update_category(uid, post_data):
if in post_data:
pass
else:
return False
the_cats_arr = []
the_cats_dict = {}
def_cate_arr = [.format(x) for x in range(10)]
for key in def_cate_arr:
if key not in post_data:
con... | Update the category of the post.
:param uid: The ID of the post. Extra info would get by requests. |
337,731 | def execution_errors(self):
if self.split_actions:
return [dict(e) for s in self.split_actions for e in s.errors]
else:
return [dict(e) for e in self.errors] | Return a list of commands that encountered execution errors, with the error.
Each dictionary entry gives the command dictionary and the error dictionary
:return: list of commands that gave errors, with their error information |
337,732 | def receive_device_value(self, raw_value: int):
new_value = self._input_to_raw_value(raw_value)
self.__value = new_value
if new_value > self.max:
self.max = new_value
elif new_value < self.min:
self.min = new_value | Set a new value, called from within the joystick implementation class when parsing the event queue.
:param raw_value: the raw value from the joystick hardware
:internal: |
337,733 | def ping(self) -> None:
if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB,
PYTHONLIB_PYMYSQL]:
return
try:
self.db.ping(True)
... | Pings a database connection, reconnecting if necessary. |
337,734 | def build_row_dict(cls, row, dialect, deleted=False, user_id=None, use_dirty=True):
data = {
: row.to_archivable_dict(dialect, use_dirty=use_dirty),
: deleted,
: datetime.now(),
: current_version_sql(as_is=True) if deleted else row.version_id
}
... | Builds a dictionary of archive data from row which is suitable for insert.
NOTE: If `deleted` is False, version ID will be set to an AsIs SQL construct.
:param row: instance of :class:`~SavageModelMixin`
:param dialect: :py:class:`~sqlalchemy.engine.interfaces.Dialect`
:param deleted: ... |
337,735 | def body_count(self):
count, labels = graph.csgraph.connected_components(
self.edges_sparse,
directed=False,
return_labels=True)
self._cache[] = labels
return count | How many connected groups of vertices exist in this mesh.
Note that this number may differ from result in mesh.split,
which is calculated from FACE rather than vertex adjacency.
Returns
-----------
count : int
Number of connected vertex groups |
337,736 | def convert_image_data_to_pil(psd, apply_icc=True, **kwargs):
from PIL import Image, ImageOps
header = psd.header
size = (header.width, header.height)
channels = []
for channel_data in psd.image_data.get_data(header):
channels.append(_create_channel(size, channel_data, header.depth))
... | Convert ImageData to PIL Image.
.. note:: Image resources contain extra alpha channels in these keys:
`ALPHA_NAMES_UNICODE`, `ALPHA_NAMES_PASCAL`, `ALPHA_IDENTIFIERS`. |
337,737 | def get_tty_size(self):
if sys.platform == :
ret = self._tty_size_windows(-10)
ret = ret or self._tty_size_windows(-11)
ret = ret or self._tty_size_windows(-12)
else:
ret = self._tty_size_linux(0)
ret = ret or... | Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. But hey, it
does. |
337,738 | def dichotomy(self, f, kmin=2, kmax=12, raise_no_convergence=True,):
for k in range(kmin, kmax):
N = pow(2, k)
sampled = self.sample_function(f, N)
coeffs = self.polyfit(sampled)
bnd = self._threshold(np.max(np.abs(coeffs)))
... | Compute the coefficients for a function f by dichotomy.
kmin, kmax: log2 of number of interpolation points to try
raise_no_convergence: whether to raise an exception if the dichotomy does not converge |
337,739 | def get_password(self, service, username):
items = self._find_passwords(service, username)
if not items:
return None
secret = items[0].secret
return (
secret
if isinstance(secret, six.text_type) else
secret.decode()
) | Get password of the username for the service |
337,740 | def pairwise(iterable):
iterator = iter(iterable)
try:
first = next(iterator)
except StopIteration:
return
for element in iterator:
yield first, element
first = element | Generate consecutive pairs of elements from the given iterable. |
337,741 | def _set_with_height(self, fig, opts):
h = 5
if "height" in opts:
h = opts["height"]
w = 12
if "width" in opts:
w = opts["width"]
try:
fig.figure.set_size_inches((w, h))
return fig
except Exception:
try:... | Set the width and height of a Matplotlib figure |
337,742 | def tree_climber(self, tree_alias, base_item):
if base_item is not None:
base_item.in_current_branch = True
if hasattr(base_item, ) and base_item.parent is not None:
self.tree_climber(tree_alias, self.get_item_by_id(tree_alias, base_item.parent.id)) | Climbs up the site tree to mark items of current branch.
:param str|unicode tree_alias:
:param TreeItemBase base_item: |
337,743 | def reionize(self, mol):
log.debug()
start_charge = Chem.GetFormalCharge(mol)
for cc in self.charge_corrections:
for match in mol.GetSubstructMatches(cc.smarts):
atom = mol.GetAtomWithIdx(match[0])
log.info(, cc.name, atom.GetSymbol... | Enforce charges on certain atoms, then perform competitive reionization.
First, charge corrections are applied to ensure, for example, that free metals are correctly ionized. Then, if
a molecule with multiple acid groups is partially ionized, ensure the strongest acids ionize first.
The algori... |
337,744 | def krumsiek11() -> AnnData:
filename = os.path.dirname(__file__) +
verbosity_save = sc.settings.verbosity
sc.settings.verbosity =
adata = sc.read(filename, first_column_names=True)
sc.settings.verbosity = verbosity_save
adata.uns[] = 0
fate_labels = {0: , 159: , 319: ,
... | Simulated myeloid progenitors [Krumsiek11]_.
The literature-curated boolean network from [Krumsiek11]_ was used to
simulate the data. It describes development to four cell fates: 'monocyte',
'erythrocyte', 'megakaryocyte' and 'neutrophil'.
See also the discussion of this data in [Wolf19]_.
Simula... |
337,745 | def _get_registry_auth(registry_url, config_path):
username = None
password = None
try:
docker_config = json.load(open(config_path))
except ValueError:
return username, password
if docker_config.get():
docker_config = dock... | Retrieve from the config file the current authentication for a given URL, and
return the username, password |
337,746 | def setMinGap(self, personID, minGap):
self._connection._sendDoubleCmd(
tc.CMD_SET_PERSON_VARIABLE, tc.VAR_MINGAP, personID, minGap) | setMinGap(string, double) -> None
Sets the offset (gap to front person if halting) for this vehicle. |
337,747 | def admin_get_user(self, attr_map=None):
user = self.client.admin_get_user(
UserPoolId=self.user_pool_id,
Username=self.username)
user_metadata = {
: user.get(),
:user.get(),
:user.get(),
: sel... | Get the user's details using admin super privileges.
:param attr_map: Dictionary map from Cognito attributes to attribute
names we would like to show to our users
:return: UserObj object |
337,748 | def update(
self, alert_condition_id, policy_id,
type=None,
condition_scope=None,
name=None,
entities=None,
metric=None,
runbook_url=None,
terms=None,
user_defined=None,
enabled=None):
... | Updates any of the optional parameters of the alert condition
:type alert_condition_id: int
:param alert_condition_id: Alerts condition id to update
:type policy_id: int
:param policy_id: Alert policy id where target alert condition belongs to
:type type: str
:param ty... |
337,749 | def _parse_docstrings(self, filepath):
xmlpath = self.get_xmldoc_path(filepath)
if self.tramp.exists(xmlpath):
xmlstring = self.tramp.read(xmlpath)
self.modulep.docparser.parsexml(xmlstring, self.modules, xmlpath) | Looks for additional docstring specifications in the correctly named
XML files in the same directory as the module. |
337,750 | def fields(self):
key = self.id +
encoding = self.client.encoding
return tuple(sorted((f.decode(encoding)
for f in self.client.smembers(key)))) | Return a tuple of ordered fields for this :class:`ColumnTS`. |
337,751 | def run_as_coroutine(self, stdin, callbacks):
assert isinstance(callbacks, EventLoopCallbacks)
stdin_reader = PosixStdinReader(stdin.fileno())
if self.closed:
raise Exception()
inputstream = InputStream(callbacks.feed_key)
try:
... | The input 'event loop'. |
337,752 | def str_to_bytes(value: str, expected_length: int) -> bytes:
length = len(value)
if length != expected_length:
raise ValueError(.format(expected_length, length))
try:
encoded = value.encode()
except UnicodeEncodeError as ex:
raise ValueError(.format(ex))
decoding = DEC... | Convert the given string to bytes and validate it is within the Base32 character set.
:param value: String to convert to bytes
:type value: :class:`~str`
:param expected_length: Expected length of the input string
:type expected_length: :class:`~int`
:return: Value converted to bytes.
:rtype: :... |
337,753 | def list_datafiles():
is_cplx, is_fpi = td_type()
it_rho = read_iter(is_fpi)
it_phase = read_iter(False)
files = []
dtype = []
files.append(it_rho)
dtype.append()
if is_cplx:
files.append(it_rho.replace(, ))
dtype.append()
if is_fpi:
files.appen... | Get the type of the tomodir and the highest iteration to list all files,
which will be plotted. |
337,754 | def stop(name):
vm_ = get_vm_info(name)
machine = vm_[]
cmd = .format(machine)
ret = __salt__[](cmd,
runas=vm_.get(),
cwd=vm_.get())
return ret == 0 | Hard shutdown the virtual machine. (vagrant halt)
CLI Example:
.. code-block:: bash
salt <host> vagrant.stop <salt_id> |
337,755 | def buildASNList(rootnames, asnname, check_for_duplicates=True):
filelist, duplicates = checkForDuplicateInputs(rootnames)
if check_for_duplicates and duplicates:
origasn = changeSuffixinASN(asnname, )
dupasn = changeSuffixinASN(asnname, )
errstr =
... | Return the list of filenames for a given set of rootnames |
337,756 | def OnLineColor(self, event):
color = event.GetValue().GetRGB()
borders = self.bordermap[self.borderstate]
post_command_event(self, self.BorderColorMsg, color=color,
borders=borders) | Line color choice event handler |
337,757 | def authorize_cache_security_group_ingress(name, ec2_security_group_name,
ec2_security_group_owner_id,
region=None, key=None, keyid=None,
profile=None):
conn = _get_conn(region=regio... | Authorize network ingress from an ec2 security group to a cache security
group.
CLI example::
salt myminion boto_elasticache.authorize_cache_security_group_ingress myelasticachesg myec2sg 879879 |
337,758 | def delete_user_entitlements(self, user_id):
route_values = {}
if user_id is not None:
route_values[] = self._serialize.url(, user_id, )
self._send(http_method=,
location_id=,
version=,
route_values=route_values) | DeleteUserEntitlements.
[Preview API]
:param str user_id: |
337,759 | def search(self, path_expression, mode=UXP, values=None, ifunc=lambda x: x):
path_and_value_list = iterutils.search(
self.data,
path_expression=path_expression,
required_values=values,
exact=(mode[1] == "x"))
return self.__return_value(... | find matches for the given path expression in the data
:param path_expression: path tuple or string
:return: |
337,760 | def import_from_source(module_filepath):
import sys
if not os.path.exists(module_filepath):
raise ValueError("Path to alleged module file doesn{}'".format(module_filepath))
fname_chars = string.ascii_letters + string.digits
name = "".join(random.choice(fname_chars) for _ in range(20)... | Import a module from a particular filesystem location.
:param str module_filepath: path to the file that constitutes the module
to import
:return module: module imported from the given location, named as indicated
:raises ValueError: if path provided does not point to an extant file |
337,761 | def _comparison_stats_from_merge(in_file, stats, svcaller, data):
truth_stats = {"tp": [], "fn": [], "fp": []}
samples = ["truth" if x.endswith("-truth") else "eval" for x in vcfutils.get_samples(in_file)]
with open(in_file) as in_handle:
for call in (l.rstrip().split("\t") for l in in_handle ... | Extract true/false positive/negatives from a merged SURIVOR VCF. |
337,762 | def _extract_header(time_series):
return TimeSeries(
metric=time_series.metric,
resource=time_series.resource,
metric_kind=time_series.metric_kind,
value_type=time_series.value_type,
) | Return a copy of time_series with the points removed. |
337,763 | def basic_logging(self) -> None:
if len(request_log.handlers) == 0:
request_handler = logging.StreamHandler()
request_handler.setFormatter(
logging.Formatter(fmt=self.DEFAULT_REQUEST_LOG_FORMAT)
)
request_log.addHandler(request_ha... | Call this on the client object to create log handlers to output request and
response messages. |
337,764 | def get_deck(self):
trace = self.get_trace()
res = [None] + [item for item in trace if isinstance(item, Deck)]
return res.pop() | Returns parent :Deck: of a :Placeable: |
337,765 | def checkInitialState(self,initialState):
assert initialState is not None, "Initial state has not been specified."
assert isinstance(initialState,(int,list,tuple,np.ndarray,set)), "initialState %r is not an int, tuple, list, set or numpy array" % initialState
if isinstance(in... | Check whether the initial state is of the correct type.
The state should be either an int, list, tuple or np.array and all its elements must be integer.
Returns an int if the state is an integer, otherwise a tuple. |
337,766 | def parents(self, lhs, rhs):
return [node for node in rhs if node.parent in lhs] | Find nodes in rhs which have parents in lhs. |
337,767 | def _get_file(self, fn, timeout=30):
msg = FILE_MAP.get(fn, None)
if msg is None:
raise FileNotFoundError(
.format(fn, .join(FILE_MAP.keys())))
result = self._loop.run_until_complete(
self._... | Request a SiriDB configuration file.
This method is used by the SiriDB manage tool and should not be used
otherwise. Full access rights are required for this request. |
337,768 | def generate_ics(courses):
events = ""
for c in courses:
created = strftime(datetime.datetime.utcnow()) + "Z"
summary = c["title"]
location = c["room"]
description = "{id}・{modules}・{credit}単位".format(**c)
try:
dates = parse_stupid_date(c)
except... | .ics作るやつ |
337,769 | def read(cls, iprot):
init_kwds = {}
iprot.read_struct_begin()
while True:
ifield_name, ifield_type, _ifield_id = iprot.read_field_begin()
if ifield_type == 0:
break
elif ifield_name == :
init_kwds[] = dict([(iprot.... | Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail.OnlineDatabaseObjectDetail |
337,770 | def componentDoc(self, starttime=True):
samplerate = self.samplerate()
doc_list = []
for row, track in enumerate(self._segments):
start_time = 0
for col, component in enumerate(track):
info = component.stateDict()
info[] = componen... | The documentation for the components, as a dict
:returns dict -- values are the generation samplerate, and a list of
the individual component docs |
337,771 | def _set_interface_hello_multiplier(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("interface_hello_multiplier_level",interface_hello_multiplier.interface_hello_multiplier, yang_name="interface-hello-multiplier", rest_name="hello-multipl... | Setter method for interface_hello_multiplier, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_hello_multiplier (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_hello_multiplier is considered as a private
method. Backe... |
337,772 | def root(self):
if self.is_root:
return self
return self.adapter.wrap_node(
self.adapter.impl_root_element, self.adapter.impl_document,
self.adapter) | :return: the root :class:`Element` node of the document that
contains this node, or ``self`` if this node is the root element. |
337,773 | def get_elapsed_time(self, issue):
last_mark = None
worklogs = self.get_worklog(issue)
if worklogs:
last_worklog = worklogs[-1]
last_mark = dateutil.parser.parse(last_worklog.raw[])
if not last_mark:
last_mark = self.get_da... | Gets the elapsed time since the last mark (either the updated time of the last log or the time that the issue was
marked in progress) |
337,774 | def _from_dict(cls, _dict):
args = {}
if in _dict:
args[] = _dict.get()
if in _dict:
args[] = _dict.get()
if in _dict:
args[] = _dict.get()
if in _dict:
args[] = [
EntityMention._from_dict(x) for x in (_... | Initialize a EntitiesResult object from a json dictionary. |
337,775 | def get_template(name):
text = re.sub(r, r, name)
text = re.sub(r, r, text)
return text | Still unsure about best way to do this, hence cruft. |
337,776 | def hexdump(src, length=8):
if not src:
return str(src)
src = input_validate_str(src, )
offset = 0
result =
for this in group(src, length):
hex_s = .join(["%02x" % ord(x) for x in this])
result += "%04X %s\n" % (offset, hex_s)
offset += length
return resul... | Produce a string hexdump of src, for debug output. |
337,777 | def patch_spyder2(verbose=False):
try:
from spyderlib import config
src_file = config.__file__
spyderlib_dir = os.path.dirname(src_file)
if verbose:
print(.format(src_file))
with open(src_file, encoding=) as src:
content = src.read()
... | Patch spyder to make it work with sos files and sos kernel |
337,778 | def getattr(self, name, context=None, class_context=True):
values = self.locals.get(name, [])
if name in self.special_attributes and class_context and not values:
result = [self.special_attributes.lookup(name)]
if name == "__bases__":
... | Get an attribute from this class, using Python's attribute semantic.
This method doesn't look in the :attr:`instance_attrs` dictionary
since it is done by an :class:`Instance` proxy at inference time.
It may return an :class:`Uninferable` object if
the attribute has not been
fou... |
337,779 | def _evaluate(self,R,phi=0.,t=0.):
if not self._tform is None:
if t < self._tform:
smooth= 0.
elif t < self._tsteady:
deltat= t-self._tform
xi= 2.*deltat/(self._tsteady-self._tform)-1.
smooth= (3./16.*xi**5... | NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
2011-10-19 - Started - Bovy (IAS) |
337,780 | def completely_parse_reader(parser: Parser[Input, Output], reader: Reader[Input]) -> Result[Output]:
result = (parser << eof).consume(reader)
if isinstance(result, Continue):
return Success(result.value)
else:
used = set()
unique_expected = []
for expected_lambda in res... | Consume reader and return Success only on complete consumption.
This is a helper function for ``parse`` methods, which return ``Success``
when the input is completely consumed and ``Failure`` with an appropriate
message otherwise.
Args:
parser: The parser doing the consuming
reader: Th... |
337,781 | def cmd_param(self, args):
self.pstate.handle_command(self.master, self.mpstate, args) | control parameters |
337,782 | def _read_stc(stc_file):
hdr = _read_hdr_file(stc_file)
stc_dtype = dtype([(, ),
(, ),
(, ),
(, ),
(, )])
with stc_file.open() as f:
f.seek(352)
hdr[] = unpack(, f.read(4))[0]
hdr[]... | Read Segment Table of Contents file.
Returns
-------
hdr : dict
- next_segment : Sample frequency in Hertz
- final : Number of channels stored
- padding : Padding
stamps : ndarray of dtype
- segment_name : Name of ERD / ETC file segment
- start_stamp : First samp... |
337,783 | def get_transaction_by_id(cls, txid):
for api_call in cls.GET_TRANSACTION_BY_ID_MAIN:
try:
return api_call(txid)
except cls.IGNORED_ERRORS:
pass
raise ConnectionError() | Gets a raw transaction hex by its transaction id (txid).
:param txid: The id of the transaction
:type txid: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``string`` |
337,784 | def get_field_info(model):
opts = model._meta.concrete_model._meta
pk = _get_pk(opts)
fields = _get_fields(opts)
forward_relations = _get_forward_relationships(opts)
reverse_relations = _get_reverse_relationships(opts)
fields_and_pk = _merge_fields_and_pk(pk, fields)
relationships = _m... | Given a model class, returns a `FieldInfo` instance, which is a
`namedtuple`, containing metadata about the various field types on the model
including information about their relationships. |
337,785 | def delete(self, action, headers=None):
return self.request(make_url(self.endpoint, action), method=,
headers=headers) | Makes a GET request |
337,786 | def _sendMsg(self, msg):
if not self.sock:
self.connect()
if not isinstance(msg, binary_type):
msg = msg.encode("UTF-8")
backoff = 0.001
while True:
try:
self.sock.sendall(msg)
break
except socket.error:
log.warning(, exc_info = True)
self.di... | Send a line to graphite. Retry with exponential backoff. |
337,787 | def recover_dynamics(data, var_names=, max_iter=100, learning_rate=None, add_key=, t_max=None, use_raw=False,
min_loss=True, fix_scaling=None, load_pars=None, return_model=False, plot_results=False, copy=False, **kwargs):
adata = data.copy() if copy else data
logg.info(, r=True)
i... | Estimates velocities in a gene-specific manner
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
Returns
-------
Returns or updates `adata` |
337,788 | def power_on(self, context, ports):
return self._power_command(context, ports, self.vm_power_management_command.power_on) | Powers on the remote vm
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! |
337,789 | def _slice(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs,
{ : ,
: ,
: })
begin = new_attrs... | Returns a slice of the input tensor along multiple axes. |
337,790 | def _compile_rules(self):
for state, table in self.RULES.items():
patterns = list()
actions = list()
nextstates = list()
for i, row in enumerate(table):
if len(row) == 2:
pattern, _action = row
nexts... | Compile the rules into the internal lexer state. |
337,791 | def write_iso19115_metadata(layer_uri, keywords, version_35=False):
active_metadata_classes = METADATA_CLASSES
if version_35:
active_metadata_classes = METADATA_CLASSES35
if in keywords:
if keywords[] in active_metadata_classes:
metadata = active_metadata_classes[
... | Create metadata object from a layer path and keywords dictionary.
This function will save these keywords to the file system or the database.
:param version_35: If we write keywords version 3.5. Default to False.
:type version_35: bool
:param layer_uri: Uri to layer.
:type layer_uri: basestring
... |
337,792 | def _overwrite(self, n):
if os.path.isfile(n[:-4]):
shutil.copy2(n[:-4], n[:-4] + ".old")
print("Old file {0} saved as {1}.old".format(
n[:-4].split("/")[-1], n[:-4].split("/")[-1]))
if os.path.isfile(n):
shutil.move(n, n[:-4])
pri... | Overwrite old file with new and keep file with suffix .old |
337,793 | def handle_multiple_callers(data, key, default=None, require_bam=True):
callers = get_variantcaller(data, key, default, require_bam=require_bam)
if isinstance(callers, six.string_types):
return [data]
elif not callers:
return []
else:
out = []
for caller in callers:
... | Split samples that potentially require multiple variant calling approaches. |
337,794 | def to_str(obj, encoding=, **encode_args):
r
if isinstance(obj, binary_type):
return obj
if isinstance(obj, text_type) or hasattr(obj, text_type_magicmethod):
return text_type(obj).encode(encoding, **encode_args)
return binary_type(obj) | r"""
Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For
example::
>>> some_str = b"\xff"
>>> some_unicode = u"\u1234"
>>> some_exception = Exception(u'Error: ' + some_unicode)
>>> r(to_str(some_str))
b'\xff'
>>> r(to_str(some_unicode))
... |
337,795 | def featureclass_to_json(fc):
if arcpyFound == False:
raise Exception("ArcPy is required to use this function")
desc = arcpy.Describe(fc)
if desc.dataType == "Table" or desc.dataType == "TableView":
return recordset_to_json(table=fc)
else:
return arcpy.FeatureSet(fc).JSON | converts a feature class to JSON |
337,796 | def _prompt_finished_hook(self):
self._input_splitter.reset()
if not self._reading:
self._highlighter.highlighting_on = False | Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed. |
337,797 | def install_host(trg_queue, *hosts, **kwargs):
user = kwargs.pop(, None)
group = kwargs.pop(, None)
mode = kwargs.pop(, None)
item_user = kwargs.pop(, None)
item_group = kwargs.pop(, None)
item_mode = kwargs.pop(, None)
is_down = kwargs.pop(, False)
mode, user, group, item_use... | Atomically install host queues |
337,798 | def blobs(shape: List[int], porosity: float = 0.5, blobiness: int = 1):
blobiness = sp.array(blobiness)
shape = sp.array(shape)
if sp.size(shape) == 1:
shape = sp.full((3, ), int(shape))
sigma = sp.mean(shape)/(40*blobiness)
im = sp.random.random(shape)
im = spim.gaussian_filter(im,... | Generates an image containing amorphous blobs
Parameters
----------
shape : list
The size of the image to generate in [Nx, Ny, Nz] where N is the
number of voxels
porosity : float
If specified, this will threshold the image to the specified value
prior to returning. If... |
337,799 | def ecs_tag_normalize(resources):
for r in resources:
if in r:
r[] = [{: t[], : t[]} for t in r[]]
r.pop() | normalize tag format on ecs resources to match common aws format. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.