Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
373,100 | def destroy(self):
if self.widget:
self.set_active(False)
super(AndroidBarcodeView, self).destroy() | Cleanup the activty lifecycle listener |
373,101 | def create_context_plot(ra, dec, name="Your object"):
plot = K2FootprintPlot()
plot.plot_galactic()
plot.plot_ecliptic()
for c in range(0, 20):
plot.plot_campaign_outline(c, facecolor="
plot.ax.scatter(ra, dec, marker=, s=250, lw=3, color="red", zorder=500)
plot.ax.text(ra... | Creates a K2FootprintPlot showing a given position in context
with respect to the campaigns. |
373,102 | def perr(self, *args, **kwargs):
kwargs[] = self.err
self.print(*args, **kwargs)
sys.stderr.flush() | Console to STERR |
373,103 | def build_sanitiser_node_dict(
cfg,
sinks_in_file
):
sanitisers = list()
for sink in sinks_in_file:
sanitisers.extend(sink.sanitisers)
sanitisers_in_file = list()
for sanitiser in sanitisers:
for cfg_node in cfg.nodes:
if sanitiser in cfg_node.label:
... | Build a dict of string -> TriggerNode pairs, where the string
is the sanitiser and the TriggerNode is a TriggerNode of the sanitiser.
Args:
cfg(CFG): cfg to traverse.
sinks_in_file(list[TriggerNode]): list of TriggerNodes containing
the sinks in the ... |
373,104 | def rm_special(user, cmd, special=None, identifier=None):
*
lst = list_tab(user)
ret =
rm_ = None
for ind in range(len(lst[])):
if rm_ is not None:
break
if _cron_matched(lst[][ind], cmd, identifier=identifier):
if special is None:
... | Remove a special cron job for a specified user.
CLI Example:
.. code-block:: bash
salt '*' cron.rm_special root /usr/bin/foo |
373,105 | def send_to_default_exchange(self, sess_id, message=None):
msg = json.dumps(message, cls=ZEngineJSONEncoder)
log.debug("Sending following message to %s queue through default exchange:\n%s" % (
sess_id, msg))
self.get_channel().publish(exchange=, routing_key=sess_id, body=msg... | Send messages through RabbitMQ's default exchange,
which will be delivered through routing_key (sess_id).
This method only used for un-authenticated users, i.e. login process.
Args:
sess_id string: Session id
message dict: Message object. |
373,106 | def replace_drive_enclosure(self, information):
uri = "{}/replaceDriveEnclosure".format(self.data["uri"])
result = self._helper.create(information, uri)
self.refresh()
return result | When a drive enclosure has been physically replaced, initiate the replacement operation that enables the
new drive enclosure to take over as a replacement for the prior drive enclosure. The request requires
specification of both the serial numbers of the original drive enclosure and its replacement to b... |
373,107 | def get(issue_id, issue_type_id):
return db.Issue.find_one(
Issue.issue_id == issue_id,
Issue.issue_type_id == issue_type_id
) | Return issue by ID
Args:
issue_id (str): Unique Issue identifier
issue_type_id (str): Type of issue to get
Returns:
:obj:`Issue`: Returns Issue object if found, else None |
373,108 | def get_tan_media(self, media_type = TANMediaType2.ALL, media_class = TANMediaClass4.ALL):
with self._get_dialog() as dialog:
hktab = self._find_highest_supported_command(HKTAB4, HKTAB5)
seg = hktab(
tan_media_type = media_type,
tan_media_class ... | Get information about TAN lists/generators.
Returns tuple of fints.formals.TANUsageOption and a list of fints.formals.TANMedia4 or fints.formals.TANMedia5 objects. |
373,109 | def get_previous_tag(cls, el):
sibling = el.previous_sibling
while not cls.is_tag(sibling) and sibling is not None:
sibling = sibling.previous_sibling
return sibling | Get previous sibling tag. |
373,110 | def File(self, path):
return vfs.FileRef(
client_id=self.client_id, path=path, context=self._context) | Returns a reference to a file with a given path on client's VFS. |
373,111 | def num_compositions(m, n):
return scipy.special.comb(n+m-1, m-1, exact=True) | The total number of m-part compositions of n, which is equal to
(n+m-1) choose (m-1).
Parameters
----------
m : scalar(int)
Number of parts of composition.
n : scalar(int)
Integer to decompose.
Returns
-------
scalar(int)
Total number of m-part compositions of ... |
373,112 | def _get_win_argv():
assert is_win
argc = ctypes.c_int()
try:
argv = winapi.CommandLineToArgvW(
winapi.GetCommandLineW(), ctypes.byref(argc))
except WindowsError:
return []
if not argv:
return []
res = argv[max(0, argc.value - len(sys.argv)):argc.valu... | Returns a unicode argv under Windows and standard sys.argv otherwise
Returns:
List[`fsnative`] |
373,113 | def backup_file(*, file, host):
.format(key_path=key_path)) | Backup a file on S3
:param file: full path to the file to be backed up
:param host: this will be used to locate the file on S3
:raises TypeError: if an argument in kwargs does not have the type expected
:raises ValueError: if an argument within kwargs has an invalid value |
373,114 | def main():
parser = ArgumentParser()
subs = parser.add_subparsers(dest=)
setup_parser = subs.add_parser()
setup_parser.add_argument(, , dest=, required=True,
help=, type=str)
setup_parser.add_argument(, , dest=, required=True,
help=, ... | Run the core. |
373,115 | def getTemplates(fnames, blend=True):
if not blend:
newhdrs = blendheaders.getSingleTemplate(fnames[0])
newtab = None
else:
newhdrs, newtab = blendheaders.get_blended_headers(inputs=fnames)
cleanTemplates(newhdrs[1],newhdrs[2],newhdrs[3])
return newhdrs, newtab | Process all headers to produce a set of combined headers
that follows the rules defined by each instrument. |
373,116 | def make_lat_lons(cvects):
lats = np.degrees(np.arcsin(cvects[2]))
lons = np.degrees(np.arctan2(cvects[0], cvects[1]))
return np.hstack([lats, lons]) | Convert from directional cosines to latitidue and longitude
Parameters
----------
cvects : directional cosine (i.e., x,y,z component) values
returns (np.ndarray(2,nsrc)) with the directional cosine (i.e., x,y,z component) values |
373,117 | def import_sqlite(db_file, older_than=None, **kwargs):
conn = _open_sqlite(db_file)
cur = conn.cursor()
select = "SELECT * FROM testcases WHERE exported != "
if older_than:
cur.execute(" ".join((select, "AND sqltime < ?")), (older_than,))
else:
cur.execute(select)
colum... | Reads the content of the database file and returns imported data. |
373,118 | def _backspace(self):
if self.command == :
return
logger.log(5, "Snippet keystroke `Backspace`.")
self.command = self.command[:-1] | Erase the last character in the snippet command. |
373,119 | def triple(self):
with ffi.OutputString(owned=False) as outmsg:
ffi.lib.LLVMPY_GetTarget(self, outmsg)
return str(outmsg) | This module's target "triple" specification, as a string. |
373,120 | def binary_classification_metrics(y_true, y_pred, y_prob):
y_true = column_or_1d(y_true)
y_pred = column_or_1d(y_pred)
y_prob = column_or_1d(y_prob)
n_samples = y_true.shape[0]
tp = float((y_pred * y_true).sum())
fp = float((y_pred[np.nonzero(y_true == 0)[0]]).sum())
fn = float(... | classification_metrics.
This function cal...
Parameters
----------
y_true : array-like
Ground truth (correct) labels.
y_pred : array-like
Predicted labels, as returned by a classifier.
y_prob : array-like
Predicted probabilities, as returned by a classifier.
Retu... |
373,121 | def load_configs(self):
self._load_default_shell_settings()
value = self.settings.general.get_boolean()
self.get_widget().set_active(value)
value = self.settings.general.get_boolean()
self.get_widget().set_active(value)
value = self.... | Load configurations for all widgets in General, Scrolling
and Appearance tabs from dconf. |
373,122 | def _get_calculated_value(self, value):
if isinstance(value, types.LambdaType):
expanded_value = value(self.structure)
return self._get_calculated_value(expanded_value)
else:
return self._parse_value(value) | Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value |
373,123 | def make_seekable(fileobj):
if sys.version_info < (3, 0) and isinstance(fileobj, file):
filename = fileobj.name
fileobj = io.FileIO(fileobj.fileno(), closefd=False)
fileobj.name = filename
assert isinstance(fileobj, io.IOBase), \
"fileobj must be an instance of io.IOBase or ... | If the file-object is not seekable, return ArchiveTemp of the fileobject,
otherwise return the file-object itself |
373,124 | def get_list(self, section, option):
value = self.get(section, option)
return list(filter(None, (x.strip() for x in value.splitlines()))) | This allows for loading of Pyramid list style configuration
options:
[foo]
bar =
baz
qux
zap
``get_list('foo', 'bar')`` returns ``['baz', 'qux', 'zap']``
:param str section:
The section to read.
:param str option:
... |
373,125 | def get_backoff_time(self):
if self._observed_errors <= 1:
return 0
backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1))
return min(self.BACKOFF_MAX, backoff_value) | Formula for computing the current backoff
:rtype: float |
373,126 | def diff_list(self, list1, list2):
for key in list1:
if key in list2 and list2[key] != list1[key]:
print key
elif key not in list2:
print key | Extracts differences between lists. For debug purposes |
373,127 | def warp(self, warp_matrix, img, iflag=cv2.INTER_NEAREST):
height, width = img.shape[:2]
warped_img = np.zeros_like(img, dtype=img.dtype)
if (self.interpolation_type == InterpolationType.LINEAR) or img.ndim == 2:
warped_img = cv2.warpAffine(img.astype(np.float32),... | Function to warp input image given an estimated 2D linear transformation
:param warp_matrix: Linear 2x3 matrix to use to linearly warp the input images
:type warp_matrix: ndarray
:param img: Image to be warped with estimated transformation
:type img: ndarray
:param iflag: Interp... |
373,128 | def list_present(name, value, delimiter=DEFAULT_TARGET_DELIM):
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {: name,
: {},
: True,
: }
grain = __salt__[](name)
if grain:
if not isinstance(grain, list):
ret[] = False
... | .. versionadded:: 2014.1.0
Ensure the value is present in the list-type grain. Note: If the grain that is
provided in ``name`` is not present on the system, this new grain will be created
with the corresponding provided value.
name
The grain name.
value
The value is present in the... |
373,129 | def get_upgrade(self, using=None, **kwargs):
return self._get_connection(using).indices.get_upgrade(index=self._name, **kwargs) | Monitor how much of the index is upgraded.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.get_upgrade`` unchanged. |
373,130 | def batch_transformer(U, thetas, out_size, name=):
with tf.variable_scope(name):
num_batch, num_transforms = map(int, thetas.get_shape().as_list()[:2])
indices = [[i] * num_transforms for i in xrange(num_batch)]
input_repeated = tf.gather(U, tf.reshape(indices, [-1]))
return tra... | Batch Spatial Transformer function for `2D Affine Transformation <https://en.wikipedia.org/wiki/Affine_transformation>`__.
Parameters
----------
U : list of float
tensor of inputs [batch, height, width, num_channels]
thetas : list of float
a set of transformations for each input [batch,... |
373,131 | def route(self, path=None, method=, callback=None, name=None,
apply=None, skip=None, **config):
if callable(path): path, callback = None, path
plugins = makelist(apply)
skiplist = makelist(skip)
if in config:
depr("The parameter was renamed to ")
... | A decorator to bind a function to a request URL. Example::
@app.route('/hello/:name')
def hello(name):
return 'Hello %s' % name
The ``:name`` part is a wildcard. See :class:`Router` for syntax
details.
:param path: Request path o... |
373,132 | def condition(condition=None, statement=None, _else=None, **kwargs):
result = None
checked = False
if condition is not None:
checked = run(condition, **kwargs)
if checked:
if statement is not None:
result = run(statement, **kwargs)
elif _else is not None:
... | Run an statement if input condition is checked and return statement result.
:param condition: condition to check.
:type condition: str or dict
:param statement: statement to process if condition is checked.
:type statement: str or dict
:param _else: else statement.
:type _else: str or dict
... |
373,133 | def patch(self, item, byte_order=BYTEORDER):
self.index_data()
if is_container(item):
length = item.container_size()
if length[1] is not 0:
raise ContainerLengthError(item, length)
field = item.first_field()
... | Returns a memory :class:`Patch` for the given *item* that shall be
patched in the `data source`.
:param item: item to patch.
:param byte_order: encoding :class:`Byteorder` for the item.
:type byte_order: :class:`Byteorder`, :class:`str` |
373,134 | def modify_module(channel, module_name, module_state):
gui = ui_embed.UI(
channel,
"{} updated".format(module_name),
"{} is now {}".format(module_name, "activated" if module_state else "deactivated"),
modulename=modulename
)
return gui | Creates an embed UI containing the module modified message
Args:
channel (discord.Channel): The Discord channel to bind the embed to
module_name (str): The name of the module that was updated
module_state (bool): The current state of the module
Returns:
embed: The created embed |
373,135 | def create_message(self):
body = dedent().format(exception=self._exception,
traceback=self._traceback,
queue=self._queue,
payload=self._payload,
worker=self._worker)
return MIMEText(body) | Returns a message body to send in this email. Should be from email.mime.* |
373,136 | def set_encoding(self, encoding):
if(encoding == self.__type_representation):
return;
if (self.__type_representation == type_encoding.CLUSTER_INDEX_LABELING):
if (encoding == type_encoding.CLUSTER_INDEX_LIST_SEPARATION):
self.__clusters ... | !
@brief Change clusters encoding to specified type (index list, object list, labeling).
@param[in] encoding (type_encoding): New type of clusters representation. |
373,137 | def errorhandle(self, resp):
if self.format == :
parsed = xmltodict.parse(resp)
errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN]
if type(errors) is list and len(errors) > 1:
messages = ", ".join([" ".join(["{}: {}".forma... | Parse API error responses and raise appropriate exceptions. |
373,138 | def intertwine(*iterables):
iterables = tuple(imap(ensure_iterable, iterables))
empty = object()
return (item
for iterable in izip_longest(*iterables, fillvalue=empty)
for item in iterable if item is not empty) | Constructs an iterable which intertwines given iterables.
The resulting iterable will return an item from first sequence,
then from second, etc. until the last one - and then another item from
first, then from second, etc. - up until all iterables are exhausted. |
373,139 | def waliki_box(context, slug, show_edit=True, *args, **kwargs):
request = context["request"]
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
page = None
if (page and check_perms_helper(, request.user, slug)
or (not page and check_perms_helper(, reques... | A templatetag to render a wiki page content as a box in any webpage,
and allow rapid edition if you have permission.
It's inspired in `django-boxes`_
.. _django-boxes: https://github.com/eldarion/django-boxes |
373,140 | def load_images(input_dir, batch_shape):
images = np.zeros(batch_shape)
filenames = []
idx = 0
batch_size = batch_shape[0]
for filepath in tf.gfile.Glob(os.path.join(input_dir, )):
with tf.gfile.Open(filepath) as f:
image = np.array(Image.open(f).convert()).astype(np.float) / 255.0
image... | Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Lenght of this list could be less than batch_size, in this case only
fi... |
373,141 | def deserialize_assign(self, workflow, start_node):
name = start_node.getAttribute()
attrib = start_node.getAttribute()
value = start_node.getAttribute()
kwargs = {}
if name == :
_exc()
if attrib != and value != :
_exc()
elif attr... | Reads the "pre-assign" or "post-assign" tag from the given node.
start_node -- the xml node (xml.dom.minidom.Node) |
373,142 | def run(self):
while True:
self.update_log_filenames()
self.open_closed_files()
anything_published = self.check_log_files_and_publish_updates()
if not anything_published:
time.sleep(0.05) | Run the log monitor.
This will query Redis once every second to check if there are new log
files to monitor. It will also store those log files in Redis. |
373,143 | def fasta_files_equal(seq_file1, seq_file2):
seq1 = SeqIO.read(open(seq_file1), )
seq2 = SeqIO.read(open(seq_file2), )
if str(seq1.seq) == str(seq2.seq):
return True
else:
return False | Check equality of a FASTA file to another FASTA file
Args:
seq_file1: Path to a FASTA file
seq_file2: Path to another FASTA file
Returns:
bool: If the sequences are the same |
373,144 | def ks(self, num_ngrams):
if self.num_bits:
k = int(self.num_bits / num_ngrams)
residue = self.num_bits % num_ngrams
return ([k + 1] * residue) + ([k] * (num_ngrams - residue))
else:
return [self.k if self.k else 0] * num_ngrams | Provide a k for each ngram in the field value.
:param num_ngrams: number of ngrams in the field value
:return: [ k, ... ] a k value for each of num_ngrams such that the sum is exactly num_bits |
373,145 | def _add_in_streams(self, bolt):
if self.inputs is None:
return
input_dict = self._sanitize_inputs()
for global_streamid, gtype in input_dict.items():
in_stream = bolt.inputs.add()
in_stream.stream.CopyFrom(self._get_stream_id(global_streamid.component_id,
... | Adds inputs to a given protobuf Bolt message |
373,146 | def unlocked(self):
if self.password is not None:
return bool(self.password)
else:
if (
"UNLOCK" in os.environ
and os.environ["UNLOCK"]
and self.config_key in self.config
and self.config[self.config_key]
... | Is the store unlocked so that I can decrypt the content? |
373,147 | def addConstraint(self, constraint, variables=None):
if not isinstance(constraint, Constraint):
if callable(constraint):
constraint = FunctionConstraint(constraint)
else:
msg = "Constraints must be instances of subclasses " "of the Constraint clas... | Add a constraint to the problem
Example:
>>> problem = Problem()
>>> problem.addVariables(["a", "b"], [1, 2, 3])
>>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"])
>>> solutions = problem.getSolutions()
>>>
@param constraint: Constraint to be included... |
373,148 | def plot_sector_exposures_net(net_exposures, sector_dict=None, ax=None):
if ax is None:
ax = plt.gca()
if sector_dict is None:
sector_names = SECTORS.values()
else:
sector_names = sector_dict.values()
color_list = plt.cm.gist_rainbow(np.linspace(0, 1, 11))
for i in r... | Plots output of compute_sector_exposures as line graphs
Parameters
----------
net_exposures : arrays
Arrays of net sector exposures (output of compute_sector_exposures).
sector_dict : dict or OrderedDict
Dictionary of all sectors
- See full description in compute_sector_exposur... |
373,149 | def _check_hint_bounds(self, ds):
ret_val = []
boundary_variables = cfutil.get_cell_boundary_variables(ds)
for name in ds.variables:
if name.endswith() and name not in boundary_variables:
msg = (
.format(name))
result = ... | Checks for variables ending with _bounds, if they are not cell methods,
make the recommendation
:param netCDF4.Dataset ds: An open netCDF dataset
:rtype: list
:return: List of results |
373,150 | def class_associations(self, cn: ClassDefinitionName, must_render: bool=False) -> str:
assocs: List[str] = []
if cn not in self.associations_generated and (not self.focus_classes or cn in self.focus_classes):
cls = self.schema.classes[cn]
... | Emit all associations for a focus class. If none are specified, all classes are generated
@param cn: Name of class to be emitted
@param must_render: True means render even if this is a target (class is specifically requested)
@return: YUML representation of the association |
373,151 | def _process_state_final_run(self, job_record):
uow = self.uow_dao.get_one(job_record.related_unit_of_work)
if uow.is_processed:
self.update_job(job_record, uow, job.STATE_PROCESSED)
elif uow.is_noop:
self.update_job(job_record, uow, job.STATE_NOOP)
elif ... | method takes care of processing job records in STATE_FINAL_RUN state |
373,152 | def merge(directory, message, branch_label, rev_id, revisions):
_merge(directory, revisions, message, branch_label, rev_id) | Merge two revisions together, creating a new revision file |
373,153 | def get_core_api():
global core_api
if core_api is None:
config.load_kube_config()
if API_KEY is not None:
configuration = client.Configuration()
configuration.api_key[] = API_KEY
configuration.api_key_prefix[] =
core_api = clie... | Create instance of Core V1 API of kubernetes:
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md
:return: instance of client |
373,154 | def collect_results(self, data_values):
self.last_poll_results[] = self.poll_data[]
consumer_name = data_values[]
del data_values[]
process_name = data_values[]
del data_values[]
if consumer_name not in self.last_poll_results:
self... | Receive the data from the consumers polled and process it.
:param dict data_values: The poll data returned from the consumer
:type data_values: dict |
373,155 | def read(filename):
mesh = meshio.read(filename)
if "tetra" in mesh.cells:
points, cells = _sanitize(mesh.points, mesh.cells["tetra"])
return (
MeshTetra(points, cells),
mesh.point_data,
mesh.cell_data,
mesh.field_data,
)
eli... | Reads an unstructured mesh with added data.
:param filenames: The files to read from.
:type filenames: str
:returns mesh{2,3}d: The mesh data.
:returns point_data: Point data read from file.
:type point_data: dict
:returns field_data: Field data read from file.
:type field_data: dict |
373,156 | def purge_queue(self, name):
content = {"_object_id": {"_object_name": "org.apache.qpid.broker:queue:{0}".format(name)},
"_method_name": "purge",
"_arguments": {"type": "queue",
"name": name,
"filt... | Create message content and properties to purge queue with QMFv2
:param name: Name of queue to purge
:type name: str
:returns: Tuple containing content and method properties |
373,157 | def process_point_value(cls, command_type, command, index, op_type):
_log.debug(.format(index, command)) | A PointValue was received from the Master. Process its payload.
:param command_type: (string) Either 'Select' or 'Operate'.
:param command: A ControlRelayOutputBlock or else a wrapped data value (AnalogOutputInt16, etc.).
:param index: (integer) DNP3 index of the payload's data definition.
... |
373,158 | def harvest_openaire_projects(source=None, setspec=None):
loader = LocalOAIRELoader(source=source) if source \
else RemoteOAIRELoader(setspec=setspec)
for grant_json in loader.iter_grants():
register_grant.delay(grant_json) | Harvest grants from OpenAIRE and store as authority records. |
373,159 | def evaluate(self, dataset):
if not isinstance(dataset, DataFrame):
raise ValueError("dataset must be a DataFrame but got %s." % type(dataset))
java_glr_summary = self._call_java("evaluate", dataset)
return GeneralizedLinearRegressionSummary(java_glr_summary) | Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame` |
373,160 | def fileImport(filepath, ignore=None):
basepath, package = EnvManager.packageSplit(filepath)
if not (basepath and package):
return None
if ignore and package in ignore:
return None
basepath = os.path.normcase(basepath)
if basepath not i... | Imports the module located at the given filepath.
:param filepath | <str>
ignore | [<str>, ..] || None
:return <module> || None |
373,161 | def get_parent_element(self):
return {AUDIT_REF_STATE: self.context.audit_record,
SIGNATURE_REF_STATE: self.context.signature}[self.ref_state] | Signatures and Audit elements share sub-elements, we need to know which to set attributes on |
373,162 | def path(self):
if not self.id:
raise ValueError()
return self.path_helper(self.taskqueue.path, self.id) | Getter property for the URL path to this Task.
:rtype: string
:returns: The URL path to this task. |
373,163 | def _Resample(self, stats, target_size):
t_first = stats[0][0]
t_last = stats[-1][0]
interval = (t_last - t_first) / target_size
result = []
current_t = t_first
current_v = 0
i = 0
while i < len(stats):
stat_t = stats[i][0]
stat_v = stats[i][1]
if stat_t <= (curr... | Resamples the stats to have a specific number of data points. |
373,164 | def console_blit(
src: tcod.console.Console,
x: int,
y: int,
w: int,
h: int,
dst: tcod.console.Console,
xdst: int,
ydst: int,
ffade: float = 1.0,
bfade: float = 1.0,
) -> None:
lib.TCOD_console_blit(
_console(src), x, y, w, h, _console(dst), xdst, ydst, ffade, bf... | Blit the console src from x,y,w,h to console dst at xdst,ydst.
.. deprecated:: 8.5
Call the :any:`Console.blit` method instead. |
373,165 | def service_list(auth=None, **kwargs):
*
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.list_services(**kwargs) | List services
CLI Example:
.. code-block:: bash
salt '*' keystoneng.service_list |
373,166 | def create_key(self, title, key):
created = None
if title and key:
url = self._build_url(, )
req = self._post(url, data={: title, : key})
json = self._json(req, 201)
if json:
created = Key(json, self)
return created | Create a new key for the authenticated user.
:param str title: (required), key title
:param key: (required), actual key contents, accepts path as a string
or file-like object
:returns: :class:`Key <github3.users.Key>` |
373,167 | def get_zip_data(self, filename):
import zipimport
markers = [+os.sep, +os.sep]
for marker in markers:
if marker in filename:
parts = filename.split(marker)
try:
zi = zipimport.zipimporter(parts[0]+marker[:-1])
... | Get data from `filename` if it is a zip file path.
Returns the string data read from the zip file, or None if no zip file
could be found or `filename` isn't in it. The data returned will be
an empty string if the file is empty. |
373,168 | def check_unique_tokens(sender, instance, **kwargs):
if isinstance(instance, CallbackToken):
if CallbackToken.objects.filter(key=instance.key, is_active=True).exists():
instance.key = generate_numeric_token() | Ensures that mobile and email tokens are unique or tries once more to generate. |
373,169 | def save_plain_image_as_file(self, filepath, format=, quality=90):
pixbuf = self.get_plain_image_as_pixbuf()
options, values = [], []
if format == :
options.append()
values.append(str(quality))
pixbuf.savev(filepath, format, options, values) | Used for generating thumbnails. Does not include overlaid
graphics. |
373,170 | def parse_wiki_terms(doc):
results = []
last3 = [, , ]
header = True
for line in doc.split():
last3.pop(0)
last3.append(line.strip())
if all(s.startswith() and not s == for s in last3):
if header:
header = False
continue
... | who needs an html parser. fragile hax, but checks the result at the end |
373,171 | def analyse(file, length=None):
if isinstance(file, bytes):
file = io.BytesIO(file)
io_check(file)
int_check(length or sys.maxsize)
return analyse2(file, length) | Analyse application layer packets.
Keyword arguments:
* file -- bytes or file-like object, packet to be analysed
* length -- int, length of the analysing packet
Returns:
* Analysis -- an Analysis object from `pcapkit.analyser` |
373,172 | def create_session(self):
session = None
if self.key_file is not None:
credfile = os.path.expandvars(os.path.expanduser(self.key_file))
try:
with open(credfile, ) as f:
creds = json.load(f)
except json.JSONDecodeError as... | Create a session.
First we look in self.key_file for a path to a json file with the
credentials. The key file should have 'AWSAccessKeyId' and 'AWSSecretKey'.
Next we look at self.profile for a profile name and try
to use the Session call to automatically pick up the keys for the profi... |
373,173 | def jdbc(self, url, table, mode=None, properties=None):
if properties is None:
properties = dict()
jprop = JavaClass("java.util.Properties", self._spark._sc._gateway._gateway_client)()
for k in properties:
jprop.setProperty(k, properties[k])
self.mode(mod... | Saves the content of the :class:`DataFrame` to an external database table via JDBC.
.. note:: Don't create too many partitions in parallel on a large cluster;
otherwise Spark might crash your external database systems.
:param url: a JDBC URL of the form ``jdbc:subprotocol:subname``
... |
373,174 | def fetch(clobber=False):
table_dir = os.path.join(data_dir(), )
if not clobber:
h5_fname = os.path.join(table_dir, )
h5_size = 5033290
h5_dsets = {
: (801, 81),
: (801, 81),
: (801, 81),
: (801, 81),
: (801, 81, 33... | Downloads the Marshall et al. (2006) dust map, which is based on 2MASS
stellar photometry.
Args:
clobber (Optional[:obj:`bool`]): If ``True``, any existing file will be
overwritten, even if it appears to match. If ``False`` (the
default), :obj:`fetch()` will attempt to determine... |
373,175 | def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(),
root=os.path.join(get_home_dir(), ), **kwargs):
r
predefined_args = {: 512,
: 2048,
: 512,
: 1,
: 0.1,
... | r"""Big 1-layer LSTMP language model.
Both embedding and projection size are 512. Hidden size is 2048.
Parameters
----------
dataset_name : str or None, default None
The dataset name on which the pre-trained model is trained.
Options are 'gbw'. If specified, then the returned vocabular... |
373,176 | def t_php_START_HEREDOC(t):
r
t.lexer.lineno += t.value.count("\n")
t.lexer.push_state()
t.lexer.heredoc_label = t.lexer.lexmatch.group()
return t | r'<<<[ \t]*(?P<label>[A-Za-z_][\w_]*)\n |
373,177 | def httpapi_request(client, **params) -> :
return requests.get(
_HTTPAPI,
params={
: client.name,
: client.version,
: 1,
**params
}) | Send a request to AniDB HTTP API.
https://wiki.anidb.net/w/HTTP_API_Definition |
373,178 | def posttrans_hook(conduit):
if not in os.environ:
with open(CK_PATH, ) as ck_fh:
ck_fh.write(.format(chksum=_get_checksum(), mtime=_get_mtime())) | Hook after the package installation transaction.
:param conduit:
:return: |
373,179 | def add_role(ctx, role):
if role is None:
log()
return
if ctx.obj[] is None:
log()
return
change_user = ctx.obj[].objectmodels[].find_one({
: ctx.obj[]
})
if role not in change_user.roles:
change_user.roles.append(role)
change_user.save(... | Grant a role to an existing user |
373,180 | def debug(self):
url = .format(self.url)
data = self._get(url)
return data.json() | Retrieve the debug information from the charmstore. |
373,181 | def run(items, background=None):
if not background: background = []
background_bams = []
paired = vcfutils.get_paired_bams([x["align_bam"] for x in items], items)
if paired:
inputs = [paired.tumor_data]
if paired.normal_bam:
background = [paired.normal_data]
... | Detect copy number variations from batched set of samples using WHAM. |
373,182 | def load_env_from_file(filename):
if not os.path.exists(filename):
raise FileNotFoundError("Environment file {} does not exist.".format(filename))
with open(filename) as f:
for lineno, line in enumerate(f):
line = line.strip()
if not line or line.startswith("
... | Read an env file into a collection of (name, value) tuples. |
373,183 | def buildFileListOrig(input, output=None, ivmlist=None,
wcskey=None, updatewcs=True, **workinplace):
filelist, output, ivmlist, oldasndict = processFilenames(input,output)
filelist = util.verifyFilePermissions(filelist)
if filelist is None or len(filelist) == 0:
... | Builds a file list which has undergone various instrument-specific
checks for input to MultiDrizzle, including splitting STIS associations.
Compared to buildFileList, this version returns the list of the
original file names as specified by the user (e.g., before GEIS->MEF, or
WAIVER FITS->MEF conversion... |
373,184 | def _build_date_header_string(self, date_value):
if isinstance(date_value, datetime):
date_value = time.mktime(date_value.timetuple())
if not isinstance(date_value, basestring):
date_value = formatdate(date_value, localtime=True)
return native(date_value) | Gets the date_value (may be None, basestring, float or
datetime.datetime instance) and returns a valid date string as per
RFC 2822. |
373,185 | def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspection],
condition_kwargs: Mapping[str, Any], a_repr: reprlib.Repr) -> List[str]:
if _is_lambda(a_function=condition):
assert lambda_inspection is not None, "Expected a lambda inspection ... | Represent function arguments and frame values in the error message on contract breach.
:param condition: condition function of the contract
:param lambda_inspection:
inspected lambda AST node corresponding to the condition function (None if the condition was not given as a
lambda function)
... |
373,186 | def _recursively_apply_get_cassette_subclass(self, replacement_dict_or_obj):
if isinstance(replacement_dict_or_obj, dict):
for key, replacement_obj in replacement_dict_or_obj.items():
replacement_obj = self._recursively_apply_get_cassette_subclass(
replac... | One of the subtleties of this class is that it does not directly
replace HTTPSConnection with `VCRRequestsHTTPSConnection`, but a
subclass of the aforementioned class that has the `cassette`
class attribute assigned to `self._cassette`. This behavior is
necessary to properly support nest... |
373,187 | def copy_dir(
src_fs,
src_path,
dst_fs,
dst_path,
walker=None,
on_copy=None,
workers=0,
):
on_copy = on_copy or (lambda *args: None)
walker = walker or Walker()
_src_path = abspath(normpath(src_path))
_dst_path = abspath(normpath(dst_path))
def sr... | Copy a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on the... |
373,188 | def inverse_transform(self, X):
check_is_fitted(self, "mean_")
if self.whiten:
return (
da.dot(
X,
np.sqrt(self.explained_variance_[:, np.newaxis]) * self.components_,
)
+ self.mean_
... | Transform data back to its original space.
Returns an array X_original whose transform would be X.
Parameters
----------
X : array-like, shape (n_samples, n_components)
New data, where n_samples in the number of samples
and n_components is the number of componen... |
373,189 | def _sumterm(lexer):
xorterm = _xorterm(lexer)
sumterm_prime = _sumterm_prime(lexer)
if sumterm_prime is None:
return xorterm
else:
return (, xorterm, sumterm_prime) | Return a sum term expresssion. |
373,190 | def consensus(aln, weights=None, gap_threshold=0.5, simple=False, trim_ends=True):
if simple:
col_consensus = make_simple_col_consensus(alnutils.aa_frequencies(aln))
def is_majority_gap(col):
return (float(col.count()) / len(col) >= gap_threshold)
... | Get the consensus of an alignment, as a string.
Emit gap characters for majority-gap columns; apply various strategies to
choose the consensus amino acid type for the remaining columns.
Parameters
----------
simple : bool
If True, use simple plurality to determine the consensus amino acid... |
373,191 | def save(self):
with rconnect() as conn:
try:
self.validate()
except ValidationError as e:
log.warn(e.messages)
raise
except ModelValidationError as e:
log.warn(e.messages)
raise
... | Save the current instance to the DB |
373,192 | def scan_dir(self, path):
r
for fname in glob.glob(os.path.join(path, + TABLE_EXT)):
if os.path.isfile(fname):
with open(fname, ) as fobj:
try:
self.add_colortable(fobj, os.path.splitext(os.path.basename(fname))[0])
... | r"""Scan a directory on disk for color table files and add them to the registry.
Parameters
----------
path : str
The path to the directory with the color tables |
373,193 | def setEmergencyDecel(self, vehID, decel):
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_EMERGENCY_DECEL, vehID, decel) | setEmergencyDecel(string, double) -> None
Sets the maximal physically possible deceleration in m/s^2 for this vehicle. |
373,194 | def index():
crawlers = []
for crawler in manager:
data = Event.get_counts(crawler)
data[] = crawler.last_run
data[] = crawler.op_count
data[] = crawler.is_running
data[] = crawler
crawlers.append(data)
return render_template(, crawlers=crawlers) | Generate a list of all crawlers, alphabetically, with op counts. |
373,195 | def triggered_token(self) -> :
if self._triggered.is_set():
return self
for token in self._chain:
if token.triggered:
return token.triggered_token
return None | Return the token which was triggered.
The returned token may be this token or one that it was chained with. |
373,196 | def cli(ctx):
click.secho("\nPyHardLinkBackup v%s\n" % PyHardLinkBackup.__version__, bg="blue", fg="white", bold=True) | PyHardLinkBackup |
373,197 | def _get_django_queryset(self):
prefetches = []
for field, fprefetch in self.prefetches.items():
has_query = hasattr(fprefetch, )
qs = fprefetch.query.queryset if has_query else None
prefetches.append(
Prefetch(field, queryset=qs)
... | Return Django QuerySet with prefetches properly configured. |
373,198 | def main():
parser = argparse.ArgumentParser(description=
,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(, , type=str, required=False,
help=)
parser.add_argument(, , type... | Phenologs |
373,199 | def timescales_from_eigenvalues(evals, tau=1):
r
if not np.allclose(evals.imag, 0.0):
warnings.warn(, ImaginaryEigenValueWarning)
ind_abs_one = np.isclose(np.abs(evals), 1.0, rtol=0.0, atol=1e-14)
if sum(ind_abs_one) > 1:
warnings.warn(, SpectralWarning)
ts = np.ze... | r"""Compute implied time scales from given eigenvalues
Parameters
----------
evals : eigenvalues
tau : lag time
Returns
-------
ts : ndarray
The implied time scales to the given eigenvalues, in the same order. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.