code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def add_callback(self, method):
from_actor = get_current()
if from_actor is not None:
callback = (method, from_actor.channel, from_actor.url)
with self.__condition:
if self.__state is not FINISHED:
self.__callbacks.append(callback)
... | Attaches a mehtod that will be called when the future finishes.
:param method: A callable from an actor that will be called
when the future completes. The only argument for that
method must be the future itself from wich you can get the
result though `future.:meth:`result()`... |
def _file_num_records_cached(filename):
if filename in _file_num_records_cache:
return _file_num_records_cache[filename]
ret = 0
for _ in tf.python_io.tf_record_iterator(filename):
ret += 1
_file_num_records_cache[filename] = ret
return ret | Return the number of TFRecords in a file. |
def _PreParse(self, key, value):
if key == "Command":
return re.sub(r"(\[\[.+?\]\])", self._Completion, value)
else:
return value | Executed against each field of each row read from index table. |
def power(a,b):
s power function
and ** syntax do. The power() function also works with sparse arrays; though it must reify
them during the process.
'
(a,b) = unbroadcast(a,b)
return cpower(a,b) | power(a,b) is equivalent to a**b except that, like the neuropythy.util.times function, it
threads over the earliest dimension possible rather than the latest, as numpy's power function
and ** syntax do. The power() function also works with sparse arrays; though it must reify
them during the process. |
def create(self, equipments):
data = {: equipments}
return super(ApiEquipment, self).post(, data) | Method to create equipments
:param equipments: List containing equipments desired to be created on database
:return: None |
def transform(self, job_name, model_name, strategy, max_concurrent_transforms, max_payload, env,
input_config, output_config, resource_config, tags):
transform_request = {
: job_name,
: model_name,
: input_config,
: output_config,
... | Create an Amazon SageMaker transform job.
Args:
job_name (str): Name of the transform job being created.
model_name (str): Name of the SageMaker model being used for the transform job.
strategy (str): The strategy used to decide how to batch records in a single request.
... |
def get_queryset(self):
qs = super(MultilingualManager, self).get_queryset()
if isinstance(qs, MultilingualQuerySet):
return qs
return self._patch_queryset(qs) | This method is repeated because some managers that don't use super() or alter queryset class
may return queryset that is not subclass of MultilingualQuerySet. |
def _create_file():
f = wave.open(, mode=)
f.setnchannels(2)
p = pyaudio.PyAudio()
f.setsampwidth(p.get_sample_size(pyaudio.paInt16))
f.setframerate(p.get_default_input_device_info()[])
try:
yield f
finally:
f.close() | Returns a file handle which is used to record audio |
def compute_payments(self, precision=None):
return quantize(sum([payment.amount for payment in self.__payments]),
precision) | Returns the total amount of payments made to this invoice.
@param precision:int Number of decimal places
@return: Decimal |
def write_smet(filename, data, metadata, nodata_value=-999, mode=, check_nan=True):
dict_d= {:,
:,
:,
:,
:,
:,
:
}
dict_h= {:,
:,
:, ... | writes smet files
Parameters
----
filename : filename/loction of output
data : data to write as pandas df
metadata: header to write input as dict
nodata_value: Nodata Value to write/use
mode: defines if to write daily ("d") or continuos data (default 'h')
check_nan... |
def remove_colormap(self, removal_type):
with _LeptonicaErrorTrap():
return Pix(
lept.pixRemoveColormapGeneral(self._cdata, removal_type, lept.L_COPY)
) | Remove a palette (colormap); if no colormap, returns a copy of this
image
removal_type - any of lept.REMOVE_CMAP_* |
def get_aws_s3_handle(config_map):
url = + config_map[] +
if not AWS_CLIENT.is_aws_s3_client_set():
client = boto3.client(
,
aws_access_key_id=config_map[],
aws_secret_access_key=config_map[]
)
AWS_CLIENT.set_aws_s3_client(client)
else:
... | Convenience function for getting AWS S3 objects
Added by cjshaw@mit.edu, Jan 9, 2015
Added to aws_adapter build by birdland@mit.edu, Jan 25, 2015, and
added support for Configuration
May 25, 2017: Switch to boto3 |
def process_insert_get_id(self, query, sql, values, sequence=None):
result = query.get_connection().select_from_write_connection(sql, values)
id = result[0][0]
if isinstance(id, int):
return id
if str(id).isdigit():
return int(id)
return id | Process an "insert get ID" query.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param sql: The sql query to execute
:type sql: str
:param values: The value bindings
:type values: list
:param sequence: The ids sequence
:type sequence:... |
def diff_prettyHtml(self, diffs):
html = []
for (op, data) in diffs:
text = (data.replace("&", "&").replace("<", "<")
.replace(">", ">").replace("\n", "¶<br>"))
if op == self.DIFF_INSERT:
html.append("<ins style=\"background:
elif op == self.DIFF_DE... | Convert a diff array into a pretty HTML report.
Args:
diffs: Array of diff tuples.
Returns:
HTML representation. |
def get_config(context):
conf_vars = [,
,
,
,
]
js =
output = [js.format(item, context[item]) for item in conf_vars \
if item in context]
return .join(output) | Return the formatted javascript for any disqus config variables. |
def point_rotate(pt, ax, theta):
import numpy as np
pt = make_nd_vec(pt, nd=3, t=np.float64, norm=False)
rot_pt = np.dot(mtx_rot(ax, theta, reps=1), pt)
return rot_pt | Rotate a 3-D point around a 3-D axis through the origin.
Handedness is a counter-clockwise rotation when viewing the rotation
axis as pointing at the observer. Thus, in a right-handed x-y-z frame,
a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point at
(0,1,0).
.. todo:: Complete ... |
def _request_devices(self, url, _type):
res = self._request(url)
return res.get(_type) if res else {} | Request list of devices. |
def set_spectator_mode(self, mode=True):
mode = bool(mode)
self.in_spectator_mode = mode
for node in self.iflat_nodes():
node.in_spectator_mode = mode
if not mode:
self.connect_signals()
else:
self.disconnect_signals... | When the flow is in spectator_mode, we have to disable signals, pickle dump and possible callbacks
A spectator can still operate on the flow but the new status of the flow won't be saved in
the pickle file. Usually the flow is in spectator mode when we are already running it via
the scheduler or... |
def save(self):
for form in self._forms:
if isinstance(form, BaseForm):
form.save(commit=False)
self.instance.save()
for form in self.forms:
if isinstance(form, BaseForm):
if hasattr(form, ):
... | Save the changes to the instance and any related objects. |
def sort_func(self, key):
if key == self._KEYS.TIME:
return
if key == self._KEYS.DATA:
return
if key == self._KEYS.SOURCE:
return
return key | Logic for sorting keys in a `Spectrum` relative to one another. |
def mask_cmp_op(x, y, op, allowed_types):
xrav = x.ravel()
result = np.empty(x.size, dtype=bool)
if isinstance(y, allowed_types):
yrav = y.ravel()
mask = notna(xrav) & notna(yrav)
result[mask] = op(np.array(list(xrav[mask])),
np.array(list(yrav[mas... | Apply the function `op` to only non-null points in x and y.
Parameters
----------
x : array-like
y : array-like
op : binary operation
allowed_types : class or tuple of classes
Returns
-------
result : ndarray[bool] |
def north_arrow_path(feature, parent):
_ = feature, parent
north_arrow_file = setting(inasafe_north_arrow_path[])
if os.path.exists(north_arrow_file):
return north_arrow_file
else:
LOGGER.info(
).format(
north_arrow_file=north_arrow_file)
... | Retrieve the full path of default north arrow logo. |
def select_dtypes(self, include=None, exclude=None):
def _get_info_slice(obj, indexer):
if not hasattr(obj, ):
msg =
raise TypeError(msg.format(typ=type(obj).__name__))
slices = [slice(None)] * obj.ndim
slices[obj._info_a... | Return a subset of the DataFrame's columns based on the column dtypes.
Parameters
----------
include, exclude : scalar or list-like
A selection of dtypes or strings to be included/excluded. At least
one of these parameters must be supplied.
Returns
-----... |
def _parse(root):
if root.tag == "nil-classes":
return []
elif root.get("type") == "array":
return [_parse(child) for child in root]
d = {}
for child in root:
type = child.get("type") or "string"
if child.get("nil"):
value = None
elif type == "b... | Recursively convert an Element into python data types |
def _get_parser_call_method(self, parser_to_method):
def inner_call(args=None, instance=None):
parser = self._cls.parser
namespace = parser.parse_args(_get_args_to_parse(args, sys.argv))
if instance is None:
... | Return the parser special method 'call' that handles sub-command
calling.
Args:
parser_to_method: mapping of the parser registered name
to the method it is linked to |
def describe_root(record, root, indent=0, suppress_values=False):
def format_node(n, extra=None, indent=0):
ret = ""
indent_s = * indent
name = n.__class__.__name__
offset = n.offset() - record.offset()
if extra is not None:
ret = "%s%s(offset=%s, %... | Args:
record (Evtx.Record):
indent (int): |
def remove_member_from(self, leaderboard_name, member):
pipeline = self.redis_connection.pipeline()
pipeline.zrem(leaderboard_name, member)
pipeline.hdel(self._member_data_key(leaderboard_name), member)
pipeline.execute() | Remove the optional member data for a given member in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name. |
def get_region():
global _REGION
if _REGION is None:
region_name = os.getenv("AWS_DEFAULT_REGION") or "us-east-1"
region_dict = {r.name: r for r in boto.regioninfo.get_regions("ec2")}
if region_name not in region_dict:
raise ValueError("No such EC2 region: {}. Check AWS_... | Use the environment to get the current region |
def parse(self, method, endpoint, body):
if isinstance(body, dict):
return body
if endpoint == :
return self.parse_list(body)
return self.parse_detail(body) | calls parse on list or detail |
def infile_path(self) -> Optional[PurePath]:
if not self.__infile_path:
return Path(self.__infile_path).expanduser()
return None | Read-only property.
:return: A ``pathlib.PurePath`` object or ``None``. |
def when_value_edited(self, *args, **kargs):
if len(self.value) > self.instance_num:
self.value.pop(-2)
self.display() | Overrided to prevent user from selecting too many instances |
def linefeed(self):
self.index()
if mo.LNM in self.mode:
self.carriage_return() | Perform an index and, if :data:`~pyte.modes.LNM` is set, a
carriage return. |
def receive_nak_requesting(self, pkt):
logger.debug("C3.1. Received NAK?, in REQUESTING state.")
if self.process_received_nak(pkt):
logger.debug("C3.1: T. Received NAK, in REQUESTING state, "
"raise INIT.")
raise self.INIT() | Receive NAK in REQUESTING state. |
def clear_all(tgt=None, tgt_type=):
return _clear_cache(tgt,
tgt_type,
clear_pillar_flag=True,
clear_grains_flag=True,
clear_mine_flag=True) | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Clear the cached pillar, grains, and mine data of the targeted minions
CLI Example:
.. code-block:: bash
salt-run cache.clear_all |
def load_graphml(filename, folder=None, node_type=int):
start_time = time.time()
if folder is None:
folder = settings.data_folder
path = os.path.join(folder, filename)
G = nx.MultiDiGraph(nx.read_graphml(path, node_type=node_type))
G.graph[] = ast.literal_eval(G.graph[])
... | Load a GraphML file from disk and convert the node/edge attributes to
correct data types.
Parameters
----------
filename : string
the name of the graphml file (including file extension)
folder : string
the folder containing the file, if None, use default data folder
node_type : ... |
def _resizeColumnToContents(self, header, data, col, limit_ms):
hdr_width = self._sizeHintForColumn(header, col, limit_ms)
data_width = self._sizeHintForColumn(data, col, limit_ms)
if data_width > hdr_width:
width = min(self.max_width, data_width)
elif hdr_widt... | Resize a column by its contents. |
def file_path(self, request, response=None, info=None):
return json.dumps(self._extract_key_info(request)) | 抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息 |
def invoke(self, results):
args = [results.get(d) for d in self.deps]
return self.component(*args) | Handles invocation of the component. The default implementation invokes
it with positional arguments based on order of dependency declaration. |
def get_device_model(self, cat, sub_cat, key=):
if cat + + sub_cat in self.device_models:
return self.device_models[cat + + sub_cat]
else:
for i_key, i_val in self.device_models.items():
if in i_val:
if i_val[] == key:
... | Return the model name given cat/subcat or product key |
def chi_eff(self):
return conversions.chi_eff(self.mass1, self.mass2, self.spin1z,
self.spin2z) | Returns the effective spin. |
def get(self, name):
if self.structs.has_key(name):
return self.structs[name]
elif self.enums.has_key(name):
return self.enums[name]
elif self.interfaces.has_key(name):
return self.interfaces[name]
else:
raise RpcException(ERR_INVA... | Returns the struct, enum, or interface with the given name, or raises RpcException if
no elements match that name.
:Parameters:
name
Name of struct/enum/interface to return |
def AddShapePointObjectUnsorted(self, shapepoint, problems):
if (len(self.sequence) == 0 or
shapepoint.shape_pt_sequence >= self.sequence[-1]):
index = len(self.sequence)
elif shapepoint.shape_pt_sequence <= self.sequence[0]:
index = 0
else:
index = bisect.bisect(self.sequence... | Insert a point into a correct position by sequence. |
def hgetall(key, host=None, port=None, db=None, password=None):
*
server = _connect(host, port, db, password)
return server.hgetall(key) | Get all fields and values from a redis hash, returns dict
CLI Example:
.. code-block:: bash
salt '*' redis.hgetall foo_hash |
def connection_delay(self):
time_waited = time.time() - (self.last_attempt or 0)
if self.state is ConnectionStates.DISCONNECTED:
return max(self._reconnect_backoff - time_waited, 0) * 1000
elif self.connecting():
return 0
else:
return float() | Return the number of milliseconds to wait, based on the connection
state, before attempting to send data. When disconnected, this respects
the reconnect backoff time. When connecting, returns 0 to allow
non-blocking connect to finish. When connected, returns a very large
number to handle... |
def merge_dicts(*dicts, **copy_check):
copyacababc
merged = {}
if not dicts:
return merged
for index, merge_dict in enumerate(dicts):
if index == 0 and not copy_check.get():
merged = merge_dict
else:
merged.update(merge_dict)
return merged | Combines dictionaries into a single dictionary. If the 'copy' keyword is passed
then the first dictionary is copied before update.
merge_dicts({'a': 1, 'c': 1}, {'a': 2, 'b': 1})
# => {'a': 2, 'b': 1, 'c': 1} |
def replace(self, photo_file, **kwds):
result = self._client.photo.replace(self, photo_file, **kwds)
self._replace_fields(result.get_fields()) | Endpoint: /photo/<id>/replace.json
Uploads the specified photo file to replace this photo. |
def _recurse_config_to_dict(t_data):
if not isinstance(t_data, type(None)):
if isinstance(t_data, list):
t_list = []
for i in t_data:
t_list.append(_recurse_config_to_dict(i))
return t_list
elif isinstance(t_data, dict):
t_dict = {... | helper function to recurse through a vim object and attempt to return all child objects |
def get_signing_key(self, key_type="", owner="", kid=None, **kwargs):
return self.get("sig", key_type, owner, kid, **kwargs) | Shortcut to use for signing keys only.
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:param kwargs: Extra key word arguments
:return: A possibly empty list of keys |
def _outfp_write_with_check(self, outfp, data, enable_overwrite_check=True):
t go beyond the bounds of the ISO.
Parameters:
outfp - The file object to write to.
data - The actual data to write.
enable_overwrite_check - Whether to do overwrite checking if it is enable... | Internal method to write data out to the output file descriptor,
ensuring that it doesn't go beyond the bounds of the ISO.
Parameters:
outfp - The file object to write to.
data - The actual data to write.
enable_overwrite_check - Whether to do overwrite checking if it is enab... |
def add_activation_summary(x, types=None, name=None, collections=None):
ndim = x.get_shape().ndims
if ndim < 2:
logger.warn("Cannot summarize scalar activation {}".format(x.name))
return
if types is None:
types = [, , ]
with cached_name_scope():
add_tensor_summary(x,... | Call :func:`add_tensor_summary` under a reused 'activation-summary' name scope.
This function is a no-op if not calling from main training tower.
Args:
x (tf.Tensor): the tensor to summary.
types (list[str]): summary types, defaults to ``['sparsity', 'rms', 'histogram']``.
name (str): i... |
def switch_axis_limits(ax, which_axis):
for a in which_axis:
assert a in (, )
ax_limits = ax.axis()
if a == :
ax.set_xlim(ax_limits[1], ax_limits[0])
else:
ax.set_ylim(ax_limits[3], ax_limits[2]) | Switch the axis limits of either x or y. Or both! |
def remove_all_network_profiles(self, obj):
profile_name_list = self.network_profile_name_list(obj)
for profile_name in profile_name_list:
self._logger.debug("delete profile: %s", profile_name)
str_buf = create_unicode_buffer(profile_name)
ret = self._wlan_... | Remove all the AP profiles. |
def handle_exception(self, exc_info=None, state=None, tags=None, return_feedback_urls=False,
dry_run=False):
if not exc_info:
exc_info = sys.exc_info()
if exc_info is None:
raise StackSentinelError("handle_exception called outside of exception ha... | Call this method from within a try/except clause to generate a call to Stack Sentinel.
:param exc_info: Return value of sys.exc_info(). If you pass None, handle_exception will call sys.exc_info() itself
:param state: Dictionary of state information associated with the error. This could be form data, co... |
def tokenize_math(text):
r
if text.startswith() and (
text.position == 0 or text.peek(-1) != or text.endswith(r)):
starter = if text.startswith() else
return TokenWithPosition(text.forward(len(starter)), text.position) | r"""Prevents math from being tokenized.
:param Buffer text: iterator over line, with current position
>>> b = Buffer(r'$\min_x$ \command')
>>> tokenize_math(b)
'$'
>>> b = Buffer(r'$$\min_x$$ \command')
>>> tokenize_math(b)
'$$' |
def parseFullScan(self, i, modifications=False):
scanObj = PeptideObject()
peptide = str(i[1])
pid=i[2]
scanObj.acc = self.protein_map.get(i[4], i[4])
if pid is None:
return None
if modifications:
sql = %pid
for row in self.con... | parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml |
def valueFromString(self, value, context=None):
if value in (, ):
return datetime.date.utcnow()
try:
return datetime.datetime.fromtimestamp(float(value))
except StandardError:
if dateutil_parser:
return dateutil_parser.parse(value)
... | Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str> |
def output(self, to=None, formatted=False, indent=0, indentation=, *args, **kwargs):
if formatted:
to.write(self.start_tag)
to.write()
if not self.tag_self_closes:
for blok in self.blox:
to.write(indentation * (indent + 1))
... | Outputs to a stream (like a file or request) |
def update_listener(self, lbaas_listener, body=None):
return self.put(self.lbaas_listener_path % (lbaas_listener),
body=body) | Updates a lbaas_listener. |
def directions(self, features, profile=,
alternatives=None, geometries=None, overview=None, steps=None,
continue_straight=None, waypoint_snapping=None, annotations=None,
language=None, **kwargs):
if in kwargs and geometries is None:
... | Request directions for waypoints encoded as GeoJSON features.
Parameters
----------
features : iterable
An collection of GeoJSON features
profile : str
Name of a Mapbox profile such as 'mapbox.driving'
alternatives : bool
Whether to try to ret... |
def from_json(cls, data, result=None):
if data.get("type") != cls._type_value:
raise exception.ElementDataWrongType(
type_expected=cls._type_value,
type_provided=data.get("type")
)
tags = data.get("tags", {})
way_id = data.get("i... | Create new Way element from JSON data
:param data: Element data from JSON
:type data: Dict
:param result: The result this element belongs to
:type result: overpy.Result
:return: New instance of Way
:rtype: overpy.Way
:raises overpy.exception.ElementDataWrongType:... |
def _from_dict(cls, _dict):
args = {}
if in _dict:
args[] = _dict.get(
)
else:
raise ValueError(
consumption_preference_category_id\
)
if in _dict:
args[] = _dict.get()
else:
ra... | Initialize a ConsumptionPreferencesCategory object from a json dictionary. |
def load_from_path(path, filetype=None, has_filetype=True):
if not isinstance(path, str):
try:
return path.read()
except AttributeError:
return path
path = normalize_path(path, filetype, has_filetype)
with open(path) as data:
return data.read() | load file content from a file specified as dot-separated
The file is located according to logic in normalize_path,
and the contents are returned. (See Note 1)
Parameters: (see normalize_path)
path - dot-separated path
filetype - optional filetype
... |
def get_ISSNs(self):
invalid_issns = set(self.get_invalid_ISSNs())
return [
self._clean_isbn(issn)
for issn in self["022a"]
if self._clean_isbn(issn) not in invalid_issns
] | Get list of VALID ISSNs (``022a``).
Returns:
list: List with *valid* ISSN strings. |
def _set_fcoe(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("fcoe_interface_name",fcoe.fcoe, yang_name="fcoe", rest_name="Fcoe", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, extensions={u: {... | Setter method for fcoe, mapped from YANG variable /interface/fcoe (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_fcoe() directly.
YANG De... |
def get_build_logs_zip(self, project, build_id, **kwargs):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
if build_id is not None:
route_values[] = self._serialize.url(, build_id, )
response = self._send(http_m... | GetBuildLogsZip.
Gets the logs for a build.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:rtype: object |
def avatar(self, blogname, size=64):
url = "/v2/blog/{}/avatar/{}".format(blogname, size)
return self.send_api_request("get", url) | Retrieves the url of the blog's avatar
:param blogname: a string, the blog you want the avatar for
:returns: A dict created from the JSON response |
def plot_calibration_purchases_vs_holdout_purchases(
model, calibration_holdout_matrix, kind="frequency_cal", n=7, **kwargs
):
from matplotlib import pyplot as plt
x_labels = {
"frequency_cal": "Purchases in calibration period",
"recency_cal": "Age of customer at last purchase",
... | Plot calibration purchases vs holdout.
This currently relies too much on the lifetimes.util calibration_and_holdout_data function.
Parameters
----------
model: lifetimes model
A fitted lifetimes model.
calibration_holdout_matrix: pandas DataFrame
DataFrame from calibration_and_hold... |
def _is_admin(user_id):
user = get_session().query(User).filter(User.id==user_id).one()
if user.is_admin():
return True
else:
return False | Is the specified user an admin |
def FlagsIntoString(self):
s =
for flag in self.FlagDict().values():
if flag.value is not None:
s += flag.serialize() +
return s | Returns a string with the flags assignments from this FlagValues object.
This function ignores flags whose value is None. Each flag
assignment is separated by a newline.
NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString
from http://code.google.com/p/google-gflags
Returns:
... |
async def dispatch(self, *args, **kwargs):
method = self.request_method()
if hasattr(self.request.app, ):
setattr(self, , self.request.app.db)
if method not in self.methods.get(self.endpoint, {}):
raise MethodNotImplemented("Unsupported method... | This method handles the actual request to the resource.
It performs all the neccesary checks and then executes the relevant member method which is mapped to the method name.
Handles authentication and de-serialization before calling the required method.
Handles the serialization of the response |
def _get_trailing_whitespace(marker, s):
suffix =
start = s.index(marker) + len(marker)
i = start
while i < len(s):
if s[i] in :
suffix += s[i]
elif s[i] in :
suffix += s[i]
if s[i] == and i + 1 < len(s) and s[i + 1] == :
suffix ... | Return the whitespace content trailing the given 'marker' in string 's',
up to and including a newline. |
def set_itunes_element(self):
self.set_itunes_author_name()
self.set_itunes_block()
self.set_itunes_closed_captioned()
self.set_itunes_duration()
self.set_itunes_explicit()
self.set_itune_image()
self.set_itunes_order()
self.set_itunes_subtitle()
... | Set each of the itunes elements. |
def select_postponed_date(self):
_form = forms.JsonForm(title="Postponed Workflow")
_form.start_date = fields.DateTime("Start Date")
_form.finish_date = fields.DateTime("Finish Date")
_form.save_button = fields.Button("Save")
self.form_out(_form) | The time intervals at which the workflow is to be extended are determined.
.. code-block:: python
# request:
{
'task_inv_key': string,
} |
def powerUp(self, powerup, interface=None, priority=0):
if interface is None:
for iface, priority in powerup._getPowerupInterfaces():
self.powerUp(powerup, iface, priority)
elif interface is IPowerupIndirector:
raise TypeError(
"You canno... | Installs a powerup (e.g. plugin) on an item or store.
Powerups will be returned in an iterator when queried for using the
'powerupsFor' method. Normally they will be returned in order of
installation [this may change in future versions, so please don't
depend on it]. Higher priorities... |
def start_gen(port, ser=, version=, detector=,
raw=False, nsources=1, datagen=, *,
debug=True):
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.setsockopt(zmq.LINGER, 0)
socket.bind(.format(port))
if ser != :
raise ValueError("Unknown seriali... | Karabo bridge server simulation.
Simulate a Karabo Bridge server and send random data from a detector,
either AGIPD or LPD.
Parameters
----------
port: str
The port to on which the server is bound.
ser: str, optional
The serialization algorithm, default is msgpack.
version:... |
def rank(self):
rank = ctypes.c_int()
check_call(_LIB.MXKVStoreGetRank(self.handle, ctypes.byref(rank)))
return rank.value | Returns the rank of this worker node.
Returns
-------
rank : int
The rank of this node, which is in range [0, num_workers()) |
def state_args(id_, state, high):
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(... | Return a set of the arguments passed to the named state |
def edit_config_input_target_config_target_candidate_candidate(self, **kwargs):
config = ET.Element("config")
edit_config = ET.Element("edit_config")
config = edit_config
input = ET.SubElement(edit_config, "input")
target = ET.SubElement(input, "target")
config_t... | Auto Generated Code |
def initialize_state(self):
if self.__hardware_source:
self.__data_item_states_changed_event_listener = self.__hardware_source.data_item_states_changed_event.listen(self.__data_item_states_changed)
self.__acquisition_state_changed_event_listener = self.__hardware_source.acquisit... | Call this to initialize the state of the UI after everything has been connected. |
def weekday_to_str(
weekday: Union[int, str], *, inverse: bool = False
) -> Union[int, str]:
s = [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
]
if not inverse:
try:
return s[weekday]
... | Given a weekday number (integer in the range 0, 1, ..., 6),
return its corresponding weekday name as a lowercase string.
Here 0 -> 'monday', 1 -> 'tuesday', and so on.
If ``inverse``, then perform the inverse operation. |
def selector_production(self, tokens):
validators = []
if self.peek(tokens, ):
type_ = self.match(tokens, )
validators.append(self.type_production(type_))
if self.peek(tokens, ):
key = self.match(tokens, )
validators.append(sel... | Production for a full selector. |
def write_file(filename, contents):
contents = "\n".join(contents)
contents = contents.encode("utf-8")
with open(filename, "wb") as f:
f.write(contents) | Create a file with the specified name and write 'contents' (a
sequence of strings without line terminators) to it. |
def get_top_edge_depth(self):
top_edge = self.mesh[0:1]
if top_edge.depths is None:
return 0
else:
return numpy.min(top_edge.depths) | Return minimum depth of surface's top edge.
:returns:
Float value, the vertical distance between the earth surface
and the shallowest point in surface's top edge in km. |
def measure_all(self, *qubit_reg_pairs):
if qubit_reg_pairs == ():
qubit_inds = self.get_qubits(indices=True)
if len(qubit_inds) == 0:
return self
ro = self.declare(, , max(qubit_inds) + 1)
for qi in qubit_inds:
self.inst(M... | Measures many qubits into their specified classical bits, in the order
they were entered. If no qubit/register pairs are provided, measure all qubits present in
the program into classical addresses of the same index.
:param Tuple qubit_reg_pairs: Tuples of qubit indices paired with classical bi... |
async def update_template_context(self, context: dict) -> None:
processors = self.template_context_processors[None]
if has_request_context():
blueprint = _request_ctx_stack.top.request.blueprint
if blueprint is not None and blueprint in self.template_context_processors:
... | Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate). |
def getoptT(X, W, Y, Z, S, M_E, E, m0, rho):
iter_max = 20
norm2WZ = np.linalg.norm(W, ord=)**2 + np.linalg.norm(Z, ord=)**2
f = np.zeros(iter_max + 1)
f[0] = F_t(X, Y, S, M_E, E, m0, rho)
t = -1e-1
for i in range(iter_max):
f[i + 1] = F_t(X + t * W, Y + t * Z, S, M_E, E, ... | Perform line search |
def liftover(args):
p = OptionParser(liftover.__doc__)
p.add_option("--checkvalid", default=False, action="store_true",
help="Check minscore, period and length")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
refbed, fastafile = args
... | %prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa
LiftOver CODIS/Y-STR markers. |
def actors(context):
fritz = context.obj
fritz.login()
for actor in fritz.get_actors():
click.echo("{} ({} {}; AIN {} )".format(
actor.name,
actor.manufacturer,
actor.productname,
actor.actor_id,
))
if actor.has_temperature:
... | Display a list of actors |
def insert_volume(self, metadata, attachments=[]):
log.debug("adding new volume:\n\tdata: {}\n\tfiles: {}".format(metadata, attachments))
requiredFields = []
for requiredField in requiredFields:
if requiredField not in metadata:
raise KeyError("Required fie... | Insert a new volume
Returns the ID of the added volume
`metadata` must be a dict containg metadata of the volume::
{
"_language" : "it", # language of the metadata
"key1" : "value1", # attribute
"key2" : "value2",
...
... |
def add_left_child(self, n, parent, **attrs):
if self.get_left_child(parent) is not None:
msg = "Right child already exists for node " + str(parent)
raise Exception(msg)
attrs[] =
self.set_node_attr(parent, , n)
self.add_child(n, parent, **attrs) | API: add_left_child(self, n, parent, **attrs)
Description:
Adds left child n to node parent.
Pre:
Left child of parent should not exist.
Input:
n: Node name.
parent: Parent node name.
attrs: Attributes of node n. |
def sum_of_gaussian_factory(N):
name = "SumNGauss%d" % N
attr = {}
for i in range(N):
key = "amplitude_%d" % i
attr[key] = Parameter(key)
key = "center_%d" % i
attr[key] = Parameter(key)
key = "stddev_%d" % i
attr[key] = Parameter(key)
attr[] ... | Return a model of the sum of N Gaussians and a constant background. |
def present(name, value, config=None):
ret = {: name,
: True,
: {},
: }
if config is None:
if in __salt__:
config = __salt__[]()
else:
config =
if __opts__[]:
current = __salt__[]()
configured... | Ensure that the named sysctl value is set in memory and persisted to the
named configuration file. The default sysctl configuration file is
/etc/sysctl.conf
name
The name of the sysctl value to edit
value
The sysctl value to apply
config
The location of the sysctl configur... |
def tagAttributes_while(fdef_master_list,root):
depth = 0
current = root
untagged_nodes = [root]
while untagged_nodes:
current = untagged_nodes.pop()
for x in fdef_master_list:
if jsName(x.path,x.name) == current[]:
current[] = x.path
if children ... | Tag each node under root with the appropriate depth. |
def kill(self, exit_code: Any = None):
self._force_kill.set()
if exit_code is not None:
self._exit_code = exit_code
logger.info("Killing behavior {0} with exit code: {1}".format(self, exit_code)) | Stops the behaviour
Args:
exit_code (object, optional): the exit code of the behaviour (Default value = None) |
def get_supported_binary_ops():
binary_ops = {}
binary_ops[np.add.__name__] =
binary_ops[np.subtract.__name__] =
binary_ops[np.multiply.__name__] =
binary_ops[np.divide.__name__] =
return binary_ops | Returns a dictionary of the Weld supported binary ops, with values being their Weld symbol. |
def process_post_categories(self, bulk_mode, api_post, post_categories):
post_categories[api_post["ID"]] = []
for api_category in six.itervalues(api_post["categories"]):
category = self.process_post_category(bulk_mode, api_category)
if category:
post_cate... | Create or update Categories related to a post.
:param bulk_mode: If True, minimize db operations by bulk creating post objects
:param api_post: the API data for the post
:param post_categories: a mapping of Categories keyed by post ID
:return: None |
def _extract_centerdistance(image, mask = slice(None), voxelspacing = None):
image = numpy.array(image, copy=False)
if None == voxelspacing:
voxelspacing = [1.] * image.ndim
centers = [(x - 1) / 2. for x in image.shape]
indices = numpy.indices(image.shape, dtype=numpy.flo... | Internal, single-image version of `centerdistance`. |
def create_scalar_summary(name, v):
assert isinstance(name, six.string_types), type(name)
v = float(v)
s = tf.Summary()
s.value.add(tag=name, simple_value=v)
return s | Args:
name (str):
v (float): scalar value
Returns:
tf.Summary: a tf.Summary object with name and simple scalar value v. |
def geotiff_tags(self):
if not self.is_geotiff:
return None
tags = self.tags
gkd = tags[].value
if gkd[0] != 1:
log.warning()
return {}
result = {
: gkd[0],
: gkd[1],
: gkd[2],
... | Return consolidated metadata from GeoTIFF tags as dict. |
def clean_path_middleware(environ, start_response=None):
path = environ[]
if path and in path:
url = re.sub("/+", , path)
if not url.startswith():
url = % url
qs = environ[]
if qs:
url = % (url, qs)
raise HttpRedirect(url) | Clean url from double slashes and redirect if needed. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.