code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def concurrent_slots(slots):
for i, slot in enumerate(slots):
for j, other_slot in enumerate(slots[i + 1:]):
if slots_overlap(slot, other_slot):
yield (i, j + i + 1) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block for_statement pattern_list identifier identifier call identifier argument_list subscript identifier slice binary_operator identifier integer block if_statement call identifier argument_list identifier identifier block expression_statement yield tuple identifier binary_operator binary_operator identifier identifier integer | Yields all concurrent slot indices. |
def format_json(json_object, indent):
indent_str = "\n" + " " * indent
json_str = json.dumps(json_object, indent=2, default=serialize_json_var)
return indent_str.join(json_str.split("\n")) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content escape_sequence string_end binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier integer keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end | Pretty-format json data |
def add_backend(self, backend):
"Add a RapidSMS backend to this tenant"
if backend in self.get_backends():
return
backend_link, created = BackendLink.all_tenants.get_or_create(backend=backend)
self.backendlink_set.add(backend_link) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end if_statement comparison_operator identifier call attribute identifier identifier argument_list block return_statement expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Add a RapidSMS backend to this tenant |
def close(self):
if self._save_filename:
self._cookie_jar.save(
self._save_filename,
ignore_discard=self._keep_session_cookies
) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier | Save the cookie jar if needed. |
def _set_autocommit(connection):
if hasattr(connection.connection, "autocommit"):
if callable(connection.connection.autocommit):
connection.connection.autocommit(True)
else:
connection.connection.autocommit = True
elif hasattr(connection.connection, "set_isolation_level"):
connection.connection.set_isolation_level(0) | module function_definition identifier parameters identifier block if_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end block if_statement call identifier argument_list attribute attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list true else_clause block expression_statement assignment attribute attribute identifier identifier identifier true elif_clause call identifier argument_list attribute identifier identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list integer | Make sure a connection is in autocommit mode. |
def delete_archive_file(self):
logger.debug("Deleting %s", self.archive_tmp_dir)
shutil.rmtree(self.archive_tmp_dir, True) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier true | Delete the directory containing the constructed archive |
def toList(value):
if type(value) == list:
return value
elif type(value) in [np.ndarray, tuple, xrange, array.array]:
return list(value)
elif isinstance(value, Vector):
return list(value.toArray())
else:
raise TypeError("Could not convert %s to list" % value) | module function_definition identifier parameters identifier block if_statement comparison_operator call identifier argument_list identifier identifier block return_statement identifier elif_clause comparison_operator call identifier argument_list identifier list attribute identifier identifier identifier identifier attribute identifier identifier block return_statement call identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Convert a value to a list, if possible. |
def parse(self, value):
if self.required and value is None:
raise ValueError("%s is required!" % self.name)
elif self.ignored and value is not None:
warn("%s is ignored for this class!" % self.name)
elif not self.multi and isinstance(value, (list, tuple)):
if len(value) > 1:
raise ValueError(
"%s does not accept multiple values!" % self.name
)
return value[0]
elif self.multi and value is not None:
if not isinstance(value, (list, tuple)):
return [value]
return value | module function_definition identifier parameters identifier identifier block if_statement boolean_operator attribute identifier identifier comparison_operator identifier none block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier elif_clause boolean_operator attribute identifier identifier comparison_operator identifier none block expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier elif_clause boolean_operator not_operator attribute identifier identifier call identifier argument_list identifier tuple identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier return_statement subscript identifier integer elif_clause boolean_operator attribute identifier identifier comparison_operator identifier none block if_statement not_operator call identifier argument_list identifier tuple identifier identifier block return_statement list identifier return_statement identifier | Enforce rules and return parsed value |
def filenames(self):
if self.topic.has_file:
yield self.topic.file.filename
for reply in self.replies:
if reply.has_file:
yield reply.file.filename | module function_definition identifier parameters identifier block if_statement attribute attribute identifier identifier identifier block expression_statement yield attribute attribute attribute identifier identifier identifier identifier for_statement identifier attribute identifier identifier block if_statement attribute identifier identifier block expression_statement yield attribute attribute identifier identifier identifier | Returns the filenames of all files attached to posts in the thread. |
async def _do(self, ctx, times: int, *, command):
msg = copy.copy(ctx.message)
msg.content = command
for i in range(times):
await self.bot.process_commands(msg) | module function_definition identifier parameters identifier identifier typed_parameter identifier type identifier keyword_separator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier identifier for_statement identifier call identifier argument_list identifier block expression_statement await call attribute attribute identifier identifier identifier argument_list identifier | Repeats a command a specified number of times. |
def _windows_cpudata():
grains = {}
if 'NUMBER_OF_PROCESSORS' in os.environ:
try:
grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
except ValueError:
grains['num_cpus'] = 1
grains['cpu_model'] = salt.utils.win_reg.read_value(
hive="HKEY_LOCAL_MACHINE",
key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
vname="ProcessorNameString").get('vdata')
return grains | module function_definition identifier parameters block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block try_statement block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end except_clause identifier block expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement assignment subscript identifier string string_start string_content string_end call attribute call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence string_end keyword_argument identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end return_statement identifier | Return some CPU information on Windows minions |
def cpp_best_split_full_model(X, Uy, C, S, U, noderange, delta,
save_memory=False):
return CSP.best_split_full_model(X, Uy, C, S, U, noderange, delta) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier default_parameter identifier false block return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier identifier identifier identifier | wrappe calling cpp splitting function |
def to_data_rows(self, brains):
fields = self.get_field_names()
return map(lambda brain: self.get_data_record(brain, fields), brains) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier identifier identifier | Returns a list of dictionaries representing the values of each brain |
def _loadable_get_(name, self):
"Used to lazily-evaluate & memoize an attribute."
func = getattr(self._attr_func_, name)
ret = func()
setattr(self._attr_data_, name, ret)
setattr(
type(self),
name,
property(
functools.partial(self._simple_get_, name)
)
)
delattr(self._attr_func_, name)
return ret | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement call identifier argument_list attribute identifier identifier identifier identifier expression_statement call identifier argument_list call identifier argument_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement call identifier argument_list attribute identifier identifier identifier return_statement identifier | Used to lazily-evaluate & memoize an attribute. |
def _get_req_rem_geo(self, ds_info):
if ds_info['dataset_groups'][0].startswith('GM'):
if self.use_tc is False:
req_geo = 'GMODO'
rem_geo = 'GMTCO'
else:
req_geo = 'GMTCO'
rem_geo = 'GMODO'
elif ds_info['dataset_groups'][0].startswith('GI'):
if self.use_tc is False:
req_geo = 'GIMGO'
rem_geo = 'GITCO'
else:
req_geo = 'GITCO'
rem_geo = 'GIMGO'
else:
raise ValueError('Unknown dataset group %s' % ds_info['dataset_groups'][0])
return req_geo, rem_geo | module function_definition identifier parameters identifier identifier block if_statement call attribute subscript subscript identifier string string_start string_content string_end integer identifier argument_list string string_start string_content string_end block if_statement comparison_operator attribute identifier identifier false block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end elif_clause call attribute subscript subscript identifier string string_start string_content string_end integer identifier argument_list string string_start string_content string_end block if_statement comparison_operator attribute identifier identifier false block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end subscript subscript identifier string string_start string_content string_end integer return_statement expression_list identifier identifier | Find out which geolocation files are needed. |
def _instant_search(self):
_keys = []
for k,v in self.searchables.iteritems():
if self.string in v:
_keys.append(k)
self.candidates.append(_keys) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Determine possible keys after a push or pop |
def python(self, cmd):
python_bin = self.cmd_path('python')
cmd = '{0} {1}'.format(python_bin, cmd)
return self._execute(cmd) | 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 expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list identifier | Execute a python script using the virtual environment python. |
def move_down(self):
self.at(ardrone.at.pcmd, True, 0, 0, -self.speed, 0) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier true integer integer unary_operator attribute identifier identifier integer | Make the drone decent downwards. |
def insertIndividual(self, individual):
try:
models.Individual.create(
id=individual.getId(),
datasetId=individual.getParentContainer().getId(),
name=individual.getLocalId(),
description=individual.getDescription(),
created=individual.getCreated(),
updated=individual.getUpdated(),
species=json.dumps(individual.getSpecies()),
sex=json.dumps(individual.getSex()),
attributes=json.dumps(individual.getAttributes()))
except Exception:
raise exceptions.DuplicateNameException(
individual.getLocalId(),
individual.getParentContainer().getLocalId()) | module function_definition identifier parameters identifier identifier block 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 call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list except_clause identifier block raise_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute call attribute identifier identifier argument_list identifier argument_list | Inserts the specified individual into this repository. |
def log_weights(self):
m = self.kernel.feature_log_prob_[self._match_class_pos()]
u = self.kernel.feature_log_prob_[self._nonmatch_class_pos()]
return self._prob_inverse_transform(m - u) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript attribute attribute identifier identifier identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list binary_operator identifier identifier | Log weights as described in the FS framework. |
def _handle_metadata(self, node, scope, ctxt, stream):
self._dlog("handling node metadata {}".format(node.metadata.keyvals))
keyvals = node.metadata.keyvals
metadata_info = []
if "watch" in node.metadata.keyvals or "update" in keyvals:
metadata_info.append(
self._handle_watch_metadata(node, scope, ctxt, stream)
)
if "packtype" in node.metadata.keyvals or "packer" in keyvals:
metadata_info.append(
self._handle_packed_metadata(node, scope, ctxt, stream)
)
return metadata_info | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier list if_statement boolean_operator comparison_operator string string_start string_content string_end attribute attribute identifier identifier identifier comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier identifier identifier if_statement boolean_operator comparison_operator string string_start string_content string_end attribute attribute identifier identifier identifier comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier identifier identifier return_statement identifier | Handle metadata for the node |
def unique(self, sort=False):
unique_vals = np.unique(self.numpy())
if sort:
unique_vals = np.sort(unique_vals)
return unique_vals | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Return unique set of values in image |
def stop(self):
if self._disconnector:
self._disconnector.stop()
self.client.disconnect() | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list | Stop this gateway agent. |
def zone(self) -> Optional[str]:
if self._device_category == DC_BASEUNIT:
return None
return '{:02x}-{:02x}'.format(self._group_number, self._unit_number) | module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block if_statement comparison_operator attribute identifier identifier identifier block return_statement none return_statement call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier | Zone the device is assigned to. |
def touch(path):
with open(path, 'a') as f:
os.utime(path, None)
f.close() | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier none expression_statement call attribute identifier identifier argument_list | Creates a file located at the given path. |
def endElement(self, name):
content = ''.join(self._contentList)
if name == 'xtvd':
self._progress.endItems()
else:
try:
if self._context == 'stations':
self._endStationsNode(name, content)
elif self._context == 'lineups':
self._endLineupsNode(name, content)
elif self._context == 'schedules':
self._endSchedulesNode(name, content)
elif self._context == 'programs':
self._endProgramsNode(name, content)
elif self._context == 'productionCrew':
self._endProductionCrewNode(name, content)
elif self._context == 'genres':
self._endGenresNode(name, content)
except Exception, e:
self._error = True
self._progress.printMsg(str(e), error=True)
self._context = self._contextStack.pop() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute string string_start string_end identifier argument_list attribute identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list else_clause block try_statement block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier except_clause identifier identifier block expression_statement assignment attribute identifier identifier true expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier keyword_argument identifier true expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list | Callback run at the end of each XML element |
def check_cache(self, e_tag, match):
if e_tag != match:
return False
self.send_response(304)
self.send_header("ETag", e_tag)
self.send_header("Cache-Control",
"max-age={0}".format(self.server.max_age))
self.end_headers()
thread_local.size = 0
return True | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier identifier block return_statement false expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier integer return_statement true | Checks the ETag and sends a cache match response if it matches. |
def passwordReset1to2(old):
new = old.upgradeVersion(old.typeName, 1, 2, installedOn=None)
for iface in new.store.interfacesFor(new):
new.store.powerDown(new, iface)
new.deleteFromStore() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier integer integer keyword_argument identifier none for_statement identifier call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list | Power down and delete the item |
def unbake(self):
for key in self.dct:
self.dct[key].pop('__abs_time__', None)
self.is_baked = False | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list string string_start string_content string_end none expression_statement assignment attribute identifier identifier false | Remove absolute times for all keys. |
def score(self, testing_features, testing_labels):
yhat = self.predict(testing_features)
return self.scoring_function(testing_labels,yhat) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier | estimates accuracy on testing set |
def start(self):
assert not self.is_running(), 'Attempted to start an energy measurement while one was already running.'
self._measurement_process = subprocess.Popen(
[self._executable, '-r'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=10000,
preexec_fn=os.setpgrp,
) | module function_definition identifier parameters identifier block assert_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list list attribute identifier identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier integer keyword_argument identifier attribute identifier identifier | Starts the external measurement program. |
def nodes(self):
getnode = self._nodes.__getitem__
return [getnode(nid) for nid in self._nodeids] | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier | Return the list of nodes. |
def make_channel(name, samples, data=None, verbose=False):
if verbose:
llog = log['make_channel']
llog.info("creating channel {0}".format(name))
chan = Channel('channel_{0}'.format(name))
chan.SetStatErrorConfig(0.05, "Poisson")
if data is not None:
if verbose:
llog.info("setting data")
chan.SetData(data)
for sample in samples:
if verbose:
llog.info("adding sample {0}".format(sample.GetName()))
chan.AddSample(sample)
return chan | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier false block if_statement identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list float string string_start string_content string_end if_statement comparison_operator identifier none block if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Create a Channel from a list of Samples |
def execute(self):
creator = make_creator(self.params.config,
storage_path=self.params.storage)
cluster_name = self.params.cluster
try:
cluster = creator.load_cluster(cluster_name)
except (ClusterNotFound, ConfigurationError) as ex:
log.error("Listing nodes from cluster %s: %s\n" %
(cluster_name, ex))
return
from elasticluster.gc3pie_config import create_gc3pie_config_snippet
if self.params.append:
path = os.path.expanduser(self.params.append)
try:
fd = open(path, 'a')
fd.write(create_gc3pie_config_snippet(cluster))
fd.close()
except IOError as ex:
log.error("Unable to write configuration to file %s: %s",
path, ex)
else:
print(create_gc3pie_config_snippet(cluster)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause as_pattern tuple identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier return_statement import_from_statement dotted_name identifier identifier dotted_name identifier if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier try_statement 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 call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier else_clause block expression_statement call identifier argument_list call identifier argument_list identifier | Load the cluster and build a GC3Pie configuration snippet. |
def login():
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
after_this_request(_commit)
if not request.is_json:
return redirect(get_post_login_redirect(form.next.data))
if request.is_json:
return _render_json(form, include_auth_token=True)
return _security.render_template(config_value('LOGIN_USER_TEMPLATE'),
login_user_form=form,
**_ctx('login')) | module function_definition identifier parameters block expression_statement assignment identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement call attribute identifier identifier argument_list block expression_statement call identifier argument_list attribute identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier expression_statement call identifier argument_list identifier if_statement not_operator attribute identifier identifier block return_statement call identifier argument_list call identifier argument_list attribute attribute identifier identifier identifier if_statement attribute identifier identifier block return_statement call identifier argument_list identifier keyword_argument identifier true return_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier dictionary_splat call identifier argument_list string string_start string_content string_end | View function for login view |
def process_request(self, request):
restricted_request_uri = request.path.startswith(
reverse('admin:index') or "cms-toolbar-login" in request.build_absolute_uri()
)
if restricted_request_uri and request.method == 'POST':
if AllowedIP.objects.count() > 0:
if AllowedIP.objects.filter(ip_address="*").count() == 0:
request_ip = get_ip_address_from_request(request)
if AllowedIP.objects.filter(ip_address=request_ip).count() == 0:
for regex_ip_range in AllowedIP.objects.filter(ip_address__endswith="*"):
if re.match(regex_ip_range.ip_address.replace("*", ".*"), request_ip):
return None
return HttpResponseForbidden("Access to admin is denied.") | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list boolean_operator call identifier argument_list string string_start string_content string_end comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list if_statement boolean_operator identifier comparison_operator attribute identifier identifier string string_start string_content string_end block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list integer block if_statement comparison_operator call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end identifier argument_list integer block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier identifier argument_list integer block for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end block if_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier block return_statement none return_statement call identifier argument_list string string_start string_content string_end | Check if the request is made form an allowed IP |
def unmasked(self, depth=0.01):
return 1 - (np.hstack(self._O2) +
np.hstack(self._O3) / depth) / np.hstack(self._O1) | module function_definition identifier parameters identifier default_parameter identifier float block return_statement binary_operator integer binary_operator parenthesized_expression binary_operator call attribute identifier identifier argument_list attribute identifier identifier binary_operator call attribute identifier identifier argument_list attribute identifier identifier identifier call attribute identifier identifier argument_list attribute identifier identifier | Return the unmasked overfitting metric for a given transit depth. |
def _add_enum_member(enum, name, value, bitmask=DEFMASK):
error = idaapi.add_enum_member(enum, name, value, bitmask)
if error:
raise _enum_member_error(error, enum, name, value, bitmask) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier identifier if_statement identifier block raise_statement call identifier argument_list identifier identifier identifier identifier identifier | Add an enum member. |
def handle_trunks(self, trunks, event_type):
LOG.debug("Trunks event received: %(event_type)s. Trunks: %(trunks)s",
{'event_type': event_type, 'trunks': trunks})
if event_type == events.DELETED:
for trunk in trunks:
self._trunks.pop(trunk.id, None)
else:
for trunk in trunks:
self._trunks[trunk.id] = trunk
self._setup_trunk(trunk) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement comparison_operator identifier attribute identifier identifier block for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier none else_clause block for_statement identifier identifier block expression_statement assignment subscript attribute identifier identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Trunk data model change from the server. |
def transform(function):
def transform_fn(_, result):
if isinstance(result, Nothing):
return result
lgr.debug("Transforming %r with %r", result, function)
try:
return function(result)
except:
exctype, value, tb = sys.exc_info()
try:
new_exc = StyleFunctionError(function, exctype, value)
new_exc.__cause__ = None
six.reraise(StyleFunctionError, new_exc, tb)
finally:
del tb
return transform_fn | module function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier try_statement block return_statement call identifier argument_list identifier except_clause block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement assignment attribute identifier identifier none expression_statement call attribute identifier identifier argument_list identifier identifier identifier finally_clause block delete_statement identifier return_statement identifier | Return a processor for a style's "transform" function. |
def compile(self):
result = TEMPLATE
for rule in self.rules:
if rule[2]:
arrow = '=>'
else:
arrow = '->'
repr_rule = repr(rule[0] + arrow + rule[1])
result += "algo.add_rule({repr_rule})\n".format(repr_rule=repr_rule)
result += "for line in stdin:\n"
result += " print(algo.execute(''.join(line.split())))"
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier identifier for_statement identifier attribute identifier identifier block if_statement subscript identifier integer block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list binary_operator binary_operator subscript identifier integer identifier subscript identifier integer expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list keyword_argument identifier identifier expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier string string_start string_content string_end return_statement identifier | Return python code for create and execute algo. |
def create_dispatcher(self):
before_context = max(self.args.before_context, self.args.context)
after_context = max(self.args.after_context, self.args.context)
if self.args.files_with_match is not None or self.args.count or self.args.only_matching or self.args.quiet:
return UnbufferedDispatcher(self._channels)
elif before_context == 0 and after_context == 0:
return UnbufferedDispatcher(self._channels)
elif self.args.thread:
return ThreadedDispatcher(self._channels, before_context, after_context)
else:
return LineBufferDispatcher(self._channels, before_context, after_context) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier if_statement boolean_operator boolean_operator boolean_operator comparison_operator attribute attribute identifier identifier identifier none attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier block return_statement call identifier argument_list attribute identifier identifier elif_clause boolean_operator comparison_operator identifier integer comparison_operator identifier integer block return_statement call identifier argument_list attribute identifier identifier elif_clause attribute attribute identifier identifier identifier block return_statement call identifier argument_list attribute identifier identifier identifier identifier else_clause block return_statement call identifier argument_list attribute identifier identifier identifier identifier | Return a dispatcher for configured channels. |
def json_encoder_default(obj):
if isinstance(obj, numbers.Integral) and (obj < min_safe_integer or obj > max_safe_integer):
return str(obj)
if isinstance(obj, np.integer):
return str(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return list(obj)
elif isinstance(obj, (set, frozenset)):
return list(obj)
raise TypeError | module function_definition identifier parameters identifier block if_statement boolean_operator call identifier argument_list identifier attribute identifier identifier parenthesized_expression boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier block return_statement call identifier argument_list identifier if_statement call identifier argument_list identifier attribute identifier identifier block return_statement call identifier argument_list identifier elif_clause call identifier argument_list identifier attribute identifier identifier block return_statement call identifier argument_list identifier elif_clause call identifier argument_list identifier attribute identifier identifier block return_statement call identifier argument_list identifier elif_clause call identifier argument_list identifier tuple identifier identifier block return_statement call identifier argument_list identifier raise_statement identifier | JSON encoder function that handles some numpy types. |
def shutdown(self):
'Close all peer connections and stop listening for new ones'
log.info("shutting down")
for peer in self._dispatcher.peers.values():
peer.go_down(reconnect=False)
if self._listener_coro:
backend.schedule_exception(
errors._BailOutOfListener(), self._listener_coro)
if self._udp_listener_coro:
backend.schedule_exception(
errors._BailOutOfListener(), self._udp_listener_coro) | module function_definition identifier parameters 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 for_statement identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list keyword_argument identifier false if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier | Close all peer connections and stop listening for new ones |
def get(self, path, query, **options):
api_options = self._parse_api_options(options, query_string=True)
query_options = self._parse_query_options(options)
parameter_options = self._parse_parameter_options(options)
query = _merge(query_options, api_options, parameter_options, query)
return self.request('get', path, params=query, **options) | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier identifier dictionary_splat identifier | Parses GET request options and dispatches a request. |
def _replay_info(replay_path):
if not replay_path.lower().endswith("sc2replay"):
print("Must be a replay.")
return
run_config = run_configs.get()
with run_config.start(want_rgb=False) as controller:
info = controller.replay_info(run_config.replay_data(replay_path))
print("-" * 60)
print(info) | module function_definition identifier parameters identifier block if_statement not_operator 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 string string_start string_content string_end return_statement expression_statement assignment identifier call attribute identifier identifier argument_list with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list keyword_argument identifier false as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end integer expression_statement call identifier argument_list identifier | Query a replay for information. |
def _check_instrument(self):
instr = INSTRUMENTS.get(self.platform_name, self.instrument.lower())
if instr != self.instrument.lower():
self.instrument = instr
LOG.warning("Inconsistent instrument/satellite input - " +
"instrument set to %s", self.instrument)
self.instrument = self.instrument.lower().replace('/', '') | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end string string_start string_end | Check and try fix instrument name if needed |
def _load_int(self):
values = numpy.fromfile(self.filepath_int)
if self.NDIM > 0:
values = values.reshape(self.seriesshape)
return values | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Load internal data from file and return it. |
def dir(self, path='/', slash=True, bus=False, timeout=0):
if slash:
msg = MSG_DIRALLSLASH
else:
msg = MSG_DIRALL
if bus:
flags = self.flags | FLG_BUS_RET
else:
flags = self.flags & ~FLG_BUS_RET
ret, data = self.sendmess(msg, str2bytez(path), flags, timeout=timeout)
if ret < 0:
raise OwnetError(-ret, self.errmess[-ret], path)
if data:
return bytes2str(data).split(',')
else:
return [] | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier true default_parameter identifier false default_parameter identifier integer block if_statement identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier identifier if_statement identifier block expression_statement assignment identifier binary_operator attribute identifier identifier identifier else_clause block expression_statement assignment identifier binary_operator attribute identifier identifier unary_operator identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier call identifier argument_list identifier identifier keyword_argument identifier identifier if_statement comparison_operator identifier integer block raise_statement call identifier argument_list unary_operator identifier subscript attribute identifier identifier unary_operator identifier identifier if_statement identifier block return_statement call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end else_clause block return_statement list | list entities at path |
def OnGoToCell(self, event):
row, col, tab = event.key
try:
self.grid.actions.cursor = row, col, tab
except ValueError:
msg = _("Cell {key} outside grid shape {shape}").format(
key=event.key, shape=self.grid.code_array.shape)
post_command_event(self.grid.main_window, self.grid.StatusBarMsg,
text=msg)
event.Skip()
return
self.grid.MakeCellVisible(row, col)
event.Skip() | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier identifier attribute identifier identifier try_statement block expression_statement assignment attribute attribute attribute identifier identifier identifier identifier expression_list identifier identifier identifier except_clause identifier block expression_statement assignment identifier call attribute call identifier argument_list string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute attribute attribute identifier identifier identifier identifier expression_statement call identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list return_statement expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list | Shift a given cell into view |
def run(configobj=None):
clean(configobj['input'],
suffix=configobj['suffix'],
stat=configobj['stat'],
maxiter=configobj['maxiter'],
sigrej=configobj['sigrej'],
lower=configobj['lower'],
upper=configobj['upper'],
binwidth=configobj['binwidth'],
mask1=configobj['mask1'],
mask2=configobj['mask2'],
dqbits=configobj['dqbits'],
rpt_clean=configobj['rpt_clean'],
atol=configobj['atol'],
cte_correct=configobj['cte_correct'],
clobber=configobj['clobber'],
verbose=configobj['verbose']) | module function_definition identifier parameters default_parameter identifier none block expression_statement call identifier argument_list subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end | TEAL interface for the `clean` function. |
def on_any_event(self, event):
if os.path.isfile(event.src_path):
self.callback(event.src_path, **self.kwargs) | module function_definition identifier parameters identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier dictionary_splat attribute identifier identifier | File created or modified |
def _urlopen_as_json(self, url, headers=None):
req = Request(url, headers=headers)
return json.loads(urlopen(req).read()) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list call attribute call identifier argument_list identifier identifier argument_list | Shorcut for return contents as json |
def state(self):
state = self._resource.get('state', self.default_state)
if state in State:
return state
else:
return getattr(State, state) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier if_statement comparison_operator identifier identifier block return_statement identifier else_clause block return_statement call identifier argument_list identifier identifier | Get the Document's state |
def from_sbv(cls, file):
parser = SBVParser().read(file)
return cls(file=file, captions=parser.captions) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier | Reads captions from a file in YouTube SBV format. |
def unregister(self, filter_name):
if filter_name in self.filter_list:
self.filter_list.pop(filter_name) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Unregister a filter from the filter list |
def validate_participation(self):
if self.participation not in self._participation_valid_values:
raise ValueError("participation should be one of: {valid}".format(
valid=", ".join(self._participation_valid_values)
)) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier | Ensure participation is of a certain type. |
def importData(directory):
dataTask = OrderedDict()
dataQueue = OrderedDict()
for fichier in sorted(os.listdir(directory)):
try:
with open("{directory}/{fichier}".format(**locals()), 'rb') as f:
fileName, fileType = fichier.rsplit('-', 1)
if fileType == "QUEUE":
dataQueue[fileName] = pickle.load(f)
else:
dataTask[fileName] = pickle.load(f)
except:
pass
return dataTask, dataQueue | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list for_statement identifier call identifier argument_list call attribute identifier identifier argument_list identifier block try_statement block with_statement with_clause with_item as_pattern call identifier argument_list call attribute string string_start string_content string_end identifier argument_list dictionary_splat call identifier argument_list string string_start string_content string_end as_pattern_target identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list identifier except_clause block pass_statement return_statement expression_list identifier identifier | Parse the input files and return two dictionnaries |
def which(software, strip_newline=True):
if software is None:
software = "singularity"
cmd = ['which', software ]
try:
result = run_command(cmd)
if strip_newline is True:
result['message'] = result['message'].strip('\n')
return result
except:
return None | module function_definition identifier parameters identifier default_parameter identifier true block if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier list string string_start string_content string_end identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier true block expression_statement assignment subscript identifier string string_start string_content string_end call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content escape_sequence string_end return_statement identifier except_clause block return_statement none | get_install will return the path to where an executable is installed. |
def chirp_stimul():
from scipy.signal import chirp, hilbert
duration = 1.0
fs = 256
samples = int(fs * duration)
t = np.arange(samples) / fs
signal = chirp(t, 20.0, t[-1], 100.0)
signal *= (1.0 + 0.5 * np.sin(2.0 * np.pi * 3.0 * t))
analytic_signal = hilbert(signal) * 0.5
ref_abs = np.abs(analytic_signal)
ref_instantaneous_phase = np.angle(analytic_signal)
return analytic_signal, ref_abs, ref_instantaneous_phase | module function_definition identifier parameters block import_from_statement dotted_name identifier identifier dotted_name identifier dotted_name identifier expression_statement assignment identifier float expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list binary_operator identifier identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier float subscript identifier unary_operator integer float expression_statement augmented_assignment identifier parenthesized_expression binary_operator float binary_operator float call attribute identifier identifier argument_list binary_operator binary_operator binary_operator float attribute identifier identifier float identifier expression_statement assignment identifier binary_operator call identifier argument_list identifier float expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier identifier | Amplitude modulated chirp signal |
async def jsk_hide(self, ctx: commands.Context):
if self.jsk.hidden:
return await ctx.send("Jishaku is already hidden.")
self.jsk.hidden = True
await ctx.send("Jishaku is now hidden.") | module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier block if_statement attribute attribute identifier identifier identifier block return_statement await call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute attribute identifier identifier identifier true expression_statement await call attribute identifier identifier argument_list string string_start string_content string_end | Hides Jishaku from the help command. |
def error(self, id, errorCode, errorString):
if errorCode == 165:
sys.stderr.write("TWS INFO - %s: %s\n" % (errorCode, errorString))
elif errorCode >= 501 and errorCode < 600:
sys.stderr.write("TWS CLIENT-ERROR - %s: %s\n" % (errorCode, errorString))
elif errorCode >= 100 and errorCode < 1100:
sys.stderr.write("TWS ERROR - %s: %s\n" % (errorCode, errorString))
elif errorCode >= 1100 and errorCode < 2100:
sys.stderr.write("TWS SYSTEM-ERROR - %s: %s\n" % (errorCode, errorString))
elif errorCode in (2104, 2106, 2108):
sys.stderr.write("TWS INFO - %s: %s\n" % (errorCode, errorString))
elif errorCode >= 2100 and errorCode <= 2110:
sys.stderr.write("TWS WARNING - %s: %s\n" % (errorCode, errorString))
else:
sys.stderr.write("TWS ERROR - %s: %s\n" % (errorCode, errorString)) | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier elif_clause boolean_operator comparison_operator identifier integer comparison_operator identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier elif_clause boolean_operator comparison_operator identifier integer comparison_operator identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier elif_clause boolean_operator comparison_operator identifier integer comparison_operator identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier elif_clause comparison_operator identifier tuple integer integer integer block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier elif_clause boolean_operator comparison_operator identifier integer comparison_operator identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple identifier identifier | Error during communication with TWS |
def _set_types(self):
for c in (self.x, self.y):
if not ( isinstance(c, int) or isinstance(c, float) ):
raise(RuntimeError('x, y coords should be int or float'))
if isinstance(self.x, int) and isinstance(self.y, int):
self._dtype = "int"
else:
self.x = float(self.x)
self.y = float(self.y)
self._dtype = "float" | module function_definition identifier parameters identifier block for_statement identifier tuple attribute identifier identifier attribute identifier identifier block if_statement not_operator parenthesized_expression boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block raise_statement parenthesized_expression call identifier argument_list string string_start string_content string_end if_statement boolean_operator call identifier argument_list attribute identifier identifier identifier call identifier argument_list attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier string string_start string_content string_end else_clause block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier string string_start string_content string_end | Make sure that x, y have consistent types and set dtype. |
def _get_jvm_opts(out_file, data):
resources = config_utils.get_resources("purple", data["config"])
jvm_opts = resources.get("jvm_opts", ["-Xms750m", "-Xmx3500m"])
jvm_opts = config_utils.adjust_opts(jvm_opts, {"algorithm": {"memory_adjust":
{"direction": "increase",
"maximum": "30000M",
"magnitude": dd.get_cores(data)}}})
jvm_opts += broad.get_default_jvm_opts(os.path.dirname(out_file))
return jvm_opts | 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 subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Retrieve Java options, adjusting memory for available cores. |
def package_remove(name):
DETAILS = _load_state()
DETAILS['packages'].pop(name)
_save_state(DETAILS)
return DETAILS['packages'] | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list identifier return_statement subscript identifier string string_start string_content string_end | Remove a "package" on the REST server |
def token(self, value):
if value and not isinstance(value, Token):
value = Token(value)
self._token = value | module function_definition identifier parameters identifier identifier block if_statement boolean_operator identifier not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier | Setter to convert any token dict into Token instance |
def readme(fname):
md = open(os.path.join(os.path.dirname(__file__), fname)).read()
output = md
try:
import pypandoc
output = pypandoc.convert(md, 'rst', format='md')
except ImportError:
pass
return output | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier identifier argument_list expression_statement assignment identifier identifier try_statement block import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end except_clause identifier block pass_statement return_statement identifier | Reads a markdown file and returns the contents formatted as rst |
def setup(self):
super(BaseMonitor, self).setup()
self.monitor_thread = LoopFuncThread(self._monitor_func)
self.monitor_thread.start() | module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Make sure the monitor is ready for fuzzing |
def _build_cache_key(self, uri):
key = uri.clone(ext=None, version=None)
if six.PY3:
key = key.encode('utf-8')
return sha1(key).hexdigest() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier none keyword_argument identifier none if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement call attribute call identifier argument_list identifier identifier argument_list | Build sha1 hex cache key to handle key length and whitespace to be compatible with Memcached |
def render_source(self, source, variables=None):
if variables is None:
variables = {}
template = self._engine.from_string(source)
return template.render(**variables) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list dictionary_splat identifier | Render a source with the passed variables. |
def update_feature_type_rates(sender, instance, created, *args, **kwargs):
if created:
for role in ContributorRole.objects.all():
FeatureTypeRate.objects.create(role=role, feature_type=instance, rate=0) | module function_definition identifier parameters identifier identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier integer | Creates a default FeatureTypeRate for each role after the creation of a FeatureTypeRate. |
def refactor_module_to_package(self):
refactor = ModuleToPackage(self.project, self.resource)
return self._get_changes(refactor) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier | Convert the current module into a package. |
def to_localtime(time):
utc_time = time.replace(tzinfo=timezone.utc)
to_zone = timezone.get_default_timezone()
return utc_time.astimezone(to_zone) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier | Converts naive datetime to localtime based on settings |
def dehydrate(self):
result = {}
for attr in self.attrs:
result[attr] = getattr(self, attr)
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier return_statement identifier | Return a dict representing this bucket. |
def create(ctx, scenario_name, driver_name):
args = ctx.obj.get('args')
subcommand = base._get_subcommand(__name__)
command_args = {
'subcommand': subcommand,
'driver_name': driver_name,
}
base.execute_cmdline_scenarios(scenario_name, args, command_args) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier | Use the provisioner to start the instances. |
def write_path(self, path_value):
parent_dir = os.path.dirname(self.path)
try:
os.makedirs(parent_dir)
except OSError:
pass
with open(self.path, "w") as fph:
fph.write(path_value.value) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block pass_statement 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 expression_statement call attribute identifier identifier argument_list attribute identifier identifier | this will overwrite dst path - be careful |
def parse_file(self, filename, encoding=None, debug=False):
stream = codecs.open(filename, "r", encoding)
try:
return self.parse_stream(stream, debug)
finally:
stream.close() | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier try_statement block return_statement call attribute identifier identifier argument_list identifier identifier finally_clause block expression_statement call attribute identifier identifier argument_list | Parse a file and return the syntax tree. |
def _spawn_redis_connection_thread(self):
self.logger.debug("Spawn redis connection thread")
self.redis_connected = False
self._redis_thread = Thread(target=self._setup_redis)
self._redis_thread.setDaemon(True)
self._redis_thread.start() | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement call attribute attribute identifier identifier identifier argument_list | Spawns a redis connection thread |
def change_zoom(self, zoom):
state = self.state
if self.mouse_pos:
(x,y) = (self.mouse_pos.x, self.mouse_pos.y)
else:
(x,y) = (state.width/2, state.height/2)
(lat,lon) = self.coordinates(x, y)
state.ground_width *= zoom
state.ground_width = max(state.ground_width, 20)
state.ground_width = min(state.ground_width, 20000000)
self.re_center(x,y, lat, lon) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment tuple_pattern identifier identifier tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier else_clause block expression_statement assignment tuple_pattern identifier identifier tuple binary_operator attribute identifier identifier integer binary_operator attribute identifier identifier integer expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier integer expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier | zoom in or out by zoom factor, keeping centered |
def _validate(self, data):
errors = {}
if not self._enabled:
return errors
for field in self.validators:
field_errors = []
for validator in self.validators[field]:
try:
validator(data.get(field, None))
except ValidationError as e:
field_errors += e.messages
if field_errors:
errors[field] = ErrorList(field_errors)
return errors | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement not_operator attribute identifier identifier block return_statement identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier list for_statement identifier subscript attribute identifier identifier identifier block try_statement block expression_statement call identifier argument_list call attribute identifier identifier argument_list identifier none except_clause as_pattern identifier as_pattern_target identifier block expression_statement augmented_assignment identifier attribute identifier identifier if_statement identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier return_statement identifier | Helper to run validators on the field data. |
def ensure():
LOGGER.debug('checking repository')
if not os.path.exists('.git'):
LOGGER.error('This command is meant to be ran in a Git repository.')
sys.exit(-1)
LOGGER.debug('repository OK') | module function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list unary_operator integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Makes sure the current working directory is a Git repository. |
def auth_token(cls, token):
store = goldman.sess.store
login = store.find(cls.RTYPE, 'token', token)
if not login:
msg = 'No login found with that token. It may have been revoked.'
raise AuthRejected(**{'detail': msg})
elif login.locked:
msg = 'The login account is currently locked out.'
raise AuthRejected(**{'detail': msg})
else:
login.post_authenticate() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end identifier if_statement not_operator identifier block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list dictionary_splat dictionary pair string string_start string_content string_end identifier elif_clause attribute identifier identifier block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list dictionary_splat dictionary pair string string_start string_content string_end identifier else_clause block expression_statement call attribute identifier identifier argument_list | Callback method for OAuth 2.0 bearer token middleware |
def selectedIndexes(self):
model = self.model()
indexes = []
for comp in self._selectedComponents:
index = model.indexByComponent(comp)
if index is None:
self._selectedComponents.remove(comp)
else:
indexes.append(index)
return indexes | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Returns a list of QModelIndex currently in the model |
def attrib(self):
return dict([
('probability', str(self.probability)),
('strike', str(self.strike)),
('dip', str(self.dip)),
('rake', str(self.rake)),
]) | module function_definition identifier parameters identifier block return_statement call identifier argument_list list tuple string string_start string_content string_end call identifier argument_list attribute identifier identifier tuple string string_start string_content string_end call identifier argument_list attribute identifier identifier tuple string string_start string_content string_end call identifier argument_list attribute identifier identifier tuple string string_start string_content string_end call identifier argument_list attribute identifier identifier | A dict of XML element attributes for this NodalPlane. |
def run_command(command, args):
for category, commands in iteritems(command_categories):
for existing_command in commands:
if existing_command.match(command):
existing_command.run(args) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block for_statement identifier identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier | Run all tasks registered in a command. |
def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False):
name = field.getName()
otherName = "%s_other" % name
value = form.get(otherName, empty_marker)
regex = field.widget.field_regex
if value and not re.match(regex, value):
value = None
if value is empty_marker or not value:
value = form.get(name, empty_marker)
if value is empty_marker:
return empty_marker
if not value and emptyReturnsMarker:
return empty_marker
return value, {} | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement boolean_operator identifier not_operator call attribute identifier identifier argument_list identifier identifier block expression_statement assignment identifier none if_statement boolean_operator comparison_operator identifier identifier not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier identifier block return_statement identifier if_statement boolean_operator not_operator identifier identifier block return_statement identifier return_statement expression_list identifier dictionary | A typed in value takes precedence over a selected value. |
def variants(ctx, variant_id, chromosome, end_chromosome, start, end, variant_type,
sv_type):
if sv_type:
variant_type = 'sv'
adapter = ctx.obj['adapter']
if (start or end):
if not (chromosome and start and end):
LOG.warning("Regions must be specified with chromosome, start and end")
return
if variant_id:
variant = adapter.get_variant({'_id':variant_id})
if variant:
click.echo(variant)
else:
LOG.info("Variant {0} does not exist in database".format(variant_id))
return
if variant_type == 'snv':
result = adapter.get_variants(
chromosome=chromosome,
start=start,
end=end
)
else:
LOG.info("Search for svs")
result = adapter.get_sv_variants(
chromosome=chromosome,
end_chromosome=end_chromosome,
sv_type=sv_type,
pos=start,
end=end
)
i = 0
for variant in result:
i += 1
pp(variant)
LOG.info("Number of variants found in database: %s", i) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block if_statement identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement parenthesized_expression boolean_operator identifier identifier block if_statement not_operator parenthesized_expression boolean_operator boolean_operator identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier integer for_statement identifier identifier block expression_statement augmented_assignment identifier integer expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Display variants in the database. |
def _add_saved_device_info(self, **kwarg):
addr = kwarg.get('address')
_LOGGER.debug('Found saved device with address %s', addr)
self._saved_devices[addr] = kwarg | module function_definition identifier parameters identifier dictionary_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 string string_start string_content string_end identifier expression_statement assignment subscript attribute identifier identifier identifier identifier | Register device info from the saved data file. |
def scan(subtitles):
from importlib.util import find_spec
try:
import subnuker
except ImportError:
fatal('Unable to scan subtitles. Please install subnuker.')
aeidon = find_spec('aeidon') is not None
if sys.stdin.isatty():
args = (['--aeidon'] if aeidon else []) + \
['--gui', '--regex'] + subtitles
subnuker.main(args)
else:
args = (['--aeidon'] if aeidon else []) + \
['--gui', '--regex']
execute(Config.TERMINAL,
'--execute',
'subnuker',
*args + subtitles) | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier try_statement block import_statement dotted_name identifier except_clause identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier comparison_operator call identifier argument_list string string_start string_content string_end none if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier binary_operator binary_operator parenthesized_expression conditional_expression list string string_start string_content string_end identifier list line_continuation list string string_start string_content string_end string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier binary_operator parenthesized_expression conditional_expression list string string_start string_content string_end identifier list line_continuation list string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end string string_start string_content string_end list_splat binary_operator identifier identifier | Remove advertising from subtitles. |
def main():
(options, _) = _parse_args()
if options.change_password:
c.keyring_set_password(c["username"])
sys.exit(0)
if options.select:
courses = client.get_courses()
c.selection_dialog(courses)
c.save()
sys.exit(0)
if options.stop:
os.system("kill -2 `cat ~/.studdp/studdp.pid`")
sys.exit(0)
task = _MainLoop(options.daemonize, options.update_courses)
if options.daemonize:
log.info("daemonizing...")
with daemon.DaemonContext(working_directory=".", pidfile=PIDLockFile(PID_FILE)):
handler = logging.FileHandler(LOG_PATH)
handler.setFormatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
log.addHandler(handler)
task()
else:
task() | module function_definition identifier parameters block expression_statement assignment tuple_pattern identifier identifier call identifier argument_list if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list integer if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end with_statement with_clause with_item call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list else_clause block expression_statement call identifier argument_list | parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon |
def convert_context_to_csv(self, context):
content = []
date_headers = context['date_headers']
headers = ['Name']
headers.extend([date.strftime('%m/%d/%Y') for date in date_headers])
headers.append('Total')
content.append(headers)
summaries = context['summaries']
summary = summaries.get(self.export, [])
for rows, totals in summary:
for name, user_id, hours in rows:
data = [name]
data.extend(hours)
content.append(data)
total = ['Totals']
total.extend(totals)
content.append(total)
return content | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list_comprehension call attribute identifier identifier argument_list string string_start string_content string_end for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier list for_statement pattern_list identifier identifier identifier block for_statement pattern_list identifier identifier identifier identifier block expression_statement assignment identifier list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Convert the context dictionary into a CSV file. |
def setup_db(session, botconfig, confdir):
Base.metadata.create_all(session.connection())
if not session.get_bind().has_table('alembic_version'):
conf_obj = config.Config()
conf_obj.set_main_option('bot_config_path', confdir)
with resources.path('cslbot', botconfig['alembic']['script_location']) as script_location:
conf_obj.set_main_option('script_location', str(script_location))
command.stamp(conf_obj, 'head')
owner_nick = botconfig['auth']['owner']
if not session.query(Permissions).filter(Permissions.nick == owner_nick).count():
session.add(Permissions(nick=owner_nick, role='owner')) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list if_statement not_operator call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement not_operator call attribute call attribute call attribute identifier identifier argument_list identifier identifier argument_list comparison_operator attribute identifier identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end | Sets up the database. |
def _format_native_types(self, na_rep='', quoting=None, **kwargs):
mask = isna(self)
if not self.is_object() and not quoting:
values = np.asarray(self).astype(str)
else:
values = np.array(self, dtype=object, copy=True)
values[mask] = na_rep
return values | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator not_operator call attribute identifier identifier argument_list not_operator identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier true expression_statement assignment subscript identifier identifier identifier return_statement identifier | Actually format specific types of the index. |
def reverse(self, matching_name, **kwargs):
for record in self.matching_records:
if record.name == matching_name:
path_template = record.path_template
break
else:
raise NotReversed
if path_template.wildcard_name:
l = kwargs.get(path_template.wildcard_name)
if not l:
raise NotReversed
additional_path = '/'.join(l)
extra_path_elements = path_template.pattern.split('/')[:-1]
pattern = join_paths('/'.join(extra_path_elements), additional_path)
else:
pattern = path_template.pattern
try:
url = pattern.format(**kwargs)
except KeyError:
raise NotReversed
return url | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier break_statement else_clause block raise_statement identifier if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement not_operator identifier block raise_statement identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end slice unary_operator integer expression_statement assignment identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier except_clause identifier block raise_statement identifier return_statement identifier | Getting a matching name and URL args and return a corresponded URL |
def show_batch_runner(self):
from safe.gui.tools.batch.batch_dialog import BatchDialog
dialog = BatchDialog(
parent=self.iface.mainWindow(),
iface=self.iface,
dock=self.dock_widget)
dialog.exec_() | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list | Show the batch runner dialog. |
def _get_all(cls, parent_id=None, grandparent_id=None):
client = cls._get_client()
endpoint = cls._endpoint.format(resource_id="",
parent_id=parent_id or "",
grandparent_id=grandparent_id or "")
resources = []
while True:
response = client.get_resource(endpoint)
for raw_data in response.get("value", []):
raw_data["parentResourceID"] = parent_id
raw_data["grandParentResourceID"] = grandparent_id
resources.append(cls.from_raw_data(raw_data))
endpoint = response.get("nextLink")
if not endpoint:
break
return resources | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_end keyword_argument identifier boolean_operator identifier string string_start string_end keyword_argument identifier boolean_operator identifier string string_start string_end expression_statement assignment identifier list while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end list block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block break_statement return_statement identifier | Retrives all the required resources. |
def role_delete(role_id, endpoint_id):
client = get_client()
res = client.delete_endpoint_role(endpoint_id, role_id)
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message") | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end | Executor for `globus endpoint role delete` |
def load_and_save_image(url, destination):
from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(url)
try:
f = urlopen(req)
print "downloading " + url
local_file = open(destination, "wb")
local_file.write(f.read())
local_file.close()
file_type = imghdr.what(destination)
local_file = open(destination, "rb")
data = local_file.read()
local_file.close()
final_file = open(destination + '.' + file_type, "wb")
final_file.write(data)
final_file.close()
print('save image preview {0}'.format(destination + '.' + file_type))
os.remove(destination)
except HTTPError, e:
print "HTTP Error:", e.code, url
except URLError, e:
print "URL Error:", e.reason, url | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier dotted_name identifier dotted_name identifier dotted_name identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier print_statement binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list binary_operator binary_operator identifier string string_start string_content string_end identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list binary_operator binary_operator identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier except_clause identifier identifier block print_statement string string_start string_content string_end attribute identifier identifier identifier except_clause identifier identifier block print_statement string string_start string_content string_end attribute identifier identifier identifier | Download image from given url and saves it to destination. |
def screenshot(self, *args):
from mss import mss
if not os.path.exists("screenshots"):
os.makedirs("screenshots")
box = {
"top": self.winfo_y(),
"left": self.winfo_x(),
"width": self.winfo_width(),
"height": self.winfo_height()
}
screenshot = mss().grab(box)
screenshot = Image.frombytes("RGB", screenshot.size, screenshot.rgb)
screenshot.save("screenshots/{}.png".format(ttk.Style(self).theme_use())) | module function_definition identifier parameters identifier list_splat_pattern identifier block import_from_statement dotted_name identifier dotted_name identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute call attribute identifier identifier argument_list identifier identifier argument_list | Take a screenshot, crop and save |
def _get_gos_upper(self, ntpltgo1, max_upper, go2parentids):
goids_possible = ntpltgo1.gosubdag.go2obj.keys()
return self._get_gosrcs_upper(goids_possible, max_upper, go2parentids) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier identifier identifier | Plot a GO DAG for the upper portion of a single Group of user GOs. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.