text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def OnChar(self, event):
""" on Character event"""
key = event.GetKeyCode()
entry = wx.TextCtrl.GetValue(self).strip()
pos = wx.TextCtrl.GetSelection(self)
# really, the order here is important:
# 1. return sends to ValidateEntry
if key == wx.WXK_RETURN:
... | 0.007401 |
def _merge_default_values(self):
"""Merge default values with resource data."""
values = self._get_default_values()
for key, value in values.items():
if not self.data.get(key):
self.data[key] = value | 0.007968 |
def startCc(CallControlCapabilities_presence=0):
"""START CC Section 9.3.23a"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x9) # 00001001
packet = a / b
if CallControlCapabilities_presence is 1:
c = CallControlCapabilitiesHdr(ieiCCC=0x15, eightBitCCC=0x0)
packet = paclet / c
retu... | 0.00304 |
def get_summary_stats(items, attr):
"""
Returns a dictionary of aggregated statistics for 'items' filtered by
"attr'. For example, it will aggregate statistics for a host across all
the playbook runs it has been a member of, with the following structure:
data[host.id] = {
'ok': 4
... | 0.000962 |
def _get_output_path(self):
"""Checks if a base file label / path is set. Returns absolute path."""
if self.Parameters['-o'].isOn():
output_path = self._absolute(str(self.Parameters['-o'].Value))
else:
raise ValueError("No output path specified.")
return output_pa... | 0.006211 |
def _clear_context(context):
'''
Clear variables stored in __context__. Run this function when a new version
of chocolatey is installed.
'''
for var in (x for x in __context__ if x.startswith('chocolatey.')):
context.pop(var) | 0.003953 |
def add_hyperedges(self, hyperedges, attr_dict=None, **attr):
"""Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node in the tail or head of any hyperedge has not
previously been added to the hypergraph, it will automatically... | 0.000764 |
def call_api_fetch(self, params, get_latest_only=True):
"""
GET https: // myserver / piwebapi / assetdatabases / D0NxzXSxtlKkGzAhZfHOB - KAQLhZ5wrU - UyRDQnzB_zGVAUEhMQUZTMDRcTlVHUkVFTg HTTP / 1.1
Host: myserver
Accept: application / json"""
output_format = 'application/json'
... | 0.006011 |
def get_sample_window(self, type_tag, size=10):
"""Get a window of samples not to exceed size (in MB).
Args:
type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...).
size: Size of samples in MBs.
Returns:
a list of md5s.
"""
# Con... | 0.007209 |
def dumps(self, fd, **kwargs):
"""
Returns the concrete content for a file descriptor.
BACKWARD COMPATIBILITY: if you ask for file descriptors 0 1 or 2, it will return the data from stdin, stdout,
or stderr as a flat string.
:param fd: A file descriptor.
:return: Th... | 0.006329 |
def request_object(self):
"""Grab an object from the pool. If the pool is empty, a new object will be generated and returned."""
obj_to_return = None
if self.queue.count > 0:
obj_to_return = self.__dequeue()
else:
#The queue is empty, generate a new item.
... | 0.008811 |
def to_json(self):
"""Convert the Humidity Condition to a dictionary."""
return {
'hum_type': self.hum_type,
'hum_value': self.hum_value,
'barometric_pressure': self.barometric_pressure,
'schedule': self.schedule,
'wet_bulb_range': self.wet_bul... | 0.005917 |
def run_project(
project_directory: str,
output_directory: str = None,
logging_path: str = None,
reader_path: str = None,
reload_project_libraries: bool = False,
**kwargs
) -> ExecutionResult:
"""
Runs a project as a single command directly within the current Pyth... | 0.000439 |
def _validate_frow(self, frow):
"""Validate frow argument."""
is_int = isinstance(frow, int) and (not isinstance(frow, bool))
pexdoc.exh.addai("frow", not (is_int and (frow >= 0)))
return frow | 0.008929 |
def unwrap(klass, value):
"""Unpack a Value into an augmented python type (selected from the 'value' field)
"""
assert isinstance(value, Value), value
V = value.value
try:
T = klass.typeMap[type(V)]
except KeyError:
raise ValueError("Can't unwrap v... | 0.007435 |
def get_files(self):
"""stub"""
files_map = {}
try:
files_map['choices'] = self.get_choices_file_urls_map()
try:
files_map.update(self.get_file_urls_map())
except IllegalState:
pass
except Exception:
files_ma... | 0.003891 |
def do_serial(self, p):
"""Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8"""
try:
self.serial.port = p
self.serial.open()
print 'Opening serial port: %s' % p
except Exception, e:
print 'Unable to open serial port: %s' % p | 0.036437 |
def parse(url_str):
"""
Extract all parts from a URL string and return them as a dictionary
"""
url_str = to_unicode(url_str)
result = urlparse(url_str)
netloc_parts = result.netloc.rsplit('@', 1)
if len(netloc_parts) == 1:
username = password = None
host = netloc_parts[0]
... | 0.001068 |
def gen_method_keys(self, *args, **kwargs):
'''Given a node, return the string to use in computing the
matching visitor methodname. Can also be a generator of strings.
'''
token = args[0]
for mro_type in type(token).__mro__[:-1]:
name = mro_type.__name__
y... | 0.006079 |
def download_layers(self, repo_name, digest=None, destination=None):
''' download layers is a wrapper to do the following for a client loaded
with a manifest for an image:
1. use the manifests to retrieve list of digests (get_digests)
2. atomically download the list to destination (ge... | 0.002012 |
def _check_chained_comparison(self, node):
"""Check if there is any chained comparison in the expression.
Add a refactoring message if a boolOp contains comparison like a < b and b < c,
which can be chained as a < b < c.
Care is taken to avoid simplifying a < b < c and b < d.
"... | 0.001736 |
def create_data_disk(vm_=None, linode_id=None, data_size=None):
r'''
Create a data disk for the linode (type is hardcoded to ext4 at the moment)
.. versionadded:: 2016.3.0
vm\_
The VM profile to create the data disk for.
linode_id
The ID of the Linode to create the data disk for.
... | 0.002981 |
def site_models(self, app_label=None):
"""Returns a dictionary of registered models.
"""
site_models = {}
app_configs = (
django_apps.get_app_configs()
if app_label is None
else [django_apps.get_app_config(app_label)]
)
for app_config i... | 0.002865 |
def update(self):
"""Update the device values."""
node = self._fritz.get_device_element(self.ain)
self._update_from_node(node) | 0.013333 |
def save(self, fn:PathOrStr):
"Save the image to `fn`."
x = image2np(self.data*255).astype(np.uint8)
PIL.Image.fromarray(x).save(fn) | 0.019231 |
def logging_raslog_module_modId_modId(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logging = ET.SubElement(config, "logging", xmlns="urn:brocade.com:mgmt:brocade-ras")
raslog = ET.SubElement(logging, "raslog")
module = ET.SubElement(raslog, "m... | 0.005435 |
def p_sens_all(self, p):
'senslist : AT TIMES'
p[0] = SensList(
(Sens(None, 'all', lineno=p.lineno(1)),), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | 0.010526 |
def _text_to_string(self, text):
""" Provides for escape characters and converting to
pdf text object (pdf strings are in parantheses).
Mainly for use in the information block here, this
functionality is also present in the text object.
"""
if text:
... | 0.013384 |
def get_default_credentials(scopes):
"""Gets the Application Default Credentials."""
credentials, _ = google.auth.default(scopes=scopes)
return credentials | 0.005988 |
def snapshot(self,
label,
snapshot_type='statevector',
qubits=None,
params=None):
"""Take a statevector snapshot of the internal simulator representation.
Works on all qubits, and prevents reordering (like barrier).
For other types of snapshots use the Sn... | 0.001033 |
def __split_file(self):
'''
Splits combined SAR output file (in ASCII format) in order to
extract info we need for it, in the format we want.
:return: ``List``-style of SAR file sections separated by
the type of info they contain (SAR file sections) without
... | 0.001771 |
def _CopyFromDateTimeString(self, time_string):
"""Copies a POSIX timestamp from a date and time string.
Args:
time_string (str): date and time value formatted as:
YYYY-MM-DD hh:mm:ss.######[+-]##:##
Where # are numeric digits ranging from 0 to 9 and the seconds
fraction ca... | 0.002394 |
async def jsk_debug(self, ctx: commands.Context, *, command_string: str):
"""
Run a command timing execution and catching exceptions.
"""
alt_ctx = await copy_context_with(ctx, content=ctx.prefix + command_string)
if alt_ctx.command is None:
return await ctx.send(f'... | 0.007236 |
def get_mimetype(self):
"""
Mimetype is calculated based on the file's content. If ``_mimetype``
attribute is available, it will be returned (backends which store
mimetypes or can easily recognize them, should set this private
attribute to indicate that type should *NOT* be calcu... | 0.004049 |
def connect_options_node_proxy(self, name, **kwargs): # noqa: E501
"""connect_options_node_proxy # noqa: E501
connect OPTIONS requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=Tr... | 0.001871 |
def stop(ctx, yes):
"""Stop job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job stop
```
\b
```bash
$ polyaxon job -xp 2 stop
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
... | 0.003421 |
def ggplot_color_wheel(n, start = 15, saturation_adjustment = None, saturation = 0.65, lightness = 1.0, prefix = ''):
'''Returns a list of colors with the same distributed spread as used in ggplot2.
A saturation of 0.5 will leave the input color at the usual saturation e.g. if start is 240 (240/360 = 0.66 = ... | 0.020539 |
def update_dataset(dataset_id, name, data_type, val, unit_id, metadata={}, flush=True, **kwargs):
"""
Update an existing dataset
"""
if dataset_id is None:
raise HydraError("Dataset must have an ID to be updated.")
user_id = kwargs.get('user_id')
dataset = db.DBSession.query(Datas... | 0.011404 |
async def find(
self,
*,
types=None,
data=None,
countries=None,
post=False,
strict=False,
dnsbl=None,
limit=0,
**kwargs
):
"""Gather and check proxies from providers or from a passed data.
:ref:`Example of usage <proxyb... | 0.001111 |
def _get_existing_logical_drives(raid_adapter):
"""Collect existing logical drives on the server.
:param raid_adapter: raid adapter info
:returns: existing_logical_drives: get logical drive on server
"""
existing_logical_drives = []
logical_drives = raid_adapter['Server']['HWConfigurationIrmc']... | 0.00177 |
def _set_show_mpls_lsp_name_debug(self, v, load=False):
"""
Setter method for show_mpls_lsp_name_debug, mapped from YANG variable /brocade_mpls_rpc/show_mpls_lsp_name_debug (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_lsp_name_debug is considered as a ... | 0.006159 |
def correct_inverted_amphibrachs(self, scansion: str) -> str:
"""
The 'inverted amphibrach': stressed_unstressed_stressed syllable pattern is invalid
in hexameters, so here we coerce it to stressed: - U - -> - - -
:param scansion: the scansion stress pattern
:return: a string w... | 0.005879 |
def _relation(self, id, join_on, join_to, level=None, featuretype=None,
order_by=None, reverse=False, completely_within=False,
limit=None):
# The following docstring will be included in the parents() and
# children() docstrings to maintain consistency, since they bot... | 0.004177 |
def _goto_playing_station(self, changing_playlist=False):
""" make sure playing station is visible """
if (self.player.isPlaying() or self.operation_mode == PLAYLIST_MODE) and \
(self.selection != self.playing or changing_playlist):
if changing_playlist:
self.star... | 0.00454 |
def execute_job(self, obj):
"""
Execute the BMDS model and parse outputs if successful.
"""
# get executable path
exe = session.BMDS.get_model(obj["bmds_version"], obj["model_name"]).get_exe_path()
# write dfile
dfile = self.tempfiles.get_tempfile(prefix="bmds-d... | 0.003992 |
async def parseResults(self, api_data):
""" See CoverSource.parseResults. """
results = []
# parse HTML and get results
parser = lxml.etree.HTMLParser()
html = lxml.etree.XML(api_data.decode("latin-1"), parser)
for rank, result in enumerate(__class__.RESULTS_SELECTOR(html), 1):
# extract... | 0.012685 |
def lstm_state_tuples(num_nodes, name):
"""Convenience so that the names of the vars are defined in the same file."""
if not isinstance(num_nodes, tf.compat.integral_types):
raise ValueError('num_nodes must be an integer: %s' % num_nodes)
return [(STATE_NAME % name + '_0', tf.float32, num_nodes),
(S... | 0.01087 |
def parse_tagLength_dist(self):
"""parses and plots tag length distribution files"""
# Find and parse homer tag length distribution reports
for f in self.find_log_files('homer/LengthDistribution', filehandles=True):
s_name = os.path.basename(f['root'])
s_name = self.clean... | 0.014563 |
def initUI(self):
#self.setMinimumSize(WIDTH,HEIGTH)
#self.setMaximumSize(WIDTH,HEIGTH)
'''Radio buttons for Original/RGB/HSV/YUV images'''
self.origButton = QRadioButton("Original")
self.rgbButton = QRadioButton("RGB")
self.hsvButton = QRadioButton("HSV")
self.... | 0.008914 |
def qn_df(df, axis='row', keep_orig=False):
'''
do quantile normalization of a dataframe dictionary, does not write to net
'''
df_qn = {}
for mat_type in df:
inst_df = df[mat_type]
# using transpose to do row qn
if axis == 'row':
inst_df = inst_df.transpose()
missing_values = inst_df.... | 0.01227 |
def set_inlets(self, pores=[], overwrite=False):
r"""
Set the locations from which the invader enters the network
Parameters
----------
pores : array_like
Locations that are initially filled with invader, from which
clusters grow and invade into the netwo... | 0.002041 |
def from_file(self, filename):
"""Read configuration from a .rc file.
`filename` is a file name to read.
"""
self.attempted_config_files.append(filename)
cp = HandyConfigParser()
files_read = cp.read(filename)
if files_read is not None: # return value changed ... | 0.002985 |
def pushbullet(body, apikey, device, title="JCVI: Job Monitor", type="note"):
"""
pushbullet.com API
<https://www.pushbullet.com/api>
"""
import base64
headers = {}
auth = base64.encodestring("{0}:".format(apikey)).strip()
headers['Authorization'] = "Basic {0}".format(auth)
headers... | 0.003044 |
def display_db_info(self):
"""Displays some basic info about the GnuCash book"""
with self.open_book() as book:
default_currency = book.default_currency
print("Default currency is ", default_currency.mnemonic) | 0.008032 |
def merge_validator_config(configs):
"""
Given a list of ValidatorConfig objects, merges them into a single
ValidatorConfig, giving priority in the order of the configs
(first has highest priority).
"""
bind_network = None
bind_component = None
bind_consensus = None
endpoint = None
... | 0.00023 |
def load(self, ioi, ac_ignore_missing=False, **options):
"""
Load config from a file path or a file / file-like object which 'ioi'
refering after some checks.
:param ioi:
'anyconfig.globals.IOInfo' namedtuple object provides various info
of input object to load d... | 0.001523 |
def trace_memory_clean_caches(self):
""" Avoid polluting results with some builtin python caches """
urllib.parse.clear_cache()
re.purge()
linecache.clearcache()
copyreg.clear_extension_cache()
if hasattr(fnmatch, "purge"):
fnmatch.purge() # pylint: disable... | 0.003284 |
def create_app():
""" Flask application factory """
# Setup Flask app and app.config
app = Flask(__name__)
app.config.from_object(__name__+'.ConfigClass')
# Initialize Flask extensions
db = SQLAlchemy(app) # Initialize Flask-SQLAlchemy
# Define the User data... | 0.005734 |
def take_home_pay(gross_pay, employer_match, taxes_and_fees, numtype='float'):
"""
Calculate net take-home pay including employer retirement savings match
using the formula laid out by Mr. Money Mustache:
http://www.mrmoneymustache.com/2015/01/26/calculating-net-worth/
Args:
gross_pay: floa... | 0.002278 |
def concurrent_exec(func, param_list):
"""Executes a function with different parameters pseudo-concurrently.
This is basically a map function. Each element (should be an iterable) in
the param_list is unpacked and passed into the function. Due to Python's
GIL, there's no true concurrency. This is suite... | 0.000727 |
def runGetBiosample(self, id_):
"""
Runs a getBiosample request for the specified ID.
"""
compoundId = datamodel.BiosampleCompoundId.parse(id_)
dataset = self.getDataRepository().getDataset(compoundId.dataset_id)
biosample = dataset.getBiosample(id_)
return self.r... | 0.005831 |
def ensure_hist_size(self):
"""
Shrink the history of updates for
a `index/doc_type` combination down to `self.marker_index_hist_size`.
"""
if self.marker_index_hist_size == 0:
return
result = self.es.search(index=self.marker_index,
... | 0.002212 |
def askopenfilename(**kwargs):
"""Return file name(s) from Tkinter's file open dialog."""
try:
from Tkinter import Tk
import tkFileDialog as filedialog
except ImportError:
from tkinter import Tk, filedialog
root = Tk()
root.withdraw()
root.update()
filenames = filedia... | 0.002571 |
def autodiscover_modules(packages, related_name_re='.+',
ignore_exceptions=False):
"""Autodiscover function follows the pattern used by Celery.
:param packages: List of package names to auto discover modules in.
:type packages: list of str
:param related_name_re: Regular expres... | 0.002648 |
def find_library_full_path(name):
"""
Similar to `from ctypes.util import find_library`, but try
to return full path if possible.
"""
from ctypes.util import find_library
if os.name == "posix" and sys.platform == "darwin":
# on Mac, ctypes already returns full path
return find_l... | 0.001524 |
def get_message_id(self):
"""Method to get messageId of group created."""
message_id = self.json_response.get("messageId", None)
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return message_id | 0.007968 |
def check(self, _):
"""Check this configure."""
try:
import yaml
except:
return True
try:
yaml.safe_load(self.recipes)
except Exception as e:
raise RADLParseException("Invalid YAML code: %s." % e, line=self.line)
return Tru... | 0.012461 |
def conditions_met(self, instance, state):
"""
Check if all conditions have been met
"""
transition = self.get_transition(state)
if transition is None:
return False
elif transition.conditions is None:
return True
else:
return a... | 0.007712 |
def convert_inputs_to_sparse_if_necessary(lhs, rhs):
'''
This function checks to see if a sparse output is desireable given the inputs and if so, casts the inputs to sparse in order to make it so.
'''
if not sp.issparse(lhs) or not sp.issparse(rhs):
if sparse_is_desireable(lhs, rhs):
... | 0.006645 |
def _negf(ins):
''' Changes sign of top of the stack (48 bits)
'''
output = _float_oper(ins.quad[2])
output.append('call __NEGF')
output.extend(_fpush())
REQUIRES.add('negf.asm')
return output | 0.004545 |
def get_form_kwargs(self):
"""
Inject the request user into the kwargs passed to the form
"""
kwargs = super(AddUpdateMixin, self).get_form_kwargs()
kwargs.update({'user': self.request.user})
return kwargs | 0.007905 |
def pre_ref_resolution_callback(self, other_model):
"""
(internal: used to store a model after parsing into the repository)
Args:
other_model: the parsed model
Returns:
nothing
"""
# print("PRE-CALLBACK{}".format(filename))
filename = oth... | 0.003781 |
def _generate_rsa_key(key_length):
"""Generate a new RSA private key.
:param int key_length: Required key length in bits
:returns: DER-encoded private key, private key identifier, and DER encoding identifier
:rtype: tuple(bytes, :class:`EncryptionKeyType`, :class:`KeyEncodingType`)
"""
private_... | 0.004329 |
def copy_config_input_source_config_source_candidate_candidate(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
copy_config = ET.Element("copy_config")
config = copy_config
input = ET.SubElement(copy_config, "input")
source = ET.SubElement... | 0.003273 |
def _predict_tree(model, X, joint_contribution=False):
"""
For a given DecisionTreeRegressor, DecisionTreeClassifier,
ExtraTreeRegressor, or ExtraTreeClassifier,
returns a triple of [prediction, bias and feature_contributions], such
that prediction ≈ bias + feature_contributions.
"""
leaves ... | 0.006906 |
def alignment_to_contacts(
sam_merged,
assembly,
output_dir,
output_file_network=DEFAULT_NETWORK_FILE_NAME,
output_file_chunk_data=DEFAULT_CHUNK_DATA_FILE_NAME,
parameters=DEFAULT_PARAMETERS,
):
"""Generates a network file (in edgelist form) from an
alignment in sam or bam format. Contig... | 0.000085 |
def set_fill_color(self,r,g=-1,b=-1):
"Set color for all filling operations"
if((r==0 and g==0 and b==0) or g==-1):
self.fill_color=sprintf('%.3f g',r/255.0)
else:
self.fill_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0)
self.color_flag=(self.fill_colo... | 0.047146 |
def express_route_links(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`ExpressRouteLinksOperations<azure.mgmt.network.v2018_08_01.operations.ExpressRouteLinksOperations>`
"""
api_version = self._get_api_version('express_route_links')
if api_version == '2... | 0.00885 |
def include(self, node):
"""Include the defined yaml file."""
result = None
if isinstance(node, ScalarNode):
result = Loader.include_file(self.construct_scalar(node))
else:
raise RuntimeError("Not supported !include on type %s" % type(node))
return result | 0.009404 |
def fprob(dfnum, dfden, F):
"""
Returns the (1-tailed) significance level (p-value) of an F
statistic given the degrees of freedom for the numerator (dfR-dfF) and
the degrees of freedom for the denominator (dfF).
Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn
"""
p = betai(0.5 * dfden,... | 0.002632 |
def _handle_http_errors(response):
"""
Check for HTTP errors and raise
OSError if relevant.
Args:
response (requests.Response):
Returns:
requests.Response: response
"""
code = response.status_code
if 200 <= code < 400:
return response
elif code in (403, 404)... | 0.002165 |
def is_result_edition_allowed(self, analysis_brain):
"""Checks if the edition of the result field is allowed
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the result field, otherwise False
"""
# Always check general edition first
... | 0.002215 |
def to_json(self):
"""Returns an input shard state for the remaining inputs.
Returns:
A json-izable version of the remaining InputReader.
"""
return {self.BLOB_KEY_PARAM: self._blob_key,
self.START_INDEX_PARAM: self._start_index,
self.END_INDEX_PARAM: self._end_index} | 0.003175 |
def read(self, filename):
"""
Read template from tar format with metadata.
:type filename: str
:param filename: Filename to read template from.
.. rubric:: Example
>>> template_a = Template(
... name='a', st=read(), lowcut=2.0, highcut=8.0, samp_rate=100,
... | 0.001896 |
def decode(self):
"Decode self.buffer, populating instance variables and return self."
buflen = len(self.buffer)
tftpassert(buflen >= 4, "malformed ERR packet, too short")
log.debug("Decoding ERR packet, length %s bytes", buflen)
if buflen == 4:
log.debug("Allowing th... | 0.003802 |
def to_entity(entity_type, value, fields):
"""
Internal API: Returns an instance of an entity of type entity_type with the specified value and fields (stored in
dict). This is only used by the local transform runner as a helper function.
"""
e = entity_type(value)
for k, v in fields.items():
... | 0.008264 |
def GetSchema(component):
"""convience function for finding the parent XMLSchema instance.
"""
parent = component
while not isinstance(parent, XMLSchema):
parent = parent._parent()
return parent | 0.004505 |
def popd():
"""Go back to where you once were.
:return: saved directory stack
"""
try:
directory = _saved_paths.pop(0)
except IndexError:
return [os.getcwd()]
os.chdir(directory)
return [directory] + _saved_paths | 0.003891 |
def to_funset(self):
"""
Converts the experimental setup to a set of `gringo.Fun`_ object instances
Returns
-------
set
The set of `gringo.Fun`_ object instances
.. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun
"""
fs = set((g... | 0.008772 |
def amust(self, args, argv):
'''
Requires the User to provide a certain parameter
for the method to function properly.
Else, an Exception is raised.
args - (tuple) arguments you are looking for.
argv - (dict) arguments you have received and want to inspect.
'''
... | 0.004415 |
def num_tagitems(self, tag):
""" Return the total number of items for the specified tag
"""
query = "/{t}/{u}/tags/{ta}/items".format(
u=self.library_id, t=self.library_type, ta=tag
)
return self._totals(query) | 0.007634 |
def do_POST(self): # pylint: disable=g-bad-name
"""Process encrypted message bundles."""
self._IncrementActiveCount()
try:
if self.path.startswith("/upload"):
stats_collector_instance.Get().IncrementCounter(
"frontend_http_requests", fields=["upload", "http"])
logging.err... | 0.008929 |
def status(config):
"""time series lastest record time by account."""
with open(config) as fh:
config = yaml.safe_load(fh.read())
jsonschema.validate(config, CONFIG_SCHEMA)
last_index = get_incremental_starts(config, None)
accounts = {}
for (a, region), last in last_index.items():
... | 0.002353 |
def draw(self, surface):
""" Draw all sprites and map onto the surface
:param surface: pygame surface to draw to
:type surface: pygame.surface.Surface
"""
ox, oy = self._map_layer.get_center_offset()
new_surfaces = list()
spritedict = self.spritedict
gl ... | 0.00451 |
def fit(self, X, y):
"""Fit
Args:
X (np.array): Array of hyperparameter values with shape (n_samples, len(tunables))
y (np.array): Array of scores with shape (n_samples, )
"""
self.X = X
self.y = y | 0.01145 |
def load_config(cls, configfile="logging.yaml"):
"""
:raises: ValueError
"""
configfile = getenv(cls.CONFIGFILE_ENV_KEY, configfile)
if isfile(configfile):
with open(configfile, "r") as cf:
# noinspection PyBroadException
try:
... | 0.007267 |
def match_option_with_value(arguments, option, value):
"""
Check if a list of command line options contains an option with a value.
:param arguments: The command line arguments (a list of strings).
:param option: The long option (a string).
:param value: The expected value (a string).
:returns:... | 0.001838 |
def set_schedule_enabled(self, state):
"""
:param state: a boolean True (on) or False (off)
:return: nothing
"""
desired_state = {"schedule_enabled": state}
response = self.api_interface.set_device_state(self, {
"desired_state": desired_state
})
... | 0.005464 |
def pack_int(v):
""" Returns <v> as packed string. """
if v == 0:
return "\0"
ret = ''
while v > 0:
c = v & 127
v >>= 7
if v != 0:
c = c | 128
ret += chr(c)
return ret | 0.004184 |
def createEditor(self, parent, option, index):
"""Returns the widget used to edit the item specified by index for editing. The parent widget and style option are used to control how the editor widget appears.
Args:
parent (QWidget): parent widget.
option (QStyleOptionViewItem): ... | 0.006237 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.