Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
377,900 | def cli_main():
import argparse
import os
def is_file_or_pipe(arg):
if not os.path.exists(arg) or os.path.isdir(arg):
parser.error(.format(arg))
else:
return arg
def is_dir(arg):
if not os.path.isdir(arg):
parser.error(.format(arg))
... | Render mustache templates using json files |
377,901 | def checkin_boardingpass(self, code, passenger_name, seat_class,
etkt_bnr, seat=, gate=, boarding_time=None,
is_cancel=False, qrcode_data=None, card_id=None):
data = {
: code,
: passenger_name,
: seat_class,
... | 飞机票接口 |
377,902 | def _import_bin(filename):
fid = open(filename, )
def fget(fid, fmt, tsize):
buffer = fid.read(tsize)
result_raw = struct.unpack(fmt, buffer)
if len(result_raw) == 1:
return result_raw[0]
else:
return result_raw
fid.seek(0, 2)
total_siz... | Read a .bin file generated by the IRIS Instruments Syscal Pro System
Parameters
----------
filename : string
Path to input filename
Returns
-------
metadata : dict
General information on the measurement
df : :py:class:`pandas.DataFrame`
dataframe containing all meas... |
377,903 | def refresh_db(root=None):
<database name>*
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__(root=root).refreshable.call(, )
for line in out.splitlines():
if not line:
continue
if line.strip().startswith() and \)[1].strip()
if in line:
... | Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db |
377,904 | def create_db_schema(cls, cur, schema_name):
create_schema_script = "CREATE SCHEMA {0} ;\n".format(schema_name)
cur.execute(create_schema_script) | Create Postgres schema script and execute it on cursor |
377,905 | def hello_user(api_client):
try:
response = api_client.get_user_profile()
except (ClientError, ServerError) as error:
fail_print(error)
return
else:
profile = response.json
first_name = profile.get()
last_name = profile.get()
email = profile.ge... | Use an authorized client to fetch and print profile information.
Parameters
api_client (UberRidesClient)
An UberRidesClient with OAuth 2.0 credentials. |
377,906 | def rc4_encrypt(key, data):
if len(key) < 5 or len(key) > 16:
raise ValueError(pretty_message(
,
len(key)
))
return _encrypt(Security.kSecAttrKeyTypeRC4, key, data, None, None) | Encrypts plaintext using RC4 with a 40-128 bit key
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
The plaintext - a byte string
:raises:
ValueError - when any of the parameters contain an invalid value
TypeError - when any of the parameters are... |
377,907 | def read_char(self, c: str) -> bool:
if self.read_eof():
return False
self._stream.save_context()
if c == self._stream.peek_char:
self._stream.incpos()
return self._stream.validate_context()
return self._stream.restore_context() | Consume the c head byte, increment current index and return True
else return False. It use peekchar and it's the same as '' in BNF. |
377,908 | def get_absolute(self, points):
is_list = isinstance(points, list)
points = ensure_numeric(points, num.float)
if len(points.shape) == 1:
msg =
if not len(points) == 2:
raise ValueError(msg)
msg =
msg += ... | Given a set of points geo referenced to this instance,
return the points as absolute values. |
377,909 | def FMErrorByNum( num ):
if not num in FMErrorNum.keys():
raise FMServerError, (num, FMErrorNum[-1])
elif num == 102:
raise FMFieldError, (num, FMErrorNum[num])
else:
raise FMServerError, (num, FMErrorNum[num]) | This function raises an error based on the specified error code. |
377,910 | async def send_media_group(self, chat_id: typing.Union[base.Integer, base.String],
media: typing.Union[types.MediaGroup, typing.List],
disable_notification: typing.Union[base.Boolean, None] = None,
reply_to_message_id: typing.U... | Use this method to send a group of photos or videos as an album.
Source: https://core.telegram.org/bots/api#sendmediagroup
:param chat_id: Unique identifier for the target chat or username of the target channel
:type chat_id: :obj:`typing.Union[base.Integer, base.String]`
:param media:... |
377,911 | def diff_config(jaide, second_host, mode):
try:
output = .join([diff for diff in
jaide.diff_config(second_host, mode.lower())])
except errors.SSHError:
output = color( %
(str(jaide.port), second_host), )
except errors.Authentic... | Perform a show | compare with some set commands.
@param jaide: The jaide connection to the device.
@type jaide: jaide.Jaide object
@param second_host: The device IP or hostname of the second host to
| compare with.
@type second_host: str
@param mode: How to compare the configu... |
377,912 | def rerun(client, revision, roots, siblings, inputs, paths):
graph = Graph(client)
outputs = graph.build(paths=paths, revision=revision)
outputs = siblings(graph, outputs)
output_paths = {node.path for node in outputs}
roots = {graph.normalize_path(root) for root in roots}
asser... | Recreate files generated by a sequence of ``run`` commands. |
377,913 | def load_keypair(keypair_file):
from Crypto.PublicKey import RSA
with open(keypair_file, ) as filey:
key = RSA.import_key(filey.read())
return quote_plus(key.publickey().exportKey().decode()) | load a keypair from a keypair file. We add attributes key (the raw key)
and public_key (the url prepared public key) to the client.
Parameters
==========
keypair_file: the pem file to load. |
377,914 | def delete_group(self, group_id):
route_values = {}
if group_id is not None:
route_values[] = self._serialize.url(, group_id, )
self._send(http_method=,
location_id=,
version=,
route_values=route_values) | DeleteGroup.
:param str group_id: |
377,915 | def content():
message = m.Message()
paragraph = m.Paragraph(
m.Image(
% resources_path()),
style_class=
)
message.add(paragraph)
body = tr(
shakemap\
)
message.add(body)
tips = m.BulletedList()
tips.add(tr... | Helper method that returns just the content.
This method was added so that the text could be reused in the
dock_help module.
.. versionadded:: 3.2.2
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message |
377,916 | def compare(self, origin, pattern):
if origin is None or pattern is None:
return False
return re.match(pattern, origin) is not None | Args:
origin (:obj:`str`): original string
pattern (:obj:`str`): Regexp pattern string
Returns:
bool: True if matches otherwise False. |
377,917 | def compute_pscale(self,cd11,cd21):
return N.sqrt(N.power(cd11,2)+N.power(cd21,2)) * 3600. | Compute the pixel scale based on active WCS values. |
377,918 | def _convert_to_folder(self, packages):
url =
with ThreadPoolExecutor(max_workers=12) as executor:
futures = []
for package in packages:
future = executor.submit(self._get, url, package)
futures.append({
: future,
... | Silverstripe's page contains a list of composer packages. This
function converts those to folder names. These may be different due
to installer-name.
Implemented exponential backoff in order to prevent packager from
being overly sensitive about the number of requests I w... |
377,919 | def to_unitary_matrix(
self,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable[ops.Qid] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128) -> np.ndarray:
... | Converts the circuit into a unitary matrix, if possible.
Args:
qubit_order: Determines how qubits are ordered when passing matrices
into np.kron.
qubits_that_should_be_present: Qubits that may or may not appear
in operations within the circuit, but that s... |
377,920 | def curve_to(self, x1, y1, x2, y2, x3, y3):
cairo.cairo_curve_to(self._pointer, x1, y1, x2, y2, x3, y3)
self._check_status() | Adds a cubic Bézier spline to the path
from the current point
to position ``(x3, y3)`` in user-space coordinates,
using ``(x1, y1)`` and ``(x2, y2)`` as the control points.
After this call the current point will be ``(x3, y3)``.
If there is no current point before the call to :m... |
377,921 | def _check_operator(self, operator):
if not isinstance(operator, type(None)):
tree = [obj.__name__ for obj in getmro(operator.__class__)]
if not any([parent in tree for parent in self._op_parents]):
warn(
.format(str(operator.__class__))) | Check Set-Up
This method checks algorithm operator against the expected parent
classes
Parameters
----------
operator : str
Algorithm operator to check |
377,922 | def _get_NTLMv2_response(user_name, password, domain_name,
server_challenge, client_challenge, timestamp,
target_info):
nt_hash = comphash._ntowfv2(user_name, password, domain_name)
temp = ComputeResponse._get_NTLMv2_temp(timestamp, cli... | [MS-NLMP] v28.0 2016-07-14
2.2.2.8 NTLM V2 Response: NTLMv2_RESPONSE
The NTLMv2_RESPONSE strucutre defines the NTLMv2 authentication
NtChallengeResponse in the AUTHENTICATE_MESSAGE. This response is used
only when NTLMv2 authentication is configured.
The guide on how this is co... |
377,923 | def smart_text(s, encoding=, strings_only=False, errors=):
if isinstance(s, Promise):
return s
return force_text(s, encoding, strings_only, errors) | Returns a text object representing 's' -- unicode on Python 2 and str on
Python 3. Treats bytestrings using the 'encoding' codec.
If strings_only is True, don't convert (some) non-string-like objects. |
377,924 | def transfer_multiple(self, destinations,
priority=prio.NORMAL, payment_id=None, unlock_time=0,
relay=True):
return self._backend.transfer(
destinations,
priority,
payment_id,
unlock_time,
account=self.index,
... | Sends a batch of transfers. Returns a list of resulting transactions.
:param destinations: a list of destination and amount pairs:
[(:class:`Address <monero.address.Address>`, `Decimal`), ...]
:param priority: transaction priority, implies fee. The priority can be a number
... |
377,925 | def OnShiftVideo(self, event):
length = self.player.get_length()
time = self.player.get_time()
if event.GetWheelRotation() < 0:
target_time = max(0, time-length/100.0)
elif event.GetWheelRotation() > 0:
target_time = min(length, time+length/100.0)
... | Shifts through the video |
377,926 | def tob32(val):
ret = bytearray(4)
ret[0] = (val>>24)&M8
ret[1] = (val>>16)&M8
ret[2] = (val>>8)&M8
ret[3] = val&M8
return ret | Return provided 32 bit value as a string of four bytes. |
377,927 | def map(self, fn, *iterables, timeout=None, chunksize=1, prefetch=None):
if timeout is not None: end_time = timeout + time.time()
if prefetch is None: prefetch = self._max_workers
if prefetch < 0: raise ValueError("prefetch count may not be negative")
argsiter = zip(*iterables)
... | Collects iterables lazily, rather than immediately.
Docstring same as parent: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor
Implmentation taken from this PR: https://github.com/python/cpython/pull/707 |
377,928 | def loadInstance(self):
if self._loaded:
return
self._loaded = True
module_path = self.modulePath()
package = projex.packageFromPath(module_path)
path = os.path.normpath(projex.packageRootPath(module_path))
if path in sys.path:
sys.path... | Loads the plugin from the proxy information that was created from the
registry file. |
377,929 | def read_excel_file(inputfile, sheet_name):
workbook = xlrd.open_workbook(inputfile)
output = []
found = False
for sheet in workbook.sheets():
if sheet.name == sheet_name:
found = True
for row in range(sheet.nrows):
values = []
for col... | Return a matrix containing all the information present in the
excel sheet of the specified excel document.
:arg inputfile: excel document to read
:arg sheetname: the name of the excel sheet to return |
377,930 | def _set_up_pool_config(self):
self._max_conns = self.settings_dict[].get(, pool_config_defaults[])
self._min_conns = self.settings_dict[].get(, self._max_conns)
self._test_on_borrow = self.settings_dict["OPTIONS"].get(,
poo... | Helper to configure pool options during DatabaseWrapper initialization. |
377,931 | def _as_symbol(value, is_symbol_value=True):
try:
return value.as_symbol()
except AttributeError:
assert isinstance(value, SymbolToken)
if not is_symbol_value:
try:
return value.regular_token()
except AttributeError:
pass... | Converts the input to a :class:`SymbolToken` suitable for being emitted as part of a :class:`IonEvent`.
If the input has an `as_symbol` method (e.g. :class:`CodePointArray`), it will be converted using that method.
Otherwise, it must already be a `SymbolToken`. In this case, there is nothing to do unless the i... |
377,932 | def i2c_slave_read(self):
data = array.array(, (0,) * self.BUFFER_SIZE)
status, addr, rx_len = api.py_aa_i2c_slave_read_ext(self.handle,
self.BUFFER_SIZE, data)
_raise_i2c_status_code_error_if_failure(status)
if addr == 0x80:
addr = 0x00
... | Read the bytes from an I2C slave reception.
The bytes are returned as a string object. |
377,933 | def _get_pdf_filenames_at(source_directory):
if not os.path.isdir(source_directory):
raise ValueError("%s is not a directory!" % source_directory)
return [os.path.join(source_directory, filename)
for filename in os.listdir(source_directory)
if filename.endswith(PDF_EXTENSION... | Find all PDF files in the specified directory.
Args:
source_directory (str): The source directory.
Returns:
list(str): Filepaths to all PDF files in the specified directory.
Raises:
ValueError |
377,934 | def parse_changes(json):
changes = []
dates = len(json)
for date in range(1, dates):
last_close = json[date - 1][]
now_close = json[date][]
changes.append(now_close - last_close)
logger.debug(.format(changes))
return changes | Gets price changes from JSON
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
Returns:
List of floats of price changes between entries in JSON. |
377,935 | def find_by_task(self, task, params={}, **options):
path = "/tasks/%s/attachments" % (task)
return self.client.get_collection(path, params, **options) | Returns the compact records for all attachments on the task.
Parameters
----------
task : {Id} Globally unique identifier for the task.
[params] : {Object} Parameters for the request |
377,936 | def getionimage(p, mz_value, tol=0.1, z=1, reduce_func=sum):
tol = abs(tol)
im = np.zeros((p.imzmldict["max count of pixels y"], p.imzmldict["max count of pixels x"]))
for i, (x, y, z_) in enumerate(p.coordinates):
if z_ == 0:
UserWarning("z coordinate = 0 present, if you're getting... | Get an image representation of the intensity distribution
of the ion with specified m/z value.
By default, the intensity values within the tolerance region are summed.
:param p:
the ImzMLParser (or anything else with similar attributes) for the desired dataset
:param mz_value:
m/z valu... |
377,937 | def dispatch(self, *args, **kwargs) -> Awaitable[bool]:
event = self.event_class(self.source(), cast(str, self.topic), *args, **kwargs)
return self.dispatch_raw(event) | Create and dispatch an event.
This method constructs an event object and then passes it to :meth:`dispatch_event` for
the actual dispatching.
:param args: positional arguments to the constructor of the associated event class
:param kwargs: keyword arguments to the constructor of the as... |
377,938 | def load(self, config, file_object, prefer=None):
return self.loads(config, file_object.read(), prefer=prefer) | An abstract method that loads from a given file object.
:param class config: The config class to load into
:param file file_object: The file object to load from
:param str prefer: The preferred serialization module name
:returns: A dictionary converted from the content of the given file... |
377,939 | def func_load(code, defaults=None, closure=None, globs=None):
if isinstance(code, (tuple, list)):
code, defaults, closure = code
code = marshal.loads(code.encode())
if globs is None:
globs = globals()
return python_types.FunctionType(code, globs,
... | Deserialize user defined function. |
377,940 | def get_context(self, template):
context = {}
for regex, context_generator in self.contexts:
if re.match(regex, template.name):
if inspect.isfunction(context_generator):
if _has_argument(context_generator):
context.update(c... | Get the context for a template.
If no matching value is found, an empty context is returned.
Otherwise, this returns either the matching value if the value is
dictionary-like or the dictionary returned by calling it with
*template* if the value is a function.
If several matchin... |
377,941 | async def get_target(config, url):
previous = config.cache.get(
, url, schema_version=SCHEMA_VERSION) if config.cache else None
headers = previous.caching if previous else None
request = await utils.retry_get(config, url, headers=headers)
if not request or not request.success:
re... | Given a URL, get the webmention endpoint |
377,942 | def call(self, method, args={}, retry=False, retry_policy=None,
ticket=None, **props):
ticket = ticket or uuid()
reply_q = self.get_reply_queue(ticket)
self.cast(method, args, declare=[reply_q], reply_to=ticket, **props)
return self.AsyncResult(ticket, self) | Send message to the same actor and return :class:`AsyncResult`. |
377,943 | def _sift_and_init_configs(self, input_dict):
configs = {}
for k, v in iteritems(input_dict):
if (k not in map(str.lower, self.format_order) and
any([f_order.lower() in k for f_order in self.format_order])):
try:
self.CFG.get(s... | Removes all key/v for keys that exist in the overall config and activates them.
Used to weed out config keys from tokens in a given input. |
377,944 | def chunk(seq: ActualIterable[T]) -> ActualIterable[ActualIterable[T]]:
seq = iter(seq)
try:
head = next(seq)
except StopIteration:
return iter(seq)
current_status = head
group = [head]
for each in seq:
status = each
if status != current_status:
... | >>> from Redy.Collections import Traversal, Flow
>>> x = [1, 1, 2]
>>> assert Flow(x)[Traversal.chunk][list].unbox == [[1, 1], [2]]
>>> assert Flow([])[Traversal.chunk][list].unbox == [] |
377,945 | def plotting_context(context=None, font_scale=1, rc=None):
if context is None:
context_dict = {k: mpl.rcParams[k] for k in _context_keys}
elif isinstance(context, dict):
context_dict = context
else:
contexts = ["paper", "notebook", "talk", "poster"]
if context not in ... | Return a parameter dict to scale elements of the figure.
This affects things like the size of the labels, lines, and other
elements of the plot, but not the overall style. The base context
is "notebook", and the other contexts are "paper", "talk", and "poster",
which are version of the notebook paramete... |
377,946 | def get_namespace_statistics(self, namespace, start_offset, end_offset):
cursor = self.cursor
cursor.execute(
,
(namespace, start_offset, end_offset))
return [long(count or 0) for count in cursor.fetchone()] | Get namespace statistics for the period between start_offset and
end_offset (inclusive) |
377,947 | def init_account(self):
ghuser = self.api.me()
hook_token = ProviderToken.create_personal(
,
self.user_id,
scopes=[],
is_internal=True,
)
self.account.extra_data = dict(
id=ghuser.id,
login... | Setup a new GitHub account. |
377,948 | def netspeed_by_name(self, hostname):
addr = self._gethostbyname(hostname)
return self.netspeed_by_addr(addr) | Returns NetSpeed name from hostname. Can be Unknown, Dial-up,
Cable, or Corporate.
:arg hostname: Hostname (e.g. example.com) |
377,949 | def from_array(array):
if array is None or not array:
return None
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.sendable.reply_markup import KeyboardButton
data = {}
data[] = KeyboardButton.from_array_list... | Deserialize a new ReplyKeyboardMarkup from a given dictionary.
:return: new ReplyKeyboardMarkup instance.
:rtype: ReplyKeyboardMarkup |
377,950 | def get_command(self, ctx, cmd_name):
cmd_name = self.MAP.get(cmd_name, cmd_name)
return super(AliasedGroup, self).get_command(ctx, cmd_name) | Map some aliases to their 'real' names. |
377,951 | def imagetransformer_sep_channels():
hparams = imagetransformer_base()
hparams.num_heads = 4
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 256
hparams.filter_size = 512
hparams.num_hidden_layers = 6
return hparams | separate rgb embeddings. |
377,952 | def _GenerateFleetspeakConfig(self, template_dir, rpm_build_dir):
source_config = os.path.join(
template_dir, "fleetspeak",
os.path.basename(
config.CONFIG.Get(
"ClientBuilder.fleetspeak_config_path", context=self.context)))
fleetspeak_service_dir = config.CONFIG... | Generates a Fleetspeak config for GRR. |
377,953 | def do_json_set_many(self, params):
if len(params.keys_values_types) % 3 != 0:
self.show_output()
return
for key, _, _ in grouper(params.keys_values_types, 3):
try:
Keys.validate(key)
except Keys.Bad as ex:
... | \x1b[1mNAME\x1b[0m
json_set_many - like `json_set`, but for multiple key/value pairs
\x1b[1mSYNOPSIS\x1b[0m
json_set_many <path> <keys> <value> <value_type> <keys1> <value1> <value_type1> ...
\x1b[1mDESCRIPTION\x1b[0m
If the key exists and the value is different, the znode will be updated with... |
377,954 | def main():
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file",
required=True,
help="input file",
type=str)
parser.add_argument("-l", "--locus",
required=True,
hel... | This is run if file is directly executed, but not if imported as
module. Having this in a separate function allows importing the file
into interactive python, and still able to execute the
function for testing |
377,955 | def version():
with open(os.path.join(, )) as input_file:
for line in input_file:
if line.startswith():
return ast.parse(line).body[0].value.s | Return version string. |
377,956 | def retract_project_bid(session, bid_id):
headers = {
:
}
bid_data = {
:
}
endpoint = .format(bid_id)
response = make_put_request(session, endpoint, headers=headers,
params_data=bid_data)
json_data = response.json()
if response.... | Retract a bid on a project |
377,957 | def custom_code(self, mask: str = ,
char: str = , digit: str = ) -> str:
char_code = ord(char)
digit_code = ord(digit)
code = bytearray(len(mask))
def random_int(a: int, b: int) -> int:
b = b - a
return int(self.random() * b) + a
... | Generate custom code using ascii uppercase and random integers.
:param mask: Mask of code.
:param char: Placeholder for characters.
:param digit: Placeholder for digits.
:return: Custom code. |
377,958 | def process(self, event):
logger.info(f"{self}: put {event.src_path}")
self.queue.put(os.path.basename(event.src_path)) | Put and process tasks in queue. |
377,959 | def retrieveJsonResponseFromServer(url):
jsonData = None
try:
data = urllib.urlopen(url)
jsonData = simplejson.load(data)
except Exception as ex:
raise Sitools2Exception(ex)
return jsonData | Retrieves a JSON response from the server.
Input parameters
----------------
url : url to call for retrieving the JSON response
Return
------
A dictionary
Exception
---------
SITools2Exception when a problem during the download or... |
377,960 | def read_tcp(self, length):
if length is None:
length = len(self)
_srcp = self._read_unpack(2)
_dstp = self._read_unpack(2)
_seqn = self._read_unpack(4)
_ackn = self._read_unpack(4)
_lenf = self._read_binary(1)
_flag = self._read_binary(1)
... | Read Transmission Control Protocol (TCP).
Structure of TCP header [RFC 793]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
... |
377,961 | def build_schema(self, fields):
content_field_name =
schema_fields = [
{: ID,
: ,
: ,
: 0},
{: DJANGO_ID,
: ,
: ,
: 1},
{: DJANGO_CT,
: ,
: ,
... | Build the schema from fields.
:param fields: A list of fields in the index
:returns: list of dictionaries
Each dictionary has the keys
field_name: The name of the field index
type: what type of value it is
'multi_valued': if it allows more than one value
'co... |
377,962 | def reflection_matrix_pow(reflection_matrix: np.ndarray, exponent: float):
squared_phase = np.dot(reflection_matrix[:, 0],
reflection_matrix[0, :])
phase = complex(np.sqrt(squared_phase))
i = np.eye(reflection_matrix.shape[0]) * phase
pos_part = (i + reflectio... | Raises a matrix with two opposing eigenvalues to a power.
Args:
reflection_matrix: The matrix to raise to a power.
exponent: The power to raise the matrix to.
Returns:
The given matrix raised to the given power. |
377,963 | def get_app(self, app_id, embed_tasks=False, embed_counts=False,
embed_deployments=False, embed_readiness=False,
embed_last_task_failure=False, embed_failures=False,
embed_task_stats=False):
params = {}
embed_params = {
: embed_tasks,
... | Get a single app.
:param str app_id: application ID
:param bool embed_tasks: embed tasks in result
:param bool embed_counts: embed all task counts
:param bool embed_deployments: embed all deployment identifier
:param bool embed_readiness: embed all readiness check results
... |
377,964 | def disassemble(co, lasti=-1):
out = StringIO()
code = co.co_code
labels = dis.findlabels(code)
linestarts = dict(dis.findlinestarts(co))
n = len(code)
i = 0
extended_arg = 0
free = None
while i < n:
c = code[i]
op = ord(c)
if i i... | Disassemble a code object. |
377,965 | def log_y_cb(self, w, val):
self.tab_plot.logy = val
self.plot_two_columns() | Toggle linear/log scale for Y-axis. |
377,966 | def changelist_view(self, request, extra_context=None):
if extra_context is None:
extra_context = {}
response = self.adv_filters_handle(request,
extra_context=extra_context)
if response:
return response
return su... | Add advanced_filters form to changelist context |
377,967 | def _encode(s, encoding=None, errors=None):
if encoding is None:
encoding = ENCODING
if errors is None:
errors = ENCODING_ERRORS
return s.encode(encoding, errors) if isinstance(s, unicode) else s | Encodes *s*. |
377,968 | def ExtractConfig(self):
logging.info("Extracting config file from .pkg.")
pkg_path = os.environ.get("PACKAGE_PATH", None)
if pkg_path is None:
logging.error("Could not locate package, giving up.")
return
zf = zipfile.ZipFile(pkg_path, mode="r")
fd = zf.open("config.yaml")
inst... | This installer extracts a config file from the .pkg file. |
377,969 | def get_params(self):
value = self._get_lookup(self.operator, self.value)
self.params.append(self.value)
return self.params | returns a list |
377,970 | def get_instance(self, payload):
return StreamMessageInstance(
self._version,
payload,
service_sid=self._solution[],
stream_sid=self._solution[],
) | Build an instance of StreamMessageInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance
:rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance |
377,971 | def update_webhook(self, webhook, name=None, metadata=None):
return self.manager.update_webhook(self.scaling_group, policy=self,
webhook=webhook, name=name, metadata=metadata) | Updates the specified webhook. One or more of the parameters may be
specified. |
377,972 | def create(self, name, targetUrl, resource, event,
filter=None, secret=None, **request_parameters):
check_type(name, basestring, may_be_none=False)
check_type(targetUrl, basestring, may_be_none=False)
check_type(resource, basestring, may_be_none=False)
check_type(... | Create a webhook.
Args:
name(basestring): A user-friendly name for this webhook.
targetUrl(basestring): The URL that receives POST requests for
each event.
resource(basestring): The resource type for the webhook.
event(basestring): The event type ... |
377,973 | def main():
FIG = {}
FIG[] = 1
dir_path =
plot, fmt = 0,
units = ,
XLP = []
norm = 1
LP = "LP-IRM"
if len(sys.argv) > 1:
if in sys.argv:
print(main.__doc__)
sys.exit()
data_model = int(pmag.get_named_arg("-DM", 3))
if in sy... | NAME
irmaq_magic.py
DESCRIPTION
plots IRM acquisition curves from measurements file
SYNTAX
irmaq_magic [command line options]
INPUT
takes magic formatted magic_measurements.txt files
OPTIONS
-h prints help message and quits
-f FILE: specify input file, d... |
377,974 | def fix_config(self, options):
options = super(Trigger, self).fix_config(options)
opt = "condition"
if opt not in options:
options[opt] = "True"
if opt not in self.help:
self.help[opt] = "The (optional) condition for teeing off the tokens; uses the meth... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict |
377,975 | def add_children(self, *children, **kwargs):
for child in children:
self.add_child(child, **kwargs) | Conveniience function: Adds objects as children in the scene graph. |
377,976 | def saveSettings(self, settings):
profile = self.saveProfile()
key = self.objectName()
settings.setValue( % key, wrapVariant(profile.toString()))
for viewType in self.viewTypes():
viewType.saveGlobalSettings(settings) | Records the current structure of the view widget to the inputed \
settings instance.
:param settings | <QSettings> |
377,977 | def get_requirements(lookup=None):
if lookup == None:
lookup = get_lookup()
install_requires = []
for module in lookup[]:
module_name = module[0]
module_meta = module[1]
if "exact_version" in module_meta:
dependency = "%s==%s" %(module_name,module_meta[])
... | get_requirements reads in requirements and versions from
the lookup obtained with get_lookup |
377,978 | def _set_exception(self):
assert not self.ready()
self._data = sys.exc_info()
self._success = False
self._event.set()
if self._collector is not None:
self._collector.notify_ready(self) | Called by a Job object to tell that an exception occured
during the processing of the function. The object will become
ready but not successful. The collector's notify_ready()
method will be called, but NOT the callback method |
377,979 | def load_sbml(filename):
import libsbml
document = libsbml.readSBML(filename)
document.validateSBML()
num_errors = (document.getNumErrors(libsbml.LIBSBML_SEV_ERROR)
+ document.getNumErrors(libsbml.LIBSBML_SEV_FATAL))
if num_errors > 0:
messages = "The generated docume... | Load a model from a SBML file.
Parameters
----------
filename : str
The input SBML filename.
Returns
-------
model : NetworkModel
y0 : dict
Initial condition.
volume : Real or Real3, optional
A size of the simulation volume. |
377,980 | def fdr(p, q=.05):
s = np.sort(p)
nvox = p.shape[0]
null = np.array(range(1, nvox + 1), dtype=) * q / nvox
below = np.where(s <= null)[0]
return s[max(below)] if len(below) else -1 | Determine FDR threshold given a p value array and desired false
discovery rate q. |
377,981 | def send(self, request, ordered=False):
if not self._user_connected:
raise ConnectionError()
if not utils.is_list_like(request):
state = RequestState(request, self._loop)
self._send_queue.append(state)
return state.future
else:
... | This method enqueues the given request to be sent. Its send
state will be saved until a response arrives, and a ``Future``
that will be resolved when the response arrives will be returned:
.. code-block:: python
async def method():
# Sending (enqueued for the send l... |
377,982 | def frequent_signups(self):
key = "{}:frequent_signups".format(self.username)
cached = cache.get(key)
if cached:
return cached
freq_signups = self.eighthsignup_set.exclude(scheduled_activity__activity__administrative=True).exclude(
scheduled_activity__act... | Return a QuerySet of activity id's and counts for the activities that a given user
has signed up for more than `settings.SIMILAR_THRESHOLD` times |
377,983 | def set_prompt(self, prompt_command="", position=0):
self.description_docs = u.format(prompt_command)
self.cli.current_buffer.reset(
initial_document=Document(
self.description_docs,
cursor_position=position))
self.cli.request_redraw() | writes the prompt line |
377,984 | def scan_in_memory(node, env, path=()):
try:
entries = node.entries
except AttributeError:
return []
entry_list = sorted(filter(do_not_scan, list(entries.keys())))
return [entries[n] for n in entry_list] | "Scans" a Node.FS.Dir for its in-memory entries. |
377,985 | def symmetrize_compact_force_constants(force_constants,
primitive,
level=1):
s2p_map = primitive.get_supercell_to_primitive_map()
p2s_map = primitive.get_primitive_to_supercell_map()
p2p_map = primitive.get_primitive_to_prim... | Symmetry force constants by translational and permutation symmetries
Parameters
----------
force_constants: ndarray
Compact force constants. Symmetrized force constants are overwritten.
dtype=double
shape=(n_patom,n_satom,3,3)
primitive: Primitive
Primitive cell
leve... |
377,986 | def marvcli_comment_list(datasets):
app = create_app()
ids = parse_setids(datasets, dbids=True)
comments = db.session.query(Comment)\
.options(db.joinedload(Comment.dataset))\
.filter(Comment.dataset_id.in_(ids))
for comment in sorted(comments, key=... | Lists comments for datasets.
Output: setid comment_id date time author message |
377,987 | def add_membership(self, subject_descriptor, container_descriptor):
route_values = {}
if subject_descriptor is not None:
route_values[] = self._serialize.url(, subject_descriptor, )
if container_descriptor is not None:
route_values[] = self._serialize.url(, conta... | AddMembership.
[Preview API] Create a new membership between a container and subject.
:param str subject_descriptor: A descriptor to a group or user that can be the child subject in the relationship.
:param str container_descriptor: A descriptor to a group that can be the container in the relati... |
377,988 | def fftconv(a, b, axes=(0, 1)):
if np.isrealobj(a) and np.isrealobj(b):
fft = rfftn
ifft = irfftn
else:
fft = fftn
ifft = ifftn
dims = np.maximum([a.shape[i] for i in axes], [b.shape[i] for i in axes])
af = fft(a, dims, axes)
bf = fft(b, dims, axes)
return i... | Compute a multi-dimensional convolution via the Discrete Fourier
Transform. Note that the output has a phase shift relative to the
output of :func:`scipy.ndimage.convolve` with the default ``origin``
parameter.
Parameters
----------
a : array_like
Input array
b : array_like
Inpu... |
377,989 | def mendelian_check(tp1, tp2, tpp, is_xlinked=False):
call_to_ints = lambda x: tuple(int(_) for _ in x.split("|") if _ != ".")
tp1_sex, tp1_call = tp1[:2]
tp2_sex, tp2_call = tp2[:2]
tpp_sex, tpp_call = tpp[:2]
tp1_call = call_to_ints(tp1_call)
tp2_call = call_to_ints(tp2_cal... | Compare TRED calls for Parent1, Parent2 and Proband. |
377,990 | def __set_components(self, requisite=True):
components = self.__components_manager.list_components()
candidate_components = \
getattr(set(components), "intersection" if requisite else "difference")(self.__requisite_components)
deactivated_components = self.__settings.get_ke... | Sets the Components.
:param requisite: Set only requisite Components.
:type requisite: bool |
377,991 | def from_lambda(cls, name, lambda_):
if PY2:
a = inspect.getargspec(lambda_)
varargs, varkw, defaults, kwonlyargs = (
a.varargs, a.keywords, a.defaults, None,
)
else:
a = inspect.getfullargspec(lambda_)
varargs, var... | Make a :class:`SassFunction` object from the given ``lambda_``
function. Since lambda functions don't have their name, it need
its ``name`` as well. Arguments are automatically inspected.
:param name: the function name
:type name: :class:`str`
:param lambda_: the actual lambda... |
377,992 | def version_binary(self):
try:
item_value, item_type = self.__reg_query_value(self.__reg_uninstall_handle, )
except pywintypes.error as exc:
if exc.winerror == winerror.ERROR_FILE_NOT_FOUND:
... | Return version number which is stored in binary format.
Returns:
str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found |
377,993 | def delete_migration(connection, basename):
sql = "DELETE FROM migrations_applied WHERE name = %s"
with connection.cursor() as cursor:
cursor.execute(sql, (basename,))
connection.commit()
return True | Delete a migration in `migrations_applied` table |
377,994 | def _structure_default(self, obj, cl):
if cl is Any or cl is Optional:
return obj
msg = (
"Unsupported type: {0}. Register a structure hook for "
"it.".format(cl)
)
raise ValueError(msg) | This is the fallthrough case. Everything is a subclass of `Any`.
A special condition here handles ``attrs`` classes.
Bare optionals end here too (optionals with arguments are unions.) We
treat bare optionals as Any. |
377,995 | def stop(self):
dd = time() - self._start
self.ms = int(round(1000 * dd)) | Stop the timer. |
377,996 | def get_(key, recurse=False, profile=None, **kwargs):
client = __utils__[](__opts__, profile, **kwargs)
if recurse:
return client.tree(key)
else:
return client.get(key, recurse=recurse) | .. versionadded:: 2014.7.0
Get a value from etcd, by direct path. Returns None on failure.
CLI Examples:
.. code-block:: bash
salt myminion etcd.get /path/to/key
salt myminion etcd.get /path/to/key profile=my_etcd_config
salt myminion etcd.get /path/to/key recurse=True profile=m... |
377,997 | def update_form_labels(self, request=None, obj=None, form=None):
for form_label in self.custom_form_labels:
if form_label.field in form.base_fields:
label = form_label.get_form_label(
request=request, obj=obj, model=self.model, form=form
)... | Returns a form obj after modifying form labels
referred to in custom_form_labels. |
377,998 | def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r
vectors, items = Reach._load(pathtovector,
wordlist,
num_t... | r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whe... |
377,999 | def set_actuator_control_target_encode(self, time_usec, group_mlx, target_system, target_component, controls):
return MAVLink_set_actuator_control_target_message(time_usec, group_mlx, target_system, target_component, controls) | Set the vehicle attitude and body angular rates.
time_usec : Timestamp (micros since boot or Unix epoch) (uint64_t)
group_mlx : Actuator group. The "_mlx" indicates this is a multi-instance message and a MAVLink parser should use this field to difference ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.