Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
361,300 | def add_pi_equation(self,par_names,pilbl=None,rhs=0.0,weight=1.0,
obs_group="pi_obgnme",coef_dict={}):
if pilbl is None:
pilbl = "pilbl_{0}".format(self.__pi_count)
self.__pi_count += 1
missing,fixed = [],[]
for par_name in par_names:
... | a helper to construct a new prior information equation.
Parameters
----------
par_names : list
parameter names in the equation
pilbl : str
name to assign the prior information equation. If None,
a generic equation name is formed. Default is None
... |
361,301 | def cache_id(self) -> str:
if self._cache_id:
return self._cache_id
with open(join(expanduser(), , , self.name, .format(self.name))) as fh_genesis:
genesis = [json.loads(line) for line in fh_genesis.readlines() if line]
hps = []
for gen_txn in genesis:... | Return identifier for archivable caches, computing it first and retaining it if need be.
Raise AbsentPool if ledger configuration is not yet available.
:param name: pool name
:return: archivable cache identifier |
361,302 | def xml(self):
if six.PY3:
data = ElementTree.tostring(self.et, encoding="unicode")
else:
data = ElementTree.tostring(self.et)
return data | :rtype: str |
361,303 | def set_pixel(self, x, y, value):
if x < 0 or x > 7 or y < 0 or y > 15:
return
self.set_led((7 - x) * 16 + y, value) | Set pixel at position x, y to the given value. X and Y should be values
of 0 to 7 and 0 to 15, resp. Value should be 0 for off and non-zero for on. |
361,304 | def toString(self):
output = ""
for layer in reverse(self.layers):
output += layer.toString()
return output | Returns the network layers as a string. |
361,305 | def getreference(self, validate=True):
if self.offset is None: return None
if self.ref:
ref = self.doc[self.ref]
else:
ref = self.finddefaultreference()
if not ref:
raise UnresolvableTextContent("Default reference for phonetic content not f... | Return and validate the Phonetic Content's reference. Raises UnresolvableTextContent when invalid |
361,306 | def stSpectralEntropy(X, n_short_blocks=10):
L = len(X)
Eol = numpy.sum(X ** 2)
sub_win_len = int(numpy.floor(L / n_short_blocks))
if L != sub_win_len * n_short_blocks:
X = X[0:sub_win_len * n_short_blocks]
sub_wins = X.reshape(sub_win_len, n_sh... | Computes the spectral entropy |
361,307 | def translate_item(self, item_dict):
if not item_dict.get():
return None
if item_dict.get(, None) == :
return None
ret_dict = {}
ret_dict[]= item_dict.get() or re.sub(item_dict[],,)
ret_dict[]= item_dict[]
ret_dict[]= ite... | cleanup item keys to match API json format |
361,308 | def format_value(column_dict, value, key=None):
formatter = column_dict.get()
prop = column_dict[]
res = value
if value in (, None,):
res =
elif formatter is not None:
res = formatter(value)
else:
if hasattr(prop, "columns"):
sqla_column = prop.colum... | Format a value coming from the database (for example converts datetimes to
strings)
:param column_dict: The column datas collected during inspection
:param value: A value coming from the database
:param key: The exportation key |
361,309 | def register_update(self, model_alias, code):
model_alias = self.get_model_alias(model_alias)
def wrapper(update_layout):
for item in self.tabs[model_alias]:
if item.code == code:
item.layout_updates.append(update_layout)
return updat... | Register tab update function, function is being called with (layout, object)
:param model_alias:
:param code:
:return: |
361,310 | def fcoe_fcoe_fabric_map_fcoe_fabric_map_fcmap(self, **kwargs):
config = ET.Element("config")
fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe")
fcoe_fabric_map = ET.SubElement(fcoe, "fcoe-fabric-map")
fcoe_fabric_map_name_key = ET.SubElement(fcoe_fa... | Auto Generated Code |
361,311 | def get_batch(self):
if self.all_finished():
return None
batch_str = self.queue_result.get()
batch = pickle.loads(batch_str)
if batch is not None:
return batch
else:
self.nb_workers_finished += 1
if self.nb_workers_finishe... | Returns a batch from the queue of augmented batches.
If workers are still running and there are no batches in the queue,
it will automatically wait for the next batch.
Returns
-------
out : None or imgaug.Batch
One batch or None if all workers have finished. |
361,312 | def get_authorize_url(self, state=None):
payload = {: self.client_id,
: ,
: self.redirect_uri,
: self.scope}
urlparams = urllib.parse.urlencode(payload)
return "%s?%s" % (self.OAUTH_AUTHORIZE_URL, urlparams) | Gets the URL to use to authorize this app |
361,313 | def bpoints2bezier(bpoints):
order = len(bpoints) - 1
if order == 3:
return CubicBezier(*bpoints)
elif order == 2:
return QuadraticBezier(*bpoints)
elif order == 1:
return Line(*bpoints)
else:
assert len(bpoints) in {2, 3, 4} | Converts a list of length 2, 3, or 4 to a CubicBezier, QuadraticBezier,
or Line object, respectively.
See also: poly2bez. |
361,314 | def nPr(n, r):
f = math.factorial
return int(f(n) / f(n-r)) | Calculates nPr.
Args:
n (int): total number of items.
r (int): items to permute
Returns:
nPr. |
361,315 | def getOverlayRenderingPid(self, ulOverlayHandle):
fn = self.function_table.getOverlayRenderingPid
result = fn(ulOverlayHandle)
return result | Gets the pid that is allowed to render to this overlay |
361,316 | def from_dict(cls, d):
execution_request = super(ExecutionRequest, cls).from_dict(d)
if isinstance(execution_request.simulation_group, dict):
execution_request.simulation_group = SimulationGroup.from_dict(execution_request.simulation_group)
return execution_request | Create an instance from a dictionary. |
361,317 | def gauss_seidel(A, x, b, iterations=1, sweep=):
A, x, b = make_system(A, x, b, formats=[, ])
if sparse.isspmatrix_csr(A):
blocksize = 1
else:
R, C = A.blocksize
if R != C:
raise ValueError()
blocksize = R
if sweep == :
row_start, row_stop, row_... | Perform Gauss-Seidel iteration on the linear system Ax=b.
Parameters
----------
A : csr_matrix, bsr_matrix
Sparse NxN matrix
x : ndarray
Approximate solution (length N)
b : ndarray
Right-hand side (length N)
iterations : int
Number of iterations to perform
sw... |
361,318 | def polygon(self, *coords, color="black", outline=False, outline_color="black"):
return self.tk.create_polygon(
*coords,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_... | Draws a polygon from an list of co-ordinates
:param int *coords:
Pairs of x and y positions which make up the polygon.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 set... |
361,319 | def parse_image_json(text):
image_details = json.loads(text)
if image_details.get() is not None:
try:
image_details = image_details.get()[0]
except IndexError:
image_details = None
return image_details | parses response output of AWS describe commands and returns the first (and only) item in array
:param text: describe output
:return: image json |
361,320 | def _bracket_dim_suggest(self, variable):
if variable is not None:
dims = variable.doc_children("dimension", ["member", "parameter", "local"])
descript = str(variable)
if len(dims) > 0:
descript += " | " + " ".join([DocElemen... | Returns a dictionary of documentation for helping complete the
dimensions of a variable. |
361,321 | def dropIndex(self, table, fields, where = ) :
"DROPs an index created by RabaDb see createIndexes()"
indexTable = self.makeIndexTableName(table, fields, where)
self.dropIndexByName(indexTable) | DROPs an index created by RabaDb see createIndexes() |
361,322 | def _update_enabled(self, name, enabled_value):
if isinstance(self.opts[][name], dict):
self.opts[][name][] = enabled_value
else:
enabled_index = self._get_index(self.opts[][name], )
if enabled_index >= 0:
self.opts[][name][enabl... | Update whether an individual beacon is enabled |
361,323 | def neurite_root_section_ids(self):
sec = self.sections
return [i for i, ss in enumerate(sec)
if ss.pid > -1 and (sec[ss.pid].ntype == POINT_TYPE.SOMA and
ss.ntype != POINT_TYPE.SOMA)] | Get the section IDs of the intitial neurite sections |
361,324 | def low(data, **kwargs):
*{"state": "pkg", "fun": "installed", "name": "vi"}
st_kwargs = __salt__.kwargs
__opts__[] = __grains__
chunks = [data]
st_ = salt.client.ssh.state.SSHHighState(
__opts__,
__pillar__,
__salt__,
__context__[])
for chunk in c... | Execute a single low data call
This function is mostly intended for testing the state system
CLI Example:
.. code-block:: bash
salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}' |
361,325 | def _citation_to_string(citation):
output =
sep =
if in citation:
authors = []
for author in citation[]:
if not in author:
continue
author_name = author[]
if in author:
author_name += + author[]
... | Convert citation object to a string, using standard citation formatting.
args:
citation: a dictionary potentially containing all fields from
pypif.obj.Reference, and possibly a few others
TODO: This is tedious and fragile. Find a better way to get 'er done.
TODO: This funct... |
361,326 | def create_markdown_cell(block):
kwargs = {: block[],
: block[]}
markdown_cell = nbbase.new_markdown_cell(**kwargs)
return markdown_cell | Create a markdown cell from a block. |
361,327 | def API_POST(self, courseid, taskid):
try:
course = self.course_factory.get_course(courseid)
except:
raise APINotFound("Course not found")
username = self.user_manager.session_username()
if not self.user_manager.course_is_open_to_user(course, usernam... | Creates a new submissions. Takes as (POST) input the key of the subproblems, with the value assigned each time.
Returns
- an error 400 Bad Request if all the input is not (correctly) given,
- an error 403 Forbidden if you are not allowed to create a new submission for this task
... |
361,328 | def deltas(self):
refkey = self.refkey
refoffset = self[refkey]
return dict(((refkey, key), self[key] - refoffset) for key in self) | Dictionary of relative offsets. The keys in the result are
pairs of keys from the offset vector, (a, b), and the
values are the relative offsets, (offset[b] - offset[a]).
Raises ValueError if the offsetvector is empty (WARNING:
this behaviour might change in the future).
Example:
>>> x = offsetvector({"H... |
361,329 | def parse_division(l, c, line, root_node, last_section_node):
name = line
name = name.replace(".", "")
tokens = [t for t in name.split() if t]
node = Name(Name.Type.Division, l, c, % (tokens[0], tokens[1]))
root_node.add_child(node)
last_div_node = node
if last_section_node:
... | Extracts a division node from a line
:param l: The line number (starting from 0)
:param c: The column number
:param line: The line string (without indentation)
:param root_node: The document root node.
:return: tuple(last_div_node, last_section_node) |
361,330 | def getVoxelsScalar(self, vmin=None, vmax=None):
nx, ny, nz = self.image.GetDimensions()
voxdata = np.zeros([nx, ny, nz])
lsx = range(nx)
lsy = range(ny)
lsz = range(nz)
renorm = vmin is not None and vmax is not None
for i in lsx:
... | Return voxel content as a ``numpy.array``.
:param float vmin: rescale scalar content to match `vmin` and `vmax` range.
:param float vmax: rescale scalar content to match `vmin` and `vmax` range. |
361,331 | def parse_url(url):
parsed = url
if not url.startswith("http://") and not url.startswith(
"https://"):
parsed = "http://" + parsed
elif url.startswith("https://"):
parsed = parsed[8:]
parsed = "http://" + parsed
index_hash ... | Parses correctly url
:param url: url to parse |
361,332 | def get_config(cls, key, default=None):
return cls._app.config.get(key, default) | Shortcut to access the application's config in your class
:param key: The key to access
:param default: The default value when None
:returns mixed: |
361,333 | def run(self, options):
self.set_signal()
self.check_exclusive_mode()
slot = self.Handle(self)
i = 0
while i < options.threads:
t = threading.Thread(target=self.worker, args=[slot])
if options.once is True or options.no_da... | In general, you don't need to overwrite this method.
:param options:
:return: |
361,334 | def plural(text):
aberrant = {
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
: ,
... | >>> plural('activity')
'activities' |
361,335 | def write_job(self,fh):
if isinstance(self.job(),CondorDAGManJob):
fh.write( .join(
[, self.__name, self.__job.get_sub_file()]) )
if self.job().get_dag_directory():
fh.write( + self.job().get_dag_directory() )
else:
fh.write( + self.__name + + self.__job.g... | Write the DAG entry for this node's job to the DAG file descriptor.
@param fh: descriptor of open DAG file. |
361,336 | def _dict_refs(obj, named):
if named:
for k, v in _items(obj):
s = str(k)
yield _NamedRef( + s, k)
yield _NamedRef( + s + + _repr(v), v)
else:
for k, v in _items(obj):
yield k
yield v | Return key and value objects of a dict/proxy. |
361,337 | def detect_anoms(data, k=0.49, alpha=0.05, num_obs_per_period=None,
use_decomp=True, one_tail=True,
upper_tail=True, verbose=False):
if num_obs_per_period is None:
raise ValueError("must supply period length for time series decomposition")
if list(data.columns.val... | # Detects anomalies in a time series using S-H-ESD.
#
# Args:
# data: Time series to perform anomaly detection on.
# k: Maximum number of anomalies that S-H-ESD will detect as a percentage of the data.
# alpha: The level of statistical significance with which to accept or reject anomalies.
# ... |
361,338 | def setComboValue(combo, value):
dataType = unwrapVariant(combo.property())
if dataType == :
return combo.setCurrentIndex(combo.findText(value))
elif dataType == :
for i in range(combo.count()):
if unwrapVariant(combo.itemData(i)) == value:
retu... | Checks to see if there is a dataType custom property set to determine
whether to return an integer or a string.
:param combo | <QComboBox>
:return <int> || <str> |
361,339 | def combining_setup(self):
(slot_type, (corner_slot, edge_slot), (corner, edge)) = self.get_slot()
cycle = ["FR", "RB", "BL", "LF"]
if slot_type == "SLOTFREE":
return ("FR", Formula(Step("y") * cycle.index(self.pair) or []))
elif slot_type == "CSLOTFREE":
... | Setup for some special F2L cases. |
361,340 | def _add_arg_datasets(datasets, args):
for dataset in args:
if not isinstance(dataset, (tuple, GentyArgs)):
dataset = (dataset,)
if isinstance(dataset, GentyArgs):
dataset_strings = dataset
else:
dataset_strings = [format_arg(d... | Add data sets of the given args.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies |
361,341 | def draw_image(self, video_name, image_name, out, start, end, x, y,
verbose=False):
cfilter = (r"[0] [1] overlay=x={x}: y={y}:"
"enable=)")\
.format(x=x, y=y, start=start, end=end)
call([, , video_name, , image_name, , ,
, , , , c... | Draws an image over the video
@param video_name : name of video input file
@param image_name: name of image input file
@param out : name of video output file
@param start : when to start overlay
@param end : when to end overlay
@param x : x pos of image
@param y :... |
361,342 | def train(input_dir, batch_size, max_steps, output_dir, checkpoint, cloud_train_config):
import google.datalab.ml as ml
if checkpoint is None:
checkpoint = _util._DEFAULT_CHECKPOINT_GSURL
staging_package_url = _util.repackage_to_staging(output_dir)
job_args = {
: input_dir,
: max... | Train model in the cloud with CloudML trainer service. |
361,343 | def filter_pages(pages, pagenum, pagename):
if pagenum:
try:
pages = [list(pages)[pagenum - 1]]
except IndexError:
raise IndexError( % pagenum)
if pagename:
pages = [page for page in pages if page.name == pagename]
if pages == []:
raise I... | Choices pages by pagenum and pagename |
361,344 | def _load_stopwords(file_path):
global _stopwords
if sys.version_info[0] < 3:
words = open(file_path, )
else:
words = open(file_path, , encoding=)
stopwords = words.readlines()
for w in stopwords:
_stopwords.add(any2unicode(w).strip()) | load stop words |
361,345 | def task_search(self, task_str, **kwargs):
self.prune()
result = collections.defaultdict(dict)
for task in self._state.get_active_tasks():
if task.id.find(task_str) != -1:
serialized = self._serialize_task(task.id, include_deps=False)
result[t... | Query for a subset of tasks by task_id.
:param task_str:
:return: |
361,346 | def load_model():
logging.info("Load language model...")
ngram_arpa_t = pkg_resources.resource_filename(,
)
with tarfile.open(ngram_arpa_t, ) as tar:
tarfolder = tempfile.mkdtemp()
tar.extractall(path=tarfolder)
ngram_arpa_f = os.pa... | Load a n-gram language model for mathematics in ARPA format which gets
shipped with hwrt.
Returns
-------
A NgramLanguageModel object |
361,347 | def tab_navigate(self, delta=1):
if delta > 0 and self.currentIndex() == self.count()-1:
index = delta-1
elif delta < 0 and self.currentIndex() == 0:
index = self.count()+delta
else:
index = self.currentIndex()+delta
self.setCurrentInd... | Ctrl+Tab |
361,348 | def minify(compiled):
compiled = compiled.strip()
if compiled:
out = []
for line in compiled.splitlines():
line = line.split("
if line:
ind = 0
while line.startswith(" "):
line = line[1:]
ind += ... | Perform basic minifications.
Fails on non-tabideal indentation or a string with a #. |
361,349 | def get_subassistants(self):
if not hasattr(self, ):
self._subassistants = []
for a in self.get_subassistant_classes():
self._subassistants.append(a())
return self._subassistants | Return list of instantiated subassistants.
Usually, this needs not be overriden in subclasses, you should just override
get_subassistant_classes
Returns:
list of instantiated subassistants |
361,350 | def get_logger(name=None):
logger = logging.getLogger(name)
if len(logger.handlers) == 0:
logger = add_stream_handler(logger)
return logger | Get a logging handle.
As with ``setup_logging``, a stream handler is added to the
log handle.
Arguments:
name (str): Name of the log handle. Default is ``None``. |
361,351 | def add_socket(self, socket):
if socket not in self._sockets:
self._sockets.add(socket)
socket.on_closed.connect(self.remove_socket) | Add a socket to the multiplexer.
:param socket: The socket. If it was added already, it won't be added a
second time. |
361,352 | def assert_matching_time_coord(arr1, arr2):
message = (
)
if not (arr1[TIME_STR].identical(arr2[TIME_STR])):
raise ValueError(message.format(arr1[TIME_STR], arr2[TIME_STR])) | Check to see if two DataArrays have the same time coordinate.
Parameters
----------
arr1 : DataArray or Dataset
First DataArray or Dataset
arr2 : DataArray or Dataset
Second DataArray or Dataset
Raises
------
ValueError
If the time coordinates are not identical betw... |
361,353 | def set_data_location(self, current_extent, tag_location):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
self.new_extent_loc = current_extent
if self.ptr is not None:
self.ptr.update_extent_location(current_extent) | A method to set the new extent location that the data for this Directory
Record should live at.
Parameters:
current_extent - The new extent.
Returns:
Nothing. |
361,354 | def is_builtin_variable(id_node):
if NodeType(id_node[]) is not NodeType.IDENTIFIER:
return False
id_value = id_node[]
if id_value.startswith():
return True
if is_builtin_function(id_node):
return True
if id_value in [, ]:
re... | Whether the specified node is a builtin identifier. |
361,355 | def from_dict(cls, dct, project=None, delim=):
r
if project is None:
project = ws.new_project()
fd = FlatDict(dct, delimiter=delim)
if delim == :
delim =
for key in list(fd.keys()):
new_key = key.replace(, delim)
... | r"""
This method converts a correctly formatted dictionary into OpenPNM
objects, and returns a handle to the *project* containing them.
Parameters
----------
dct : dictionary
The Python dictionary containing the data. The nesting and
labeling of the dict... |
361,356 | def get_event_times(self):
times = []
times.extend(self.Breaker.get_times())
for model in self.__dict__[].all_models:
times.extend(self.__dict__[model].get_times())
if times:
times = sorted(list(set(times)))
return times | Return event times of Fault, Breaker and other timed events
Returns
-------
list
A sorted list of event times |
361,357 | def custom_showwarning(
message, category, filename="", lineno=-1, file=None, line=None
):
if file is None:
file = sys.stderr
if file is None:
return
text = "%s: %s\n" % (category.__name__, message)
try:
file.write(text)
except OSEr... | Hook to override default showwarning.
https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings |
361,358 | def insert_documents(self, documents, database_name=None, collection_name=None):
if documents is None:
raise AirflowBadRequest("You cannot insert empty documents")
created_documents = []
for single_document in documents:
created_documents.append(
... | Insert a list of new documents into an existing collection in the CosmosDB database. |
361,359 | def _generate_lambda(self):
self.tf_conf[][][] = {
: ,
: self.resource_name,
: ,
: ,
:
,
: self.description,
: ,
: 120
}
self.tf_conf[][] = {
:
... | Generate the lambda function and its IAM role, and add to self.tf_conf |
361,360 | def fetch(self, *args, **kwargs):
response = client.get(.format(self.id))
self._update_data(response.json()) | 同步服务器的 Notification 数据 |
361,361 | def handler(self, event):
if self.escape(event):
self.stop()
elif self.diagnostic:
self._diagnostic(event)
else:
self._tap(event)
return True | Upper level handler of keyboard events. |
361,362 | def _start_services(self, console_env):
self._ad.services.register(, sl4a_service.Sl4aService)
console_env[] = self._ad.services.sl4a
console_env[] = self._ad.sl4a
console_env[] = self._ad.ed | Overrides superclass. |
361,363 | def jsonresolver_loader(url_map):
from flask import current_app
from . import current_jsonschemas
url_map.add(Rule(
"{0}/<path:path>".format(current_app.config[]),
endpoint=current_jsonschemas.get_schema,
host=current_app.config[])) | JSON resolver plugin that loads the schema endpoint.
Injected into Invenio-Records JSON resolver. |
361,364 | def _linux_nqn():
ret = []
initiator =
try:
with salt.utils.files.fopen(initiator, ) as _nvme:
for line in _nvme:
line = line.strip()
if line.startswith():
ret.append(line)
except IOError as ex:
if ex.errno != errno.E... | Return NVMe NQN from a Linux host. |
361,365 | def rna_transcript_expression_dict_from_args(args):
if args.rna_transcript_fpkm_tracking_file:
return load_cufflinks_fpkm_dict(args.rna_transcript_fpkm_tracking_file)
elif args.rna_transcript_fpkm_gtf_file:
return load_transcript_fpkm_dict_from_gtf(
args.rna_transcript_fpkm_gtf_... | Returns a dictionary mapping Ensembl transcript IDs to FPKM expression
values or None if neither Cufflinks tracking file nor StringTie GTF file
were specified. |
361,366 | 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 |
361,367 | def to_python(self, data):
if data is None:
return data
if self.datatype:
return self.datatype(data)
else:
return data | Convert a data to python format. |
361,368 | def delete_image(self, image_id):
response = self._perform_request(url= + image_id,
method=)
return response | Removes only user created images.
:param image_id: The unique ID of the image.
:type image_id: ``str`` |
361,369 | def construct_api_url(api_url, **params):
querystring = []
params, _ = _transparent_params(params or {})
params = requests.utils.to_key_val_list(params)
for (k, v) in params:
querystring.append(
% (Twython.encode(k), quote_plus(Twython.encode(v)))
... | Construct a Twitter API url, encoded, with parameters
:param api_url: URL of the Twitter API endpoint you are attempting
to construct
:param \*\*params: Parameters that are accepted by Twitter for the
endpoint you're requesting
:rtype: string
Usage::
>>> from... |
361,370 | def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
assert wait_for_completion is True
try:
console = hmc.consoles.lookup_by_oid(None)
except KeyError:
raise InvalidResourceError(method, uri)
check_required_fie... | Operation: Create Password Rule. |
361,371 | def rename_fields(env, field_spec, no_deep=False):
cr = env.cr
for model, table, old_field, new_field in field_spec:
if column_exists(cr, table, old_field):
rename_columns(cr, {table: [(old_field, new_field)]})
cr.execute(, (new_field, old_field, model),
)
... | Rename fields. Typically called in the pre script. WARNING: If using
this on base module, pass the argument ``no_deep`` with True value for
avoiding the using of the environment (which is not yet loaded).
This, in contrast of ``rename_columns``, performs all the steps for
completely rename a field from... |
361,372 | def get_machine_stats(self):
self.logger.debug("Gathering machine stats")
the_dict = {}
keys = self.redis_conn.keys()
for key in keys:
elements = key.split(":")
machine = elements[2]
spider = elements[3]
response = el... | Gather spider based stats |
361,373 | def info_cmd():
sdat = stagyydata.StagyyData(conf.core.path)
lsnap = sdat.snaps.last
lstep = sdat.steps.last
print(.format(sdat.path))
if lsnap.geom.threed:
dimension = .format(lsnap.geom.nxtot,
lsnap.geom.nytot,
... | Print basic information about StagYY run. |
361,374 | def euler_from_matrix(matrix, axes=):
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
except (AttributeError, KeyError):
_TUPLE2AXES[axes]
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = _NEXT_AXIS[i + parity]
k = _NEXT_AXIS[i - par... | Return Euler angles from rotation matrix for specified axis sequence.
axes : One of 24 axis sequences as string or encoded tuple
Note that many Euler angle triplets can describe one matrix.
>>> R0 = euler_matrix(1, 2, 3, 'syxz')
>>> al, be, ga = euler_from_matrix(R0, 'syxz')
>>> R1 = euler_matrix... |
361,375 | def update_identities(self, identities):
content = self._serialize.body(identities, )
response = self._send(http_method=,
location_id=,
version=,
content=content)
return self._deserialize(, self._u... | UpdateIdentities.
:param :class:`<VssJsonCollectionWrapper> <azure.devops.v5_0.identity.models.VssJsonCollectionWrapper>` identities:
:rtype: [IdentityUpdateData] |
361,376 | def _get_required_args(fn):
argspec = tf_inspect.getfullargspec(fn)
args = argspec.args
if tf_inspect.isclass(fn):
args = args[1:]
if argspec.defaults:
args = args[:-len(argspec.defaults)]
return tuple(args) | Returns the distribution's required args. |
361,377 | def print(self):
print(tabulate(
((i, *row) for i, row in enumerate(self.results, 1)),
headers=self.headers,
)) | Print results table.
>>> Results(['title'], [('Konosuba',), ('Oreimo',)]).print()
# title
--- --------
1 Konosuba
2 Oreimo |
361,378 | def assign_highest_value(exposure, hazard):
output_layer_name = assign_highest_value_steps[]
hazard_inasafe_fields = hazard.keywords[]
if not hazard.keywords.get():
raise InvalidKeywordsForProcessingAlgorithm
if not hazard_inasafe_fields.get(hazard_class_field[]):
raise InvalidKey... | Assign the highest hazard value to an indivisible feature.
For indivisible polygon exposure layers such as buildings, we need to
assigned the greatest hazard that each polygon touches and use that as the
effective hazard class.
Issue https://github.com/inasafe/inasafe/issues/3192
We follow the co... |
361,379 | def messages(self):
offset = self.header_length
maxlen = self.header_length + self.total_messages * MacIndexMessage.LENGTH
while offset < maxlen:
yield MacIndexMessage(mm=self.mmap, offset=o... | A generator yielding the :class:`MacIndexMessage`
structures in this index file. |
361,380 | def get_pmg_structure(phonopy_structure):
lattice = phonopy_structure.get_cell()
frac_coords = phonopy_structure.get_scaled_positions()
symbols = phonopy_structure.get_chemical_symbols()
masses = phonopy_structure.get_masses()
mms = phonopy_structure.get_magnetic_moments()
mms = mms or [0]... | Convert a PhonopyAtoms object to pymatgen Structure object.
Args:
phonopy_structure (PhonopyAtoms): A phonopy structure object. |
361,381 | def query_entities(self, table_name, filter=None, select=None, num_results=None,
marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA,
property_resolver=None, timeout=None):
args = (table_name,)
kwargs = {: filter, : select, : num_results, :... | Returns a generator to list the entities in the table specified. The
generator will lazily follow the continuation tokens returned by the
service and stop when all entities have been returned or max_results is
reached.
If max_results is specified and the account has more than that nu... |
361,382 | async def _task(self):
if self._handlers.values():
start_tasks = [h.start() for h in self._handlers.values()]
await asyncio.wait(start_tasks, loop=self.loop)
while self.running:
if self.events:
event, kwargs = await self._queue.get()
... | Main queue processor |
361,383 | def add_tools(self, *tools):
for tool in tools:
if not isinstance(tool, Tool):
raise ValueError("All arguments to add_tool must be Tool subclasses.")
self.toolbar.tools.append(tool) | Adds tools to the plot.
Args:
*tools (Tool) : the tools to add to the Plot
Returns:
None |
361,384 | def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]:
jsonschema_validate(request, schema)
return request | Wraps jsonschema.validate, returning the same object passed in.
Args:
request: The deserialized-from-json request.
schema: The jsonschema schema to validate against.
Raises:
jsonschema.ValidationError |
361,385 | def _write(self, stream, text, byte_order):
if text:
self._write_txt(stream)
else:
if self._have_list:
self._write_bin(stream, byte_order)
else:
stream.write(s... | Write the data to a PLY file. |
361,386 | def zip(self, enumerable, func):
if not isinstance(enumerable, Enumerable3):
raise TypeError()
return Enumerable3(itertools.zip_longest(self, enumerable)) \
.where(lambda x: x[0] is not None and x[1] is not None) \
.select(lambda x: func(x)) | Merges 2 Enumerables using the given function. If the 2 collections are of unequal length, then
merging continues until the end of one of the collections is reached
:param enumerable: Enumerable collection to merge with
:param func: a function to perform the merging
:return: Enumerable |
361,387 | def is_valid(self):
import scipy.sparse
if scipy.sparse.isspmatrix(self.matrix):
raise NotImplementedError(
)
elif self._eigval is not None:
return np.all(np.greater(self._eigval, 0))
else:
try:
... | Test if the matrix is positive definite Hermitian.
If the matrix decomposition is available, this test checks
if all eigenvalues are positive.
Otherwise, the test tries to calculate a Cholesky decomposition,
which can be very time-consuming for large matrices. Sparse
matrices ar... |
361,388 | def prepare(self):
self._provenance_ready = False
if len(self._exposures) < 2:
message = generate_input_error_message(
tr(),
m.Paragraph(tr()))
self._is_ready = False
return PREPARE_FAILED_BAD_INPUT, message
existing... | Method to check if the impact function can be run.
:return: A tuple with the status of the IF and an error message if
needed.
The status is PREPARE_SUCCESS if everything was fine.
The status is PREPARE_FAILED_BAD_INPUT if the client should fix
something.
... |
361,389 | def register_handler(self, callable_obj, entrypoint, methods=(,)):
router_obj = Route.wrap_callable(
uri=entrypoint,
methods=methods,
callable_obj=callable_obj
)
if router_obj.is_valid:
self._routes.add(router_obj)
return sel... | Register a handler callable to a specific route.
Args:
entrypoint (str): The uri relative path.
methods (tuple): A tuple of valid method strings.
callable_obj (callable): The callable object.
Returns:
The Router instance (for chaining purposes).
... |
361,390 | def daemons_start(self, run_daemons=True):
result = True
if run_daemons:
logger.info("Alignak configured daemons start:")
else:
logger.info("Alignak configured daemons check:")
for satellites_list in [self.conf.arbiters, self.conf.receivers, se... | Manage the list of the daemons in the configuration
Check if the daemon needs to be started by the Arbiter.
If so, starts the daemon if `run_daemons` is True
:param run_daemons: run the daemons or make a simple check
:type run_daemons: bool
:return: True if all daemons are ru... |
361,391 | def _request(self, request, proxies, timeout, verify, **_):
settings = self.http.merge_environment_settings(
request.url, proxies, False, verify, None)
self._delay()
response = self.http.send(
request, timeout=timeout, allow_redirects=False, **settings)
... | This is where we apply rate limiting and make the HTTP request. |
361,392 | def minimum_spanning_tree_kruskal(self, display = None, components = None):
s Algorithm.
Input:
display: Display method.
component: component number.
Post:
attribute of nodes and edges may change.
Return:
Returns list of edges where edges ... | API: minimum_spanning_tree_kruskal(self, display = None,
components = None)
Description:
Determines a minimum spanning tree using Kruskal's Algorithm.
Input:
display: Display method.
component: component number.
Post:
... |
361,393 | def contributor_group(self):
items = listify(chained_get(self._head, [, ], []))
out = []
fields =
pers = namedtuple(, fields)
for item in items:
entry = item.get(, {})
new = pers(indexed_name=entry.get(),
role=entry.get(), surname... | List of namedtuples representing contributors compiled by Scopus,
in the form (given_name, initials, surname, indexed_name, role). |
361,394 | def login(self, username=None, password=None,
section=):
if self.has_logged_in:
return True
if username is None or password is None:
credential = conf.get_credential(section)
username = credential[]
password = credential[]
p... | Created the passport with ``username`` and ``password`` and log in.
If either ``username`` or ``password`` is None or omitted, the
credentials file will be parsed.
:param str username: username to login (email, phone number or user ID)
:param str password: password
:param str se... |
361,395 | def _strip_schema(url):
result = parse_url(url, allow_fragments=False)
return result.netloc + result.path | Returns the url without the s3:// part |
361,396 | def move(src, dst):
*
src = os.path.expanduser(src)
dst = os.path.expanduser(dst)
if not os.path.isabs(src):
raise SaltInvocationError()
if not os.path.isabs(dst):
raise SaltInvocationError()
ret = {
: True,
: " moved to ".format(src, dst),
}
try:
... | Move a file or directory
CLI Example:
.. code-block:: bash
salt '*' file.move /path/to/src /path/to/dst |
361,397 | def to_array(self):
array = super(VideoNote, self).to_array()
array[] = u(self.file_id)
array[] = int(self.length)
array[] = int(self.duration)
if self.thumb is not None:
array[] = self.thumb.to_array()
if self.file_size is not None:
... | Serializes this VideoNote to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
361,398 | def list_hosts():
with Session() as session:
try:
resp = session.VFolder.list_hosts()
print(f"Default vfolder host: {resp[]}")
print(f"Usable hosts: {.join(resp[])}")
except Exception as e:
print_error(e)
sys.exit(1) | List the hosts of virtual folders that is accessible to the current user. |
361,399 | def add_namespace(self, name, a_namespace):
self.namespaces[name] = a_namespace
for k in a_namespace.keys_breadth_first():
an_option = a_namespace[k]
if not an_option.foreign_data:
an_option.foreign_data = DotDict()
... | as we build up argparse, the actions that define a subparser are
translated into configman options. Each of those options must be
tagged with the value of the subparse to which they correspond. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.