Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
341,000 | def patch(self, *args, **kwargs):
return self.session.patch(*args, **self.get_kwargs(**kwargs)) | Executes an HTTP PATCH.
:Parameters:
- `args`: Non-keyword arguments
- `kwargs`: Keyword arguments |
341,001 | async def send_message(
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
with async_timeout.timeout(self.timeout):
async with self.session.post(
self.endpoint, data=request, ssl=self.ssl
) as response:
response... | Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. |
341,002 | def get_output_every(dirname):
fnames = get_filenames(dirname)
i_s = np.array([_f_to_i(fname) for fname in fnames])
everys = list(set(np.diff(i_s)))
if len(everys) > 1:
raise TypeError(
.format(everys))
return everys[0] | Get how many iterations between outputs have been done in a directory
run.
If there are multiple values used in a run, raise an exception.
Parameters
----------
dirname: str
A path to a directory.
Returns
-------
output_every: int
The inferred number of iterations betw... |
341,003 | def ws010(self, value=None):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError(
.format(value))
self._ws010 = value | Corresponds to IDD Field `ws010`
Wind speed corresponding to 1.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `ws010`
Unit: m/s
if `value` is None it will not be checked against the
specification and is a... |
341,004 | def delete(self):
modification = table_admin_v2_pb2.ModifyColumnFamiliesRequest.Modification(
id=self.column_family_id, drop=True
)
client = self._table._instance._client
client.table_admin_client.modify_column_families(
self._table.nam... | Delete this column family.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_delete_column_family]
:end-before: [END bigtable_delete_column_family] |
341,005 | def show(
self,
at=None,
shape=(1, 1),
N=None,
pos=(0, 0),
size="auto",
screensize="auto",
title="",
bg="blackboard",
bg2=None,
axes=4,
infinity=False,
verbose=True,
interactive=None,
offscreen=False,... | Create on the fly an instance of class ``Plotter`` or use the last existing one to
show one single object.
Allowed input objects are: ``Actor`` or ``Volume``.
This is meant as a shortcut. If more than one object needs to be visualised
please use the syntax `show([actor1, actor2,...], o... |
341,006 | def create_block(mc, block_id, subtype=None):
ptx, pty, ptz = mc.player.getTilePos()
px, py, pz = mc.player.getPos()
if subtype is None:
mc.setBlock(ptx, pty, ptz, block_id)
else:
mc.setBlock(ptx, pty, ptz, block_id, subtype)
mc.player.setPos(px, py+1, pz) | Build a block with the specified id and subtype under the player in the
Minecraft world. Subtype is optional and can be specified as None to use
the default subtype for the block. |
341,007 | def F_t(X, Y, S, M_E, E, m0, rho):
r = X.shape[1]
out1 = (((np.dot(np.dot(X, S), Y.T) - M_E) * E)**2).sum() / 2
out2 = rho * G(Y, m0, r)
out3 = rho * G(X, m0, r)
return out1 + out2 + out3 | Compute the distortion |
341,008 | def santalucia98_corrections(seq, pars_error):
98 method (unified parameters).
:param seq: sequence for which to calculate corrections.
:type seq: str
:param pars_error: dictionary of error corrections
:type pars_error: dict
:returns: Corrected delta_H and delta_S parameters
:rtype: list of... | Sum corrections for SantaLucia '98 method (unified parameters).
:param seq: sequence for which to calculate corrections.
:type seq: str
:param pars_error: dictionary of error corrections
:type pars_error: dict
:returns: Corrected delta_H and delta_S parameters
:rtype: list of floats |
341,009 | def include(self, target):
if self._clean.isDict():
return self._wrap(target in self.obj.values())
else:
return self._wrap(target in self.obj) | Determine if a given value is included in the
array or object using `is`. |
341,010 | def initializeProfile(self):
LOGGER.debug("> Building profile.".format(self.__file))
sections_file_parser = SectionsFileParser(self.__file)
sections_file_parser.parse()
if sections_file_parser.sections:
fileStructureParsingError = lambda attribute: foundations.ex... | Initializes the Component Profile.
:return: Method success.
:rtype: bool |
341,011 | def render_response(self, sort=True):
rendered = [cookie.render_response() for cookie in self.values()]
return rendered if not sort else sorted(rendered) | Render the dict's Cookie objects into list of strings formatted for
HTTP response headers (detailed 'Set-Cookie: ' style). |
341,012 | def get_avatar(self):
if not bool(self._my_map[]):
raise errors.IllegalState()
mgr = self._get_provider_manager()
if not mgr.supports_asset_lookup():
raise errors.OperationFailed()
lookup_session = mgr.get_asset_lookup_session(proxy=getattr(self,... | Gets the asset.
return: (osid.repository.Asset) - the asset
raise: IllegalState - ``has_avatar()`` is ``false``
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.* |
341,013 | def method_cache(by=,method=):
def decorate_(func):
def decorate(*args, **kwargs):
model = args[0]
assert hasattr(model,method), "Model must have a method."%method
if func.__name__ == method:
method_args = kwargs
else:
... | A decorator used on any model method which calls the model's 'method'
method if that latter method has not been called using the current
arguments or simply sets model attributes to match the run results if
it has. |
341,014 | def open(self):
if self.device is not None and self.device.is_open:
self.close()
self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate,
bytesize=self.bytesize, parity=self.parity,
stopbits=self.s... | Setup serial port and set is as escpos device |
341,015 | def _parse_control_fields(self, fields, tag_id="tag"):
for field in fields:
params = field.params
if tag_id not in params:
continue
self.controlfields[params[tag_id]] = field.getContent().strip() | Parse control fields.
Args:
fields (list): list of HTMLElements
tag_id (str): parameter name, which holds the information, about
field name this is normally "tag", but in case of
oai_marc "id". |
341,016 | def dangling(self, targets: sos_targets):
existing = []
missing = []
if env.config[]:
for x in self._all_depends_files.keys():
if x not in self._all_output_files:
if x.target_exists():
existing.append(x)
... | returns
1. missing targets, which are missing from the DAG or from the provided targets
2. existing targets of provided target list, not in DAG |
341,017 | def star_alignment_chart (self):
keys = OrderedDict()
keys[] = { : , : }
keys[] = { : , : }
keys[] = { : , : }
keys[] = { : , : }
keys[] = { : , : }
keys[] = { : , : }
pconfig = {
: ,
... | Make the plot showing alignment rates |
341,018 | def get_asset_from_new_extension_draft(self, publisher_name, draft_id, asset_type, **kwargs):
route_values = {}
if publisher_name is not None:
route_values[] = self._serialize.url(, publisher_name, )
if draft_id is not None:
route_values[] = self._serialize.url(,... | GetAssetFromNewExtensionDraft.
[Preview API]
:param str publisher_name:
:param str draft_id:
:param str asset_type:
:rtype: object |
341,019 | def lchmod(self, mode):
if self._closed:
self._raise_closed()
self._accessor.lchmod(self, mode) | Like chmod(), except if the path points to a symlink, the symlink's
permissions are changed, rather than its target's. |
341,020 | def edit(community):
form = EditCommunityForm(formdata=request.values, obj=community)
deleteform = DeleteCommunityForm()
ctx = mycommunities_ctx()
ctx.update({
: form,
: False,
: community,
: deleteform,
})
if form.validate_on_submit():
for field, va... | Create or edit a community. |
341,021 | def validate_INCREASING(in_value, restriction):
flat_list = _flatten_value(in_value)
previous = None
for a in flat_list:
if previous is None:
previous = a
continue
try:
if a < previous:
raise ValidationError("INCREASING")
exc... | Test to ensure the values in a list are increasing.
Parameters: a list of values and None. The none is there simply
to conform with the rest of the validation routines. |
341,022 | def reinitialize_command(self, command, reinit_subcommands):
cmd_obj = _DISTUTILS_REINIT(self, command, reinit_subcommands)
options = self.command_options.get(command)
if options:
self._set_command_options(cmd_obj, options)
return cmd_obj | Monkeypatch distutils.Distribution.reinitialize_command() to match behavior
of Distribution.get_command_obj()
This fixes a problem where 'pip install -e' does not reinitialise options
using the setup(options={...}) variable for the build_ext command.
This also effects other option sourcs such as setup.c... |
341,023 | def _sort_labels(label_data):
labels = list(label_data)
labels.sort(key=label_data.get, reverse=True)
return labels | Returns the labels in `label_data` sorted in descending order
according to the 'size' (total token count) of their referent
corpora.
:param label_data: labels (with their token counts) to sort
:type: `dict`
:rtype: `list` |
341,024 | def _compute_shallow_site_response(self, C, sites, pga1100):
stiff_factor = C[] + (C[] * C[])
fsite = stiff_factor * np.log(sites.vs30 / C[])
idx = sites.vs30 < C[]
if np.any(idx):
pga_scale = np.log(pga1100[idx] +
(C[... | Returns the shallow site response term (equation 11, page 146) |
341,025 | def on_disconnect(self):
"Called when the socket disconnects"
self._sock = None
if self._buffer is not None:
self._buffer.close()
self._buffer = None
self.encoder = None | Called when the socket disconnects |
341,026 | def _update_persistent_boot(self, device_type=[], persistent=False):
tenure =
new_device = device_type[0]
if device_type[0].upper() in DEVICE_COMMON_TO_RIS:
new_device = DEVICE_COMMON_TO_RIS[device_type[0].upper()]
if persistent:
tenure =
... | Changes the persistent boot device order in BIOS boot mode for host
Note: It uses first boot device from the device_type and ignores rest.
:param device_type: ordered list of boot devices
:param persistent: Boolean flag to indicate if the device to be set as
a persis... |
341,027 | def parse_name_altree(record):
name_tuple = split_name(record.value)
if name_tuple[1] == :
name_tuple = (name_tuple[0], , name_tuple[2])
maiden = record.sub_tag_value("SURN")
if maiden:
ending = + maiden +
surname = name_tuple[1]
if surname.endswith(ending... | Parse NAME structure assuming ALTREE dialect.
In ALTREE dialect maiden name (if present) is saved as SURN sub-record
and is also appended to family name in parens. Given name is saved in
GIVN sub-record. Few examples:
No maiden name:
1 NAME John /Smith/
2 GIVN John
With maiden na... |
341,028 | def _extents(self):
def start_and_size(idx, other_idx):
return min(idx, other_idx), abs(idx - other_idx) + 1
tc, other_tc = self._tc, self._other_tc
left, width = start_and_size(tc.col_idx, other_tc.col_idx)
top, height = start_and_size(tc.row_idx, oth... | A (left, top, width, height) tuple describing range extents.
Note this is normalized to accommodate the various orderings of the
corner cells provided on construction, which may be in any of four
configurations such as (top-left, bottom-right),
(bottom-left, top-right), etc. |
341,029 | def prepare(self, context):
if __debug__:
log.debug("Preparing request context.", extra=dict(request=id(context)))
if context.request.remainder and not context.request.remainder[0]:
del context.request.remainder[0]
context.path = Bread() | Add the usual suspects to the context.
This adds `request`, `response`, and `path` to the `RequestContext` instance. |
341,030 | def _validate_empty(self, empty, field, value):
if isinstance(value, Iterable) and len(value) == 0:
self._drop_remaining_rules(
, , , , ,
, )
if not empty:
self._error(field, errors.EMPTY_NOT_ALLOWED) | {'type': 'boolean'} |
341,031 | def assert_is(first, second, msg_fmt="{msg}"):
if first is not second:
msg = "{!r} is not {!r}".format(first, second)
fail(msg_fmt.format(msg=msg, first=first, second=second)) | Fail if first and second do not refer to the same object.
>>> list1 = [5, "foo"]
>>> list2 = [5, "foo"]
>>> assert_is(list1, list1)
>>> assert_is(list1, list2)
Traceback (most recent call last):
...
AssertionError: [5, 'foo'] is not [5, 'foo']
The following msg_fmt arguments are su... |
341,032 | def trimmed(self, pred=trimmed_pred_default):
new_children = []
for child in self.children:
if isinstance(child, ParseNode):
new_child = child.trimmed(pred)
else:
new_child = child
if not pred(new_child, self):
new_children.append(new_child)
return ParseNode... | Trim a ParseTree.
A node is trimmed if pred(node) returns True. |
341,033 | def strip_credentials(message):
message = copy.deepcopy(message)
for field in [, ]:
if field in message:
del message[field]
return message | Strip credentials from a message dict.
A new dict is returned without either `signature` or `certificate` keys.
This method can be called safely; the original dict is not modified.
This function is applicable using either using the x509 or gpg backends. |
341,034 | def get(self, want_leading = False, want_comment = False):
if not self.ungotten_token is None:
token = self.ungotten_token
self.ungotten_token = None
if token.is_whitespace():
if want_leading:
return token
elif token.i... | Get the next token.
@param want_leading: If True, return a WHITESPACE token if the
first character read is whitespace. The default is False.
@type want_leading: bool
@param want_comment: If True, return a COMMENT token if the
first token read is a comment. The default is False... |
341,035 | def _shadow_contents_from_chunks(contents, chunks, block_out_regexes=None):
shadow_contents = [list(l) for l in contents]
for chunk in chunks:
char_offset = chunk.column
line_offset = 0
for index, line in enumerate(chunk.data):
for character_in_line in rang... | Remove all contents in spellcheckable :chunks: from contents. |
341,036 | def stack(files, version="4.10", sync=True, **kwargs):
if not files:
raise MdfException("No files given for stack")
version = validate_version_argument(version)
callback = kwargs.get("callback", None)
stacked = MDF(version=version, callback=callback)
file... | stack several files and return the stacked *MDF* object
Parameters
----------
files : list | tuple
list of *MDF* file names or *MDF* instances
version : str
merged file version
sync : bool
sync the files based on the start of measurement, defa... |
341,037 | def get_ph_bs_symm_line_from_dict(bands_dict, has_nac=False, labels_dict=None):
structure = get_structure_from_dict(bands_dict)
qpts = []
frequencies = []
eigendisplacements = []
phonopy_labels_dict = {}
for p in bands_dict[]:
q = p[]
qpts.append(q)
bands = []
... | Creates a pymatgen PhononBandStructure object from the dictionary
extracted by the band.yaml file produced by phonopy. The labels
will be extracted from the dictionary, if present. If the 'eigenvector'
key is found the eigendisplacements will be calculated according to the
formula::
ex... |
341,038 | def batch_load_docs(db, doc_iterator, on_duplicate="replace"):
batch_size = 100
counter = 0
collections = {}
docs = {}
if on_duplicate not in ["error", "update", "replace", "ignore"]:
log.error(f"Bad parameter for on_duplicate: {on_duplicate}")
return
for (collection_nam... | Batch load documents
Args:
db: ArangoDB client database handle
doc_iterator: function that yields (collection_name, doc_key, doc)
on_duplicate: defaults to replace, but can be error, update, replace or ignore
https://python-driver-for-arangodb.readthedocs.io/en/master/specs.html?h... |
341,039 | def call(self, inputs):
image_shape = tf.shape(input=inputs)[-3:]
collapsed_shape = tf.concat(([-1], image_shape), axis=0)
out = tf.reshape(inputs, collapsed_shape)
out = self.conv1(out)
out = self.conv2(out)
out = self.conv3(out)
out = self.conv4(out)
expanded_shape = tf.concat((... | Runs the model to generate an intermediate representation of x_t.
Args:
inputs: A batch of image sequences `x_{1:T}` of shape
`[sample_shape, batch_size, timesteps, height, width,
channels]`.
Returns:
A batch of intermediate representations of shape [sample_shape,
batch_size,... |
341,040 | def slice(self, window_size=1, step_size=1, cumulative=False,
count_only=False, subcorpus=True, feature_name=None):
if not in self.indices:
self.index()
start = min(self.indices[].keys())
end = max(self.indices[].keys())
while start <= end - (window... | Returns a generator that yields ``(key, subcorpus)`` tuples for
sequential time windows.
Two common slicing patterns are the "sliding time-window" and the
"time-period" patterns. Whereas time-period slicing divides the corpus
into subcorpora by sequential non-overlapping time periods, s... |
341,041 | def _calculateParameters(self, fout):
q_d_f = 0
for self.q_counter in range(128):
self.q_total = self.q_counter + 2
if (self.fref / self.q_total) < 0.25:
break
for self.div in range(2, 128):
q_d_f = self.q_total * self.div *... | fout = fref * (p_total / q_total) * (1 / div)
p_total = 2 * ((p_counter + 4) + p_0) [16..1023]
q_total = q_counter + 2 [2..129]
div = [2,(3),4..127]
constraints:
f_ref * p_total / q_total = [100..400] MHz
f_ref / q_total > 0.25 MHz |
341,042 | def _prepare(self, query):
self._logger.info(u.format(query))
| Send the query to be prepared to the server. The server will parse the
query and return some metadata. |
341,043 | def eat_length(self, length):
pos = self.pos
if self.eos or pos + length > self.length:
return None
col = self.col
row = self.row
for char in self.string[pos:pos + length]:
col += 1
pos += 1
if char == :
... | Move current position forward by length and sets eos if needed. |
341,044 | def cast_out(self, klass):
if _debug: SequenceOfAny._debug("cast_out %r", klass)
if not issubclass(klass, List):
raise DecodingError("%r is not a list" % (klass,))
helper = klass()
t = TagList(self.tagList[:])
helper.de... | Interpret the content as a particular class. |
341,045 | def remove(self, source: Source) -> None:
self.unload(source)
if isinstance(source, RemoteSource):
shutil.rmtree(source.location, ignore_errors=True)
self.save() | Unregisters a given source with this server. If the given source is a
remote source, then its local copy will be removed from disk.
Raises:
KeyError: if the given source is not registered with this server. |
341,046 | def sys_get_char_size() -> Tuple[int, int]:
w = ffi.new("int *")
h = ffi.new("int *")
lib.TCOD_sys_get_char_size(w, h)
return w[0], h[0] | Return the current fonts character size as (width, height)
Returns:
Tuple[int,int]: The current font glyph size in (width, height) |
341,047 | def close(self):
_LIB.Close(self._env)
self._env = None
if self.viewer is not None:
self.viewer.close() | Close the environment. |
341,048 | def build_exception_map(cls, tokens):
exception_ranges = defaultdict(list)
for token in tokens:
token_type, _, token_start, token_end = token[0:4]
if token_type in (tokenize.COMMENT, tokenize.STRING):
if token_start[0] == token_end[0]:
exception_ranges[token_start[0]].append((... | Generates a set of ranges where we accept trailing slashes, specifically within comments
and strings. |
341,049 | def backwards(self, orm):
"Write your backwards methods here."
orm[].objects.filter(name=)\
.update(queryable=True) | Write your backwards methods here. |
341,050 | def url_concat(url, args, keep_existing=True):
if not args:
return url
if keep_existing:
if url[-1] not in (, ):
url += if ( in url) else
return url + urlencode(args, 1)
else:
url, seq, query = url.partition()
query = urlparse.parse_qs(query, True)... | Concatenate url and argument dictionary
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
:arg string url: URL being concat to.
:arg dict args: Args being concat.
:arg bool keep_existing: (Optional) Whether to keep the args which are
... |
341,051 | def label(self, nid, id_if_null=False):
g = self.get_graph()
if nid in g:
n = g.node[nid]
if in n:
return n[]
else:
if id_if_null:
return nid
else:
return None
el... | Fetches label for a node
Arguments
---------
nid : str
Node identifier for entity to be queried
id_if_null : bool
If True and node has no label return id as label
Return
------
str |
341,052 | def set_model_internal_data(model, original_data, modified_data, deleted_data):
model.__original_data__ = original_data
list(map(model._prepare_child, model.__original_data__))
model.__modified_data__ = modified_data
list(map(model._prepare_child, model.__modified_data__))
model.__deleted_fie... | Set internal data to model. |
341,053 | def listdir(self, location, authority_name=None):
authority_name, location = self._normalize_archive_name(
location,
authority_name=authority_name)
if authority_name is None:
authority_name = self.default_authority_name
return self._authorities[aut... | List archive path components at a given location
.. Note ::
When using listdir on versioned archives, listdir will provide the
version numbers when a full archive path is supplied as the
location argument. This is because DataFS stores the archive path
as a dire... |
341,054 | def parse_logout_request(self, xmlstr, binding=BINDING_SOAP):
return self._parse_request(xmlstr, saml_request.LogoutRequest,
"single_logout_service", binding) | Deal with a LogoutRequest
:param xmlstr: The response as a xml string
:param binding: What type of binding this message came through.
:return: None if the reply doesn't contain a valid SAML LogoutResponse,
otherwise the reponse if the logout was successful and None if it
... |
341,055 | def reply(self):
sock = self.__sock(zmq.REP)
return self.__send_function(sock), self.__recv_generator(sock) | Returns a callable and an iterable respectively. Those can be used to
both transmit a message and/or iterate over incoming messages,
that were requested by a request socket. Note that the iterable returns
as many parts as sent by requesters. Also, the sender function has a
``print`` like... |
341,056 | def scheduleTask(self, *args, **kwargs):
return self._makeApiCall(self.funcinfo["scheduleTask"], *args, **kwargs) | Schedule Defined Task
scheduleTask will schedule a task to be executed, even if it has
unresolved dependencies. A task would otherwise only be scheduled if
its dependencies were resolved.
This is useful if you have defined a task that depends on itself or on
some other task tha... |
341,057 | def authorize_password(self, client_id, username, password):
self.auth_data = {
"grant_type": "password",
"username": username,
"password": password,
"client_id": client_id,
"scope": ["regular_user"]
}
self._do_authorize() | Authorize to platform as regular user
You must provide a valid client_id (same as web application),
your password and your username. Username and password is not stored in
client but refresh token is stored. The only valid scope for this
authorization is "regular_user".
:param ... |
341,058 | def thread(self):
if not self._thread_calculated:
self._thread_calculated = True
split_tokens = self.split_tokens
if not self.datetime_nextpos:
return None
if len(split_tokens) <= self.datetime_nextpos:
return None
... | Extract thread name if available (lazy). |
341,059 | def extensions(self):
_tmp_extensions = self.mimes.encodings_map.keys() + \
self.mimes.suffix_map.keys() + \
self.mimes.types_map[1].keys() + \
cfg[]
extensions = []
for ext in _tmp_extensions:
if ext.startswith():
extensio... | Generate the regular expression to match all the known extensions.
@return: the regular expression.
@rtype: regular expression object |
341,060 | def demo(host, port):
loop = asyncio.get_event_loop()
stl = AsyncSatel(host,
port,
loop,
[1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 25, 26, 27, 28, 29, 30],
[8, 9, 1... | Basic demo of the monitoring capabilities. |
341,061 | async def load_tracks(self, query) -> LoadResult:
self.__check_node_ready()
url = self._uri + quote(str(query))
data = await self._get(url)
if isinstance(data, dict):
return LoadResult(data)
elif isinstance(data, list):
modified_data = {
... | Executes a loadtracks request. Only works on Lavalink V3.
Parameters
----------
query : str
Returns
-------
LoadResult |
341,062 | def check_sizes(size, width, height):
if not size:
return width, height
if len(size) != 2:
raise ValueError(
"size argument should be a pair (width, height)")
if width is not None and width != size[0]:
raise ValueError(
"size[0] (%r) and width (%r) should ma... | Check that these arguments, in supplied, are consistent.
Return a (width, height) pair. |
341,063 | def set(self, index, value):
nodes = parse_anything(value).nodes
if len(nodes) > 1:
raise ValueError("Cannot coerce multiple nodes into one index")
if index >= len(self.nodes) or -1 * index > len(self.nodes):
raise IndexError("List assignment index out of range")... | Set the ``Node`` at *index* to *value*.
Raises :exc:`IndexError` if *index* is out of range, or
:exc:`ValueError` if *value* cannot be coerced into one :class:`.Node`.
To insert multiple nodes at an index, use :meth:`get` with either
:meth:`remove` and :meth:`insert` or :meth:`replace`. |
341,064 | def save(self, commit=True):
db.session.add(self)
if commit:
db.session.commit()
return self | Save model to database |
341,065 | def save(self, record_key, record_data, overwrite=True, secret_key=):
labunittests1473719695.2165067.json
title = % self.__class__.__name__
input_fields = {
: record_key,
: secret_key
}
for key, value in input_fields.items():... | a method to create a record in the collection folder
:param record_key: string with name to assign to record (see NOTES below)
:param record_data: byte data for record body
:param overwrite: [optional] boolean to overwrite records with same name
:param secret_key: [optional] string... |
341,066 | def set_access_control_entries(self, container, security_namespace_id):
route_values = {}
if security_namespace_id is not None:
route_values[] = self._serialize.url(, security_namespace_id, )
content = self._serialize.body(container, )
response = self._send(http_meth... | SetAccessControlEntries.
Add or update ACEs in the ACL for the provided token. The request body contains the target token, a list of [ACEs](https://docs.microsoft.com/en-us/rest/api/azure/devops/security/access%20control%20entries/set%20access%20control%20entries?#accesscontrolentry) and a optional merge parame... |
341,067 | def update(self, containers):
self._containers = deepcopy(containers)
self.__write(containers, initialize=False) | Update the current state file with the specified contents |
341,068 | def _send_rtm_message(self, channel_id, text):
message = {
: self._current_message_id,
: ,
: channel_id,
: text,
}
self.ws.send(json.dumps(message))
self._current_message_id += 1 | Send a Slack message to a channel over RTM.
:param channel_id: a slack channel id.
:param text: a slack message. Serverside formatting is done
in a similar way to normal user message; see
`Slack's docs <https://api.slack.com/docs/formatting>`__. |
341,069 | def _check_model(obj, models=None):
return isinstance(obj, type) and issubclass(obj, pw.Model) and hasattr(obj, ) | Checks object if it's a peewee model and unique. |
341,070 | def do_request(self, http_verb, url, headers, data=None):
if data:
data = json.dumps(data)
request = urllib.request.Request(url, data, headers)
request.get_method = lambda: http_verb
try:
response = urllib.request.urlopen(request)
except urllib.e... | :see :func:`~HttpRequest.do_request` |
341,071 | def _process_panel_configuration(self, config):
try:
dashboard = config.get()
if not dashboard:
LOG.warning("Skipping %s because it doesnPANELPANEL_GROUPDEFAULT_PANELREMOVE_PANELADD_PANELADD_PANELmoduleexccan_registercan_registerpanelCould not process panel %(pan... | Add, remove and set default panels on the dashboard. |
341,072 | def compute_path(self, start_x, start_y, dest_x, dest_y,
diagonal_cost=_math.sqrt(2)):
return tcod.path.AStar(self, diagonal_cost).get_path(start_x, start_y,
dest_x, dest_y) | Get the shortest path between two points.
Args:
start_x (int): Starting x-position.
start_y (int): Starting y-position.
dest_x (int): Destination x-position.
dest_y (int): Destination y-position.
diagonal_cost (float): Multiplier for diagonal movement... |
341,073 | def insert(self, packet, time=None, **kwargs):
fields = {}
pd = packet._defn
for defn in pd.fields:
val = getattr(packet.raw, defn.name)
if pd.history and defn.name in pd.history:
val = getattr(packet.history, defn.name)
... | Insert a packet into the database
Arguments
packet
The :class:`ait.core.tlm.Packet` instance to insert into
the database
time
Optional parameter specifying the time value to use when inserting
the record into the database.... |
341,074 | def load_accelerators(self):
def getk(x):
return self.guake.settings.keybindingsLocal.get_string(x)
key, mask = Gtk.accelerator_parse(getk())
if key > 0:
self.accel_group.connect(
key, mask, Gtk.AccelFlags.VISIBLE, self.guake.accel_reset_termin... | Reads all gconf paths under /apps/guake/keybindings/local
and adds to the main accel_group. |
341,075 | async def throttle(self, key, *, rate=None, user=None, chat=None, no_error=None) -> bool:
if not self.storage.has_bucket():
raise RuntimeError()
if no_error is None:
no_error = self.no_throttle_error
if rate is None:
rate = self.throttling_rate_limit... | Execute throttling manager.
Returns True if limit has not exceeded otherwise raises ThrottleError or returns False
:param key: key in storage
:param rate: limit (by default is equal to default rate limit)
:param user: user id
:param chat: chat id
:param no_error: return ... |
341,076 | def validate_token(cls, token, expected_data):
data = SecretLinkFactory.validate_token(
token, expected_data=expected_data
)
if data:
link = cls.query.get(data[])
if link and link.is_valid():
return True
return False | Validate a secret link token.
Only queries the database if token is valid to determine that the token
has not been revoked. |
341,077 | def _get_url(self, filename):
return self.cdn_url.format(self.mver, self.relnum, filename) | Returns url for cdn.urbanterror.info to pass to _not_wget().
http://cdn.urbanterror.info/urt/<major_ver_without_.>/<release_num>-<magic_number>/q3ut4/<filename> |
341,078 | def _exclude_region(self, contig, start, end, fout):
sam_reader = pysam.Samfile(self.bam, "rb")
exclude_interval = pyfastaq.intervals.Interval(start, end - 1)
for read in sam_reader.fetch(contig):
read_interval = pyfastaq.intervals.Interval(read.pos, read.reference_end - 1)
... | Writes reads not mapping to the given region of contig, start and end as per python convention |
341,079 | def parse_args(argv):
parser = make_parser()
opts, args = parser.parse_args(argv[1:])
if not args and (sdk_version_key in os.environ):
args = (os.environ[sdk_version_key],)
return opts, args | Returns a tuple of (opts, args) for arguments. |
341,080 | def read_requirements_file(path):
last_pypi_url = None
with open(path) as f:
requires = []
pypi_urls = []
for line in f.readlines():
if not line:
continue
if in line:
match = re.match(r, line)
if match:
... | reads requirements.txt file and handles PyPI index URLs
:param path: (str) path to requirements.txt file
:return: (tuple of lists) |
341,081 | def main():
setup_main()
config = ConfigData(clean=True)
try:
config.register()
finally:
config.clean_after_if_needed() | register a function on pypi or gemfury
:return: |
341,082 | def _inject_lua_code(self, lua_code):
msg = (ctypes.c_ubyte * len(lua_code)).from_buffer_copy(lua_code.encode())
self.call_remote_api(, , msg) | Sends raw lua code and evaluate it wihtout any checking! |
341,083 | def flush(self, parser):
if self._verbose:
show = self._verbose if isinstance(self._verbose, str) else None
self.show(show)
parser.parse(self._filter(self.clear(), parser)) | Flush all current commands to the GLIR interpreter. |
341,084 | def data_dtype(self):
if not self.header:
return self._init_data_dtype
try:
mode = int(self.header[][])
except KeyError:
return self._init_data_dtype
else:
try:
return MRC_MODE_TO_NPY_DTYPE[mode]
except ... | Data type of the data block as determined from `header`.
If no header is available (i.e., before it has been initialized),
or the header entry ``'mode'`` is missing, the data type gained
from the ``dtype`` argument in the initializer is returned.
Otherwise, it is determined from ``mode`... |
341,085 | def update_particle(position_update, velocity_update, state, nbest_topology,
idx_particle):
(idx, particle) = idx_particle
nbest = state.swarm[nbest_topology[idx]].best_position
velocity = velocity_update(particle, nbest, state)
position = position_update(particle.position, ve... | Update function for a particle.
Calculates and updates the velocity and position of a particle for a
single iteration of the PSO algorithm. Social best particle is determined
by the state.params['topology'] function.
Args:
state: cipy.algorithms.pso.State: The state of the PSO algorithm.
... |
341,086 | def p_param_substitution_list(self, p):
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | param_substitution_list : param_substitution_list COMMA param_substitution |
341,087 | def add_navi_series_from_jsonp(self, data_src=None, data_name=, series_type="line", **kwargs):
if not self.jsonp_data_flag:
self.jsonp_data_flag = True
self.jsonp_data_url = json.dumps(data_src)
if data_name == :
data_name = + data_name... | set series for navigator option in highstocks |
341,088 | def map_masked_1d_array_to_2d_array_from_array_1d_shape_and_one_to_two(array_1d, shape, one_to_two):
array_2d = np.zeros(shape)
for index in range(len(one_to_two)):
array_2d[one_to_two[index, 0], one_to_two[index, 1]] = array_1d[index]
return array_2d | For a 1D array that was computed by mapping unmasked values from a 2D array of shape (rows, columns), map its \
values back to the original 2D array where masked values are set to zero.
This uses a 1D array 'one_to_two' where each index gives the 2D pixel indexes of the 1D array's unmasked pixels, \
for ex... |
341,089 | def take(self, indexer, axis=1, verify=True, convert=True):
self._consolidate_inplace()
indexer = (np.arange(indexer.start, indexer.stop, indexer.step,
dtype=)
if isinstance(indexer, slice)
else np.asanyarray(indexer, dtype=))
... | Take items along any axis. |
341,090 | def _add_comments(self, comments, original_string=""):
return comments and "{0}
"; ".join(comments)) or original_string | Returns a string with comments added |
341,091 | def get_credentials(cls, consumer_key, code):
headers = {
: ,
}
url =
payload = {
: consumer_key,
: code,
}
return cls._make_request(url, payload, headers)[0] | Fetches access token from using the request token and consumer key |
341,092 | def check_edit_tab(self, tab: str, md_type: str):
if not isinstance(tab, str):
raise TypeError(" expected a str value.")
else:
pass
if not isinstance(md_type, str):
raise TypeError(" expected a str value.")
else:
pass
... | Check if asked tab is part of Isogeo web form and reliable
with metadata type.
:param str tab: tab to check. Must be one one of EDIT_TABS attribute
:param str md_type: metadata type. Must be one one of FILTER_TYPES |
341,093 | def generate_upload_policy(self, conditions, expiration=None, client=None):
client = self._require_client(client)
credentials = client._base_connection.credentials
_signing.ensure_signed_credentials(credentials)
if expiration is None:
expiration = _NOW() + datetime.... | Create a signed upload policy for uploading objects.
This method generates and signs a policy document. You can use
`policy documents`_ to allow visitors to a website to upload files to
Google Cloud Storage without giving them direct write access.
For example:
.. literalinclud... |
341,094 | def _launch_forever_coro(coro, args, kwargs, loop):
thing = coro(*args, **kwargs)
if iscoroutine(thing):
loop.create_task(thing) | This helper function launches an async main function that was tagged with
forever=True. There are two possibilities:
- The function is a normal function, which handles initializing the event
loop, which is then run forever
- The function is a coroutine, which needs to be scheduled in the event
... |
341,095 | def get_object(self):
queryset = None
slug = self.kwargs.get(self.slug_url_kwarg, None)
if slug is not None:
queryset = self.get_queryset()
slug_field = self.slug_field
queryset = queryset.filter(**{slug_field: slug})
try:
... | If a single object has been requested, will set
`self.object` and return the object. |
341,096 | def check(self):
status = True
g = get_root(self).globals
if self.mag.ok():
self.mag.config(bg=g.COL[])
else:
self.mag.config(bg=g.COL[])
status = False
if self.airmass.ok():
self.airmass.config(bg=g.COL[])
else:
... | Checks values |
341,097 | def visit_CallTrue(self, node: parsing.CallTrue) -> ast.expr:
return ast.Lambda(
ast.arguments([], None, None, [], None, None, [], []),
ast.BoolOp(
ast.Or(),
[
self.visit_Call(node),
ast.Name(, ast.Load())])... | Generates python code calling the function and returning True.
lambda: fn(*args) or True |
341,098 | def mean(self):
if self.counter.value > 0:
return self.sum.value / self.counter.value
return 0.0 | Returns the mean value. |
341,099 | def combined_loss(new_params,
old_params,
policy_and_value_net_apply,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
gamma=0.99,
lambda_=0.95,
... | Computes the combined (clipped loss + value loss) given observations. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.