code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def sendCommand(self, **msg):
assert 'type' in msg, 'Message type is required.'
msg['id'] = self.next_message_id
self.next_message_id += 1
if self.next_message_id >= maxint:
self.next_message_id = 1
self.sendMessage(json.dumps(msg))
return msg['id'] | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block assert_statement comparison_operator string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement subscript identifier string string_start string_content string_end | Sends a raw command to the Slack server, generating a message ID automatically. |
def save(self, filename='classifier.dump'):
ofile = open(filename,'w+')
pickle.dump(self.classifier, ofile)
ofile.close() | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list | Pickles the classifier and dumps it into a file |
def export_data(self):
def export_field(value):
try:
return value.export_data()
except AttributeError:
return value
if self.__modified_data__ is not None:
return [export_field(value) for value in self.__modified_data__]
return [export_field(value) for value in self.__original_data__] | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block try_statement block return_statement call attribute identifier identifier argument_list except_clause identifier block return_statement identifier if_statement comparison_operator attribute identifier identifier none block return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier | Retrieves the data in a jsoned form |
def _check_copy_number_changes(svtype, cn, minor_cn, data):
if svtype == "LOH" and minor_cn == 0:
return svtype
elif svtype == "amplification" and cn > dd.get_ploidy(data):
return svtype
else:
return "std" | module function_definition identifier parameters identifier identifier identifier identifier block if_statement boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier integer block return_statement identifier elif_clause boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier call attribute identifier identifier argument_list identifier block return_statement identifier else_clause block return_statement string string_start string_content string_end | Check if copy number changes match the expected svtype. |
def read_resource_list(self, uri):
self.logger.info("Reading resource list %s" % (uri))
try:
resource_list = ResourceList(allow_multifile=self.allow_multifile,
mapper=self.mapper)
resource_list.read(uri=uri)
except Exception as e:
raise ClientError("Can't read source resource list from %s (%s)" %
(uri, str(e)))
self.logger.debug("Finished reading resource list")
return(resource_list) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier try_statement block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement parenthesized_expression identifier | Read resource list from specified URI else raise exception. |
def _starting_consonants_only(self, letters: list) -> list:
for idx, letter in enumerate(letters):
if not self._contains_vowels(letter) and self._contains_consonants(letter):
return [idx]
if self._contains_vowels(letter):
return []
if self._contains_vowels(letter) and self._contains_consonants(letter):
return []
return [] | module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement boolean_operator not_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier block return_statement list identifier if_statement call attribute identifier identifier argument_list identifier block return_statement list if_statement boolean_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier block return_statement list return_statement list | Return a list of starting consonant positions. |
def login():
" View function which handles an authentication request. "
form = LoginForm(request.form)
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and user.check_password(form.password.data):
users.login(user)
flash(_('Welcome %(user)s', user=user.username))
return redirect(url_for('users.profile'))
flash(_('Wrong email or password'), 'error-message')
return redirect(request.referrer or url_for(users._login_manager.login_view)) | module function_definition identifier parameters block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier identifier argument_list if_statement boolean_operator identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list call identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier return_statement call identifier argument_list call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list call identifier argument_list string string_start string_content string_end string string_start string_content string_end return_statement call identifier argument_list boolean_operator attribute identifier identifier call identifier argument_list attribute attribute identifier identifier identifier | View function which handles an authentication request. |
def manage_initial_service_status_brok(self, b):
host_name = b.data['host_name']
service_description = b.data['service_description']
service_id = host_name+"/"+service_description
logger.debug("got initial service status: %s", service_id)
if host_name not in self.hosts_cache:
logger.error("initial service status, host is unknown: %s.", service_id)
return
self.services_cache[service_id] = {
}
if 'customs' in b.data:
self.services_cache[service_id]['_GRAPHITE_POST'] = \
sanitize_name(b.data['customs'].get('_GRAPHITE_POST', None))
logger.debug("initial service status received: %s", service_id) | module function_definition identifier parameters 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 binary_operator identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement expression_statement assignment subscript attribute identifier identifier identifier dictionary if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript subscript attribute identifier identifier identifier string string_start string_content string_end line_continuation call identifier argument_list call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end none expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Prepare the known services cache |
async def viewreaction(self, ctx, *, reactor : str):
data = self.config.get(ctx.message.server.id, {})
keyword = data.get(reactor, {})
if not keyword:
await self.bot.responses.failure(message="Reaction '{}' was not found.".format(reactor))
return
response = data.get(reactor, {}).get("response", "")
reacts = data.get(reactor, {}).get("reaction", [])
for i, r in enumerate(reacts):
if ":" in r:
reacts[i] = "<:" + r + ">"
reacts = " ".join(reacts) if reacts else "-"
response = response if response else "-"
string = "Here's what I say to '{reactor}': {response}\n"\
"I'll react to this message how I react to '{reactor}'.".format(reactor=reactor,response=response)
await self.bot.responses.full(sections=[{"name": "Response", "value": response},
{"name": "Reactions", "value": reacts, "inline": False}]) | module function_definition identifier parameters identifier identifier keyword_separator typed_parameter identifier type identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary if_statement not_operator identifier block expression_statement await call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier dictionary identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier dictionary identifier argument_list string string_start string_content string_end list for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier identifier binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier conditional_expression call attribute string string_start string_content string_end identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier conditional_expression identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute concatenated_string string string_start string_content escape_sequence string_end string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement await call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier list dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end 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 identifier pair string string_start string_content string_end false | Views a specific reaction |
def _get_help_for_estimator(prefix, estimator, defaults=None):
from numpydoc.docscrape import ClassDoc
defaults = defaults or {}
estimator = _extract_estimator_cls(estimator)
yield "<{}> options:".format(estimator.__name__)
doc = ClassDoc(estimator)
yield from _get_help_for_params(
doc['Parameters'],
prefix=prefix,
defaults=defaults,
)
yield '' | module function_definition identifier parameters identifier identifier default_parameter identifier none block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier boolean_operator identifier dictionary expression_statement assignment identifier call identifier argument_list identifier expression_statement yield call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement yield call identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier expression_statement yield string string_start string_end | Yield help lines for the given estimator and prefix. |
def clip_rect(self, x:float, y:float, w:float, h:float) -> None:
pass | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type none block pass_statement | Clip further output to this rect. |
def reset(self):
self._frame_counter = 0
ob_real = self.real_env.reset()
self.sim_env.add_to_initial_stack(ob_real)
for _ in range(3):
ob_real, _, _, _ = self.real_env.step(self.name_to_action_num["NOOP"])
self.sim_env.add_to_initial_stack(ob_real)
ob_sim = self.sim_env.reset()
assert np.all(ob_real == ob_sim)
self._last_step_tuples = self._pack_step_tuples((ob_real, 0, False, {}),
(ob_sim, 0, False, {}))
self.set_zero_cumulative_rewards()
ob, _, _, _ = self._player_step_tuple(self._last_step_tuples)
return ob | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier call identifier argument_list integer block expression_statement assignment pattern_list identifier identifier identifier identifier call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list assert_statement call attribute identifier identifier argument_list comparison_operator identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list tuple identifier integer false dictionary tuple identifier integer false dictionary expression_statement call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Reset simulated and real environments. |
def with_legacy_dict(self, legacy_dict_object):
warnings.warn(DeprecationWarning('Legacy configuration object has been used '
'to load the ConfigResolver.'))
return self.with_config_source(LegacyDictConfigSource(legacy_dict_object)) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement call attribute identifier identifier argument_list call identifier argument_list identifier | Configure a source that consumes the dict that where used on Lexicon 2.x |
def arbiters(self):
return [
{
"_id": self.host2id(member),
"host": member,
"server_id": self._servers.host_to_server_id(member)
}
for member in self.get_members_in_state(7)
] | module function_definition identifier parameters identifier block return_statement list_comprehension dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list integer | return list of arbiters |
def validate(ctx, schema, all_schemata):
database = ctx.obj['db']
if schema is None:
if all_schemata is False:
log('No schema given. Read the help', lvl=warn)
return
else:
schemata = database.objectmodels.keys()
else:
schemata = [schema]
for schema in schemata:
try:
things = database.objectmodels[schema]
with click.progressbar(things.find(), length=things.count(),
label='Validating %15s' % schema) as object_bar:
for obj in object_bar:
obj.validate()
except Exception as e:
log('Exception while validating:',
schema, e, type(e),
'\n\nFix this object and rerun validation!',
emitter='MANAGE', lvl=error)
log('Done') | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator identifier none block if_statement comparison_operator identifier false block expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier return_statement else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement assignment identifier list identifier for_statement identifier identifier block try_statement block expression_statement assignment identifier subscript attribute identifier identifier identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier binary_operator string string_start string_content string_end identifier as_pattern_target identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier identifier call identifier argument_list identifier string string_start string_content escape_sequence escape_sequence string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier expression_statement call identifier argument_list string string_start string_content string_end | Validates all objects or all objects of a given schema. |
def favorites_add(photo_id):
method = 'flickr.favorites.add'
_dopost(method, auth=True, photo_id=photo_id)
return True | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement call identifier argument_list identifier keyword_argument identifier true keyword_argument identifier identifier return_statement true | Add a photo to the user's favorites. |
def store_oath_entry(args, nonce, aead, oath_c):
data = {"key": args.uid,
"aead": aead.data.encode('hex'),
"nonce": nonce.encode('hex'),
"key_handle": args.key_handle,
"oath_C": oath_c,
"oath_T": None,
}
entry = ValOathEntry(data)
db = ValOathDb(args.db_file)
try:
if args.force:
db.delete(entry)
db.add(entry)
except sqlite3.IntegrityError, e:
sys.stderr.write("ERROR: %s\n" % (e))
return False
return True | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end none expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier try_statement block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier except_clause attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end parenthesized_expression identifier return_statement false return_statement true | Store the AEAD in the database. |
def status(self):
response = requests.get(
"https://tccna.honeywell.com/WebAPI/emea/api/v1/"
"location/%s/status?includeTemperatureControlSystems=True" %
self.locationId,
headers=self.client._headers()
)
response.raise_for_status()
data = response.json()
for gw_data in data['gateways']:
gateway = self.gateways[gw_data['gatewayId']]
for sys in gw_data["temperatureControlSystems"]:
system = gateway.control_systems[sys['systemId']]
system.__dict__.update(
{'systemModeStatus': sys['systemModeStatus'],
'activeFaults': sys['activeFaults']})
if 'dhw' in sys:
system.hotwater.__dict__.update(sys['dhw'])
for zone_data in sys["zones"]:
zone = system.zones[zone_data['name']]
zone.__dict__.update(zone_data)
return data | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end attribute identifier identifier keyword_argument identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute identifier identifier subscript identifier string string_start string_content string_end for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list subscript identifier string string_start string_content string_end for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Retrieves the location status. |
def add_restriction(self, subject, predicate, object_):
if type(object_) != rdflib.URIRef:
object_ = self.check_thing(object_)
if type(predicate) != rdflib.URIRef:
predicate = self.check_thing(predicate)
if type(subject) != infixowl.Class:
if type(subject) != rdflib.URIRef:
subject = self.check_thing(subject)
subject = infixowl.Class(subject, graph=self.g)
restriction = infixowl.Restriction(predicate, graph=self.g, someValuesFrom=object_)
subject.subClassOf = [restriction] + [c for c in subject.subClassOf] | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment attribute identifier identifier binary_operator list identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier | Lift normal triples into restrictions using someValuesFrom. |
def tokenize_list(self, text):
return [self.get_record_token(record) for record in self.analyze(text)] | module function_definition identifier parameters identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list identifier | Split a text into separate words. |
def strip_accents(s):
nfkd = unicodedata.normalize('NFKD', unicode(s))
return u''.join(ch for ch in nfkd if not unicodedata.combining(ch)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier return_statement call attribute string string_start string_end identifier generator_expression identifier for_in_clause identifier identifier if_clause not_operator call attribute identifier identifier argument_list identifier | Strip accents to prepare for slugification. |
def check_params(features_spec, groups_spec, num_bins, edge_range_spec, trim_outliers, trim_percentile):
if isinstance(features_spec, str) and isinstance(groups_spec, str):
features, groups = read_features_and_groups(features_spec, groups_spec)
else:
features, groups = features_spec, groups_spec
num_bins, edge_range, features, groups = type_cast_params(num_bins, edge_range_spec, features, groups)
num_values = len(features)
group_ids, num_groups = identify_groups(groups)
num_links = np.int64(num_groups * (num_groups - 1) / 2.0)
check_param_ranges(num_bins, num_groups, num_values, trim_outliers, trim_percentile)
return features, groups, num_bins, edge_range, group_ids, num_groups, num_links | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier else_clause block expression_statement assignment pattern_list identifier identifier expression_list identifier identifier expression_statement assignment pattern_list identifier identifier identifier identifier call identifier argument_list identifier identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator binary_operator identifier parenthesized_expression binary_operator identifier integer float expression_statement call identifier argument_list identifier identifier identifier identifier identifier return_statement expression_list identifier identifier identifier identifier identifier identifier identifier | Necessary check on values, ranges, and types. |
def _initStormLibs(self):
self.addStormLib(('str',), s_stormtypes.LibStr)
self.addStormLib(('time',), s_stormtypes.LibTime) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list tuple string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list tuple string string_start string_content string_end attribute identifier identifier | Registration for built-in Storm Libraries |
def alias_field(model, field):
for part in field.split(LOOKUP_SEP)[:-1]:
model = associate_model(model,part)
return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1] | module function_definition identifier parameters identifier identifier block for_statement identifier subscript call attribute identifier identifier argument_list identifier slice unary_operator integer block expression_statement assignment identifier call identifier argument_list identifier identifier return_statement binary_operator binary_operator attribute identifier identifier string string_start string_content string_end subscript call attribute identifier identifier argument_list identifier unary_operator integer | Return the prefix name of a field |
def save_to_file_object(self, fd, format=None, **kwargs):
format = 'pickle' if format is None else format
save = getattr(self, "save_%s" % format, None)
if save is None:
raise ValueError("Unknown format '%s'." % format)
save(fd, **kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator identifier none identifier expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end identifier none if_statement comparison_operator identifier none block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call identifier argument_list identifier dictionary_splat identifier | Save the object to a given file like object in the given format. |
def _get_range(self, endpoint_name):
url = self.build_url(self._endpoints.get(endpoint_name))
response = self.session.get(url)
if not response:
return None
data = response.json()
return self.range_constructor(parent=self, **{self._cloud_data_key: data}) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement not_operator identifier block return_statement none expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier dictionary_splat dictionary pair attribute identifier identifier identifier | Returns a Range based on the endpoint name |
def build(ctx, builder="html", options=""):
sourcedir = ctx.config.sphinx.sourcedir
destdir = Path(ctx.config.sphinx.destdir or "build")/builder
destdir = destdir.abspath()
with cd(sourcedir):
destdir_relative = Path(".").relpathto(destdir)
command = "sphinx-build {opts} -b {builder} {sourcedir} {destdir}" \
.format(builder=builder, sourcedir=".",
destdir=destdir_relative, opts=options)
ctx.run(command) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_end block expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier binary_operator call identifier argument_list boolean_operator attribute attribute attribute identifier identifier identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list with_statement with_clause with_item call identifier argument_list identifier block expression_statement assignment identifier call attribute call identifier argument_list string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end line_continuation identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Build docs with sphinx-build |
def shuffle_characters(s):
s = list(s)
random.shuffle(s)
s =''.join(s)
return s | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_end identifier argument_list identifier return_statement identifier | Randomly shuffle the characters in a string |
def convert_bam_to_fastq(in_file, work_dir, data, dirs, config):
return alignprep.prep_fastq_inputs([in_file], data) | module function_definition identifier parameters identifier identifier identifier identifier identifier block return_statement call attribute identifier identifier argument_list list identifier identifier | Convert BAM input file into FASTQ files. |
def reactivate(credit_card_id: str) -> None:
logger.info('reactivating-credit-card', credit_card_id=credit_card_id)
with transaction.atomic():
cc = CreditCard.objects.get(pk=credit_card_id)
cc.reactivate()
cc.save() | module function_definition identifier parameters typed_parameter identifier type identifier type none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier with_statement with_clause with_item call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Reactivates a credit card. |
def get(self, key, default=None):
if key in self:
return self.items_dict[self.__dict__[str(type(key))][key]]
else:
return default | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier identifier block return_statement subscript attribute identifier identifier subscript subscript attribute identifier identifier call identifier argument_list call identifier argument_list identifier identifier else_clause block return_statement identifier | Return the value at index specified as key. |
def clean_honeypot(self):
value = self.cleaned_data["honeypot"]
if value:
raise forms.ValidationError(self.fields["honeypot"].label)
return value | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement identifier block raise_statement call attribute identifier identifier argument_list attribute subscript attribute identifier identifier string string_start string_content string_end identifier return_statement identifier | Check that nothing's been entered into the honeypot. |
def with_category(category: str) -> Callable:
def cat_decorator(func):
categorize(func, category)
return func
return cat_decorator | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block function_definition identifier parameters identifier block expression_statement call identifier argument_list identifier identifier return_statement identifier return_statement identifier | A decorator to apply a category to a command function. |
def optgroups(self, name, value, attrs=None):
if not self.is_required and not self.allow_multiple_selected:
self.choices = list(chain([('', '')], self.choices))
return super(Select2Mixin, self).optgroups(name, value, attrs=attrs) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement boolean_operator not_operator attribute identifier identifier not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list call identifier argument_list list tuple string string_start string_end string string_start string_end attribute identifier identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier keyword_argument identifier identifier | Add empty option for clearable selects. |
def _prompt_changer(attr, val):
try:
sys.ps1 = conf.color_theme.prompt(conf.prompt)
except Exception:
pass
try:
apply_ipython_style(get_ipython())
except NameError:
pass | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier except_clause identifier block pass_statement try_statement block expression_statement call identifier argument_list call identifier argument_list except_clause identifier block pass_statement | Change the current prompt theme |
def term_to_binary(term, compressed=False):
data_uncompressed = _term_to_binary(term)
if compressed is False:
return b_chr(_TAG_VERSION) + data_uncompressed
else:
if compressed is True:
compressed = 6
if compressed < 0 or compressed > 9:
raise InputException('compressed in [0..9]')
data_compressed = zlib.compress(data_uncompressed, compressed)
size_uncompressed = len(data_uncompressed)
if size_uncompressed > 4294967295:
raise OutputException('uint32 overflow')
return (
b_chr(_TAG_VERSION) + b_chr(_TAG_COMPRESSED_ZLIB) +
struct.pack(b'>I', size_uncompressed) + data_compressed
) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier false block return_statement binary_operator call identifier argument_list identifier identifier else_clause block if_statement comparison_operator identifier true block expression_statement assignment identifier integer if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end return_statement parenthesized_expression binary_operator binary_operator binary_operator call identifier argument_list identifier call identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier | Encode Python types into Erlang terms in binary data |
def create_room(self, payload):
response, status_code = self.__pod__.Streams.post_v2_room_create(
payload=payload
).result()
self.logger.debug('%s: %s' % (status_code, response))
return status_code, response | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement expression_list identifier identifier | create a stream in a non-inclusive manner |
def recordHostname(self, basedir):
"Record my hostname in twistd.hostname, for user convenience"
log.msg("recording hostname in twistd.hostname")
filename = os.path.join(basedir, "twistd.hostname")
try:
hostname = os.uname()[1]
except AttributeError:
hostname = socket.getfqdn()
try:
with open(filename, "w") as f:
f.write("{0}\n".format(hostname))
except Exception:
log.msg("failed - ignoring") | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end try_statement block expression_statement assignment identifier subscript call attribute identifier identifier argument_list integer except_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Record my hostname in twistd.hostname, for user convenience |
def parse_cdhit_clstr_file(lines):
clusters = []
curr_cluster = []
for l in lines:
if l.startswith('>Cluster'):
if not curr_cluster:
continue
clusters.append(curr_cluster)
curr_cluster = []
else:
curr_cluster.append(clean_cluster_seq_id(l.split()[2]))
if curr_cluster:
clusters.append(curr_cluster)
return clusters | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block if_statement not_operator identifier block continue_statement expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier list else_clause block expression_statement call attribute identifier identifier argument_list call identifier argument_list subscript call attribute identifier identifier argument_list integer if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Returns a list of list of sequence ids representing clusters |
def __find_a_zero(self):
row = -1
col = -1
i = 0
n = self.n
done = False
while not done:
j = 0
while True:
if (self.C[i][j] == 0) and \
(not self.row_covered[i]) and \
(not self.col_covered[j]):
row = i
col = j
done = True
j += 1
if j >= n:
break
i += 1
if i >= n:
done = True
return (row, col) | module function_definition identifier parameters identifier block expression_statement assignment identifier unary_operator integer expression_statement assignment identifier unary_operator integer expression_statement assignment identifier integer expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier false while_statement not_operator identifier block expression_statement assignment identifier integer while_statement true block if_statement boolean_operator boolean_operator parenthesized_expression comparison_operator subscript subscript attribute identifier identifier identifier identifier integer line_continuation parenthesized_expression not_operator subscript attribute identifier identifier identifier line_continuation parenthesized_expression not_operator subscript attribute identifier identifier identifier block expression_statement assignment identifier identifier expression_statement assignment identifier identifier expression_statement assignment identifier true expression_statement augmented_assignment identifier integer if_statement comparison_operator identifier identifier block break_statement expression_statement augmented_assignment identifier integer if_statement comparison_operator identifier identifier block expression_statement assignment identifier true return_statement tuple identifier identifier | Find the first uncovered element with value 0 |
def make_title(self, chan, cycle, stage, evt_type):
cyc_str = None
if cycle is not None:
cyc_str = [str(c[2]) for c in cycle]
cyc_str[0] = 'cycle ' + cyc_str[0]
title = [' + '.join([str(x) for x in y]) for y in [chan, cyc_str,
stage, evt_type] if y is not None]
return ', '.join(title) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier none if_statement comparison_operator identifier none block expression_statement assignment identifier list_comprehension call identifier argument_list subscript identifier integer for_in_clause identifier identifier expression_statement assignment subscript identifier integer binary_operator string string_start string_content string_end subscript identifier integer expression_statement assignment identifier list_comprehension call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier for_in_clause identifier list identifier identifier identifier identifier if_clause comparison_operator identifier none return_statement call attribute string string_start string_content string_end identifier argument_list identifier | Make a title for plots, etc. |
def apply_array_ufunc(func, *args, dask='forbidden'):
if any(isinstance(arg, dask_array_type) for arg in args):
if dask == 'forbidden':
raise ValueError('apply_ufunc encountered a dask array on an '
'argument, but handling for dask arrays has not '
'been enabled. Either set the ``dask`` argument '
'or load your data into memory first with '
'``.load()`` or ``.compute()``')
elif dask == 'parallelized':
raise ValueError("cannot use dask='parallelized' for apply_ufunc "
'unless at least one input is an xarray object')
elif dask == 'allowed':
pass
else:
raise ValueError('unknown setting for dask array handling: {}'
.format(dask))
return func(*args) | module function_definition identifier parameters identifier list_splat_pattern identifier default_parameter identifier string string_start string_content string_end block if_statement call identifier generator_expression call identifier argument_list identifier identifier for_in_clause identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end elif_clause comparison_operator identifier string string_start string_content string_end block raise_statement call identifier argument_list concatenated_string 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 pass_statement else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement call identifier argument_list list_splat identifier | Apply a ndarray level function over ndarray objects. |
def generate_url(self, name: str, **kwargs) -> str:
return self.urlmapper.generate(name, **kwargs) | module function_definition identifier parameters identifier typed_parameter identifier type identifier dictionary_splat_pattern identifier type identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier dictionary_splat identifier | generate url with urlgenerator used by urldispatch |
def drag_drop_cb(self, viewer, urls):
channel = self.fv.get_current_channel()
if channel is None:
return
self.fv.open_uris(urls, chname=channel.name, bulk_add=True)
return True | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier none block return_statement expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true return_statement true | Punt drag-drops to the ginga shell. |
def _GetBindingNamespace(self):
return (list(self.zeep_client.wsdl.bindings.itervalues())[0]
.port_name.namespace) | module function_definition identifier parameters identifier block return_statement parenthesized_expression attribute attribute subscript call identifier argument_list call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list integer identifier identifier | Return a string with the namespace of the service binding in the WSDL. |
def make_anchor_id(self):
result = re.sub(
'[^a-zA-Z0-9_]', '_', self.user + '_' + self.timestamp)
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end binary_operator binary_operator attribute identifier identifier string string_start string_content string_end attribute identifier identifier return_statement identifier | Return string to use as URL anchor for this comment. |
def makeExecutable(fp):
mode = ((os.stat(fp).st_mode) | 0o555) & 0o7777
setup_log.info("Adding executable bit to %s (mode is now %o)", fp, mode)
os.chmod(fp, mode) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator parenthesized_expression attribute call attribute identifier identifier argument_list identifier identifier integer integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Adds the executable bit to the file at filepath `fp` |
def _make_output(value, output_script, version=None):
if 'decred' in riemann.get_current_network_name():
return tx.DecredTxOut(
value=value,
version=version,
output_script=output_script)
return tx.TxOut(value=value, output_script=output_script) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier | byte-like, byte-like -> TxOut |
def addRequest(self, service, *args):
wrapper = RequestWrapper(self, '/%d' % self.request_number,
service, *args)
self.request_number += 1
self.requests.append(wrapper)
if self.logger:
self.logger.debug('Adding request %s%r', wrapper.service, args)
return wrapper | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end attribute identifier identifier identifier list_splat identifier expression_statement augmented_assignment attribute identifier identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier return_statement identifier | Adds a request to be sent to the remoting gateway. |
def doc_parser():
parser = argparse.ArgumentParser(
prog='ambry',
description='Ambry {}. Management interface for ambry, libraries '
'and repositories. '.format(ambry._meta.__version__))
return parser | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier return_statement identifier | Utility function to allow getting the arguments for a single command, for Sphinx documentation |
def doctor(ctx, client):
click.secho('\n'.join(textwrap.wrap(DOCTOR_INFO)) + '\n', bold=True)
from . import _checks
is_ok = True
for attr in _checks.__all__:
is_ok &= getattr(_checks, attr)(client)
if is_ok:
click.secho('Everything seems to be ok.', fg='green')
ctx.exit(0 if is_ok else 1) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator call attribute string string_start string_content escape_sequence string_end identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content escape_sequence string_end keyword_argument identifier true import_from_statement relative_import import_prefix dotted_name identifier expression_statement assignment identifier true for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier call call identifier argument_list identifier identifier argument_list identifier if_statement identifier block 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 expression_statement call attribute identifier identifier argument_list conditional_expression integer identifier integer | Check your system and repository for potential problems. |
def _detect_timezone_windows():
global win32timezone_to_en
tzi = DTZI_c()
kernel32 = ctypes.windll.kernel32
getter = kernel32.GetTimeZoneInformation
getter = getattr(kernel32, "GetDynamicTimeZoneInformation", getter)
_ = getter(ctypes.byref(tzi))
win32tz_key_name = tzi.key_name
if not win32tz_key_name:
if win32timezone is None:
return None
win32tz_name = tzi.standard_name
if not win32timezone_to_en:
win32timezone_to_en = dict(
win32timezone.TimeZoneInfo._get_indexed_time_zone_keys("Std"))
win32tz_key_name = win32timezone_to_en.get(win32tz_name, win32tz_name)
territory = locale.getdefaultlocale()[0].split("_", 1)[1]
olson_name = win32tz_map.win32timezones.get((win32tz_key_name, territory), win32tz_map.win32timezones.get(win32tz_key_name, None))
if not olson_name:
return None
if not isinstance(olson_name, str):
olson_name = olson_name.encode("ascii")
return pytz.timezone(olson_name) | module function_definition identifier parameters block global_statement identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier if_statement not_operator identifier block if_statement comparison_operator identifier none block return_statement none expression_statement assignment identifier attribute identifier identifier if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier subscript call attribute subscript call attribute identifier identifier argument_list integer identifier argument_list string string_start string_content string_end integer integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list tuple identifier identifier call attribute attribute identifier identifier identifier argument_list identifier none if_statement not_operator identifier block return_statement none if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier | Detect timezone on the windows platform. |
def find_next_comma(self, node, sub):
position = (sub.last_line, sub.last_col)
first, last = find_next_comma(self.lcode, position)
if first:
node.op_pos.append(NodeWithPosition(last, first)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier tuple attribute identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list attribute identifier identifier identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier identifier | Find comma after sub andd add NodeWithPosition in node |
def cast_item(cls, key, value):
schema_type = cls.schema.get(key)
if schema_type is None:
if cls.strict:
raise TypeError(f'Invalid key {key!r}')
elif not isinstance(value, schema_type):
try:
return schema_type(value)
except CastError:
raise
except Exception as exc:
raise CastError(value, schema_type) from exc
return value | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block if_statement attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content interpolation identifier type_conversion string_end elif_clause not_operator call identifier argument_list identifier identifier block try_statement block return_statement call identifier argument_list identifier except_clause identifier block raise_statement except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier identifier identifier return_statement identifier | Cast schema item to the appropriate tag type. |
def itermovieshash(self):
cur = self._db.firstkey()
while cur is not None:
yield cur
cur = self._db.nextkey(cur) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list while_statement comparison_operator identifier none block expression_statement yield identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier | Iterate over movies hash stored in the database. |
def process_url(self, page_num, page_size, url):
params = dict()
if page_num is not None:
url = re.sub('page=\d+', '', url)
params['page'] = page_num
if page_size is not None:
url = re.sub('per_page=\d+', '', url)
params['per_page'] = page_size
return params, url | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement expression_list identifier identifier | When slicing, remove the per_page and page parameters and pass to requests in the params dict |
def next_haab(month, jd):
if jd < EPOCH:
raise IndexError("Input day is before Mayan epoch.")
hday, hmonth = to_haab(jd)
if hmonth == month:
days = 1 - hday
else:
count1 = _haab_count(hday, hmonth)
count2 = _haab_count(1, month)
days = (count2 - count1) % 365
return jd + days | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier binary_operator integer identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list integer identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier integer return_statement binary_operator identifier identifier | For a given haab month and a julian day count, find the next start of that month on or after the JDC |
def visit_paragraph(self, node):
find = re.search(r'\[[^\]]+\]\([^\)]+\)', node.rawsource)
if find is not None:
self.document.reporter.warning(
'(rst) Link is formatted in Markdown style.', base_node=node) | 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 attribute identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier | Check syntax of reStructuredText. |
def compile(self, name, folder=None, data=None):
template_name = name.replace(os.sep, "")
if folder is None:
folder = ""
full_name = os.path.join(
folder.strip(os.sep), template_name)
if data is None:
data = {}
try:
self.templates[template_name] = \
self.jinja.get_template(full_name).render(data)
except TemplateNotFound as template_error:
if current_app.config['DEBUG']:
raise template_error | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_end if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary try_statement block expression_statement assignment subscript attribute identifier identifier identifier line_continuation call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement subscript attribute identifier identifier string string_start string_content string_end block raise_statement identifier | renders template_name + self.extension file with data using jinja |
def convert_to_si(self):
self._values, self._header._unit = self._header.data_type.to_si(
self._values, self._header.unit) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list attribute identifier identifier attribute attribute identifier identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier | Convert the Data Collection to SI units. |
def cancel(self):
if self.OBSERVE_UPDATES:
self.detach()
self.ioloop.add_callback(self.cancel_timeouts) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Detach strategy from its sensor and cancel ioloop callbacks. |
def save(self, filename):
with io.open(filename,'w',encoding='utf-8') as f:
f.write(self.xml()) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument 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 | Save metadata to XML file |
def hashing_type(self, cluster='main'):
if not self.config.has_section(cluster):
raise SystemExit("Cluster '%s' not defined in %s"
% (cluster, self.config_file))
hashing_type = 'carbon_ch'
try:
return self.config.get(cluster, 'hashing_type')
except NoOptionError:
return hashing_type | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier expression_statement assignment identifier string string_start string_content string_end try_statement block return_statement call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end except_clause identifier block return_statement identifier | Hashing type of cluster. |
def _isdictclass(obj):
c = getattr(obj, '__class__', None)
return c and c.__name__ in _dict_classes.get(c.__module__, ()) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none return_statement boolean_operator identifier comparison_operator attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier tuple | Return True for known dict objects. |
def _map_trajectory(self):
self.trajectory_map = {}
with open(self.filepath, 'r') as trajectory_file:
with closing(
mmap(
trajectory_file.fileno(), 0,
access=ACCESS_READ)) as mapped_file:
progress = 0
line = 0
frame = -1
frame_start = 0
while progress <= len(mapped_file):
line = line + 1
bline = mapped_file.readline()
if len(bline) == 0:
frame = frame + 1
if progress - frame_start > 10:
self.trajectory_map[frame] = [
frame_start, progress
]
break
sline = bline.decode("utf-8").strip('\n').split()
if len(sline) == 1 and sline[0] == 'END':
frame = frame + 1
self.trajectory_map[frame] = [frame_start, progress]
frame_start = progress
progress = progress + len(bline)
self.no_of_frames = frame | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list integer keyword_argument identifier identifier as_pattern_target identifier block expression_statement assignment identifier integer expression_statement assignment identifier integer expression_statement assignment identifier unary_operator integer expression_statement assignment identifier integer while_statement comparison_operator identifier call identifier argument_list identifier block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier binary_operator identifier integer if_statement comparison_operator binary_operator identifier identifier integer block expression_statement assignment subscript attribute identifier identifier identifier list identifier identifier break_statement expression_statement assignment identifier call attribute 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 identifier argument_list if_statement boolean_operator comparison_operator call identifier argument_list identifier integer comparison_operator subscript identifier integer string string_start string_content string_end block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment subscript attribute identifier identifier identifier list identifier identifier expression_statement assignment identifier identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier | Return filepath as a class attribute |
def item_after(self, item):
next_iter = self._next_iter_for(item)
if next_iter is not None:
return self._object_at_iter(next_iter) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement call attribute identifier identifier argument_list identifier | The item after an item |
def list(self, list_id):
r = requests.get(
"https://kippt.com/api/users/%s/lists/%s" % (self.id, list_id),
headers=self.kippt.header
)
return (r.json()) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier return_statement parenthesized_expression call attribute identifier identifier argument_list | Retrieve the list given for the user. |
def sweep(crypto, private_key, to_address, fee=None, password=None, **modes):
from moneywagon.tx import Transaction
tx = Transaction(crypto, verbose=modes.get('verbose', False))
tx.add_inputs(private_key=private_key, password=password, **modes)
tx.change_address = to_address
tx.fee(fee)
return tx.push() | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end false expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list | Move all funds by private key to another address. |
def _get_tags_by_num(self):
by_revision = operator.attrgetter('revision')
tags = sorted(self.get_tags(), key=by_revision)
revision_tags = itertools.groupby(tags, key=by_revision)
def get_id(rev):
return rev.split(':', 1)[0]
return dict(
(get_id(rev), [tr.tag for tr in tr_list])
for rev, tr_list in revision_tags
) | 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 identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier function_definition identifier parameters identifier block return_statement subscript call attribute identifier identifier argument_list string string_start string_content string_end integer integer return_statement call identifier generator_expression tuple call identifier argument_list identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier for_in_clause pattern_list identifier identifier identifier | Return a dictionary mapping revision number to tags for that number. |
def post_save_update_cache(sender, instance, created, raw, **kwargs):
if raw:
return
name = sender.__name__
if name in cached_model_names:
delay_cache = getattr(instance, '_delay_cache', False)
if not delay_cache:
from .tasks import update_cache_for_instance
update_cache_for_instance(name, instance.pk, instance) | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block if_statement identifier block return_statement expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end false if_statement not_operator identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement call identifier argument_list identifier attribute identifier identifier identifier | Update the cache when an instance is created or modified. |
def gen_and(src1, src2, dst):
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.AND, src1, src2, dst) | module function_definition identifier parameters identifier identifier identifier block assert_statement comparison_operator attribute identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier identifier | Return an AND instruction. |
def _apply_filter(self, filters, candidates):
if filters:
filter_input = candidates
for fetch_vector_filter in filters:
filter_input = fetch_vector_filter.filter_vectors(filter_input)
return filter_input
else:
return candidates | module function_definition identifier parameters identifier identifier identifier block if_statement identifier block expression_statement assignment identifier identifier for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier else_clause block return_statement identifier | Apply vector filters if specified and return filtered list |
def login(config, api_key=""):
if not api_key:
info_out(
"If you don't have an API Key, go to:\n"
"https://bugzilla.mozilla.org/userprefs.cgi?tab=apikey\n"
)
api_key = getpass.getpass("API Key: ")
url = urllib.parse.urljoin(config.bugzilla_url, "/rest/whoami")
assert url.startswith("https://"), url
response = requests.get(url, params={"api_key": api_key})
if response.status_code == 200:
if response.json().get("error"):
error_out("Failed - {}".format(response.json()))
else:
update(
config.configfile,
{
"BUGZILLA": {
"bugzilla_url": config.bugzilla_url,
"api_key": api_key,
}
},
)
success_out("Yay! It worked!")
else:
error_out("Failed - {} ({})".format(response.status_code, response.json())) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end block if_statement not_operator identifier block expression_statement call identifier argument_list concatenated_string string string_start string_content escape_sequence string_end string string_start string_content escape_sequence string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end assert_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier dictionary pair string string_start string_content string_end identifier if_statement comparison_operator attribute identifier identifier integer block if_statement call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list else_clause block expression_statement call identifier argument_list attribute identifier identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier expression_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list | Store your Bugzilla API Key |
def _model_mask(self, wavelengths=None):
if wavelengths is None:
wavelengths = self.wavelengths
wavelengths = np.array(wavelengths)
mask = np.ones_like(wavelengths, dtype=bool)
model_mask = self._configuration.get("masks", {}).get("model", [])
logger.debug("Applying model mask: {0}".format(model_mask))
for start, end in model_mask:
idx = np.clip(wavelengths.searchsorted([start, end]) + [0, 1], 0,
wavelengths.size)
mask[idx[0]:idx[1]] = False
return mask | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list string string_start string_content string_end list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier for_statement pattern_list identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list list identifier identifier list integer integer integer attribute identifier identifier expression_statement assignment subscript identifier slice subscript identifier integer subscript identifier integer false return_statement identifier | Apply pre-defined model masks. |
def package_ensure_apt(*packages):
package = " ".join(packages)
status = run("dpkg-query -W -f='${{Status}} ' {p}; true".format(p=package))
status = status.lower()
if 'no packages found' in status or 'not-installed' in status:
sudo("apt-get --yes install " + package)
return False
else:
return True | module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement false else_clause block return_statement true | Ensure apt packages are installed |
def run_preassembly():
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
stmts_json = body.get('statements')
stmts = stmts_from_json(stmts_json)
scorer = body.get('scorer')
return_toplevel = body.get('return_toplevel')
if scorer == 'wm':
belief_scorer = get_eidos_scorer()
else:
belief_scorer = None
stmts_out = ac.run_preassembly(stmts, belief_scorer=belief_scorer,
return_toplevel=return_toplevel)
return _return_stmts(stmts_out) | module function_definition identifier parameters block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement dictionary expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list 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 if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list else_clause block expression_statement assignment identifier none expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement call identifier argument_list identifier | Run preassembly on a list of INDRA Statements. |
def cast(cls, c):
if isinstance(c, Complete):
return c
elif isinstance(c, Translation):
return Complete(np.identity(3, float), c.t)
elif isinstance(c, Rotation):
return Complete(c.r, np.zeros(3, float)) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list integer identifier attribute identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list integer identifier | Convert the first argument into a Complete object |
def find_cookie(self):
return_cookies = []
origin_domain = self.request_object.dest_addr
for cookie in self.cookiejar:
for cookie_morsals in cookie[0].values():
cover_domain = cookie_morsals['domain']
if cover_domain == '':
if origin_domain == cookie[1]:
return_cookies.append(cookie[0])
else:
bvalue = cover_domain.lower()
hdn = origin_domain.lower()
nend = hdn.find(bvalue)
if nend is not False:
return_cookies.append(cookie[0])
return return_cookies | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier attribute attribute identifier identifier identifier for_statement identifier attribute identifier identifier block for_statement identifier call attribute subscript identifier integer identifier argument_list block expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement comparison_operator identifier string string_start string_end block if_statement comparison_operator identifier subscript identifier integer block expression_statement call attribute identifier identifier argument_list subscript identifier integer else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier false block expression_statement call attribute identifier identifier argument_list subscript identifier integer return_statement identifier | Find a list of all cookies for a given domain |
def _parse_port_ranges(pool_str):
ports = set()
for range_str in pool_str.split(','):
try:
a, b = range_str.split('-', 1)
start, end = int(a), int(b)
except ValueError:
log.error('Ignoring unparsable port range %r.', range_str)
continue
if start < 1 or end > 65535:
log.error('Ignoring out of bounds port range %r.', range_str)
continue
ports.update(set(range(start, end + 1)))
return ports | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block try_statement block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment pattern_list identifier identifier expression_list call identifier argument_list identifier call identifier argument_list identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier continue_statement if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier continue_statement expression_statement call attribute identifier identifier argument_list call identifier argument_list call identifier argument_list identifier binary_operator identifier integer return_statement identifier | Given a 'N-P,X-Y' description of port ranges, return a set of ints. |
def flip(self, reactions):
for reaction in reactions:
if reaction in self._flipped:
self._flipped.remove(reaction)
else:
self._flipped.add(reaction) | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Flip the specified reactions. |
def status(self, *msg):
label = colors.yellow("STATUS")
self._msg(label, *msg) | module function_definition identifier parameters identifier list_splat_pattern identifier 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 identifier list_splat identifier | Prints a status message |
def permission_required(action):
def decorator(f):
@wraps(f)
def inner(community, *args, **kwargs):
permission = current_permission_factory(community, action=action)
if not permission.can():
abort(403)
return f(community, *args, **kwargs)
return inner
return decorator | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier if_statement not_operator call attribute identifier identifier argument_list block expression_statement call identifier argument_list integer return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier return_statement identifier | Decorator to require permission. |
def insertReadGroup(self, readGroup):
statsJson = json.dumps(protocol.toJsonDict(readGroup.getStats()))
experimentJson = json.dumps(
protocol.toJsonDict(readGroup.getExperiment()))
try:
models.Readgroup.create(
id=readGroup.getId(),
readgroupsetid=readGroup.getParentContainer().getId(),
name=readGroup.getLocalId(),
predictedinsertedsize=readGroup.getPredictedInsertSize(),
samplename=readGroup.getSampleName(),
description=readGroup.getDescription(),
stats=statsJson,
experiment=experimentJson,
biosampleid=readGroup.getBiosampleId(),
attributes=json.dumps(readGroup.getAttributes()))
except Exception as e:
raise exceptions.RepoManagerException(e) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block raise_statement call attribute identifier identifier argument_list identifier | Inserts the specified readGroup into the DB. |
def _get_interfaces():
v1_interfaces = INTERFACE[USB_BACKEND].get_all_connected_interfaces()
v2_interfaces = INTERFACE[USB_BACKEND_V2].get_all_connected_interfaces()
devices_in_both = [v1 for v1 in v1_interfaces for v2 in v2_interfaces
if _get_unique_id(v1) == _get_unique_id(v2)]
for dev in devices_in_both:
v1_interfaces.remove(dev)
return v1_interfaces + v2_interfaces | module function_definition identifier parameters block expression_statement assignment identifier call attribute subscript identifier identifier identifier argument_list expression_statement assignment identifier call attribute subscript identifier identifier identifier argument_list expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier for_in_clause identifier identifier if_clause comparison_operator call identifier argument_list identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement binary_operator identifier identifier | Get the connected USB devices |
def create(klass, account, **kwargs):
params = {}
params.update(kwargs)
if 'media_ids' in params and isinstance(params['media_ids'], list):
params['media_ids'] = ','.join(map(str, params['media_ids']))
resource = klass.TWEET_CREATE.format(account_id=account.id)
response = Request(account.client, 'post', resource, params=params).perform()
return response.body['data'] | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator string string_start string_content string_end identifier call identifier argument_list subscript identifier string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute call identifier argument_list attribute identifier identifier string string_start string_content string_end identifier keyword_argument identifier identifier identifier argument_list return_statement subscript attribute identifier identifier string string_start string_content string_end | Creates a "Promoted-Only" Tweet using the specialized Ads API end point. |
def _get_buffer(self, index):
if not 0 <= index < self.count:
raise IndexError()
size = struct.calcsize(self.format)
buf = bytearray(size + 1)
buf[0] = self.first_register + size * index
return buf | module function_definition identifier parameters identifier identifier block if_statement not_operator comparison_operator integer identifier attribute identifier identifier block raise_statement call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list binary_operator identifier integer expression_statement assignment subscript identifier integer binary_operator attribute identifier identifier binary_operator identifier identifier return_statement identifier | Shared bounds checking and buffer creation. |
def insert(self, table, columns, values, execute=True):
cols, vals = get_col_val_str(columns)
statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(wrap(table), cols, vals)
if execute:
self._cursor.execute(statement, values)
self._commit()
self._printer('\tMySQL row successfully inserted into {0}'.format(table))
else:
return statement | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier true block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier else_clause block return_statement identifier | Insert a single row into a table. |
def _check_cats(cats, vtypes, df, prep, callers):
out = []
for cat in cats:
all_vals = []
for vtype in vtypes:
vals, labels, maxval = _get_chart_info(df, vtype, cat, prep, callers)
all_vals.extend(vals)
if sum(all_vals) / float(len(all_vals)) > 2:
out.append(cat)
if len(out) == 0:
return cats
else:
return out | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator binary_operator call identifier argument_list identifier call identifier argument_list call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block return_statement identifier else_clause block return_statement identifier | Only include categories in the final output if they have values. |
def decode_cpu_id(self, cpuid):
ret = ()
for i in cpuid.split(':'):
ret += (eval('0x' + i),)
return ret | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier tuple for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement augmented_assignment identifier tuple call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement identifier | Decode the CPU id into a string |
def synchronise(func):
def inner(request, *args):
lock_id = '%s-%s-built-%s' % (
datetime.date.today(), func.__name__,
",".join([str(a) for a in args]))
if cache.add(lock_id, 'true', LOCK_EXPIRE):
result = func(request, *args)
cache.set(lock_id, result.task_id)
else:
task_id = cache.get(lock_id)
if not task_id:
return None
cache.set(lock_id, "")
result = Task.AsyncResult(task_id)
if result.ready():
result.forget()
return None
return result
return inner | module function_definition identifier parameters identifier block function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple call attribute attribute identifier identifier identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier if_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier block expression_statement assignment identifier call identifier argument_list identifier list_splat identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block return_statement none expression_statement call attribute identifier identifier argument_list identifier string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list return_statement none return_statement identifier return_statement identifier | If task already queued, running, or finished, don't restart. |
def local_users(self):
userdirs = filter(self._is_user_directory, os.listdir(self.userdata_location()))
return map(lambda userdir: user.User(self, int(userdir)), userdirs) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement call identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier call identifier argument_list identifier identifier | Returns an array of user ids for users on the filesystem |
def _weighted_formula(form, weight_func):
for e, mf in form.items():
if e == Atom.H:
continue
yield e, mf, weight_func(e) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier attribute identifier identifier block continue_statement expression_statement yield expression_list identifier identifier call identifier argument_list identifier | Yield weight of each formula element. |
def import_csv(csv_file, **kwargs):
records = get_imported_data(csv_file, **kwargs)
_check_required_columns(csv_file, records.results)
return records | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier dictionary_splat identifier expression_statement call identifier argument_list identifier attribute identifier identifier return_statement identifier | Imports data and checks that all required columns are there. |
def update_nodes_published(self):
if self.pk:
self.node_set.all().update(is_published=self.is_published) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list keyword_argument identifier attribute identifier identifier | publish or unpublish nodes of current layer |
def function(self, new_function):
self._client.change_state(
self._monitor_url,
{'Monitor[Function]': new_function.value}) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier dictionary pair string string_start string_content string_end attribute identifier identifier | Set the MonitorState of this Monitor. |
def dotted(self):
" Returns dotted-decimal reperesentation "
obj = libcrypto.OBJ_nid2obj(self.nid)
buf = create_string_buffer(256)
libcrypto.OBJ_obj2txt(buf, 256, obj, 1)
if pyver == 2:
return buf.value
else:
return buf.value.decode('ascii') | 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 attribute identifier identifier expression_statement assignment identifier call identifier argument_list integer expression_statement call attribute identifier identifier argument_list identifier integer identifier integer if_statement comparison_operator identifier integer block return_statement attribute identifier identifier else_clause block return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end | Returns dotted-decimal reperesentation |
def remove_not_requested_analyses_view(portal):
logger.info("Removing 'Analyses not requested' view ...")
ar_ptype = portal.portal_types.AnalysisRequest
ar_ptype._actions = filter(lambda act: act.id != "analyses_not_requested",
ar_ptype.listActions()) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list lambda lambda_parameters identifier comparison_operator attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list | Remove the view 'Not requested analyses" from inside AR |
def connectivity_matrix(cm):
if cm.size == 0:
return True
if cm.ndim != 2:
raise ValueError("Connectivity matrix must be 2-dimensional.")
if cm.shape[0] != cm.shape[1]:
raise ValueError("Connectivity matrix must be square.")
if not np.all(np.logical_or(cm == 1, cm == 0)):
raise ValueError("Connectivity matrix must contain only binary "
"values.")
return True | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier integer block return_statement true if_statement comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator subscript attribute identifier identifier integer subscript attribute identifier identifier integer block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list comparison_operator identifier integer comparison_operator identifier integer block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement true | Validate the given connectivity matrix. |
def getDctDescription(self) :
"returns a dict describing the object"
return {'type' : RabaFields.RABA_FIELD_TYPE_IS_RABA_OBJECT, 'className' : self._rabaClass.__name__, 'raba_id' : self.raba_id, 'raba_namespace' : self._raba_namespace} | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end return_statement dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier | returns a dict describing the object |
def rsync(local_path, remote_path, exclude=None, extra_opts=None):
if not local_path.endswith('/'):
local_path += '/'
exclude = exclude or []
exclude.extend(['*.egg-info', '*.pyc', '.git', '.gitignore',
'.gitmodules', '/build/', '/dist/'])
with hide('running'):
run("mkdir -p '{}'".format(remote_path))
return rsync_project(
remote_path, local_path, delete=True,
extra_opts='-i --omit-dir-times -FF ' +
(extra_opts if extra_opts else ''),
ssh_opts='-o StrictHostKeyChecking=no',
exclude=exclude) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement assignment identifier boolean_operator identifier list expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end 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 with_statement with_clause with_item call identifier argument_list string string_start string_content string_end block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement call identifier argument_list identifier identifier keyword_argument identifier true keyword_argument identifier binary_operator string string_start string_content string_end parenthesized_expression conditional_expression identifier identifier string string_start string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier | Helper to rsync submodules across |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.