code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def _parse_mut(mut):
multiplier = 1
if mut.startswith("-"):
mut = mut[1:]
multiplier = -1
nt = mut.strip('0123456789')
pos = int(mut[:-2]) * multiplier
return nt, pos | module function_definition identifier parameters identifier block expression_statement assignment identifier integer if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier subscript identifier slice integer expression_statement assignment identifier unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator call identifier argument_list subscript identifier slice unary_operator integer identifier return_statement expression_list identifier identifier | Parse mutation field to get position and nts. |
def install_config(self):
text = templ_config.render(**self.options)
config = Configuration(self.buildout, 'supervisord.conf', {
'deployment': self.deployment_name,
'text': text})
return [config.install()] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier return_statement list call attribute identifier identifier argument_list | install supervisor main config file |
def auth(self, encoded):
message, signature = self.split(encoded)
computed = self.sign(message)
if not hmac.compare_digest(signature, computed):
raise AuthenticatorInvalidSignature | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator call attribute identifier identifier argument_list identifier identifier block raise_statement identifier | Validate integrity of encoded bytes |
def reject(self):
if self.hideWindow():
self.hideWindow().show()
self.close()
self.deleteLater() | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Rejects the snapshot and closes the widget. |
def build_graph(formula):
graph = {}
for clause in formula:
for (lit, _) in clause:
for neg in [False, True]:
graph[(lit, neg)] = []
for ((a_lit, a_neg), (b_lit, b_neg)) in formula:
add_edge(graph, (a_lit, a_neg), (b_lit, not b_neg))
add_edge(graph, (b_lit, b_neg), (a_lit, not a_neg))
return graph | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block for_statement tuple_pattern identifier identifier identifier block for_statement identifier list false true block expression_statement assignment subscript identifier tuple identifier identifier list for_statement tuple_pattern tuple_pattern identifier identifier tuple_pattern identifier identifier identifier block expression_statement call identifier argument_list identifier tuple identifier identifier tuple identifier not_operator identifier expression_statement call identifier argument_list identifier tuple identifier identifier tuple identifier not_operator identifier return_statement identifier | Builds the implication graph from the formula |
def _find_integer_tolerance(epsilon, v_max, min_tol):
int_tol = min(epsilon / (10 * v_max), 0.1)
min_tol = max(1e-10, min_tol)
if int_tol < min_tol:
eps_lower = min_tol * 10 * v_max
logger.warning(
'When the maximum flux is {}, it is recommended that'
' epsilon > {} to avoid numerical issues with this'
' solver. Results may be incorrect with'
' the current settings!'.format(v_max, eps_lower))
return min_tol
return int_tol | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator identifier parenthesized_expression binary_operator integer identifier float expression_statement assignment identifier call identifier argument_list float identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier binary_operator binary_operator identifier integer identifier expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier identifier return_statement identifier return_statement identifier | Find appropriate integer tolerance for gap-filling problems. |
def create_csp_header(cspDict):
policy = ['%s %s' % (k, v) for k, v in cspDict.items() if v != '']
return '; '.join(policy) | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension binary_operator string string_start string_content string_end tuple identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier string string_start string_end return_statement call attribute string string_start string_content string_end identifier argument_list identifier | create csp header string |
def collab_learner(data, n_factors:int=None, use_nn:bool=False, emb_szs:Dict[str,int]=None, layers:Collection[int]=None,
ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True,
bn_final:bool=False, **learn_kwargs)->Learner:
"Create a Learner for collaborative filtering on `data`."
emb_szs = data.get_emb_szs(ifnone(emb_szs, {}))
u,m = data.train_ds.x.classes.values()
if use_nn: model = EmbeddingNN(emb_szs=emb_szs, layers=layers, ps=ps, emb_drop=emb_drop, y_range=y_range,
use_bn=use_bn, bn_final=bn_final, **learn_kwargs)
else: model = EmbeddingDotBias(n_factors, len(u), len(m), y_range=y_range)
return CollabLearner(data, model, **learn_kwargs) | module function_definition identifier parameters identifier typed_default_parameter identifier type identifier none typed_default_parameter identifier type identifier false typed_default_parameter identifier type generic_type identifier type_parameter type identifier type identifier none typed_default_parameter identifier type generic_type identifier type_parameter type identifier none typed_default_parameter identifier type generic_type identifier type_parameter type identifier none typed_default_parameter identifier type identifier float typed_default_parameter identifier type identifier none typed_default_parameter identifier type identifier true typed_default_parameter identifier type identifier false dictionary_splat_pattern identifier type identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier dictionary expression_statement assignment pattern_list identifier identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list identifier call identifier argument_list identifier keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier dictionary_splat identifier | Create a Learner for collaborative filtering on `data`. |
def upgrade_defaults(self):
self.defaults.upgrade()
self.reset_defaults(self.defaults.filename) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier | Upgrade config file and reload. |
def redact_http_basic_auth(output):
url_re = '(https?)://.*@'
redacted = r'\1://<redacted>@'
if sys.version_info >= (2, 7):
return re.sub(url_re, redacted, output, flags=re.IGNORECASE)
else:
if re.search(url_re, output.lower()):
return re.sub(url_re, redacted, output.lower())
return output | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator attribute identifier identifier tuple integer integer block return_statement call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier attribute identifier identifier else_clause block if_statement call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list block return_statement call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list return_statement identifier | Remove HTTP user and password |
def import_backend(config):
backend_name = config['backend']
path = backend_name.split('.')
backend_mod_name, backend_class_name = '.'.join(path[:-1]), path[-1]
backend_mod = importlib.import_module(backend_mod_name)
backend_class = getattr(backend_mod, backend_class_name)
return backend_class(config['settings']) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier expression_list call attribute string string_start string_content string_end identifier argument_list subscript identifier slice unary_operator integer subscript identifier unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement call identifier argument_list subscript identifier string string_start string_content string_end | Imports and initializes the Backend class. |
def __make_scubadir(self):
self.__scubadir_hostpath = tempfile.mkdtemp(prefix='scubadir')
self.__scubadir_contpath = '/.scuba'
self.add_volume(self.__scubadir_hostpath, self.__scubadir_contpath) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Make temp directory where all ancillary files are bind-mounted |
def example_ylm(m=0, n=2, shape=128, limits=[-4, 4], draw=True, show=True, **kwargs):
import ipyvolume.pylab as p3
__, __, __, r, theta, phi = xyz(shape=shape, limits=limits, spherical=True)
radial = np.exp(-(r - 2) ** 2)
data = np.abs(scipy.special.sph_harm(m, n, theta, phi) ** 2) * radial
if draw:
vol = p3.volshow(data=data, **kwargs)
if show:
p3.show()
return vol
else:
return data | module function_definition identifier parameters default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier list unary_operator integer integer default_parameter identifier true default_parameter identifier true dictionary_splat_pattern identifier block import_statement aliased_import dotted_name identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier identifier identifier identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier true expression_statement assignment identifier call attribute identifier identifier argument_list unary_operator binary_operator parenthesized_expression binary_operator identifier integer integer expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list binary_operator call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier integer identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier dictionary_splat identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list return_statement identifier else_clause block return_statement identifier | Show a spherical harmonic. |
def _insert_html_configs(c, *, project_name, short_project_name):
c['templates_path'] = [
'_templates',
lsst_sphinx_bootstrap_theme.get_html_templates_path()]
c['html_theme'] = 'lsst_sphinx_bootstrap_theme'
c['html_theme_path'] = [lsst_sphinx_bootstrap_theme.get_html_theme_path()]
c['html_theme_options'] = {'logotext': short_project_name}
c['html_title'] = project_name
c['html_short_title'] = short_project_name
c['html_logo'] = None
c['html_favicon'] = None
if os.path.isdir('_static'):
c['html_static_path'] = ['_static']
else:
c['html_static_path'] = []
c['html_last_updated_fmt'] = '%b %d, %Y'
c['html_use_smartypants'] = True
c['html_domain_indices'] = False
c['html_use_index'] = False
c['html_split_index'] = False
c['html_show_sourcelink'] = True
c['html_show_sphinx'] = True
c['html_show_copyright'] = True
c['html_file_suffix'] = '.html'
c['html_search_language'] = 'en'
return c | module function_definition identifier parameters identifier keyword_separator identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end list string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end list call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end dictionary pair string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end none expression_statement assignment subscript identifier string string_start string_content string_end none if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end list string string_start string_content string_end else_clause block expression_statement assignment subscript identifier string string_start string_content string_end list expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end true expression_statement assignment subscript identifier string string_start string_content string_end false expression_statement assignment subscript identifier string string_start string_content string_end false expression_statement assignment subscript identifier string string_start string_content string_end false expression_statement assignment subscript identifier string string_start string_content string_end true expression_statement assignment subscript identifier string string_start string_content string_end true expression_statement assignment subscript identifier string string_start string_content string_end true expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end return_statement identifier | Insert HTML theme configurations. |
def convertDate(date):
d, t = date.split('T')
return decimal_date(d, timeobs=t) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list identifier keyword_argument identifier identifier | Convert DATE string into a decimal year. |
def comply(self, path):
utils.ensure_permissions(path, self.user.pw_name, self.group.gr_name,
self.mode) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier attribute identifier identifier | Issues a chown and chmod to the file paths specified. |
def to_det_oid(self, det_id_or_det_oid):
try:
int(det_id_or_det_oid)
except ValueError:
return det_id_or_det_oid
else:
return self.get_det_oid(det_id_or_det_oid) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call identifier argument_list identifier except_clause identifier block return_statement identifier else_clause block return_statement call attribute identifier identifier argument_list identifier | Convert det OID or ID to det OID |
def msg(self, target, message, formatted=True, tags=None):
if formatted:
message = unescape(message)
self.send('PRIVMSG', params=[target, message], source=self.nick, tags=tags) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true default_parameter identifier none block if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier list identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier | Send a privmsg to the given target. |
def _check_status(self):
logger.info('Checking repo status')
status = self.log_call(
['git', 'status', '--porcelain'],
callwith=subprocess.check_output,
cwd=self.cwd,
)
if status:
raise DirtyException(status) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier if_statement identifier block raise_statement call identifier argument_list identifier | Check repo status and except if dirty. |
def _remove_finder(importer, finder):
existing_finder = _get_finder(importer)
if not existing_finder:
return
if isinstance(existing_finder, ChainedFinder):
try:
existing_finder.finders.remove(finder)
except ValueError:
return
if len(existing_finder.finders) == 1:
pkg_resources.register_finder(importer, existing_finder.finders[0])
elif len(existing_finder.finders) == 0:
pkg_resources.register_finder(importer, pkg_resources.find_nothing)
else:
pkg_resources.register_finder(importer, pkg_resources.find_nothing) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block return_statement if_statement call identifier argument_list identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier block return_statement if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list identifier subscript attribute identifier identifier integer elif_clause comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier | Remove an existing finder from pkg_resources. |
def _merge_sorted_items(self, index):
def load_partition(j):
path = self._get_spill_dir(j)
p = os.path.join(path, str(index))
with open(p, 'rb', 65536) as f:
for v in self.serializer.load_stream(f):
yield v
disk_items = [load_partition(j) for j in range(self.spills)]
if self._sorted:
sorted_items = heapq.merge(disk_items, key=operator.itemgetter(0))
else:
ser = self.flattened_serializer()
sorter = ExternalSorter(self.memory_limit, ser)
sorted_items = sorter.sorted(itertools.chain(*disk_items),
key=operator.itemgetter(0))
return ((k, vs) for k, vs in GroupByKey(sorted_items)) | module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end integer as_pattern_target identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list identifier block expression_statement yield identifier expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier call identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list integer else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list list_splat identifier keyword_argument identifier call attribute identifier identifier argument_list integer return_statement generator_expression tuple identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier | load a partition from disk, then sort and group by key |
def user_terms_updated(sender, **kwargs):
LOGGER.debug("User T&C Updated Signal Handler")
if kwargs.get('instance').user:
cache.delete('tandc.not_agreed_terms_' + kwargs.get('instance').user.get_username()) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list | Called when user terms and conditions is changed - to force cache clearing |
def cmd_up(self, args):
if len(args) == 0:
adjust = 5.0
else:
adjust = float(args[0])
old_trim = self.get_mav_param('TRIM_PITCH_CD', None)
if old_trim is None:
print("Existing trim value unknown!")
return
new_trim = int(old_trim + (adjust*100))
if math.fabs(new_trim - old_trim) > 1000:
print("Adjustment by %d too large (from %d to %d)" % (adjust*100, old_trim, new_trim))
return
print("Adjusting TRIM_PITCH_CD from %d to %d" % (old_trim, new_trim))
self.param_set('TRIM_PITCH_CD', new_trim) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier float else_clause block expression_statement assignment identifier call identifier argument_list subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement comparison_operator identifier none block expression_statement call identifier argument_list string string_start string_content string_end return_statement expression_statement assignment identifier call identifier argument_list binary_operator identifier parenthesized_expression binary_operator identifier integer if_statement comparison_operator call attribute identifier identifier argument_list binary_operator identifier identifier integer block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple binary_operator identifier integer identifier identifier return_statement expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | adjust TRIM_PITCH_CD up by 5 degrees |
def to_unit(C, val, unit=None):
md = re.match(r'^(?P<num>[\d\.]+)(?P<unit>.*)$', val)
if md is not None:
un = float(md.group('num')) * CSS.units[md.group('unit')]
if unit is not None:
return un.asUnit(unit)
else:
return un | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end subscript attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block return_statement call attribute identifier identifier argument_list identifier else_clause block return_statement identifier | convert a string measurement to a Unum |
def send(self, to, from_, body):
try:
msg = self.client.sms.messages.create(
body=body,
to=to,
from_=from_
)
print msg.sid
except twilio.TwilioRestException as e:
raise | module function_definition identifier parameters identifier identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier print_statement attribute identifier identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block raise_statement | Send BODY to TO from FROM as an SMS! |
def show_grid_from_file(self, fname):
with open(fname, "r") as f:
for y, row in enumerate(f):
for x, val in enumerate(row):
self.draw_cell(y, x, val) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier | reads a saved grid file and paints it on the canvas |
def _apply_orthogonal_view(self):
left, right, bottom, top = self.get_view_coordinates()
glOrtho(left, right, bottom, top, -10, 0) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier identifier identifier identifier unary_operator integer integer | Orthogonal view with respect to current aspect ratio |
def system_summary(providername=None):
_providername = providername
if not _providername:
_providername = provider_check()
import_str = 'netshowlib.%s.system_summary' % _providername
return import_module(import_str).SystemSummary() | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier identifier if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content string_end identifier return_statement call attribute call identifier argument_list identifier identifier argument_list | returns SystemSummary class from mentioned provider |
def emit(self, record):
if self.triggerLevelNo is not None and record.levelno>=self.triggerLevelNo:
self.triggered = True
logging.handlers.BufferingHandler.emit(self,record) | module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier true expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier | Emit record after checking if message triggers later sending of e-mail. |
def unquote_string(self, string):
value = string[1:-1]
forbidden_sequences = {ESCAPE_SUBS[STRING_QUOTES[string[0]]]}
valid_sequences = set(ESCAPE_SEQUENCES) - forbidden_sequences
for seq in ESCAPE_REGEX.findall(value):
if seq not in valid_sequences:
raise self.error(f'Invalid escape sequence "{seq}"')
for seq, sub in ESCAPE_SEQUENCES.items():
value = value.replace(seq, sub)
return value | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier slice integer unary_operator integer expression_statement assignment identifier set subscript identifier subscript identifier subscript identifier integer expression_statement assignment identifier binary_operator call identifier argument_list identifier identifier for_statement identifier call attribute identifier identifier argument_list identifier block if_statement comparison_operator identifier identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content interpolation identifier string_content string_end for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier | Return the unquoted value of a quoted string. |
def combine_hla_fqs(hlas, out_file, data):
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for hla_type, hla_fq in hlas:
if utils.file_exists(hla_fq):
with open(hla_fq) as in_handle:
shutil.copyfileobj(in_handle, out_handle)
return out_file | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier identifier as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement pattern_list identifier identifier identifier block if_statement call attribute identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier return_statement identifier | OptiType performs best on a combination of all extracted HLAs. |
def machine_listings_to_file_entries(listings: Iterable[dict]) -> \
Iterable[FileEntry]:
for listing in listings:
yield FileEntry(
listing['name'],
type=listing.get('type'),
size=listing.get('size'),
date=listing.get('modify')
) | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier line_continuation type generic_type identifier type_parameter type identifier block for_statement identifier identifier block expression_statement yield call identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end | Convert results from parsing machine listings to FileEntry list. |
def crop_box(im, box=False, **kwargs):
if box:
im = im.crop(box)
return im | module function_definition identifier parameters identifier default_parameter identifier false dictionary_splat_pattern identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Uses box coordinates to crop an image without resizing it first. |
def execfile(fname, variables):
with open(fname) as f:
code = compile(f.read(), fname, 'exec')
exec(code, variables) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement call identifier argument_list identifier identifier | This is builtin in python2, but we have to roll our own on py3. |
def initialize(self):
if self.croniter is None:
self.time = time.time()
self.datetime = datetime.now(self.tz)
self.loop_time = self.loop.time()
self.croniter = croniter(self.spec, start_time=self.datetime) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier | Initialize croniter and related times |
def start_index(self):
paginator = self.paginator
if paginator.count == 0:
return 0
elif self.number == 1:
return 1
return (
(self.number - 2) * paginator.per_page + paginator.first_page + 1) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block return_statement integer elif_clause comparison_operator attribute identifier identifier integer block return_statement integer return_statement parenthesized_expression binary_operator binary_operator binary_operator parenthesized_expression binary_operator attribute identifier identifier integer attribute identifier identifier attribute identifier identifier integer | Return the 1-based index of the first item on this page. |
def _initial_interior_point(self, buses, generators, xmin, xmax, ny):
Va = self.om.get_var("Va")
va_refs = [b.v_angle * pi / 180.0 for b in buses
if b.type == REFERENCE]
x0 = (xmin + xmax) / 2.0
x0[Va.i1:Va.iN + 1] = va_refs[0]
if ny > 0:
yvar = self.om.get_var("y")
c = []
for g in generators:
if g.pcost_model == PW_LINEAR:
for _, y in g.p_cost:
c.append(y)
x0[yvar.i1:yvar.iN + 1] = max(c) * 1.1
return x0 | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list_comprehension binary_operator binary_operator attribute identifier identifier identifier float for_in_clause identifier identifier if_clause comparison_operator attribute identifier identifier identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier float expression_statement assignment subscript identifier slice attribute identifier identifier binary_operator attribute identifier identifier integer subscript identifier integer if_statement comparison_operator identifier integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block for_statement pattern_list identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier slice attribute identifier identifier binary_operator attribute identifier identifier integer binary_operator call identifier argument_list identifier float return_statement identifier | Selects an interior initial point for interior point solver. |
def sink_storage(client, to_delete):
bucket = _sink_storage_setup(client)
to_delete.append(bucket)
SINK_NAME = "robots-storage-%d" % (_millis(),)
FILTER = "textPayload:robot"
DESTINATION = "storage.googleapis.com/%s" % (bucket.name,)
sink = client.sink(SINK_NAME, filter_=FILTER, destination=DESTINATION)
assert not sink.exists()
sink.create()
assert sink.exists()
to_delete.insert(0, sink) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple call identifier argument_list expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier assert_statement not_operator call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list assert_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list integer identifier | Sink log entries to storage. |
def save(self, fname=''):
if fname != '':
with open(fname, 'w') as f:
for i in self.lstPrograms:
f.write(self.get_file_info_line(i, ','))
filemap = mod_filemap.FileMap([], [])
object_fileList = filemap.get_full_filename(filemap.find_type('OBJECT'), filemap.find_ontology('FILE-PROGRAM')[0])
print('object_fileList = ' + object_fileList + '\n')
if os.path.exists(object_fileList):
os.remove(object_fileList)
self.lstPrograms.sort()
try:
with open(object_fileList, 'a') as f:
f.write('\n'.join([i[0] for i in self.lstPrograms]))
except Exception as ex:
print('ERROR = cant write to object_filelist ' , object_fileList, str(ex)) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end block if_statement comparison_operator identifier string string_start string_end block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list list list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end subscript call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement call identifier argument_list binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content escape_sequence string_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list try_statement block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list list_comprehension subscript identifier integer for_in_clause identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier call identifier argument_list identifier | Save the list of items to AIKIF core and optionally to local file fname |
def get(self, *args, **kwargs):
self.before_get(args, kwargs)
relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()
obj, data = self._data_layer.get_relationship(model_relationship_field,
related_type_,
related_id_field,
kwargs)
result = {'links': {'self': request.path,
'related': self.schema._declared_fields[relationship_field].get_related_url(obj)},
'data': data}
qs = QSManager(request.args, self.schema)
if qs.include:
schema = compute_schema(self.schema, dict(), qs, qs.include)
serialized_obj = schema.dump(obj)
result['included'] = serialized_obj.data.get('included', dict())
final_result = self.after_get(result)
return final_result | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call attribute subscript attribute attribute identifier identifier identifier identifier identifier argument_list identifier pair string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier call identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Get a relationship details |
def size(self):
try:
return os.fstat(self.file.fileno()).st_size
except io.UnsupportedOperation:
pass
if is_seekable(self.file):
with wpull.util.reset_file_offset(self.file):
self.file.seek(0, os.SEEK_END)
return self.file.tell()
raise OSError('Unsupported operation.') | module function_definition identifier parameters identifier block try_statement block return_statement attribute call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier except_clause attribute identifier identifier block pass_statement if_statement call identifier argument_list attribute identifier identifier block with_statement with_clause with_item call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list integer attribute identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list raise_statement call identifier argument_list string string_start string_content string_end | Return the size of the file. |
async def _clean_shutdown(self):
remaining_tasks = []
for task in self._tasks.get(None, []):
self._logger.debug("Cancelling task at shutdown %s", task)
task.cancel()
remaining_tasks.append(task)
asyncio.gather(*remaining_tasks, return_exceptions=True)
if len(remaining_tasks) > 0:
del self._tasks[None]
remaining_tasks = []
for address in sorted(self._tasks, reverse=True):
if address is None:
continue
self._logger.debug("Shutting down tasks for tile at %d", address)
for task in self._tasks.get(address, []):
task.cancel()
remaining_tasks.append(task)
asyncio.gather(*remaining_tasks, return_exceptions=True)
await self._rpc_queue.stop()
self._loop.stop() | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call attribute attribute identifier identifier identifier argument_list none list block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list list_splat identifier keyword_argument identifier true if_statement comparison_operator call identifier argument_list identifier integer block delete_statement subscript attribute identifier identifier none expression_statement assignment identifier list for_statement identifier call identifier argument_list attribute identifier identifier keyword_argument identifier true block if_statement comparison_operator identifier none block continue_statement expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier for_statement identifier call attribute attribute identifier identifier identifier argument_list identifier list block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list list_splat identifier keyword_argument identifier true expression_statement await call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list | Cleanly shutdown the emulation loop. |
def piece_wise_linear(scale, points):
assert len(points) >= 2
assert points[0][0] == 0
assert points[-1][0] == 1
assert all(i < j for i, j in zip(points[:-1], points[1:]))
out = numpy.zeros((scale, 3))
p1, c1 = points[0]
p2, c2 = points[1]
next_pt = 2
for i in range(1, scale):
v = i / scale
if v > p2:
p1, c1 = p2, c2
p2, c2 = points[next_pt]
next_pt += 1
frac = (v - p1) / (p2 - p1)
out[i, :] = c1 * (1 - frac) + c2 * frac
return out | module function_definition identifier parameters identifier identifier block assert_statement comparison_operator call identifier argument_list identifier integer assert_statement comparison_operator subscript subscript identifier integer integer integer assert_statement comparison_operator subscript subscript identifier unary_operator integer integer integer assert_statement call identifier generator_expression comparison_operator identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list subscript identifier slice unary_operator integer subscript identifier slice integer expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier integer expression_statement assignment pattern_list identifier identifier subscript identifier integer expression_statement assignment pattern_list identifier identifier subscript identifier integer expression_statement assignment identifier integer for_statement identifier call identifier argument_list integer identifier block expression_statement assignment identifier binary_operator identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment pattern_list identifier identifier expression_list identifier identifier expression_statement assignment pattern_list identifier identifier subscript identifier identifier expression_statement augmented_assignment identifier integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier parenthesized_expression binary_operator identifier identifier expression_statement assignment subscript identifier identifier slice binary_operator binary_operator identifier parenthesized_expression binary_operator integer identifier binary_operator identifier identifier return_statement identifier | Create a palette that is piece-wise linear given some colors at points. |
def updateSiteName(self, block_name, origin_site_name):
if not origin_site_name:
dbsExceptionHandler('dbsException-invalid-input',
"DBSBlock/updateSiteName. origin_site_name is mandatory.")
conn = self.dbi.connection()
trans = conn.begin()
try:
self.updatesitename.execute(conn, block_name, origin_site_name)
except:
if trans:
trans.rollback()
raise
else:
if trans:
trans.commit()
finally:
if conn:
conn.close() | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier except_clause block if_statement identifier block expression_statement call attribute identifier identifier argument_list raise_statement else_clause block if_statement identifier block expression_statement call attribute identifier identifier argument_list finally_clause block if_statement identifier block expression_statement call attribute identifier identifier argument_list | Update the origin_site_name for a given block name |
def to_geojson(self, filename):
with open(filename, 'w') as fd:
json.dump(self.to_record(WGS84_CRS), fd) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier | Save vector as geojson. |
def _on_sphinx_thread_error_msg(self, error_msg):
self._sphinx_thread.wait()
self.plain_text_action.setChecked(True)
sphinx_ver = programs.get_module_version('sphinx')
QMessageBox.critical(self,
_('Help'),
_("The following error occured when calling "
"<b>Sphinx %s</b>. <br>Incompatible Sphinx "
"version or doc string decoding failed."
"<br><br>Error message:<br>%s"
) % (sphinx_ver, error_msg)) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list string string_start string_content string_end binary_operator call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end tuple identifier identifier | Display error message on Sphinx rich text failure |
def _load_names(self) -> List[str]:
names = []
for path in self._get_files():
for name in self._get_names(path):
names.append(self._normalize_name(name))
return names | module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement identifier | Return list of thirdparty modules from requirements |
def update(self):
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_charging_params(self._id)
if data:
self.__battery_range = data['battery_range']
self.__est_battery_range = data['est_battery_range']
self.__ideal_battery_range = data['ideal_battery_range']
data = self._controller.get_gui_params(self._id)
if data:
if data['gui_distance_units'] == "mi/hr":
self.measurement = 'LENGTH_MILES'
else:
self.measurement = 'LENGTH_KILOMETERS'
self.__rated = (data['gui_range_display'] == "Rated") | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier false expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement identifier block expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement identifier block if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment attribute identifier identifier string string_start string_content string_end else_clause block expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier parenthesized_expression comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end | Update the battery range state. |
def mirror():
slack_mirror = read_config(
read_file("{0}{1}".format(etc_slackpkg, "mirrors")))
if slack_mirror:
return slack_mirror + changelog_txt
else:
print("\nYou do not have any mirror selected in /etc/slackpkg/mirrors"
"\nPlease edit that file and uncomment ONE mirror.\n")
return "" | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier string string_start string_content string_end if_statement identifier block return_statement binary_operator identifier identifier else_clause block expression_statement call identifier argument_list concatenated_string string string_start string_content escape_sequence string_end string string_start string_content escape_sequence escape_sequence string_end return_statement string string_start string_end | Get mirror from slackpkg mirrors file |
def format_error(module, error):
logging.error(module)
print error.message
print json.dumps(error.error, sort_keys=True, indent=4, separators=(',', ': '))
exit(1) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier print_statement attribute identifier identifier print_statement call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier true keyword_argument identifier integer keyword_argument identifier tuple string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list integer | Format the error for the given module. |
def filter_sum(self, inst_rc, threshold, take_abs=True):
inst_df = self.dat_to_df()
if inst_rc == 'row':
inst_df = run_filter.df_filter_row_sum(inst_df, threshold, take_abs)
elif inst_rc == 'col':
inst_df = run_filter.df_filter_col_sum(inst_df, threshold, take_abs)
self.df_to_dat(inst_df) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Filter a network's rows or columns based on the sum across rows or columns. |
def json_error_formatter(body, status, title, environ):
body = webob.exc.strip_tags(body)
status_code = int(status.split(None, 1)[0])
error_dict = {
'status': status_code,
'title': title,
'detail': body
}
return {'errors': [error_dict]} | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list subscript call attribute identifier identifier argument_list none integer integer expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier return_statement dictionary pair string string_start string_content string_end list identifier | A json_formatter for webob exceptions. |
def _call_one_middleware(self, middleware):
args = {}
for arg in middleware['args']:
if hasattr(self, arg):
args[arg] = reduce(getattr, arg.split('.'), self)
self.logger.debug('calling middleware event {}'
.format(middleware['name']))
middleware['call'](**args) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier subscript identifier string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end expression_statement call subscript identifier string string_start string_content string_end argument_list dictionary_splat identifier | Evaluate arguments and execute the middleware function |
def add_tags(self, *tags):
self.tags.extend([
Tag(name=tag) for tag in tags
]) | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list list_comprehension call identifier argument_list keyword_argument identifier identifier for_in_clause identifier identifier | Add a list of strings to the statement as tags. |
def to_dict(self):
d = dict(doses=self.doses, ns=self.ns, incidences=self.incidences)
d.update(self.kwargs)
return d | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Returns a dictionary representation of the dataset. |
def complete(self, uio, dropped=False):
if self.dropped and not dropped:
return
for end in ['src', 'dst']:
if getattr(self, end):
continue
uio.show('\nEnter ' + end + ' for transaction:')
uio.show('')
uio.show(self.summary())
try:
endpoints = []
remaining = self.amount
while remaining:
account = uio.text(' Enter account', None)
amount = uio.decimal(
' Enter amount',
default=remaining,
lower=0,
upper=remaining
)
endpoints.append(Endpoint(account, amount))
remaining = self.amount \
- sum(map(lambda x: x.amount, endpoints))
except ui.RejectWarning:
sys.exit("bye!")
if end == 'src':
endpoints = map(
lambda x: Endpoint(x.account, -x.amount),
endpoints
)
setattr(self, end, endpoints) | module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement boolean_operator attribute identifier identifier not_operator identifier block return_statement for_statement identifier list string string_start string_content string_end string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list binary_operator binary_operator string string_start string_content escape_sequence string_end identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier list expression_statement assignment identifier attribute identifier identifier while_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier integer keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier line_continuation call identifier argument_list call identifier argument_list lambda lambda_parameters identifier attribute identifier identifier identifier except_clause attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier call identifier argument_list attribute identifier identifier unary_operator attribute identifier identifier identifier expression_statement call identifier argument_list identifier identifier identifier | Query for all missing information in the transaction |
def pout(*args, **kwargs):
if should_msg(kwargs.get("groups", ["normal"])):
args = indent_text(*args, **kwargs)
sys.stderr.write("".join(args))
sys.stderr.write("\n") | module function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_end identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence string_end | print to stdout, maintaining indent level |
def random_crop_and_flip(x, pad_rows=4, pad_cols=4):
rows = tf.shape(x)[1]
cols = tf.shape(x)[2]
channels = x.get_shape()[3]
def _rand_crop_img(img):
return tf.random_crop(img, [rows, cols, channels])
with tf.device('/CPU:0'):
x = tf.image.resize_image_with_crop_or_pad(x, rows + pad_rows,
cols + pad_cols)
x = tf.map_fn(_rand_crop_img, x)
x = tf.image.random_flip_left_right(x)
return x | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer block expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier subscript call attribute identifier identifier argument_list integer function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list identifier list identifier identifier identifier with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier binary_operator identifier identifier binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Augment a batch by randomly cropping and horizontally flipping it. |
def uninstall(self):
if self.is_installed():
installed = self.installed_dir()
if installed.is_symlink():
installed.unlink()
else:
shutil.rmtree(str(installed)) | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier | Delete code inside NApp directory, if existent. |
def align_cell(fmt, elem, width):
if fmt == "<":
return elem + ' ' * (width - len(elem))
if fmt == ">":
return ' ' * (width - len(elem)) + elem
return elem | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block return_statement binary_operator identifier binary_operator string string_start string_content string_end parenthesized_expression binary_operator identifier call identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block return_statement binary_operator binary_operator string string_start string_content string_end parenthesized_expression binary_operator identifier call identifier argument_list identifier identifier return_statement identifier | Returns an aligned element. |
def resample(self, target_sr):
y_hat = librosa.core.resample(self.y, self.sr, target_sr)
return Sound(y_hat, target_sr) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier return_statement call identifier argument_list identifier identifier | Returns a new sound with a samplerate of target_sr. |
def fetchone(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
return select(table, cols, where, group, order, limit, **kwargs).fetchone() | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier tuple default_parameter identifier string string_start string_end default_parameter identifier tuple default_parameter identifier tuple dictionary_splat_pattern identifier block return_statement call attribute call identifier argument_list identifier identifier identifier identifier identifier identifier dictionary_splat identifier identifier argument_list | Convenience wrapper for database SELECT and fetch one. |
def build_data_list(lst):
txt = '<H3>' + List + '<H3><UL>'
for i in lst:
txt += '<LI>' + i + '</LI>'
txt += '<UL>'
return txt | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end for_statement identifier identifier block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end expression_statement augmented_assignment identifier string string_start string_content string_end return_statement identifier | returns the html with supplied list as a HTML listbox |
def reset(self) -> None:
Log.debug('resetting timer task %s')
self.target = self.time() + self.DELAY | module function_definition identifier parameters identifier type none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier binary_operator call attribute identifier identifier argument_list attribute identifier identifier | Reset task execution to `DELAY` seconds from now. |
def __roll(self, unrolled):
rolled = []
index = 0
for count in range(len(self.__sizes) - 1):
in_size = self.__sizes[count]
out_size = self.__sizes[count+1]
theta_unrolled = np.matrix(unrolled[index:index+(in_size+1)*out_size])
theta_rolled = theta_unrolled.reshape((out_size, in_size+1))
rolled.append(theta_rolled)
index += (in_size + 1) * out_size
return rolled | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier integer for_statement identifier call identifier argument_list binary_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier subscript attribute identifier identifier binary_operator identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier slice identifier binary_operator identifier binary_operator parenthesized_expression binary_operator identifier integer identifier expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier binary_operator identifier integer expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier binary_operator parenthesized_expression binary_operator identifier integer identifier return_statement identifier | Converts parameter array back into matrices. |
def keyPressEvent(self, ev):
if ev.key() in (Qt.Key_Enter, Qt.Key_Return):
self._startOrStopEditing()
elif ev.key() == Qt.Key_Escape:
self._cancelEditing()
else:
Kittens.widgets.ClickableTreeWidget.keyPressEvent(self, ev) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list tuple attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list elif_clause comparison_operator call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier | Stop editing if enter is pressed |
def loadJson(self, filename):
jsonConfig = {}
if os.path.isfile(filename):
jsonConfig = json.loads(' '.join(open(filename, 'r').readlines()))
return jsonConfig | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute call identifier argument_list identifier string string_start string_content string_end identifier argument_list return_statement identifier | Read, parse and return given Json config file |
def verify_convention_version(self, ds):
try:
for convention in getattr(ds, "Conventions", '').replace(' ', '').split(','):
if convention == 'ACDD-' + self._cc_spec_version:
return ratable_result((2, 2), None, [])
m = ["Conventions does not contain 'ACDD-{}'".format(self._cc_spec_version)]
return ratable_result((1, 2), "Global Attributes", m)
except AttributeError:
m = ["No Conventions attribute present; must contain ACDD-{}".format(self._cc_spec_version)]
return ratable_result((0, 2), "Global Attributes", m) | module function_definition identifier parameters identifier identifier block try_statement block for_statement identifier call attribute call attribute call identifier argument_list identifier string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_end block if_statement comparison_operator identifier binary_operator string string_start string_content string_end attribute identifier identifier block return_statement call identifier argument_list tuple integer integer none list expression_statement assignment identifier list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier return_statement call identifier argument_list tuple integer integer string string_start string_content string_end identifier except_clause identifier block expression_statement assignment identifier list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier return_statement call identifier argument_list tuple integer integer string string_start string_content string_end identifier | Verify that the version in the Conventions field is correct |
def check_missing(self, param, action):
assert action in ('debug', 'info', 'warn', 'error'), action
if self.inputs.get(param):
msg = '%s_file in %s is ignored in %s' % (
param, self.inputs['job_ini'], self.calculation_mode)
if action == 'error':
raise InvalidFile(msg)
else:
getattr(logging, action)(msg) | module function_definition identifier parameters identifier identifier identifier block assert_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block raise_statement call identifier argument_list identifier else_clause block expression_statement call call identifier argument_list identifier identifier argument_list identifier | Make sure the given parameter is missing in the job.ini file |
def readn(self, n):
data = ''
while len(data) < n:
received = self.sock.recv(n - len(data))
if not len(received):
raise socket.error('no data read from socket')
data += received
return data | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_end while_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator identifier call identifier argument_list identifier if_statement not_operator call identifier argument_list identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement augmented_assignment identifier identifier return_statement identifier | Keep receiving data until exactly `n` bytes have been read. |
def print_verbose(*args, **kwargs):
if kwargs.pop('verbose', False) is True:
gprint(*args, **kwargs) | module function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end false true block expression_statement call identifier argument_list list_splat identifier dictionary_splat identifier | Utility to print something only if verbose=True is given |
def add_log_error(self, x, flag_also_show=False, E=None):
if len(x) == 0:
x = "(empty error)"
tb.print_stack()
x_ = x
if E is not None:
a99.get_python_logger().exception(x_)
else:
a99.get_python_logger().info("ERROR: {}".format(x_))
x = '<span style="color: {0!s}">{1!s}</span>'.format(a99.COLOR_ERROR, x)
self._add_log_no_logger(x, False)
if flag_also_show:
a99.show_error(x_) | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier none block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list identifier else_clause block expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier false if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier | Sets text of labelError. |
def _get_folds(n_rows, n_folds, use_stored):
if use_stored is not None:
with open(os.path.expanduser(use_stored)) as json_file:
json_data = json.load(json_file)
if json_data['N_rows'] != n_rows:
raise Exception('N_rows from folds doesnt match the number of rows of X_seq, X_feat, y')
if json_data['N_folds'] != n_folds:
raise Exception('n_folds dont match', json_data['N_folds'], n_folds)
kf = [(np.array(train), np.array(test)) for (train, test) in json_data['folds']]
else:
kf = KFold(n_splits=n_folds).split(np.zeros((n_rows, 1)))
i = 1
folds = []
for train, test in kf:
fold = "fold_" + str(i)
folds.append((fold, train, test))
i = i + 1
return folds | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block with_statement with_clause with_item as_pattern call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator subscript identifier string string_start string_content string_end identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator subscript identifier string string_start string_content string_end identifier block raise_statement call identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier list_comprehension tuple call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier for_in_clause tuple_pattern identifier identifier subscript identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call attribute call identifier argument_list keyword_argument identifier identifier identifier argument_list call attribute identifier identifier argument_list tuple identifier integer expression_statement assignment identifier integer expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list tuple identifier identifier identifier expression_statement assignment identifier binary_operator identifier integer return_statement identifier | Get the used CV folds |
def ticket1to2(old):
if isinstance(old.benefactor, Multifactor):
types = list(chain(*[b.powerupNames for b in
old.benefactor.benefactors('ascending')]))
elif isinstance(old.benefactor, InitializerBenefactor):
types = list(chain(*[b.powerupNames for b in
old.benefactor.realBenefactor.benefactors('ascending')]))
newProduct = old.store.findOrCreate(Product,
types=types)
if old.issuer is None:
issuer = old.store.findOrCreate(TicketBooth)
else:
issuer = old.issuer
t = old.upgradeVersion(Ticket.typeName, 1, 2,
product = newProduct,
issuer = issuer,
booth = old.booth,
avatar = old.avatar,
claimed = old.claimed,
email = old.email,
nonce = old.nonce) | module function_definition identifier parameters identifier block if_statement call identifier argument_list attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list list_splat list_comprehension attribute identifier identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end elif_clause call identifier argument_list attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list list_splat list_comprehension attribute identifier identifier for_in_clause identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier integer integer keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | change Ticket to refer to Products and not benefactor factories. |
def toimages(self):
from thunder.images.images import Images
if self.mode == 'spark':
values = self.values.values_to_keys((0,)).unchunk()
if self.mode == 'local':
values = self.values.unchunk()
return Images(values) | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list tuple integer identifier argument_list if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list return_statement call identifier argument_list identifier | Convert blocks to images. |
def _create_memory_database_interface(self) -> GraphDatabaseInterface:
Base = declarative_base()
engine = sqlalchemy.create_engine("sqlite://", poolclass=StaticPool)
Session = sessionmaker(bind=engine)
dbi: GraphDatabaseInterface = create_graph_database_interface(
sqlalchemy, Session(), Base, sqlalchemy.orm.relationship
)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
return dbi | module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier type identifier call identifier argument_list identifier call identifier argument_list identifier attribute attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Creates and returns the in-memory database interface the graph will use. |
def main(conf):
global config
config = load_configuration(conf)
app.conf.update(config['celery'])
run(host=config['valigator']['bind'], port=config['valigator']['port']) | module function_definition identifier parameters identifier block global_statement identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement call identifier argument_list keyword_argument identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end keyword_argument identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end | Main function, entry point of the program. |
def remove_update_callback(self, callback, device):
if [callback, device] in self._update_callbacks:
self._update_callbacks.remove([callback, device])
_LOGGER.debug('Removed update callback %s for %s',
callback, device) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator list identifier identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list list identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier | Remove a registered update callback. |
def update(self):
yield from self.update_remotes()
yield from self.rename_local_untracked()
yield from self.reset_deleted_files()
if self.repo_is_dirty():
yield from self.ensure_lock()
yield from execute_cmd(['git', 'commit', '-am', 'WIP', '--allow-empty'], cwd=self.repo_dir)
yield from self.ensure_lock()
yield from execute_cmd(['git', 'merge', '-Xours', 'origin/{}'.format(self.branch_name)], cwd=self.repo_dir) | module function_definition identifier parameters identifier block expression_statement yield call attribute identifier identifier argument_list expression_statement yield call attribute identifier identifier argument_list expression_statement yield call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list block expression_statement yield call attribute identifier identifier argument_list expression_statement yield call identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement yield call attribute identifier identifier argument_list expression_statement yield call identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier | Do the pulling if necessary |
def colorgamut(self):
try:
light_spec = self.controlcapabilities
gtup = tuple([XYPoint(*x) for x in light_spec['colorgamut']])
color_gamut = GamutType(*gtup)
except KeyError:
color_gamut = None
return color_gamut | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list list_comprehension call identifier argument_list list_splat identifier for_in_clause identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list list_splat identifier except_clause identifier block expression_statement assignment identifier none return_statement identifier | The color gamut information of the light. |
def total_length_per_neurite(neurites, neurite_type=NeuriteType.all):
return list(sum(s.length for s in n.iter_sections())
for n in iter_neurites(neurites, filt=is_type(neurite_type))) | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block return_statement call identifier generator_expression call identifier generator_expression attribute identifier identifier for_in_clause identifier call attribute identifier identifier argument_list for_in_clause identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list identifier | Get the path length per neurite in a collection |
def main(argv=None):
arguments = cli_common(__doc__, argv=argv)
report = ReportNode(arguments['CAMPAIGN-DIR'])
jobs = wait_for_completion(report, float(arguments['--interval']))
status = ReportStatus(report, jobs)
if not arguments['--silent']:
fmt = arguments['--format'] or 'log'
status.log(fmt)
if argv is None:
sys.exit(0 if status.succeeded else 1)
return status.status | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier if_statement not_operator subscript identifier string string_start string_content string_end block expression_statement assignment identifier boolean_operator subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list conditional_expression integer attribute identifier identifier integer return_statement attribute identifier identifier | ben-wait entry point |
def add_basic_info(self, run_id, timestamp):
datetime = time.strftime('%A %b %d, %Y %H:%M:%S', time.localtime(timestamp))
user = getpass.getuser()
machine = socket.gethostname()
buildroot = get_buildroot()
self.add_infos(('id', run_id), ('timestamp', timestamp), ('datetime', datetime),
('user', user), ('machine', machine), ('path', buildroot),
('buildroot', buildroot), ('version', version.VERSION)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier tuple string string_start string_content string_end identifier tuple string string_start string_content string_end attribute identifier identifier | Adds basic build info. |
def _accept_as_blank(self, url_info: URLInfo):
_logger.debug(__('Got empty robots.txt for {0}.', url_info.url))
self._robots_txt_pool.load_robots_txt(url_info, '') | module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier string string_start string_end | Mark the URL as OK in the pool. |
def inspect_current_object(self):
editor = self.get_current_editor()
editor.sig_display_signature.connect(self.display_signature_help)
line, col = editor.get_cursor_line_column()
editor.request_hover(line, col) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier | Inspect current object in the Help plugin |
def selectByIdx(self, rowIdxs):
'Select given row indexes, without progress bar.'
self.select((self.rows[i] for i in rowIdxs), progress=False) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement call attribute identifier identifier argument_list generator_expression subscript attribute identifier identifier identifier for_in_clause identifier identifier keyword_argument identifier false | Select given row indexes, without progress bar. |
def setbit(self, key, offset, value):
key = self._encode(key)
index, bits, mask = self._get_bits_and_offset(key, offset)
if index >= len(bits):
bits.extend(b"\x00" * (index + 1 - len(bits)))
prev_val = 1 if (bits[index] & mask) else 0
if value:
bits[index] |= mask
else:
bits[index] &= ~mask
self.redis[key] = bytes(bits)
return prev_val | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end parenthesized_expression binary_operator binary_operator identifier integer call identifier argument_list identifier expression_statement assignment identifier conditional_expression integer parenthesized_expression binary_operator subscript identifier identifier identifier integer if_statement identifier block expression_statement augmented_assignment subscript identifier identifier identifier else_clause block expression_statement augmented_assignment subscript identifier identifier unary_operator identifier expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list identifier return_statement identifier | Set the bit at ``offset`` in ``key`` to ``value``. |
def increment_title(title):
count = re.search('\d+$', title).group(0)
new_title = title[:-(len(count))] + str(int(count)+1)
return new_title | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list integer expression_statement assignment identifier binary_operator subscript identifier slice unary_operator parenthesized_expression call identifier argument_list identifier call identifier argument_list binary_operator call identifier argument_list identifier integer return_statement identifier | Increments a string that ends in a number |
def save_twi(self, rootpath, raw=False, as_int=True):
self.twi = np.ma.masked_array(self.twi, mask=self.twi <= 0,
fill_value=-9999)
self.twi[self.flats] = 0
self.twi.mask[self.flats] = True
self.save_array(self.twi, None, 'twi', rootpath, raw, as_int=as_int) | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier true block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier comparison_operator attribute identifier identifier integer keyword_argument identifier unary_operator integer expression_statement assignment subscript attribute identifier identifier attribute identifier identifier integer expression_statement assignment subscript attribute attribute identifier identifier identifier attribute identifier identifier true expression_statement call attribute identifier identifier argument_list attribute identifier identifier none string string_start string_content string_end identifier identifier keyword_argument identifier identifier | Saves the topographic wetness index to a file |
def __embed_branch_recursive(u, dfs_data):
for v in dfs_data['adj'][u]:
nonplanar = True
if a(v, dfs_data) == u:
if b(v, dfs_data) == u:
successful = __insert_branch(u, v, dfs_data)
if not successful:
nonplanar = True
return nonplanar
nonplanar = __embed_branch_recursive(v, dfs_data)
if nonplanar:
return nonplanar
elif is_frond(u, v, dfs_data):
successful = __embed_frond(u, v, dfs_data)
if not successful:
nonplanar = True
return nonplanar
else:
pass
nonplanar = False
return nonplanar | module function_definition identifier parameters identifier identifier block for_statement identifier subscript subscript identifier string string_start string_content string_end identifier block expression_statement assignment identifier true if_statement comparison_operator call identifier argument_list identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement not_operator identifier block expression_statement assignment identifier true return_statement identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement identifier block return_statement identifier elif_clause call identifier argument_list identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement not_operator identifier block expression_statement assignment identifier true return_statement identifier else_clause block pass_statement expression_statement assignment identifier false return_statement identifier | A recursive implementation of the EmbedBranch function, as defined on pages 8 and 22 of the paper. |
def main(name, output, font):
bootstrapped_directory = os.getcwd() + os.sep + name.lower().replace(' ', '-') + os.sep
copy_tree(get_real_path(os.sep + 'my-cool-os-template'), bootstrapped_directory)
start_byte = int('0xb8000', 16)
instructions_list = []
for c in output:
char_as_hex = '0x02'+ c.encode('hex')
instructions_list.append('\tmov word [{0}], {1} ; {2}'.format(hex(start_byte), char_as_hex, c))
start_byte += 2
banner = Figlet(font=font).renderText(name)
render_template_file(bootstrapped_directory + 'README.md', {'name' : name, 'banner' : banner})
render_template_file(bootstrapped_directory + 'grub.cfg' , {'name' : name})
render_template_file(bootstrapped_directory + 'boot.asm' , {'instructions_list' : instructions_list})
print('finished bootstrapping project into directory ' + bootstrapped_directory) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator binary_operator binary_operator call attribute identifier identifier argument_list attribute identifier identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list call identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list call identifier argument_list identifier identifier identifier expression_statement augmented_assignment identifier integer expression_statement assignment identifier call attribute call identifier argument_list keyword_argument identifier identifier identifier argument_list identifier expression_statement call identifier argument_list binary_operator identifier string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement call identifier argument_list binary_operator identifier string string_start string_content string_end dictionary pair string string_start string_content string_end identifier expression_statement call identifier argument_list binary_operator identifier string string_start string_content string_end dictionary pair string string_start string_content string_end identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Easily bootstrap an OS project to fool HR departments and pad your resume. |
def delete(self):
with self.draft_context():
draft = self.one(Q._uid == self._uid)
if draft:
super(PublisherFrame, draft).delete()
with self.published_context():
published = self.one(Q._uid == self._uid)
if published:
super(PublisherFrame, published).delete() | module function_definition identifier parameters identifier block with_statement with_clause with_item call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list comparison_operator attribute identifier identifier attribute identifier identifier if_statement identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list with_statement with_clause with_item call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list comparison_operator attribute identifier identifier attribute identifier identifier if_statement identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list | Delete this document and any counterpart document |
def wait_until_done(self, timeout=None):
start = datetime.now()
if not self.__th:
raise IndraDBRestResponseError("There is no thread waiting to "
"complete.")
self.__th.join(timeout)
now = datetime.now()
dt = now - start
if self.__th.is_alive():
logger.warning("Timed out after %0.3f seconds waiting for "
"statement load to complete." % dt.total_seconds())
ret = False
else:
logger.info("Waited %0.3f seconds for statements to finish loading."
% dt.total_seconds())
ret = True
return ret | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment identifier false else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment identifier true return_statement identifier | Wait for the background load to complete. |
def applyVoucherCodesFinal(sender,**kwargs):
logger.debug('Signal fired to mark voucher codes as applied.')
finalReg = kwargs.pop('registration')
tr = finalReg.temporaryRegistration
tvus = TemporaryVoucherUse.objects.filter(registration=tr)
for tvu in tvus:
vu = VoucherUse(voucher=tvu.voucher,registration=finalReg,amount=tvu.amount)
vu.save()
if getConstant('referrals__enableReferralProgram'):
awardReferrers(vu) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list if_statement call identifier argument_list string string_start string_content string_end block expression_statement call identifier argument_list identifier | Once a registration has been completed, vouchers are used and referrers are awarded |
def format_users():
lines = []
u = users()
count = u['count']
if not count:
raise DapiCommError('Could not find any users on DAPI.')
for user in u['results']:
line = user['username']
if user['full_name']:
line += ' (' + user['full_name'] + ')'
lines.append(line)
return lines | module function_definition identifier parameters block expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement subscript identifier string string_start string_content string_end block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Formats a list of users available on Dapi |
def _iter_vals(key):
for i in range(winreg.QueryInfoKey(key)[1]):
yield winreg.EnumValue(key, i) | module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list subscript call attribute identifier identifier argument_list identifier integer block expression_statement yield call attribute identifier identifier argument_list identifier identifier | ! Iterate over values of a key |
def overlap(self, query, subject):
if (self.pt_within(query[0], subject) or self.pt_within(query[1], subject) or
self.pt_within(subject[0], query) or self.pt_within(subject[1], query)):
return True
return False | module function_definition identifier parameters identifier identifier identifier block if_statement parenthesized_expression boolean_operator boolean_operator boolean_operator call attribute identifier identifier argument_list subscript identifier integer identifier call attribute identifier identifier argument_list subscript identifier integer identifier call attribute identifier identifier argument_list subscript identifier integer identifier call attribute identifier identifier argument_list subscript identifier integer identifier block return_statement true return_statement false | Accessory function to check if two ranges overlap |
def _calculate_average_field_lengths(self):
accumulator = defaultdict(int)
documents_with_field = defaultdict(int)
for field_ref, length in self.field_lengths.items():
_field_ref = FieldRef.from_string(field_ref)
field = _field_ref.field_name
documents_with_field[field] += 1
accumulator[field] += length
for field_name in self._fields:
accumulator[field_name] /= documents_with_field[field_name]
self.average_field_length = accumulator | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier expression_statement augmented_assignment subscript identifier identifier integer expression_statement augmented_assignment subscript identifier identifier identifier for_statement identifier attribute identifier identifier block expression_statement augmented_assignment subscript identifier identifier subscript identifier identifier expression_statement assignment attribute identifier identifier identifier | Calculates the average document length for this index |
def unproject(self, xy):
(x, y) = xy
lng = x/EARTH_RADIUS * RAD_TO_DEG
lat = 2 * atan(exp(y/EARTH_RADIUS)) - pi/2 * RAD_TO_DEG
return (lng, lat) | module function_definition identifier parameters identifier identifier block expression_statement assignment tuple_pattern identifier identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier identifier identifier expression_statement assignment identifier binary_operator binary_operator integer call identifier argument_list call identifier argument_list binary_operator identifier identifier binary_operator binary_operator identifier integer identifier return_statement tuple identifier identifier | Returns the coordinates from position in meters |
def training_data(self):
data = pickle.load(open(os.path.join(self.repopath, 'training.pkl')))
return data.keys(), data.values() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end return_statement expression_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list | Returns data dictionary from training.pkl |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.