Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
343,900 | def process(fn, bound_names):
if isinstance(fn, _AutoContext):
fn = fn.fn
if isinstance(fn, _FnCodeStr):
if bound_names:
assign_code_str = .format(
syms=.join(bound_names) + , names=repr(bound_names))
else:
assign_code_str =
... | process automatic context variable capturing.
return the transformed function and its ast. |
343,901 | def process_result(self, new_sia, min_sia):
if new_sia.phi == 0:
self.done = True
return new_sia
elif new_sia < min_sia:
return new_sia
return min_sia | Check if the new SIA has smaller |big_phi| than the standing
result. |
343,902 | def _relevant_connections(self, subsystem):
_from, to = self.direction.order(self.mechanism, self.purview)
return connectivity.relevant_connections(subsystem.network.size,
_from, to) | Identify connections that “matter” to this concept.
For a |MIC|, the important connections are those which connect the
purview to the mechanism; for a |MIE| they are the connections from the
mechanism to the purview.
Returns an |N x N| matrix, where `N` is the number of nodes in this
... |
343,903 | def f_remove(self, *args):
for arg in args:
arg = self.f_translate_key(arg)
if arg in self._data:
del self._data[arg]
else:
raise AttributeError( % (self.name_, arg)) | Removes `*args` from the result |
343,904 | def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
parts = []
parts.append(super(XmlObjectForm, self)._html_output(normal_row, error_row, row_ender,
help_text_html, errors_on_separate_row))
def _subform_output(subform):
... | Extend BaseForm's helper function for outputting HTML. Used by as_table(), as_ul(), as_p().
Combines the HTML version of the main form's fields with the HTML content
for any subforms. |
343,905 | def load(self, cfgstr=None):
from six.moves import cPickle as pickle
cfgstr = self._rectify_cfgstr(cfgstr)
dpath = self.dpath
fname = self.fname
verbose = self.verbose
if not self.enabled:
if verbose > 1:
self.log(.format(self.fname)... | Loads the data
Raises:
IOError - if the data is unable to be loaded. This could be due to
a cache miss or because the cache is disabled.
Example:
>>> from ubelt.util_cache import * # NOQA
>>> # Setting the cacher as enabled=False turns it off
... |
343,906 | def eval(self, code, *args):
warnings.warn("Database.eval() is deprecated",
DeprecationWarning, stacklevel=2)
if not isinstance(code, Code):
code = Code(code)
result = self.command("$eval", code, args=args)
return result.get("retval", None) | **DEPRECATED**: Evaluate a JavaScript expression in MongoDB.
:Parameters:
- `code`: string representation of JavaScript code to be
evaluated
- `args` (optional): additional positional arguments are
passed to the `code` being evaluated
.. warning:: the eval c... |
343,907 | def get_edges_as_list(self):
my_edges = []
for edge_node in self.__get_edge_nodes():
my_edges.append(Cedge(edge_node))
return my_edges | Iterator that returns all the edge objects
@rtype: L{Cedge}
@return: terminal objects (iterator) |
343,908 | def add_config(self, config):
for attr in self.__fixed_attrs:
if attr in config:
raise Exception("cannot set outside of init", attr)
stages = config.get(, None)
if stages:
self.stages = stages
self.__dry_run... | Update internel configuration dict with config and recheck |
343,909 | def assign(institute_id, case_name, user_id=None):
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
link = url_for(, institute_id=institute_id, case_name=case_name)
if user_id:
user_obj = store.user(user_id)
else:
user_obj = store.user(current_user.email)... | Assign and unassign a user from a case. |
343,910 | def rss_parse(self, response):
match = re.match(re_export, response.text)
if match:
last_update_zip_url = match.group(1)
r = requests.get(last_update_zip_url)
z = zipfile.ZipFile(io.BytesIO(r.content))
extracted ... | Extracts all article links and initiates crawling them.
:param obj response: The scrapy response |
343,911 | def close(self):
for key in self.masklist.keys():
self.masklist[key] = None
self.masklist = {} | Deletes all static mask objects. |
343,912 | def plist(iterable=(), reverse=False):
if not reverse:
iterable = list(iterable)
iterable.reverse()
return reduce(lambda pl, elem: pl.cons(elem), iterable, _EMPTY_PLIST) | Creates a new persistent list containing all elements of iterable.
Optional parameter reverse specifies if the elements should be inserted in
reverse order or not.
>>> plist([1, 2, 3])
plist([1, 2, 3])
>>> plist([1, 2, 3], reverse=True)
plist([3, 2, 1]) |
343,913 | def restore_bios_config(irmc_info, bios_config):
def _process_bios_config():
try:
if isinstance(bios_config, dict):
input_data = bios_config
else:
input_data = jsonutils.loads(bios_config)
bios_cfg = input_d... | restore bios configuration
This function sends a RESTORE BIOS request to the server. Then when the
bios
is ready for restoring, it will apply the provided settings and return.
Note that this operation may take time.
:param irmc_info: node info
:param bios_config: bios config |
343,914 | def launch_shell(username, hostname, password, port=22):
if not username or not hostname or not password:
return False
with tempfile.NamedTemporaryFile() as tmpFile:
os.system(sshCmdLine.format(password, tmpFile.name, username, hostname,
port))
retur... | Launches an ssh shell |
343,915 | def set_tensor_symmetry_PJ(force_constants,
lattice,
positions,
symmetry):
rotations = symmetry.get_symmetry_operations()[]
translations = symmetry.get_symmetry_operations()[]
symprec = symmetry.get_symmetry_tolerance()
... | Full force constants are symmetrized using crystal symmetry.
This method extracts symmetrically equivalent sets of atomic pairs and
take sum of their force constants and average the sum.
Since get_force_constants_disps may include crystal symmetry, this method
is usually meaningless. |
343,916 | def linked_model_for_class(self, cls, make_constants_variable=False, **kwargs):
constructor_args = inspect.getfullargspec(cls).args
attribute_tuples = self.attribute_tuples
new_model = PriorModel(cls)
for attribute_tuple in attribute_tuples:
name = attribute_tuple.na... | Create a PriorModel wrapping the specified class with attributes from this instance. Priors can be overridden
using keyword arguments. Any constructor arguments of the new class for which there is no attribute associated
with this class and no keyword argument are created from config.
If make_c... |
343,917 | def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
envs = [EnvFactory() for i in range(n)]
return [(A, test_agent(A, steps, copy.deepcopy(envs)))
for A in AgentFactories] | See how well each of several agents do in n instances of an environment.
Pass in a factory (constructor) for environments, and several for agents.
Create n instances of the environment, and run each agent in copies of
each one for steps. Return a list of (agent, average-score) tuples. |
343,918 | def windowed_weir_cockerham_fst(pos, g, subpops, size=None, start=None,
stop=None, step=None, windows=None,
fill=np.nan, max_allele=None):
a, b, c = weir_cockerham_fst(g, subpops, max_allele=max_allele)
def average_fst(wa, wb, wc):... | Estimate average Fst in windows over a single chromosome/contig,
following the method of Weir and Cockerham (1984).
Parameters
----------
pos : array_like, int, shape (n_items,)
Variant positions, using 1-based coordinates, in ascending order.
g : array_like, int, shape (n_variants, n_sampl... |
343,919 | def get_uri_prefix_map(self):
mapping = {}
for ni in six.itervalues(self.__ns_uri_map):
if ni.preferred_prefix:
mapping[ni.uri] = ni.preferred_prefix
elif len(ni.prefixes) > 0:
mapping[ni.uri] = next(iter(ni.prefixes))
... | Constructs and returns a map from namespace URI to prefix,
representing all namespaces in this set. The prefix chosen for each
namespace is its preferred prefix if it's not None. If the preferred
prefix is None, one is chosen from the set of registered
prefixes. In the latter situatio... |
343,920 | def getAnalysisRequests(self, **kwargs):
brains = self.getAnalysisRequestsBrains(**kwargs)
return [b.getObject() for b in brains] | Return all the Analysis Requests objects linked to the Batch kargs
are passed directly to the catalog. |
343,921 | def shutdown(self, callback=None):
if self._state == self.S_UNWRAPPED:
raise RuntimeError()
self._state = self.S_SHUTDOWN
self._shutdown_cb = callback
ssldata, appdata = self.feed_ssldata(b)
assert appdata == [] or appdata == [b]
return ssldata | Start the SSL shutdown sequence. Return a list of ssldata.
The optional *callback* argument can be used to install a callback that
will be called when the shutdown is complete. The callback will be
called without arguments. |
343,922 | def run(self, host=, port=8080):
from wsgiref import simple_server
self._server = simple_server.make_server(host, port, self)
self._server.serve_forever() | Run the application using a simple WSGI server.
Arguments:
host (str, optional): Host on which to listen.
port (int, optional): Port number on which to listen. |
343,923 | def intersects_segment(self, other):
i = _bisect_left(self, other)
return ((i != 0) and (other[0] < self[i-1][1])) or ((i != len(self)) and (other[1] > self[i][0])) | Returns True if the intersection of self and the segment
other is not the null set, otherwise returns False. The
algorithm is O(log n). Requires the list to be coalesced. |
343,924 | def on_state_changed(self, state):
if state:
self.action.triggered.connect(self.comment)
self.editor.add_action(self.action, sub_menu=)
if in os.environ[].lower():
self.editor.key_pressed.connect(self.on_key_pressed)
else:
self.ed... | Called when the mode is activated/deactivated |
343,925 | def validate(self):
super().validate()
nb_entities = len(self.entities)
if nb_entities != self.rows + self.columns:
raise self.error(
% (
nb_entities, self.rows, self.columns,
self.rows + self.columns)... | Base validation + entities = rows + columns. |
343,926 | def copy_from(self, other_state):
for prop in self.properties().values():
setattr(self, prop.name, getattr(other_state, prop.name)) | Copy data from another shard state entity to self. |
343,927 | def update_selection(self):
self.clear_boxes()
self.draw_figure(self.s)
if self.Data[self.s][] == "T":
self.temperatures = np.array(self.Data[self.s][]) - 273.
else:
self.temperatures = np.array(self.Data[self.s][])
self.T_lis... | update figures and statistics windows with a new selection of specimen |
343,928 | def sliceit(iterable, lower=0, upper=None):
if upper is None:
upper = len(iterable)
try:
result = iterable[lower: upper]
except TypeError:
result = []
if lower < 0:
lower += len(iterable)
if upper < 0:
upper += len(iterable)
... | Apply a slice on input iterable.
:param iterable: object which provides the method __getitem__ or __iter__.
:param int lower: lower bound from where start to get items.
:param int upper: upper bound from where finish to get items.
:return: sliced object of the same type of iterable if not dict, or spec... |
343,929 | def get_alerts_since(self, timestamp):
unix_timestamp = timeformatutils.to_UNIXtime(timestamp)
result = []
for alert in self.alerts:
if alert.last_update >= unix_timestamp:
result.append(alert)
return result | Returns all the `Alert` objects of this `Trigger` that were fired since the specified timestamp.
:param timestamp: time object representing the point in time since when alerts have to be fetched
:type timestamp: int, ``datetime.datetime`` or ISO8601-formatted string
:return: list of `Alert` inst... |
343,930 | def GroupsUsersDelete(self, group_id, user_id):
if self.__SenseApiCall__(.format(group_id = group_id, user_id = user_id), ):
return True
else:
self.__error__ = "api call unsuccessful"
return False | Delete a user from a group in CommonSense.
@return (bool) - Boolean indicating whether GroupsPost was successful. |
343,931 | def get_trace_id():
checkers = (
get_trace_id_from_django,
get_trace_id_from_flask,
get_trace_id_from_webapp2,
)
for checker in checkers:
trace_id = checker()
if trace_id is not None:
return trace_id
return None | Helper to get trace_id from web application request header.
:rtype: str
:returns: TraceID in HTTP request headers. |
343,932 | def convex_comb_dis(model,a,b):
K = len(a)-1
wL,wR,z = {},{},{}
for k in range(K):
wL[k] = model.addVar(lb=0, ub=1, vtype="C")
wR[k] = model.addVar(lb=0, ub=1, vtype="C")
z[k] = model.addVar(vtype="B")
X = model.addVar(lb=a[0], ub=a[K], vtype="C")
Y = model.addVar(lb=-mo... | convex_comb_dis -- add piecewise relation with convex combination formulation
Parameters:
- model: a model where to include the piecewise linear relation
- a[k]: x-coordinate of the k-th point in the piecewise linear relation
- b[k]: y-coordinate of the k-th point in the piecewise linear rel... |
343,933 | def apply_with(self, status=None, raw=None, header=None):
if status != None:
self.__status = status
r = (final(self.__op.responses.get(str(self.__status), None)) or
final(self.__op.responses.get(, None)))
if header != None:
if isinstance(header, (... | update header, status code, raw datum, ...etc
:param int status: status code
:param str raw: body content
:param dict header: header section
:return: return self for chaining
:rtype: Response |
343,934 | def _get_drawn_rect(self, grid, key, rect):
rect = self.get_merged_rect(grid, key, rect)
if rect is None:
if grid.is_merged_cell_drawn(key):
row, col, __ = key = self.get_merging_cell(grid, key)
rect = grid.CellToRect(ro... | Replaces drawn rect if the one provided by wx is incorrect
This handles merged rects including those that are partly off screen. |
343,935 | def resolve_is_aggregate(values):
result = [x
for x in values
if x is not None]
if result:
return all(result)
return None | Resolves the is_aggregate flag for an expression that contains multiple terms. This works like a voter system,
each term votes True or False or abstains with None.
:param values: A list of booleans (or None) for each term in the expression
:return: If all values are True or None, True is returned. If all... |
343,936 | def get_common_session_key_proof(self, session_key, salt, server_public, client_public):
h = self.hash
prove = h(
h(self._prime) ^ h(self._gen),
h(self._user),
salt,
client_public,
server_public,
session_key,
as... | M = H(H(N) XOR H(g) | H(U) | s | A | B | K)
:param bytes session_key:
:param int salt:
:param int server_public:
:param int client_public:
:rtype: bytes |
343,937 | def list_containers(self):
result = []
for c in self.d.containers(all=True):
name = None
names = c.get("Names", None)
if names:
name = names[0]
i = DockerImage(None, identifier=c["ImageID"])
cont = DockerContainer(i, c[... | List all available docker containers.
Container objects returned from this methods will contain a limited
amount of metadata in property `short_metadata`. These are just a subset
of `.inspect()`, but don't require an API call against dockerd.
:return: collection of instances of :class:... |
343,938 | def discount_bootstrap_gae(rewards_buffer, dones_buffer, values_buffer, final_values, discount_factor, gae_lambda,
number_of_steps):
advantage_buffer = torch.zeros_like(rewards_buffer)
sum_accumulator = 0
for i in reversed(range(number_of_steps)):
if i == numbe... | Calculate state values bootstrapping off the following state values - Generalized Advantage Estimation
https://arxiv.org/abs/1506.02438 |
343,939 | def use_contextual_arguments(**kw_only_args_defaults):
def decorator(f):
arg_names, varargs, keywords, defaults = inspect.getargspec(f)
if defaults is None:
defaults = []
defaults = (([Required] * (len(arg_names... | Decorator function which allows the wrapped function to accept
arguments not specified in the call from the context.
Arguments whose default value is set to the Required sentinel must be
supplied either by the context or the caller and a TypeError is raised
if not.
.. warning::... |
343,940 | def __lazy_migration(self, master_id):
collection_name = self.request.headers.get("collection")
if collection_name:
stack = AsyncSchedulableDocumentRevisionStack(collection_name,
self.settings,
... | Creates a revision for a master id that didn't previously have a
revision, this allows you to easily turn on revisioning for a
collection that didn't previously allow for it.
:param master_id:
:returns: list of objects |
343,941 | def _on_channel_open(self, channel):
channel.add_on_close_callback(self._on_channel_close)
channel.add_on_cancel_callback(self._on_cancel)
channel.basic_qos(callback=self._on_qosok, **config.conf["qos"]) | Callback used when a channel is opened.
This registers all the channel callbacks.
Args:
channel (pika.channel.Channel): The channel that successfully opened. |
343,942 | def clip(layer_to_clip, mask_layer):
output_layer_name = clip_steps[]
output_layer_name = output_layer_name % (
layer_to_clip.keywords[])
parameters = {: layer_to_clip,
: mask_layer,
: }
initialize_processing()
feedback = create_processing_fe... | Clip a vector layer with another.
Issue https://github.com/inasafe/inasafe/issues/3186
:param layer_to_clip: The vector layer to clip.
:type layer_to_clip: QgsVectorLayer
:param mask_layer: The vector layer to use for clipping.
:type mask_layer: QgsVectorLayer
:return: The clip vector layer.... |
343,943 | def _parse_eloss(line, lines):
split_line = line.split()
energy = float(split_line[0])
eloss_xx = float(split_line[1])
eloss_zz = float(split_line[2])
return {"energy": energy, "eloss_xx": eloss_xx, "eloss_zz": eloss_zz} | Parse Energy [eV] eloss_xx eloss_zz |
343,944 | def check_mass_balance(self):
reaction_element_dict = defaultdict(int)
for metabolite, coefficient in iteritems(self._metabolites):
if metabolite.charge is not None:
reaction_element_dict["charge"] += \
coefficient * metabolite.charge
... | Compute mass and charge balance for the reaction
returns a dict of {element: amount} for unbalanced elements.
"charge" is treated as an element in this dict
This should be empty for balanced reactions. |
343,945 | def _enum_elements(name, server=None):
elements = []
data = _api_get(name, server)
if any(data[][]):
for element in data[][]:
elements.append(element)
return elements
return None | Enum elements |
343,946 | def _parse_manifest(self):
with open(self.manifest_file, ) as f:
for line in f:
if line.startswith("Version"):
self.mver, self.relnum = self._parse_version(line)
lineitems = line.split()
if len(lineitems) == 2:
... | Read the defined file, parse and set Version line, and return generator of filenames. |
343,947 | def get_threads(self):
thread_list = {}
for thread in threading.enumerate():
thread_ident = thread.ident
thread_list[thread_ident] = {
"ident": thread_ident,
"name": thread.name,
"is_debugger": thread_ident == self.debugger... | Returns a dict of all threads and indicates thread being debugged.
key is thread ident and values thread info.
Information from this list can be used to swap thread being debugged. |
343,948 | def filter_percentile(matrix, top, percentile=50):
assert isinstance(matrix, ExpMatrix)
assert isinstance(top, int)
assert isinstance(percentile, (int, float))
if top >= matrix.p:
logger.warning(
)
top = matrix.p
a = np.argsort(np.percentile(matrix.X, pe... | Filter genes in an expression matrix by percentile expression.
Parameters
----------
matrix: ExpMatrix
The expression matrix.
top: int
The number of genes to retain.
percentile: int or float, optinonal
The percentile to use Defaults to the median (50th percentile).
Ret... |
343,949 | def _get_events(self):
events, changed_container_ids = self.docker_util.get_events()
if not self._disable_net_metrics:
self._invalidate_network_mapping_cache(events)
if changed_container_ids and self._service_discovery:
get_sd_backend(self.agentConfig).update_che... | Get the list of events. |
343,950 | def cols_(df,col_list,func,*args,**kwargs):
return _pd.DataFrame({col_name:func(df,col_name,*args,**kwargs) for col_name in col_list}) | Do a function over a list of columns and return the result
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to coerce
func - function
function to use |
343,951 | def debug_text_world(self, text: str, pos: Union[Unit, Point2, Point3], color=None, size: int = 8):
if isinstance(pos, Point2) and not isinstance(pos, Point3):
pos = Point3((pos.x, pos.y, 0))
self._debug_texts.append(self.to_debug_message(text, color, pos, size)) | Draws a text at Point3 position. Don't forget to add 'await self._client.send_debug'.
To grab a unit's 3d position, use unit.position3d
Usually the Z value of a Point3 is between 8 and 14 (except for flying units) |
343,952 | def _bind_posix_socket(socket_name=None):
assert socket_name is None or isinstance(socket_name, six.text_type)
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if socket_name:
s.bind(socket_name)
return socket_name, s
else:
i = 0
while True:
try:
... | Find a socket to listen on and return it.
Returns (socket_name, sock_obj) |
343,953 | def get_candidate_election(self, candidate):
return CandidateElection.objects.get(
candidate=candidate, election=self
) | Get CandidateElection for a Candidate in this election. |
343,954 | async def i2c_read_data(self, address):
if address in self.i2c_map:
map_entry = self.i2c_map.get(address)
data = map_entry.get()
return data
else:
return None | This method retrieves cached i2c data to support a polling mode.
:param address: I2C device address
:returns: Last cached value read |
343,955 | def on_accept(self, auto=False):
if self.model.is_current_source_named():
provisional_name = self.model.get_current_source_name()
else:
provisional_name = self._generate_provisional_name()
band = self.model.get_current_band()
logger.debug("Got band {} a... | Initiates acceptance procedure, gathering required data.
@param auto: Set on_accept to automatic measure of source? |
343,956 | def inspect_secret(self, id):
url = self._url(, id)
return self._result(self._get(url), True) | Retrieve secret metadata
Args:
id (string): Full ID of the secret to remove
Returns (dict): A dictionary of metadata
Raises:
:py:class:`docker.errors.NotFound`
if no secret with that ID exists |
343,957 | def build_bot(config_file=None):
from . import bot
config = ConfigParser(interpolation=None)
if config_file is None:
config.read_string(default_config)
elif isinstance(config_file, ConfigParser):
config = config_file
else:
config.read(config_file)
db_... | Parse a config and return a SeshetBot instance. After, the bot can be run
simply by calling .connect() and then .start()
Optional arguments:
config_file - valid file path or ConfigParser instance
If config_file is None, will read default config defined in this module. |
343,958 | def run(self):
self.logger.debug()
self.game_interface.load_interface()
self.prepare_for_run()
rate_limit = rate_limiter.RateLimiter(GAME_TICK_PACKET_POLLS_PER_SECOND)
last_tick_game_time = None
last_call_real_time = datetime.now()
... | Loads interface for RLBot, prepares environment and agent, and calls the update for the agent. |
343,959 | def authenticate(self, account=None, app_account=None, flush=True):
with self._get_account(account) as account:
if app_account is None:
app_account = account
if not self.proto_authenticated:
self.protocol_authenticate(account)
self.ap... | Like login(), but skips the authorization procedure.
.. HINT::
If you are unsure whether to use :class:`authenticate()` or
:class:`login()`, stick with :class:`login`.
:type account: Account
:param account: The account for protocol level authentication.
:type ap... |
343,960 | def check(self, value_spec, arg_name, decorated_function):
def raise_exception(text_spec):
exc_text = % (
arg_name, Verifier.function_name(decorated_function)
)
exc_text += % text_spec
raise ValueError(exc_text)
if isinstance(value_spec, (tuple, list, set)):
for single_value in value_spec... | Return callable that checks function parameter for value validity. Checks parameter if its value
passes specified restrictions.
:param value_spec: function or list/tuple/set of functions. Each function must accept one parameter and \
must return True or False if it passed restrictions or not.
:param arg_name: ... |
343,961 | def not_found(cls, errors=None):
if cls.expose_status:
cls.response.content_type =
cls.response._status_line =
return cls(404, None, errors).to_json | Shortcut API for HTTP 404 `Not found` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance. |
343,962 | def BuildDefaultGlobals():
global GlobalDict
if GlobalDict is None:
GlobalDict = {}
import SCons.Script
d = SCons.Script.__dict__
def not_a_module(m, d=d, mtype=type(SCons.Script)):
return not isinstance(d[m], mtype)
for m in filter(not_a_module, dir(S... | Create a dictionary containing all the default globals for
SConstruct and SConscript files. |
343,963 | def form(context, form, **kwargs):
if not isinstance(form, (forms.BaseForm, TapeformFieldset)):
raise template.TemplateSyntaxError(
.format(
form.__class__.__name__))
return render_to_string(
form.get_layout_template(kwargs.get(, None)),
form.get_layout... | The `form` template tag will render a tape-form enabled form using the template
provided by `get_layout_template` method of the form using the context generated
by `get_layout_context` method of the form.
Usage::
{% load tapeforms %}
{% form my_form %}
You can override the used layout... |
343,964 | def promote(name):
*
res = __salt__[](
__utils__[](
command=,
target=name,
),
python_shell=False,
)
return __utils__[](res, ) | Promotes a clone file system to no longer be dependent on its "origin"
snapshot.
.. note::
This makes it possible to destroy the file system that the
clone was created from. The clone parent-child dependency relationship
is reversed, so that the origin file system becomes a clone of th... |
343,965 | def options_utils(self):
group = self.parser.add_argument_group("Utils")
group.add_argument(
"--path", action="append", dest="paths",
help="Path to the metadata tree (default: current directory)")
group.add_argument(
"--verbose", action="store_true",
... | Utilities |
343,966 | def post(self, repo):
datapackage = repo.package
url = self.url
token = self.token
headers = {
: .format(token),
:
}
try:
r = requests.post(url,
data = json.dumps(datapackage),
... | Post to the metadata server
Parameters
----------
repo |
343,967 | def add_line(preso, x1, y1, x2, y2, width="3pt", color="red"):
marker_end_ratio = .459 / 3
marker_start_ratio = .359 / 3
stroke_ratio = .106 / 3
w = float(width[0:width.index("pt")])
sw = w * stroke_ratio
mew = w * marker_end_ratio
msw = w * marker_start_ratio
attribs = {
... | Arrow pointing up to right:
context.xml:
office:automatic-styles/
<style:style style:name="gr1" style:family="graphic" style:parent-style-name="objectwithoutfill">
<style:graphic-properties
draw:marker-end="Arrow"
draw:marker-end-width="0.3cm"
draw:fill="none"
draw:textarea-vertica... |
343,968 | def finalize(self, **kwargs):
self.set_title(.format(self.name))
loc = kwargs.pop("loc", "best")
edgecolor = kwargs.pop("edgecolor", "k")
self.ax.legend(frameon=True, loc=loc, edgecolor=edgecolor)
self.ax.xaxis.set_major_locator(ticker.Multi... | Add the title, legend, and other visual final touches to the plot. |
343,969 | def getArgumentDescriptions(f):
argspec = inspect.getargspec(f)
docstring = f.__doc__
descriptions = {}
if docstring:
lines = docstring.split()
i = 0
while i < len(lines):
stripped = lines[i].lstrip()
if not stripped:
i += 1
continue
... | Get the arguments, default values, and argument descriptions for a function.
Parses the argument descriptions out of the function docstring, using a
format something lke this:
::
[junk]
argument_name: description...
description...
description...
[junk]
[more arguments]
It wil... |
343,970 | def get_parent(self, path):
self.__validate_storage_path(path, projects_allowed=False)
path_steps = [step for step in path.split() if step]
del path_steps[-1]
parent_path = .format(.join(path_steps))
return self.api_client.get_entity_by_query(path=parent_path) | Get the parent entity of the entity pointed by the given path.
Args:
path (str): The path of the entity whose parent is needed
Returns:
A JSON object of the parent entity if found.
Raises:
StorageArgumentException: Invalid arguments
StorageForbi... |
343,971 | def task(self, task_uuid):
request = clearly_pb2.FindTaskRequest(task_uuid=task_uuid)
task = self._stub.find_task(request)
if task.uuid:
ClearlyClient._display_task(task, True, True, True)
else:
print(EMPTY) | Finds one specific task.
Args:
task_uuid (str): the task id |
343,972 | def setEditable(self, state):
self._editable = state
if state:
self.setEditTriggers(self.AllEditTriggers)
else:
self.setEditTriggers(self.NoEditTriggers) | Sets whether or not the user can edit the items in the list by
typing.
:param state | <bool> |
343,973 | def config_to_dict_of_dict(desired_type: Type[T], config: ConfigParser, logger: Logger,
conversion_finder: ConversionFinder, **kwargs) -> DictOfDict:
base_typ, discarded = _extract_collection_base_type(desired_type, exception_if_none=False)
base_typ = base_typ or ... | Helper method to read a configuration file according to the 'configparser' format, and return it as a dictionary
of dictionaries [section > [property > value]].
:param file_object:
:return: |
343,974 | def _set_redistribute_static(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=redistribute_static.redistribute_static, is_container=, presence=True, yang_name="redistribute-static", rest_name="static", parent=self, path_helper=self._path_helper, extmet... | Setter method for redistribute_static, mapped from YANG variable /rbridge_id/ipv6/router/ospf/redistribute/redistribute_static (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_redistribute_static is considered as a private
method. Backends looking to populate this... |
343,975 | def load_hha(self, idx):
im = Image.open(.format(self.nyud_dir, idx))
hha = np.array(im, dtype=np.float32)
hha -= self.mean_hha
hha = hha.transpose((2,0,1))
return hha | Load HHA features from Gupta et al. ECCV14.
See https://github.com/s-gupta/rcnn-depth/blob/master/rcnn/saveHHA.m |
343,976 | def create_result(self, env_name, other_val, meta, val, dividers):
args = [env_name]
if other_val is NotSpecified:
other_val = None
if not dividers:
args.extend([None, None])
elif dividers[0] == :
args.extend([other_val, None])
elif di... | Set default_val and set_val depending on the seperator |
343,977 | def stop_collecting_data(self, queues=None, edge=None, edge_type=None):
queues = _get_queues(self.g, queues, edge, edge_type)
for k in queues:
self.edge2queue[k].collect_data = False | Tells the queues to stop collecting data on agents.
If none of the parameters are given then every
:class:`.QueueServer` will stop collecting data.
Parameters
----------
queues : int, *array_like* (optional)
The edge index (or an iterable of edge indices) identifyin... |
343,978 | def breed(self, egg_donor, sperm_donor):
offspring = []
try:
num_children = npchoice([1,2], 1, p=[0.8, 0.2])[0]
for _ in range(num_children):
child = God(egg_donor, sperm_donor)
offspring.append(child)
send_birth_announcem... | Get it on. |
343,979 | def _get_chain_by_pid(pid):
try:
return d1_gmn.app.models.ChainMember.objects.get(pid__did=pid).chain
except d1_gmn.app.models.ChainMember.DoesNotExist:
pass | Find chain by pid.
Return None if not found. |
343,980 | def mapper_from_gaussian_tuples(self, tuples, a=None, r=None):
prior_tuples = self.prior_tuples_ordered_by_id
prior_class_dict = self.prior_class_dict
arguments = {}
for i, prior_tuple in enumerate(prior_tuples):
prior = prior_tuple.prior
cls = prior_cl... | Creates a new model mapper from a list of floats describing the mean values of gaussian priors. The widths \
of the new priors are taken from the width_config. The new gaussian priors must be provided in the same \
order as the priors associated with model.
If a is not None then all priors are ... |
343,981 | def page_through(page_size, function, *args, **kwargs):
kwargs["limit"] = page_size
def get_page(token):
page_kwargs = kwargs.copy()
if token:
page_kwargs["token"] = token
return function(*args, **page_kwargs)
def page_generator():
... | Return an iterator over all pages of a REST operation.
:param page_size: Number of elements to retrieve per call.
:param function: FlashArray function that accepts limit as an argument.
:param \*args: Positional arguments to be passed to function.
:param \*\*kwargs: Keyword arguments to... |
343,982 | def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.dumps(context, cls=JSON_ENCODER),
content_type=,
**response_kwargs) | Returns a response, using the `response_class` for this
view, with a template rendered with the given context.
If any keyword arguments are provided, they will be
passed to the constructor of the response class. |
343,983 | def replaceIDs(data, receivedUUID, receivedGen, parentUUID, parentGen):
if len(data) < 20:
return data
logger.debug(
"Setting received %s/%d and parent %s/%d",
receivedUUID, receivedGen or 0, parentUUID, parentGen or 0.
)
data = bytearray(data)
buf = ioctl.Buffer... | Parse and replace UUID and transid info in data stream. |
343,984 | def as_enum(enum):
if isinstance(enum, string_types):
try:
enum = getattr(gl, + enum.upper())
except AttributeError:
try:
enum = _internalformats[ + enum.upper()]
except KeyError:
raise ValueError( % enum)
return enum | Turn a possibly string enum into an integer enum. |
343,985 | def _parse_version(version):
parsed_version = parse_version(version)
return tuple(
int(dot_version)
for dot_version in parsed_version.base_version.split()
) + (parsed_version.is_prerelease,) | Parse a version string.
Args:
version (str): A string representing a version e.g. '1.9rc2'
Returns:
tuple: major, minor, patch parts cast as integer and whether or not
it was a pre-release version. |
343,986 | def update(self, **kwargs):
return self.__class__(self.resource.update(kwargs),
self.client,
wallet=self.wallet) | Update the Account resource with specified content.
Args:
name (str): Human-readable name for the account
Returns: the updated Account object. |
343,987 | def run(align_bams, items, ref_file, assoc_files, region, out_file):
call_file = "%s-raw.vcf.gz" % utils.splitext_plus(out_file)[0]
strelka_work_dir = "%s-work" % utils.splitext_plus(out_file)[0]
paired = vcfutils.get_paired_bams(align_bams, items)
if paired:
assert paired.normal_bam, "Stre... | Run strelka2 variant calling, either paired tumor/normal or germline calling.
region can be a single region or list of multiple regions for multicore calling. |
343,988 | def versional(a, b):
stra = nstr(a).lower()
strb = nstr(b).lower()
aresults = EXPR_VERSIONAL.findall(stra)
bresults = EXPR_VERSIONAL.findall(strb)
bcount = len(bresults)
for i in range(len(aresults)):
else:
anum = int(anum)
bnum = int(bnu... | Sorts the inputted items by their natural order, trying to extract a \
number from them to sort by.
:param a <str>
b <str>
:return <int> 1 || 0 || -1
:usage |>>> from projex import sorting
|>>> a = [ 'test-1.1.2', 'test-1.02', 'tes... |
343,989 | def post(self, message):
return self.connection.post(, data=dict(message=message)) | Simply test Put a string
:param message: str of the message
:return: str of the message |
343,990 | def go_left(self):
start, end = self._interval
delay = (end - start) * .2
self.shift(-delay) | Go to left. |
343,991 | def _updateFrame(self):
for col, mov in self._movies.items():
self.setIcon(col, QtGui.QIcon(mov.currentPixmap())) | Updates the frame for the given sender. |
343,992 | def request_encode_url(self, method, url, fields=None, headers=None,
**urlopen_kw):
if headers is None:
headers = self.headers
extra_kw = {: headers}
extra_kw.update(urlopen_kw)
if fields:
url += + urlencode(fields)
... | Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc. |
343,993 | def validate(self):
from .files import AudioFile
try:
assert self.kind == content_kinds.AUDIO, "Assumption Failed: Node should be audio"
assert self.questions == [], "Assumption Failed: Audio should not have questions"
assert len(self.files) > 0, "Assumption ... | validate: Makes sure audio is valid
Args: None
Returns: boolean indicating if audio is valid |
343,994 | def _set_login_policy(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=login_policy.login_policy, is_container=, presence=False, yang_name="login-policy", rest_name="login-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods... | Setter method for login_policy, mapped from YANG variable /rbridge_id/fabric/login_policy (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_login_policy is considered as a private
method. Backends looking to populate this variable should
do so via calling thisO... |
343,995 | def node_setup(name, master, ticket):
ret = {: name,
: {},
: True,
: }
cert = "{0}{1}.crt.orig".format(get_certs_path(), name)
key = "{0}{1}.key.orig".format(get_certs_path(), name)
if os.path.isfile(cert) and os.path.isfile(cert):
ret[] =
ret... | Setup the icinga2 node.
name
The domain name for which this certificate will be saved
master
Icinga2 master node for which this certificate will be saved
ticket
Authentication ticket generated on icinga2 master |
343,996 | def push_file(self, local_source, remote_dir):
remote_dest = remote_dir + + os.path.basename(local_source)
try:
self.makedirs(remote_dir, exist_ok=True)
except IOError as e:
logger.exception("Pushing {0} to {1} failed".format(local_source, remote_dir))
... | Transport a local file to a directory on a remote machine
Args:
- local_source (string): Path
- remote_dir (string): Remote path
Returns:
- str: Path to copied file on remote machine
Raises:
- BadScriptPath : if script path on the remote side is... |
343,997 | def configure_backup_directory(self):
self._display_question("Please choose a directory in which to store the backup files. By default, the tool will them in the current "
"directory")
backup_directory = None
while backup_directory is None:
bac... | Configure backup directory |
343,998 | def prepare_additional_parameters(additional_properties, language_hints, web_detection_params):
if language_hints is None and web_detection_params is None:
return additional_properties
if additional_properties is None:
return {}
merged_additional_parameters = deepcopy(additional_prope... | Creates additional_properties parameter based on language_hints, web_detection_params and
additional_properties parameters specified by the user |
343,999 | def moduli_to_velocities(rho, K_s, G):
return np.sqrt(K_s / rho), np.sqrt(G / rho) | convert moduli to velocities
mainly to support Burnman operations
:param rho: density in kg/m^3
:param v_phi: adiabatic bulk modulus in Pa
:param v_s: shear modulus in Pa
:return: bulk sound speed and shear velocity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.