Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
5,900 | def add_final_state(self, f):
if f not in self.Q:
LOG.error("The specified value is invalid, f must be a member of Q")
raise InputError("The specified value is invalid, f must be a member of Q")
self.F.add(f) | :param f: int , the state qi to be added to F, epsilon is
conventionally defined as the last node (q_|S|) |
5,901 | def zipper(root_dir="", name="", path_name_ext=""):
logger_zips.info("re_zip: name: {}, dir_tmp: {}".format(path_name_ext, root_dir))
shutil.make_archive(path_name_ext, format=, root_dir=root_dir, base_dir=name)
os.rename("{}.zip".format(path_name_ext), path_name_ext)
return | Zips up directory back to the original location
:param str root_dir: Root directory of the archive
:param str name: <datasetname>.lpd
:param str path_name_ext: /path/to/filename.lpd |
5,902 | def _get_dependencies_of(name, location=None):
if not location:
detailed_dap_list = get_installed_daps_detailed()
if name not in detailed_dap_list:
return _get_api_dependencies_of(name)
location = detailed_dap_list[name][0][]
meta = .format(d=location, dap=name)
try... | Returns list of first level dependencies of the given installed dap
or dap from Dapi if not installed
If a location is specified, this only checks for dap installed in that path
and return [] if the dap is not located there |
5,903 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.element_pair is not None:
_dict[] = [x._to_dict() for x in self.element_pair]
if hasattr(self, ) and self.identical_text is not None:
_dict[] = self.identical_text
if hasattr(self, ) and self.prov... | Return a json dictionary representing this model. |
5,904 | def table_schema_call(self, target, cls):
index_defs = []
for name in cls.index_names() or []:
index_defs.append(GlobalIncludeIndex(
gsi_name(name),
parts=[HashKey(name)],
includes=[]
))
return target(
... | Perform a table schema call.
We call the callable target with the args and keywords needed for the
table defined by cls. This is how we centralize the Table.create and
Table ctor calls. |
5,905 | def find_state_op_colocation_error(graph, reported_tags=None):
state_op_types = list_registered_stateful_ops_without_inputs()
state_op_map = {op.name: op for op in graph.get_operations()
if op.type in state_op_types}
for op in state_op_map.values():
for colocation_group in op.colocation_g... | Returns error message for colocation of state ops, or None if ok. |
5,906 | def extract_geometry(dataset):
alg = vtk.vtkGeometryFilter()
alg.SetInputDataObject(dataset)
alg.Update()
return _get_output(alg) | Extract the outer surface of a volume or structured grid dataset as
PolyData. This will extract all 0D, 1D, and 2D cells producing the
boundary faces of the dataset. |
5,907 | def put(
self,
id,
name,
description,
private,
runs_executable_tasks,
runs_docker_container_tasks,
runs_singularity_container_tasks,
active,
whitelists,
):
request_url = self._client.base_api_url + self.detail_... | Updates a task queue on the saltant server.
Args:
id (int): The ID of the task queue.
name (str): The name of the task queue.
description (str): The description of the task queue.
private (bool): A Booleon signalling whether the queue can
only be ... |
5,908 | def registered(self, driver, executorInfo, frameworkInfo, agentInfo):
self.id = executorInfo.executor_id.get(, None)
log.debug("Registered executor %s with framework", self.id)
self.address = socket.gethostbyname(agentInfo.hostname)
nodeInfoThread = th... | Invoked once the executor driver has been able to successfully connect with Mesos. |
5,909 | def argument(self, argument_dest, arg_type=None, **kwargs):
self._check_stale()
if not self._applicable():
return
deprecate_action = self._handle_deprecations(argument_dest, **kwargs)
if deprecate_action:
kwargs[] = deprecate_action
self.command_... | Register an argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided kwargs.
... |
5,910 | def compute_metrics_cv(self, X, y, **kwargs):
results = self.cv_score_mean(X, y)
return results | Compute cross-validated metrics.
Trains this model on data X with labels y.
Returns a list of dict with keys name, scoring_name, value.
Args:
X (Union[np.array, pd.DataFrame]): data
y (Union[np.array, pd.DataFrame, pd.Series]): labels |
5,911 | def update(self, infos):
for info in infos:
if isinstance(info, LearningGene):
self.replicate(info) | Process received infos. |
5,912 | def make_mecard(name, reading=None, email=None, phone=None, videophone=None,
memo=None, nickname=None, birthday=None, url=None, pobox=None,
roomno=None, houseno=None, city=None, prefecture=None,
zipcode=None, country=None):
return segno.make_qr(make_mecard_data(n... | \
Returns a QR Code which encodes a `MeCard <https://en.wikipedia.org/wiki/MeCard>`_
:param str name: Name. If it contains a comma, the first part
is treated as lastname and the second part is treated as forename.
:param str|None reading: Designates a text string to be set as the
ka... |
5,913 | def setResult(self, value):
self.setResultCaptureDate(DateTime())
val = str("" if not value and value != 0 else value).strip()
if val and val[0] in [LDL, UDL]:
oper = val[0]
val = val.replace(oper, "", 1)
... | Validate and set a value into the Result field, taking into
account the Detection Limits.
:param value: is expected to be a string. |
5,914 | def _build_payload(data):
for k, v in iteritems(data):
data[k] = _transform(v, key=(k,))
payload = {
: SETTINGS[],
: data
}
return payload | Returns the full payload as a string. |
5,915 | def asizeof(self, *objs, **opts):
if opts:
self.set(**opts)
s, _ = self._sizes(objs, None)
return s | Return the combined size of the given objects
(with modified options, see method **set**). |
5,916 | def main():
authenticator = prawcore.TrustedAuthenticator(
prawcore.Requestor("prawcore_script_auth_example"),
os.environ["PRAWCORE_CLIENT_ID"],
os.environ["PRAWCORE_CLIENT_SECRET"],
)
authorizer = prawcore.ScriptAuthorizer(
authenticator,
os.environ["PRAWCORE_US... | Provide the program's entry point when directly executed. |
5,917 | def Pgas(rho,T,mu):
R = old_div(boltzmann_constant, atomic_mass_unit)
return (old_div(R,mu)) * rho * T | P = R/mu * rho * T
Parameters
----------
mu : float
Mean molecular weight
rho : float
Density [cgs]
T : float
Temperature [K] |
5,918 | def periodic_send(self, content, interval, title=):
url = .format(self.remote)
if isinstance(interval, datetime.timedelta):
interval = int(interval.total_seconds())
if not isinstance(interval, int):
raise ValueError
data = self._wrap_post_data(title=title... | 发送周期消息
:param content: (必填|str) - 需要发送的消息内容
:param interval: (必填|int|datetime.timedelta) - 发送消息间隔时间,支持 datetime.timedelta 或 integer 表示的秒数
:param title: (选填|str) - 需要发送的消息标题
:return: * status:发送状态,True 发送成,False 发送失败
* message:发送失败详情 |
5,919 | def add(self, pat, fun):
r
self._pat = None
self._pats.append(pat)
self._funs.append(fun) | r"""Add a pattern and replacement.
The pattern must not contain capturing groups.
The replacement might be either a string template in which \& will be
replaced with the match, or a function that will get the matching text
as argument. It does not get match object, because capturing is
... |
5,920 | def publish(dataset_uri):
try:
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
except dtoolcore.DtoolCoreTypeError:
print("Not a dataset: {}".format(dataset_uri))
sys.exit(1)
try:
access_uri = dataset._storage_broker.http_enable()
except AttributeError:
p... | Return access URL to HTTP enabled (published) dataset.
Exits with error code 1 if the dataset_uri is not a dataset.
Exits with error code 2 if the dataset cannot be HTTP enabled. |
5,921 | def loggable(obj):
if isinstance(obj, logging.Logger):
return True
else:
return (inspect.isclass(obj)
and inspect.ismethod(getattr(obj, , None))
and inspect.ismethod(getattr(obj, , None))
and inspect.ismethod(getattr(obj, , None))) | Return "True" if the obj implements the minimum Logger API
required by the 'trace' decorator. |
5,922 | def set_resolved_name(self, ref: dict, type_name2solve: TypeName,
type_name_ref: TypeName):
if self.resolution[type_name2solve.value] is None:
self.resolution[type_name2solve.value] = ref[type_name_ref.value] | Warning!!! Need to rethink it when global poly type |
5,923 | def nl_nlmsg_flags2str(flags, buf, _=None):
del buf[:]
all_flags = (
(, libnl.linux_private.netlink.NLM_F_REQUEST),
(, libnl.linux_private.netlink.NLM_F_MULTI),
(, libnl.linux_private.netlink.NLM_F_ACK),
(, libnl.linux_private.netlink.NLM_F_ECHO),
(, libnl.linux_priv... | Netlink Message Flags Translations.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L664
Positional arguments:
flags -- integer.
buf -- bytearray().
Keyword arguments:
_ -- unused.
Returns:
Reference to `buf`. |
5,924 | def parse(self, *args, **kwargs):
cmd = args[0]
resp = args[1]
if cmd in self.parsers:
try:
return self.parsers[cmd](resp)
except Exception as err:
print(err)
return {} | Parse response.
:param args: List. 2 first items used as parser name and response to parse
:param kwargs: dict, not used
:return: dictionary or return value of called callable from parser. |
5,925 | def initializeSessionAsAlice(sessionState, sessionVersion, parameters):
sessionState.setSessionVersion(sessionVersion)
sessionState.setRemoteIdentityKey(parameters.getTheirIdentityKey())
sessionState.setLocalIdentityKey(parameters.getOurIdentityKey().getPublicKey())
sendingRatc... | :type sessionState: SessionState
:type sessionVersion: int
:type parameters: AliceAxolotlParameters |
5,926 | def _rem_id_from_keys(self, pk, conn=None):
if conn is None:
conn = self._get_connection()
conn.srem(self._get_ids_key(), pk) | _rem_id_from_keys - Remove primary key from table
internal |
5,927 | def overlay_gateway_site_bfd_enable(self, **kwargs):
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
name_key.text = kwargs.pop()
site... | Auto Generated Code |
5,928 | def update(self, widget, widget_tree):
self.listeners_list = []
self.build_widget_list_from_tree(widget_tree)
self.label.set_text( + widget.attributes[])
self.container = gui.VBox(width=, height=)
self.container.style[] =
self.container.style[] =
... | for the selected widget are listed the relative signals
for each signal there is a dropdown containing all the widgets
the user will select the widget that have to listen a specific event |
5,929 | def delete_char(self, e):
u
self.l_buffer.delete_char(self.argument_reset)
self.finalize() | u"""Delete the character at point. If point is at the beginning of
the line, there are no characters in the line, and the last
character typed was not bound to delete-char, then return EOF. |
5,930 | def _get_cpu_info_from_sysctl():
try:
if not DataSource.has_sysctl():
return {}
returncode, output = DataSource.sysctl_machdep_cpu_hw_cpufrequency()
if output == None or returncode != 0:
return {}
vendor_id = _get_field(False, output, None, None, )
processor_brand = _get_field(True, output... | Returns the CPU info gathered from sysctl.
Returns {} if sysctl is not found. |
5,931 | def createFileLink(self, resourceno):
data = {: ,
: resourceno,
: self.user_id,
: self.useridx,
}
s, metadata = self.GET(, data)
if s:
print "URL: %s" % (metadata[])
return metadata[]
else:... | Make a link of file
If you don't know ``resourceno``, you'd better use ``getFileLink``.
:param resourceno: Resource number of a file to create link
:return: ``Shared url`` or ``False`` when failed to share a file |
5,932 | def generate(size, output, schema):
pii_data = randomnames.NameList(size)
if schema is not None:
raise NotImplementedError
randomnames.save_csv(
pii_data.names,
[f.identifier for f in pii_data.SCHEMA.fields],
output) | Generate fake PII data for testing |
5,933 | def _build_metrics(func_name, namespace):
metrics = {: func_name, : datetime.utcnow(),
: .format(list(sys.argv)), : getpass.getuser()}
assert isinstance(namespace, Namespace)
tmp_dic = vars(namespace)
metrics[] = tmp_dic.get()
metrics[] = tmp_dic.get()
metrics[] = tmp_dic.g... | Builds metrics dict from function args
It assumes that function arguments is from airflow.bin.cli module's function
and has Namespace instance where it optionally contains "dag_id", "task_id",
and "execution_date".
:param func_name: name of function
:param namespace: Namespace instance from argpars... |
5,934 | def forcemerge(self, index=None, params=None):
return self.transport.perform_request(
"POST", _make_path(index, "_forcemerge"), params=params
) | The force merge API allows to force merging of one or more indices
through an API. The merge relates to the number of segments a Lucene
index holds within each shard. The force merge operation allows to
reduce the number of segments by merging them.
This call will block until the merge ... |
5,935 | def start(self):
timeout = self.timeout()
if timeout is not None and timeout > 0:
self.__loop.add_timeout(timedelta(0, timeout), self.stop)
self.handler().setup_handler(self.loop())
self.loop().start()
self.handler().loop_stopped() | Set up handler and start loop
:return: None |
5,936 | def actually_flatten(iterable):
remainder = iter(iterable)
while True:
first = next(remainder)
is_iter = isinstance(first, collections.Iterable)
try:
basestring
except NameError:
basestring = str
if is_py3() and is_iter and not_a... | Flatten iterables
This is super ugly. There must be a cleaner py2/3 way
of handling this. |
5,937 | def get(self, pk, **kwargs):
item = self.datamodel.get(pk, self._base_filters)
if not item:
return self.response_404()
_response = dict()
_args = kwargs.get("rison", {})
select_cols = _args.get(API_SELECT_COLUMNS_RIS_KEY, [])
_pruned_select_cols = [c... | Get item from Model
---
get:
parameters:
- in: path
schema:
type: integer
name: pk
- $ref: '#/components/parameters/get_item_schema'
responses:
200:
description: Item from Model
content:... |
5,938 | def ansi_split(text, _re=re.compile(u"(\x1b\\[(\\d*;?)*\\S)")):
for part in _re.split(text):
if part:
yield (bool(_re.match(part)), part) | Yields (is_ansi, text) |
5,939 | def _encode(self):
data = ByteBuffer()
if not hasattr(self, ):
return data.tostring()
for field in self.__fields__:
field.encode(self, data)
return data.tostring() | Encode the message and return a bytestring. |
5,940 | def configure_settings():
if not settings.configured:
db_config = {
: ,
: ,
}
settings.configure(
TEST_RUNNER=,
NOSE_ARGS=[, , ],
DATABASES={
: db_config,
},
INSTALLED_APPS=(
... | Configures settings for manage.py and for run_tests.py. |
5,941 | def addFull(self, vehID, routeID, typeID="DEFAULT_VEHTYPE", depart=None,
departLane="first", departPos="base", departSpeed="0",
arrivalLane="current", arrivalPos="max", arrivalSpeed="current",
fromTaz="", toTaz="", line="", personCapacity=0, personNumber=0):
... | Add a new vehicle (new style with all possible parameters) |
5,942 | def b58encode_int(i, default_one=True):
if not i and default_one:
return alphabet[0]
string = ""
while i:
i, idx = divmod(i, 58)
string = alphabet[idx] + string
return string | Encode an integer using Base58 |
5,943 | def column_mask(self):
margin = compress_pruned(
self._slice.margin(
axis=0,
weighted=False,
include_transforms_for_dims=self._hs_dims,
prune=self._prune,
)
)
mask = margin < self._size
if m... | ndarray, True where column margin <= min_base_size, same shape as slice. |
5,944 | def weld_str_replace(array, pat, rep):
obj_id, weld_obj = create_weld_object(array)
pat_id = get_weld_obj_id(weld_obj, pat)
rep_id = get_weld_obj_id(weld_obj, rep)
weld_template =
weld_obj.weld_code = weld_template.format(array=obj_id,
pat=pat_id... | Replace first occurrence of pat with rep.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
pat : str
To find.
rep : str
To replace with.
Returns
-------
WeldObject
Representation of this computation. |
5,945 | def webui_schematics_assets_asset_asset_type_image_base_64_image(self, **kwargs):
config = ET.Element("config")
webui = ET.SubElement(config, "webui", xmlns="http://tail-f.com/ns/webui")
schematics = ET.SubElement(webui, "schematics")
assets = ET.SubElement(schematics, "assets")... | Auto Generated Code |
5,946 | def classe(self, name):
for klass in self.classes():
if klass.node.name == name:
return klass
raise KeyError(name) | return a class by its name, raise KeyError if not found |
5,947 | def _encode_binary(message, on=1, off=0):
l = _encode_morse(message)
s = .join(l)
l = list(s)
bin_conv = {: [on], : [on] * 3, : [off]}
l = map(lambda symb: [off] + bin_conv[symb], l)
lst = [item for sublist in l for item in sublist]
return lst[1:] | >>> message = "SOS"
>>> _encode_binary(message)
[1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1]
>>> _encode_binary(message, on='1', off='0')
['1', '0', '1', '0', '1', '0', '0', '0', '1', '1', '1', '0', '1', '1', '1', '0', '1', '1', '1', '0', '0', '0', '1', '0', '1', '0... |
5,948 | def position_input(obj, visible=False):
if not obj.generic_position.all():
ObjectPosition.objects.create(content_object=obj)
return {: obj, : visible,
: obj.generic_position.all()[0]} | Template tag to return an input field for the position of the object. |
5,949 | def render_html(html_str):
import utool as ut
from os.path import abspath
import webbrowser
try:
html_str = html_str.decode()
except Exception:
pass
html_dpath = ut.ensure_app_resource_dir(, )
fpath = abspath(ut.unixjoin(html_dpath, ))
url = + fpath
ut.writeto... | makes a temporary html rendering |
5,950 | def asdict(self, rawkey=False):
r
if rawkey:
return dict(self.items())
else:
return {
str(k): v
for k, v in self.items()
} | r"""Convert Result to dict.
Parameters:
rawkey(bool):
* True: dict key is Descriptor instance
* False: dict key is str
Returns:
dict |
5,951 | def _get_interfaces(self):
ios_cfg = self._get_running_config()
parse = HTParser(ios_cfg)
itfcs_raw = parse.find_lines("^interface GigabitEthernet")
itfcs = [raw_if.strip().split()[1] for raw_if in itfcs_raw]
LOG.debug("Interfaces on hosting device: %s", itfcs)
r... | Get a list of interfaces on this hosting device.
:return: List of the interfaces |
5,952 | def _resolveAddress(address):
address = address.split()
assert len(address) in (1, 2)
address[0] = socket.gethostbyname(address[0])
return .join(address) | Resolves the host in the given string. The input is of the form host[:port]. This method
is idempotent, i.e. the host may already be a dotted IP address.
>>> # noinspection PyProtectedMember
>>> f=MesosBatchSystem._resolveAddress
>>> f('localhost')
'127.0.0.1'
>>> f('127... |
5,953 | def UpdateSNMPObjsAsync():
if threading.active_count() == 1:
LogMsg("Creating thread for UpdateSNMPObjs().")
t = threading.Thread(target=UpdateSNMPObjs, name="UpdateSNMPObjsThread")
t.daemon = True
t.start()
else:
LogMsg("Data update still active, data update interval too low?") | Starts UpdateSNMPObjs() in a separate thread. |
5,954 | def excepthook(type, value, tb):
if (issubclass(type, Error) or issubclass(type, lib50.Error)) and str(value):
for line in str(value).split("\n"):
cprint(str(line), "yellow")
else:
cprint(_("Sorry, something's wrong! Let sysadmins@cs50.harvard.edu know!"), "yellow")
if exce... | Report an exception. |
5,955 | def get_binary_path(executable, logging_level=):
if sys.platform == :
if executable == :
return executable
executable = executable +
if executable in os.listdir():
binary = os.path.join(os.getcwd(), executable)
else:
binary = next((os.path.jo... | Gets the software name and returns the path of the binary. |
5,956 | def transform_vector_coorb_to_inertial(vec_coorb, orbPhase, quat_copr):
vec_copr = rotate_in_plane(vec_coorb, -orbPhase)
vec = transformTimeDependentVector(np.array([quat_copr]).T,
np.array([vec_copr]).T).T[0]
return np.array(vec) | Given a vector (of size 3) in coorbital frame, orbital phase in
coprecessing frame and a minimal rotation frame quat, transforms
the vector from the coorbital to the inertial frame. |
5,957 | def __kullback_leibler(h1, h2):
result = h1.astype(scipy.float_)
mask = h1 != 0
result[mask] = scipy.multiply(h1[mask], scipy.log(h1[mask] / h2[mask]))
return scipy.sum(result) | The actual KL implementation. @see kullback_leibler() for details.
Expects the histograms to be of type scipy.ndarray. |
5,958 | def post_event(event,
channel=None,
username=None,
api_url=None,
hook=None):
if not api_url:
api_url = _get_api_url()
if not hook:
hook = _get_hook()
if not username:
username = _get_username()
if not channel:
... | Send an event to a Mattermost channel.
:param channel: The channel name, either will work.
:param username: The username of the poster.
:param event: The event to send to the Mattermost channel.
:param api_url: The Mattermost api url, if not specified in the configuration.
:param ho... |
5,959 | def backprop(self, input_data, df_output, cache=None):
if self.l1_penalty_weight:
df_W += self.l1_penalty_weight * sign(self.W)
if self.l2_penalty_weight:
df_W += self.l2_penalty_weight * self.W
return (df_W, df_b), df_input | Backpropagate through the hidden layer
**Parameters:**
input_data : ``GPUArray``
Input data to compute activations for.
df_output : ``GPUArray``
Gradients with respect to the activations of this layer
(received from the layer above).
cache : list o... |
5,960 | def has_symbol(self, symbol, as_of=None):
try:
self._read_metadata(symbol, as_of=as_of, read_preference=ReadPreference.PRIMARY)
return True
except NoDataFoundException:
return False | Return True if the 'symbol' exists in this library AND the symbol
isn't deleted in the specified as_of.
It's possible for a deleted symbol to exist in older snapshots.
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `dat... |
5,961 | def _create_object(self, data, request):
if request.method.upper() == and self.post_factory:
fac_func = self.post_factory.create
else:
fac_func = self.factory.create
if isinstance(data, (list, tuple)):
return map(fac_func, data)
else:
... | Create a python object from the given data.
This will use ``self.factory`` object's ``create()`` function to
create the data.
If no factory is defined, this will simply return the same data
that was given. |
5,962 | def mark_seen(self):
data = self.get_selected_item()
if data[]:
with self.term.loader():
data[].mark_as_read()
if not self.term.loader.exception:
data[] = False
else:
with self.term.loader():
data[].mark... | Mark the selected message or comment as seen. |
5,963 | def getSlaveStatus(self):
info_dict = {}
if self.checkVersion():
cols = [, , ,
, , , ,
, , ,
, , ,]
cur = self._conn.cursor()
cur.execute(
% .join(cols))
rows ... | Returns status of replication slaves.
@return: Dictionary of status items. |
5,964 | def addition_circuit(
addend0: Qubits,
addend1: Qubits,
carry: Qubits) -> Circuit:
if len(addend0) != len(addend1):
raise ValueError()
if len(carry) != 2:
raise ValueError()
def _maj(qubits: Qubits) -> Circuit:
q0, q1, q2 = qubits
circ = Circui... | Returns a quantum circuit for ripple-carry addition. [Cuccaro2004]_
Requires two carry qubit (input and output). The result is returned in
addend1.
.. [Cuccaro2004]
A new quantum ripple-carry addition circuit, Steven A. Cuccaro,
Thomas G. Draper, Samuel A. Kutin, David Petrie Moulton
... |
5,965 | def get_text_field_mask(text_field_tensors: Dict[str, torch.Tensor],
num_wrapping_dims: int = 0) -> torch.LongTensor:
if "mask" in text_field_tensors:
return text_field_tensors["mask"]
tensor_dims = [(tensor.dim(), tensor) for tensor in text_field_tensors.values()]
tens... | Takes the dictionary of tensors produced by a ``TextField`` and returns a mask
with 0 where the tokens are padding, and 1 otherwise. We also handle ``TextFields``
wrapped by an arbitrary number of ``ListFields``, where the number of wrapping ``ListFields``
is given by ``num_wrapping_dims``.
If ``num_w... |
5,966 | def _setup_watch(self, alias, path, flags):
assert alias not in self.descriptors, "Registering alias %s twice!" % alias
wd = LibC.inotify_add_watch(self._fd, path, flags)
if wd < 0:
raise IOError("Error setting up watch on %s with flags %s: wd=%s" % (
path, f... | Actual rule setup. |
5,967 | def _search(self, searchfilter, attrs, basedn):
if attrs == NO_ATTR:
attrlist = []
elif attrs == DISPLAYED_ATTRS:
attrlist = self.attrlist
elif attrs == LISTED_ATTRS:
attrlist = self.attrlist
elif attrs == ALL_ATTRS:
a... | Generic search |
5,968 | def dumplist(args):
from .query import Database
db = Database()
r = db.objects(
protocol=args.protocol,
purposes=args.purpose,
model_ids=(args.client,),
groups=args.group,
classes=args.sclass
)
output = sys.stdout
if args.selftest:
from bob.db.utils import null
ou... | Dumps lists of files based on your criteria |
5,969 | def add_property(self, c_property_tuple, sync=True):
LOGGER.debug("Container.add_property")
if c_property_tuple[1] is None:
LOGGER.debug("Property " + c_property_tuple[0] + " has None value. Ignore.")
return
if not sync or self.id is None:
self.prope... | add property to this container. if this container has no id then it's like sync=False.
:param c_property_tuple: property tuple defined like this :
=> property name = c_property_tuple[0]
=> property value = c_property_tuple[1]
:param sync: If sync=True(default) synchronize w... |
5,970 | def serialize(self, value):
if isinstance(value, list):
return self.list_sep.join(_helpers.str_or_unicode(x.name) for x in value)
else:
return _helpers.str_or_unicode(value.name) | See base class. |
5,971 | def appendBitPadding(str, blocksize=AES_blocksize):
10
pad_len = paddingLength(len(str), blocksize) - 1
padding = chr(0x80)+*pad_len
return str + padding | Bit padding a.k.a. One and Zeroes Padding
A single set ('1') bit is added to the message and then as many reset ('0') bits as required (possibly none) are added.
Input: (str) str - String to be padded
(int) blocksize - block size of the algorithm
Return: Padded string according to ANSI X.923 standart
... |
5,972 | def filter_factory(global_conf, **local_conf):
conf = global_conf.copy()
conf.update(local_conf)
def blacklist(app):
return BlacklistFilter(app, conf)
return blacklist | Returns a WSGI filter app for use with paste.deploy. |
5,973 | def end_prov_graph(self):
endTime = Literal(datetime.now())
self.prov_g.add((self.entity_d, self.prov.generatedAtTime, endTime))
self.prov_g.add((self.activity, self.prov.endedAtTime, endTime)) | Finalize prov recording with end time |
5,974 | def subspace_detector_plot(detector, stachans, size, **kwargs):
import matplotlib.pyplot as plt
if stachans == and not detector.multiplex:
stachans = detector.stachans
elif detector.multiplex:
stachans = [(, )]
if np.isinf(detector.dimension):
msg = .join([,
... | Plotting for the subspace detector class.
Plot the output basis vectors for the detector at the given dimension.
Corresponds to the first n horizontal vectors of the V matrix.
:type detector: :class:`eqcorrscan.core.subspace.Detector`
:type stachans: list
:param stachans: list of tuples of statio... |
5,975 | def screenshot(self, png_filename=None, format=):
value = self.http.get().value
raw_value = base64.b64decode(value)
png_header = b"\x89PNG\r\n\x1a\n"
if not raw_value.startswith(png_header) and png_filename:
raise WDAError(-1, "screenshot png format error")
... | Screenshot with PNG format
Args:
png_filename(string): optional, save file name
format(string): return format, pillow or raw(default)
Returns:
raw data or PIL.Image
Raises:
WDAError |
5,976 | def getNextSample(self, V):
randPos = random.randint(0, len(V)-2)
W = copy.deepcopy(V)
d = V[randPos]
c = V[randPos+1]
W[randPos] = c
W[randPos+1] = d
prMW = 1
prMV = 1
prob = min(1.0,(prMW/prMV)*pow(self.phi, self.wmg[... | Generate the next sample by randomly flipping two adjacent candidates.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in a vote, from first to last. This is the current sample. |
5,977 | def control_group(action, action_space, control_group_act, control_group_id):
del action_space
select = action.action_ui.control_group
select.action = control_group_act
select.control_group_index = control_group_id | Act on a control group, selecting, setting, etc. |
5,978 | async def set_power(
self, power_type: str,
power_parameters: typing.Mapping[str, typing.Any] = {}):
data = await self._handler.update(
system_id=self.system_id, power_type=power_type,
power_parameters=power_parameters)
self.power_type = data[] | Set the power type and power parameters for this node. |
5,979 | def get_selected_files(self, pipeline=, forfile=None, quiet=0, allowedfileformats=):
file_dict = dict(self.bids_tags)
if allowedfileformats == :
allowedfileformats = [, ]
if forfile:
if isinstance(forfile, str):
forfile = get_bids_tag(for... | Parameters
----------
pipeline : string
can be \'pipeline\' (main analysis pipeline, self in tnet.set_pipeline) or \'confound\' (where confound files are, set in tnet.set_confonud_pipeline()),
\'functionalconnectivity\'
quiet: int
If 1, prints results. If 0, n... |
5,980 | def get_curent_module_classes(module):
classes = []
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj):
classes.append(obj)
return classes | 获取制定模块的所有类
:param module: 模块
:return: 类的列表 |
5,981 | def has_image(self, name: str) -> bool:
path = "docker/images/{}".format(name)
r = self.__api.head(path)
if r.status_code == 204:
return True
elif r.status_code == 404:
return False
self.__api.handle_erroneous_response(r) | Determines whether the server has a Docker image with a given name. |
5,982 | def effectiv_num_data_points(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps):
num_linear = 0
if self._image_likelihood is True:
num_linear = self.image_likelihood.num_param_linear(kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps)
num_param, _ = self.p... | returns the effective number of data points considered in the X2 estimation to compute the reduced X2 value |
5,983 | def get(self, request, template_id, view_type):
template = get_object_or_404(EnrollmentNotificationEmailTemplate, pk=template_id)
if view_type not in self.view_type_contexts:
return HttpResponse(status=404)
base_context = self.view_type_contexts[view_type].copy()
bas... | Render the given template with the stock data. |
5,984 | def ngrams(path, elem, ignore_hash=True):
grams = GramGenerator(path, elem, ignore_hash=ignore_hash)
return FeatureSet({k: Feature(f) for k, f in grams}) | Yields N-grams from a JSTOR DfR dataset.
Parameters
----------
path : string
Path to unzipped JSTOR DfR folder containing N-grams.
elem : string
Name of subdirectory containing N-grams. (e.g. 'bigrams').
ignore_hash : bool
If True, will exclude all N-grams that contain the h... |
5,985 | def _validate_cidr(self, rule):
try:
network = ipaddress.IPv4Network(rule[])
except (ipaddress.NetmaskValueError, ValueError) as error:
raise SpinnakerSecurityGroupCreationFailed(error)
self.log.debug(, network.exploded)
return True | Validate the cidr block in a rule.
Returns:
True: Upon successful completion.
Raises:
SpinnakerSecurityGroupCreationFailed: CIDR definition is invalid or
the network range is too wide. |
5,986 | def _write_ctrl_meas(self):
self._write_register_byte(_BME280_REGISTER_CTRL_HUM, self.overscan_humidity)
self._write_register_byte(_BME280_REGISTER_CTRL_MEAS, self._ctrl_meas) | Write the values to the ctrl_meas and ctrl_hum registers in the device
ctrl_meas sets the pressure and temperature data acquistion options
ctrl_hum sets the humidty oversampling and must be written to first |
5,987 | def __initialize(self, sample):
self.__processed = [False] * len(sample)
self.__optics_objects = [optics_descriptor(i) for i in range(len(sample))]
self.__ordered_database = []
self.__clusters = None
self.__noise = None | !
@brief Initializes internal states and resets clustering results in line with input sample. |
5,988 | def emit(self, record):
try:
if self.check_base_filename(record):
self.build_base_filename()
FileHandler.emit(self, record)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record) | Emit a record.
Always check time |
5,989 | def _isbn_cleanse(isbn, checksum=True):
if not isinstance(isbn, string_types):
raise TypeError( % isbn)
if PY2 and isinstance(isbn, str):
isbn = unicode(isbn)
uni_input = False
else:
uni_input = True
for dash in DASHES:
isbn = isbn.replace(dash, unicode... | Check ISBN is a string, and passes basic sanity checks.
Args:
isbn (str): SBN, ISBN-10 or ISBN-13
checksum (bool): ``True`` if ``isbn`` includes checksum character
Returns:
``str``: ISBN with hyphenation removed, including when called with a
SBN
Raises:
TypeErr... |
5,990 | def get_graph_by_most_recent(self, name: str) -> Optional[BELGraph]:
network = self.get_most_recent_network_by_name(name)
if network is None:
return
return network.as_bel() | Get the most recently created network with the given name as a :class:`pybel.BELGraph`. |
5,991 | def arccalibration(wv_master,
xpos_arc,
naxis1_arc,
crpix1,
wv_ini_search,
wv_end_search,
wvmin_useful,
wvmax_useful,
error_xpos_arc,
times_sigma_r,
... | Performs arc line identification for arc calibration.
This function is a wrapper of two functions, which are responsible
of computing all the relevant information concerning the triplets
generated from the master table and the actual identification
procedure of the arc lines, respectively.
The sep... |
5,992 | def _invertMapping(mapping):
invertedMapping = ddict(set)
for key, values in viewitems(mapping):
for value in values:
invertedMapping[value].add(key)
return invertedMapping | Converts a protein to peptide or peptide to protein mapping.
:param mapping: dict, for each key contains a set of entries
:returns: an inverted mapping that each entry of the values points to a set
of initial keys. |
5,993 | def _doc(from_func):
def decorator(to_func):
to_func.__doc__ = from_func.__doc__
return to_func
return decorator | copy doc from one function to another
use as a decorator eg::
@_doc(file.tell)
def tell(..):
... |
5,994 | def configure():
completer = Completer()
readline.set_completer_delims()
readline.parse_and_bind()
readline.set_completer(completer.path_completer)
home = os.path.expanduser()
if os.path.isfile(os.path.join(home, , )):
with open(os.path.join(home, , ), ) as fp:
config =... | Configure the transfer environment and store |
5,995 | def create_payment_transaction(cls, payment_transaction, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._create_payment_transaction_with_http_info(payment_transaction, **kwargs)
else:
(data) = cls._create_payment_transaction_with_http_info(payment_transac... | Create PaymentTransaction
Create a new PaymentTransaction
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_payment_transaction(payment_transaction, async=True)
>>> result = thread.get()
... |
5,996 | def _cnx_is_empty(in_file):
with open(in_file) as in_handle:
for i, line in enumerate(in_handle):
if i > 0:
return False
return True | Check if cnr or cns files are empty (only have a header) |
5,997 | def detect_languages(self, texts):
text_list = TextUtils.format_list_to_send(texts)
infos_translate = TextDetectLanguageModel(text_list).to_dict()
texts_for_detect = TextUtils.change_key(infos_translate, "text",
"texts", infos_tra... | Params:
::texts = Array of texts for detect languages
Returns:
Returns language present on array of text. |
5,998 | def py_module_preamble(ctx: GeneratorContext,) -> GeneratedPyAST:
preamble: List[ast.AST] = []
preamble.extend(_module_imports(ctx))
preamble.append(_from_module_import())
preamble.append(_ns_var())
return GeneratedPyAST(node=ast.NameConstant(None), dependencies=preamble) | Bootstrap a new module with imports and other boilerplate. |
5,999 | def get_model_file(name, root=os.path.join(base.data_dir(), )):
r
file_name = .format(name=name,
short_hash=short_hash(name))
root = os.path.expanduser(root)
file_path = os.path.join(root, file_name+)
sha1_hash = _model_sha1[name]
if os.path.exists(fi... | r"""Return location for the pretrained on local file system.
This function will download from online model zoo when model cannot be found or has mismatch.
The root directory will be created if it doesn't exist.
Parameters
----------
name : str
Name of the model.
root : str, default $MX... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.