code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def datapath(self):
path = self._fields['path']
if not path:
path = self.fetch('directory')
if path and not self._fields['is_multi_file']:
path = os.path.join(path, self._fields['name'])
return os.path.expanduser(fmt.to_unicode(path)) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator identifier not_operator subscript attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier subscript attribute identifier identifier string string_start string_content string_end return_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier | Get an item's data path. |
def as_odict(self):
if hasattr(self, 'cust_odict'):
return self.cust_odict
if hasattr(self, 'attr_check'):
self.attr_check()
odc = odict()
for attr in self.attrorder:
odc[attr] = getattr(self, attr)
return odc | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block return_statement attribute identifier identifier if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier return_statement identifier | returns an odict version of the object, based on it's attributes |
def create_backend(self,
service_id,
version_number,
name,
address,
use_ssl=False,
port=80,
connect_timeout=1000,
first_byte_timeout=15000,
between_bytes_timeout=10000,
error_threshold=0,
max_conn=20,
weight=100,
auto_loadbalance=False,
shield=None,
request_condition=None,
healthcheck=None,
comment=None):
body = self._formdata({
"name": name,
"address": address,
"use_ssl": use_ssl,
"port": port,
"connect_timeout": connect_timeout,
"first_byte_timeout": first_byte_timeout,
"between_bytes_timeout": between_bytes_timeout,
"error_threshold": error_threshold,
"max_conn": max_conn,
"weight": weight,
"auto_loadbalance": auto_loadbalance,
"shield": shield,
"request_condition": request_condition,
"healthcheck": healthcheck,
"comment": comment,
}, FastlyBackend.FIELDS)
content = self._fetch("/service/%s/version/%d/backend" % (service_id, version_number), method="POST", body=body)
return FastlyBackend(self, content) | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier false default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier false default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list 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 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 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 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 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 attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier | Create a backend for a particular service and version. |
def copy(self, src_fs, src_path, dst_fs, dst_path):
if self.queue is None:
copy_file_internal(src_fs, src_path, dst_fs, dst_path)
else:
src_file = src_fs.openbin(src_path, "r")
try:
dst_file = dst_fs.openbin(dst_path, "w")
except Exception:
src_file.close()
raise
task = _CopyTask(src_file, dst_file)
self.queue.put(task) | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call identifier argument_list identifier identifier identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list raise_statement expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Copy a file from one fs to another. |
def runlist_view(name, **kwargs):
ctx = Context(**kwargs)
ctx.execute_action('runlist:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name
}) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary_splat dictionary pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end identifier | Show configuration content for a specified runlist. |
def decode_token(self, token):
key = current_app.secret_key
if key is None:
if current_app.debug:
current_app.logger.debug("app.secret_key not set")
return None
try:
return jwt.decode(
token, key,
algorithms=[self.config["algorithm"]],
options={'require_exp': True}
)
except jwt.InvalidTokenError:
return None | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement none try_statement block return_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier list subscript attribute identifier identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end true except_clause attribute identifier identifier block return_statement none | Decode Authorization token, return None if token invalid |
def deserialize_number(s, fmt=SER_BINARY):
ret = gmpy.mpz(0)
if fmt == SER_BINARY:
if isinstance(s, six.text_type):
raise ValueError(
"Encode `s` to a bytestring yourself to" +
" prevent problems with different default encodings")
for c in s:
ret *= 256
ret += byte2int(c)
return ret
assert fmt == SER_COMPACT
if isinstance(s, six.text_type):
s = s.encode('ascii')
for c in s:
ret *= len(COMPACT_DIGITS)
ret += R_COMPACT_DIGITS[c]
return ret | module function_definition identifier parameters identifier default_parameter identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer if_statement comparison_operator identifier identifier block if_statement call identifier argument_list identifier attribute identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement augmented_assignment identifier integer expression_statement augmented_assignment identifier call identifier argument_list identifier return_statement identifier assert_statement comparison_operator identifier identifier if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement augmented_assignment identifier call identifier argument_list identifier expression_statement augmented_assignment identifier subscript identifier identifier return_statement identifier | Deserializes a number from a string `s' in format `fmt' |
def setup_observations(self):
obs_methods = [self.setup_water_budget_obs,self.setup_hyd,
self.setup_smp,self.setup_hob,self.setup_hds,
self.setup_sfr_obs]
obs_types = ["mflist water budget obs","hyd file",
"external obs-sim smp files","hob","hds","sfr"]
self.obs_dfs = {}
for obs_method, obs_type in zip(obs_methods,obs_types):
self.log("processing obs type {0}".format(obs_type))
obs_method()
self.log("processing obs type {0}".format(obs_type)) | module function_definition identifier parameters identifier block expression_statement assignment identifier list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier 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 string string_start string_content string_end expression_statement assignment attribute identifier identifier dictionary for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | main entry point for setting up observations |
def disk2ram(self):
values = self.series
self.deactivate_disk()
self.ramflag = True
self.__set_array(values)
self.update_fastaccess() | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Move internal data from disk to RAM. |
def rpc_get_docstring(self, filename, source, offset):
return self._call_backend("rpc_get_docstring", None, filename,
get_source(source), offset) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end none identifier call identifier argument_list identifier identifier | Get the docstring for the symbol at the offset. |
def run(self):
install.run(self)
spath = os.path.join(self.install_scripts, 'pygubu')
for ext in ('.py', '.pyw'):
filename = spath + ext
if os.path.exists(filename):
os.remove(filename)
if platform.system() == 'Windows':
spath = os.path.join(self.install_scripts, 'pygubu-designer.bat')
if os.path.exists(spath):
os.remove(spath) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end for_statement identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier binary_operator identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator 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 attribute identifier identifier string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier | Run parent install, and then save the install dir in the script. |
def _serialize_object(self, response_data, request):
if self._is_doc_request(request):
return response_data
else:
return super(DocumentedResource, self)._serialize_object(
response_data, request) | module function_definition identifier parameters identifier identifier identifier block if_statement call attribute identifier identifier argument_list identifier block return_statement identifier else_clause block return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier | Override to not serialize doc responses. |
def evaluate(molecules, ensemble_chunk, sort_order, options, output_queue=None):
results = {}
for ensemble in ensemble_chunk:
results[ensemble] = calculate_performance(molecules, ensemble, sort_order, options)
if output_queue is not None:
output_queue.put(results)
else:
return results | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier else_clause block return_statement identifier | Evaluate VS performance of each ensemble in ensemble_chunk |
def flat_data(self):
def flat_field(value):
try:
value.flat_data()
return value
except AttributeError:
return value
modified_dict = self.__original_data__
modified_dict.update(self.__modified_data__)
self.__original_data__ = {k: flat_field(v)
for k, v in modified_dict.items()
if k not in self.__deleted_fields__}
self.clear_modified_data() | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list return_statement identifier except_clause identifier block return_statement identifier expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier dictionary_comprehension pair identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list | Pass all the data from modified_data to original_data |
def cost_min2(self, alpha):
n = self.V.dim()
ax = alpha[:n]
ay = alpha[n:]
q2, r2 = self.get_q2_r2(ax, ay)
Lax = self.L * ax
Lay = self.L * ay
out = [
0.5 * numpy.dot(Lax, Lax),
0.5 * numpy.dot(Lay, Lay),
0.5 * numpy.dot(q2 - 1, q2 - 1),
0.5 * numpy.dot(r2, r2),
]
if self.num_f_eval % 10000 == 0:
print("{:7d} {:e} {:e} {:e} {:e}".format(self.num_f_eval, *out))
self.num_f_eval += 1
return numpy.sum(out) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier subscript identifier slice identifier expression_statement assignment identifier subscript identifier slice identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement assignment identifier list binary_operator float call attribute identifier identifier argument_list identifier identifier binary_operator float call attribute identifier identifier argument_list identifier identifier binary_operator float call attribute identifier identifier argument_list binary_operator identifier integer binary_operator identifier integer binary_operator float call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator binary_operator attribute identifier identifier integer integer block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier list_splat identifier expression_statement augmented_assignment attribute identifier identifier integer return_statement call attribute identifier identifier argument_list identifier | Residual formulation, Hessian is a low-rank update of the identity. |
def run(self):
while not self.wait(self.delay()):
try:
logger.info('Invoking callback %s', self.callback)
self.callback()
except StandardError:
logger.exception('Callback failed') | module function_definition identifier parameters identifier block while_statement not_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list block try_statement block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Run the callback periodically |
def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True):
if root is None:
root = {}
tcoords = dataset.GetPointData().GetTCoords()
if tcoords:
dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress)
root['pointData']['activeTCoords'] = len(root['pointData']['arrays'])
root['pointData']['arrays'].append({'data': dumped_array}) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier true block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier dictionary identifier expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end call identifier argument_list subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list dictionary pair string string_start string_content string_end identifier | dump vtkjs texture coordinates |
def _check_voSet(orb,kwargs,funcName):
if not orb._voSet and kwargs.get('vo',None) is None:
warnings.warn("Method %s(.) requires vo to be given at Orbit initialization or at method evaluation; using default vo which is %f km/s" % (funcName,orb._vo),
galpyWarning) | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator not_operator attribute identifier identifier comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end none none block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier identifier | Function to check whether vo is set, because it's required for funcName |
def SetCoreGRRKnowledgeBaseValues(kb, client_obj):
client_schema = client_obj.Schema
kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.FQDN, ""))
if not kb.fqdn:
kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.HOSTNAME, ""))
versions = client_obj.Get(client_schema.OS_VERSION)
if versions and versions.versions:
try:
kb.os_major_version = versions.versions[0]
kb.os_minor_version = versions.versions[1]
except IndexError:
pass
client_os = client_obj.Get(client_schema.SYSTEM)
if client_os:
kb.os = utils.SmartUnicode(client_obj.Get(client_schema.SYSTEM)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier string string_start string_end if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement boolean_operator identifier attribute identifier identifier block try_statement block expression_statement assignment attribute identifier identifier subscript attribute identifier identifier integer expression_statement assignment attribute identifier identifier subscript attribute identifier identifier integer except_clause identifier block pass_statement expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier | Set core values from GRR into the knowledgebase. |
def execute(self):
self.prepare_models()
self.prepare_worker()
if self.options.print_options:
self.print_options()
self.run() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list if_statement attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Main method to call to run the worker |
def as_set(self, decode=False):
items = self.database.smembers(self.key)
return set(_decode(item) for item in items) if decode else items | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement conditional_expression call identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier identifier identifier | Return a Python set containing all the items in the collection. |
def _panel_domains(self,n=2,min_panel_size=.15,spacing=0.08,top_margin=1,bottom_margin=0):
d={}
for _ in range(n+1,1,-1):
lower=round(bottom_margin+(min_panel_size+spacing)*(n+1-_),2)
d['yaxis{0}'.format(_)]=dict(domain=(lower,lower+min_panel_size))
top=d['yaxis2']['domain']
d['yaxis2']['domain']=(top[0],top_margin)
return d | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier float default_parameter identifier float default_parameter identifier integer default_parameter identifier integer block expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list binary_operator identifier integer integer unary_operator integer block expression_statement assignment identifier call identifier argument_list binary_operator identifier binary_operator parenthesized_expression binary_operator identifier identifier parenthesized_expression binary_operator binary_operator identifier integer identifier integer expression_statement assignment subscript identifier call attribute string string_start string_content string_end identifier argument_list identifier call identifier argument_list keyword_argument identifier tuple identifier binary_operator identifier identifier expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end tuple subscript identifier integer identifier return_statement identifier | Returns the panel domains for each axis |
def _update_keymap(self, first_keycode, count):
lastcode = first_keycode + count
for keysym, codes in self._keymap_syms.items():
i = 0
while i < len(codes):
code = codes[i][1]
if code >= first_keycode and code < lastcode:
del codes[i]
else:
i = i + 1
keysyms = self.get_keyboard_mapping(first_keycode, count)
self._keymap_codes[first_keycode:lastcode] = keysyms
code = first_keycode
for syms in keysyms:
index = 0
for sym in syms:
if sym != X.NoSymbol:
if sym in self._keymap_syms:
symcodes = self._keymap_syms[sym]
symcodes.append((index, code))
symcodes.sort()
else:
self._keymap_syms[sym] = [(index, code)]
index = index + 1
code = code + 1 | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator identifier identifier for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier integer while_statement comparison_operator identifier call identifier argument_list identifier block expression_statement assignment identifier subscript subscript identifier identifier integer if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier block delete_statement subscript identifier identifier else_clause block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript attribute identifier identifier slice identifier identifier identifier expression_statement assignment identifier identifier for_statement identifier identifier block expression_statement assignment identifier integer for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list tuple identifier identifier expression_statement call attribute identifier identifier argument_list else_clause block expression_statement assignment subscript attribute identifier identifier identifier list tuple identifier identifier expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator identifier integer | Internal function, called to refresh the keymap cache. |
def fetcher_factory(conf):
global PROMOTERS
applicable = []
if not PROMOTERS:
PROMOTERS = load_promoters()
for promoter in PROMOTERS:
if promoter.is_applicable(conf):
applicable.append((promoter.PRIORITY, promoter))
if applicable:
best_match = sorted(applicable, reverse=True)[0][1]
return best_match(conf)
else:
raise ConfigurationError(
'No fetcher is applicable for "{0}"'.format(conf['name'])
) | module function_definition identifier parameters identifier block global_statement identifier expression_statement assignment identifier list if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list tuple attribute identifier identifier identifier if_statement identifier block expression_statement assignment identifier subscript subscript call identifier argument_list identifier keyword_argument identifier true integer integer return_statement call identifier argument_list identifier else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end | Return initialized fetcher capable of processing given conf. |
def memory_error():
warning_heading = m.Heading(
tr('Memory issue'), **WARNING_STYLE)
warning_message = tr(
'There is not enough free memory to run this analysis.')
suggestion_heading = m.Heading(
tr('Suggestion'), **SUGGESTION_STYLE)
suggestion = tr(
'Try zooming in to a smaller area or using a raster layer with a '
'coarser resolution to speed up execution and reduce memory '
'requirements. You could also try adding more RAM to your computer.')
message = m.Message()
message.add(warning_heading)
message.add(warning_message)
message.add(suggestion_heading)
message.add(suggestion)
send_static_message(dispatcher.Anonymous, message) | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end dictionary_splat identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end dictionary_splat identifier expression_statement assignment identifier 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 expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list attribute identifier identifier identifier | Display an error when there is not enough memory. |
def _empty_queue(self):
while True:
try:
self.queue.pop()
self.unused += 1
self.nqueue -= 1
except:
self.nqueue = 0
break | module function_definition identifier parameters identifier block while_statement true block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement augmented_assignment attribute identifier identifier integer expression_statement augmented_assignment attribute identifier identifier integer except_clause block expression_statement assignment attribute identifier identifier integer break_statement | Dump all live point proposals currently on the queue. |
def to_json(self, value):
if not self.is_valid(value):
raise ex.SerializeException('Invalid value: {}'.format(value))
return value | module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block raise_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Subclasses should override this method for JSON encoding. |
def update(self):
self.filename = self.parent.info.dataset.filename
self.chan = self.parent.info.dataset.header['chan_name']
for chan in self.chan:
self.idx_chan.addItem(chan) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier attribute attribute attribute attribute identifier identifier identifier identifier identifier expression_statement assignment attribute identifier identifier subscript attribute attribute attribute attribute identifier identifier identifier identifier identifier string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Get info from dataset before opening dialog. |
def AuthorizeUser(self, user, subject):
user_set = self.authorized_users.setdefault(subject, set())
user_set.add(user) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier | Allow given user access to a given subject. |
def settings(request):
from waliki.settings import WALIKI_USE_MATHJAX
return {k: v for (k, v) in locals().items() if k.startswith('WALIKI')} | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier return_statement dictionary_comprehension pair identifier identifier for_in_clause tuple_pattern identifier identifier call attribute call identifier argument_list identifier argument_list if_clause call attribute identifier identifier argument_list string string_start string_content string_end | inject few waliki's settings to the context to be used in templates |
def do_add_item(self, args):
if args.food:
add_item = args.food
elif args.sport:
add_item = args.sport
elif args.other:
add_item = args.other
else:
add_item = 'no items'
self.poutput("You added {}".format(add_item)) | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier elif_clause attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier elif_clause attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Add item command help |
def coerce(self, value, includes=None, errors=None, resources=None, default_locale='en-US', locale=None):
if includes is None:
includes = []
if errors is None:
errors = []
return self._coerce_block(
value,
includes=includes,
errors=errors,
resources=resources,
default_locale=default_locale,
locale=locale
) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier list if_statement comparison_operator identifier none block expression_statement assignment identifier list return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Coerces Rich Text properly. |
def to_jd(year, month, day):
gyear = year + 78
leap = isleap(gyear)
start = gregorian.to_jd(gyear, 3, 22 - leap)
if leap:
Caitra = 31
else:
Caitra = 30
if month == 1:
jd = start + (day - 1)
else:
jd = start + Caitra
m = month - 2
m = min(m, 5)
jd += m * 31
if month >= 8:
m = month - 7
jd += m * 30
jd += day - 1
return jd | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer binary_operator integer identifier if_statement identifier block expression_statement assignment identifier integer else_clause block expression_statement assignment identifier integer if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator identifier parenthesized_expression binary_operator identifier integer else_clause block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier call identifier argument_list identifier integer expression_statement augmented_assignment identifier binary_operator identifier integer if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator identifier integer expression_statement augmented_assignment identifier binary_operator identifier integer expression_statement augmented_assignment identifier binary_operator identifier integer return_statement identifier | Obtain Julian day for Indian Civil date |
def signup_time_future(self):
now = datetime.datetime.now()
return (now.date() < self.date or (self.date == now.date() and self.signup_time > now.time())) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list return_statement parenthesized_expression boolean_operator comparison_operator call attribute identifier identifier argument_list attribute identifier identifier parenthesized_expression boolean_operator comparison_operator attribute identifier identifier call attribute identifier identifier argument_list comparison_operator attribute identifier identifier call attribute identifier identifier argument_list | Is the signup time in the future? |
def spatialDomainNoGrid(self):
self.w = np.zeros(self.xw.shape)
if self.Debug:
print("w = ")
print(self.w.shape)
for i in range(len(self.q)):
if self.q[i] != 0:
dist = np.abs(self.xw - self.x[i])
self.w -= self.q[i] * self.coeff * np.exp(-dist/self.alpha) * \
( np.cos(dist/self.alpha) + np.sin(dist/self.alpha) ) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier if_statement attribute identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list attribute attribute identifier identifier identifier for_statement identifier call identifier argument_list call identifier argument_list attribute identifier identifier block if_statement comparison_operator subscript attribute identifier identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator attribute identifier identifier subscript attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier binary_operator binary_operator binary_operator subscript attribute identifier identifier identifier attribute identifier identifier call attribute identifier identifier argument_list binary_operator unary_operator identifier attribute identifier identifier line_continuation parenthesized_expression binary_operator call attribute identifier identifier argument_list binary_operator identifier attribute identifier identifier call attribute identifier identifier argument_list binary_operator identifier attribute identifier identifier | Superposition of analytical solutions without a gridded domain |
def _sync_filters(self, filters_json):
for filter_json in filters_json:
filter_id = filter_json['id']
self.filters[filter_id] = Filter(filter_json, self) | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list identifier identifier | Populate the user's filters from a JSON encoded list. |
def cancel(self, *args, **kwargs):
super().cancel()
for future in self.traverse():
if not future.cancelled():
future.cancel() | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute call identifier argument_list identifier argument_list for_statement identifier call attribute identifier identifier argument_list block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list | Manually cancel all tasks assigned to this event loop. |
def as_point(row):
return Point(row[COLS.X], row[COLS.Y], row[COLS.Z],
row[COLS.R], int(row[COLS.TYPE])) | module function_definition identifier parameters identifier block return_statement call identifier argument_list subscript identifier attribute identifier identifier subscript identifier attribute identifier identifier subscript identifier attribute identifier identifier subscript identifier attribute identifier identifier call identifier argument_list subscript identifier attribute identifier identifier | Create a Point from a data block row |
def cleanup_event_loop(self):
for task in asyncio.Task.all_tasks(loop=self.loop):
if self.debug:
warnings.warn('Cancelling task: %s' % task)
task._log_destroy_pending = False
task.cancel()
self.loop.close()
self.loop.set_exception_handler(self.loop_exception_handler_save)
self.loop_exception_handler_save = None
self.loop_policy = None
self.loop = None | module function_definition identifier parameters identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment attribute identifier identifier false expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none | Cleanup an event loop and close it down forever. |
def merge_dicts(*dicts, **kwargs):
result = {}
for d in dicts:
result.update(d)
result.update(kwargs)
return result | module function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Merges dicts and kwargs into one dict |
def _request_eip(interface, vm_):
params = {'Action': 'AllocateAddress'}
params['Domain'] = interface.setdefault('domain', 'vpc')
eips = aws.query(params,
return_root=True,
location=get_location(vm_),
provider=get_provider(),
opts=__opts__,
sigver='4')
for eip in eips:
if 'allocationId' in eip:
return eip['allocationId']
return None | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair 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 call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true keyword_argument identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block return_statement subscript identifier string string_start string_content string_end return_statement none | Request and return Elastic IP |
def delete_nve_member(self, nexus_host, nve_int_num, vni):
starttime = time.time()
path_snip = snipp.PATH_VNI_UPDATE % (nve_int_num, vni)
self.client.rest_delete(path_snip, nexus_host)
self.capture_and_print_timeshot(
starttime, "delete_nve",
switch=nexus_host) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator attribute identifier identifier tuple identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier identifier | Delete a member configuration on the NVE interface. |
def slides(self):
sldIdLst = self._element.get_or_add_sldIdLst()
self.part.rename_slide_parts([sldId.rId for sldId in sldIdLst])
return Slides(sldIdLst, self) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list list_comprehension attribute identifier identifier for_in_clause identifier identifier return_statement call identifier argument_list identifier identifier | |Slides| object containing the slides in this presentation. |
def _createbound(obj):
try:
kls = obj._unboundreference_()
except AttributeError:
kls = type(obj)
unbound = _createunbound(kls)
def valueget():
return obj
for t in (BoundBitfieldNode, BoundStructureNode, BoundArrayNode):
if isinstance(unbound, t._unboundtype):
kls = t
break
else:
kls = BoundSimpleNode
child = kls(unbound, valueget)
return child | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier function_definition identifier parameters block return_statement identifier for_statement identifier tuple identifier identifier identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier identifier break_statement else_clause block expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement identifier | Create a new BoundNode representing a given object. |
def list_domains_by_service(self, service_id):
content = self._fetch("/service/%s/domain" % service_id, method="GET")
return map(lambda x: FastlyDomain(self, x), content) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier string string_start string_content string_end return_statement call identifier argument_list lambda lambda_parameters identifier call identifier argument_list identifier identifier identifier | List the domains within a service. |
def _fix_valid_indices(cls, valid_indices, insertion_index, dim):
indices = np.array(sorted(valid_indices[dim]))
slice_index = np.sum(indices <= insertion_index)
indices[slice_index:] += 1
indices = np.insert(indices, slice_index, insertion_index + 1)
valid_indices[dim] = indices.tolist()
return valid_indices | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list subscript identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list comparison_operator identifier identifier expression_statement augmented_assignment subscript identifier slice identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier binary_operator identifier integer expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list return_statement identifier | Add indices for H&S inserted elements. |
def _read_object(self, path):
if not os.path.exists(path):
return None
if os.path.isdir(path):
raise RuntimeError('%s is a directory, not a file.' % path)
with open(path) as f:
file_contents = f.read()
return file_contents | module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block return_statement none if_statement call attribute attribute identifier identifier identifier argument_list identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier | read in object from file at `path` |
def _replace_lines(fn, startswith, new_line):
new_lines = []
for line in open(fn):
if line.startswith(startswith):
new_lines.append(new_line)
else:
new_lines.append(line)
with open(fn, 'w') as f:
f.write('\n'.join(new_lines)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier 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 identifier | Replace lines starting with starts_with in fn with new_line. |
def decls(self) -> List[z3.ExprRef]:
result = []
for internal_model in self.raw:
result.extend(internal_model.decls())
return result | module function_definition identifier parameters identifier type generic_type identifier type_parameter type attribute identifier identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier | Get the declarations for this model |
def search(self, searchTerm):
if type(searchTerm)==type(''):
searchTerm=SearchTerm(searchTerm)
if searchTerm not in self.featpaths:
matches = None
if searchTerm.type != None and searchTerm.type != self.classname():
matches = self._searchInChildren(searchTerm)
elif searchTerm.isAtomic():
matches = self._searchSingleTerm(searchTerm)
else:
matches = self._searchMultipleTerms(searchTerm)
if matches == True:
matches = [self]
if matches == False:
matches = []
self.featpaths[searchTerm] = matches
return self.featpaths[searchTerm] | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list string string_start string_end block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier none if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier elif_clause call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier true block expression_statement assignment identifier list identifier if_statement comparison_operator identifier false block expression_statement assignment identifier list expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement subscript attribute identifier identifier identifier | Returns objects matching the query. |
def handle_response(self, content, target=None, single_result=True, raw=False):
response = content['response']
self.check_errors(response)
data = response.get('data')
if is_empty(data):
return data
elif is_paginated(data):
if 'count' in data and not data['count']:
return data['data']
data = data['data']
if raw:
return data
return self.init_all_objects(data, target=target, single_result=single_result) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier true default_parameter identifier false block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement call identifier argument_list identifier block return_statement identifier elif_clause call identifier argument_list identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier not_operator subscript identifier string string_start string_content string_end block return_statement subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement identifier block return_statement identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier | Parses response, checks it. |
def build_dir_tree(self, files):
def helper(split_files):
this_dir = {'files' : {}, 'dirs' : {}}
dirs = defaultdict(list)
for fle in split_files:
index = fle[0]; fileinfo = fle[1]
if len(index) == 1:
fileinfo['path'] = index[0]
this_dir['files'][fileinfo['path']] = fileinfo
elif len(index) > 1:
dirs[index[0]].append((index[1:], fileinfo))
for name,info in dirs.iteritems():
this_dir['dirs'][name] = helper(info)
return this_dir
return helper([(name.split('/')[1:], file_info) for name, file_info in files.iteritems()]) | module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end dictionary expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier integer expression_statement assignment subscript subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end identifier elif_clause comparison_operator call identifier argument_list identifier integer block expression_statement call attribute subscript identifier subscript identifier integer identifier argument_list tuple subscript identifier slice integer identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript subscript identifier string string_start string_content string_end identifier call identifier argument_list identifier return_statement identifier return_statement call identifier argument_list list_comprehension tuple subscript call attribute identifier identifier argument_list string string_start string_content string_end slice integer identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list | Convert a flat file dict into the tree format used for storage |
def parse(s):
stopwatch = StopWatch()
for line in s.splitlines():
if line.strip():
parts = line.split(None)
name = parts[0]
if name != "%":
rest = (float(v) for v in parts[2:])
stopwatch.times[parts[0]].merge(Stat.build(*rest))
return stopwatch | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier call attribute identifier identifier argument_list block if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list none expression_statement assignment identifier subscript identifier integer if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier generator_expression call identifier argument_list identifier for_in_clause identifier subscript identifier slice integer expression_statement call attribute subscript attribute identifier identifier subscript identifier integer identifier argument_list call attribute identifier identifier argument_list list_splat identifier return_statement identifier | Parse the output below to create a new StopWatch. |
def walk(node, walker):
method_name = '_' + node.__class__.__name__
method = getattr(walker, method_name, None)
if method is not None:
if isinstance(node, _ast.ImportFrom) and node.module is None:
node.module = ''
return method(node)
for child in get_child_nodes(node):
walk(child, walker) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier none if_statement comparison_operator identifier none block if_statement boolean_operator call identifier argument_list identifier attribute identifier identifier comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier string string_start string_end return_statement call identifier argument_list identifier for_statement identifier call identifier argument_list identifier block expression_statement call identifier argument_list identifier identifier | Walk the syntax tree |
def _find_glob_matches(in_files, metadata):
reg_files = copy.deepcopy(in_files)
glob_files = []
for glob_search in [x for x in metadata.keys() if "*" in x]:
cur = []
for fname in in_files:
if fnmatch.fnmatch(fname, "*/%s" % glob_search):
cur.append(fname)
reg_files.remove(fname)
assert cur, "Did not find file matches for %s" % glob_search
glob_files.append(cur)
return reg_files, glob_files | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier assert_statement identifier binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier | Group files that match by globs for merging, rather than by explicit pairs. |
def split(attrs, inputs, proto_obj):
split_list = attrs.get('split') if 'split' in attrs else []
new_attrs = translation_utils._fix_attribute_names(attrs,
{'split' : 'num_outputs'})
if 'axis' not in attrs:
new_attrs = translation_utils._add_extra_attributes(new_attrs, {'axis': 0})
if not split_list:
num_outputs = len(proto_obj.model_metadata.get('output_tensor_data'))
else:
if len(set(split_list)) == 1:
num_outputs = len(split_list)
else:
raise NotImplementedError("Operator {} in MXNet does not support variable splits."
"Tracking the issue to support variable split here: "
"https://github.com/apache/incubator-mxnet/issues/11594"
.format('split'))
new_attrs['num_outputs'] = num_outputs
return 'split', new_attrs, inputs | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator string string_start string_content string_end identifier list expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary pair string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary pair string string_start string_content string_end integer if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end else_clause block if_statement comparison_operator call identifier argument_list call identifier argument_list identifier integer block expression_statement assignment identifier call identifier argument_list identifier else_clause block raise_statement call 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 identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement expression_list string string_start string_content string_end identifier identifier | Splits an array along a particular axis into multiple sub-arrays. |
def jenkins(self):
job_name = self.format['jenkins_job_name'].format(**self.data)
job = {'name': job_name}
return job | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list dictionary_splat attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier return_statement identifier | Generate jenkins job details. |
def connected(self, client):
self.clients.add(client)
self._log_connected(client)
self._start_watching(client)
self.send_msg(client, WELCOME, (self.pickle_protocol, __version__),
pickle_protocol=0)
profiler = self.profiler
while True:
try:
profiler = profiler.profiler
except AttributeError:
break
self.send_msg(client, PROFILER, type(profiler))
if self._latest_result_data is not None:
try:
self._send(client, self._latest_result_data)
except socket.error as exc:
if exc.errno in (EBADF, EPIPE):
self.disconnected(client)
return
raise
if len(self.clients) == 1:
self._start_profiling() | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier tuple attribute identifier identifier identifier keyword_argument identifier integer expression_statement assignment identifier attribute identifier identifier while_statement true block try_statement block expression_statement assignment identifier attribute identifier identifier except_clause identifier block break_statement expression_statement call attribute identifier identifier argument_list identifier identifier call identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block try_statement block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block if_statement comparison_operator attribute identifier identifier tuple identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement raise_statement if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list | Call this method when a client connected. |
def _bend_cos_low(a, b, deriv):
a = Vector3(6, deriv, a, (0, 1, 2))
b = Vector3(6, deriv, b, (3, 4, 5))
a /= a.norm()
b /= b.norm()
return dot(a, b).results() | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list integer identifier identifier tuple integer integer integer expression_statement assignment identifier call identifier argument_list integer identifier identifier tuple integer integer integer expression_statement augmented_assignment identifier call attribute identifier identifier argument_list expression_statement augmented_assignment identifier call attribute identifier identifier argument_list return_statement call attribute call identifier argument_list identifier identifier identifier argument_list | Similar to bend_cos, but with relative vectors |
def invenio_query_factory(parser=None, walkers=None):
parser = parser or Main
walkers = walkers or [PypegConverter()]
walkers.append(ElasticSearchDSL())
def invenio_query(pattern):
query = pypeg2.parse(pattern, parser, whitespace="")
for walker in walkers:
query = query.accept(walker)
return query
return invenio_query | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier identifier expression_statement assignment identifier boolean_operator identifier list call identifier argument_list expression_statement call attribute identifier identifier argument_list call identifier argument_list function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_end for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier return_statement identifier | Create a parser returning Elastic Search DSL query instance. |
def json(func):
"Decorator to make JSON views simpler"
def wrapper(self, request, *args, **kwargs):
try:
response = {
"success": True,
"data": func(self, request, *args, **kwargs)
}
except GargoyleException, exc:
response = {
"success": False,
"data": exc.message
}
except Switch.DoesNotExist:
response = {
"success": False,
"data": "Switch cannot be found"
}
except ValidationError, e:
response = {
"success": False,
"data": u','.join(map(unicode, e.messages)),
}
except Exception:
if settings.DEBUG:
import traceback
traceback.print_exc()
raise
return HttpResponse(dumps(response), content_type="application/json")
wrapper = wraps(func)(wrapper)
return wrapper | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier dictionary pair string string_start string_content string_end true pair string string_start string_content string_end call identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier except_clause identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end false pair string string_start string_content string_end attribute identifier identifier except_clause attribute identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end false pair string string_start string_content string_end string string_start string_content string_end except_clause identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end false pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier attribute identifier identifier except_clause identifier block if_statement attribute identifier identifier block import_statement dotted_name identifier expression_statement call attribute identifier identifier argument_list raise_statement return_statement call identifier argument_list call identifier argument_list identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call call identifier argument_list identifier argument_list identifier return_statement identifier | Decorator to make JSON views simpler |
def reset_scan_stats(self):
self._scan_event_count = 0
self._v1_scan_count = 0
self._v1_scan_response_count = 0
self._v2_scan_count = 0
self._device_scan_counts = {}
self._last_reset_time = time.time() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list | Clears the scan event statistics and updates the last reset time |
def marker_index_document_id(self):
params = '%s:%s:%s' % (self.index, self.doc_type, self.update_id)
return hashlib.sha1(params.encode('utf-8')).hexdigest() | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier return_statement call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list | Generate an id for the indicator document. |
def accuracy_thresh_expand(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor:
"Compute accuracy after expanding `y_true` to the size of `y_pred`."
if sigmoid: y_pred = y_pred.sigmoid()
return ((y_pred>thresh)==y_true[:,None].expand_as(y_pred).byte()).float().mean() | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier float typed_default_parameter identifier type identifier true type identifier block expression_statement string string_start string_content string_end if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute call attribute parenthesized_expression comparison_operator parenthesized_expression comparison_operator identifier identifier call attribute call attribute subscript identifier slice none identifier argument_list identifier identifier argument_list identifier argument_list identifier argument_list | Compute accuracy after expanding `y_true` to the size of `y_pred`. |
def check_config(config):
"basic checks that the configuration file is valid"
shortnames = [count['shortname'] for count in config['count']]
if len(shortnames) != len(set(shortnames)):
logger.error("error: duplicate `shortname' in count configuration.")
return False
return True | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier subscript identifier string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier call identifier argument_list call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false return_statement true | basic checks that the configuration file is valid |
def __safe_name(self, method_name):
safe_name = re.sub(r'[^\.a-zA-Z0-9_]', '', method_name)
safe_name = safe_name.lstrip('_')
return safe_name[0:1].lower() + safe_name[1:] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement binary_operator call attribute subscript identifier slice integer integer identifier argument_list subscript identifier slice integer | Restrict method name to a-zA-Z0-9_, first char lowercase. |
def add_task_to_job(self, job_or_job_name, task_command, task_name=None,
**kwargs):
if isinstance(job_or_job_name, Job):
job = job_or_job_name
else:
job = self.get_job(job_or_job_name)
if not job:
raise DagobahError('job %s does not exist' % job_or_job_name)
logger.debug('Adding task with command {0} to job {1}'.format(task_command, job.name))
if not job.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current " +
"state: %s"
% job.state.status)
job.add_task(task_command, task_name, **kwargs)
job.commit() | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier attribute identifier identifier if_statement not_operator attribute attribute identifier identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier dictionary_splat identifier expression_statement call attribute identifier identifier argument_list | Add a task to a job owned by the Dagobah instance. |
def getL2Representations(self):
return [set(L2.getSelf()._pooler.getActiveCells()) for L2 in self.L2Regions] | module function_definition identifier parameters identifier block return_statement list_comprehension call identifier argument_list call attribute attribute call attribute identifier identifier argument_list identifier identifier argument_list for_in_clause identifier attribute identifier identifier | Returns the active representation in L2. |
def run_file(self, path, all_errors_exit=True):
path = fixpath(path)
with self.handling_errors(all_errors_exit):
module_vars = run_file(path)
self.vars.update(module_vars)
self.store("from " + splitname(path)[1] + " import *") | module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier call identifier argument_list identifier with_statement with_clause with_item call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator binary_operator string string_start string_content string_end subscript call identifier argument_list identifier integer string string_start string_content string_end | Execute a Python file. |
def image_box(center, shape, box):
return tuple(slice_create(c, b, stop=s)
for c, s, b in zip(center, shape, box)) | module function_definition identifier parameters identifier identifier identifier block return_statement call identifier generator_expression call identifier argument_list identifier identifier keyword_argument identifier identifier for_in_clause pattern_list identifier identifier identifier call identifier argument_list identifier identifier identifier | Create a region of size box, around a center in a image of shape. |
def write_file(data, outfilename):
if not data:
return False
try:
with open(outfilename, 'w') as outfile:
for line in data:
if line:
outfile.write(line)
return True
except (OSError, IOError) as err:
sys.stderr.write('An error occurred while writing {0}:\n{1}'
.format(outfilename, str(err)))
return False | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement false 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 for_statement identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement true except_clause as_pattern tuple identifier identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier call identifier argument_list identifier return_statement false | Write a single file to disk. |
def find_name():
name_file = read_file('__init__.py')
name_match = re.search(r'^__package_name__ = ["\']([^"\']*)["\']',
name_file, re.M)
if name_match:
return name_match.group(1)
raise RuntimeError('Unable to find name string.') | module function_definition identifier parameters block expression_statement assignment identifier call 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 identifier attribute identifier identifier if_statement identifier block return_statement call attribute identifier identifier argument_list integer raise_statement call identifier argument_list string string_start string_content string_end | Only define name in one place |
def _merge_inplace(self, other):
if other is None:
yield
else:
priority_vars = OrderedDict(
kv for kv in self.variables.items() if kv[0] not in self.dims)
variables = merge_coords_for_inplace_math(
[self.variables, other.variables], priority_vars=priority_vars)
yield
self._update_coords(variables) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block expression_statement yield else_clause block expression_statement assignment identifier call identifier generator_expression identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list if_clause comparison_operator subscript identifier integer attribute identifier identifier expression_statement assignment identifier call identifier argument_list list attribute identifier identifier attribute identifier identifier keyword_argument identifier identifier expression_statement yield expression_statement call attribute identifier identifier argument_list identifier | For use with in-place binary arithmetic. |
def auto_complete(self, term, state=None, postcode=None, max_results=None):
self._validate_state(state)
params = {"term": term, "state": state, "postcode": postcode,
"max_results": max_results or self.max_results}
return self._make_request('/address/autoComplete', params) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement call attribute identifier identifier argument_list identifier 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 pair string string_start string_content string_end boolean_operator identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Gets a list of addresses that begin with the given term. |
def insert_child(self, child_pid):
self._check_child_limits(child_pid)
try:
with db.session.begin_nested():
if not isinstance(child_pid, PersistentIdentifier):
child_pid = resolve_pid(child_pid)
return PIDRelation.create(
self._resolved_pid, child_pid, self.relation_type.id, None
)
except IntegrityError:
raise PIDRelationConsistencyError("PID Relation already exists.") | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier try_statement block with_statement with_clause with_item call attribute attribute identifier identifier identifier argument_list block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier attribute attribute identifier identifier identifier none except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end | Add the given PID to the list of children PIDs. |
def _tool_classpath(self, tool, products, scheduler):
classpath = self.tool_classpath_from_products(products,
self.versioned_tool_name(tool, self.version),
scope=self.options_scope)
classpath = tuple(fast_relpath(c, get_buildroot()) for c in classpath)
return self._memoized_scalac_classpath(classpath, scheduler) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call identifier generator_expression call identifier argument_list identifier call identifier argument_list for_in_clause identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier | Return the proper classpath based on products and scala version. |
def could_be(self, other):
if type(other) is not type(self):
return NotImplemented
if self == other:
return True
for attr in ['title', 'firstname', 'middlename', 'nickname', 'prefix', 'lastname', 'suffix']:
if attr not in self or attr not in other:
continue
puncmap = dict((ord(char), None) for char in string.punctuation)
s = self[attr].lower().translate(puncmap)
o = other[attr].lower().translate(puncmap)
if s == o:
continue
if attr in {'firstname', 'middlename', 'lastname'}:
if (({len(comp) for comp in s.split()} == {1} and [el[0] for el in o.split()] == s.split()) or
({len(comp) for comp in o.split()} == {1} and [el[0] for el in s.split()] == o.split())):
continue
return False
return True | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier block return_statement identifier if_statement comparison_operator identifier identifier block return_statement true for_statement identifier 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 string string_start string_content string_end string string_start string_content string_end block if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier block continue_statement expression_statement assignment identifier call identifier generator_expression tuple call identifier argument_list identifier none for_in_clause identifier attribute identifier identifier expression_statement assignment identifier call attribute call attribute subscript identifier identifier identifier argument_list identifier argument_list identifier expression_statement assignment identifier call attribute call attribute subscript identifier identifier identifier argument_list identifier argument_list identifier if_statement comparison_operator identifier identifier block continue_statement if_statement comparison_operator identifier set string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block if_statement parenthesized_expression boolean_operator parenthesized_expression boolean_operator comparison_operator set_comprehension call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list set integer comparison_operator list_comprehension subscript identifier integer for_in_clause identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list parenthesized_expression boolean_operator comparison_operator set_comprehension call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list set integer comparison_operator list_comprehension subscript identifier integer for_in_clause identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list block continue_statement return_statement false return_statement true | Return True if the other PersonName is not explicitly inconsistent. |
def _all_keys(self):
file_keys = [self._filename_to_key(fn) for fn in self._all_filenames()]
if self._sync:
return set(file_keys)
else:
return set(file_keys + list(self._buffer)) | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list if_statement attribute identifier identifier block return_statement call identifier argument_list identifier else_clause block return_statement call identifier argument_list binary_operator identifier call identifier argument_list attribute identifier identifier | Return a list of all encoded key names. |
def overlap_summary(self):
olaps = self.compute_overlaps()
table = [["5%: ",np.percentile(olaps,5)],
["25%: ",np.percentile(olaps,25)],
["50%: ",np.percentile(olaps,50)],
["75%: ",np.percentile(olaps,75)],
["95%: ",np.percentile(olaps,95)],
[" " , " "],
["Min: ",np.min(olaps)],
["Mean: ",np.mean(olaps)],
["Max: ",np.max(olaps)]]
header = ["Percentile","Overlap"]
print tabulate(table,header,tablefmt="rst") | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list list string string_start string_content string_end call attribute identifier identifier argument_list identifier integer list string string_start string_content string_end call attribute identifier identifier argument_list identifier integer list string string_start string_content string_end call attribute identifier identifier argument_list identifier integer list string string_start string_content string_end call attribute identifier identifier argument_list identifier integer list string string_start string_content string_end call attribute identifier identifier argument_list identifier integer list string string_start string_content string_end string string_start string_content string_end list string string_start string_content string_end call attribute identifier identifier argument_list identifier list string string_start string_content string_end call attribute identifier identifier argument_list identifier list string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end print_statement call identifier argument_list identifier identifier keyword_argument identifier string string_start string_content string_end | print summary of reconstruction overlaps |
def remove_node(self, node):
if _debug: Network._debug("remove_node %r", node)
self.nodes.remove(node)
node.lan = None | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier none | Remove a node from this network. |
def getEvent(self, dev_id, starttime, endtime):
path = 'device/%s/event?startTime=%s&endTime=%s' % \
(dev_id, starttime, endtime)
return self.rachio.get(path) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end line_continuation tuple identifier identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier | Retrieve events for a device entity. |
def filter_dup(lst, lists):
max_rank = len(lst) + 1
dct = to_ranked_dict(lst)
dicts = [to_ranked_dict(l) for l in lists]
return [word for word in lst if all(dct[word] < dct2.get(word, max_rank) for dct2 in dicts)] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator call identifier argument_list identifier integer expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier return_statement list_comprehension identifier for_in_clause identifier identifier if_clause call identifier generator_expression comparison_operator subscript identifier identifier call attribute identifier identifier argument_list identifier identifier for_in_clause identifier identifier | filters lst to only include terms that don't have lower rank in another list |
def set(self, val):
msg = ExtendedSend(
address=self._address,
commandtuple=COMMAND_THERMOSTAT_SET_COOL_SETPOINT_0X6C_NONE,
cmd2=int(val * 2),
userdata=Userdata())
msg.set_checksum()
self._send_method(msg, self._set_cool_point_ack) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier call identifier argument_list binary_operator identifier integer keyword_argument identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier | Set the cool set point. |
def _send_event(self, title, text, tags, event_type, aggregation_key, severity='info'):
event_dict = {
'timestamp': int(time()),
'source_type_name': self.SOURCE_TYPE_NAME,
'msg_title': title,
'event_type': event_type,
'alert_type': severity,
'msg_text': text,
'tags': tags,
'aggregation_key': aggregation_key,
}
self.event(event_dict) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier dictionary pair string string_start string_content string_end call identifier argument_list call identifier argument_list pair string string_start string_content string_end attribute identifier identifier 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 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 expression_statement call attribute identifier identifier argument_list identifier | Emit an event to the Datadog Event Stream. |
def _convert_agent_types(ind, to_string=False, **kwargs):
if to_string:
return serialize_distribution(ind, **kwargs)
return deserialize_distribution(ind, **kwargs) | module function_definition identifier parameters identifier default_parameter identifier false dictionary_splat_pattern identifier block if_statement identifier block return_statement call identifier argument_list identifier dictionary_splat identifier return_statement call identifier argument_list identifier dictionary_splat identifier | Convenience method to allow specifying agents by class or class name. |
def _parse_result(self, ok, match, fh=None):
peek_match = None
try:
if fh is not None and self._try_peeking:
peek_match = self.yaml_block_start.match(fh.peek())
except StopIteration:
pass
if peek_match is None:
return Result(
ok,
number=match.group("number"),
description=match.group("description").strip(),
directive=Directive(match.group("directive")),
)
indent = peek_match.group("indent")
concat_yaml = self._extract_yaml_block(indent, fh)
return Result(
ok,
number=match.group("number"),
description=match.group("description").strip(),
directive=Directive(match.group("directive")),
raw_yaml_block=concat_yaml,
) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier none try_statement block if_statement boolean_operator comparison_operator identifier none attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list except_clause identifier block pass_statement if_statement comparison_operator identifier none block return_statement call identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list keyword_argument identifier call identifier argument_list 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 call attribute identifier identifier argument_list identifier identifier return_statement call identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list keyword_argument identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier | Parse a matching result line into a result instance. |
def threeprime_plot(self):
data = dict()
dict_to_add = dict()
for key in self.threepGtoAfreq_data:
pos = list(range(1,len(self.threepGtoAfreq_data.get(key))))
tmp = [i * 100.0 for i in self.threepGtoAfreq_data.get(key)]
tuples = list(zip(pos,tmp))
data = dict((x, y) for x, y in tuples)
dict_to_add[key] = data
config = {
'id': 'threeprime_misinc_plot',
'title': 'DamageProfiler: 3P G>A misincorporation plot',
'ylab': '% G to A substituted',
'xlab': 'Nucleotide position from 3\'',
'tt_label': '{point.y:.2f} % G>A misincorporations at nucleotide position {point.x}',
'ymin': 0,
'xmin': 1
}
return linegraph.plot(dict_to_add,config) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list integer call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension binary_operator identifier float for_in_clause identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier expression_statement assignment identifier call identifier generator_expression tuple identifier identifier for_in_clause pattern_list identifier identifier identifier expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content escape_sequence string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end integer pair string string_start string_content string_end integer return_statement call attribute identifier identifier argument_list identifier identifier | Generate a 3' G>A linegraph plot |
def placeFiles(ftp, path):
for name in os.listdir(path):
if name != "config.py" and name != "config.pyc" and name != "templates" and name != "content":
localpath = os.path.join(path, name)
if os.path.isfile(localpath):
print("STOR", name, localpath)
ftp.storbinary('STOR ' + name, open(localpath, 'rb'))
elif os.path.isdir(localpath):
print("MKD", name)
try:
ftp.mkd(name)
except error_perm as e:
if not e.args[0].startswith('550'):
raise
print("CWD", name)
ftp.cwd(name)
placeFiles(ftp, localpath)
print("CWD", "..")
ftp.cwd("..") | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier block if_statement boolean_operator boolean_operator boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier call identifier argument_list identifier string string_start string_content string_end elif_clause call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement not_operator call attribute subscript attribute identifier identifier integer identifier argument_list string string_start string_content string_end block raise_statement expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list identifier identifier expression_statement call identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Upload the built files to FTP |
def put_field(self, field):
fpath = self.fields_json_path(field)
with InterProcessLock(fpath + self.LOCK_SUFFIX, logger=logger):
try:
with open(fpath, 'r') as f:
dct = json.load(f)
except IOError as e:
if e.errno == errno.ENOENT:
dct = {}
else:
raise
if field.array:
dct[field.name] = list(field.value)
else:
dct[field.name] = field.value
with open(fpath, 'w') as f:
json.dump(dct, f, indent=2) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier with_statement with_clause with_item call identifier argument_list binary_operator identifier attribute identifier identifier keyword_argument identifier identifier block 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 assignment identifier call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier dictionary else_clause block raise_statement if_statement attribute identifier identifier block expression_statement assignment subscript identifier attribute identifier identifier call identifier argument_list attribute identifier identifier else_clause block expression_statement assignment subscript identifier attribute identifier identifier attribute identifier identifier 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 identifier identifier keyword_argument identifier integer | Inserts or updates a field in the repository |
def ctrl_int_cmd(self, cmd):
cmd_url = 'ctrl-int/1/{}?[AUTH]&prompt-id=0'.format(cmd)
return self.daap.post(cmd_url) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier | Perform a "ctrl-int" command. |
def _check_all_metadata_found(metadata, items):
for name in metadata:
seen = False
for sample in items:
check_file = sample["files"][0] if sample.get("files") else sample["vrn_file"]
if isinstance(name, (tuple, list)):
if check_file.find(name[0]) > -1:
seen = True
elif check_file.find(name) > -1:
seen = True
elif "*" in name and fnmatch.fnmatch(check_file, "*/%s" % name):
seen = True
if not seen:
print("WARNING: sample not found %s" % str(name)) | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block expression_statement assignment identifier false for_statement identifier identifier block expression_statement assignment identifier conditional_expression subscript subscript identifier string string_start string_content string_end integer call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement call identifier argument_list identifier tuple identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list subscript identifier integer unary_operator integer block expression_statement assignment identifier true elif_clause comparison_operator call attribute identifier identifier argument_list identifier unary_operator integer block expression_statement assignment identifier true elif_clause boolean_operator comparison_operator string string_start string_content string_end identifier call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end identifier block expression_statement assignment identifier true if_statement not_operator identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier | Print warning if samples in CSV file are missing in folder |
def reset(self):
self.context = pyblish.api.Context()
self.plugins = pyblish.api.discover()
self.was_discovered.emit()
self.pair_generator = None
self.current_pair = (None, None)
self.current_error = None
self.processing = {
"nextOrder": None,
"ordersWithError": set()
}
self._load()
self._run(until=pyblish.api.CollectorOrder,
on_finished=self.was_reset.emit) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier tuple none none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier dictionary pair string string_start string_content string_end none pair string string_start string_content string_end call identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier | Discover plug-ins and run collection |
def make_module_to_builder_dict(datasets=None):
module_to_builder = collections.defaultdict(
lambda: collections.defaultdict(
lambda: collections.defaultdict(list)))
if datasets:
builders = [tfds.builder(name) for name in datasets]
else:
builders = [
tfds.builder(name)
for name in tfds.list_builders()
if name not in BUILDER_BLACKLIST
] + [tfds.builder("image_label_folder", dataset_name="image_label_folder")]
for builder in builders:
mod_name = builder.__class__.__module__
modules = mod_name.split(".")
if "testing" in modules:
continue
current_mod_ctr = module_to_builder
for mod in modules:
current_mod_ctr = current_mod_ctr[mod]
current_mod_ctr.append(builder)
module_to_builder = module_to_builder["tensorflow_datasets"]
return module_to_builder | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list lambda call attribute identifier identifier argument_list lambda call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier else_clause block expression_statement assignment identifier binary_operator list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier identifier list call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block continue_statement expression_statement assignment identifier identifier for_statement identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end return_statement identifier | Get all builders organized by module in nested dicts. |
def increment(self, gold_set, test_set):
"Add examples from sets."
self.gold += len(gold_set)
self.test += len(test_set)
self.correct += len(gold_set & test_set) | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement augmented_assignment attribute identifier identifier call identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier call identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier call identifier argument_list binary_operator identifier identifier | Add examples from sets. |
def engineering(value, precision=3, prefix=False, prefixes=SI):
display = decimal.Context(prec=precision)
value = decimal.Decimal(value).normalize(context=display)
string = value.to_eng_string()
if prefix:
prefixes = {e(exponent): prefix for exponent, prefix in prefixes.items()}
return replace(string, prefixes)
else:
return string | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier false default_parameter identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier dictionary_comprehension pair call identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list return_statement call identifier argument_list identifier identifier else_clause block return_statement identifier | Convert a number to engineering notation. |
def negate_gate(wordlen, input='x', output='~x'):
neg = bitwise_negate(wordlen, input, "tmp")
inc = inc_gate(wordlen, "tmp", output)
return neg >> inc | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end identifier return_statement binary_operator identifier identifier | Implements two's complement negation. |
def cause_repertoire(self, mechanism, purview):
return self.repertoire(Direction.CAUSE, mechanism, purview) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier | Return the cause repertoire. |
def _put_many(self, items):
for item in items:
if not isinstance(item, self._item_class):
raise RuntimeError('Items mismatch for %s and %s' % (self._item_class, type(item)))
self._put_one(item) | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | store items in sqlite database |
def check_drives(drivename, drivestatus):
return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format(
drivename, DISK_STATES[int(drivestatus)]["result"]) | module function_definition identifier parameters identifier identifier block return_statement expression_list subscript subscript identifier call identifier argument_list identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier subscript subscript identifier call identifier argument_list identifier string string_start string_content string_end | check the drive status |
def list_from_metadata(cls, url, metadata):
key = cls._get_key(url)
metadata = Metadata(**metadata)
ct = cls._get_create_time(key)
time_buckets = cls.get_time_buckets_from_metadata(metadata)
return [cls(url, metadata, t, ct, key.size) for t in time_buckets] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement list_comprehension call identifier argument_list identifier identifier identifier identifier attribute identifier identifier for_in_clause identifier identifier | return a list of DatalakeRecords for the url and metadata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.