text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def fcoe_get_login_input_fcoe_login_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_login = ET.Element("fcoe_get_login")
config = fcoe_get_login
input = ET.SubElement(fcoe_get_login, "input")
fcoe_login_rbridge_id = ET... | 0.003795 |
def interval(self, T=[0, 1000]):
"""
Get all spikes in a time interval T.
Parameters
----------
T : list
Time interval.
Returns
-------
s : list
Nested list with spike times.
See also
--------
sqlite3.... | 0.007952 |
def get_entry(self, entry_name, key):
"""Returns cache entry parameter value by its name.
:param str|unicode entry_name:
:param key:
:return:
"""
return self.cache[entry_name].get(key, False) | 0.008333 |
def get_height(self, id=None, endpoint=None):
"""
Get the current height of the blockchain
Args:
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Returns:
json object of the result or the... | 0.004505 |
def reload_core(host=None, core_name=None):
'''
MULTI-CORE HOSTS ONLY
Load a new core from the same configuration as an existing registered core.
While the "new" core is initializing, the "old" one will continue to accept
requests. Once it has finished, all new request will go to the "new" core,
... | 0.001239 |
def get_initial(self):
"""
Returns a copy of `initial` with empty initial data dictionaries for each form.
"""
initial = super(MultiFormView, self).get_initial()
for key in six.iterkeys(self.form_classes):
initial[key] = {}
return initial | 0.010067 |
def do_diff(self, subcmd, opts, *args):
"""Display the differences between two paths.
usage:
1. diff [-r N[:M]] [TARGET[@REV]...]
2. diff [-r N[:M]] --old=OLD-TGT[@OLDREV] [--new=NEW-TGT[@NEWREV]] \
[PATH...]
3. diff OLD-URL[@OLDREV] NEW-URL[@NEWR... | 0.007838 |
def load_writer(writer, ppp_config_dir=None, **writer_kwargs):
"""Find and load writer `writer` in the available configuration files."""
if ppp_config_dir is None:
ppp_config_dir = get_environ_config_dir()
config_fn = writer + ".yaml" if "." not in writer else writer
config_files = config_searc... | 0.001124 |
def _handleSelectAllAxes(self, evt):
"""Called when the 'select all axes' menu item is selected."""
if len(self._axisId) == 0:
return
for i in range(len(self._axisId)):
self._menu.Check(self._axisId[i], True)
self._toolbar.set_active(self.getActiveAxes())
... | 0.006061 |
def to_index_variable(self):
"""Return this variable as an xarray.IndexVariable"""
return IndexVariable(self.dims, self._data, self._attrs,
encoding=self._encoding, fastpath=True) | 0.008929 |
def script_file(self):
"""
Returns the startup script file for this VPCS VM.
:returns: path to startup script file
"""
# use the default VPCS file if it exists
path = os.path.join(self.working_dir, 'startup.vpc')
if os.path.exists(path):
return path
... | 0.005602 |
def list_all(course, single=None):
"""
Lists all of the exercises in the current course.
"""
def bs(val):
return "●" if val else " "
def bc(val):
return as_success("✔") if val else as_error("✘")
def format_line(exercise):
return "{0} │ {1} │ {2} │ {3} │ {4}".format(exe... | 0.001094 |
def after(self, context):
"Invokes all after functions with context passed to them."
self._invoke(self._after, context)
run.after_each.execute(context) | 0.011429 |
def get_dirname(self, index):
"""Return dirname associated with *index*"""
fname = self.get_filename(index)
if fname:
if osp.isdir(fname):
return fname
else:
return osp.dirname(fname) | 0.007407 |
def _build_iterable_validator(iterable):
"""Build a validator from an iterable."""
sub_schemas = [parse_schema(s) for s in iterable]
def item_validator(value):
"""Validate items in an iterable."""
for sub in sub_schemas:
try:
return sub(value)
except... | 0.001376 |
def _tupleCompare(tuple1, ineq, tuple2,
eq=lambda a,b: (a==b),
ander=AND,
orer=OR):
"""
Compare two 'in-database tuples'. Useful when sorting by a compound key
and slicing into the middle of that query.
"""
orholder = []
for limit in range(len... | 0.010221 |
def request_data_stream_encode(self, target_system, target_component, req_stream_id, req_message_rate, start_stop):
'''
THIS INTERFACE IS DEPRECATED. USE SET_MESSAGE_INTERVAL INSTEAD.
target_system : The target requested to send the message stream. (uint8_t)
... | 0.010651 |
def stop(self) -> None:
"""
Stop the :class:`~lahja.endpoint.Endpoint` from receiving further events.
"""
if not self._running:
return
self._running = False
self._receiving_queue.put_nowait((TRANSPARENT_EVENT, None))
self._internal_queue.put_nowait((T... | 0.008721 |
def bind_socket(sock, channel='can0'):
"""
Binds the given socket to the given interface.
:param socket.socket sock:
The socket to be bound
:raises OSError:
If the specified interface isn't found.
"""
log.debug('Binding socket to channel=%s', channel)
if HAS_NATIVE_SUPPORT:
... | 0.001984 |
def run(self, *args, **kwargs):
"""Start genesis
:returns: None
:rtype: None
:raises: None
"""
if self.win:
self.win.deleteLater()
mayawin = maya_main_window()
self.win = ReftrackWin(self.inter, parent=mayawin)
self.win.destroyed.conne... | 0.005051 |
def get_function_hash(self, func, args=None, kwargs=None, ttl=None, key=None, noc=None):
"""Compute the hash of the function to be evaluated.
"""
base_hash = settings.HASH_FUNCTION()
if PY3:
base_hash.update(func.__name__.encode(settings.DEFAULT_ENCODING))
else:
... | 0.003072 |
def set_mt_wcs(self, image):
""" Reset the WCS for this image based on the WCS information from
another imageObject.
"""
for chip in range(1,self._numchips+1,1):
sci_chip = self._image[self.scienceExt,chip]
ref_chip = image._image[image.scienceExt,chip]
... | 0.013636 |
def request(self, hash_, quickkey, doc_type, page=None,
output=None, size_id=None, metadata=None,
request_conversion_only=None):
"""Query conversion server
hash_: 4 characters of file hash
quickkey: File quickkey
doc_type: "i" for image, "d" for documents... | 0.002506 |
def parse_plist(self, preferences_file):
"""Try to reset preferences from preference_file."""
preferences_file = os.path.expanduser(preferences_file)
# Try to open using FoundationPlist. If it's not available,
# fall back to plistlib and hope it's not binary encoded.
try:
... | 0.001351 |
def save_named_query(self, alias, querystring, afterwards=None):
"""
add an alias for a query string.
These are stored in the notmuch database and can be used as part of
more complex queries using the syntax "query:alias".
See :manpage:`notmuch-search-terms(7)` for more info.
... | 0.002571 |
def _rnd_datetime(self, start, end):
"""Internal random datetime generator.
"""
return self.from_utctimestamp(
random.randint(
int(self.to_utctimestamp(start)),
int(self.to_utctimestamp(end)),
)
) | 0.007042 |
def get_products(self, latitude, longitude):
"""Get information about the Uber products offered at a given location.
Parameters
latitude (float)
The latitude component of a location.
longitude (float)
The longitude component of a location.
... | 0.003221 |
def read(self, size=sys.maxsize):
"""Read at most size bytes from the file (less if the read hits EOF
before obtaining size bytes).
"""
blob_size = int(self.blob_properties.get('content-length'))
if self._pointer < blob_size:
chunk = self._download_chunk_with_retries(... | 0.004545 |
def _get_positions_to_highlight(self, document):
"""
Return a list of (row, col) tuples that need to be highlighted.
"""
# Try for the character under the cursor.
if document.current_char and document.current_char in self.chars:
pos = document.find_matching_bracket_po... | 0.005751 |
def _validate(self, data: Any, schema: AnyMapping) -> Any:
"""Validate data against given schema.
:param data: Data to validate.
:param schema: Schema to use for validation.
"""
try:
return self.validate_func(schema, self._pure_data(data))
except self.validat... | 0.003067 |
def _create(self, monomer, mon_vector):
"""
create the polymer from the monomer
Args:
monomer (Molecule)
mon_vector (numpy.array): molecule vector that starts from the
start atom index to the end atom index
"""
while self.length != (self.n... | 0.005 |
def token(self):
"""
Returns authorization token provided by Cocaine.
The real meaning of the token is determined by its type. For example OAUTH2 token will
have "bearer" type.
:return: A tuple of token type and body.
"""
if self._token is None:
toke... | 0.006036 |
def sort(self):
"""Sort by commit size, per author."""
# First sort commits by author email
users = []
# Group commits by author email, so they can be merged
for _, group in itertools.groupby(sorted(self.commits),
operator.attrgetter('aut... | 0.00292 |
def substitutes(self):
""" Return the substitutions for the templating replacements. """
author_collector = AuthorCollector()
substitute_dict = dict(
project = self.project_name,
date = date.today().isoformat(),
author = author_collector.collect()
)
... | 0.022989 |
def execute(self):
"""
params = {
"ApexCode" : "None",
"ApexProfiling" : "01pd0000001yXtYAAU",
"Callout" : True,
"Database" : 1,
"ExpirationDate" : 3,
"ScopeId" ... | 0.003655 |
def inc_convert(self, value):
"""Default converter for the inc:// protocol."""
if not os.path.isabs(value):
value = os.path.join(self.base, value)
with codecs.open(value, 'r', encoding='utf-8') as f:
result = json.load(f)
return result | 0.006873 |
def _post_query(self, **query_dict):
"""Perform a POST query against Solr and return the response as a Python
dict."""
param_dict = query_dict.copy()
return self._send_query(do_post=True, **param_dict) | 0.012876 |
def linearize_aliases(self):
# type: () -> typing.List[Alias]
"""
Returns a list of all aliases used in the namespace. The aliases are
ordered to ensure that if they reference other aliases those aliases
come earlier in the list.
"""
linearized_aliases = []
... | 0.003623 |
def get_reader_input_fn(train_config, preprocess_output_dir, model_type,
data_paths, batch_size, shuffle, num_epochs=None):
"""Builds input layer for training."""
def get_input_features():
"""Read the input features from the given data paths."""
_, examples = util.read_examples(
... | 0.004721 |
def load(self, dbfile, password=None, keyfile=None, readonly=False):
"""
Load the database from file/stream.
:param dbfile: The database file path/stream.
:type dbfile: str or file-like object
:param password: The password for the database.
:type password: str
... | 0.009002 |
def String(self, str):
"""Get an interned string from the reader, allows for example
to speedup string name comparisons """
ret = libxml2mod.xmlTextReaderConstString(self._o, str)
return ret | 0.008889 |
def semaphore(branch: str):
"""
Performs necessary checks to ensure that the semaphore build is successful,
on the correct branch and not a pull-request.
:param branch: The branch the environment should be running against.
"""
assert os.environ.get('BRANCH_NAME') == branch
assert os.enviro... | 0.002375 |
def is_ancestor_of_family(self, id_, family_id):
"""Tests if an ``Id`` is an ancestor of a family.
arg: id (osid.id.Id): an ``Id``
arg: family_id (osid.id.Id): the ``Id`` of a family
return: (boolean) - ``true`` if this ``id`` is an ancestor of
``family_id,`` ``fa... | 0.003802 |
def get(self, key):
"""
Retrieve the decrypted value of a key in a giraffez
configuration file.
:param str key: The key used to lookup the encrypted value
"""
if not key.startswith("secure.") and not key.startswith("connections."):
key = "secure.{0}".format(k... | 0.00655 |
def run(self):
"""Run the sync.
Confront the local and the remote directories and perform the needed changes."""
# Check if remote path is present
try:
self.sftp.stat(self.remote_path)
except FileNotFoundError as e:
if self.create_remote_directory:
... | 0.003478 |
def get_analysis_config(self, group_name):
""" Gets any config data saved for the analysis.
:param group_name: The name of the analysis group.
:returns: A dictionary of dictionaries. Each key represents
an analysis step. Each value is a dictionary containing the
analysis... | 0.003053 |
def render_js_template(self, template_path, element_id, context=None):
"""
Render a js template.
"""
context = context or {}
return u"<script type='text/template' id='{}'>\n{}\n</script>".format(
element_id,
self.render_template(template_path, context)
... | 0.006135 |
def _parse_nested(self, name, results):
"""
Parse the nested relationship in a relation.
:param name: The name of the relationship
:type name: str
:type results: dict
:rtype: dict
"""
progress = []
for segment in name.split('.'):
pr... | 0.003861 |
def init(self, key_value_pairs=None, **kwargs):
"""Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore.
:rtype: Iterable[tornado.concurrent.Future]
... | 0.003846 |
def unwrap_arguments(xml_response):
"""Extract arguments and their values from a SOAP response.
Args:
xml_response (str): SOAP/xml response text (unicode,
not utf-8).
Returns:
dict: a dict of ``{argument_name: value}`` items.
"""
# A UP... | 0.000928 |
def wantFunction(self, function):
"""Is the function a test function?
"""
try:
if hasattr(function, 'compat_func_name'):
funcname = function.compat_func_name
else:
funcname = function.__name__
except AttributeError:
# no... | 0.002594 |
def getLogicalDisplayInfo(self):
'''
Gets C{mDefaultViewport} and then C{deviceWidth} and C{deviceHeight} values from dumpsys.
This is a method to obtain display logical dimensions and density
'''
self.__checkTransport()
logicalDisplayRE = re.compile(
'.*Disp... | 0.00766 |
def to_sql(self, conn, table_name, dbapi_module=None,
use_python_type_specifiers=False, use_exact_column_names=True):
"""
Convert an SFrame to a single table in a SQL database.
This function does not attempt to create the table or check if a table
named `table_name` exists i... | 0.008627 |
def assemble_transcripts(run_parallel, samples):
"""
assembly strategy rationale implemented as suggested in
http://www.nature.com/nprot/journal/v7/n3/full/nprot.2012.016.html
run Cufflinks in without a reference GTF for each individual sample
merge the assemblies with Cuffmerge using a reference G... | 0.001121 |
def _setHeaders(self, call = None, **kwargs):
'''
Attach particular SOAP headers to the request depending on the method call made
'''
# All calls, including utility calls, set the session header
headers = {'SessionHeader': self._sessionHeader}
if 'debug_categories' in kwargs:
#ERROR, WARN... | 0.008053 |
def _send_to_group(self, group, **kwargs):
""" You shouldn't use this method directly.
Send a single command to specific group.
Handles automatically sending command to white or rgbw group.
"""
retries = kwargs.get("retries", self.repeat_commands)
for _ in range(retries... | 0.003837 |
def normalize_name(name):
'''
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. cod... | 0.001328 |
def set_domain(clz, dag):
""" Sets the domain. Should only be called once per class instantiation. """
logging.info("Setting domain for poset %s" % clz.__name__)
if nx.number_of_nodes(dag) == 0:
raise CellConstructionFailure("Empty DAG structure.")
if not nx.is_... | 0.007092 |
def _get(self, k, obj=None):
'Return Option object for k in context of obj. Cache result until any set().'
opt = self._cache.get((k, obj), None)
if opt is None:
opt = self._opts._get(k, obj)
self._cache[(k, obj or vd.sheet)] = opt
return opt | 0.010101 |
def outputSimple(self):
"""
Simple output mode
"""
out = []
errors = []
successfulResponses = \
len([True for rsp in self.results if rsp['success']])
out.append("INFO QUERIED {0}".format(
len(self.serverList)))
out.append("INFO S... | 0.002049 |
def hl_canvas2table_box(self, canvas, tag):
"""Highlight all masks inside user drawn box on table."""
self.treeview.clear_selection()
# Remove existing box
cobj = canvas.get_object_by_tag(tag)
if cobj.kind != 'rectangle':
return
canvas.delete_object_by_tag(ta... | 0.001538 |
def router_fabric_virtual_gateway_address_family_ipv4_accept_unicast_arp_request(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
router = ET.SubElement(config, "router", xmlns="urn:brocade.com:mgmt:brocade-common-def")
fabric_virtual_gateway = ET.SubElem... | 0.009682 |
def import_module_with_exceptions(name, package=None):
"""Wrapper around importlib.import_module to import TimeSide subpackage
and ignoring ImportError if Aubio, Yaafe and Vamp Host are not available"""
from timeside.core import _WITH_AUBIO, _WITH_YAAFE, _WITH_VAMP
if name.count('.server.'):
#... | 0.002632 |
def captchaform(field_name):
"""Decorator to add a simple captcha to a form
To use this decorator, you must specify the captcha field's name as an
argument to the decorator. For example:
@captchaform('captcha')
class MyForm(Form):
pass
This would add a new form field named 'captcha' t... | 0.001437 |
def plugin_is_enabled(name, runas=None):
'''
Return whether the plugin is enabled.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.plugin_is_enabled rabbitmq_plugin_name
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
r... | 0.00277 |
def layout(request, ident, stateless=False, cache_id=None, **kwargs):
'Return the layout of the dash application'
_, app = DashApp.locate_item(ident, stateless)
view_func = app.locate_endpoint_function('dash-layout')
resp = view_func()
initial_arguments = get_initial_arguments(request, cache_id)
... | 0.004107 |
def user(self):
"""
Returns the current user set by current context
"""
return self.users.get(self.contexts[self.current_context].get("user", ""), {}) | 0.016484 |
def get_template_names(self):
"""
datagrid的默认模板
"""
names = super(CommandDatagridView, self).get_template_names()
names.append('easyui/command_datagrid.html')
return names | 0.009132 |
def resource_collection_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/resource_collections#create-a-resource-collection"
api_path = "/api/v2/resource_collections.json"
return self.call(api_path, method="POST", data=data, **kwargs) | 0.010417 |
def paired_reader_from_bamfile(args,
log,
usage_logger,
annotated_writer):
'''Given a BAM file, return a generator that yields filtered, paired reads'''
total_aligns = pysamwrapper.total_align_count(args.input_bam)
... | 0.004854 |
def get_results(self, hql, schema='default', fetch_size=None, hive_conf=None):
"""
Get results of the provided hql in target schema.
:param hql: hql to be executed.
:type hql: str or list
:param schema: target schema, default to 'default'.
:type schema: str
:para... | 0.004415 |
def valid_daily_max_temperature(comp, units='K'):
r"""Decorator to check that a computation runs on a valid temperature dataset."""
@wraps(comp)
def func(tasmax, *args, **kwds):
check_valid_temperature(tasmax, units)
check_valid(tasmax, 'cell_methods', 'time: maximum within days')
r... | 0.005405 |
def browse(self):
''' Browse the history of a single file
adds one commit that doesn't contain changes in test_file_1.
there are four commits in summary, so the check for buffer line
count compares with 3.
at the end, a fifth commit must be present due to resetting the
fi... | 0.001961 |
def get_temp_dimname(dims: Container[Hashable], new_dim: Hashable) -> Hashable:
""" Get an new dimension name based on new_dim, that is not used in dims.
If the same name exists, we add an underscore(s) in the head.
Example1:
dims: ['a', 'b', 'c']
new_dim: ['_rolling']
-> ['_rolling... | 0.001908 |
def getresponse(self):
"""Get the response from the server.
If the HTTPConnection is in the correct state, returns an
instance of HTTPResponse or of whatever object is returned by
class the response_class variable.
If a request has not been sent or if a previous response has
... | 0.000874 |
def unparse(text, entities):
"""
Performs the reverse operation to .parse(), effectively returning HTML
given a normal text and its MessageEntity's.
:param text: the text to be reconverted into HTML.
:param entities: the MessageEntity's applied to the text.
:return: a HTML representation of the... | 0.000421 |
def correct_bitstring_probs(p, assignment_probabilities):
"""
Given a 2d array of corrupted bitstring probabilities (outer axis iterates over shots, inner
axis over bits) and a list of assignment probability matrices (one for each bit in the readout)
compute the corrected probabilities.
:param np.a... | 0.009302 |
def _run_cell_text(self, text, line):
"""Run cell code in the console.
Cell code is run in the console by copying it to the console if
`self.run_cell_copy` is ``True`` otherwise by using the `run_cell`
function.
Parameters
----------
text : str
... | 0.00201 |
def delete_user_entitlements(self, user_id):
"""DeleteUserEntitlements.
[Preview API]
:param str user_id:
"""
route_values = {}
if user_id is not None:
route_values['userId'] = self._serialize.url('user_id', user_id, 'str')
self._send(http_method='DELE... | 0.006186 |
def parse_traceback(msg, site_path="site-packages", in_app_prefix="c7n"):
"""Extract a sentry traceback structure,
From a python formatted traceback string per python stdlib
traceback.print_exc()
"""
data = {}
lines = list(filter(None, msg.split('\n')))
data['frames'] = []
err_ctx = No... | 0.002647 |
def movies_opening(self, **kwargs):
"""Gets the current opening movies from the API.
Args:
limit (optional): limits the number of movies returned, default=10
country (optional): localized data for selected country, default="us"
Returns:
A dict respresentation of t... | 0.003831 |
def _change_volume(self, increase):
"""Change volume using amixer
"""
sign = "+" if increase else "-"
delta = "%d%%%s" % (self.volume_tick, sign)
self._run(["amixer", "-q", "sset", "Master", delta]) | 0.008403 |
def assign_taxonomy(
data, min_confidence=0.80, output_fp=None, training_data_fp=None,
fixrank=True, max_memory=None, tmp_dir=tempfile.gettempdir()):
"""Assign taxonomy to each sequence in data with the RDP classifier
data: open fasta file object or list of fasta lines
confidence: m... | 0.00037 |
def vcsNodeState_originator_switch_info_switchIpV6Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcsNodeState = ET.SubElement(config, "vcsNodeState", xmlns="urn:brocade.com:mgmt:brocade-vcs")
originator_switch_info = ET.SubElement(vcsNodeState, ... | 0.008503 |
def get_num_shards(num_samples: int, samples_per_shard: int, min_num_shards: int) -> int:
"""
Returns the number of shards.
:param num_samples: Number of training data samples.
:param samples_per_shard: Samples per shard.
:param min_num_shards: Minimum number of shards.
:return: Number of shard... | 0.004878 |
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Generic Output Location Read from File Method
"""
# Assign file extension attribute to file object
self.fileExtension = extension
# Open file and pars... | 0.003409 |
def paragraphs(self):
"""
Immutable sequence of |_Paragraph| instances corresponding to the
paragraphs in this text frame. A text frame always contains at least
one paragraph.
"""
return tuple([_Paragraph(p, self) for p in self._txBody.p_lst]) | 0.006873 |
def verify_sig(signed_request, secret, issuer=None, algorithms=None,
expected_aud=None):
"""
Verify the JWT signature.
Given a raw JWT, this verifies it was signed with
*secret*, decodes it, and returns the JSON dict.
"""
if not issuer:
issuer = _get_issuer(signed_request... | 0.001143 |
def _Region2(T, P):
"""Basic equation for region 2
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
Returns
-------
prop : dict
Dict with calculated properties. The available properties are:
* v: Specific volume, [m³/kg]
... | 0.000244 |
def load_and_check(self, base_settings, prompt=None):
"""Load settings and check them.
Loads the settings from ``base_settings``, then checks them.
Returns:
(merged settings, True) on success
(None, False) on failure
"""
checker = Checker(self.file_name... | 0.00578 |
def _init_a(D):
'''Initial guess for Dirichlet alpha parameters given data D'''
E = D.mean(axis=0)
E2 = (D**2).mean(axis=0)
return ((E[0] - E2[0])/(E2[0]-E[0]**2)) * E | 0.005464 |
def _create_rubber_bands_action(self):
"""Create action for toggling rubber bands."""
icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')
self.action_toggle_rubberbands = QAction(
QIcon(icon),
self.tr('Toggle Scenario Outlines'), self.iface.mainWindow())
... | 0.002144 |
def random_tree(n_leaves):
"""
Randomly partition the nodes
"""
def _random_subtree(leaves):
if len(leaves) == 1:
return leaves[0]
elif len(leaves) == 2:
return (leaves[0], leaves[1])
else:
split = npr.randint(1, len(leaves)-1)
retu... | 0.002183 |
def _try_assign_utc_time(self, raw_time, time_base):
"""Try to assign a UTC time to this reading."""
# Check if the raw time is encoded UTC since y2k or just uptime
if raw_time != IOTileEvent.InvalidRawTime and (raw_time & (1 << 31)):
y2k_offset = self.raw_time ^ (1 << 31)
... | 0.003899 |
def search_users(self, username_keyword, limit=10):
"""
Searches for users whose username matches ``username_keyword``, and returns
a list of matched users.
:param str username_keyword: keyword to search with
:param int limit: maximum number of returned users
:return: a ... | 0.006812 |
def is_course_run_upgradeable(course_run):
"""
Return true if the course run has a verified seat with an unexpired upgrade deadline, false otherwise.
"""
now = datetime.datetime.now(pytz.UTC)
for seat in course_run.get('seats', []):
if seat.get('type') == 'verified':
upgrade_dead... | 0.006397 |
def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False):
"""Parses the sections in the memory and returns a list of them"""
sections = []
optional_header_offset = imageDosHeader.header.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER)
offset = optional_header_offs... | 0.007105 |
def _contains_policies(self, resource_properties):
"""
Is there policies data in this resource?
:param dict resource_properties: Properties of the resource
:return: True if we can process this resource. False, otherwise
"""
return resource_properties is not None \
... | 0.004587 |
def aggregate_weights(weights, drop_date=False):
"""
Transforms list of tuples of weights into pandas.DataFrame of weights.
Parameters:
-----------
weights: list
A list of tuples consisting of the generic instrument name,
the tradeable contract as a string, the weight on this contra... | 0.000935 |
def almost_equal(f: DataFrame, g: DataFrame) -> bool:
"""
Return ``True`` if and only if the given DataFrames are equal after
sorting their columns names, sorting their values, and
reseting their indices.
"""
if f.empty or g.empty:
return f.equals(g)
else:
# Put in canonical ... | 0.001608 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.