text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_responses(self):
"""Gets list of the latest responses"""
response_list = []
for question_map in self._my_map['questions']:
response_list.append(self._get_response_from_question_map(question_map))
return ResponseList(response_list) | 0.010638 |
def install_python_package(self, arch, name=None, env=None, is_dir=True):
'''Automate the installation of a Python package (or a cython
package where the cython components are pre-built).'''
# arch = self.filtered_archs[0] # old kivy-ios way
if name is None:
name = self.name... | 0.002092 |
def tags_published():
"""
Return the published tags.
"""
from tagging.models import Tag
from zinnia.models.entry import Entry
tags_entry_published = Tag.objects.usage_for_queryset(
Entry.published.all())
# Need to do that until the issue #44 of django-tagging is fixed
return Tag.... | 0.002611 |
def get_res(ds, t_srs=None, square=False):
"""Get GDAL Dataset raster resolution
"""
gt = ds.GetGeoTransform()
ds_srs = get_ds_srs(ds)
#This is Xres, Yres
res = [gt[1], np.abs(gt[5])]
if square:
res = [np.mean(res), np.mean(res)]
if t_srs is not None and not ds_srs.IsSame(t_srs):... | 0.009774 |
def search(cls, *, limit=100, page=1, properties=None, return_query=False):
"""Search for issues based on the provided filters
Args:
limit (`int`): Number of results to return. Default: 100
page (`int`): Pagination offset for results. Default: 1
properties (`dict`): ... | 0.002899 |
def xmoe2_dense(sz):
"""Series of architectural experiments on language modeling.
Larger models than the ones above.
All models are trained on sequences of 1024 tokens.
We assume infinite training data, so no dropout necessary.
We process 2^36 tokens in training = 524288 steps at batch size 128
TODO(noa... | 0.011285 |
def load_entry_points(self):
"""Load tasks from entry points."""
if self.entry_point_group:
task_packages = {}
for item in pkg_resources.iter_entry_points(
group=self.entry_point_group):
# Celery 4.2 requires autodiscover to be called with
... | 0.001433 |
def from_dict(raw_data):
"""Create Image from raw dictionary data."""
url = None
width = None
height = None
try:
url = raw_data['url']
width = raw_data['width']
height = raw_data['height']
except KeyError:
raise ValueError('... | 0.003899 |
def _getPageInfo(self, pno, what):
"""Show fonts or images used on a page."""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
val = _fitz.Document__getPageInfo(self, pno, what)
x = []
for v in val:
i... | 0.005038 |
def _create_djset(args, cls):
""" Return a DjSecret object """
name = args.get('--name')
settings = args.get('--settings')
if name:
return cls(name=name)
elif settings:
return cls(name=settings)
else:
return cls() | 0.003831 |
def shutdown(self):
"""Forcefully shutdown the entire pool, closing all non-executing
connections.
:raises: ConnectionBusyError
"""
with self._lock:
for cid in list(self.connections.keys()):
if self.connections[cid].executing:
rai... | 0.003752 |
def dump_pdb(filename, molecule, atomnames=None, resnames=None, chain_ids=None, occupancies=None, betas=None):
"""Writes a single molecule to a pdb file.
This function is based on the pdb file specification:
http://www.wwpdb.org/documentation/format32/sect9.html
For convenience, the relevant t... | 0.003813 |
def filter(self, model=None, context=None):
"""
Perform filtering on the model. Will change model in place.
:param model: object or dict
:param context: object, dict or None
:return: None
"""
if model is None:
return
# properties
self.... | 0.003899 |
def _should_trigger_abbreviation(self, buffer):
"""
Checks whether, based on the settings for the abbreviation and the given input,
the abbreviation should trigger.
@param buffer Input buffer to be checked (as string)
"""
return any(self.__checkInput(buffer, abbr) for ab... | 0.011594 |
def add_properties(self, filename):
"""
Add properties to config based on filename replacing previous values.
:param filename: str path to YAML file to pull top level properties from
"""
filename = os.path.expanduser(filename)
if os.path.exists(filename):
with... | 0.007143 |
def modify_account(self, account, attrs):
"""
:param account: a zobjects.Account
:param attrs : a dictionary of attributes to set ({key:value,...})
"""
attrs = [{'n': k, '_content': v} for k, v in attrs.items()]
self.request('ModifyAccount', {
'id': self._get... | 0.005076 |
def new_screen(self):
"""Makes a new screen with a size of SCREEN_SIZE, and VIDEO_OPTION as flags. Sets the windows name to NAME."""
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.display.set_caption(self.NAME)
screen_s = self.SCREEN_SIZE
video_options = self.VIDEO_OPTIONS
... | 0.004717 |
def to_cloudformation(self, **kwargs):
"""Returns the Lambda Permission resource allowing SNS to invoke the function this event source triggers.
:param dict kwargs: no existing resources need to be modified
:returns: a list of vanilla CloudFormation Resources, to which this SNS event expands
... | 0.007634 |
def export_obj(vertices, triangles, filename):
"""
Exports a mesh in the (.obj) format.
"""
with open(filename, 'w') as fh:
for v in vertices:
fh.write("v {} {} {}\n".format(*v))
for f in triangles:
fh.write("f {} {} {}\n".format(*(f + 1... | 0.012384 |
def insert_element(self, vector, value, idx, name=''):
"""
Returns vector with vector[idx] replaced by value.
The result is undefined if the idx is larger or equal the vector length.
"""
instr = instructions.InsertElement(self.block, vector, value, idx,
... | 0.007576 |
def search(self, **kwargs):
"""
Method to search object group permissions general based on extends search.
:param search: Dict containing QuerySets to find object group permissions general.
:param include: Array containing fields to include on response.
:param exclude: Array con... | 0.008642 |
def retrieve_state_ids(self, activity, agent, registration=None, since=None):
"""Retrieve state id's from the LRS with the provided parameters
:param activity: Activity object of desired states
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of desired state... | 0.00135 |
def render(self, name, value, attrs=None):
if value is None:
value = ''
value = smart_unicode(value)
final_attrs = self.build_attrs(attrs)
final_attrs['name'] = name
assert 'id' in final_attrs, \
"TinyMCE widget attributes must contain 'id'"
mce_co... | 0.000931 |
def nth_combination(iterable, r, index):
"""Equivalent to ``list(combinations(iterable, r))[index]``.
The subsequences of *iterable* that are of length *r* can be ordered
lexicographically. :func:`nth_combination` computes the subsequence at
sort position *index* directly, without computing the previou... | 0.001152 |
def _check_item_type(item, field_name, allowed_types, expect_list=False,
required_channels='all'):
"""
Check the item's type against a set of allowed types.
Vary the print message regarding whether the item can be None.
Helper to `BaseRecord.check_field`.
Parameters
--------... | 0.001499 |
def _expand(self, str, local_vars={}):
"""Expand $vars in a string."""
return ninja_syntax.expand(str, self.vars, local_vars) | 0.014184 |
def load_multiple(paths=None, first_data_line="auto", filters="*.*", text="Select some files, FACEHEAD.", default_directory="default_directory", quiet=True, header_only=False, transpose=False, **kwargs):
"""
Loads a list of data files into a list of databox data objects.
Returns said list.
Paramete... | 0.01002 |
def _try_mask_first_value(value, row, all_close):
'''
mask first value in row
value1 : ~typing.Any
row : 1d masked array
all_close : bool
compare with np.isclose instead of ==
Return whether masked a value
'''
# Compare value to row
for i, value2 in enumerate(row):
... | 0.002299 |
def start_element (self, tag, attrs):
"""Search for meta robots.txt "nofollow" and "noindex" flags."""
if tag == 'meta' and attrs.get('name') == 'robots':
val = attrs.get_true('content', u'').lower().split(u',')
self.follow = u'nofollow' not in val
self.index = u'noin... | 0.006369 |
def write_fasta_file(seq_records, outname, outdir=None, outext='.faa', force_rerun=False):
"""Write a FASTA file for a SeqRecord or a list of SeqRecord objects.
Args:
seq_records (SeqRecord, list): SeqRecord or a list of SeqRecord objects
outname: Name of the output file which will have outext ... | 0.003525 |
def filter_values(column, default=None):
""" Gets a values for a particular filter as a list
This is useful if:
- you want to use a filter box to filter a query where the name of filter box
column doesn't match the one in the select statement
- you want to have the ability for filter ... | 0.00301 |
def do_refresh(self,args):
"""Refresh the view of the log group"""
print "stackResource: {}".format(self.stackResource)
self.roleDetails = AwsConnectionFactory.getIamClient().get_role(RoleName=self.stackResource.physical_resource_id)
print "== role details =="
pprint(sel... | 0.010846 |
def get_account_history_page(address, page, hostport=None, proxy=None):
"""
Get a page of the account's history
Returns the list of account operations on success
Returns {'error': ...} on error
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_h... | 0.003083 |
def bytes_cast(maybe_str, encoding='utf-8'):
"""
Converts any string-like input to a bytes-like output, with respect to
python version
Parameters
----------
maybe_str : if this is a string-like object, it will be converted to bytes
encoding : str, default='utf-8'
encoding to be use... | 0.002141 |
def resize_cover(image, size, resample=Image.LANCZOS):
"""
Resize image according to size.
image: a Pillow image instance
size: a list of two integers [width, height]
"""
img_format = image.format
img = image.copy()
img_size = img.size
ratio = max(size[0] / img_size[0], si... | 0.001704 |
def restore(self, state):
"""Restore this state from the output of a previous call to dump().
Only those properties in this object and listed in state will be
updated. Other properties will not be modified and state may contain
keys that do not correspond with properties in this object... | 0.002497 |
def get_dashboard_version(self, id, version, **kwargs): # noqa: E501
"""Get a specific version of a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thre... | 0.00201 |
def make_pkey(key_type=crypto.TYPE_RSA, key_bits=4096):
"""Make a public/private key pair.
:param int key_type: The key type. For example,
:class:`OpenSSL.crypto.TYPE_RSA`.
:param int key_bits: The size of the key in bits.
:return: A private key.
:rtype: :class:`OpenSSL.crypto.PKey`
"""
key = crypto... | 0.013193 |
def graph_multiresolution(G, levels, sparsify=True, sparsify_eps=None,
downsampling_method='largest_eigenvector',
reduction_method='kron', compute_full_eigen=False,
reg_eps=0.005):
r"""Compute a pyramid of graphs (by Kron reduction).
... | 0.001044 |
def send(self, data):
"""
Send data to the child process through.
"""
self.stdin.write(data)
self.stdin.flush() | 0.013245 |
def get_reactions(self):
"""
:calls: `GET /repos/:owner/:repo/issues/:number/reactions <https://developer.github.com/v3/reactions/#list-reactions-for-an-issue>`_
:return: :class: :class:`github.PaginatedList.PaginatedList` of :class:`github.Reaction.Reaction`
"""
return github.Pa... | 0.007366 |
def _variant_vc(checkpoints):
"""Add variant calling to workflow, if configured.
"""
if not checkpoints.get("vc"):
return [], []
vc_wf = [s("get_parallel_regions", "batch-split",
[["batch_rec"]],
[cwlout(["region_block"], {"type": "array", "items": "string"})],
... | 0.004369 |
def ellipticity2phi_q(e1, e2):
"""
:param e1:
:param e2:
:return:
"""
phi = np.arctan2(e2, e1)/2
c = np.sqrt(e1**2+e2**2)
if c > 0.999:
c = 0.999
q = (1-c)/(1+c)
return phi, q | 0.004484 |
def contains(x):
"""Return true if this string or integer tuple appears in tables"""
if isinstance(x, str):
x = canonical_name(x)
return x in _TO_COLOR_USER or x in _TO_COLOR
else:
x = tuple(x)
return x in _TO_NAME_USER or x in _TO_NAME | 0.003571 |
def get_t_periastron(self, params):
"""
Return the time of periastron passage (calculated using `params.t0`).
"""
phase = self._get_phase(params, "primary")
return params.t0 - params.per*phase | 0.034653 |
def uniprot_ec(uniprot_id):
"""Retrieve the EC number annotation for a UniProt ID.
Args:
uniprot_id: Valid UniProt ID
Returns:
"""
r = requests.post('http://www.uniprot.org/uniprot/?query=%s&columns=ec&format=tab' % uniprot_id)
ec = r.content.decode('utf-8').splitlines()[1]
if le... | 0.005495 |
def initiate(self, transport, to = None):
"""Initiate an XMPP connection over the `transport`.
:Parameters:
- `transport`: an XMPP transport instance
- `to`: peer name (defaults to own jid domain part)
"""
if to is None:
to = JID(self.me.domain)
... | 0.010811 |
def run(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Run tumor only smCounter2 calling.
"""
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and not paired.normal_bam, ("smCounter2 supports tumor-only variant calling: %s" %
... | 0.006455 |
def logging_file_install(path):
"""
Install logger that will write to file. If this function has already installed a handler, replace it.
:param path: path to the log file, Use None for default file location.
"""
if path is None:
path = configuration_get_default_folder() / LOGGING_DEFAULTNAM... | 0.003565 |
def find_clusters(struct, connected_list):
"""
Finds bonded clusters of atoms in the structure with periodic boundary conditions.
If there are atoms that are not bonded to anything, returns [0,1,0].(For faster computation time in FindDimension())
Args:
struct (Structure): Input structure
... | 0.003121 |
def username(self, value=None):
"""
Return or set the username
:param string value: the new username to use
:returns: string or new :class:`URL` instance
"""
if value is not None:
return URL._mutate(self, username=value)
return unicode_unquote(self._t... | 0.005988 |
def nutation(date, eop_correction=True, terms=106): # pragma: no cover
"""Nutation as a rotation matrix
"""
epsilon_bar, delta_psi, delta_eps = np.deg2rad(_nutation(date, eop_correction, terms))
epsilon = epsilon_bar + delta_eps
return rot1(-epsilon_bar) @ rot3(delta_psi) @ rot1(epsilon) | 0.006452 |
def use_federated_family_view(self):
"""Pass through to provider RelationshipLookupSession.use_federated_family_view"""
self._family_view = FEDERATED
# self._get_provider_session('relationship_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessio... | 0.008889 |
def create_ssl_context():
"""Create and return SSL Context."""
ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
return ssl_context | 0.007634 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'text') and self.text is not None:
_dict['text'] = self.text
if hasattr(self, '_additionalProperties'):
for _key in self._additionalProperties:
... | 0.004396 |
def _CheckDatabaseEncoding(cursor):
"""Enforces a sane UTF-8 encoding for the database."""
cur_character_set = _ReadVariable("character_set_database", cursor)
if cur_character_set != CHARACTER_SET:
raise EncodingEnforcementError(
"Require MySQL character_set_database of {}, got {}."
" To creat... | 0.007813 |
def start(self, blocking=False):
"""
Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start
"""
self.debug("()")
... | 0.003571 |
def outfiles(fmt, nfiles, progress, leave=True):
"""Get output file paths.
Parameters
----------
fmt : `str`
File path format string.
nfiles : `int`
Number of files.
progress : `bool`
Show progress bars.
leave : `bool`, optional
Leave progress bar (default: T... | 0.001083 |
def raw_corpus_length_ratio(hypotheses: Iterable[str], references: Iterable[str]) -> float:
"""
Simple wrapper around length ratio implementation.
:param hypotheses: Hypotheses stream.
:param references: Reference stream.
:return: Length ratio score as float.
"""
ratios = [len(h.split())/le... | 0.006944 |
def select_layout(self, layout_type):
"""
Select one of the predefined layouts.
"""
assert layout_type in LayoutTypes._ALL
# When there is only one pane, always choose EVEN_HORIZONTAL,
# Otherwise, we create VSplit/HSplit instances with an empty list of
# childre... | 0.001169 |
def form_to_params(fn=None, return_json=True):
"""
Convert bottle forms request to parameters for the wrapped function.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON?
"""
def forms_to_params_decorator(fn):
... | 0.001186 |
def start(self):
"""Start the pool of threads."""
for i in range(self.min):
self._threads.append(WorkerThread(self.server))
for worker in self._threads:
worker.setName("CP Server " + worker.getName())
worker.start()
for worker in self._threads:
... | 0.005277 |
def _configure_key_pair(config):
"""Configure SSH access, using an existing key pair if possible.
Creates a project-wide ssh key that can be used to access all the instances
unless explicitly prohibited by instance config.
The ssh-keys created by ray are of format:
[USERNAME]:ssh-rsa [KEY_VALUE... | 0.000356 |
def add_ruleclause_name(self, ns_name, rid) -> bool:
"""Create a tree.Rule"""
ns_name.parser_tree = parsing.Rule(self.value(rid))
return True | 0.006536 |
def _to_rfc822(date):
"""_to_rfc822(datetime.datetime) -> str
The datetime `strftime` method is subject to locale-specific
day and month names, so this function hardcodes the conversion."""
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
da... | 0.001541 |
def on_pbnBack_released(self):
"""Handle the Back button release.
.. note:: This is an automatic Qt slot
executed when the Back button is released.
"""
current_step = self.get_current_step()
if current_step.step_type == STEP_FC:
new_step = self.impact_func... | 0.001661 |
def get_context_data(self, **kwargs):
"""
Add error and pattern in context.
"""
context = super(BaseEntrySearch, self).get_context_data(**kwargs)
context.update({'error': self.error, 'pattern': self.pattern})
return context | 0.00738 |
def _escape_string(text, _map={}):
"""
Escape the given bytestring for safe use as a LLVM array constant.
"""
if isinstance(text, str):
text = text.encode('ascii')
assert isinstance(text, (bytes, bytearray))
if not _map:
for ch in range(256):
if ch in _VALID_CHARS:
... | 0.001859 |
def challenge():
"""Creates an enum for contest type"""
enums = dict(
ACTIVE="active",
UPCOMING="upcoming",
HIRING="hiring",
ALL="all",
SHORT="short",
)
return type('Enum', (), enums) | 0.018868 |
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if self.blank and not value:
return {}
value = value or '{}'
if isinstance(value, six... | 0.002584 |
def filter_genes_dispersion(data,
flavor='seurat',
min_disp=None, max_disp=None,
min_mean=None, max_mean=None,
n_bins=20,
n_top_genes=None,
log=True,
... | 0.00262 |
def tsort(self):
"""Given a partial ordering, return a totally ordered list.
part is a dict of partial orderings. Each value is a set,
which the key depends on.
The return value is a list of sets, each of which has only
dependencies on items in previous entries in the list.
... | 0.00473 |
def build_stop_ids(shape_id):
"""
Create a pair of stop IDs based on the given shape ID.
"""
return [cs.SEP.join(['stp', shape_id, str(i)]) for i in range(2)] | 0.005747 |
def get_data_home(data_home=None):
"""
Return the path of the revrand data dir.
This folder is used by some large dataset loaders to avoid
downloading the data several times.
By default the data dir is set to a folder named 'revrand_data'
in the user home folder.
Alternatively, it can be ... | 0.001124 |
def encrypt_file(file_path, sender, recipients):
"Returns encrypted binary file content if successful"
for recipient_key in recipients:
crypto.assert_type_and_length('recipient_key', recipient_key, (str, crypto.UserLock))
crypto.assert_type_and_length("sender_key", sender, crypto.UserLock)
if (n... | 0.007485 |
def viterbi_tags(self,
logits: torch.Tensor,
mask: torch.Tensor) -> List[Tuple[List[int], float]]:
"""
Uses viterbi algorithm to find most likely tags for the given inputs.
If constraints are applied, disallows all other transitions.
"""
... | 0.004648 |
def get_managers(self):
"""Get managers for the slave environments.
"""
if self._single_env:
return None
if not hasattr(self, '_managers'):
self._managers = self.env.get_slave_managers()
return self._managers | 0.007353 |
def __EncodedAttribute_generic_encode_rgb24(self, rgb24, width=0, height=0, quality=0, format=_ImageFormat.RawImage):
"""Internal usage only"""
if not is_seq(rgb24):
raise TypeError("Expected sequence (str, numpy.ndarray, list, tuple "
"or bytearray) as first argument")
is_s... | 0.001485 |
def percentile(data, n):
"""Return the n-th percentile of the given data
Assume that the data are already sorted
"""
size = len(data)
idx = (n / 100.0) * size - 0.5
if idx < 0 or idx > size:
raise StatisticsError("Too few data points ({}) for {}th percentile".format(size, n))
re... | 0.0059 |
def render_widgets(kb_app: kb,
sphinx_app: Sphinx,
doctree: doctree,
fromdocname: str,
):
""" Go through docs and replace widget directive with rendering """
builder: StandaloneHTMLBuilder = sphinx_app.builder
for node in doctree.... | 0.001253 |
def letter():
'''Parse a letter in alphabet.'''
@Parser
def letter_parser(text, index=0):
if index < len(text) and text[index].isalpha():
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'a letter')
return letter_parser | 0.003279 |
def load_into_collection_from_stream(collection, stream, content_type):
"""
Loads resources from the given resource data stream (of the specified MIME
content type) into the given collection resource.
"""
rpr = as_representer(collection, content_type)
with stream:
data_el = rpr.data_from... | 0.002551 |
def on_chat(self, data):
''' Transfert a message to everybody '''
# XXX: we cannot use on_message as it's 'official' one already used
# by sockjsroom to create multiple on_* elements (like on_chat),
# so we use on_chat instead of on_message
# data => message
if self.room... | 0.003766 |
def disassemble_hex(bytecode, pc=0, fork=DEFAULT_FORK):
""" Disassemble an EVM bytecode
:param bytecode: canonical representation of an evm bytecode (hexadecimal)
:type bytecode: str
:param pc: program counter of the first instruction(optional)
:type pc: int
:param fork: for... | 0.002463 |
def _update_plotting_params(self, **kwargs):
"""Some plotting parameters can be changed through the tool; this
updataes those plotting parameters.
"""
scalars = kwargs.get('scalars', None)
if scalars is not None:
old = self.display_params['scalars']
self.d... | 0.003663 |
def ilumin(method, target, et, fixref, abcorr, obsrvr, spoint):
"""
Find the illumination angles (phase, solar incidence, and
emission) at a specified surface point of a target body.
This routine supersedes illum.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ilumin_c.html
:param me... | 0.000546 |
def get_texts_and_labels(sentence_chunk):
"""Given a sentence chunk, extract original texts and labels."""
words = sentence_chunk.split('\n')
texts = []
labels = []
for word in words:
word = word.strip()
if len(word) > 0:
toks = word.split('\t')
texts.append(t... | 0.002475 |
def parse_log_entry(text):
"""This function does all real job on log line parsing.
it setup two cases for restart parsing if a line
with wrong format was found.
Restarts:
- use_value: just retuns an object it was passed. This can
be any value.
- reparse: calls `parse_log_entry` again with... | 0.002632 |
def rotate_du_by_yaw(self, du, heading):
"""Rotate all DOMs on DU by a given (yaw) heading."""
mask = (self.pmts.du == du)
dom_ids = np.unique(self.pmts.dom_id[mask])
for dom_id in dom_ids:
self.rotate_dom_by_yaw(dom_id, heading)
self.reset_caches() | 0.006645 |
def apply(script, value=None, vars={}, url=None, opener=default_opener, library_paths=[]):
"""
Transform value by script, returning all results as list.
"""
return all(script, value, vars, url, opener, library_paths) | 0.008621 |
def _build_pub_key_auth(self, context, nonce, auth_token, public_key):
"""
[MS-CSSP] 3.1.5 Processing Events and Sequencing Rules - Step 3
https://msdn.microsoft.com/en-us/library/cc226791.aspx
This step sends the final SPNEGO token to the server if required and
computes the val... | 0.001041 |
def yn(self, prompt, default=None):
"""Prompts the user for yes/no confirmation, with optional default"""
if default is True:
opts = " [Y/n]: "
elif default is False:
opts = " [y/N]: "
else:
opts = " [y/n]: "
prompt += opts
return self.... | 0.005435 |
def collect(self):
"""
Collect s3 bucket stats
"""
if boto is None:
self.log.error("Unable to import boto python module")
return {}
for s3instance in self.config['s3']:
self.log.info("S3: byte_unit: %s" % self.config['byte_unit'])
a... | 0.001845 |
def _referer(self, extension):
"""
Return the referer for the given extension.
:param extension: A valid domain extension.
:type extension: str
:return: The whois server to use to get the WHOIS record.
:rtype: str
"""
# We get the a copy of the page.
... | 0.002058 |
def _parse_singlefile(self, desired_type: Type[T], file_path: str, encoding: str, logger: Logger,
options: Dict[str, Dict[str, Any]]) -> T:
"""
Relies on the inner parsing function to parse the file.
If _streaming_mode is True, the file will be opened and closed by this... | 0.004978 |
def column(self):
"""获取文章所在专栏.
:return: 文章所在专栏
:rtype: Column
"""
from .column import Column
if 'column' in self.soup:
url = Column_Url + '/' + self.soup['column']['slug']
name = self.soup['column']['name']
return Column(url, name, se... | 0.005291 |
def cmd(send, msg, _):
"""Finds a random quote from tjbash.org given search criteria.
Syntax: {command} [searchstring]
"""
if not msg:
url = 'http://tjbash.org/random1.html'
params = {}
else:
targs = msg.split()
if len(targs) == 1 and targs[0].isnumeric():
... | 0.002357 |
def popenCatch(command, stdinString=None):
"""Runs a command and return standard out.
"""
logger.debug("Running the command: %s" % command)
if stdinString != None:
process = subprocess.Popen(command, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, bu... | 0.009044 |
def set_writer(self, writer):
"""
Changes the writer function to handle writing to the text edit.
A writer function must have the following prototype:
.. code-block:: python
def write(text_edit, text, color)
:param writer: write function as described above.
... | 0.004329 |
def normalizeFeatureText(value):
"""
Normalizes feature text.
* **value** must be a :ref:`type-string`.
* Returned value will be an unencoded ``unicode`` string.
"""
if not isinstance(value, basestring):
raise TypeError("Feature text must be a string, not %s."
% ... | 0.002725 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.