Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
14,400 | def get_worksheet(self, id_or_name):
url = self.build_url(self._endpoints.get().format(id=quote(id_or_name)))
response = self.session.get(url)
if not response:
return None
return self.worksheet_constructor(parent=self, **{self._cloud_data_key: response.json()}) | Gets a specific worksheet by id or name |
14,401 | def remove_record(self, record):
if not self.has_record(record):
current_app.logger.warning(
.format(uuid=record.id, comm=self.id))
else:
key = current_app.config[]
record[key] = [c for c in record[key] if c != self.id]
... | Remove an already accepted record from the community.
:param record: Record object.
:type record: `invenio_records.api.Record` |
14,402 | def fetch_command(self, global_options, subcommand):
commands = self.get_commands(global_options)
try:
klass = commands[subcommand]
except KeyError:
sys.stderr.write("Unknown command: %r\nType for usage.\nMany commands will only run at project directory, m... | Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"uliweb") if it can't be found. |
14,403 | def _sanity_check_coerce_type_outside_of_fold(ir_blocks):
is_in_fold = False
for first_block, second_block in pairwise(ir_blocks):
if isinstance(first_block, Fold):
is_in_fold = True
if not is_in_fold and isinstance(first_block, CoerceType):
if not isinstance(second... | Ensure that CoerceType not in a @fold are followed by a MarkLocation or Filter block. |
14,404 | def main(argv):
input_file = ""
output_file = ""
monitor = None
formula = None
trace = None
iformula = None
itrace = None
isys = None
online = False
fuzzer = False
l2m = False
debug = False
rounds = 1
server_port = 8080
webservice = False
help_str_ex... | Main mon
:param argv: console arguments
:return: |
14,405 | def setData(self, data, setName=None):
if not isinstance(data, DataFrame):
if pd is not None and isinstance(data, pd.DataFrame):
data = DataFrame.fromPandas(data)
if setName is None:
lock_and_call(
lambda: self._impl.setData(data._impl),
... | Assign the data in the dataframe to the AMPL entities with the names
corresponding to the column names.
Args:
data: The dataframe containing the data to be assigned.
setName: The name of the set to which the indices values of the
DataFrame are to be assigned.
... |
14,406 | def getConfig(self, key):
if hasattr(self, key):
return getattr(self, key)
else:
return False | Get a Config Value |
14,407 | def get_instance(self, payload):
return RoleInstance(self._version, payload, service_sid=self._solution[], ) | Build an instance of RoleInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.role.RoleInstance
:rtype: twilio.rest.chat.v2.service.role.RoleInstance |
14,408 | def all_sharded_cluster_links(cluster_id, shard_id=None,
router_id=None, rel_to=None):
return [
sharded_cluster_link(rel, cluster_id, shard_id, router_id,
self_rel=(rel == rel_to))
for rel in (
, ,
, ,
... | Get a list of all links to be included with ShardedClusters. |
14,409 | def parts(self, *args, **kwargs):
return self._client.parts(*args, activity=self.id, **kwargs) | Retrieve parts belonging to this activity.
Without any arguments it retrieves the Instances related to this task only.
This call only returns the configured properties in an activity. So properties that are not configured
are not in the returned parts.
See :class:`pykechain.Client.par... |
14,410 | def _filter_desc(self, indexing):
if len(indexing) > 0:
desc_tmp = np.zeros((len(indexing),len(self.header_desc)),dtype=)
data_tmp = np.zeros((len(indexing),len(self.header_data)))
style_tmp= np.zeros((len(indexing),len(self.header_style)),dtype=)
... | Private function to filter data, goes with filter_desc |
14,411 | def update_group_states_for_vifs(self, vifs, ack):
vif_keys = [self.vif_key(vif.device_id, vif.mac_address)
for vif in vifs]
self.set_fields(vif_keys, SECURITY_GROUP_ACK, ack) | Updates security groups by setting the ack field |
14,412 | def customchain(**kwargsChain):
def wrap(f):
@click.pass_context
@verbose
def new_func(ctx, *args, **kwargs):
newoptions = ctx.obj
newoptions.update(kwargsChain)
ctx.bitshares = BitShares(**newoptions)
ctx.blockchain = ctx.bitshares
... | This decorator allows you to access ``ctx.bitshares`` which is
an instance of BitShares. But in contrast to @chain, this is a
decorator that expects parameters that are directed right to
``BitShares()``.
... code-block::python
@main.command()
@click.opti... |
14,413 | def stop(self):
if not self._running:
logging.warning()
return False
if self._cap:
self._cap.release()
self._cap = None
self._running = False
return True | Stop the sensor. |
14,414 | def release(input_dict, environment_dict):
allow_ssl_insecure = _get_user_argument(input_dict, ) is not None
groupname = environment_dict[]
nodelist = seash_global_variables.targets[groupname]
retdict = seash_helper.contact_targets(nodelist, _get_clearinghouse_vessel_handle)
clearinghouse_vesse... | <Purpose>
Releases the specified vessels.
<Arguments>
input_dict: The commanddict representing the user's input.
environment_dict: The dictionary representing the current seash
environment.
<Side Effects>
Connects to the Clearinghouse and releases vessels.
Removes the ... |
14,415 | def _onSize(self, evt):
DEBUG_MSG("_onSize()", 2, self)
self._width, self._height = self.GetClientSize()
self.bitmap =wx.EmptyBitmap(self._width, self._height)
self._isDrawn = False
if self._width <= 1 or self._height <= 1: return
dpival = self.figur... | Called when wxEventSize is generated.
In this application we attempt to resize to fit the window, so it
is better to take the performance hit and redraw the whole window. |
14,416 | def new(partname, content_type):
xml = % nsmap[]
override = parse_xml(xml)
override.set(, partname)
override.set(, content_type)
return override | Return a new ``<Override>`` element with attributes set to parameter
values. |
14,417 | def add_multiple_to_queue(self, items, container=None):
if container is not None:
container_uri = container.resources[0].uri
container_metadata = to_didl_string(container)
else:
container_uri =
container_metadata =
chunk_size = 16 ... | Add a sequence of items to the queue.
Args:
items (list): A sequence of items to the be added to the queue
container (DidlObject, optional): A container object which
includes the items. |
14,418 | def _get_sd(file_descr):
for stream_descr in NonBlockingStreamReader._streams:
if file_descr == stream_descr.stream.fileno():
return stream_descr
return None | Get streamdescriptor matching file_descr fileno.
:param file_descr: file object
:return: StreamDescriptor or None |
14,419 | def init_cas_a (year):
year = float (year)
models[] = lambda f: cas_a (f, year) | Insert an entry for Cas A into the table of models. Need to specify the
year of the observations to account for the time variation of Cas A's
emission. |
14,420 | def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
if n is None:
collections.deque(iterator, maxlen=0)
else:
next(islice(iterator, n, n), None) | Advance the iterator n-steps ahead. If n is none, consume entirely. |
14,421 | def _legion_state(self, inputs, t, argv):
index = argv;
x = inputs[0];
y = inputs[1];
p = inputs[2];
potential_influence = heaviside(p + math.exp(-self._params.alpha * t) - self._params.teta);
dx = 3.0 * x - x ** ... | !
@brief Returns new values of excitatory and inhibitory parts of oscillator and potential of oscillator.
@param[in] inputs (list): Initial values (current) of oscillator [excitatory, inhibitory, potential].
@param[in] t (double): Current time of simulation.
@param[in] argv... |
14,422 | def fix(self):
fill_layout = None
fill_height = y = 0
for _ in range(2):
if self._has_border:
x = y = start_y = 1
height = self._canvas.height - 2
width = self._canvas.width - 2
else:
... | Fix the layouts and calculate the locations of all the widgets.
This function should be called once all Layouts have been added to the Frame and all
widgets added to the Layouts. |
14,423 | def _getgrnam(name, root=None):
root = root or
passwd = os.path.join(root, )
with salt.utils.files.fopen(passwd) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = line.strip().split()
if len(comps) < 4:
log.debug... | Alternative implementation for getgrnam, that use only /etc/group |
14,424 | def hosts(self, **kwargs):
kwargs[] = self.id
return self.connection.listHosts(**kwargs) | Convenience wrapper around listHosts(...) for this channel ID.
:param **kwargs: keyword arguments to the listHosts RPC.
:returns: deferred that when fired returns a list of hosts (dicts). |
14,425 | def es_query_proto(path, selects, wheres, schema):
output = None
last_where = MATCH_ALL
for p in reversed(sorted( wheres.keys() | set(selects.keys()))):
where = wheres.get(p)
select = selects.get(p)
if where:
where = AndOp(where).partial_eval().to_esfilter(schema)
... | RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE
:param path: THE NESTED PATH (NOT INCLUDING TABLE NAME)
:param wheres: MAP FROM path TO LIST OF WHERE CONDITIONS
:return: (es_query, filters_map) TUPLE |
14,426 | def retrieveVals(self):
file_stats = self._fileInfo.getContainerStats()
for contname in self._fileContList:
stats = file_stats.get(contname)
if stats is not None:
if self.hasGraph():
self.setGraphVal(, contname,
... | Retrieve values for graphs. |
14,427 | def _add_access_token_to_response(self, response, access_token):
response[] = access_token.value
response[] = access_token.type
response[] = access_token.expires_in | Adds the Access Token and the associated parameters to the Token Response. |
14,428 | def Create(self, *args, **kwargs):
if not self.writable:
raise IOError()
options = kwargs.pop(, {})
kwargs[] = driverdict_tolist(options or self.settings)
return self._driver.Create(*args, **kwargs) | Calls Driver.Create() with optionally provided creation options as
dict, or falls back to driver specific defaults. |
14,429 | def wrap(self, sock):
EMPTY_RESULT = None, {}
try:
s = self.context.wrap_socket(
sock, do_handshake_on_connect=True, server_side=True,
)
except ssl.SSLError as ex:
if ex.errno == ssl.SSL_ERROR_EOF:
... | Wrap and return the given socket, plus WSGI environ entries. |
14,430 | def _replace_coerce(self, to_replace, value, inplace=True, regex=False,
convert=False, mask=None):
if mask.any():
block = super()._replace_coerce(
to_replace=to_replace, value=value, inplace=inplace,
regex=regex, convert=convert, mask=... | Replace value corresponding to the given boolean array with another
value.
Parameters
----------
to_replace : object or pattern
Scalar to replace or regular expression to match.
value : object
Replacement object.
inplace : bool, default False
... |
14,431 | def assume_role_credentials(self, arn):
log.info("Assuming role as %s", arn)
for name in [, , , ]:
if name in os.environ and not os.environ[name]:
del os.environ[name]
sts = self.amazon.session.client("sts")
with self.catch_boto_400("Couldn... | Return the environment variables for an assumed role |
14,432 | def _start(self):
self._recv_lock = coros.Semaphore(0)
self._send_lock = coros.Semaphore(0)
self._recv_thread = gevent.spawn(self._recv)
self._send_thread = gevent.spawn(self._send)
self._recv_thread.link(self._thread_error)
... | Starts the underlying send and receive threads. |
14,433 | def get_memfree(memory, parallel):
number = int(memory.rstrip(string.ascii_letters))
memtype = memory.lstrip(string.digits)
if not memtype:
memtype = "G"
return "%d%s" % (number*parallel, memtype) | Computes the memory required for the memfree field. |
14,434 | def select_by_index(self, index):
match = str(index)
for opt in self.options:
if opt.get_attribute("index") == match:
self._setSelected(opt)
return
raise NoSuchElementException("Could not locate element with index %d" % index) | Select the option at the given index. This is done by examing the "index" attribute of an
element, and not merely by counting.
:Args:
- index - The option at this index will be selected
throws NoSuchElementException If there is no option with specified index in SELECT |
14,435 | def clearOldCalibrations(self, date=None):
self.coeffs[] = [self.coeffs[][-1]]
self.coeffs[] = [self.coeffs[][-1]]
for light in self.coeffs[]:
self.coeffs[][light] = [
self.coeffs[][light][-1]]
for light in self.coeffs[]:
self.co... | if not only a specific date than remove all except of the youngest calibration |
14,436 | def buscar_timeout_opcvip(self, id_ambiente_vip):
if not is_valid_int_param(id_ambiente_vip):
raise InvalidParameterError(
u)
url = + str(id_ambiente_vip) +
code, xml = self.submit(None, , url)
return self.response(code, xml) | Buscar nome_opcao_txt das Opcoes VIp quando tipo_opcao = 'Timeout' pelo environmentvip_id
:return: Dictionary with the following structure:
::
{‘timeout_opt’: ‘timeout_opt’: <'nome_opcao_txt'>}
:raise InvalidParameterError: Environment VIP identifier is null and invalid.
:... |
14,437 | def _shrink_list(self, shrink):
res = []
if len(shrink) == 1:
return self.shrink(shrink[0])
else:
for a in shrink:
temp = self.shrink(a)
if temp:
res.append(temp)
return res | Shrink list down to essentials
:param shrink: List to shrink
:type shrink: list
:return: Shrunk list
:rtype: list |
14,438 | def updateTerms(self, data:list, LIMIT:int=20, _print:bool=True, crawl:bool=False,) -> list:
url_base = self.base_url +
merged_data = []
old_data = self.identifierSearches(
[d[] for d in data],
LIMIT = LIMIT,
_print = _print,
... | Updates existing entities
Args:
data:
needs:
id <str>
ilx_id <str>
options:
definition <str> #bug with qutations
superclasses ... |
14,439 | def read(self):
if self._is_initialized:
return
self._is_initialized = True
if not isinstance(self._file_or_files, (tuple, list)):
files_to_read = [self._file_or_files]
else:
files_to_read = list(self._file_or_files)
seen = ... | Reads the data stored in the files we have been initialized with. It will
ignore files that cannot be read, possibly leaving an empty configuration
:return: Nothing
:raise IOError: if a file cannot be handled |
14,440 | def spaceout_and_resize_panels(self):
ncol = self.ncol
nrow = self.nrow
figure = self.figure
theme = self.theme
get_property = theme.themeables.property
left = figure.subplotpars.left
right = figure.subplotpars.right
top = figure.subplotpars.top
... | Adjust the spacing between the panels and resize them
to meet the aspect ratio |
14,441 | def close(self):
assert self._opened, "RPC System is not opened"
logger.debug("Closing rpc system. Stopping ping loop")
self._ping_loop.stop()
if self._ping_current_iteration:
self._ping_current_iteration.cancel()
return self._connectionpool.close() | Stop listing for new connections and close all open connections.
:returns: Deferred that calls back once everything is closed. |
14,442 | def _inferSchemaFromList(self, data, names=None):
if not data:
raise ValueError("can not infer schema from empty dataset")
first = data[0]
if type(first) is dict:
warnings.warn("inferring schema from dict is deprecated,"
"please use pysp... | Infer schema from list of Row or tuple.
:param data: list of Row or tuple
:param names: list of column names
:return: :class:`pyspark.sql.types.StructType` |
14,443 | def distance_centimeters_continuous(self):
self._ensure_mode(self.MODE_US_DIST_CM)
return self.value(0) * self._scale() | Measurement of the distance detected by the sensor,
in centimeters.
The sensor will continue to take measurements so
they are available for future reads.
Prefer using the equivalent :meth:`UltrasonicSensor.distance_centimeters` property. |
14,444 | def build(self, X, Y, w=None, edges=None):
self.reset()
if X is None or Y is None:
return
self.__set_data(X, Y, w)
if self.debug:
sys.stdout.write("Graph Preparation: ")
start = time.clock()
self.graph_rep = nglpy.Graph(
... | Assigns data to this object and builds the requested topological
structure
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
... |
14,445 | def adsSyncWriteControlReqEx(
port, address, ads_state, device_state, data, plc_data_type
):
sync_write_control_request = _adsDLL.AdsSyncWriteControlReqEx
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
ads_state_c = ctypes.c_ulong(ads_state)
device_state_c = ctypes.c_ulong(... | Change the ADS state and the machine-state of the ADS-server.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr adr: local or remote AmsAddr
:param int ads_state: new ADS-state, according to ADSTATE constants
:param int device_state: new machine-state
:para... |
14,446 | def getTableAsCsv(self, networkId, tableType, verbose=None):
response=api(url=self.___url++str(networkId)++str(tableType)+, method="GET", verbose=verbose, parse_params=False)
return response | Returns a CSV representation of the table specified by the `networkId` and `tableType` parameters. All column names are included in the first row.
:param networkId: SUID of the network containing the table
:param tableType: Table type
:param verbose: print more
:returns: 200: successfu... |
14,447 | def start_resolver(finder=None, wheel_cache=None):
pip_command = get_pip_command()
pip_options = get_pip_options(pip_command=pip_command)
if not finder:
finder = get_finder(pip_command=pip_command, pip_options=pip_options)
if not wheel_cache:
wheel_cache = WHEEL_CACHE
_ensure... | Context manager to produce a resolver.
:param finder: A package finder to use for searching the index
:type finder: :class:`~pip._internal.index.PackageFinder`
:return: A 3-tuple of finder, preparer, resolver
:rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._interna... |
14,448 | def find_by_id(self, organization_export, params={}, **options):
path = "/organization_exports/%s" % (organization_export)
return self.client.get(path, params, **options) | Returns details of a previously-requested Organization export.
Parameters
----------
organization_export : {Id} Globally unique identifier for the Organization export.
[params] : {Object} Parameters for the request |
14,449 | def format_modes(modes, full_modes=False, current_mode=None):
t = table.Table(((
if mode == current_mode else ,
str(Q.CGDisplayModeGetWidth(mode)),
str(Q.CGDisplayModeGetHeight(mode)), ... | Creates a nice readily printable Table for a list of modes.
Used in `displays list' and the candidates list
in `displays set'. |
14,450 | def __step1(self):
C = self.C
n = self.n
for i in range(n):
minval = min(self.C[i])
for j in range(n):
self.C[i][j] -= minval
return 2 | For each row of the matrix, find the smallest element and
subtract it from every element in its row. Go to Step 2. |
14,451 | def _handle_double_click(self, event):
if event.get_button()[1] == 1:
path_info = self.tree_view.get_path_at_pos(int(event.x), int(event.y))
if path_info:
path = path_info[0]
iter = self.list_store.get_iter(path)
model = self.l... | Double click with left mouse button focuses the element |
14,452 | def transform(self, X):
if self.mode_ == :
return np.apply_along_axis(self._target, 1, np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2])))
if self.mode_ == :
return np.apply_along_axis(self._majority, 1, np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2])))
... | Parameters
----------
X : array-like, shape [n x m]
The mask in form of n x m array. |
14,453 | async def _async_connect(self):
try:
self.conn_coro = self.client.connected()
aenter = type(self.conn_coro).__aenter__(self.conn_coro)
self.stream = await aenter
logger.info(f"Agent {str(self.jid)} connected and authenticated.")
except aiosasl.A... | connect and authenticate to the XMPP server. Async mode. |
14,454 | def rytov_sc(radius=5e-6, sphere_index=1.339, medium_index=1.333,
wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80),
center=(39.5, 39.5), radius_sampling=42):
r
r_ryt, n_ryt = correct_rytov_sc_input(radius_sc=radius,
sphere_index_sc=sphere... | r"""Field behind a dielectric sphere, systematically corrected Rytov
This method implements a correction of
:func:`qpsphere.models.rytov`, where the
`radius` :math:`r_\text{Ryt}` and the `sphere_index`
:math:`n_\text{Ryt}` are corrected using
the approach described in :cite:`Mueller2018` (eqns. 3,4... |
14,455 | def keys(name, basepath=, **kwargs):
ret = {: name, : {}, : True, : }
pillar_kwargs = {}
for key, value in six.iteritems(kwargs):
pillar_kwargs[.format(key)] = value
pillar = __salt__[]({: }, pillar_kwargs)
paths = {
: os.path.join(basepath, ,
... | Manage libvirt keys.
name
The name variable used to track the execution
basepath
Defaults to ``/etc/pki``, this is the root location used for libvirt
keys on the hypervisor
The following parameters are optional:
country
The country that the certificate should ... |
14,456 | def shapely_formatter(_, vertices, codes=None):
elements = []
if codes is None:
for vertices_ in vertices:
if np.all(vertices_[0, :] == vertices_[-1, :]):
if len(vertices) < 3:
elements.append(Point(vertices_[0, :]))
... | `Shapely`_ style contour formatter.
Contours are returned as a list of :class:`shapely.geometry.LineString`,
:class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`
geometry elements.
Filled contours return a list of :class:`shapely.geometry.Polygon`
elements instead.
.. not... |
14,457 | def plot_data():
var = [, , , , , , , ]
lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2], [0, 9]])
for fname in fnames:
fig, axes = plt.subplots(nrows=4, ncols=2)
fig.set_size_inches(20, 10)
fig.subplots_adjust(top=0.95, bottom=0.... | Plot sample data up with the fancy colormaps. |
14,458 | def config_acl(args):
r = fapi.get_repository_config_acl(args.namespace, args.config,
args.snapshot_id)
fapi._check_response_code(r, 200)
acls = sorted(r.json(), key=lambda k: k[])
return map(lambda acl: .format(acl[], acl[]), acls) | Retrieve access control list for a method configuration |
14,459 | def set_current_limit(self, value, channel=1):
cmd = "I%d %f" % (channel, value)
self.write(cmd) | channel: 1=OP1, 2=OP2, AUX is not supported |
14,460 | def get_type_hints(obj, globalns=None, localns=None):
if getattr(obj, , None):
return {}
if isinstance(obj, type):
hints = {}
for base in reversed(obj.__mro__):
if globalns is None:
base_globals = sys.modules[base.__module__].__dict__
el... | Return type hints for an object.
This is often the same as obj.__annotations__, but it handles
forward references encoded as string literals, and if necessary
adds Optional[t] if a default value equal to None is set.
The argument may be a module, class, method, or function. The annotations
are ret... |
14,461 | def average_data(self,ranges=[[None,None]],percentile=None):
ranges=copy.deepcopy(ranges)
for i in range(len(ranges)):
if ranges[i][0] is None:
ranges[i][0] = 0
else:
ranges[i][0] = int(ranges[i][0]*self.rate)
if rang... | given a list of ranges, return single point averages for every sweep.
Units are in seconds. Expects something like:
ranges=[[1,2],[4,5],[7,7.5]]
None values will be replaced with maximum/minimum bounds.
For baseline subtraction, make a range baseline then sub it youtself.
... |
14,462 | def expanding_stdize(obj, **kwargs):
return (obj - obj.expanding(**kwargs).mean()) / (
obj.expanding(**kwargs).std()
) | Standardize a pandas object column-wise on expanding window.
**kwargs -> passed to `obj.expanding`
Example
-------
df = pd.DataFrame(np.random.randn(10, 3))
print(expanding_stdize(df, min_periods=5))
0 1 2
0 NaN NaN NaN
1 NaN Na... |
14,463 | def _all_escape(self):
self.unesc = not self.unesc
self.urls, self.urls_unesc = self.urls_unesc, self.urls
urls = iter(self.urls)
for item in self.items:
if isinstance(item, urwid.Columns):
item[1].set_label(shorten_url(next(urls... | u |
14,464 | def usable_ids(cls, id, accept_multi=True):
try:
qry_id = [int(id)]
except ValueError:
try:
qry_id = cls.from_cn(id)
except Exception:
qry_id = None
if not qry_id or not accept_multi and len(qry_id) != 1:
m... | Retrieve id from input which can be an id or a cn. |
14,465 | def installed(name,
pkgs=None,
dir=None,
user=None,
force_reinstall=False,
registry=None,
env=None):
ret = {: name, : None, : , : {}}
pkg_list = pkgs if pkgs else [name]
try:
installed_pkgs = __salt__[](dir=di... | Verify that the given package is installed and is at the correct version
(if specified).
.. code-block:: yaml
coffee-script:
npm.installed:
- user: someuser
coffee-script@1.0.1:
npm.installed: []
name
The package to install
.. versionchang... |
14,466 | def print_summary(self):
for input in self.form.find_all(
("input", "textarea", "select", "button")):
input_copy = copy.copy(input)
for subtag in input_copy.find_all() + [input_copy]:
if subtag.string:
... | Print a summary of the form.
May help finding which fields need to be filled-in. |
14,467 | def preferred_format(incomplete_format, preferred_formats):
incomplete_format = long_form_one_format(incomplete_format)
if in incomplete_format:
return incomplete_format
for fmt in long_form_multiple_formats(preferred_formats):
if ((incomplete_format[] == fmt[] or (
fm... | Return the preferred format for the given extension |
14,468 | def extract_fields(lines, delim, searches, match_lineno=1, **kwargs):
keep_idx = []
for lineno, line in lines:
if lineno < match_lineno or delim not in line:
if lineno == match_lineno:
raise WcutError(.format(
match_lineno))
yield [line]
... | Return generator of fields matching `searches`.
Parameters
----------
lines : iterable
Provides line number (1-based) and line (str)
delim : str
Delimiter to split line by to produce fields
searches : iterable
Returns search (str) to match against line fields.
match_line... |
14,469 | def completeness(self, catalogue, config, saveplot=False, filetype=,
timeout=120):
magnitude_bintime_binincrement_lock
if saveplot and not isinstance(saveplot, str):
raise ValueError()
magnitude_bins = self._get_magnitudes_from_spacing(
cata... | :param catalogue:
Earthquake catalogue as instance of
:class:`openquake.hmtk.seismicity.catalogue.Catalogue`
:param dict config:
Configuration parameters of the algorithm, containing the
following information:
'magnitude_bin' Size of magnitude bin (non... |
14,470 | def get_local_annotations(
cls, target, exclude=None, ctx=None, select=lambda *p: True
):
result = []
exclude = () if exclude is None else exclude
try:
local_annotations = get_local_property(
target, Annotation.__ANNOT... | Get a list of local target annotations in the order of their
definition.
:param type cls: type of annotation to get from target.
:param target: target from where get annotations.
:param tuple/type exclude: annotation types to exclude from selection.
:param ctx: target ctx.
... |
14,471 | def _split_tidy(self, string, maxsplit=None):
if maxsplit is None:
return string.rstrip("\n").split("\t")
else:
return string.rstrip("\n").split("\t", maxsplit) | Rstrips string for \n and splits string for \t |
14,472 | def ae_latent_softmax(latents_pred, latents_discrete, hparams):
vocab_size = 2 ** hparams.z_size
if hparams.num_decode_blocks < 2:
latents_logits = tf.layers.dense(latents_pred, vocab_size,
name="extra_logits")
if hparams.logit_normalization:
latents_logits *= t... | Latent prediction and loss. |
14,473 | def get_all_groups(region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
retries = 30
while True:
try:
next_token =
asgs = []
while next_token is not None:
ret = conn.get_all_... | Return all AutoScale Groups visible in the account
(as a list of boto.ec2.autoscale.group.AutoScalingGroup).
.. versionadded:: 2016.11.0
CLI example:
.. code-block:: bash
salt-call boto_asg.get_all_groups region=us-east-1 --output yaml |
14,474 | def hessian(self, x, y, grid_interp_x=None, grid_interp_y=None, f_=None, f_x=None, f_y=None, f_xx=None, f_yy=None, f_xy=None):
n = len(np.atleast_1d(x))
if n <= 1 and np.shape(x) == ():
f_xx_out = self.f_xx_interp(x, y, grid_interp_x, grid_interp_y, f_xx)
... | returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy |
14,475 | def add_interface_to_router(self, segment_id,
router_name, gip, router_ip, mask, server):
if not segment_id:
segment_id = DEFAULT_VLAN
cmds = []
for c in self._interfaceDict[]:
if self._mlag_configured:
... | Adds an interface to existing HW router on Arista HW device.
:param segment_id: VLAN Id associated with interface that is added
:param router_name: globally unique identifier for router/VRF
:param gip: Gateway IP associated with the subnet
:param router_ip: IP address of the router
... |
14,476 | def issues(self):
for board in self.get_boards():
for lst in self.get_lists(board[]):
listextra = dict(boardname=board[], listname=lst[])
for card in self.get_cards(lst[]):
issue = self.get_issue_for_record(card, extra=listextra)
... | Returns a list of dicts representing issues from a remote service. |
14,477 | def get_analysis_question(hazard, exposure):
question = specific_analysis_question(hazard, exposure)
if question:
return question
if hazard == hazard_generic:
return question | Construct analysis question based on hazard and exposure.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:returns: Analysis question based on reporting standards.
:rtype: str |
14,478 | def increment(self, key, value=1):
data, time_ = self._get_payload(key)
integer = int(data) + value
self.put(key, integer, int(time_))
return integer | Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool |
14,479 | def update(self, response):
data = response.splitlines()
_LOGGER.debug(, data, self.host)
while data:
line = data.pop(0)
if in line:
self.rtsp_version = int(line.split()[0][5])
self.status_code = int(line.split()[1])
... | Update session information from device response.
Increment sequence number when starting stream, not when playing.
If device requires authentication resend previous message with auth. |
14,480 | def from_string(string, _or=):
if _or:
and_or =
else:
and_or =
return Input(string, and_or=and_or) | Parse a given string and turn it into an input token. |
14,481 | def eval(self, expression):
expression_wrapped = wrap_script.format(expression)
self._libeng.engEvalString(self._ep, expression_wrapped)
mxresult = self._libeng.engGetVariable(self._ep, )
error_string = self._libmx.mxArrayToString(mxresult)
self._l... | Evaluate `expression` in MATLAB engine.
Parameters
----------
expression : str
Expression is passed to MATLAB engine and evaluated. |
14,482 | def uninstall_pgpm_from_db(self):
drop_schema_cascade_script =
if self._conn.closed:
self._conn = psycopg2.connect(self._connection_string, connection_factory=pgpm.lib.utils.db.MegaConnection)
cur = self._conn.cursor()
cur.execute(pgpm.lib.utils.db.SqlSc... | Removes pgpm from db and all related metadata (_pgpm schema). Install packages are left as they are
:return: 0 if successful and error otherwise |
14,483 | def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int:
if not hasattr(transaction, ):
raise TypeError(
"Transaction is missing attribute sender.",
"If sending an unsigned transaction, use SpoofTransaction and provide the",
"se... | Run the transaction with various gas limits, progressively
approaching the minimum needed to succeed without an OutOfGas exception.
The starting range of possible estimates is:
[transaction.intrinsic_gas, state.gas_limit].
After the first OutOfGas exception, the range is: (largest_limit_out_of_gas, sta... |
14,484 | def product_data_request(self):
msg = StandardSend(self._address,
COMMAND_PRODUCT_DATA_REQUEST_0X03_0X00)
self._send_msg(msg) | Request product data from a device.
Not supported by all devices.
Required after 01-Feb-2007. |
14,485 | def chunks(seq, chunk_size):
return (seq[i:i + chunk_size] for i in range(0, len(seq), chunk_size)) | Split seq into chunk_size-sized chunks.
:param seq: A sequence to chunk.
:param chunk_size: The size of chunk. |
14,486 | def command(execute=None):
if connexion.request.is_json:
execute = Execute.from_dict(connexion.request.get_json())
if(not hasAccess()):
return redirectUnauthorized()
try:
connector = None
parameters = {}
if (execute.command.parameters):
parame... | Execute a Command
Execute a command # noqa: E501
:param execute: The data needed to execute this command
:type execute: dict | bytes
:rtype: Response |
14,487 | def get_pickled_ontology(filename):
pickledfile = os.path.join(ONTOSPY_LOCAL_CACHE, filename + ".pickle")
if GLOBAL_DISABLE_CACHE:
printDebug(
"WARNING: DEMO MODE cache has been disabled in __init__.py ==============",
"red")
if os.path.isfile(pickledfile) and not G... | try to retrieve a cached ontology |
14,488 | def health_node(consul_url=None, token=None, node=None, **kwargs):
*node1
ret = {}
query_params = {}
if not consul_url:
consul_url = _get_config()
if not consul_url:
log.error()
ret[] =
ret[] = False
return ret
if not node:
ra... | Health information about the registered node.
:param consul_url: The Consul server URL.
:param node: The node to request health information about.
:param dc: By default, the datacenter of the agent is queried;
however, the dc can be provided using the "dc" parameter.
:return: Health info... |
14,489 | def _extend_support_with_default_value(self, x, f, default_value):
with tf.name_scope("extend_support_with_default_value"):
x = tf.convert_to_tensor(value=x, dtype=self.dtype, name="x")
loc = self.loc + tf.zeros_like(self.scale) + tf.zeros_like(x)
x = x + tf.zeros_like(loc)
... | Returns `f(x)` if x is in the support, and `default_value` otherwise.
Given `f` which is defined on the support of this distribution
(`x >= loc`), extend the function definition to the real line
by defining `f(x) = default_value` for `x < loc`.
Args:
x: Floating-point `Tensor` to evaluate `f` at... |
14,490 | def fetch_entity_cls_from_registry(entity):
if isinstance(entity, str):
try:
return repo_factory.get_entity(entity)
except AssertionError:
raise
else:
return entity | Util Method to fetch an Entity class from an entity's name |
14,491 | def add_object(self, start, obj, object_size):
self._store(start, obj, object_size, overwrite=False) | Add/Store an object to this region at the given offset.
:param start:
:param obj:
:param int object_size: Size of the object
:return: |
14,492 | def text_input(self, window, allow_resize=False):
window.clear()
except exceptions.EscapeInterrupt:
out = None
self.curs_set(0)
return self.strip_textpad(out) | Transform a window into a text box that will accept user input and loop
until an escape sequence is entered.
If the escape key (27) is pressed, cancel the textbox and return None.
Otherwise, the textbox will wait until it is full (^j, or a new line is
entered on the bottom line) or the ... |
14,493 | def _merge(self, value):
if not value:
return []
if value is not None and not isinstance(value, list):
return value
item_spec = self._nested_validator
return [x if x is None else item_spec.get_default_for(x) for x in value] | Returns a list based on `value`:
* missing required value is converted to an empty list;
* missing required items are never created;
* nested items are merged recursively. |
14,494 | def getRegionsByType(self, regionClass):
regions = []
for region in self.regions.values():
if type(region.getSelf()) is regionClass:
regions.append(region)
return regions | Gets all region instances of a given class
(for example, nupic.regions.sp_region.SPRegion). |
14,495 | def get(self, name, default=None):
session_object = super(NotificationManager, self).get(name, default)
if session_object is not None:
self.delete(name)
return session_object | Retrieves the object with "name", like with SessionManager.get(), but
removes the object from the database after retrieval, so that it can be
retrieved only once |
14,496 | def tag_name(cls, tag):
while isinstance(tag, etree._Element):
tag = tag.tag
return tag.split()[-1] | return the name of the tag, with the namespace removed |
14,497 | def get_levenshtein(first, second):
if not first:
return len(second)
if not second:
return len(first)
prev_distances = range(0, len(second) + 1)
curr_distances = None
for first_idx, first_char in enumerate(first, start=1):
curr_distanc... | \
Get the Levenshtein distance between two strings.
:param first: the first string
:param second: the second string |
14,498 | def log(arg, base=None):
op = ops.Log(arg, base)
return op.to_expr() | Perform the logarithm using a specified base
Parameters
----------
base : number, default None
If None, base e is used
Returns
-------
logarithm : double type |
14,499 | def _complete_path(path=None):
if not path:
return _listdir()
dirname, rest = os.path.split(path)
tmp = dirname if dirname else
res = [p for p in _listdir(tmp) if p.startswith(rest)]
if len(res) > 1 or not os.path.exists(path):
return res
if os.path.isdir... | Perform completion of filesystem path.
https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.