Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
354,600 | def _calc_new_threshold(self, score):
if self.threshold_mode == :
abs_threshold_change = self.threshold * score
else:
abs_threshold_change = self.threshold
if self.lower_is_better:
new_threshold = score - abs_threshold_change
else:
... | Determine threshold based on score. |
354,601 | def shift(self, timezone):
try:
self._tzinfo = pytz.timezone(timezone)
except pytz.UnknownTimeZoneError:
raise DeloreanInvalidTimezone()
self._dt = self._tzinfo.normalize(self._dt.astimezone(self._tzinfo))
self._tzinfo = self._dt.tzinfo
return sel... | Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object,
modifying the Delorean object and returning the modified object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
... |
354,602 | def __get_path_parameters(self, path):
path_parameters_by_segment = {}
for format_var_name in re.findall(_PATH_VARIABLE_PATTERN, path):
first_segment = format_var_name.split(, 1)[0]
matches = path_parameters_by_segment.setdefault(first_segment, [])
matches.append(format_var_name)
ret... | Parses path paremeters from a URI path and organizes them by parameter.
Some of the parameters may correspond to message fields, and so will be
represented as segments corresponding to each subfield; e.g. first.second if
the field "second" in the message field "first" is pulled from the path.
The resu... |
354,603 | def add(self, dist):
if dist.path not in self.path:
self.path[dist.path] = dist
self.name.setdefault(dist.key, []).append(dist) | Add a distribution to the cache.
:param dist: The distribution to add. |
354,604 | def do_some_work(
self,
work_dict):
label = "do_some_work"
log.info(("task - {} - start "
"work_dict={}")
.format(label,
work_dict))
ret_data = {
"job_results": ("some response key={}").format(
str(uu... | do_some_work
:param work_dict: dictionary for key/values |
354,605 | def build_anchor_link(header_text_trimmed: str,
header_duplicate_counter: str,
parser: str = ) -> str:
r
if (parser == or parser == or parser ==
or parser == ):
header_text_trimmed = header_text_trimmed.lower()
header_t... | r"""Apply the specified slug rule to build the anchor link.
:parameter header_text_trimmed: the text that needs to be transformed
in a link.
:parameter header_duplicate_counter: a data structure that keeps track of
possible duplicate header links in order to avoid them. This is
meani... |
354,606 | def get_object_id(obj):
try:
idx = objIds.index(obj)
return idx + 1
except ValueError:
objIds.append(obj)
return len(objIds) | Get object identifier |
354,607 | def EU28as(self, to=):
if type(to) is str:
to = [to]
return self.data[self.data.EU < 2015][to] | Return EU28 countries in the specified classification
Parameters
----------
to : str, optional
Output classification (valid str for an index of
country_data file), default: name_short
Returns
-------
Pandas DataFrame |
354,608 | def compile(self, *mibnames, **options):
processed = {}
parsedMibs = {}
failedMibs = {}
borrowedMibs = {}
builtMibs = {}
symbolTableMap = {}
mibsToParse = [x for x in mibnames]
canonicalMibNames = {}
while mibsToParse:
mibname... | Transform requested and possibly referred MIBs.
The *compile* method should be invoked when *MibCompiler* object
is operational meaning at least *sources* are specified.
Once called with a MIB module name, *compile* will:
* fetch ASN.1 MIB module with given name by calling *sources*
... |
354,609 | def Set(self, value, context=None):
if self.has_error: return
if self.value is None:
self.value = value
self._context["old_value"] = value
self._context.update({"old_" + k: v for k, v in context.items()})
elif self.value != value:
self.has_error = True
self._context["new_v... | Receives a value for the object and some context on its source. |
354,610 | def p_param_substitution(self, p):
p[0] = (p[1], p[3])
p.set_lineno(0, p.lineno(1)) | param_substitution : ID EQUALS rvalue |
354,611 | def btc_make_p2wpkh_address( pubkey_hex ):
pubkey_hex = keylib.key_formatting.compress(pubkey_hex)
hash160_bin = hashing.bin_hash160(pubkey_hex.decode())
return segwit_addr_encode(hash160_bin) | Make a p2wpkh address from a hex pubkey |
354,612 | def main():
if len(argv) < 3:
print % argv[0]
print \
% argv[0]
print
print
print
print
return
alphabet = createalphabet()
mode = argv[2]
optimized = 0
splitstring = 0
if mode == :
optimized = int(argv[3... | Function for PDA to CNF Operation
:type argv: list
:param argv: Parameters |
354,613 | def get_netapp_elem(self, netapp_api=None, sub_element=None):
netapp_data = self.server.invoke_elem(netapp_api)
if netapp_data.results_status() == :
self.log.error(
% self.device)
print(netapp_data.sprintf())
return
... | Retrieve netapp elem |
354,614 | def parse_tables(self):
tables = self._parse_tables(self._build_doc(), self.match, self.attrs)
return (self._parse_thead_tbody_tfoot(table) for table in tables) | Parse and return all tables from the DOM.
Returns
-------
list of parsed (header, body, footer) tuples from tables. |
354,615 | def add_ipv6addr(self, ipv6addr):
for addr in self.ipv6addrs:
if ((isinstance(addr, dict) and addr[] == ipv6addr) or
(isinstance(addr, HostIPv4) and addr.ipv6addr == ipv6addr)):
raise ValueError()
self.ipv6addrs.append({: ipv6addr}) | Add an IPv6 address to the host.
:param str ipv6addr: The IP address to add.
:raises: ValueError |
354,616 | def version_gt(version, gt):
version_split = strip_letters(version).split()
gt_split = strip_letters(gt).split()
v_len = len(version_split)
g_len = len(gt_split)
if v_len > g_len:
longest = version_split
shortest_len = len(gt_split)
l = v_len
else:
longest =... | Code for parsing simple, numeric versions. Letters will be stripped prior to
comparison. Simple appendages such as 1-rc1 are supported. Test cases for
function are present on dscan/tests/fingerprint_tests.py |
354,617 | def get_price(self, undefined=""):
return _undefined_pattern(
"".join(self.get_subfields("020", "c")),
lambda x: x.strip() == "",
undefined
) | Args:
undefined (optional): Argument, which will be returned if the
`price` record is not found.
Returns:
str: Price of the book (with currency) or `undefined` if `price` \
is not found. |
354,618 | def int2mjd(d, loc):
if len(loc):
intcol = d[].index()
segmentcol = d[].index()
if d.has_key():
scancol = d[].index()
t0 = np.array([d[][loc[i,scancol]][loc[i,segmentcol],0] for i in range(len(loc))])
else:
t0 = d[][loc[:,segmentcol]]... | Function to convert segment+integration into mjd seconds. |
354,619 | def create_bundle(self, name=None, media_url=None,
audio_channel=None, metadata=None, notify_url=None,
external_id=None):
if len(fields) > 0:
data = fields
raw_result = self.post(path, data)
if raw_result.status < 200 ... | Create a new bundle.
'metadata' may be None, or an object that can be converted to a JSON
string. See API documentation for restrictions. The conversion
will take place before the API call.
All other parameters are also optional. For information about these
see https://api.cl... |
354,620 | def list_permissions(self, group_name=None, resource=None):
self.project_service.set_auth(self._token_project)
return self.project_service.list_permissions(group_name, resource) | List permission sets associated filtering by group and/or resource.
Args:
group_name (string): Name of group.
resource (intern.resource.boss.Resource): Identifies which data
model object to operate on.
Returns:
(list): List of permissions.
R... |
354,621 | def get_template_files(self, location, class_name):
template_name = utils.camel_to_snake(class_name)
dir_ = location[:-9] +
files_ = []
for file_ in self.get_templates_files_in_dir(dir_):
if file_.startswith(template_name) and file_.endswith((, )):
i... | Multilanguage support means that for each template
we can have multiple templtate files, this methods
returns all the template (html and txt) files
that match the (class) template name |
354,622 | def decode_coords(ds, gridfile=None):
extra_coords = set(ds.coords)
for var in six.itervalues(ds.variables):
if in var.attrs:
mesh = var.attrs[]
if mesh not in extra_coords:
extra_coords.add(mesh)
try:
... | Reimplemented to set the mesh variables as coordinates
Parameters
----------
%(CFDecoder.decode_coords.parameters)s
Returns
-------
%(CFDecoder.decode_coords.returns)s |
354,623 | def ucnstring_to_unicode(ucn_string):
ucn_string = ucnstring_to_python(ucn_string).decode()
assert isinstance(ucn_string, text_type)
return ucn_string | Return ucnstring as Unicode. |
354,624 | def print_pos(self, coordinates=None, pos=None):
if not pos:
pos = self.pos
self.graph = [list(map(self._transform, pos[i])) for i in self.pos_range]
xaxis = .join([chr(ASC_ONE + _) for _ in range(min(self.board_size, MAX_NUM))])
if (self.board_size > MAX_NUM):
... | Print the chessboard |
354,625 | def needs_remesh(self):
return len(self.features) > 0 or self.is_misaligned or self.ecc != 0 or self.dynamics_method != | whether the star needs to be re-meshed (for any reason) |
354,626 | def community_post_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/posts
api_path = "/api/v2/community/posts.json"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/help_center/posts#create-post |
354,627 | def proxy_property_directly(bind_attr, attrs):
def cls_builder(cls):
for attr_name in attrs:
setattr(cls, attr_name, _make_proxy_property(bind_attr, attr_name))
return cls
return cls_builder | 为类添加代理属性 |
354,628 | def as_command(self, sock_info):
if self._as_command is not None:
return self._as_command
explain = in self.spec
cmd = _gen_find_command(
self.coll, self.spec, self.fields, self.ntoskip,
self.limit, self.batch_size, self.flags, sel... | Return a find command document for this query. |
354,629 | def datagramReceived(self, data):
try:
obj = json.loads(data)
except ValueError, e:
log.err(e, % data)
return
if u in obj:
obj = Status.fromDict(obj)
else:
log.msg( % obj)
return
self.callback(obj... | Decode the JSON-encoded datagram and call the callback. |
354,630 | def to_grid(self, mapping):
return list(reversed([[mapping.get((x,y), None)
for x in range(self.cols)]
for y in range(self.rows)])) | Convert a mapping from (x, y) to v into a [[..., v, ...]] grid. |
354,631 | def get_column_definition_all(self, table):
col_defs = self.get_table_definition(table).split()
return [i[0:-1].strip().replace(, ) for i in col_defs if i.strip().startswith()] | Retrieve the column definition statement for all columns in a table. |
354,632 | def plot_multiple_regions_coverage(samples, out_file, data, region_bed=None, stem_bed=None):
mpl.use(, force=True)
PAD = 100
if file_exists(out_file):
return out_file
in_bams = [dd.get_align_bam(x) for x in samples]
samplenames = [dd.get_sample_name(x) for x in samples]
if isinstanc... | given a list of bcbio samples and a bed file or BedTool of regions,
makes a plot of the coverage in the regions for the set of samples
if given a bed file or BedTool of locations in stem_bed with a label,
plots lollipops at those locations |
354,633 | def value(self):
val = {}
if self.sourcelocale is not None:
val[] = self.sourcelocale
if self.geocodeServiceUrl is not None:
val[] = self.geocodeServiceUrl
if self.sourcecountry is not None:
val[] = self.sourcecountry
if self.sourcecou... | returns object as a dictionary |
354,634 | def generate_PVdelV_nt_pos_vecs(self, generative_model, genomic_data):
cutV_genomic_CDR3_segs = genomic_data.cutV_genomic_CDR3_segs
nt2num = {: 0, : 1, : 2, : 3}
num_del_pos = generative_model.PdelV_given_V.shape[0]
num_V_genes = generative_model.PdelV_given_V.shape[1]
... | Process P(delV|V) into Pi arrays.
Set the attributes PVdelV_nt_pos_vec and PVdelV_2nd_nt_pos_per_aa_vec.
Parameters
----------
generative_model : GenerativeModelVJ
VJ generative model class containing the model parameters.
genomic_data : Geno... |
354,635 | def assert_finite(x, data=None, summarize=None, message=None, name=None):
with tf.compat.v2.name_scope(name or ):
x_ = tf.get_static_value(x)
if x_ is not None:
if ~np.all(np.isfinite(x_)):
raise ValueError(message)
return x
assertion = tf.compat.v1.assert_equal(
tf.math.is_... | Assert all elements of `x` are finite.
Args:
x: Numeric `Tensor`.
data: The tensors to print out if the condition is False. Defaults to
error message and first few entries of `x`.
summarize: Print this many entries of each tensor.
message: A string to prefix to the default message.
name:... |
354,636 | def get_token_identifiers(
chain_state: ChainState,
payment_network_id: PaymentNetworkID,
) -> List[TokenAddress]:
payment_network = chain_state.identifiers_to_paymentnetworks.get(payment_network_id)
if payment_network is not None:
return [
token_address
for... | Return the list of tokens registered with the given payment network. |
354,637 | def _massage_data(self):
self._xdata_massaged, self._ydata_massaged, self._eydata_massaged = self.get_processed_data()
return self | Processes the data and stores it. |
354,638 | def make_admin_on_demand_service(injector_gear):
LOGGER.debug("InjectorCachedGearService.make_admin_on_demand_service")
args = {
: injector_gear.id,
: injector_gear.admin,
: injector_gear.id + " - On Demand Start/Stop Service"
}
return Injecto... | create an admin service to stop or start the linked gear
:param injector_gear: the gear to be linked to this admin service
:return: the service created |
354,639 | def download_tile(map_layer, zoom, x, y):
try:
tile_url = map_layer.get_tile_url(zoom, x, y)
tmp_file, headers = urllib.request.urlretrieve(tile_url)
return (x, y), tmp_file
except URLError as e:
app.logger.info("Error downloading tile x={}, y={}, z={} for layer {}: {}".form... | Download a given tile from the tile server.
Args:
map_layer (MapLayer): MapLayer object which provides the tile-url.
zoom (int): zoom level
x (int): Tile-x-coordinate
y (int): Tile-y-coordinate
Returns:
file: temporary file containing the downloaded image. |
354,640 | def clear(self, keep_input=True):
if self._executing:
self._control.clear()
else:
if keep_input:
input_buffer = self.input_buffer
self._control.clear()
self._show_prompt()
if keep_input:
self.input_buffe... | Clear the console.
Parameters:
-----------
keep_input : bool, optional (default True)
If set, restores the old input buffer if a new prompt is written. |
354,641 | def list_categories(self):
self.section("Classes of commands:")
cats = list(categories.keys())
cats.sort()
for cat in cats:
self.rst_msg(line)
pass
return | List the command categories and a short description of each. |
354,642 | def registerInternalRouters(app):
urlPath = CONF.get("endpointRoot", "flask-profiler")
fp = Blueprint(
, __name__,
url_prefix="/" + urlPath,
static_folder="static/dist/", static_url_path=)
@fp.route("/".format(urlPath))
@auth.login_required
def index():
return ... | These are the endpoints which are used to display measurements in the
flask-profiler dashboard.
Note: these should be defined after wrapping user defined endpoints
via wrapAppEndpoints()
:param app: Flask application instance
:return: |
354,643 | def get_client_str(username: str, ip_address: str, user_agent: str, path_info: str) -> str:
client_dict = dict()
if settings.AXES_VERBOSE:
client_dict[] = username
client_dict[] = ip_address
client_dict[] = user_agent
else:
client_dict = get_client_pa... | Get a readable string that can be used in e.g. logging to distinguish client requests.
Example log format would be ``{username: "example", ip_address: "127.0.0.1", path_info: "/example/"}`` |
354,644 | def ccall(self, ret_type, func_obj, args):
list_args = list(args)
new_args = []
for arg in list_args:
if isinstance(arg, VexValue):
arg = arg.rdt
new_args.append(arg)
args = tuple(new_args)
if isinstance(func_ob... | Creates a CCall operation.
A CCall is a procedure that calculates a value at *runtime*, not at lift-time.
You can use these for flags, unresolvable jump targets, etc.
We caution you to avoid using them when at all possible though.
For an example of how to write and use a CCall, see gymr... |
354,645 | def wait_for_bump(self, buttons, timeout_ms=None):
start_time = time.time()
if self.wait_for_pressed(buttons, timeout_ms):
if timeout_ms is not None:
timeout_ms -= int((time.time() - start_time) * 1000)
return self.wait_for_released(buttons, timeout_ms)
... | Wait for the button to be pressed down and then released.
Both actions must happen within timeout_ms. |
354,646 | def set_dn(self,dn):
try:
domain_col = self.table[][].index()
for row_idx in range(len(self.table[][])):
row_list = list(self.table[][][row_idx])
row_list[domain_col] = dn
self.table[][][row_idx] = tuple(row_list)
except ValueError:
self.table[][][] =
self.t... | Use the domain column in the process table to store the DN
dn = dn to be added |
354,647 | def create_volume(self, project_id, plan, size, facility, label=""):
try:
return self.manager.create_volume(project_id, label, plan, size, facility)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg) | Creates a new volume. |
354,648 | def warn_deprecated(msg, stacklevel=2):
import warnings
warnings.warn(msg,
category=DeprecationWarning,
stacklevel=stacklevel) | Generate a non-silent deprecation warning with stacktrace.
The used warning is ``imgaug.imgaug.DeprecationWarning``.
Parameters
----------
msg : str
The message of the warning.
stacklevel : int, optional
How many steps above this function to "jump" in the stacktrace for
th... |
354,649 | def get_redis_connection():
if config.MOCK_REDIS:
import mockredis
return mockredis.mock_strict_redis_client()
elif config.DEFENDER_REDIS_NAME:
try:
cache = caches[config.DEFENDER_REDIS_NAME]
except InvalidCacheBackendError:
raise KeyError(INVAL... | Get the redis connection if not using mock |
354,650 | def hasannotation(self,Class,set=None):
return sum( 1 for _ in self.select(Class,set,True,default_ignore_annotations)) | Returns an integer indicating whether such as annotation exists, and if so, how many.
See :meth:`AllowTokenAnnotation.annotations`` for a description of the parameters. |
354,651 | def add_host(self, endpoint, datacenter=None, rack=None, signal=True, refresh_nodes=True):
host, new = self.metadata.add_or_return_host(Host(endpoint, self.conviction_policy_factory, datacenter, rack))
if new and signal:
log.info("New Cassandra host %r discovered", host)
... | Called when adding initial contact points and when the control
connection subsequently discovers a new node.
Returns a Host instance, and a flag indicating whether it was new in
the metadata.
Intended for internal use only. |
354,652 | def show_plane(orig, n, scale=1.0, **kwargs):
b1 = orthogonal_vector(n)
b1 /= la.norm(b1)
b2 = np.cross(b1, n)
b2 /= la.norm(b2)
verts = [orig + scale*(-b1 - b2),
orig + scale*(b1 - b2),
orig + scale*(b1 + b2),
orig + scale*(-b1 + b2)]
faces = [(0, 1, ... | Show the plane with the given origin and normal. scale give its size |
354,653 | def activities(self):
if self._activities is None:
self.assert_bind_client()
self._activities = self.bind_client.get_club_activities(self.id)
return self._activities | An iterator of reverse-chronological :class:`stravalib.model.Activity` activities for this club. |
354,654 | def verify(self, store, flags, data=None, certs=None):
bio = None
if data != None:
bio_obj = Membio(data)
bio = bio_obj.bio
if certs is not None and len(certs) > 0:
certstack_obj = StackOfX509(certs)
certstack = certstack_obj.ptr
... | Verifies signature under CMS message using trusted cert store
@param store - X509Store object with trusted certs
@param flags - OR-ed combination of flag consants
@param data - message data, if messge has detached signature
param certs - list of certificates to use during verification
... |
354,655 | def render(self, name, value, attrs=None, renderer=None):
output = [super(TagAutoComplete, self).render(name, value, attrs)]
output.append()
output.append()
output.append()
output.append( % name)
output.append()
output.append()
output.append()
... | Render the default widget and initialize select2. |
354,656 | def restore(self):
if self._fire_model_event("restoring") is False:
return False
setattr(self, self.get_deleted_at_column(), None)
self.set_exists(True)
result = self.save()
self._fire_model_event("restored")
return result | Restore a soft-deleted model instance. |
354,657 | def get_room_id(self, room_alias):
content = self._send("GET", "/directory/room/{}".format(quote(room_alias)))
return content.get("room_id", None) | Get room id from its alias.
Args:
room_alias (str): The room alias name.
Returns:
Wanted room's id. |
354,658 | def from_df(cls, data, entities=None, source=):
variables = []
for col in data.columns:
_data = pd.DataFrame(data[col].values, columns=[])
if entities is not None:
_data = pd.concat([_data, entities], axis=1, sort=True)
variables.append(Simple... | Create a Collection from a pandas DataFrame.
Args:
df (DataFrame): The DataFrame to convert to a Collection. Each
column will be converted to a SimpleVariable.
entities (DataFrame): An optional second DataFrame containing
entity information.
s... |
354,659 | def _dist(self, x, y, A):
"(x - y)^T A (x - y)"
return scipy.spatial.distance.mahalanobis(x, y, A) ** 2 | (x - y)^T A (x - y) |
354,660 | def _expand_overlap(dna, oligo_indices, index, oligos, length_max):
left_len = len(oligos[index])
right_len = len(oligos[index + 1])
if right_len == length_max:
oligo_indices[1] = _adjust_overlap(oligo_indices[1], index, )
elif left_len == length_max:
oligo_indices[0] = _adjus... | Given an overlap to increase, increases smaller oligo.
:param dna: Sequence being split into oligos.
:type dna: coral.DNA
:param oligo_indices: index of oligo starts and stops
:type oligo_indices: list
:param index: index of the oligo
:type index: int
:param left_len: length of left oligo
... |
354,661 | def fuzzy_match_tipnames(ttree, names, wildcard, regex, mrca=True, mono=True):
if not any([names, wildcard, regex]):
raise ToytreeError(
"must enter an outgroup, wildcard selector, or regex pattern")
tips = []
if names:
if isinstance(names, (str, int)):
... | Used in multiple internal functions (e.g., .root()) and .drop_tips())
to select an internal mrca node, or multiple tipnames, using fuzzy matching
so that every name does not need to be written out by hand.
name: verbose list
wildcard: matching unique string
regex: regex expression
mrca: return ... |
354,662 | async def create_lease_store_if_not_exists_async(self):
try:
await self.host.loop.run_in_executor(
self.executor,
functools.partial(
self.storage_client.create_container,
self.lease_container_name))
except Exce... | Create the lease store if it does not exist, do nothing if it does exist.
:return: `True` if the lease store already exists or was created successfully, `False` if not.
:rtype: bool |
354,663 | def blank(self, channel):
self._image = None
info = channel.extdata._header_info
info.table.clear() | This is called when image is cleared. |
354,664 | def _convert_eta_to_c(eta, ref_position):
exp_eta = np.exp(eta)
exp_eta[np.isposinf(exp_eta)] = max_comp_value
exp_eta[exp_eta == 0] = min_comp_value
denom = exp_eta.sum(axis=0) + 1
replace_list = list(range(eta.shape[0] + 1))
replace_list.remove(r... | Parameters
----------
eta : 1D or 2D ndarray.
The elements of the array should be this model's 'transformed' shape
parameters, i.e. the natural log of (the corresponding shape parameter
divided by the reference shape parameter). This array's elements will
be real valued. If `eta`... |
354,665 | def get_release_task_attachment_content(self, project, release_id, environment_id, attempt_id, plan_id, timeline_id, record_id, type, name, **kwargs):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
if release_id is not None:
... | GetReleaseTaskAttachmentContent.
[Preview API]
:param str project: Project ID or project name
:param int release_id:
:param int environment_id:
:param int attempt_id:
:param str plan_id:
:param str timeline_id:
:param str record_id:
:param str type... |
354,666 | def configure_cmake(self):
cmake = CMake(self)
cmake.definitions["FLATBUFFERS_BUILD_TESTS"] = False
cmake.definitions["FLATBUFFERS_BUILD_SHAREDLIB"] = self.options.shared
cmake.definitions["FLATBUFFERS_BUILD_FLATLIB"] = not self.options.shared
cmake.configure()
r... | Create CMake instance and execute configure step |
354,667 | def set(self, key: bytes, value: bytes) -> Tuple[Hash32]:
validate_is_bytes(key)
validate_length(key, self._key_size)
validate_is_bytes(value)
path = to_int(key)
node = value
_, branch = self._get(key)
proof_update = []
target_bit = 1
... | Returns all updated hashes in root->leaf order |
354,668 | def set_runtime_value_int(self, resourceid: int, intvalue: int):
payload = .format(id=resourceid, value=intvalue)
xdoc = self.connection.soap_action(,
, payload)
if xdoc:
result = xdoc.find(,
IHCSoapCl... | Set a integer runtime value |
354,669 | def crypto_config_from_kwargs(fallback, **kwargs):
try:
crypto_config = kwargs.pop("crypto_config")
except KeyError:
try:
fallback_kwargs = {"table_name": kwargs["TableName"]}
except KeyError:
fallback_kwargs = {}
crypto_config = fallback(**fallback_k... | Pull all encryption-specific parameters from the request and use them to build a crypto config.
:returns: crypto config and updated kwargs
:rtype: dynamodb_encryption_sdk.encrypted.CryptoConfig and dict |
354,670 | def _apply(self, force=False):
if self.displayed == self.active_layout and not force:
return
combination, mode = self.combinations_map.get(self.displayed, (None, None))
if combination is None and mode is None:
return
cmd = "xra... | Call xrandr and apply the selected (displayed) combination mode. |
354,671 | def list_installed():
*
cmd = \
\
\
features = _pshell_json(cmd)
ret = {}
for entry in features:
if entry[]:
ret[entry[]] = entry[]
return ret | List installed features. Supported on Windows Server 2008 and Windows 8 and
newer.
Returns:
dict: A dictionary of installed features
CLI Example:
.. code-block:: bash
salt '*' win_servermanager.list_installed |
354,672 | def get_starred(self):
return github.PaginatedList.PaginatedList(
github.Repository.Repository,
self._requester,
"/user/starred",
None
) | :calls: `GET /user/starred <http://developer.github.com/v3/activity/starring>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository` |
354,673 | def define_from_fits(cls, fitsobj, extnum=0):
with fits.open(fitsobj) as hdulist:
image_header = hdulist[extnum].header
return cls.define_from_header(image_header) | Define class object from header information in FITS file.
Parameters
----------
fitsobj: file object
FITS file whose header contains the DTU information
needed to initialise the members of this class.
extnum : int
Extension number (first extension is ... |
354,674 | def schema_val(self, messages=None):
"Perform validation with processed YAML and Schema"
self._ymlproc = YAMLProcessor(self._ymlfile)
self._schemaproc = SchemaProcessor(self._schemafile)
valid = True
log.debug("BEGIN: Schema-based validation for YAML with schema ", self._ymlfil... | Perform validation with processed YAML and Schema |
354,675 | def singular_noun(self, text, count=None, gender=None):
pre, word, post = self.partition_word(text)
if not word:
return text
sing = self._sinoun(word, count=count, gender=gender)
if sing is not False:
plural = self.postprocess(
word, self.... | Return the singular of text, where text is a plural noun.
If count supplied, then return the singular if count is one of:
1, a, an, one, each, every, this, that or if count is None
otherwise return text unchanged.
Whitespace at the start and end is preserved. |
354,676 | def _token_auth(self):
return TcExTokenAuth(
self,
self.args.tc_token,
self.args.tc_token_expires,
self.args.tc_api_path,
self.tcex.log,
) | Add ThreatConnect Token Auth to Session. |
354,677 | def read(path):
url = .format(settings.VAULT_BASE_URL.rstrip(),
settings.VAULT_BASE_SECRET_PATH.strip(),
path.lstrip())
headers = {: settings.VAULT_ACCESS_TOKEN}
resp = requests.get(url, headers=headers)
if resp.ok:
return resp.json()... | Read a secret from Vault REST endpoint |
354,678 | def edit(self, resource):
schema = TagSchema(only=(, , , , ))
json = self.service.encode(schema, resource)
schema = TagSchema()
resp = self.service.edit(self.base, resource.name, json)
return self.service.decode(schema, resp) | Edit a tag.
:param resource: :class:`tags.Tag <tags.Tag>` object
:return: :class:`tags.Tag <tags.Tag>` object
:rtype: tags.Tag |
354,679 | def bind(self, devices_to_bind):
if self.entity_api_key == "":
return {: , : }
url = self.base_url + "api/0.1.0/subscribe/bind"
headers = {"apikey": self.entity_api_key}
data = {
"exchange": "amq.topic",
"keys": devices_to_bind,
"q... | This function allows an entity to list the devices to subscribe for data. This function must be called
at least once, before doing a subscribe. Subscribe function will listen to devices that are bound here.
Args:
devices_to_bind (list): an array of devices to listen to.
... |
354,680 | def mkpath(self, url, path, filename=None, gzip=False):
if path:
url = "%s/%s" % (url.rstrip(), path.strip())
if filename:
url = "%s/%s" % (url, filename.lstrip())
content_type = mimetypes.guess_type(url)[0]
if gzip and content_type in mediasync... | Assembles various components to form a complete resource URL.
args:
url: (str) A base media URL.
path: (str) The path on the host (specified in 'url') leading up
to the file.
filename: (str) The file name to serve.
gzip: (bool) True if clien... |
354,681 | def get_color_theme(theme):
import salt.utils.data
import salt.utils.files
import salt.utils.yaml
if not os.path.isfile(theme):
log.warning(, theme)
try:
with salt.utils.files.fopen(theme, ) as fp_:
colors = salt.utils.data.decode(salt.utils.yaml.safe_load(fp_)... | Return the color theme to use |
354,682 | def _determine_doubled_obj(self):
if isinstance(self.obj, ObjectDouble):
return self.obj._doubles_target
else:
return self.obj | Return the target object.
Returns the object that should be treated as the target object. For partial doubles, this
will be the same as ``self.obj``, but for pure doubles, it's pulled from the special
``_doubles_target`` attribute.
:return: The object to be doubled.
:rtype: obj... |
354,683 | def visitCodeDecl(self, ctx: ShExDocParser.CodeDeclContext):
semact = SemAct()
semact.name = self.context.iri_to_iriref(ctx.iri())
if ctx.CODE():
semact.code = ctx.CODE().getText()[1:-2].replace(, ).encode().decode()
self.semacts.append(semact) | codeDecl: '%' iri (CODE | '%')
CODE: : '{' (~[%\\] | '\\' [%\\] | UCHAR)* '%' '}' |
354,684 | def set_completed(self, *, completition_date=None):
self.__status = Flag.Complete
completition_date = completition_date or dt.datetime.now()
if completition_date.tzinfo is None:
completition_date = self.protocol.timezone.localize(completition_date)
self.__completed =... | Sets this message flag as completed
:param completition_date: the datetime this followUp was completed |
354,685 | def _main(instaloader: Instaloader, targetlist: List[str],
username: Optional[str] = None, password: Optional[str] = None,
sessionfile: Optional[str] = None,
download_profile_pic: bool = True, download_posts=True,
download_stories: bool = False, download_highlights: bool = False,... | Download set of profiles, hashtags etc. and handle logging in and session files if desired. |
354,686 | def register_hook(self, hook, event_type=None):
if event_type is not None:
assert type(event_type) is int, "register hooks with int values"
return self.hooks[event_type].append(hook)
for event_type in EventType._fields:
func = getattr(hook, event_type, None)... | If ``event_type`` is provided, then ``hook`` will be called whenever
that event is fired.
If no ``event_type`` is specifid, but ``hook`` implements any methods
with names matching an event hook, then those will be registered with
their corresponding events. This allows for more stateful... |
354,687 | def memory_read(self, start_position: int, size: int) -> memoryview:
return self._memory.read(start_position, size) | Read and return a view of ``size`` bytes from memory starting at ``start_position``. |
354,688 | def consistency(self, consistency):
clone = copy.deepcopy(self)
clone._consistency = consistency
return clone | Sets the consistency level for the operation. See :class:`.ConsistencyLevel`.
.. code-block:: python
for user in User.objects(id=3).consistency(CL.ONE):
print(user) |
354,689 | def initGroupStyle(self, useIcons=True, columnCount=None):
flags = self.flags()
if flags & QtCore.Qt.ItemIsSelectable:
flags ^= QtCore.Qt.ItemIsSelectable
self.setFlags(flags)
if useIcons:
ico = QtGui.QIcon(resources.find(... | Initialzes this item with a grouping style option. |
354,690 | def patch_validating_webhook_configuration(self, name, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.patch_validating_webhook_configuration_with_http_info(name, body, **kwargs)
else:
(data) = self.patch_validating_webhook_configuration_with_http_i... | partially update the specified ValidatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_validating_webhook_configuration(name, body, async_req=True)
>>> result = thread.... |
354,691 | def get_help_datapacks(filepath, prefix="!"):
help_contents = get_help_data(filepath)
datapacks = []
for d in help_contents:
heading = d
content = ""
if "commands" in d.lower():
for c in help_contents[d]:
if "name" not in c:
... | Load help text from a file and give it as datapacks
Args:
filepath (str): The file to load help text from
prefix (str): The prefix to use for commands
Returns:
datapacks (list): The datapacks from the file |
354,692 | def update(self, data):
updated = self.set_property(, data[])
updated |= self.set_property(, sorted(data[] or []))
updated |= self.set_property(, data[])
if updated:
self.set_property(, datetime.now())
return updated | Updates the object information based on live data, if there were any changes made. Any changes will be
automatically applied to the object, but will not be automatically persisted. You must manually call
`db.session.add(instance)` on the object.
Args:
data (:obj:): AWS API Resource ... |
354,693 | def main(
gpu:Param("GPU to run on", str)=None,
lr: Param("Learning rate", float)=1e-3,
size: Param("Size (px: 128,192,224)", int)=128,
debias_mom: Param("Debias statistics", bool)=False,
debias_sqr: Param("Debias statistics", bool)=False,
opt: Param("Optimizer: ,,,", str... | Distributed training of Imagenette.
Fastest multi-gpu speed is if you run with: python -m fastai.launch |
354,694 | def __find_and_modify(self, filter, projection, sort, upsert=None,
return_document=ReturnDocument.BEFORE,
array_filters=None, session=None, **kwargs):
common.validate_is_mapping("filter", filter)
if not isinstance(return_document, bool):
... | Internal findAndModify helper. |
354,695 | def load_from_json(db_file, language=DEFAULT_LANG):
data = {
: raw[],
: raw[],
: DBVuln.handle_ref(raw[], language=language),
: raw[],
: raw.get(, []),
: raw.get(, []),
: raw.get(, []),
... | Parses the JSON data and returns it
:param db_file: File and path pointing to the JSON file to parse
:param language: The user's language (en, es, etc.)
:raises: All kind of exceptions if the file doesn't exist or JSON is
invalid.
:return: None |
354,696 | def _analyze_function_features(self, all_funcs_completed=False):
changes = {
: [],
: []
}
if self._updated_nonreturning_functions is not None:
all_func_addrs = self._updated_nonreturning_functions
all_functions = [ self.kb.... | For each function in the function_manager, try to determine if it returns or not. A function does not return if
it calls another function that is known to be not returning, and this function does not have other exits.
We might as well analyze other features of functions in the future.
:param b... |
354,697 | def create(self):
created_id = self._post_request(
data=self.element_to_string(self.encode())
).headers.get().split()[-1]
return self.get(created_id) | Creates the object
:return: the created object
:rtype: object |
354,698 | def ensure_dir(path):
try:
log.info( % path)
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise | Ensure that a needed directory exists, creating it if it doesn't |
354,699 | def Li_Wu(m, x, D, rhol, rhog, mul, kl, Hvap, sigma, q=None, Te=None):
r
G = m/(pi/4*D**2)
Rel = G*D*(1-x)/mul
Bo = Bond(rhol=rhol, rhog=rhog, sigma=sigma, L=D)
if q:
Bg = Boiling(G=G, q=q, Hvap=Hvap)
return 334*Bg**0.3*(Bo*Rel**0.36)**0.4*kl/D
elif Te:
A = 334*(Bo*Rel**0... | r'''Calculates heat transfer coefficient for film boiling of saturated
fluid in any orientation of flow. Correlation
is as shown in [1]_, and also reviewed in [2]_ and [3]_.
Either the heat flux or excess temperature is required for the calculation
of heat transfer coefficient. Uses liquid Reynolds... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.