text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def simulate(s0, transmat, steps=1):
"""Simulate the next state
Parameters
----------
s0 : ndarray
Vector with state variables at t=0
transmat : ndarray
The estimated transition/stochastic matrix.
steps : int
(Default: 1) The number of steps to simulate model outputs a... | 0.001016 |
def tcc(text: str) -> str:
"""
TCC generator, generates Thai Character Clusters
:param str text: text to be tokenized to character clusters
:return: subword (character cluster)
"""
if not text or not isinstance(text, str):
return ""
p = 0
while p < len(text):
m = PAT_TCC... | 0.004396 |
def unweave(iterable, n=2):
r"""Divide `iterable` in `n` lists, so that every `n`th element belongs to
list `n`.
Example:
>>> unweave((1,2,3,4,5), 3)
[[1, 4], [2, 5], [3]]
"""
res = [[] for i in range(n)]
i = 0
for x in iterable:
res[i % n].append(x)
i += 1
retu... | 0.003067 |
def _factory_default(self, confirm=False):
"""Resets the device to factory defaults.
:param confirm: This function should not normally be used, to prevent
accidental resets, a confirm value of `True` must be used.
"""
if confirm is True:
self._write(('DFLT', Int... | 0.004751 |
def _download_tlds_list(self):
"""
Function downloads list of TLDs from IANA.
LINK: https://data.iana.org/TLD/tlds-alpha-by-domain.txt
:return: True if list was downloaded, False in case of an error
:rtype: bool
"""
url_list = 'https://data.iana.org/TLD/tlds-alph... | 0.000999 |
def create_sonos_playlist(self, title):
"""Create a new empty Sonos playlist.
Args:
title: Name of the playlist
:rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer`
"""
response = self.avTransport.CreateSavedQueue([
('InstanceID', 0),
... | 0.002558 |
def NodeDriver_wait_until_running(self, node, wait_period=3, timeout=600,
ssh_interface='public_ips', force_ipv4=True):
"""
Block until node is fully booted and has an IP address assigned.
@keyword node: Node instance.
@type node: C{Node}
@keyword wait... | 0.000921 |
def subvolume_delete(name=None, names=None, commit=None):
'''
Delete the subvolume(s) from the filesystem
The user can remove one single subvolume (name) or multiple of
then at the same time (names). One of the two parameters needs to
specified.
Please, refer to the documentation to understand... | 0.000582 |
def getcwd(fs_encoding=FS_ENCODING, cwd_fnc=os.getcwd):
'''
Get current work directory's absolute path.
Like os.getcwd but garanteed to return an unicode-str object.
:param fs_encoding: filesystem encoding, defaults to autodetected
:type fs_encoding: str
:param cwd_fnc: callable used to get the... | 0.001972 |
def _checkin_remote_bundle(self, remote, ref):
"""
Checkin a remote bundle from a remote
:param remote: a Remote object
:param ref: Any bundle reference
:return: The vid of the loaded bundle
"""
from ambry.bundle.process import call_interval
from ambry.orm... | 0.003313 |
def _process_stockprop(self, limit):
"""
This will add depiction association between a strain and
images hosted at flybase.
:param limit:
:return:
"""
if self.test_mode:
graph = self.testgraph
else:
graph = self.graph
mode... | 0.00227 |
def _parse_fc(self, f, natom, dim):
"""Parse force constants part
Physical unit of force cosntants in the file is Ry/au^2.
"""
ndim = np.prod(dim)
fc = np.zeros((natom, natom * ndim, 3, 3), dtype='double', order='C')
for k, l, i, j in np.ndindex((3, 3, natom, natom)):
... | 0.003407 |
def magic_memit(self, line=''):
"""Measure memory usage of a Python statement
Usage, in line mode:
%memit [-r<R>t<T>i<I>] statement
Options:
-r<R>: repeat the loop iteration <R> times and take the best result.
Default: 1
-t<T>: timeout after <T> seconds. Default: None
-i<I>: Get ti... | 0.000521 |
def store(self, extractions: List[Extraction], attribute: str, group_by_tags: bool = True) -> None:
"""
Records extractions in the container, and for each individual extraction inserts a
ProvenanceRecord to record where the extraction is stored.
Records the "output_segment" in the proven... | 0.004945 |
def bind(self, handler, argspec):
"""
:param handler: a function with
:param argspec:
:return:
"""
self.handlers[argspec.key].append((handler, argspec)) | 0.01 |
def add_leaf(self, value, do_hash=False):
"""
Add a leaf to the tree.
:param value: hash value (as a Buffer) or hex string
:param do_hash: whether to hash value
"""
self.tree['is_ready'] = False
self._add_leaf(value, do_hash) | 0.007117 |
def approximate_density(
dist,
xloc,
parameters=None,
cache=None,
eps=1.e-7
):
"""
Approximate the probability density function.
Args:
dist : Dist
Distribution in question. May not be an advanced variable.
xloc : numpy.ndarray
... | 0.000571 |
def load_config_from_files(filenames=None):
"""Load D-Wave Cloud Client configuration from a list of files.
.. note:: This method is not standardly used to set up D-Wave Cloud Client configuration.
It is recommended you use :meth:`.Client.from_config` or
:meth:`.config.load_config` instead.
... | 0.002757 |
def del_stmt(self, stmt_loc, exprs):
# Python uses exprlist here, but does *not* obey the usual
# tuple-wrapping semantics, so we embed the rule directly.
"""del_stmt: 'del' exprlist"""
return ast.Delete(targets=[self._assignable(expr, is_delete=True) for expr in exprs],
... | 0.015584 |
def _fixIndex(self, index, truncate=False):
"""
@param truncate: If true, negative indices which go past the
beginning of the list will be evaluated as zero.
For example::
>>> L = List([1,2,3,4,5])
>>> l... | 0.002608 |
def paint(self):
"""
Renders a javascript snippet suitable for use as a mapbox-gl fill paint entry
Returns:
A dict that can be converted to a mapbox-gl javascript paint snippet
"""
snippet = {
'fill-opacity': VectorStyle.get_style_value(self.opacity),
... | 0.008606 |
def paramiko_tunnel(lport, rport, server, remoteip='127.0.0.1', keyfile=None, password=None, timeout=60):
"""launch a tunner with paramiko in a subprocess. This should only be used
when shell ssh is unavailable (e.g. Windows).
This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
as ... | 0.005432 |
def stringify(element, newlines=True):
"""
Return the raw text version of an elements (and its children element).
Example:
>>> from panflute import *
>>> e1 = Emph(Str('Hello'), Space, Str('world!'))
>>> e2 = Strong(Str('Bye!'))
>>> para = Para(e1, Space, e2)
>>> st... | 0.001032 |
def which(program, environ=None):
"""
Find out if an executable exists in the supplied PATH.
If so, the absolute path to the executable is returned.
If not, an exception is raised.
:type string
:param program: Executable to be checked for
:param dict
:param environ: Any additional ENV ... | 0.001768 |
def delete(id):
"""Delete a post.
Ensures that the post exists and that the logged in user is the
author of the post.
"""
post = get_post(id)
db.session.delete(post)
db.session.commit()
return redirect(url_for("blog.index")) | 0.003891 |
def accel_ES(q: np.ndarray):
"""
Compute the gravitational accelerations in the earth-sun system.
q in row vector of 6 elements: sun (x, y, z), earth (x, y, z)
"""
# Number of celestial bodies
num_bodies: int = 2
# Number of dimensions in arrays; 3 spatial dimensions times the number of bod... | 0.004421 |
def buffer(self, item):
"""
Receive an item and write it.
"""
key = self.get_key_from_item(item)
if not self.grouping_info.is_first_file_item(key):
self.items_group_files.add_item_separator_to_file(key)
self.grouping_info.ensure_group_info(key)
self.it... | 0.00551 |
def find_bright_peaks(self, data, threshold=None, sigma=5, radius=5):
"""
Find bright peak candidates in (data). (threshold) specifies a
threshold value below which an object is not considered a candidate.
If threshold is blank, a default is calculated using (sigma).
(radius) de... | 0.002632 |
def run_jar(self, mem=None):
"""
Special case of run() when the executable is a JAR file.
"""
cmd = config.get_command('java')
if mem:
cmd.append('-Xmx%s' % mem)
cmd.append('-jar')
cmd += self.cmd
self.run(cmd) | 0.006993 |
def cli(ctx, email, first_name, last_name, password, role="user", metadata={}):
"""Create a new user
Output:
an empty dictionary
"""
return ctx.gi.users.create_user(email, first_name, last_name, password, role=role, metadata=metadata) | 0.007937 |
def add_resource_context(router: web.AbstractRouter,
url_prefix: str = None,
name_prefix: str = None) -> Iterator[Any]:
"""Context manager for adding resources for given router.
Main goal of context manager to easify process of adding resources with
routes ... | 0.000387 |
def top_comments(self):
"""Return a markdown representation of the top comments."""
num = min(10, len(self.comments))
if num <= 0:
return ''
top_comments = sorted(
self.comments, key=lambda x: (-x.score, str(x.author)))[:num]
retval = self.post_header.for... | 0.002999 |
def slug(self, language=None, fallback=True):
"""
Return the slug of the page depending on the given language.
:param language: wanted language, if not defined default is used.
:param fallback: if ``True``, the slug will also be searched in other \
languages.
"""
... | 0.004854 |
def max_posterior(lnps_per_walker, dim):
"""Burn in based on samples being within dim/2 of maximum posterior.
Parameters
----------
lnps_per_walker : 2D array
Array of values that are proportional to the log posterior values. Must
have shape ``nwalkers x niterations``.
dim : int
... | 0.000676 |
def _hab_s(s):
"""Define the boundary between Region 2a and 2b, h=f(s)
Parameters
----------
s : float
Specific entropy, [kJ/kgK]
Returns
-------
h : float
Specific enthalpy, [kJ/kg]
References
----------
IAPWS, Revised Supplementary Release on Backward Equatio... | 0.001086 |
def generate_hash(data: dict, token: str) -> str:
"""
Generate secret hash
:param data:
:param token:
:return:
"""
secret = hashlib.sha256()
secret.update(token.encode('utf-8'))
sorted_params = collections.OrderedDict(sorted(data.items()))
msg = '\n'.join("{}={}".format(k, v) fo... | 0.006479 |
def get_plugins() -> Dict[str, pkg_resources.EntryPoint]:
"""
Get all available plugins for unidown.
:return: plugin name list
:rtype: Dict[str, ~pkg_resources.EntryPoint]
"""
return {entry.name: entry for entry in pkg_resources.iter_entry_points('unidown.plugin')} | 0.009554 |
def get_cache_path(profile_name):
'''获取这个帐户的缓存目录, 如果不存在, 就创建它'''
path = os.path.join(CACHE_DIR, profile_name, 'cache')
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
return path | 0.00463 |
def create_access_token(self, request, credentials):
"""Create and save a new access token.
Similar to OAuth 2, indication of granted scopes will be included as a
space separated list in ``oauth_authorized_realms``.
:param request: OAuthlib request.
:type request: oauthlib.comm... | 0.002186 |
def translate(env, func, *args, **kwargs):
"""
Given a shellcode environment, a function and its parameters, translate
the function to a list of shellcode operations ready to be compiled or
assembled using :meth:`~pwnypack.shellcode.base.BaseEnvironment.compile`
or :meth:`~pwnypack.shellcode.base.Ba... | 0.001065 |
def create_index_table(environ, envdir):
''' create an html table
Parameters:
environ (dict):
A tree environment dictionary
envdir (str):
The filepath for the env directory
Returns:
An html table definition string
'''
table_header = """<table id=... | 0.003116 |
def temporarily_enabled(self):
"""
Temporarily enable the cache (useful for testing)
"""
old_setting = self.options.enabled
self.enable()
try:
yield
finally:
self.options.enabled = old_setting | 0.007353 |
def send_message(self, message):
"""Send chat message to this steam user
:param message: message to send
:type message: str
"""
self._steam.send(MsgProto(EMsg.ClientFriendMsg), {
'steamid': self.steam_id,
'chat_entry_type': EChatEntryType.ChatMsg,
... | 0.005348 |
def get_bookmark(self, bookmark_id):
"""
Get a single bookmark represented by `bookmark_id`.
The requested bookmark must belong to the current user.
:param bookmark_id: ID of the bookmark to retrieve.
"""
url = self._generate_url('bookmarks/{0}'.format(bookmark_id))
... | 0.005797 |
def plot(result_pickle_file_path, show, plot_save_file):
"""
[sys_analyser] draw result DataFrame
"""
import pandas as pd
from .plot import plot_result
result_dict = pd.read_pickle(result_pickle_file_path)
plot_result(result_dict, show, plot_save_file) | 0.003559 |
def _to_ned(self):
"""
Switches the reference frame to NED
"""
if self.ref_frame is 'USE':
# Rotate
return utils.use_to_ned(self.tensor), \
utils.use_to_ned(self.tensor_sigma)
elif self.ref_frame is 'NED':
# Alreadt NED
... | 0.003868 |
def _set_fill_word(self, v, load=False):
"""
Setter method for fill_word, mapped from YANG variable /interface/fc_port/fill_word (fc-fillword-cfg-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_fill_word is considered as a private
method. Backends looking to po... | 0.004373 |
def define_from_fits(cls, fitsobj, extnum=0):
"""Define class object from header information in FITS file.
Parameters
----------
fitsobj: file object
FITS file whose header contains the DTU information
needed to initialise the members of this class.
extnu... | 0.003484 |
def merged_args_dicts(global_args, subcommand_args):
'''We deal with docopt args from the toplevel peru parse and the subcommand
parse. We don't want False values for a flag in the subcommand to override
True values if that flag was given at the top level. This function
specifically handles that case.''... | 0.001565 |
def travis_build_package():
"""Assumed called on Travis, to prepare a package to be deployed
This method prints on stdout for Travis.
Return is obj to pass to sys.exit() directly
"""
travis_tag = os.environ.get('TRAVIS_TAG')
if not travis_tag:
print("TRAVIS_TAG environment variable is ... | 0.004386 |
def _main_loop(self):
'''
The internal while true main loop for the redis monitor
'''
self.logger.debug("Running main loop")
old_time = 0
while True:
for plugin_key in self.plugins_dict:
obj = self.plugins_dict[plugin_key]
self.... | 0.003205 |
def parse_datetime_range(time_filter):
"""
Parse the url param to python objects.
From what time range to divide by a.time.gap into intervals.
Defaults to q.time and otherwise 90 days.
Validate in API: re.search("\\[(.*) TO (.*)\\]", value)
:param time_filter: [2013-03-01 TO 2013-05-01T00:00:00]... | 0.003252 |
async def service_status(self, name):
"""Pull the current status of a service by name.
Returns:
dict: A dictionary of service status
"""
return await self.send_command(OPERATIONS.CMD_QUERY_STATUS, {'name': name},
MESSAGES.QueryStatusRe... | 0.011765 |
def _safe_squeeze(arr, *args, **kwargs):
"""
numpy.squeeze will reduce a 1-item array down to a zero-dimensional "array",
which is not necessarily desirable.
This function does the squeeze operation, but ensures that there is at least
1 dimension in the output.
"""
out = np.squeeze(arr, *arg... | 0.007407 |
def setFontStrikeOut(self, strikeOut):
"""
Sets whether or not this editor is currently striking out the text.
:param strikeOut | <bool>
"""
font = self.currentFont()
font.setStrikeOut(strikeOut)
self.setCurrentFont(font) | 0.010033 |
def make_setup_state(
self,
app: 'Quart',
first_registration: bool,
*,
url_prefix: Optional[str]=None,
) -> 'BlueprintSetupState':
"""Return a blueprint setup state instance.
Arguments:
first_registration: True if this is the f... | 0.011111 |
def handle_aggregated_quotas(sender, instance, **kwargs):
""" Call aggregated quotas fields update methods """
quota = instance
# aggregation is not supported for global quotas.
if quota.scope is None:
return
quota_field = quota.get_field()
# usage aggregation should not count another us... | 0.005568 |
def get_grammar(self):
"""
Returns the grammar of the UAI file.
"""
network_name = Word(alphas).setResultsName('network_name')
no_variables = Word(nums).setResultsName('no_variables')
grammar = network_name + no_variables
self.no_variables = int(grammar.parseStrin... | 0.007181 |
def delete_pipeline(app='', pipeline_name=''):
"""Delete _pipeline_name_ from _app_."""
safe_pipeline_name = normalize_pipeline_name(name=pipeline_name)
LOG.warning('Deleting Pipeline: %s', safe_pipeline_name)
url = '{host}/pipelines/{app}/{pipeline}'.format(host=API_URL, app=app, pipeline=safe_pipeli... | 0.007099 |
def main_btn_clicked(self, widget, data=None):
"""
Button switches to Dev Assistant GUI main window
"""
self.remove_link_button()
data = dict()
data['debugging'] = self.debugging
self.run_window.hide()
self.parent.open_window(widget, data) | 0.006601 |
def create_cloud(self):
"""
Create instances for the cloud providers
"""
instances = []
for i in range(self.settings['NUMBER_NODES']):
new_instance = Instance.new(settings=self.settings, cluster=self)
instances.append(new_instance)
create_nodes = ... | 0.00375 |
def _print_figures(figures, arguments='', file_format='pdf', target_width=8.5, target_height=11.0, target_pad=0.5):
"""
figure printing loop designed to be launched in a separate thread.
"""
for fig in figures:
# get the temp path
temp_path = _os.path.join(_settings.path_home, "temp")
... | 0.003973 |
def update_redirect_to_from_json(page, redirect_to_complete_slugs):
"""
The second pass of create_and_update_from_json_data
used to update the redirect_to field.
Returns a messages list to be appended to the messages from the
first pass.
"""
messages = []
s = ''
for lang, s in list(... | 0.003125 |
def ahrs2_send(self, roll, pitch, yaw, altitude, lat, lng, force_mavlink1=False):
'''
Status of secondary AHRS filter if available
roll : Roll angle (rad) (float)
pitch : Pitch angle (rad) (float)
y... | 0.006757 |
def parse_type_comment(type_comment):
"""Parse a type comment string into AST nodes."""
try:
result = ast3.parse(type_comment, '<type_comment>', 'eval')
except SyntaxError:
raise ValueError(f"invalid type comment: {type_comment!r}") from None
assert isinstance(result, ast3.Expression)
... | 0.002933 |
def remove_bounding_box(self, loc=None):
"""
Removes bounding box from the active renderer.
Parameters
----------
loc : int, tuple, or list
Index of the renderer to add the actor to. For example,
``loc=2`` or ``loc=(1, 1)``. If None, selects the last
... | 0.003839 |
def excel_key(index):
"""create a key for index by converting index into a base-26 number, using A-Z as the characters."""
X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''
return X(int(index)) | 0.013761 |
def initialize_gdt_x86(self,state,concrete_target):
"""
Create a GDT in the state memory and populate the segment registers.
Rehook the vsyscall address using the real value in the concrete process memory
:param state: state which will be modified
:param concrete_t... | 0.009747 |
def write_java_message(key,val,text_file):
"""
Loop through all java messages that are not associated with a unit test and
write them into a log file.
Parameters
----------
key : str
9.general_bad_java_messages
val : list of list of str
contains the bad java messages and th... | 0.00361 |
def inverse_distance_to_points(points, values, xi, r, gamma=None, kappa=None, min_neighbors=3,
kind='cressman'):
r"""Generate an inverse distance weighting interpolation to the given points.
Values are assigned to the given interpolation points based on either [Cressman1959]_ or
... | 0.002761 |
def _clean_isbn(isbn):
"""
Remove all non-digit and non "x" characters from given string.
Args:
isbn (str): isbn string, which will be cleaned.
Returns:
list: array of numbers (if "x" is found, it is converted to 10).
"""
if isinstance(isbn, basestring):
isbn = list(isb... | 0.001938 |
def _traverse_nodes(self):
""" Debugging function (exposes cython nodes as dummy nodes) """
node = self.root
stack = []
while stack or node is not None:
if node is not None:
stack.append(node)
node = node.left
else:
... | 0.005013 |
def get_attribute_classes() -> Dict[str, Attribute]:
"""
Lookup all builtin Attribute subclasses, load them, and return a dict
"""
attribute_children = pkgutil.iter_modules(
importlib.import_module('jawa.attributes').__path__,
prefix='jawa.attributes.'
)
result = {}
for _, n... | 0.001302 |
def get_stats(self):
"""Retrieves the bus statistics.
Use like so:
>>> stats = bus.get_stats()
>>> print(stats)
std_data: 0, std_remote: 0, ext_data: 0, ext_remote: 0, err_frame: 0, bus_load: 0.0%, overruns: 0
:returns: bus statistics.
:rtype: can.interfaces.kv... | 0.004785 |
def _get_config(self, host, port, unix_socket, auth, config_key):
"""Return config string from specified Redis instance and config key
:param str host: redis host
:param int port: redis port
:param str host: redis config_key
:rtype: str
"""
client = self._client(host, port, unix_socket, auth)... | 0.004237 |
def verified(self, institute_id):
"""Return all verified variants for a given institute
Args:
institute_id(str): institute id
Returns:
res(list): a list with validated variants
"""
query = {
'verb' : 'validate',
'institute' : inst... | 0.009018 |
def _set_client(self, v, load=False):
"""
Setter method for client, mapped from YANG variable /rbridge_id/ssh/client (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_client is considered as a private
method. Backends looking to populate this variable shoul... | 0.006135 |
def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source
else:
stream = BytesIO(source)
t... | 0.006316 |
def _get_columns(self, blueprint):
"""
Get the blueprint's columns definitions.
:param blueprint: The blueprint
:type blueprint: Blueprint
:rtype: list
"""
columns = []
for column in blueprint.get_added_columns():
sql = self.wrap(column) + '... | 0.004505 |
def stop_serving(self):
"""Stop the serving container.
The serving container runs in async mode to allow the SDK to do other tasks.
"""
if self.container:
self.container.down()
self.container.join()
self._cleanup()
# for serving we can delete ... | 0.007595 |
def auto_correlation(sequence):
"""
test for the autocorrelation of a sequence between t and t - 1
as the 'auto_correlation' it is less likely that the sequence is
generated randomly.
:param sequence: any iterable with at most 2 values that can be turned
into a float via np.floa... | 0.000891 |
def _parse(value, strict=True):
"""
Preliminary duration value parser
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values
"""
pattern = r'(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)'
match = re.match(pattern, ... | 0.001572 |
def _call_marginalizevlos(self,o,integrate_method='dopr54_c',**kwargs):
"""Call the DF, marginalizing over line-of-sight velocity"""
#Get d, l, vperp
l= o.ll(obs=[1.,0.,0.],ro=1.)*_DEGTORAD
vperp= o.vll(ro=1.,vo=1.,obs=[1.,0.,0.,0.,0.,0.])
R= o.R(use_physical=False)
phi= ... | 0.02644 |
def list_uncollated_submission_versions(self, course_id, ascending=None, assignment_id=None, user_id=None):
"""
List uncollated submission versions.
Gives a paginated, uncollated list of submission versions for all matching
submissions in the context. This SubmissionVersion objects... | 0.004278 |
def abort(self, exception=exc.ConnectError):
"""
Aborts a connection and puts all pending futures into an error state.
If ``sys.exc_info()`` is set (i.e. this is being called in an exception
handler) then pending futures will have that exc info set. Otherwise
the given ``except... | 0.002584 |
def get_agent_queues(self, project=None, queue_name=None, action_filter=None):
"""GetAgentQueues.
[Preview API] Get a list of agent queues.
:param str project: Project ID or project name
:param str queue_name: Filter on the agent queue name
:param str action_filter: Filter by whe... | 0.006324 |
def list_settings(self):
"""
Get list of all appropriate settings and their default values.
"""
result = super().list_settings()
result.append((self.SETTING_TEXT_HIGHLIGHT, None))
return result | 0.008299 |
def _search_ldap(self, ldap, con, username):
"""
Searches LDAP for user, assumes ldap_search is set.
:param ldap: The ldap module reference
:param con: The ldap connection
:param username: username to match with auth_ldap_uid_field
:return: ldap objec... | 0.001748 |
def main(_):
"""Convert a file to examples."""
if FLAGS.subword_text_encoder_filename:
encoder = text_encoder.SubwordTextEncoder(
FLAGS.subword_text_encoder_filename)
elif FLAGS.token_text_encoder_filename:
encoder = text_encoder.TokenTextEncoder(FLAGS.token_text_encoder_filename)
elif FLAGS.byt... | 0.012716 |
def setAccelerometerSensitivity(self, value):
"""
Sets the accelerometer sensitivity to 2, 4, 8 or 16 according to the given value. Throws an ArgumentError if
the value provided is not valid.
:param value: the target sensitivity.
"""
# note that this implicitly disables t... | 0.004918 |
def load_ui_wrapper(uifile, base_instance=None):
"""Load a Qt Designer .ui file and returns an instance of the user interface
Args:
uifile (str): Absolute path to .ui file
base_instance (QWidget): The widget into which UI widgets are loaded
Returns:
function: pyside_load_ui or uic.... | 0.003623 |
def parse_cookies(self, req, name, field):
"""Pull the value from the cookiejar."""
return core.get_value(req.cookies, name, field) | 0.013605 |
def connect(self):
'initialize ldap connection and set options'
log.debug("Connecting to ldap server %s" % self.config['URI'])
self.conn = ldap.initialize(self.config['URI'])
# There are some settings that can't be changed at runtime without a context restart.
# It's possible to... | 0.005034 |
def print_projects(self, projects):
"""Print method for projects.
"""
for project in projects:
print('{}: {}'.format(project.name, project.id)) | 0.011173 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'score') and self.score is not None:
_dict['score'] = self.score
if hasattr(self, 'sentence') and self.sentence is not None:
_dict['sentence'] = self.sentence
... | 0.003454 |
def preview_filter_from_query(query, id_field="id", field_map={}):
"""This filter includes the "excluded_ids" so they still show up in the editor."""
f = groups_filter_from_query(query, field_map=field_map)
# NOTE: we don't exclude the excluded ids here so they show up in the editor
# include these, ple... | 0.005894 |
def from_p12_keyfile(cls, service_account_email, filename,
private_key_password=None, scopes='',
token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
"""Factory constructor from JSON keyfile.
Arg... | 0.002887 |
def create(ctx):
""" Create default config file
"""
import shutil
this_dir, this_filename = os.path.split(__file__)
default_config_file = os.path.join(this_dir, "apis/example-config.yaml")
config_file = ctx.obj["configfile"]
shutil.copyfile(default_config_file, config_file)
print_messag... | 0.002717 |
def clean_email(self):
""" Validate that the e-mail address is unique. """
if get_user_model().objects.filter(email__iexact=self.cleaned_data['email']):
if userena_settings.USERENA_ACTIVATION_REQUIRED and UserenaSignup.objects.filter(user__email__iexact=self.cleaned_data['email']).exclude(ac... | 0.009009 |
def oneup(self, window_name, object_name, iterations):
"""
Press scrollbar up with number of iterations
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type... | 0.00159 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.