code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def tracefunc_xml(func):
funcname = meta_util_six.get_funcname(func)
def wrp_tracefunc2(*args, **kwargs):
verbose = kwargs.get('verbose', True)
if verbose:
print('<%s>' % (funcname,))
with util_print.Indenter(' '):
ret = func(*args, **kwargs)
if verbose:
print('</%s>' % (funcname,))
return ret
wrp_tracefunc2_ = ignores_exc_tb(wrp_tracefunc2)
wrp_tracefunc2_ = preserve_sig(wrp_tracefunc2_, func)
return wrp_tracefunc2_ | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end true if_statement identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier if_statement identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier return_statement identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement identifier | Causes output of function to be printed in an XML style block |
def _index_document(self, document, force=False):
query = text(
)
self.execute(query, **document) | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier | Adds dataset document to the index. |
def iterkeys(self):
"Returns an iterator over the keys of ConfigMap."
return chain(self._pb.StringMap.keys(),
self._pb.IntMap.keys(),
self._pb.FloatMap.keys(),
self._pb.BoolMap.keys()) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end return_statement call identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list | Returns an iterator over the keys of ConfigMap. |
def removePhenotypeAssociationSet(self, phenotypeAssociationSet):
q = models.Phenotypeassociationset.delete().where(
models.Phenotypeassociationset.id ==
phenotypeAssociationSet.getId())
q.execute() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list comparison_operator attribute attribute identifier identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Remove a phenotype association set from the repo |
def hash_values(values, alg="md5"):
import hashlib
if alg not in ['md5', 'sha1', 'sha256']:
raise Exception("Invalid hashing algorithm!")
hasher = getattr(hashlib, alg)
if type(values) == str:
output = hasher(values).hexdigest()
elif type(values) == list:
output = list()
for item in values:
output.append(hasher(item).hexdigest())
return output | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block import_statement dotted_name identifier if_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list elif_clause comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute call identifier argument_list identifier identifier argument_list return_statement identifier | Hash a list of values. |
def send_email(self, user, subject, msg):
print('To:', user)
print('Subject:', subject)
print(msg) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call identifier argument_list identifier | Should be overwritten in the setup |
def action_to_approve(self):
template = self.env.ref(
'document_page_approval.email_template_new_draft_need_approval')
approver_gid = self.env.ref(
'document_page_approval.group_document_approver_user')
for rec in self:
if rec.state != 'draft':
raise UserError(
_("Can't approve pages in '%s' state.") % rec.state)
if not (rec.am_i_owner or rec.am_i_approver):
raise UserError(
_('You are not authorized to do this.\r\n'
'Only owners or approvers can request approval.'))
if rec.is_approval_required:
rec.write({'state': 'to approve'})
guids = [g.id for g in rec.page_id.approver_group_ids]
users = self.env['res.users'].search([
('groups_id', 'in', guids),
('groups_id', 'in', approver_gid.id)])
rec.message_subscribe_users([u.id for u in users])
rec.message_post_with_template(template.id)
else:
rec.action_approve() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block raise_statement call identifier argument_list binary_operator call identifier argument_list string string_start string_content string_end attribute identifier identifier if_statement not_operator parenthesized_expression boolean_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call identifier argument_list concatenated_string string string_start string_content escape_sequence escape_sequence string_end string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list list tuple string string_start string_content string_end string string_start string_content string_end identifier tuple string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list list_comprehension attribute identifier identifier for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list | Set a change request as to approve |
def query(self, parents=None):
q = Select([])
q = self.project(q, parent=True)
q = self.filter(q, parents=parents)
if self.parent is None:
subq = Select([self.var])
subq = self.filter(subq, parents=parents)
subq = subq.offset(self.node.offset)
subq = subq.limit(self.node.limit)
subq = subq.distinct()
subq = subq.order_by(desc(self.var))
q = q.where(subq)
log.debug("Compiled query: %r", q.compile())
return q | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call identifier argument_list list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list return_statement identifier | Compose the query and generate SPARQL. |
def _build_tag_param_list(params, tags):
keys = sorted(tags.keys())
i = 1
for key in keys:
value = tags[key]
params['Tags.member.{0}.Key'.format(i)] = key
if value is not None:
params['Tags.member.{0}.Value'.format(i)] = value
i += 1 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier integer for_statement identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment subscript identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement assignment subscript identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement augmented_assignment identifier integer | helper function to build a tag parameter list to send |
def random_id(k=5):
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k)) | module function_definition identifier parameters default_parameter identifier integer block return_statement call attribute string string_start string_end identifier argument_list call attribute identifier identifier argument_list binary_operator attribute identifier identifier attribute identifier identifier keyword_argument identifier identifier | Random id to use for AWS identifiers. |
def unpack(self, unpacker):
(a, b, c, d) = unpacker.unpack_struct(_HHHH)
self.inner_info_ref = a
self.outer_info_ref = b
self.name_ref = c
self.access_flags = d | module function_definition identifier parameters identifier identifier block expression_statement assignment tuple_pattern identifier identifier identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier | unpack this instance with data from unpacker |
def handle_unsuback(self):
self.logger.info("UNSUBACK received")
ret, mid = self.in_packet.read_uint16()
if ret != NC.ERR_SUCCESS:
return ret
evt = event.EventUnsuback(mid)
self.push_event(evt)
return NC.ERR_SUCCESS | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block return_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement attribute identifier identifier | Handle incoming UNSUBACK packet. |
def save(self, commit=True):
for localized_field in self.instance.localized_fields:
setattr(self.instance, localized_field, self.cleaned_data[localized_field])
return super(LocalisedForm, self).save(commit) | module function_definition identifier parameters identifier default_parameter identifier true block for_statement identifier attribute attribute identifier identifier identifier block expression_statement call identifier argument_list attribute identifier identifier identifier subscript attribute identifier identifier identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier | Override save method to also save the localised fields. |
def fetch(url, timeout=5, userAgent=None, only_mime_types=None):
headers = {}
if userAgent:
headers['User-agent'] = str(userAgent)
else:
headers['User-agent'] = ua.random
response = requests.get(url, headers=headers, timeout=timeout)
if only_mime_types:
assert isinstance(only_mime_types, (tuple, list))
ct, mt_encoding = mimetypes.guess_type(url)
if not ct:
response_info = response.info()
ct = (response_info.getheader('Content-Type') or '').split(';')[0]
if ct not in only_mime_types:
return
try:
return response.text
except httplib.IncompleteRead as e:
return e.partial | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier dictionary if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier else_clause block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement identifier block assert_statement call identifier argument_list identifier tuple identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript call attribute parenthesized_expression boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_end integer if_statement comparison_operator identifier identifier block return_statement try_statement block return_statement attribute identifier identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block return_statement attribute identifier identifier | Retrieves the raw content of the URL. |
def max_normal_germline_depth(in_file, params, somatic_info):
bcf_in = pysam.VariantFile(in_file)
depths = []
for rec in bcf_in:
stats = _is_possible_loh(rec, bcf_in, params, somatic_info)
if tz.get_in(["normal", "depth"], stats):
depths.append(tz.get_in(["normal", "depth"], stats))
if depths:
return np.median(depths) * NORMAL_FILTER_PARAMS["max_depth_percent"] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier if_statement call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end identifier if_statement identifier block return_statement binary_operator call attribute identifier identifier argument_list identifier subscript identifier string string_start string_content string_end | Calculate threshold for excluding potential heterozygotes based on normal depth. |
def to_json(self):
result = {
'sys': {}
}
for k, v in self.sys.items():
if k in ['space', 'content_type', 'created_by',
'updated_by', 'published_by']:
v = v.to_json()
if k in ['created_at', 'updated_at', 'deleted_at',
'first_published_at', 'published_at', 'expires_at']:
v = v.isoformat()
result['sys'][camel_case(k)] = v
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator 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 block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator 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 block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript subscript identifier string string_start string_content string_end call identifier argument_list identifier identifier return_statement identifier | Returns the JSON representation of the resource. |
def model(self):
if self.is_bootloader:
out = self.fastboot.getvar('product').strip()
lines = out.decode('utf-8').split('\n', 1)
if lines:
tokens = lines[0].split(' ')
if len(tokens) > 1:
return tokens[1].lower()
return None
model = self.adb.getprop('ro.build.product').lower()
if model == 'sprout':
return model
return self.adb.getprop('ro.product.name').lower() | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_content escape_sequence string_end integer if_statement identifier block expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block return_statement call attribute subscript identifier integer identifier argument_list return_statement none expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block return_statement identifier return_statement call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list | The Android code name for the device. |
def import_object(object_name):
package, name = object_name.rsplit('.', 1)
return getattr(importlib.import_module(package), name) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer return_statement call identifier argument_list call attribute identifier identifier argument_list identifier identifier | Import an object from its Fully Qualified Name. |
def connected(self):
return self.websocket is not None and \
self.websocket.sock is not None and \
self.websocket.sock.connected | module function_definition identifier parameters identifier block return_statement boolean_operator boolean_operator comparison_operator attribute identifier identifier none line_continuation comparison_operator attribute attribute identifier identifier identifier none line_continuation attribute attribute attribute identifier identifier identifier identifier | If connected to server. |
def _get_ticks(self, opts):
opts, _ = self._get_opts(opts, None)
if "xticks" not in opts:
if "xticks" not in self.chart_opts:
self.err(self.dlinear_,
"Please set the xticks option for this chart to work")
return
else:
xticks = self.chart_opts["xticks"]
else:
xticks = opts["xticks"]
if "yticks" not in opts:
if "yticks"not in self.chart_opts:
self.err(self.dlinear_,
"Please set the yticks option for this chart to work")
return
else:
yticks = self.chart_opts["yticks"]
else:
yticks = opts["yticks"]
return xticks, yticks | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier none if_statement comparison_operator string string_start string_content string_end identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end return_statement else_clause block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end else_clause block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end return_statement else_clause block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end else_clause block expression_statement assignment identifier subscript identifier string string_start string_content string_end return_statement expression_list identifier identifier | Check if xticks and yticks are set |
def example_df():
country_names = ['Germany',
'France',
'Indonesia',
'Ireland',
'Spain',
'Vatican']
population = [82521653, 66991000, 255461700, 4761865, 46549045, None]
population_time = [dt.datetime(2016, 12, 1),
dt.datetime(2017, 1, 1),
dt.datetime(2017, 1, 1),
None,
dt.datetime(2017, 6, 1),
None,
]
euro = [True, True, False, True, True, True]
df = pd.DataFrame({'country': country_names,
'population': population,
'population_time': population_time,
'EUR': euro})
df = df[['country', 'population', 'population_time', 'EUR']]
return df | module function_definition identifier parameters block 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 identifier list integer integer integer integer integer none expression_statement assignment identifier list call attribute identifier identifier argument_list integer integer integer call attribute identifier identifier argument_list integer integer integer call attribute identifier identifier argument_list integer integer integer none call attribute identifier identifier argument_list integer integer integer none expression_statement assignment identifier list true true false true true true 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 expression_statement assignment identifier subscript 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 return_statement identifier | Create an example dataframe. |
def cli(ctx, ids, query, filters, details, interval):
if details:
display = 'details'
else:
display = 'compact'
from_date = None
auto_refresh = True
while auto_refresh:
try:
auto_refresh, from_date = ctx.invoke(query_cmd, ids=ids, query=query,
filters=filters, display=display, from_date=from_date)
time.sleep(interval)
except (KeyboardInterrupt, SystemExit) as e:
sys.exit(e) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement identifier block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier none expression_statement assignment identifier true while_statement identifier block try_statement block expression_statement assignment pattern_list identifier identifier 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 expression_statement call attribute identifier identifier argument_list identifier except_clause as_pattern tuple identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier | Watch for new alerts. |
def fetch(self, year, week, overwrite=False):
self.config['overwrite_files'] = overwrite
time_start = time.time()
self._fetch_pageviews(self.storage, year, week, ip_users=False)
self._fetch_downloads(self.storage, year, week, ip_users=False)
self._fetch_pageviews(self.storage, year, week, ip_users=True)
self._fetch_downloads(self.storage, year, week, ip_users=True)
logger.info('Fetch %s-%s in %s seconds.', year, week,
time.time() - time_start) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier keyword_argument identifier false expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier keyword_argument identifier false expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier binary_operator call attribute identifier identifier argument_list identifier | Fetch PageViews and Downloads from Elasticsearch. |
def register_logger(self, logger):
handler = CommandHandler(self)
handler.setFormatter(CommandFormatter())
logger.handlers = [handler]
logger.propagate = False
output = self.output
level = logging.WARNING
if output.is_debug():
level = logging.DEBUG
elif output.is_very_verbose() or output.is_verbose():
level = logging.INFO
logger.setLevel(level) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list expression_statement assignment attribute identifier identifier list identifier expression_statement assignment attribute identifier identifier false expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier attribute identifier identifier elif_clause boolean_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Register a new logger. |
def acceptNavigationRequest(self, url, navigation_type, isMainFrame):
if navigation_type == QWebEnginePage.NavigationTypeLinkClicked:
self.linkClicked.emit(url)
return False
return True | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement false return_statement true | Overloaded method to handle links ourselves |
def reset(cls):
cls._func_from_name = {}
cls._func_from_hash = {}
cls._func_hash = {}
register = cls._do_register
for (func, hash_name, hash_new) in cls._std_func_data:
register(func, func.name, hash_name, hash_new)
assert set(cls._func_hash) == set(Func) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier dictionary expression_statement assignment identifier attribute identifier identifier for_statement tuple_pattern identifier identifier identifier attribute identifier identifier block expression_statement call identifier argument_list identifier attribute identifier identifier identifier identifier assert_statement comparison_operator call identifier argument_list attribute identifier identifier call identifier argument_list identifier | Reset the registry to the standard multihash functions. |
def on_message(self, data):
data = json.loads(data)
if not data["name"] is None:
logging.debug("%s: receiving message %s" % (data["name"], data["data"]))
fct = getattr(self, "on_" + data["name"])
try:
res = fct(Struct(data["data"]))
except:
res = fct(data["data"])
if res is not None:
self.write_message(res)
else:
logging.error("SockJSDefaultHandler: data.name was null") | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator comparison_operator subscript identifier string string_start string_content string_end none block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call identifier argument_list call identifier argument_list subscript identifier string string_start string_content string_end except_clause block expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Parsing data, and try to call responding message |
def detect(self, fstring, fname=None):
if fname is not None and '.' in fname:
extension = fname.rsplit('.', 1)[1]
if extension in {'pdf', 'html', 'xml'}:
return False
return True | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement boolean_operator comparison_operator identifier none comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer integer 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 return_statement false return_statement true | Have a stab at most files. |
def to_file(self, filename):
with open(filename, 'wb') as f:
f.write(self.to_bytes()) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list | Writes the contents of the CCACHE object to a file |
def com_google_fonts_check_glyphnames_max_length(ttFont):
if ttFont.sfntVersion == b'\x00\x01\x00\x00' and ttFont.get(
"post") and ttFont["post"].formatType == 3.0:
yield PASS, ("TrueType fonts with a format 3.0 post table contain no "
"glyph names.")
else:
failed = False
for name in ttFont.getGlyphOrder():
if len(name) > 109:
failed = True
yield FAIL, ("Glyph name is too long:" " '{}'").format(name)
if not failed:
yield PASS, "No glyph names exceed max allowed length." | module function_definition identifier parameters identifier block if_statement boolean_operator boolean_operator comparison_operator attribute identifier identifier string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence string_end call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator attribute subscript identifier string string_start string_content string_end identifier float block expression_statement yield expression_list identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment identifier false for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier true expression_statement yield expression_list identifier call attribute parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier if_statement not_operator identifier block expression_statement yield expression_list identifier string string_start string_content string_end | Check that glyph names do not exceed max length. |
def _load_parameters(self):
"Retrieve a list of available parameters from the database"
parameters = self._get_json('allparam/s')
data = {}
for parameter in parameters:
data[parameter['Name'].lower()] = parameter
self._parameters = ParametersContainer(data) | module function_definition identifier parameters identifier block expression_statement 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 dictionary for_statement identifier identifier block expression_statement assignment subscript identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier | Retrieve a list of available parameters from the database |
def _find_parameter(cls, dct):
num_found = 0
field = None
for key, val in dct.iteritems():
if isinstance(val, DataType) and val.is_key:
field = key
num_found += 1
if num_found > 1:
raise SetupError(502)
elif num_found == 0:
return False
dct['_cbs_key_field'] = field
dct['key'] = cls._build_prop(field)
return True | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier none for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement boolean_operator call identifier argument_list identifier identifier attribute identifier identifier block expression_statement assignment identifier identifier expression_statement augmented_assignment identifier integer if_statement comparison_operator identifier integer block raise_statement call identifier argument_list integer elif_clause comparison_operator identifier integer block return_statement false expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier return_statement true | Search for the 'key=True' case, and confirm no more than one parameter has that property. |
def remove_locations(node):
def fix(node):
if 'lineno' in node._attributes and hasattr(node, 'lineno'):
del node.lineno
if 'col_offset' in node._attributes and hasattr(node, 'col_offset'):
del node.col_offset
for child in iter_child_nodes(node):
fix(child)
fix(node) | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end attribute identifier identifier call identifier argument_list identifier string string_start string_content string_end block delete_statement attribute identifier identifier if_statement boolean_operator comparison_operator string string_start string_content string_end attribute identifier identifier call identifier argument_list identifier string string_start string_content string_end block delete_statement attribute identifier identifier for_statement identifier call identifier argument_list identifier block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier | Removes locations from the given AST tree completely |
def process_set(line, annotations):
matches = re.match('SET\s+(\w+)\s*=\s*"?(.*?)"?\s*$', line)
key = None
if matches:
key = matches.group(1)
val = matches.group(2)
if key == "STATEMENT_GROUP":
annotations["statement_group"] = val
elif key == "Citation":
annotations["citation"] = process_citation(val)
elif key.lower() == "support" or key.lower() == "evidence":
annotations["evidence"] = val
elif re.match("\s*{.*?}", val):
vals = convert_csv_str_to_list(val)
annotations[key] = vals
else:
annotations[key] = val
return annotations | 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 identifier expression_statement assignment identifier none if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list integer if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier elif_clause boolean_operator comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end identifier elif_clause call attribute identifier identifier argument_list string string_start string_content string_end identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript identifier identifier identifier else_clause block expression_statement assignment subscript identifier identifier identifier return_statement identifier | Convert annotations into nanopub_bel annotations format |
def build_select(query_obj):
return build_select_query(query_obj.source, query_obj.fields, query_obj.filter, skip=query_obj.skip, \
limit=query_obj.limit, sort=query_obj.sort, distinct=query_obj.distinct) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier line_continuation keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Given a Query obj, return the corresponding sql |
def count_emails(self, conditions={}):
url = self.EMAILS_COUNT_URL + "?"
for key, value in conditions.items():
if key is 'ids':
value = ",".join(value)
url += '&%s=%s' % (key, value)
connection = Connection(self.token)
connection.set_url(self.production, url)
connection.set_url(self.production, url)
return connection.get_request() | module function_definition identifier parameters identifier default_parameter identifier dictionary block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier return_statement call attribute identifier identifier argument_list | Count all certified emails |
def stop(self):
self._stop_event.set()
if not self.persistence:
return
if self._cancel_save is not None:
self._cancel_save()
self._cancel_save = None
self.persistence.save_sensors() | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list if_statement not_operator attribute identifier identifier block return_statement if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier none expression_statement call attribute attribute identifier identifier identifier argument_list | Stop the background thread. |
def _compute_input_activations(self, X):
n_samples = X.shape[0]
mlp_acts = np.zeros((n_samples, self.n_hidden))
if (self._use_mlp_input):
b = self.components_['biases']
w = self.components_['weights']
mlp_acts = self.alpha * (safe_sparse_dot(X, w) + b)
rbf_acts = np.zeros((n_samples, self.n_hidden))
if (self._use_rbf_input):
radii = self.components_['radii']
centers = self.components_['centers']
scale = self.rbf_width * (1.0 - self.alpha)
rbf_acts = scale * cdist(X, centers)/radii
self.input_activations_ = mlp_acts + rbf_acts | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier attribute identifier identifier if_statement parenthesized_expression attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier binary_operator attribute identifier identifier parenthesized_expression binary_operator call identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier attribute identifier identifier if_statement parenthesized_expression attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier binary_operator attribute identifier identifier parenthesized_expression binary_operator float attribute identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier call identifier argument_list identifier identifier identifier expression_statement assignment attribute identifier identifier binary_operator identifier identifier | Compute input activations given X |
def divsin_fc(fdata):
nrows = fdata.shape[0]
ncols = fdata.shape[1]
L = int(nrows / 2)
L2 = L - 2
g = np.zeros([nrows, ncols], dtype=np.complex128)
g[L2, :] = 2 * 1j * fdata[L - 1, :]
for k in xrange(L2, -L2, -1):
g[k - 1, :] = 2 * 1j * fdata[k, :] + g[k + 1, :]
fdata[:, :] = g | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier call identifier argument_list binary_operator identifier integer expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list list identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment subscript identifier identifier slice binary_operator binary_operator integer integer subscript identifier binary_operator identifier integer slice for_statement identifier call identifier argument_list identifier unary_operator identifier unary_operator integer block expression_statement assignment subscript identifier binary_operator identifier integer slice binary_operator binary_operator binary_operator integer integer subscript identifier identifier slice subscript identifier binary_operator identifier integer slice expression_statement assignment subscript identifier slice slice identifier | Apply divide by sine in the Fourier domain. |
def close(self) -> None:
if not self._closed:
self._async_client.close()
self._io_loop.close()
self._closed = True | module function_definition identifier parameters identifier type none block if_statement not_operator attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier true | Closes the HTTPClient, freeing any resources used. |
def build_command(self, config, **kwargs):
command = ['perl', self.script, CLI_OPTIONS['config']['option'], config]
for key, value in kwargs.items():
if value:
command.append(CLI_OPTIONS[key]['option'])
if value is True:
command.append(CLI_OPTIONS[key].get('default', '1'))
else:
command.append(value)
return command | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier list string string_start string_content string_end attribute identifier identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement identifier block expression_statement call attribute identifier identifier argument_list subscript subscript identifier identifier string string_start string_content string_end if_statement comparison_operator identifier true block expression_statement call attribute identifier identifier argument_list call attribute subscript identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Builds the command to execute MIP. |
def _check_spawnable(source_channels, target_channels):
if len(target_channels) != len(set(target_channels)):
raise Exception('Spawn channels must be unique')
return source_channels.issubset(
set(target_channels)) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list call identifier argument_list identifier | Check whether gate is spawnable on the target channels. |
def _on_capacity_data(self, conn, command, kwargs, response, capacity):
if self._analyzing:
self.consumed_capacities.append((command, capacity))
if self._query_rate_limit is not None:
self._query_rate_limit.on_capacity(
conn, command, kwargs, response, capacity
)
elif self.rate_limit is not None:
self.rate_limit.callback = self._on_throttle
self.rate_limit.on_capacity(conn, command, kwargs, response, capacity) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier identifier elif_clause comparison_operator attribute identifier identifier none block expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier identifier | Log the received consumed capacity data |
def main(args=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("-V", "--version", action="version",
version=__version__,
help="show version number and exit")
parser.add_argument("-l", "--local", action="store_true", default=False,
help="print datetimes in local timezone")
parser.add_argument("-f", "--format", type=str, action="store",
default=r"%Y-%m-%d %H:%M:%S.%f %Z",
help="output datetime format (default: %(default)r)")
parser.add_argument("input", help="GPS or datetime string to convert",
nargs="*")
args = parser.parse_args(args)
input_ = " ".join(args.input)
output = tconvert(input_)
if isinstance(output, datetime.datetime):
output = output.replace(tzinfo=tz.tzutc())
if args.local:
output = output.astimezone(tz.tzlocal())
print(output.strftime(args.format))
else:
print(output) | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier false keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier else_clause block expression_statement call identifier argument_list identifier | Parse command-line arguments, tconvert inputs, and print |
def PDBasXMLwithSymwithPolarH(self, id):
print _WARNING
h_s_xml = urllib.urlopen("http://www.cmbi.ru.nl/wiwsd/rest/PDBasXMLwithSymwithPolarH/id/" + id)
self.raw = h_s_xml
p = self.parser
h_s_smcra = p.read(h_s_xml, 'WHATIF_Output')
return h_s_smcra | module function_definition identifier parameters identifier identifier block print_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end return_statement identifier | Adds Hydrogen Atoms to a Structure. |
def _add_boundaries(self, interval):
begin = interval.begin
end = interval.end
if begin in self.boundary_table:
self.boundary_table[begin] += 1
else:
self.boundary_table[begin] = 1
if end in self.boundary_table:
self.boundary_table[end] += 1
else:
self.boundary_table[end] = 1 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement augmented_assignment subscript attribute identifier identifier identifier integer else_clause block expression_statement assignment subscript attribute identifier identifier identifier integer if_statement comparison_operator identifier attribute identifier identifier block expression_statement augmented_assignment subscript attribute identifier identifier identifier integer else_clause block expression_statement assignment subscript attribute identifier identifier identifier integer | Records the boundaries of the interval in the boundary table. |
def ipv4_range_type(string):
import re
ip_format = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
if not re.match("^{}$".format(ip_format), string):
if not re.match("^{ip_format}-{ip_format}$".format(ip_format=ip_format), string):
raise ValueError
return string | module function_definition identifier parameters identifier block import_statement dotted_name identifier expression_statement assignment identifier string string_start string_content string_end if_statement not_operator call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier block if_statement not_operator call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier identifier block raise_statement identifier return_statement identifier | Validates an IPv4 address or address range. |
def add(self, indices, values):
for i, v in zip(indices, values):
self.buffer[i] = numpy.append(self.buffer[i], v)
self.buffer_expire[i] = numpy.append(self.buffer_expire[i], self.time)
self.advance_time() | module function_definition identifier parameters identifier identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list subscript attribute identifier identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list subscript attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list | Add triggers in 'values' to the buffers indicated by the indices |
def open_report_template_path(self):
directory_name = QFileDialog.getExistingDirectory(
self,
self.tr('Templates directory'),
self.leReportTemplatePath.text(),
QFileDialog.ShowDirsOnly)
if directory_name:
self.leReportTemplatePath.setText(directory_name) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Open File dialog to choose the report template path. |
def validate(self, *args, **kwds):
if self.behavior:
return self.behavior.validate(self, *args, **kwds)
return True | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement attribute identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement true | Call the behavior's validate method, or return True. |
def _categorize(self, category):
self.torrents = [result for result in self.torrents
if result.category == category] | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator attribute identifier identifier identifier | Remove torrents with unwanted category from self.torrents |
def receive_reply(self, msg, content):
reply_head = content.head()
if reply_head == 'error':
comment = content.gets('comment')
logger.error('Got error reply: "%s"' % comment)
else:
extractions = content.gets('ekb')
self.extractions.append(extractions)
self.reply_counter -= 1
if self.reply_counter == 0:
self.exit(0) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier integer if_statement comparison_operator attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list integer | Handle replies with reading results. |
def _validate_node_name(self, var_value):
var_values = var_value if isinstance(var_value, list) else [var_value]
for item in var_values:
if (not isinstance(item, str)) or (
isinstance(item, str)
and (
(" " in item)
or any(
[
element.strip() == ""
for element in item.strip().split(self._node_separator)
]
)
)
):
return True
return False | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier conditional_expression identifier call identifier argument_list identifier identifier list identifier for_statement identifier identifier block if_statement boolean_operator parenthesized_expression not_operator call identifier argument_list identifier identifier parenthesized_expression boolean_operator call identifier argument_list identifier identifier parenthesized_expression boolean_operator parenthesized_expression comparison_operator string string_start string_content string_end identifier call identifier argument_list list_comprehension comparison_operator call attribute identifier identifier argument_list string string_start string_end for_in_clause identifier call attribute call attribute identifier identifier argument_list identifier argument_list attribute identifier identifier block return_statement true return_statement false | Validate NodeName pseudo-type. |
def _generate_routes(self, namespace):
self.cur_namespace = namespace
if self.args.auth_type is not None:
self.supported_auth_types = [auth_type.strip().lower() for auth_type in self.args.auth_type.split(',')]
check_route_name_conflict(namespace)
for route in namespace.routes:
if self.supported_auth_types is None:
self._generate_route_helper(namespace, route)
if route.attrs.get('style') == 'download':
self._generate_route_helper(namespace, route, True)
else:
route_auth_attr = None
if route.attrs is not None:
route_auth_attr = route.attrs.get('auth')
if route_auth_attr is None:
continue
route_auth_modes = [mode.strip().lower() for mode in route_auth_attr.split(',')]
for base_auth_type in self.supported_auth_types:
if base_auth_type in route_auth_modes:
self._generate_route_helper(namespace, route)
if route.attrs.get('style') == 'download':
self._generate_route_helper(namespace, route, True)
break | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier none block expression_statement assignment attribute identifier identifier list_comprehension call attribute call attribute identifier identifier argument_list identifier argument_list for_in_clause identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier true else_clause block expression_statement assignment identifier none if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block continue_statement expression_statement assignment identifier list_comprehension call attribute call attribute identifier identifier argument_list identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier true break_statement | Generates Python methods that correspond to routes in the namespace. |
def getStat(cls, obj, name):
objClass = type(obj)
for theClass in objClass.__mro__:
if theClass == object:
break
for value in theClass.__dict__.values():
if isinstance(value, Stat) and value.getName() == name:
return value | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier identifier block break_statement for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator call attribute identifier identifier argument_list identifier block return_statement identifier | Gets the stat for the given object with the given name, or None if no such stat exists. |
def delete(self, row):
i = self._get_key_index(row)
del self.keys[i] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier delete_statement subscript attribute identifier identifier identifier | Delete a track value |
def guess_number_format(self, rb=1, align=1, **fmt_args):
fct = fmt.guess_formatter(self.actual_values, **fmt_args)
return self.apply_number_format(fct, rb=rb, align=align) | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier dictionary_splat identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier | Determine the most appropriate formatter by inspected all the region values |
def validate(self, data):
if 'verb' in data and data['verb'] != self.__class__.__name__:
raise ValidationError(
'This is not a valid OAI-PMH verb:{0}'.format(data['verb']),
field_names=['verb'],
)
if 'from_' in data and 'until' in data and \
data['from_'] > data['until']:
raise ValidationError('Date "from" must be before "until".')
extra = set(request.values.keys()) - set([
f.load_from or f.name for f in self.fields.values()
])
if extra:
raise ValidationError('You have passed too many arguments.') | module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier 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 keyword_argument identifier list string string_start string_content string_end if_statement boolean_operator boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier line_continuation comparison_operator subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator call identifier argument_list call attribute attribute identifier identifier identifier argument_list call identifier argument_list list_comprehension boolean_operator attribute identifier identifier attribute identifier identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list if_statement identifier block raise_statement call identifier argument_list string string_start string_content string_end | Check range between dates under keys ``from_`` and ``until``. |
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:
N = rank(tensor0)
axes = list(range(N))
return tf.tensordot(tf.math.conj(tensor0), tensor1, axes=(axes, axes)) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier return_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier tuple identifier identifier | Return the inner product between two states |
def scc(graph):
order = []
vis = {vertex: False for vertex in graph}
graph_transposed = {vertex: [] for vertex in graph}
for (v, neighbours) in graph.iteritems():
for u in neighbours:
add_edge(graph_transposed, u, v)
for v in graph:
if not vis[v]:
dfs_transposed(v, graph_transposed, order, vis)
vis = {vertex: False for vertex in graph}
vertex_scc = {}
current_comp = 0
for v in reversed(order):
if not vis[v]:
dfs(v, current_comp, vertex_scc, graph, vis)
current_comp += 1
return vertex_scc | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier dictionary_comprehension pair identifier false for_in_clause identifier identifier expression_statement assignment identifier dictionary_comprehension pair identifier list for_in_clause identifier identifier for_statement tuple_pattern identifier identifier call attribute identifier identifier argument_list block for_statement identifier identifier block expression_statement call identifier argument_list identifier identifier identifier for_statement identifier identifier block if_statement not_operator subscript identifier identifier block expression_statement call identifier argument_list identifier identifier identifier identifier expression_statement assignment identifier dictionary_comprehension pair identifier false for_in_clause identifier identifier expression_statement assignment identifier dictionary expression_statement assignment identifier integer for_statement identifier call identifier argument_list identifier block if_statement not_operator subscript identifier identifier block expression_statement call identifier argument_list identifier identifier identifier identifier identifier expression_statement augmented_assignment identifier integer return_statement identifier | Computes the strongly connected components of a graph |
def errors_as_dict(self):
errors = []
for e in self.errors:
errors.append({
'file': e.term.file_name,
'row': e.term.row if e.term else '<unknown>',
'col': e.term.col if e.term else '<unknown>',
'term': e.term.join if e.term else '<unknown>',
'error': str(e)
})
return errors | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end conditional_expression attribute attribute identifier identifier identifier attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end conditional_expression attribute attribute identifier identifier identifier attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end conditional_expression attribute attribute identifier identifier identifier attribute identifier identifier string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list identifier return_statement identifier | Return parse errors as a dict |
def _on_split_requested(self):
orientation = self.sender().text()
widget = self.widget(self.tab_under_menu())
if 'horizontally' in orientation:
self.split_requested.emit(
widget, QtCore.Qt.Horizontal)
else:
self.split_requested.emit(
widget, QtCore.Qt.Vertical) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute attribute identifier identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute attribute identifier identifier identifier | Emits the split requested signal with the desired orientation. |
def charm_dir():
d = os.environ.get('JUJU_CHARM_DIR')
if d is not None:
return d
return os.environ.get('CHARM_DIR') | module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block return_statement identifier return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end | Return the root directory of the current charm |
def from_dict(cls, database, key, data, clear=False):
hsh = cls(database, key)
if clear:
hsh.clear()
hsh.update(data)
return hsh | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Create and populate a Hash object from a data dictionary. |
def compute_default(kwargs):
ranked_default = kwargs.get('default')
typ = kwargs.get('type', str)
default = ranked_default.value if ranked_default else None
if default is None:
return 'None'
if typ == list:
default_str = '[{}]'.format(','.join(["'{}'".format(s) for s in default]))
elif typ == dict:
if default:
default_str = '{{ {} }}'.format(
','.join(["'{}':'{}'".format(k, v) for k, v in default.items()]))
else:
default_str = '{}'
elif typ == str:
default_str = "'{}'".format(default).replace('\n', ' ')
else:
default_str = str(default)
return default_str | module function_definition identifier parameters identifier block 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 string string_start string_content string_end identifier expression_statement assignment identifier conditional_expression attribute identifier identifier identifier none if_statement comparison_operator identifier none block return_statement string string_start string_content string_end if_statement comparison_operator identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argument_list list_comprehension call attribute string string_start string_content string_end identifier argument_list identifier for_in_clause identifier identifier elif_clause comparison_operator identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argument_list list_comprehension call attribute string string_start string_content string_end identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator identifier identifier block expression_statement assignment identifier call attribute call attribute string string_start string_content string_end identifier argument_list identifier identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | Compute the default value to display in help for an option registered with these kwargs. |
def parse_firefox (url_data):
filename = url_data.get_os_filename()
for url, name in firefox.parse_bookmark_file(filename):
url_data.add_url(url, name=name) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | Parse a Firefox3 bookmark file. |
def python_value(self, dtype, dvalue):
try:
return CONVERTERS[dtype](dvalue)
except KeyError:
if dtype == clips.common.CLIPSType.MULTIFIELD:
return self.multifield_to_list()
if dtype == clips.common.CLIPSType.FACT_ADDRESS:
return clips.facts.new_fact(self._env, lib.to_pointer(dvalue))
if dtype == clips.common.CLIPSType.INSTANCE_ADDRESS:
return clips.classes.Instance(self._env, lib.to_pointer(dvalue))
return None | module function_definition identifier parameters identifier identifier identifier block try_statement block return_statement call subscript identifier identifier argument_list identifier except_clause identifier block if_statement comparison_operator identifier attribute attribute attribute identifier identifier identifier identifier block return_statement call attribute identifier identifier argument_list if_statement comparison_operator identifier attribute attribute attribute identifier identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier attribute attribute attribute identifier identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list identifier return_statement none | Convert a CLIPS type into Python. |
def init_registered(self, request):
created_items = models.DefaultPriceListItem.init_from_registered_resources()
if created_items:
message = ungettext(
_('Price item was created: %s.') % created_items[0].name,
_('Price items were created: %s.') % ', '.join(item.name for item in created_items),
len(created_items)
)
self.message_user(request, message)
else:
self.message_user(request, _('Price items for all registered resources have been updated.'))
return redirect(reverse('admin:cost_tracking_defaultpricelistitem_changelist')) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call identifier argument_list binary_operator call identifier argument_list string string_start string_content string_end attribute subscript identifier integer identifier binary_operator call identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier generator_expression attribute identifier identifier for_in_clause identifier identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list string string_start string_content string_end return_statement call identifier argument_list call identifier argument_list string string_start string_content string_end | Create default price list items for each registered resource. |
def save_example_fit(fit):
json_directory = os.path.join('examples', 'json')
plot_directory = os.path.join('examples', 'plots')
if not os.path.isdir(json_directory): os.makedirs(json_directory)
if not os.path.isdir(plot_directory): os.makedirs(plot_directory)
fit.to_json(os.path.join(json_directory, fit.name + '.json'), meta=fit.metadata)
plot = Plot(fit)
plot.save(os.path.join(plot_directory, fit.name + '.svg'))
plot.close() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier binary_operator attribute identifier identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list | Save fit result to a json file and a plot to an svg file. |
def format_str(self):
if self.static:
return self.route.replace('%','%%')
out, i = '', 0
for token, value in self.tokens():
if token == 'TXT': out += value.replace('%','%%')
elif token == 'ANON': out += '%%(anon%d)s' % i; i+=1
elif token == 'VAR': out += '%%(%s)s' % value[1]
return out | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment pattern_list identifier identifier expression_list string string_start string_end integer for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement augmented_assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end identifier expression_statement augmented_assignment identifier integer elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end subscript identifier integer return_statement identifier | Return a format string with named fields. |
def watch_for_events():
fd = inotify.init()
try:
wd = inotify.add_watch(fd, '/tmp', inotify.IN_CLOSE_WRITE)
while True:
for event in inotify.get_events(fd):
print("event:", event.name, event.get_mask_description())
finally:
os.close(fd) | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end attribute identifier identifier while_statement true block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list finally_clause block expression_statement call attribute identifier identifier argument_list identifier | Wait for events and print them to stdout. |
def basename(path):
base_path = path.strip(SEP)
sep_ind = base_path.rfind(SEP)
if sep_ind < 0:
return path
return base_path[sep_ind + 1:] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier integer block return_statement identifier return_statement subscript identifier slice binary_operator identifier integer | Rightmost part of path after separator. |
def render(self, template_name, variables=None):
if variables is None:
variables = {}
template = self._engine.get_template(template_name)
return template.render(**variables) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list dictionary_splat identifier | Render a template with the passed variables. |
def update_backend(self, service_id, version_number, name_key, **kwargs):
body = self._formdata(kwargs, FastlyBackend.FIELDS)
content = self._fetch("/service/%s/version/%d/backend/%s" % (service_id, version_number, name_key), method="PUT", body=body)
return FastlyBackend(self, content) | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list 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 identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier | Update the backend for a particular service and version. |
def Reverse(self, y):
return self._Bisect(y, self.ys, self.xs) | module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier | Looks up y and returns the corresponding value of x. |
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
_ = stderr, time_taken, args, knowledge_base
self.CheckReturn(cmd, return_val)
result = rdf_protodict.AttributedDict()
for entry in self._field_parser.ParseEntries(stdout):
line_str = " ".join(entry)
mount_rslt = self.mount_re.match(line_str)
if mount_rslt:
device, mount_point, fs_type, option_str = mount_rslt.groups()
result = rdf_client_fs.Filesystem()
result.device = device
result.mount_point = mount_point
result.type = fs_type
options = KeyValueParser(term=",").ParseToOrderedDict(option_str)
for k, v in iteritems(options):
options[k] = v or [True]
result.options = rdf_protodict.AttributedDict(**options)
yield result | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier expression_list identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement identifier block expression_statement assignment pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call attribute call identifier argument_list keyword_argument identifier string string_start string_content string_end identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment subscript identifier identifier boolean_operator identifier list true expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement yield identifier | Parse the mount command output. |
def bk_green(cls):
"Make the text background color green."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
wAttributes |= win32.BACKGROUND_GREEN
cls._set_text_attributes(wAttributes) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement augmented_assignment identifier unary_operator attribute identifier identifier expression_statement augmented_assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Make the text background color green. |
def fmt_subst(regex, subst):
return lambda text: re.sub(regex, subst, text) if text else text | module function_definition identifier parameters identifier identifier block return_statement lambda lambda_parameters identifier conditional_expression call attribute identifier identifier argument_list identifier identifier identifier identifier identifier | Replace regex with string. |
def next_frame_ae_tiny():
hparams = next_frame_tiny()
hparams.bottom["inputs"] = modalities.video_bitwise_bottom
hparams.top["inputs"] = modalities.video_top
hparams.batch_size = 8
hparams.dropout = 0.4
return hparams | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier float return_statement identifier | Conv autoencoder, tiny set for testing. |
def make_c_args(arg_pairs):
logging.debug(arg_pairs)
c_args = [
'{} {}'.format(arg_type, arg_name) if arg_name else arg_type
for dummy_number, arg_type, arg_name in sorted(arg_pairs)
]
return ', '.join(c_args) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension conditional_expression call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier identifier for_in_clause pattern_list identifier identifier identifier call identifier argument_list identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier | Build a C argument list from return type and arguments pairs. |
def write(self, msg, level=logging.INFO):
if msg is not None and len(msg.strip()) > 0:
self.logger.log(level, msg) | module function_definition identifier parameters identifier identifier default_parameter identifier attribute identifier identifier block if_statement boolean_operator comparison_operator identifier none comparison_operator call identifier argument_list call attribute identifier identifier argument_list integer block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | method implements stream write interface, allowing to redirect stdout to logger |
def _set_expressions(self, expressions):
self.expressions = {}
for key, item in expressions.items():
self.expressions[key] = {'function': item} | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript attribute identifier identifier identifier dictionary pair string string_start string_content string_end identifier | Extract expressions and variables from the user provided expressions. |
def cmd_as_file(cmd, *args, **kwargs):
kwargs['stdout'] = subprocess.PIPE
stdin = kwargs.pop('stdin', None)
if isinstance(stdin, basestring):
with tempfile.TemporaryFile() as stdin_file:
stdin_file.write(stdin)
stdin_file.seek(0)
kwargs['stdin'] = stdin_file
p = subprocess.Popen(cmd, *args, **kwargs)
else:
p = subprocess.Popen(cmd, *args, **kwargs)
try:
yield p.stdout
finally:
p.stdout.close()
if p.wait():
raise subprocess.CalledProcessError(p.returncode, cmd) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement call identifier argument_list identifier identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list integer expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier try_statement block expression_statement yield attribute identifier identifier finally_clause block expression_statement call attribute attribute identifier identifier identifier argument_list if_statement call attribute identifier identifier argument_list block raise_statement call attribute identifier identifier argument_list attribute identifier identifier identifier | Launch `cmd` and treat its stdout as a file object |
def _add_flags(flags, new_flags):
flags = _get_flags(flags)
new_flags = _get_flags(new_flags)
return flags | new_flags | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier return_statement binary_operator identifier identifier | Combine ``flags`` and ``new_flags`` |
def _decode_meta(self, meta, **extra):
_meta = json.loads(meta) if meta else {}
_meta.update(extra)
return _meta | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list identifier identifier dictionary expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Decode and load underlying meta structure to dict and apply optional extra values. |
def _get_tags(c):
tags_ = []
for tagstr in c.run("git tag", hide=True).stdout.strip().split("\n"):
try:
tags_.append(Version(tagstr))
except ValueError:
pass
return sorted(tags_) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call attribute call attribute attribute call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true identifier identifier argument_list identifier argument_list string string_start string_content escape_sequence string_end block try_statement block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier except_clause identifier block pass_statement return_statement call identifier argument_list identifier | Return sorted list of release-style tags as semver objects. |
def add_attr2fields(self, attr_name, attr_val, fields=[], exclude=[], include_all_if_empty=True):
for f in self.filter_fields(fields, exclude, include_all_if_empty):
f = self.fields[f.name]
org_val = f.widget.attrs.get(attr_name, '')
f.widget.attrs[attr_name] = '%s %s' % (org_val, attr_val) if org_val else attr_val | module function_definition identifier parameters identifier identifier identifier default_parameter identifier list default_parameter identifier list default_parameter identifier true block for_statement identifier call attribute identifier identifier argument_list identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_end expression_statement assignment subscript attribute attribute identifier identifier identifier identifier conditional_expression binary_operator string string_start string_content string_end tuple identifier identifier identifier identifier | add attr to fields |
def links(self):
links = super(OffsetLimitPaginatedList, self).links
if self._page.offset + self._page.limit < self.count:
links["next"] = Link.for_(
self._operation,
self._ns,
qs=self._page.next_page.to_items(),
**self._context
)
if self.offset > 0:
links["prev"] = Link.for_(
self._operation,
self._ns,
qs=self._page.prev_page.to_items(),
**self._context
)
return links | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute call identifier argument_list identifier identifier identifier if_statement comparison_operator binary_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier keyword_argument identifier call attribute attribute attribute identifier identifier identifier identifier argument_list dictionary_splat attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier keyword_argument identifier call attribute attribute attribute identifier identifier identifier identifier argument_list dictionary_splat attribute identifier identifier return_statement identifier | Include previous and next links. |
def render(template, context=None, **kwargs):
renderer = Renderer()
return renderer.render(template, context, **kwargs) | module function_definition identifier parameters identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list return_statement call attribute identifier identifier argument_list identifier identifier dictionary_splat identifier | Return the given template string rendered using the given context. |
def _f(self, x, user_data=None):
p_gen = x[self._Pg.i1:self._Pg.iN + 1]
q_gen = x[self._Qg.i1:self._Qg.iN + 1]
xx = r_[p_gen, q_gen] * self._base_mva
if len(self._ipol) > 0:
f = sum([g.total_cost(xx[i]) for i,g in enumerate(self._gn)])
else:
f = 0
if self._ny:
y = self.om.get_var("y")
self._ccost = csr_matrix((ones(self._ny),
(range(y.i1, y.iN + 1), zeros(self._ny))),
shape=(self._nxyz, 1)).T
f = f + self._ccost * x
else:
self._ccost = zeros((1, self._nxyz))
return f | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier subscript identifier slice attribute attribute identifier identifier identifier binary_operator attribute attribute identifier identifier identifier integer expression_statement assignment identifier subscript identifier slice attribute attribute identifier identifier identifier binary_operator attribute attribute identifier identifier identifier integer expression_statement assignment identifier binary_operator subscript identifier identifier identifier attribute identifier identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier call identifier argument_list list_comprehension call attribute identifier identifier argument_list subscript identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier integer if_statement attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier attribute call identifier argument_list tuple call identifier argument_list attribute identifier identifier tuple call identifier argument_list attribute identifier identifier binary_operator attribute identifier identifier integer call identifier argument_list attribute identifier identifier keyword_argument identifier tuple attribute identifier identifier integer identifier expression_statement assignment identifier binary_operator identifier binary_operator attribute identifier identifier identifier else_clause block expression_statement assignment attribute identifier identifier call identifier argument_list tuple integer attribute identifier identifier return_statement identifier | Evaluates the objective function. |
async def get_entity(self):
if not self.entity and await self.get_input_entity():
try:
self._entity =\
await self._client.get_entity(self._input_entity)
except ValueError:
pass
return self._entity | module function_definition identifier parameters identifier block if_statement boolean_operator not_operator attribute identifier identifier await call attribute identifier identifier argument_list block try_statement block expression_statement assignment attribute identifier identifier line_continuation await call attribute attribute identifier identifier identifier argument_list attribute identifier identifier except_clause identifier block pass_statement return_statement attribute identifier identifier | Returns `entity` but will make an API call if necessary. |
def start(self, *args, **kwargs):
if args:
LOG.debug("args: %s" % str(args))
if kwargs:
LOG.debug("kwargs: %s" % str(kwargs))
try:
self._server.start()
self._server.proxyInit()
return True
except Exception as err:
LOG.critical("Failed to start server")
LOG.debug(str(err))
self._server.stop()
return False | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list return_statement true except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list return_statement false | Start the server thread if it wasn't created with autostart = True. |
def prt_paths(paths, prt=sys.stdout):
pat = "PATHES: {GO} L{L:02} D{D:02}\n"
for path in paths:
for go_obj in path:
prt.write(pat.format(GO=go_obj.id, L=go_obj.level, D=go_obj.depth))
prt.write("\n") | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block expression_statement assignment identifier string string_start string_content escape_sequence string_end for_statement identifier identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end | Print list of paths. |
def count(cls, iterable):
iterable = iter(iterable)
count = 0
while True:
try:
next(iterable)
except StopIteration:
break
count += 1
return count | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier integer while_statement true block try_statement block expression_statement call identifier argument_list identifier except_clause identifier block break_statement expression_statement augmented_assignment identifier integer return_statement identifier | Returns the number of items in an iterable. |
def _extract_shifted_mean_gauss(image, mask = slice(None), offset = None, sigma = 1, voxelspacing = None):
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
if offset is None:
offset = [0] * image.ndim
sigma = _create_structure_array(sigma, voxelspacing)
smoothed = gaussian_filter(image, sigma)
shifted = numpy.zeros_like(smoothed)
in_slicer = []
out_slicer = []
for o in offset:
in_slicer.append(slice(o, None))
out_slicer.append(slice(None, -1 * o))
shifted[out_slicer] = smoothed[in_slicer]
return _extract_intensities(shifted, mask) | module function_definition identifier parameters identifier default_parameter identifier call identifier argument_list none default_parameter identifier none default_parameter identifier integer default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator list float attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator list integer attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier none expression_statement call attribute identifier identifier argument_list call identifier argument_list none binary_operator unary_operator integer identifier expression_statement assignment subscript identifier identifier subscript identifier identifier return_statement call identifier argument_list identifier identifier | Internal, single-image version of `shifted_mean_gauss`. |
def can_join_group(self, project):
if project.class_.is_locked or project.group_max < 2:
return False
u2g = self.fetch_group_assoc(project)
if u2g:
return len(list(u2g.group.users)) < project.group_max
return True | module function_definition identifier parameters identifier identifier block if_statement boolean_operator attribute attribute identifier identifier identifier comparison_operator attribute identifier identifier integer block return_statement false expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block return_statement comparison_operator call identifier argument_list call identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier return_statement true | Return whether or not user can join a group on `project`. |
def convert_to_btc_on(self, amount, currency, date_obj):
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
start = date_obj.strftime('%Y-%m-%d')
end = date_obj.strftime('%Y-%m-%d')
url = (
'https://api.coindesk.com/v1/bpi/historical/close.json'
'?start={}&end={}¤cy={}'.format(
start, end, currency
)
)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi', {}).get(start, None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc_on requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given Date") | module function_definition identifier parameters identifier identifier identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier true else_clause block expression_statement assignment identifier attribute identifier identifier 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 string string_start string_content string_end expression_statement assignment identifier parenthesized_expression call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list identifier none if_statement identifier block if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier try_statement block expression_statement assignment identifier binary_operator identifier identifier return_statement identifier except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end raise_statement call identifier argument_list string string_start string_content string_end | Convert X amount to BTC based on given date rate |
def fastp_read_n_plot(self):
data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_n_content_data, 'Base Content Percent')
pconfig = {
'id': 'fastp-seq-content-n-plot',
'title': 'Fastp: Read N Content',
'xlab': 'Read Position',
'ylab': 'R1 Before filtering: Base Content Percent',
'yCeiling': 100,
'yMinRange': 5,
'ymin': 0,
'xDecimals': False,
'yLabelFormat': '{value}%',
'tt_label': '{point.x}: {point.y:.2f}%',
'data_labels': data_labels
}
return linegraph.plot(pdata, pconfig) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end 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 string_end pair string string_start string_content string_end integer pair string string_start string_content string_end integer pair string string_start string_content string_end integer pair string string_start string_content string_end false 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 identifier return_statement call attribute identifier identifier argument_list identifier identifier | Make the read N content plot for Fastp |
def evaluate_emb(emb, labels):
d_mat = get_distance_matrix(emb)
d_mat = d_mat.asnumpy()
labels = labels.asnumpy()
names = []
accs = []
for k in [1, 2, 4, 8, 16]:
names.append('Recall@%d' % k)
correct, cnt = 0.0, 0.0
for i in range(emb.shape[0]):
d_mat[i, i] = 1e10
nns = argpartition(d_mat[i], k)[:k]
if any(labels[i] == labels[nn] for nn in nns):
correct += 1
cnt += 1
accs.append(correct/cnt)
return names, accs | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier list integer integer integer integer integer block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment pattern_list identifier identifier expression_list float float for_statement identifier call identifier argument_list subscript attribute identifier identifier integer block expression_statement assignment subscript identifier identifier identifier float expression_statement assignment identifier subscript call identifier argument_list subscript identifier identifier identifier slice identifier if_statement call identifier generator_expression comparison_operator subscript identifier identifier subscript identifier identifier for_in_clause identifier identifier block expression_statement augmented_assignment identifier integer expression_statement augmented_assignment identifier integer expression_statement call attribute identifier identifier argument_list binary_operator identifier identifier return_statement expression_list identifier identifier | Evaluate embeddings based on Recall@k. |
def format_entry(record, show_level=False, colorize=False):
if show_level:
log_str = u'{}: {}'.format(record.levelname, record.getMessage())
else:
log_str = record.getMessage()
if colorize and record.levelname in LOG_COLORS:
log_str = u'<span color="{}">'.format(LOG_COLORS[record.levelname]) + log_str + u'</span>'
return log_str | module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false block if_statement identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator identifier comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier binary_operator binary_operator call attribute string string_start string_content string_end identifier argument_list subscript identifier attribute identifier identifier identifier string string_start string_content string_end return_statement identifier | Format a log entry according to its level and context |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.