Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
354,500 | def _check_fix_Q(self, fixed_mu=False):
self.Pi /= self.Pi.sum()
self.W += self.break_degen + self.break_degen.T
np.fill_diagonal(self.W, 0)
Wdiag = -(self.Q).sum(axis=0)/self.Pi
np.fill_diagonal(self.W, Wdiag)
scale_factor = -np.sum(n... | Check the main diagonal of Q and fix it in case it does not corresond
the definition of the rate matrix. Should be run every time when creating
custom GTR model. |
354,501 | def render_cheetah_tmpl(tmplstr, context, tmplpath=None):
from Cheetah.Template import Template
return salt.utils.data.decode(Template(tmplstr, searchList=[context])) | Render a Cheetah template. |
354,502 | def getReffs(self, textId, level=1, subreference=None):
passage, inventory = self.__getText__(textId)
if subreference:
passage = passage.getTextualNode(subreference)
return passage.getReffs(level=level, subreference=subreference) | Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:type textId: str
:param level: Depth for retrieval
:type level: int
:param subreference: CapitainsCtsPassage CtsReference
:type subreference: str
:return: List of references
... |
354,503 | def _galaxy_tool_copy(finfo, outputs):
tool_map = {"align": "bam", "variants": "vcf.gz"}
for galaxy_key, finfo_type in tool_map.items():
if galaxy_key in outputs and finfo.get("type") == finfo_type:
shutil.copy(finfo["path"], outputs[galaxy_key]) | Copy information directly to pre-defined outputs from a Galaxy tool.
XXX Needs generalization |
354,504 | def invert(dict_):
result = defaultdict(lambda: set())
for k, val in dict_.items():
result[val].add(k)
return dict(result) | Invert dict by swapping each value with its key.
Parameters
----------
dict_ : ~typing.Dict[~typing.Hashable, ~typing.Hashable]
Dict to invert.
Returns
-------
~typing.Dict[~typing.Hashable, ~typing.Set[~typing.Hashable]]
Dict with keys and values swapped.
See also
---... |
354,505 | def request_vpc_peering_connection(name, requester_vpc_id=None, requester_vpc_name=None,
peer_vpc_id=None, peer_vpc_name=None, conn_name=None,
peer_owner_id=None, peer_region=None, region=None,
key=None, keyid=None,... | name
Name of the state
requester_vpc_id
ID of the requesting VPC. Exclusive with requester_vpc_name. String type.
requester_vpc_name
Name tag of the requesting VPC. Exclusive with requester_vpc_id. String type.
peer_vpc_id
ID of the VPC tp crete VPC peering connection wi... |
354,506 | def _initialize(self):
if not os.path.exists(self._logdir):
raise CollectorError("Log directory %s not exists" % self._logdir)
self.logger.info("Collector started, taking %s as parent directory"
"for all job logs." % self._logdir)
JobRecor... | Initialize collector worker thread, Log path will be checked first.
Records in DB backend will be cleared. |
354,507 | def add_override(self, symbol, ind, val, dt_log=None, user=None, comment=None):
self._add_orfs(, symbol, ind, val, dt_log, user, comment) | Appends a single indexed-value pair, to a symbol object, to be
used during the final steps of the aggregation of the datatable.
With default settings Overrides, get applied with highest priority.
Parameters
----------
symbol : Symbol or str
The Symbo... |
354,508 | def AUNP_calc(classes, P, POP, AUC_dict):
try:
result = 0
for i in classes:
result += (P[i] / POP[i]) * AUC_dict[i]
return result
except Exception:
return "None" | Calculate AUNP.
:param classes: classes
:type classes : list
:param P: condition positive
:type P : dict
:param POP: population
:type POP : dict
:param AUC_dict: AUC (Area under the ROC curve) for each class
:type AUC_dict : dict
:return: AUNP as float |
354,509 | def read(self, line, f, data):
N = len(data["symbols"])
masses = np.zeros(N, float)
counter = 0
while counter < N:
words = f.readline().split()
for word in words:
masses[counter] = float(word)*amu
counter += 1
data[... | See :meth:`PunchParser.read` |
354,510 | def iperf_version(self):
VersionType = c_char * 30
return VersionType.in_dll(self.lib, "version").value.decode() | Returns the version of the libiperf library
:rtype: string |
354,511 | def warningFailure(self, failure, swallow=True):
if _canShortcutLogging(self.logCategory, WARN):
if swallow:
return
return failure
warningObject(self.logObjectName(), self.logCategory,
*self.logFunction(getFailureMessage(failure)))
if ... | Log a warning about a Twisted Failure. Useful as an errback handler:
d.addErrback(self.warningFailure)
@param swallow: whether to swallow the failure or not
@type swallow: bool |
354,512 | def generate_steady_rt_pic(process_data, para_meter, scale, steady_time):
pic_path_steady = para_meter[] +
plt.figure(figsize=(4 * scale, 2.5 * scale))
for key in process_data.keys():
if len(process_data[key]) < steady_time:
steady_time = len(process_data[key])
plt.s... | generate rate steady |
354,513 | def assemble(self, blueprint, quota):
blueprint.reset()
documents = []
for i in range(0, int(quota)):
documents.append(blueprint.assemble())
return documents | Assemble a quota of documents |
354,514 | def _get_uptime(self, app_stats):
if "program_start" not in app_stats.keys():
return 0
if not app_stats["program_start"].isdigit():
return 0
uptime = int(time.time()) - int(app_stats["program_start"])
if uptime < 0:
return 0
return ... | Return Icinga's uptime |
354,515 | def blockUser(self, user_id):
data = {"fbid": user_id}
r = self._post(self.req_url.BLOCK_USER, data)
return r.ok | Blocks messages from a specifed user
:param user_id: The ID of the user that you want to block
:return: Whether the request was successful
:raises: FBchatException if request failed |
354,516 | def propose(self):
prop_dist = self.proposal_distribution.lower()
if prop_dist == "normal":
self.stochastic.value = rnormal(
self.stochastic.value,
self.adaptive_scale_factor *
self.proposal_sd,
size=self.stochast... | This method is called by step() to generate proposed values
if self.proposal_distribution is "Normal" (i.e. no proposal specified). |
354,517 | def merge_accounts(self, request):
try:
netid = NetID.objects.get(identity=self.identity, provider=self.provider)
except NetID.DoesNotExist:
netid = NetID(user=request.user, identity=self.identity, provider=self.provider)
netid.save()
... | Attach NetID account to regular django
account and then redirect user. In this situation
user dont have to fill extra fields because he filled
them when first account (request.user) was created.
Note that self.indentity must be already set in this stage by
validate_response func... |
354,518 | def write_neurommsig_bel(file,
df: pd.DataFrame,
disease: str,
nift_values: Mapping[str, str],
):
write_neurommsig_biolerplate(disease, file)
missing_features = set()
fixed_caps = set()
nift_value_o... | Writes the NeuroMMSigDB excel sheet to BEL
:param file: a file or file-like that can be writen to
:param df:
:param disease:
:param nift_values: a dictionary of lowercased to normal names in NIFT |
354,519 | def image_to_base64(self, image):
if isinstance(image, file_):
return base64.b64encode(image.read())
elif isinstance(image, basestring):
if image.startswith("http"):
with open(image) as f:
return base64.b64encode(f.read())
... | :param image: One of file object, path, or URL
:return: Base64 of image |
354,520 | def _init_required_options(self, **kwargs):
for field in self.required_options:
setattr(self, field, kwargs.get(field))
self._store_option(field) | Initialize the required option as class members. The value will be
either None or the specified value in the kwargs or __init__. The logic
here is to make the required options accesible to edit after a class
instance has been created. |
354,521 | def check_connection (self):
for mail in sorted(self.addresses):
self.check_smtp_domain(mail)
if not self.valid:
break | Verify a list of email addresses. If one address fails,
the whole list will fail.
For each mail address the MX DNS records are found.
If no MX records are found, print a warning and try
to look for A DNS records. If no A records are found either
print an error. |
354,522 | def check(self, group_id, session):
request = TOPRequest()
request[] = group_id
self.create(self.execute(request, session))
return self.is_finished | taobao.crm.grouptask.check 查询分组任务是否完成
检查一个分组上是否有异步任务,异步任务包括
- 1.将一个分组下的所有用户添加到另外一个分组
- 2.将一个分组下的所有用户移动到另外一个分组
- 3.删除某个分组 若分组上有任务则该属性不能被操作。 |
354,523 | def _parse_multi_byte(self, s):
assert(len(s) >= 2)
tmp_len = len(s)
value = 0
i = 1
byte = orb(s[i])
max_value = 1 << 64
while byte & 0x80:
value += (byte ^ 0x80) << (7 * (i - 1))
if value > max_value... | _parse_multi_byte parses x as a multibyte representation to get the
int value of this AbstractUVarIntField.
@param str s: the multibyte string to parse.
@return int: The parsed int value represented by this AbstractUVarIntField. # noqa: E501
@raise: AssertionError
@raise: Sca... |
354,524 | def create_db(data, dbfn, id_spec=None, force=False, verbose=False,
checklines=10, merge_strategy=, transform=None,
gtf_transcript_key=, gtf_gene_key=,
gtf_subfeature=, force_gff=False,
force_dialect_check=False, from_string=False, keep_order=False,
... | Create a database from a GFF or GTF file.
For more details on when and how to use the kwargs below, see the examples
in the online documentation (:ref:`examples`).
Parameters
----------
data : string or iterable
If a string (and `from_string` is False), then `data` is the path to
... |
354,525 | def get_arguments(self):
self._configure_logging()
if self.args.api_host is not None:
self._api_host = self.args.api_host
if self.args.email is not None:
self._email = self.args.email
if self.args.api_token is not None:
sel... | CLIs get called back so that they can process any command line arguments
that are given. This method handles the standard command line arguments for:
API Host, user, password, etc. |
354,526 | def matches(self, pattern):
return ArrayPredicate(
term=self,
op=LabelArray.matches,
opargs=(pattern,),
) | Construct a Filter that checks regex matches against ``pattern``.
Parameters
----------
pattern : str
Regex pattern against which to compare values produced by ``self``.
Returns
-------
matches : Filter
Filter returning True for all sid/date pair... |
354,527 | def copy(self, resource_view):
if isinstance(resource_view, str):
if is_valid_uuid(resource_view) is False:
raise HDXError( % resource_view)
resource_view = ResourceView.read_from_hdx(resource_view)
if not isinstance(resource_view, dict) and not ... | Copies all fields except id, resource_id and package_id from another resource view.
Args:
resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ResourceView object or a dictionary
Returns:
None |
354,528 | def generate(self, projectpath, parameters, serviceid, servicename,serviceurl):
parameters = sanitizeparameters(parameters)
program = Program(projectpath, [self])
match, optional_absent = self.match(projectpath, parameters)
if match:
input... | Generate output metadata on the basis of input files and parameters. Projectpath must be absolute. Returns a Program instance. |
354,529 | def _bond_length_low(r, deriv):
r = Vector3(3, deriv, r, (0, 1, 2))
d = r.norm()
return d.results() | Similar to bond_length, but with a relative vector |
354,530 | def _get_part(pointlist, strokes):
result = []
strokes = sorted(strokes)
for stroke_index in strokes:
result.append(pointlist[stroke_index])
return result | Get some strokes of pointlist
Parameters
----------
pointlist : list of lists of dicts
strokes : list of integers
Returns
-------
list of lists of dicts |
354,531 | def generateProjectFiles(self, dir=os.getcwd(), args=[]):
if os.path.exists(os.path.join(dir, )) == False:
Utility.printStderr()
return
genScript = self.getGenerateScript()
projectFile = self.getProjectDescriptor(dir)
Utility.run([genScript, + projectFile, , ] + args, cwd=os.path.dirname(g... | Generates IDE project files for the Unreal project in the specified directory |
354,532 | def validate(self, request, value):
if self.required and value == DEFAULT_FIELD_VALUE:
return ValidationResult(is_success=False,
reason=)
if not self.nullable and value is None:
return ValidationResult(is_success=False,
... | This is not for business validation
This should be only used for type validation
Hence the only input is the value of the field
:param value:
:return: |
354,533 | def next(self):
if self.iter_next():
if self.is_train:
data_raw_list = self.getdata()
data_shifted = []
for data_raw in data_raw_list[0]:
data_shifted.append(random_shift(data_raw.asnumpy(), 0.1, 0.1))
retur... | Generate next of iterator |
354,534 | def remove(self, payload):
succeeded = []
failed = []
for key in payload[]:
running = self.process_handler.is_running(key)
if not running:
removed = self.queue.remove(key)
if removed:
succeeded.append(str(key))
... | Remove specified entries from the queue. |
354,535 | def _get_text_sequence(self, text, span, context_length):
start = max(0, span[0] - context_length)
end = min(len(text), span[1] + context_length)
return text[start:end], (start, end) | Returns the subset of `text` encompassed by `span`, plus
`context_length` characters before and after.
:param text: text to extract the sequence from
:type text: `str`
:param span: start and end indices within `text`
:type span: 2-`tuple` of `int`
:param context_length: ... |
354,536 | def clear_break(
self, filename, lineno=None, temporary=False, cond=None,
funcname=None
):
log.info(
%
(filename, lineno, temporary, cond, funcname)
)
breakpoint = self.get_break(
filename, lineno, temporary or False, con... | Remove a breakpoint |
354,537 | def _checkAttribs(self, strict):
if self.choice:
warning("Choice values not allowed for real-type parameter " +
self.name, strict)
self.choice = None | Check initial attributes to make sure they are legal |
354,538 | def set_expire(self, y = 2999, mon = 12, d = 28, h = 23, min_ = 59,
s = 59):
if type(y) is not int or type(mon) is not int or type(d) is not int or \
type(h) is not int or type(min_) is not int or type(s) is not int:
raise KPError("Date variables must be int... | This method is used to change the expire date of a group
- y is the year between 1 and 9999 inclusive
- mon is the month between 1 and 12
- d is a day in the given month
- h is a hour between 0 and 23
- min_ is a minute between 0 and 59
- s is a s... |
354,539 | def get_license_assignment_manager(service_instance):
log.debug()
try:
lic_assignment_manager = \
service_instance.content.licenseManager.licenseAssignmentManager
except vim.fault.NoPermission as exc:
log.exception(exc)
raise salt.exceptions.VMwareApiError(
... | Returns the license assignment manager.
service_instance
The Service Instance Object from which to obrain the license manager. |
354,540 | def impulse_response(genrate, fresponse, frequencies, frange, filter_len=2 ** 14, db=True):
freq = frequencies
max_freq = genrate / 2 + 1
attenuations = np.zeros_like(fresponse)
winsz = 0.05
lowf = max(0, frange[0] - (frange[1] - frange[0]) * winsz)
highf = min(frequencies[-1], fra... | Calculate filter kernel from attenuation vector.
Attenuation vector should represent magnitude frequency response of system
:param genrate: The generation samplerate at which the test signal was played
:type genrate: int
:param fresponse: Frequency response of the system in dB, i.e. relative attenu... |
354,541 | def _send(saltdata, metric_base, opts):
host = opts.get()
port = opts.get()
skip = opts.get()
metric_base_pattern = opts.get()
mode = opts.get().lower() if in opts else
log.debug(, host, port)
log.debug(, mode)
if not (host and port):
log.error()
return
... | Send the data to carbon |
354,542 | def b64decode_url(istr):
istr = encode_safe(istr)
try:
return urlsafe_b64decode(istr + * (4 - (len(istr) % 4)))
except TypeError as e:
raise Error( % (e)) | JWT Tokens may be truncated without the usual trailing padding '='
symbols. Compensate by padding to the nearest 4 bytes. |
354,543 | def close(self):
if not self._connected.is_set():
raise exceptions.ConnectionError()
self._closing = True
if self._clustering:
for host in self._cluster.keys():
self._cluster[host].close()
elif self._connection:
self._connectio... | Close any open connections to Redis.
:raises: :exc:`tredis.exceptions.ConnectionError` |
354,544 | def get(key, default=-1):
if isinstance(key, int):
return OptionClass(key)
if key not in OptionClass._member_map_:
extend_enum(OptionClass, key, default)
return OptionClass[key] | Backport support for original codes. |
354,545 | def __buttonEvent(event):
global boxRoot, __widgetTexts, __replyButtonText
__replyButtonText = __widgetTexts[event.widget]
boxRoot.quit() | Handle an event that is generated by a person clicking a button. |
354,546 | def _internal_add_node(self,
node_name: str,
external_id: Optional[str] = None,
are_neighbors_cached: bool = False,
add_to_cache: bool = False) -> None:
index: int = len(self)
node... | Adds a node with the given name to the graph without checking whether it already exists or not.
Arguments:
node_name (str): The name of the node to add.
external_id (Optional[str]): The external ID of the node.
are_neighbors_cached (bool): Whether the neighbors of the n... |
354,547 | def _post_xml(self, *args, **kwargs):
if not in kwargs:
kwargs[] = self.timeout
req = self.session_xml.post(*args, **kwargs)
return req | Wrapper around Requests for POST requests
Returns:
Response:
A Requests Response object |
354,548 | def min(self):
if "min" not in self.attrs.keys():
def f(dataset, s):
return np.nanmin(dataset[s])
self.attrs["min"] = np.nanmin(list(self.chunkwise(f).values()))
return self.attrs["min"] | Minimum, ignoring nans. |
354,549 | def as_dict(self):
odict = OrderedDict()
for name in self._order:
attr_value = getattr(self, name)
if isinstance(attr_value, List):
_list = []
for item in attr_value:
_list.append((item.as_dict() if isinstance(item, Ent... | create a dict based on class attributes |
354,550 | def _get_slave_status(self, db, above_560, nonblocking):
try:
with closing(db.cursor()) as cursor:
if above_560 and nonblocking:
cursor.execute("SELECT THREAD_ID, NAME FROM performance_schema.threads WHERE NAME LI... | Retrieve the slaves' statuses using:
1. The `performance_schema.threads` table. Non-blocking, requires version > 5.6.0
2. The `information_schema.processlist` table. Blocking |
354,551 | def get_response_time(chatbot, statement=):
import time
start_time = time.time()
chatbot.get_response(statement)
return time.time() - start_time | Returns the amount of time taken for a given
chat bot to return a response.
:param chatbot: A chat bot instance.
:type chatbot: ChatBot
:returns: The response time in seconds.
:rtype: float |
354,552 | def maybe_key_vault(client, mount_path):
d = client.read_kv2(, mount_path=mount_path)
def get_or_create_key(client_key):
if client_key is not None:
key_data = client_key[][]
key = _load_pem_private_key_bytes(key_data[].encode())
return JWKRSA(key=key)
el... | Set up a client key in Vault if one does not exist already.
:param client:
The Vault API client to use.
:param mount_path:
The Vault key/value mount path to use.
:rtype: twisted.internet.defer.Deferred |
354,553 | def remove_nonancestors_of(self, node):
if isinstance(node, int):
warnings.warn(
,
DeprecationWarning, 2)
node = self._id_to_node[node]
anc = nx.ancestors(self._multi_graph, node)
comp = list(set(self._multi_gr... | Remove all of the non-ancestors operation nodes of node. |
354,554 | def unpack_weights(self, args):
args = args.copy()
if not self._gate_names:
return args
h = self._num_hidden
for group_name in [, ]:
weight = args.pop(%(self._prefix, group_name))
bias = args.pop( % (self._prefix, group_name))
for ... | Unpack fused weight matrices into separate
weight matrices.
For example, say you use a module object `mod` to run a network that has an lstm cell.
In `mod.get_params()[0]`, the lstm parameters are all represented as a single big vector.
`cell.unpack_weights(mod.get_params()[0])` will un... |
354,555 | def collect(self):
logger.debug("Collecting metrics")
for name, metricset in compat.iteritems(self._metricsets):
data = metricset.collect()
if data:
self._queue_func(constants.METRICSET, data) | Collect metrics from all registered metric sets
:return: |
354,556 | def validate_account_id(sts_client, account_id):
resp = sts_client.get_caller_identity()
if in resp:
if resp[] == account_id:
LOGGER.info(
,
account_id)
else:
LOGGER.error(
,
... | Exit if get_caller_identity doesn't match account_id. |
354,557 | def equivalent_diameter(target, pore_volume=,
pore_shape=):
r
from scipy.special import cbrt
pore_vols = target[pore_volume]
if pore_shape.startswith():
value = cbrt(6*pore_vols/_np.pi)
elif pore_shape.startswith():
value = cbrt(pore_vols)
return value | r"""
Calculates the diameter of a sphere or edge-length of a cube with same
volume as the pore.
Parameters
----------
target : OpenPNM Geometry Object
The Geometry object which this model is associated with. This controls
the length of the calculated array, and also provides access ... |
354,558 | def find_biconnected_components_as_subgraphs(graph):
list_of_graphs = []
list_of_components = find_biconnected_components(graph)
for edge_list in list_of_components:
subgraph = get_subgraph_from_edge_list(graph, edge_list)
list_of_graphs.append(subgraph)
return list_of_graphs | Finds the biconnected components and returns them as subgraphs. |
354,559 | def query_parameters(self):
result = getattr(self, "_query_parameters", None)
if result is None:
result = self._query_parameters = normalize_query_parameters(
self.query_string)
return result | A key to list of values mapping of the query parameters seen in the
request. |
354,560 | def distort(value):
value = value.lower()
if (RandomBoolean.chance(1, 5)):
value = value[0:1].upper() + value[1:]
if (RandomBoolean.chance(1, 3)):
value = value + random.choice(_symbols)
return value | Distorts a string by randomly replacing characters in it.
:param value: a string to distort.
:return: a distored string. |
354,561 | def build_query(spec):
query = model.Entry.select()
if spec.get(, False):
query = where_entry_deleted(query)
elif spec.get(, False):
query = where_entry_visible_future(query)
else:
query = where_entry_visible(query)
if spec.get() is not None:
path = ... | build the where clause based on a view specification
spec -- The view specification. Contains the following possible values:
future -- Boolean; whether to include entries from the future
category -- Which category to limit to
recurse -- Whether to include subcategories
entry_type --... |
354,562 | def is_descriptor_class(desc, include_abstract=False):
r
return (
isinstance(desc, type)
and issubclass(desc, Descriptor)
and (True if include_abstract else not inspect.isabstract(desc))
) | r"""Check calculatable descriptor class or not.
Returns:
bool |
354,563 | def incomplete(test_func):
if not isinstance(test_func, (type, ClassObjType)):
@functools.wraps(test_func)
def skip_wrapper(*args, **kwargs):
raise TestIncompleteException(test_func, _())
return skip_wrapper | The incomplete decorator behaves much like a normal skip; however,
tests that are marked as incomplete get tracked under a different metric.
This allows for you to create a skeleton around all of your features and
specifications, and track what tests have been written and what
tests are left outstanding... |
354,564 | def get_property_by_hash(self, property_hash: str) -> Optional[Property]:
return self.session.query(Property).filter(Property.sha512 == property_hash).one_or_none() | Get a property by its hash if it exists. |
354,565 | def _fix_slicing_order(self, outer_fields, inner_select, order, inner_table_name):
if order is None:
meta = self.query.get_meta()
column = meta.pk.db_column or meta.pk.get_attname()
order = .format(
inner_table_name,
self.conn... | Apply any necessary fixes to the outer_fields, inner_select, and order
strings due to slicing. |
354,566 | def check_siblings(self, individual_1_id, individual_2_id):
self.logger.debug("Checking if {0} and {1} are siblings".format(
individual_1_id, individual_2_id
))
ind_1 = self.individuals[individual_1_id]
ind_2 = self.individuals[individual_2_id]
if ((... | Check if two family members are siblings.
Arguments:
individual_1_id (str): The id of an individual
individual_2_id (str): The id of an individual
Returns:
bool : True if the individuals are siblings
False if they are not sibling... |
354,567 | def load(self):
payload = {
: self.id
}
response = self.lc.session.get(, query=payload)
self.response = response
json_response = response.json()
if self.lc.session.json_success(json_response) and json_response[] != :
self.name =... | Load the filter from the server |
354,568 | def _get_per_location_glob(tasks, outputs, regexes):
paths = [o.path for o in outputs]
matches = [r.search(p) for r, p in zip(regexes, paths)]
for m, p, t in zip(matches, paths, tasks):
if m is None:
raise NotImplementedError("Couldns the same for all paths
for start,... | Builds a glob listing existing output paths.
Esoteric reverse engineering, but worth it given that (compared to an
equivalent contiguousness guarantee by naive complete() checks)
requests to the filesystem are cut by orders of magnitude, and users
don't even have to retrofit existing tasks anyhow. |
354,569 | def _get_stream_id(comp_name, stream_id):
proto_stream_id = topology_pb2.StreamId()
proto_stream_id.id = stream_id
proto_stream_id.component_name = comp_name
return proto_stream_id | Returns a StreamId protobuf message |
354,570 | def post_fork_child(self, fingerprint, jvm_options, classpath, stdout, stderr):
java = SubprocessExecutor(self._distribution)
subproc = java.spawn(classpath=classpath,
main=,
jvm_options=jvm_options,
args=[],
... | Post-fork() child callback for ProcessManager.daemon_spawn(). |
354,571 | def save_xml(self, doc, element):
new_element = doc.createElementNS(RTS_NS, RTS_NS_S + )
self.target_component.save_xml(doc, new_element)
element.appendChild(new_element) | Save this participant into an xml.dom.Element object. |
354,572 | def remove_entry(data, entry):
file_field = entry[].get()
if file_field:
try:
os.remove(file_field)
except IOError:
click.echo(s file was missing')
data.remove(entry) | Remove an entry in place. |
354,573 | def _actionsFreqsAngles(self,*args,**kwargs):
if len(args) == 5:
raise IOError("You need to provide phi when calculating angles")
elif len(args) == 6:
R,vR,vT, z, vz, phi= args
else:
self._parse_eval_args(*args)
R= self._eval_R
... | NAME:
actionsFreqsAngles (_actionsFreqsAngles)
PURPOSE:
evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez)
INPUT:
Either:
a) R,vR,vT,z,vz[,phi]:
1) floats: phase-space value for single obj... |
354,574 | def lv_present(name,
vgname=None,
size=None,
extents=None,
snapshot=None,
pv=,
thinvolume=False,
thinpool=False,
force=False,
**kwargs):
ret = {: {},
: ,
... | Create a new Logical Volume
name
The name of the Logical Volume
vgname
The name of the Volume Group on which the Logical Volume resides
size
The initial size of the Logical Volume
extents
The number of logical extents to allocate
snapshot
The name of the ... |
354,575 | def pack_balance_proof_update(
nonce: Nonce,
balance_hash: BalanceHash,
additional_hash: AdditionalHash,
canonical_identifier: CanonicalIdentifier,
partner_signature: Signature,
) -> bytes:
return pack_balance_proof(
nonce=nonce,
balance_hash=balance_hash... | Packs balance proof data to be signed for updateNonClosingBalanceProof
Packs the given arguments in a byte array in the same configuration the
contracts expect the signed data for updateNonClosingBalanceProof to have. |
354,576 | def sentences(obj: BioCCollection or BioCDocument or BioCPassage) \
-> Generator[BioCSentence, None, None]:
if isinstance(obj, BioCCollection):
for document in obj.documents:
yield from sentences(document)
elif isinstance(obj, BioCDocument):
for passage in obj.pas... | Get all sentences in document id.
Args:
obj: BioCCollection, BioCDocument, or BioCPassage
Yields:
one sentence |
354,577 | def real_main(release_url=None,
tests_json_path=None,
upload_build_id=None,
upload_release_name=None):
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
data = open(FLAGS.tests_json_path).read()
tests = load... | Runs diff_my_images. |
354,578 | def do_continue(self, args):
self._do_print_from_last_cmd = True
self._interp.cont()
return True | Continue the interpreter |
354,579 | def queue_build(self, build, project, ignore_warnings=None, check_in_ticket=None, source_build_id=None):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
query_parameters = {}
if ignore_warnings is not None:
quer... | QueueBuild.
Queues a build
:param :class:`<Build> <azure.devops.v5_0.build.models.Build>` build:
:param str project: Project ID or project name
:param bool ignore_warnings:
:param str check_in_ticket:
:param int source_build_id:
:rtype: :class:`<Build> <azure.devo... |
354,580 | def __write_divider(self, top=False, bot=False, nl=True):
if top:
self.noaa_txt += "\n
if nl:
self.noaa_txt += "\n"
self.noaa_txt += "
if bot:
self.noaa_txt += "\n
return | Write a divider line
:return none: |
354,581 | def load_mask(image, allow_empty=True):
img = check_img(image, make_it_3d=True)
values = np.unique(img.get_data())
if len(values) == 1:
if values[0] == 0 and not allow_empty:
raise ValueError()
elif len(values) == 2:
if 0 not in values:
... | Load a Nifti mask volume.
Parameters
----------
image: img-like object or boyle.nifti.NeuroImage or str
Can either be:
- a file path to a Nifti image
- any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image.
If niimg is a string, consider it as a path... |
354,582 | def refresh(self):
search_string = Software\ \
Driver\
searcher = self._session.CreateUpdateSearcher()
self._session.ClientApplicationID =
try:
results = searcher.Search(search_string)
if results.Updat... | Refresh the contents of the ``_updates`` collection. This gets all
updates in the Windows Update system and loads them into the collection.
This is the part that is slow.
Code Example:
.. code-block:: python
import salt.utils.win_update
wua = salt.utils.win_upd... |
354,583 | def probabilities(self, choosers, alternatives):
logger.debug(
.format(
self.name))
choosers, alternatives = self.apply_predict_filters(
choosers, alternatives)
result = self._group.probabilities(choosers, alternatives)
logger.debug(
... | Returns alternative probabilties for each chooser segment as
a dictionary keyed by segment name.
Parameters
----------
choosers : pandas.DataFrame
Table describing the agents making choices, e.g. households.
Must have a column matching the .segmentation_col attri... |
354,584 | def computeEntropy(spikeTrains):
MIN_ACTIVATION_PROB = 0.000001
activationProb = np.mean(spikeTrains, 1)
activationProb[activationProb < MIN_ACTIVATION_PROB] = MIN_ACTIVATION_PROB
activationProb = activationProb / np.sum(activationProb)
entropy = -np.dot(activationProb, np.log2(activationProb))
return en... | Estimates entropy in spike trains.
@param spikeTrains (array) matrix of spike trains
@return entropy (float) entropy |
354,585 | def get_pod_by_uid(uid, podlist):
for pod in podlist.get("items", []):
try:
if pod["metadata"]["uid"] == uid:
return pod
except KeyError:
continue
return None | Searches for a pod uid in the podlist and returns the pod if found
:param uid: pod uid
:param podlist: podlist dict object
:return: pod dict object if found, None if not found |
354,586 | def get_kwargs(self):
kwargs = {}
if self.font_face:
kwargs["fontname"] = repr(self.font_face)
if self.font_size:
kwargs["fontsize"] = repr(self.font_size)
if self.font_style in self.style_wx2mpl:
kwargs["fontstyle"] = repr(self.style_wx2mpl... | Return kwargs dict for text |
354,587 | def warn_attribs(loc,
node,
recognised_attribs,
reqd_attribs=None):
if reqd_attribs is None:
reqd_attribs = recognised_attribs
found_attribs = set(node.keys())
if reqd_attribs - found_attribs:
print(loc, .format(node.tag),
... | Error checking of XML input: check that the given node has certain
required attributes, and does not have any unrecognised
attributes.
Arguments:
- `loc`: a string with some information about the location of the
error in the XML file
- `node`: the node to check
- `recognised_attribs`: a s... |
354,588 | def mechanism(self, x):
layers = []
layers.append(th.nn.modules.Linear(self.n_causes+1, self.nh))
layers.append(th.nn.Tanh())
layers.append(th.nn.modules.Linear(self.nh, 1))
self.layers = th.nn.Sequential(*layers)
data = x.astype()
data = th.from_numpy... | Mechanism function. |
354,589 | def appendcsv(table, source=None, encoding=None, errors=,
write_header=False, **csvargs):
source = write_source_from_arg(source)
csvargs.setdefault(, )
appendcsv_impl(table, source=source, encoding=encoding, errors=errors,
write_header=write_header, **csvargs) | Append data rows to an existing CSV file. As :func:`petl.io.csv.tocsv`
but the file is opened in append mode and the table header is not written by
default.
Note that no attempt is made to check that the fields or row lengths are
consistent with the existing data, the data rows from the table are simpl... |
354,590 | def setup_contracts_or_exit(
config: Dict[str, Any],
network_id: int,
) -> Dict[str, Any]:
environment_type = config[]
not_allowed = (
network_id == 1 and
environment_type == Environment.DEVELOPMENT
)
if not_allowed:
click.secho(
f
... | Sets the contract deployment data depending on the network id and environment type
If an invalid combination of network id and environment type is provided, exits
the program with an error |
354,591 | def showEvent(self, event):
super(CompletionWidget, self).showEvent(event)
self._text_edit.cursorPositionChanged.connect(self._update_current)
self._text_edit.installEventFilter(self) | Reimplemented to connect signal handlers and event filter. |
354,592 | def format_diffindex(diff_index):
for diff in diff_index:
if diff.new_file:
yield format_diff_A(diff)
elif diff.deleted_file:
yield format_diff_D(diff)
elif diff.renamed:
yield format_diff_R(diff)
elif diff.a_blob and diff.b_blob and diff.a_bl... | Return a JSON formattable representation of a DiffIndex.
Returns a generator that returns dictionaries representing the changes.
.. code::
[
{
'type': 'A',
'path': 'path/to/added/file.txt',
},
{
'type': 'D',
... |
354,593 | def get_child(self, child_number, is_prime=None, as_private=True):
boundary = 0x80000000
if abs(child_number) >= boundary:
raise ValueError("Invalid child number %s" % child_number)
private_exponent = (
(long_or_i... | Derive a child key.
:param child_number: The number of the child key to compute
:type child_number: int
:param is_prime: If True, the child is calculated via private
derivation. If False, then public derivation is used. If None,
then it is figured out from the value of c... |
354,594 | def _get_replica_set_members(self, selector):
with self._lock:
topology_type = self._description.topology_type
if topology_type not in (TOPOLOGY_TYPE.ReplicaSetWithPrimary,
TOPOLOGY_TYPE.ReplicaSetNoPrimary):
return s... | Return set of replica set member addresses. |
354,595 | def append(self, listname, xy_idx, var_name, element_name):
self.resize()
string =
if listname not in [, , , ]:
logger.error()
return
elif listname in [, ]:
string =
if isinstance(element_name, list):
for i, j in zip(xy_... | Append variable names to the name lists |
354,596 | def registerStatsHandler(app, serverName, prefix=):
if prefix[-1] != :
prefix +=
handler = functools.partial(statsHandler, serverName)
app.add_url_rule(prefix, , handler, methods=[])
app.add_url_rule(prefix + , , handler, methods=[]) | Register the stats handler with a Flask app, serving routes
with a given prefix. The prefix defaults to '/status/', which is
generally what you want. |
354,597 | def get_labels(self, request_data, project=None, top=None, skip=None):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
query_parameters = {}
if request_data is not None:
if request_data.label_scope is not None:
... | GetLabels.
Get a collection of shallow label references.
:param :class:`<TfvcLabelRequestData> <azure.devops.v5_0.tfvc.models.TfvcLabelRequestData>` request_data: labelScope, name, owner, and itemLabelFilter
:param str project: Project ID or project name
:param int top: Max number of lab... |
354,598 | def _initialize(self):
credentials = (self.username if self.username else ) + + (self.password if self.password else )
credentials = credentials.encode(self._encoding)
self._connection.send(credentials + b)
response = self._connection.recv(1)
if len(response) != 1:
... | Performs a IPC protocol handshake. |
354,599 | def set_bulk_size(size):
prev = ctypes.c_int()
check_call(_LIB.MXEngineSetBulkSize(
ctypes.c_int(size), ctypes.byref(prev)))
return prev.value | Set size limit on bulk execution.
Bulk execution bundles many operators to run together.
This can improve performance when running a lot of small
operators sequentially.
Parameters
----------
size : int
Maximum number of operators that can be bundled in a bulk.
Returns
-------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.