code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def line(y, thickness, gaussian_width):
distance_from_line = abs(y)
gaussian_y_coord = distance_from_line - thickness/2.0
sigmasq = gaussian_width*gaussian_width
if sigmasq==0.0:
falloff = y*0.0
else:
with float_error_ignore():
falloff = np.exp(np.divide(-gaussian_y_coord*gaussian_y_coord,2*sigmasq))
return np.where(gaussian_y_coord<=0, 1.0, falloff) | Infinite-length line with a solid central region, then Gaussian fall-off at the edges. |
def add_cat(self, arg=None):
try:
self.done_callback(self.cat)
self.visible = False
except Exception as e:
self.validator.object = ICONS['error']
raise e | Add cat and close panel |
def resolve_extensions(bot: commands.Bot, name: str) -> list:
if name.endswith('.*'):
module_parts = name[:-2].split('.')
path = pathlib.Path(module_parts.pop(0))
for part in module_parts:
path = path / part
return find_extensions_in(path)
if name == '~':
return list(bot.extensions.keys())
return [name] | Tries to resolve extension queries into a list of extension names. |
def upload_gallery_photo(self, gallery_id, source_amigo_id, file_obj,
chunk_size=CHUNK_SIZE, force_chunked=False,
metadata=None):
simple_upload_url = 'related_tables/%s/upload' % gallery_id
chunked_upload_url = 'related_tables/%s/chunked_upload' % gallery_id
data = {'source_amigo_id': source_amigo_id}
if isinstance(file_obj, basestring):
data['filename'] = os.path.basename(file_obj)
else:
data['filename'] = os.path.basename(file_obj.name)
if metadata:
data.update(metadata)
return self.upload_file(simple_upload_url, chunked_upload_url,
file_obj, chunk_size=chunk_size,
force_chunked=force_chunked, extra_data=data) | Upload a photo to a dataset's gallery. |
def foreign(self, value, context=None):
if self.separator is None:
separator = ' '
else:
separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator
value = self._clean(value)
try:
value = separator.join(value)
except Exception as e:
raise Concern("{0} caught, failed to convert to string: {1}", e.__class__.__name__, str(e))
return super().foreign(value) | Construct a string-like representation for an iterable of string-like objects. |
def chat(self, message):
if message:
action_chat = sc_pb.ActionChat(
channel=sc_pb.ActionChat.Broadcast, message=message)
action = sc_pb.Action(action_chat=action_chat)
return self.act(action) | Send chat message as a broadcast. |
def exit(status=0):
if status == 0:
lab.io.printf(lab.io.Colours.GREEN, "Done.")
else:
lab.io.printf(lab.io.Colours.RED, "Error {0}".format(status))
sys.exit(status) | Terminate the program with the given status code. |
def parse_template(self, template, **context):
required_blocks = ["subject", "body"]
optional_blocks = ["text_body", "html_body", "return_path", "format"]
if self.template_context:
context = dict(self.template_context.items() + context.items())
blocks = self.template.render_blocks(template, **context)
for rb in required_blocks:
if rb not in blocks:
raise AttributeError("Template error: block '%s' is missing from '%s'" % (rb, template))
mail_params = {
"subject": blocks["subject"].strip(),
"body": blocks["body"]
}
for ob in optional_blocks:
if ob in blocks:
if ob == "format" and mail_params[ob].lower() not in ["html", "text"]:
continue
mail_params[ob] = blocks[ob]
return mail_params | To parse a template and return all the blocks |
def validate_geotweet(self, record):
if record and self._validate('user', record) \
and self._validate('coordinates', record):
return True
return False | check that stream record is actual tweet with coordinates |
def _update_name(self):
self._name = self._json_state.get('name')
if not self._name:
self._name = self.type + ' ' + self.device_id | Set the device name from _json_state, with a sensible default. |
def _parse_bare_key(self):
key_type = None
dotted = False
self.mark()
while self._current.is_bare_key_char() and self.inc():
pass
key = self.extract()
if self._current == ".":
self.inc()
dotted = True
key += "." + self._parse_key().as_string()
key_type = KeyType.Bare
return Key(key, key_type, "", dotted) | Parses a bare key. |
def _set_lastpage(self):
self.last_page = (len(self._page_data) - 1) // self.screen.page_size | Calculate value of class attribute ``last_page``. |
def next_token(self, tokenum, value, scol):
self.current.set(tokenum, value, scol)
if self.current.tokenum == INDENT and self.current.value:
self.indent_type = self.current.value[0]
if not self.ignore_token():
self.determine_if_whitespace()
self.determine_inside_container()
self.determine_indentation()
if self.forced_insert():
return
if self.inserted_line and self.current.tokenum == NEWLINE:
self.inserted_line = False
if self.result and not self.is_space and self.inserted_line:
if self.current.tokenum != COMMENT:
self.result.append((OP, ';'))
self.inserted_line = False
self.progress()
if self.single and self.single.skipped:
self.single.skipped = False
self.result.append((NEWLINE, '\n'))
self.after_space = self.is_space | Determine what to do with the next token |
def plot_neff(self, ax, xt_labelsize, titlesize, markersize):
for plotter in self.plotters.values():
for y, ess, color in plotter.ess():
if ess is not None:
ax.plot(
ess,
y,
"o",
color=color,
clip_on=False,
markersize=markersize,
markeredgecolor="k",
)
ax.set_xlim(left=0)
ax.set_title("ess", fontsize=titlesize, wrap=True)
ax.tick_params(labelsize=xt_labelsize)
return ax | Draw effective n for each plotter. |
def inspect_filter_calculation(self):
try:
node = self.ctx.cif_filter
self.ctx.cif = node.outputs.cif
except exceptions.NotExistent:
self.report('aborting: CifFilterCalculation<{}> did not return the required cif output'.format(node.uuid))
return self.exit_codes.ERROR_CIF_FILTER_FAILED | Inspect the result of the CifFilterCalculation, verifying that it produced a CifData output node. |
def for_name(modpath, classname):
module = __import__(modpath, fromlist=[classname])
classobj = getattr(module, classname)
return classobj() | Returns a class of "classname" from module "modname". |
def decrypt(data, key):
data_len = len(data)
data = ffi.from_buffer(data)
key = ffi.from_buffer(__tobytes(key))
out_len = ffi.new('size_t *')
result = lib.xxtea_decrypt(data, data_len, key, out_len)
ret = ffi.buffer(result, out_len[0])[:]
lib.free(result)
return ret | decrypt the data with the key |
def reenqueue(self, batch):
now = time.time()
batch.attempts += 1
batch.last_attempt = now
batch.last_append = now
batch.set_retry()
assert batch.topic_partition in self._tp_locks, 'TopicPartition not in locks dict'
assert batch.topic_partition in self._batches, 'TopicPartition not in batches'
dq = self._batches[batch.topic_partition]
with self._tp_locks[batch.topic_partition]:
dq.appendleft(batch) | Re-enqueue the given record batch in the accumulator to retry. |
def list_feeds():
with Database("feeds") as feeds, Database("aliases") as aliases_db:
for feed in feeds:
name = feed
url = feeds[feed]
aliases = []
for k, v in zip(list(aliases_db.keys()), list(aliases_db.values())):
if v == name:
aliases.append(k)
if aliases:
print(name, " : %s Aliases: %s" % (url, aliases))
else:
print(name, " : %s" % url) | List all feeds in plain text and give their aliases |
def _format_list(self, data):
dataset = "["
i = 0
for el in data:
if pd.isnull(el):
dataset += "null"
else:
dtype = type(data[i])
if dtype == int or dtype == float:
dataset += str(el)
else:
dataset += '"' + el + '"'
if i < len(data) - 1:
dataset += ', '
dataset += "]"
return dataset | Format a list to use in javascript |
def isfinite(self):
"Test whether the predicted values are finite"
if self._multiple_outputs:
if self.hy_test is not None:
r = [(hy.isfinite() and (hyt is None or hyt.isfinite()))
for hy, hyt in zip(self.hy, self.hy_test)]
else:
r = [hy.isfinite() for hy in self.hy]
return np.all(r)
return self.hy.isfinite() and (self.hy_test is None or
self.hy_test.isfinite()) | Test whether the predicted values are finite |
def fetch_from(self, year: int, month: int):
self.raw_data = []
self.data = []
today = datetime.datetime.today()
for year, month in self._month_year_iter(month, year, today.month, today.year):
self.raw_data.append(self.fetcher.fetch(year, month, self.sid))
self.data.extend(self.raw_data[-1]['data'])
return self.data | Fetch data from year, month to current year month data |
def unicode2str(content):
if isinstance(content, dict):
result = {}
for key in content.keys():
result[unicode2str(key)] = unicode2str(content[key])
return result
elif isinstance(content, list):
return [unicode2str(element) for element in content]
elif isinstance(content, int) or isinstance(content, float):
return content
else:
return content.encode("utf-8") | Convert the unicode element of the content to str recursively. |
def build_stats(counts):
stats = {
'status': 0,
'reportnum': counts['reportnum'],
'title': counts['title'],
'author': counts['auth_group'],
'url': counts['url'],
'doi': counts['doi'],
'misc': counts['misc'],
}
stats_str = "%(status)s-%(reportnum)s-%(title)s-%(author)s-%(url)s-%(doi)s-%(misc)s" % stats
stats["old_stats_str"] = stats_str
stats["date"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
stats["version"] = version
return stats | Return stats information from counts structure. |
def _disks_equal(disk1, disk2):
target1 = disk1.find('target')
target2 = disk2.find('target')
source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None
source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None
return source1 == source2 and \
target1 is not None and target2 is not None and \
target1.get('bus') == target2.get('bus') and \
disk1.get('device', 'disk') == disk2.get('device', 'disk') and \
target1.get('dev') == target2.get('dev') | Test if two disk elements should be considered like the same device |
def find(self, searchText, layers,
contains=True, searchFields="",
sr="", layerDefs="",
returnGeometry=True, maxAllowableOffset="",
geometryPrecision="", dynamicLayers="",
returnZ=False, returnM=False, gdbVersion=""):
url = self._url + "/find"
params = {
"f" : "json",
"searchText" : searchText,
"contains" : self._convert_boolean(contains),
"searchFields": searchFields,
"sr" : sr,
"layerDefs" : layerDefs,
"returnGeometry" : self._convert_boolean(returnGeometry),
"maxAllowableOffset" : maxAllowableOffset,
"geometryPrecision" : geometryPrecision,
"dynamicLayers" : dynamicLayers,
"returnZ" : self._convert_boolean(returnZ),
"returnM" : self._convert_boolean(returnM),
"gdbVersion" : gdbVersion,
"layers" : layers
}
res = self._get(url, params,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
qResults = []
for r in res['results']:
qResults.append(Feature(r))
return qResults | performs the map service find operation |
def clone(self, config, **kwargs):
gta = GTAnalysis(config, **kwargs)
gta._roi = copy.deepcopy(self.roi)
return gta | Make a clone of this analysis instance. |
def rustcall(func, *args):
lib.semaphore_err_clear()
rv = func(*args)
err = lib.semaphore_err_get_last_code()
if not err:
return rv
msg = lib.semaphore_err_get_last_message()
cls = exceptions_by_code.get(err, SemaphoreError)
exc = cls(decode_str(msg))
backtrace = decode_str(lib.semaphore_err_get_backtrace())
if backtrace:
exc.rust_info = backtrace
raise exc | Calls rust method and does some error handling. |
def unique_(self, col):
try:
df = self.df.drop_duplicates(subset=[col], inplace=False)
return list(df[col])
except Exception as e:
self.err(e, "Can not select unique data") | Returns unique values in a column |
def insert(self, resourcetype, source, insert_date=None):
caller = inspect.stack()[1][3]
if caller == 'transaction':
hhclass = 'Layer'
source = resourcetype
resourcetype = resourcetype.csw_schema
else:
hhclass = 'Service'
if resourcetype not in HYPERMAP_SERVICE_TYPES.keys():
raise RuntimeError('Unsupported Service Type')
return self._insert_or_update(resourcetype, source, mode='insert', hhclass=hhclass) | Insert a record into the repository |
def load_stock_quantity(self):
info = StocksInfo(self.config)
for stock in self.model.stocks:
stock.quantity = info.load_stock_quantity(stock.symbol)
info.gc_book.close() | Loads quantities for all stocks |
def peek(self):
try:
self._fetch()
pkt = self.pkt_queue[0]
return pkt
except IndexError:
raise StopIteration() | Get the current packet without consuming it. |
def execute(self, *args, **kwargs):
try:
return self.client.execute(*args, **kwargs)
except requests.exceptions.HTTPError as err:
res = err.response
logger.error("%s response executing GraphQL." % res.status_code)
logger.error(res.text)
self.display_gorilla_error_if_found(res)
six.reraise(*sys.exc_info()) | Wrapper around execute that logs in cases of failure. |
def _compute_std_0(self, c1, c2, mag):
if mag < 5:
return c1
elif mag >= 5 and mag <= 7:
return c1 + (c2 - c1) * (mag - 5) / 2
else:
return c2 | Common part of equations 27 and 28, pag 82. |
def search_mode_provides(self, product, pipeline='default'):
pipeline = self.pipelines[pipeline]
for obj, mode, field in self.iterate_mode_provides(self.modes, pipeline):
if obj.name() == product:
return ProductEntry(obj.name(), mode.key, field)
else:
raise ValueError('no mode provides %s' % product) | Search the mode that provides a given product |
def scan(self, t, dt=None, aggfunc=None):
return self.data.scan(t, dt, aggfunc) | Returns the spectrum from a specific time or range of times. |
def balance(output):
lines = map(pattern.search, output.splitlines())
stack = []
top = []
for item in map(match_to_dict, itertools.takewhile(lambda x: x, lines)):
while stack and item['indent'] <= stack[-1]['indent']:
stack.pop()
if not stack:
stack.append(item)
top.append(item)
else:
item['parent'] = stack[-1]
stack[-1]['children'].append(item)
stack.append(item)
return top | Convert `ledger balance` output into an hierarchical data structure. |
def setup_cache(app: Flask, cache_config) -> Optional[Cache]:
if cache_config and cache_config.get('CACHE_TYPE') != 'null':
return Cache(app, config=cache_config)
return None | Setup the flask-cache on a flask app |
def frame(*msgs):
res = io.BytesIO()
for msg in msgs:
res.write(msg)
msg = res.getvalue()
return pack('L', len(msg)) + msg | Serialize MSB-first length-prefixed frame. |
def ports(self):
with self._mutex:
if not self._ports:
self._ports = [ports.parse_port(port, self) \
for port in self._obj.get_ports()]
return self._ports | The list of all ports belonging to this component. |
def deactivate(self, request, queryset):
selected_cats = self.model.objects.filter(
pk__in=[int(x) for x in request.POST.getlist('_selected_action')])
for item in selected_cats:
if item.active:
item.active = False
item.save()
item.children.all().update(active=False) | Set active to False for selected items |
def find_pkg_dist(pkg_name, working_set=None):
working_set = working_set or default_working_set
req = Requirement.parse(pkg_name)
return working_set.find(req) | Locate a package's distribution by its name. |
def _cache_index(self, dbname, collection, index, cache_for):
now = datetime.datetime.utcnow()
expire = datetime.timedelta(seconds=cache_for) + now
with self.__index_cache_lock:
if dbname not in self.__index_cache:
self.__index_cache[dbname] = {}
self.__index_cache[dbname][collection] = {}
self.__index_cache[dbname][collection][index] = expire
elif collection not in self.__index_cache[dbname]:
self.__index_cache[dbname][collection] = {}
self.__index_cache[dbname][collection][index] = expire
else:
self.__index_cache[dbname][collection][index] = expire | Add an index to the index cache for ensure_index operations. |
def update_token(self):
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64.b64encode(
(self._key + ':' + self._secret).encode()).decode()
}
data = {'grant_type': 'client_credentials'}
response = requests.post(TOKEN_URL, data=data, headers=headers)
obj = json.loads(response.content.decode('UTF-8'))
self._token = obj['access_token']
self._token_expire_date = (
datetime.now() +
timedelta(minutes=self._expiery)) | Get token from key and secret |
def data(self):
header = struct.pack('>BLB',
4,
self.created,
self.algo_id)
oid = util.prefix_len('>B', self.curve_info['oid'])
blob = self.curve_info['serialize'](self.verifying_key)
return header + oid + blob + self.ecdh_packet | Data for packet creation. |
def _get_binding_info(hostheader='', ipaddress='*', port=80):
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret | Combine the host header, IP address, and TCP port into bindingInformation format. |
def astensor(array: TensorLike) -> BKTensor:
array = np.asarray(array, dtype=CTYPE)
return array | Converts a numpy array to the backend's tensor object |
def rdb_repository(_context, name=None, make_default=False,
aggregate_class=None, repository_class=None,
db_string=None, metadata_factory=None):
cnf = {}
if not db_string is None:
cnf['db_string'] = db_string
if not metadata_factory is None:
cnf['metadata_factory'] = metadata_factory
_repository(_context, name, make_default,
aggregate_class, repository_class,
REPOSITORY_TYPES.RDB, 'add_rdb_repository', cnf) | Directive for registering a RDBM based repository. |
def head(self) -> Any:
lambda_list = self._get_value()
return lambda_list(lambda head, _: head) | Retrive first element in List. |
def get(identifier, value=None):
if value is None:
value = identifier
if identifier is None:
return None
elif isinstance(identifier, dict):
try:
return deserialize(identifier)
except ValueError:
return value
elif isinstance(identifier, six.string_types):
config = {'class_name': str(identifier), 'config': {}}
try:
return deserialize(config)
except ValueError:
return value
elif callable(identifier):
return identifier
return value | Getter for loading from strings; returns value if can't load. |
def save_ufunc(self, obj):
name = obj.__name__
numpy_tst_mods = ['numpy', 'scipy.special']
for tst_mod_name in numpy_tst_mods:
tst_mod = sys.modules.get(tst_mod_name, None)
if tst_mod and name in tst_mod.__dict__:
return self.save_reduce(_getobject, (tst_mod_name, name))
raise pickle.PicklingError('cannot save %s. Cannot resolve what module it is defined in'
% str(obj)) | Hack function for saving numpy ufunc objects |
def create_model(samples_x, samples_y_aggregation,
n_restarts_optimizer=250, is_white_kernel=False):
kernel = gp.kernels.ConstantKernel(constant_value=1,
constant_value_bounds=(1e-12, 1e12)) * \
gp.kernels.Matern(nu=1.5)
if is_white_kernel is True:
kernel += gp.kernels.WhiteKernel(noise_level=1, noise_level_bounds=(1e-12, 1e12))
regressor = gp.GaussianProcessRegressor(kernel=kernel,
n_restarts_optimizer=n_restarts_optimizer,
normalize_y=True,
alpha=1e-10)
regressor.fit(numpy.array(samples_x), numpy.array(samples_y_aggregation))
model = {}
model['model'] = regressor
model['kernel_prior'] = str(kernel)
model['kernel_posterior'] = str(regressor.kernel_)
model['model_loglikelihood'] = regressor.log_marginal_likelihood(regressor.kernel_.theta)
return model | Trains GP regression model |
def list_pubs(self, buf):
assert not buf.read()
keys = self.conn.parse_public_keys()
code = util.pack('B', msg_code('SSH2_AGENT_IDENTITIES_ANSWER'))
num = util.pack('L', len(keys))
log.debug('available keys: %s', [k['name'] for k in keys])
for i, k in enumerate(keys):
log.debug('%2d) %s', i+1, k['fingerprint'])
pubs = [util.frame(k['blob']) + util.frame(k['name']) for k in keys]
return util.frame(code, num, *pubs) | SSH v2 public keys are serialized and returned. |
def add_item(c, name, item):
if isinstance(item, MenuItem):
if name not in c.items:
c.items[name] = []
c.items[name].append(item)
c.sorted[name] = False | add_item adds MenuItems to the menu identified by 'name' |
def GetGRRVersionString(self):
client_info = self.startup_info.client_info
client_name = client_info.client_description or client_info.client_name
if client_info.client_version > 0:
client_version = str(client_info.client_version)
else:
client_version = _UNKNOWN_GRR_VERSION
return " ".join([client_name, client_version]) | Returns the client installation-name and GRR version as a string. |
def register_plugins(self):
registered = set()
for plugin_fqdn in chain(self.APP_PLUGINS, self.config["PLUGINS"]):
if plugin_fqdn not in registered:
self.register_plugin(plugin_fqdn)
registered.add(plugin_fqdn) | Load plugins listed in config variable 'PLUGINS'. |
def remove(self, transport):
if transport.uid in self.transports:
del (self.transports[transport.uid]) | removes a transport if a member of this group |
def pop(self):
root = self.heap[1]
del self.rank[root]
x = self.heap.pop()
if self:
self.heap[1] = x
self.rank[x] = 1
self.down(1)
return root | Remove and return smallest element |
def validate_args(args):
if not any([args.environment, args.stage, args.account]):
sys.exit(NO_ACCT_OR_ENV_ERROR)
if args.environment and args.account:
sys.exit(ENV_AND_ACCT_ERROR)
if args.environment and args.role:
sys.exit(ENV_AND_ROLE_ERROR) | Validate command-line arguments. |
def flush(self):
if os.path.isdir(self._directory):
for root, dirs, files in os.walk(self._directory, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name)) | Remove all items from the cache. |
def insert_attachments(self, volumeID, attachments):
log.debug("adding new attachments to volume '{}': {}".format(volumeID, attachments))
if not attachments:
return
rawVolume = self._req_raw_volume(volumeID)
attsID = list()
for index, a in enumerate(attachments):
try:
rawAttachment = self._assemble_attachment(a['file'], a)
rawVolume['_source']['_attachments'].append(rawAttachment)
attsID.append(rawAttachment['id'])
except Exception:
log.exception("Error while elaborating attachments array at index: {}".format(index))
raise
self._db.modify_book(volumeID, rawVolume['_source'], version=rawVolume['_version'])
return attsID | add attachments to an already existing volume |
def render_property(property):
if 'type' in property and property['type'] in PROPERTY_FIELDS:
fields = {}
for field in PROPERTY_FIELDS[property['type']]:
if type(field) is tuple:
fields[field[0]] = '(( .properties.{}.{} ))'.format(property['name'], field[1])
else:
fields[field] = '(( .properties.{}.{} ))'.format(property['name'], field)
out = { property['name']: fields }
else:
if property.get('is_reference', False):
out = { property['name']: property['default'] }
else:
out = { property['name']: '(( .properties.{}.value ))'.format(property['name']) }
return out | Render a property for bosh manifest, according to its type. |
def load_csv(self):
if path.exists(self.csv_filepath):
self.results = self.results.append(
pandas.read_csv(self.csv_filepath)) | Load old benchmark results from CSV. |
def create(self):
out = helm(
"repo",
"add",
"jupyterhub",
self.helm_repo
)
out = helm("repo", "update")
secret_yaml = self.get_security_yaml()
out = helm(
"upgrade",
"--install",
self.release,
"jupyterhub/jupyterhub",
namespace=self.namespace,
version=self.version,
input=secret_yaml
)
if out.returncode != 0:
print(out.stderr)
else:
print(out.stdout) | Create a single instance of notebook. |
def commit(self):
self._addFlushBatch()
for core in self.endpoints:
self._send_solr_command(self.endpoints[core], "{ \"commit\":{} }") | Flushes all pending changes and commits Solr changes |
def samples_to_batches(samples: Iterable, batch_size: int):
it = iter(samples)
while True:
with suppress(StopIteration):
batch_in, batch_out = [], []
for i in range(batch_size):
sample_in, sample_out = next(it)
batch_in.append(sample_in)
batch_out.append(sample_out)
if not batch_in:
raise StopIteration
yield np.array(batch_in), np.array(batch_out) | Chunk a series of network inputs and outputs into larger batches |
def _dump_model(model, attrs=None):
fields = []
for field in model._meta.fields:
fields.append((field.name, str(getattr(model, field.name))))
if attrs is not None:
for attr in attrs:
fields.append((attr, str(getattr(model, attr))))
for field in model._meta.many_to_many:
vals = getattr(model, field.name)
fields.append((field.name, '{val} ({count})'.format(
val=', '.join(map(str, vals.all())),
count=vals.count(),
)))
print(', '.join(
'{0}={1}'.format(field, value)
for field, value in fields
)) | Dump the model fields for debugging. |
def total_consumption(self):
if self.use_legacy_protocol:
return 'N/A'
res = 'N/A'
try:
res = self.SOAPAction("GetPMWarningThreshold", "TotalConsumption", self.moduleParameters("2"))
except:
return 'N/A'
if res is None:
return 'N/A'
try:
float(res)
except ValueError:
_LOGGER.error("Failed to retrieve total power consumption from SmartPlug")
return res | Get the total power consumpuntion in the device lifetime. |
def open_mask_rle(mask_rle:str, shape:Tuple[int, int])->ImageSegment:
"Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`."
x = FloatTensor(rle_decode(str(mask_rle), shape).astype(np.uint8))
x = x.view(shape[1], shape[0], -1)
return ImageSegment(x.permute(2,0,1)) | Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`. |
def isNewerThan(self, other):
if self.getValue("name") == other.getValue("name"):
if other.getValue("version"):
if not other.getValue("version"):
return False
else:
return LooseVersion(self.getValue("version")) > LooseVersion(other.getValue("version"))
else:
return True
else:
return False | Compare if the version of this app is newer that the other |
def _send_view_change_done_message(self):
new_primary_name = self.provider.next_primary_name()
ledger_summary = self.provider.ledger_summary()
message = ViewChangeDone(self.view_no,
new_primary_name,
ledger_summary)
logger.info("{} is sending ViewChangeDone msg to all : {}".format(self, message))
self.send(message)
self._on_verified_view_change_done_msg(message, self.name) | Sends ViewChangeDone message to other protocol participants |
def ask_dir(self):
args ['directory'] = askdirectory(**self.dir_opt)
self.dir_text.set(args ['directory']) | dialogue box for choosing directory |
def _clean_for_xml(data):
if data:
data = data.encode("ascii", "xmlcharrefreplace").decode("ascii")
return _illegal_xml_chars_re.sub("", data)
return data | Sanitize any user-submitted data to ensure that it can be used in XML |
def power_status_update(self, POWER_STATUS):
now = time.time()
Vservo = POWER_STATUS.Vservo * 0.001
Vcc = POWER_STATUS.Vcc * 0.001
self.high_servo_voltage = max(self.high_servo_voltage, Vservo)
if self.high_servo_voltage > 1 and Vservo < self.settings.servowarn:
if now - self.last_servo_warn_time > 30:
self.last_servo_warn_time = now
self.say("Servo volt %.1f" % Vservo)
if Vservo < 1:
self.high_servo_voltage = Vservo
if Vcc > 0 and Vcc < self.settings.vccwarn:
if now - self.last_vcc_warn_time > 30:
self.last_vcc_warn_time = now
self.say("Vcc %.1f" % Vcc) | update POWER_STATUS warnings level |
def add(self, modpath, name, origin):
self.map.setdefault(modpath, {}).setdefault(name, set()).add(origin) | Adds a possible origin for the given name in the given module. |
def parameter_struct_dict(self):
if self._parameter_struct_dict is None:
self._parameter_struct_dict = self._make_ff_params_dict()
elif self.auto_update_f_params:
new_hash = hash(
tuple([tuple(item)
for sublist in self.values()
for item in sublist.values()]))
if self._old_hash != new_hash:
self._parameter_struct_dict = self._make_ff_params_dict()
self._old_hash = new_hash
return self._parameter_struct_dict | Dictionary containing PyAtomData structs for the force field. |
def output_cert(gandi, cert, output_keys, justify=13):
output = list(output_keys)
display_altnames = False
if 'altnames' in output:
display_altnames = True
output.remove('altnames')
display_output = False
if 'cert' in output:
display_output = True
output.remove('cert')
output_generic(gandi, cert, output, justify)
if display_output:
crt = gandi.certificate.pretty_format_cert(cert)
if crt:
output_line(gandi, 'cert', '\n' + crt, justify)
if display_altnames:
for altname in cert['altnames']:
output_line(gandi, 'altname', altname, justify) | Helper to output a certificate information. |
def _config_drag_cols(self, drag_cols):
self._drag_cols = drag_cols
if self._drag_cols:
self._im_drag.paste(self._im_draggable)
else:
self._im_drag.paste(self._im_not_draggable)
self.focus_set()
self.update_idletasks() | Configure a new drag_cols state |
def clean_text(self, domain, **kwargs):
try:
domain = urlparse(domain).hostname or domain
domain = domain.lower()
domain = domain.rsplit(':', 1)[0]
domain = domain.rstrip('.')
domain = domain.encode("idna").decode('ascii')
except ValueError:
return None
if self.validate(domain):
return domain | Try to extract only the domain bit from the |
def kill_cursor(self, cursor):
text = cursor.selectedText()
if text:
cursor.removeSelectedText()
self.kill(text) | Kills the text selected by the give cursor. |
def stop(self):
with self._operational_lock:
self._bidi_rpc.close()
if self._thread is not None:
self.resume()
self._thread.join()
self._thread = None | Stop consuming the stream and shutdown the background thread. |
def require_minimum_pyarrow_version():
minimum_pyarrow_version = "0.12.1"
from distutils.version import LooseVersion
try:
import pyarrow
have_arrow = True
except ImportError:
have_arrow = False
if not have_arrow:
raise ImportError("PyArrow >= %s must be installed; however, "
"it was not found." % minimum_pyarrow_version)
if LooseVersion(pyarrow.__version__) < LooseVersion(minimum_pyarrow_version):
raise ImportError("PyArrow >= %s must be installed; however, "
"your version was %s." % (minimum_pyarrow_version, pyarrow.__version__)) | Raise ImportError if minimum version of pyarrow is not installed |
def on_finish(self, exc=None):
super(GarbageCollector, self).on_finish(exc)
self._cycles_left -= 1
if self._cycles_left <= 0:
num_collected = gc.collect()
self._cycles_left = self.collection_cycle
LOGGER.debug('garbage collection run, %d objects evicted',
num_collected) | Used to initiate the garbage collection |
def exception_class(self, exception):
cls = type(exception)
if cls.__module__ == 'exceptions':
return cls.__name__
return "%s.%s" % (cls.__module__, cls.__name__) | Return a name representing the class of an exception. |
async def get_playback_settings(self) -> List[Setting]:
return [
Setting.make(**x)
for x in await self.services["avContent"]["getPlaybackModeSettings"]({})
] | Get playback settings such as shuffle and repeat. |
def write (self, data):
self.tmpbuf.append(data)
self.pos += len(data) | Write data to buffer. |
def dump (env, form):
for var, value in env.items():
log(env, var+"="+value)
for key in form:
log(env, str(formvalue(form, key))) | Log environment and form. |
def analysis_question_report(feature, parent):
_ = feature, parent
project_context_scope = QgsExpressionContextUtils.projectScope()
key = provenance_layer_analysis_impacted['provenance_key']
if not project_context_scope.hasVariable(key):
return None
analysis_dir = dirname(project_context_scope.variable(key))
complete_html_report = get_impact_report_as_string(analysis_dir)
requested_html_report = get_report_section(
complete_html_report, component_id=analysis_question_component['key'])
return requested_html_report | Retrieve the analysis question section from InaSAFE report. |
def _rds_cluster_tags(model, dbs, session_factory, generator, retry):
client = local_session(session_factory).client('rds')
def process_tags(db):
try:
db['Tags'] = retry(
client.list_tags_for_resource,
ResourceName=generator(db[model.id]))['TagList']
return db
except client.exceptions.DBClusterNotFoundFault:
return None
return list(filter(None, map(process_tags, dbs))) | Augment rds clusters with their respective tags. |
def correction(sentence, pos):
"Most probable spelling correction for word."
word = sentence[pos]
cands = candidates(word)
if not cands:
cands = candidates(word, False)
if not cands:
return word
cands = sorted(cands, key=lambda w: P(w, sentence, pos), reverse=True)
cands = [c[0] for c in cands]
return cands | Most probable spelling correction for word. |
def _node_runner():
env.host_string = lib.get_env_host_string()
node = lib.get_node(env.host_string)
_configure_fabric_for_platform(node.get("platform"))
if __testing__:
print "TEST: would now configure {0}".format(env.host_string)
else:
lib.print_header("Configuring {0}".format(env.host_string))
if env.autodeploy_chef and not chef.chef_test():
deploy_chef(ask="no")
chef.sync_node(node) | This is only used by node so that we can execute in parallel |
def family_directory(fonts):
if fonts:
dirname = os.path.dirname(fonts[0])
if dirname == '':
dirname = '.'
return dirname | Get the path of font project directory. |
def reset_small(self, eq):
assert eq in ('f', 'g')
for idx, var in enumerate(self.__dict__[eq]):
if abs(var) <= 1e-12:
self.__dict__[eq][idx] = 0 | Reset numbers smaller than 1e-12 in f and g equations |
def smoothness(self):
energies = self.energies
try:
sp = self.spline()
except:
print("Energy spline failed.")
return None
spline_energies = sp(range(len(energies)))
diff = spline_energies - energies
rms = np.sqrt(np.sum(np.square(diff)) / len(energies))
return rms | Get rms average difference between spline and energy trend. |
def send_stdout(cls, sock, payload):
cls.write_chunk(sock, ChunkType.STDOUT, payload) | Send the Stdout chunk over the specified socket. |
def implements(obj, protocol):
if isinstance(obj, type):
raise TypeError("First argument to implements must be an instance. "
"Got %r." % obj)
return isinstance(obj, protocol) or issubclass(AnyType, protocol) | Does the object 'obj' implement the 'prococol'? |
def load_from_local(cls):
try:
with open(cls.LOCAL_DB_PATH, 'rb') as f:
b = f.read()
s = security.protege_data(b, False)
except (FileNotFoundError, KeyError):
logging.exception(cls.__name__)
raise StructureError(
"Erreur dans le chargement de la sauvegarde locale !")
else:
return cls(cls.decode_json_str(s)) | Load datas from local file. |
def pick_monomials_up_to_degree(monomials, degree):
ordered_monomials = []
if degree >= 0:
ordered_monomials.append(S.One)
for deg in range(1, degree + 1):
ordered_monomials.extend(pick_monomials_of_degree(monomials, deg))
return ordered_monomials | Collect monomials up to a given degree. |
def unlock(self, request, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
self.object.status = Topic.TOPIC_UNLOCKED
self.object.save()
messages.success(self.request, self.success_message)
return HttpResponseRedirect(success_url) | Unlocks the considered topic and retirects the user to the success URL. |
def option_changed(self, option, value):
setattr(self, to_text_string(option), value)
self.shellwidget.set_namespace_view_settings()
if self.setup_in_progress is False:
self.sig_option_changed.emit(option, value) | Handle when the value of an option has changed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.