code
stringlengths 51
2.34k
| sequence
stringlengths 186
3.94k
| docstring
stringlengths 11
171
|
|---|---|---|
def single_triangle():
points = np.zeros((3, 3))
points[1] = [1, 0, 0]
points[2] = [0.5, 0.707, 0]
cells = np.array([[3, 0, 1, 2]], ctypes.c_long)
return vtki.PolyData(points, cells)
|
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list tuple integer integer expression_statement assignment subscript identifier integer list integer integer integer expression_statement assignment subscript identifier integer list float float integer expression_statement assignment identifier call attribute identifier identifier argument_list list list integer integer integer integer attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier
|
A single PolyData triangle
|
def load_speaker(corpus, path):
base_path, speaker_name = os.path.split(path)
base_path, gender_desc = os.path.split(base_path)
base_path, __ = os.path.split(base_path)
base_path, tag = os.path.split(base_path)
gender = issuers.Gender.UNKNOWN
if gender_desc == 'male':
gender = issuers.Gender.MALE
elif gender_desc == 'female':
gender = issuers.Gender.FEMALE
speaker = issuers.Speaker(speaker_name, gender=gender)
corpus.import_issuers(speaker)
return speaker
|
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier attribute attribute identifier identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
|
Create a speaker instance for the given path.
|
def login(self) -> bool:
response = self.get(self.LOGIN_URL)
login_url = get_base_url(response.text)
login_data = {'email': self._login, 'pass': self._password}
login_response = self.post(login_url, login_data)
url_params = get_url_params(login_response.url)
self.check_for_additional_actions(url_params,
login_response.text,
login_data)
if 'remixsid' in self.cookies or 'remixsid6' in self.cookies:
return True
|
module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier identifier if_statement boolean_operator comparison_operator string string_start string_content string_end attribute identifier identifier comparison_operator string string_start string_content string_end attribute identifier identifier block return_statement true
|
Authorizes a user and returns a bool value of the result
|
def cmdline(argv=sys.argv[1:]):
parser = ArgumentParser(
description='Create and merge collections of stop words')
parser.add_argument(
'language', help='The language used in the collection')
parser.add_argument('sources', metavar='FILE', nargs='+',
help='Source files to parse')
options = parser.parse_args(argv)
factory = StopWordFactory()
language = options.language
stop_words = factory.get_stop_words(language, fail_safe=True)
for filename in options.sources:
stop_words += StopWord(language, factory.read_collection(filename))
filename = factory.get_collection_filename(stop_words.language)
factory.write_collection(filename, stop_words.collection)
|
module function_definition identifier parameters default_parameter identifier subscript attribute identifier identifier slice integer block expression_statement assignment identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier
|
Script for merging different collections of stop words.
|
def load_bookmarks(filename):
bookmarks = _load_all_bookmarks()
return {k: v for k, v in bookmarks.items() if v[0] == filename}
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list return_statement dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list if_clause comparison_operator subscript identifier integer identifier
|
Load all bookmarks for a specific file from config.
|
def error_handler(exception_cls, response):
error = convert_response_to_text(response)
exception = exception_cls("Response Code: %s\tResponse: %s" %
(response.status_code, error))
exception.status_code = response.status_code
raise exception
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple attribute identifier identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier raise_statement identifier
|
Handle HTTP errors by formatting into strings.
|
def _set_cache_(self, attr):
if attr in TagObject.__slots__:
ostream = self.repo.odb.stream(self.binsha)
lines = ostream.read().decode(defenc).splitlines()
obj, hexsha = lines[0].split(" ")
type_token, type_name = lines[1].split(" ")
self.object = \
get_object_type_by_name(type_name.encode('ascii'))(self.repo, hex_to_bin(hexsha))
self.tag = lines[2][4:]
tagger_info = lines[3]
self.tagger, self.tagged_date, self.tagger_tz_offset = parse_actor_and_date(tagger_info)
if len(lines) > 5:
self.message = "\n".join(lines[5:])
else:
self.message = ''
else:
super(TagObject, self)._set_cache_(attr)
|
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list identifier argument_list identifier identifier argument_list expression_statement assignment pattern_list identifier identifier call attribute subscript identifier integer identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute subscript identifier integer identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier line_continuation call call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end argument_list attribute identifier identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier subscript subscript identifier integer slice integer expression_statement assignment identifier subscript identifier integer expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier attribute identifier identifier call identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment attribute identifier identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list subscript identifier slice integer else_clause block expression_statement assignment attribute identifier identifier string string_start string_end else_clause block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier
|
Cache all our attributes at once
|
def write_raw_byte(self, value):
self.bus.write_byte(self.address, value)
self.log.debug("write_raw_byte: Wrote 0x%02X" % value)
|
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier
|
Writes an 8-bit byte directly to the bus
|
def cli(env, ip_version):
mgr = SoftLayer.NetworkManager(env.client)
table = formatting.Table(['id', 'ip', 'assigned', 'target'])
version = None
if ip_version == 'v4':
version = 4
elif ip_version == 'v6':
version = 6
ips = mgr.list_global_ips(version=version)
for ip_address in ips:
assigned = 'No'
target = 'None'
if ip_address.get('destinationIpAddress'):
dest = ip_address['destinationIpAddress']
assigned = 'Yes'
target = dest['ipAddress']
virtual_guest = dest.get('virtualGuest')
if virtual_guest:
target += (' (%s)'
% virtual_guest['fullyQualifiedDomainName'])
elif ip_address['destinationIpAddress'].get('hardware'):
target += (' (%s)'
% dest['hardware']['fullyQualifiedDomainName'])
table.add_row([ip_address['id'],
ip_address['ipAddress']['ipAddress'],
assigned,
target])
env.fout(table)
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier none if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier integer elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier for_statement identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement augmented_assignment identifier parenthesized_expression binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end elif_clause call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end block expression_statement augmented_assignment identifier parenthesized_expression binary_operator string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list subscript identifier string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list identifier
|
List all global IPs.
|
def path(self, root_dir):
path = os.path.realpath(root_dir)
if not os.path.exists(path):
raise ValueError('Build root does not exist: {}'.format(root_dir))
self._root_dir = path
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier
|
Manually establishes the build root for the current workspace.
|
def load_plugins(group='metrics.plugin.10'):
file_processors = []
build_processors = []
for ep in pkg_resources.iter_entry_points(group, name=None):
log.debug('loading \'%s\'', ep)
plugin = ep.load()
if hasattr(plugin, 'get_file_processors'):
file_processors.extend(plugin.get_file_processors())
if hasattr(plugin, 'get_build_processors'):
build_processors.extend(plugin.get_build_processors())
return file_processors, build_processors
|
module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list identifier keyword_argument identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement expression_list identifier identifier
|
Load and installed metrics plugins.
|
def similarity(self, other):
ratio = SequenceMatcher(a=self.value, b=other.value).ratio()
similarity = self.Similarity(ratio)
return similarity
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier
|
Get similarity as a ratio of the two texts.
|
def select(self, cb=None):
if not self._enabled:
self._enabled = True
self.send_frame(MethodFrame(self.channel_id, 90, 10))
self._select_cb.append(cb)
self.channel.add_synchronous_cb(self._recv_select_ok)
|
module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier integer integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier
|
Set this channel to use transactions.
|
def find_censored_md5ext(post_id: int) -> Optional[str]:
"Find MD5 for a censored post's ID, return None if can't find."
try:
last_pull_date = LAST_PULL_DATE_FILE.read_text().strip()
except FileNotFoundError:
last_pull_date = ""
date = datetime.utcnow()
date = f"{date.year}{date.month}{date.day}"
if last_pull_date != date:
update_batches()
LAST_PULL_DATE_FILE.parent.mkdir(exist_ok=True, parents=True)
LAST_PULL_DATE_FILE.write_text(date)
post_id = str(post_id)
for batch in BATCHES_DIR.iterdir():
with open(batch, "r") as content:
for line in content:
an_id, its_md5_ext = line.split(":")
if post_id == an_id:
return its_md5_ext.rstrip().split(".")
return None
|
module function_definition identifier parameters typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block expression_statement string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list except_clause identifier block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier string string_start interpolation attribute identifier identifier interpolation attribute identifier identifier interpolation attribute identifier identifier string_end if_statement comparison_operator identifier identifier block expression_statement call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true keyword_argument identifier true expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier identifier block return_statement call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end return_statement none
|
Find MD5 for a censored post's ID, return None if can't find.
|
def format_server_configuration_management_settings(result):
from collections import OrderedDict
order_dict = OrderedDict([('sqlConnectivityUpdateSettings',
format_sql_connectivity_update_settings(result.sql_connectivity_update_settings)),
('sqlWorkloadTypeUpdateSettings', format_sql_workload_type_update_settings(result.sql_workload_type_update_settings)),
('sqlStorageUpdateSettings', format_sql_storage_update_settings(result.sql_storage_update_settings)),
('additionalFeaturesServerConfigurations',
format_additional_features_server_configurations(result.additional_features_server_configurations))])
return order_dict
|
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier 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 return_statement identifier
|
Formats the ServerConfigurationsManagementSettings object removing arguments that are empty
|
def delete_user_action(model, request):
try:
users = model.parent.backend
uid = model.model.name
del users[uid]
users()
model.parent.invalidate()
localizer = get_localizer(request)
message = localizer.translate(_(
'delete_user_from_database',
default="Deleted user '${uid}' from database.",
mapping={'uid': uid}
))
return {
'success': True,
'message': message
}
except Exception as e:
return {
'success': False,
'message': str(e)
}
|
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier delete_statement subscript identifier identifier expression_statement call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end identifier return_statement dictionary pair string string_start string_content string_end true pair string string_start string_content string_end identifier except_clause as_pattern identifier as_pattern_target identifier block return_statement dictionary pair string string_start string_content string_end false pair string string_start string_content string_end call identifier argument_list identifier
|
Delete user from database.
|
def execute_notebook_with_engine(self, engine_name, nb, kernel_name, **kwargs):
return self.get_engine(engine_name).execute_notebook(nb, kernel_name, **kwargs)
|
module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block return_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier identifier dictionary_splat identifier
|
Fetch a named engine and execute the nb object against it.
|
def start_tasks(self):
while self.tasks_at_once > len(self.pending_results) and self._has_more_tasks():
task, parent_result = self.tasks.popleft()
self.execute_task(task, parent_result)
|
module function_definition identifier parameters identifier block while_statement boolean_operator comparison_operator attribute identifier identifier call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier
|
Start however many tasks we can based on our limits and what we have left to finish.
|
def parse_child_elements(self, element):
for child in element.iterchildren():
self.parsers[child.tag](child)
|
module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement call subscript attribute identifier identifier attribute identifier identifier argument_list identifier
|
parses all children of an etree element
|
def annotate_from_changeset(self, changeset):
if self.annotate_from_changeset_func:
return self.annotate_from_changeset_func(changeset)
else:
return ''.join((changeset.id, '\n'))
|
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block return_statement call attribute identifier identifier argument_list identifier else_clause block return_statement call attribute string string_start string_end identifier argument_list tuple attribute identifier identifier string string_start string_content escape_sequence string_end
|
Returns full html line for single changeset per annotated line.
|
def demo_args(self):
argv = random.choice(self.examples).replace("--demo", "")
self._reparse_args['pos'] = shlex.split(argv)
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier
|
Additional method for replacing input arguments by demo ones.
|
def distVersion():
from pkg_resources import parse_version
build_number = buildNumber()
parsedBaseVersion = parse_version(baseVersion)
if isinstance(parsedBaseVersion, tuple):
raise RuntimeError("Setuptools version 8.0 or newer required. Update by running "
"'pip install setuptools --upgrade'")
if build_number is not None and parsedBaseVersion.is_prerelease:
return baseVersion + '.dev' + build_number
else:
return baseVersion
|
module function_definition identifier parameters block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier if_statement call identifier argument_list identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end if_statement boolean_operator comparison_operator identifier none attribute identifier identifier block return_statement binary_operator binary_operator identifier string string_start string_content string_end identifier else_clause block return_statement identifier
|
The distribution version identifying a published release on PyPI.
|
def _get_command_by_name(self, blueprint, name):
commands = self._get_commands_by_name(blueprint, name)
if len(commands):
return commands[0]
|
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement call identifier argument_list identifier block return_statement subscript identifier integer
|
Get the primary key command it it exists.
|
def populate(self):
from django.conf import settings
from django.core import urlresolvers
self.append(("", ""))
urlconf = settings.ROOT_URLCONF
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
for key, value in resolver.reverse_dict.items():
if isinstance(key, basestring):
args = value[0][0][1]
url = "/" + value[0][0][0]
self.append((key, " ".join(key.split("_"))))
for namespace, url in resolver.namespace_dict.items():
for key, value in url[1].reverse_dict.items():
if isinstance(key, basestring):
args = value[0][0][1]
full_key = '%s:%s' % (namespace, key)
self.append((full_key, "%s: %s" % (namespace, " ".join(key.split("_")))))
self.sort()
|
module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement call attribute identifier identifier argument_list tuple string string_start string_end string string_start string_end expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript subscript subscript identifier integer integer integer expression_statement assignment identifier binary_operator string string_start string_content string_end subscript subscript subscript identifier integer integer integer expression_statement call attribute identifier identifier argument_list tuple identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block for_statement pattern_list identifier identifier call attribute attribute subscript identifier integer identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript subscript subscript identifier integer integer integer expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier expression_statement call attribute identifier identifier argument_list tuple identifier binary_operator string string_start string_content string_end tuple identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list
|
Populate this list with all views that take no arguments.
|
def _setup_db(cls):
uri = cls._app.config.get("DB_URL")
if uri:
db.connect__(uri, cls._app)
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier
|
Setup the DB connection if DB_URL is set
|
def pre_change_receiver(self, instance: Model, action: Action):
if action == Action.CREATE:
group_names = set()
else:
group_names = set(self.group_names(instance))
if not hasattr(instance, '__instance_groups'):
instance.__instance_groups = threading.local()
instance.__instance_groups.observers = {}
if not hasattr(instance.__instance_groups, 'observers'):
instance.__instance_groups.observers = {}
instance.__instance_groups.observers[self] = group_names
|
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list else_clause block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute attribute identifier identifier identifier dictionary if_statement not_operator call identifier argument_list attribute identifier identifier string string_start string_content string_end block expression_statement assignment attribute attribute identifier identifier identifier dictionary expression_statement assignment subscript attribute attribute identifier identifier identifier identifier identifier
|
Entry point for triggering the old_binding from save signals.
|
def setContextNode(self, node):
if node is None: node__o = None
else: node__o = node._o
libxml2mod.xmlXPathSetContextNode(self._o, node__o)
|
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier none else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier
|
Set the current node of an xpathContext
|
def trim_decimals(s, precision=-3):
encoded = s.encode('ascii', 'ignore')
str_val = ""
if six.PY3:
str_val = str(encoded, encoding='ascii', errors='ignore')[:precision]
else:
if precision == 0:
str_val = str(encoded)
else:
str_val = str(encoded)[:precision]
if len(str_val) > 0:
return float(str_val)
else:
return 0
|
module function_definition identifier parameters identifier default_parameter identifier unary_operator integer block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier string string_start string_end if_statement attribute identifier identifier block expression_statement assignment identifier subscript call identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end slice identifier else_clause block if_statement comparison_operator identifier integer block expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier subscript call identifier argument_list identifier slice identifier if_statement comparison_operator call identifier argument_list identifier integer block return_statement call identifier argument_list identifier else_clause block return_statement integer
|
Convert from scientific notation using precision
|
def handle_request(path):
accept = bottle.request.get_header("accept", default="text/plain")
bottle.response.status = 200
try:
if "text/html" in accept:
ret = CURRENT_STATE.as_html(path=path)
bottle.response.content_type = "text/html"
elif "application/json" in accept:
ret = CURRENT_STATE.as_json(path=path)
bottle.response.content_type = "application/json"
elif "text/" in accept or "*/*" in accept:
ret = CURRENT_STATE.as_json(path=path, with_indent=True)
bottle.response.content_type = "text/plain"
else:
bottle.response.status = 407
ret = "Cannot render data in acceptable content type"
except StateError:
bottle.response.status = 404
ret = "Requested state component not found"
return ret
|
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 keyword_argument identifier string string_start string_content string_end expression_statement assignment attribute attribute identifier identifier identifier integer try_statement block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment attribute attribute identifier identifier identifier string string_start string_content string_end elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment attribute attribute identifier identifier identifier string string_start string_content string_end elif_clause boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier true expression_statement assignment attribute attribute identifier identifier identifier string string_start string_content string_end else_clause block expression_statement assignment attribute attribute identifier identifier identifier integer expression_statement assignment identifier string string_start string_content string_end except_clause identifier block expression_statement assignment attribute attribute identifier identifier identifier integer expression_statement assignment identifier string string_start string_content string_end return_statement identifier
|
Return the current status.
|
def server_id(self) :
"asks the server at the other end for its unique id."
c_result = dbus.dbus_connection_get_server_id(self._dbobj)
result = ct.cast(c_result, ct.c_char_p).value.decode()
dbus.dbus_free(c_result)
return \
result
|
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute attribute call attribute identifier identifier argument_list identifier attribute identifier identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement line_continuation identifier
|
asks the server at the other end for its unique id.
|
def user_s3_bucket(canonical_user_id=None):
s3 = _s3_resource()
if not canonical_user_id:
canonical_user_id = _get_canonical_aws_user_id(s3)
s3_bucket_name = "dallinger-{}".format(
hashlib.sha256(canonical_user_id.encode("utf8")).hexdigest()[0:8]
)
return _get_or_create_s3_bucket(s3, s3_bucket_name)
|
module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call identifier argument_list if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list subscript call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list slice integer integer return_statement call identifier argument_list identifier identifier
|
Get the user's S3 bucket.
|
def replaceint(fname, replacewith='%s'):
words = fname.split()
for i, word in enumerate(words):
try:
word = int(word)
words[i] = replacewith
except ValueError:
pass
return ' '.join(words)
|
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript identifier identifier identifier except_clause identifier block pass_statement return_statement call attribute string string_start string_content string_end identifier argument_list identifier
|
replace int in lst
|
def fail(self, message=None, force_exit=False):
global last_exit_code
if not last_exit_code:
last_exit_code = 1
with self.git.batch_commit('FAILED'):
self.set_status('FAILED', add_section=False)
self.git.commit_json_file('FAIL_MESSAGE', 'aetros/job/crash/error', str(message) if message else '')
if isinstance(sys.stderr, GeneralLogger):
self.git.commit_json_file('FAIL_MESSAGE_LAST_LOG', 'aetros/job/crash/last_message', sys.stderr.last_messages)
self.logger.debug('Crash report stored in commit ' + self.git.get_head_commit())
self.stop(JOB_STATUS.PROGRESS_STATUS_FAILED, force_exit=force_exit)
|
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false block global_statement identifier if_statement not_operator identifier block expression_statement assignment identifier integer with_statement with_clause with_item 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 keyword_argument identifier false expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end conditional_expression call identifier argument_list identifier identifier string string_start string_end if_statement call identifier argument_list attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier
|
Marks the job as failed, saves the given error message and force exists the process when force_exit=True.
|
def loadTargetPatterns(self, filename, cols = None, everyNrows = 1,
delim = ' ', checkEven = 1):
self.loadTargetPatternssFromFile(filename, cols, everyNrows,
delim, checkEven)
|
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier integer default_parameter identifier string string_start string_content string_end default_parameter identifier integer block expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier identifier
|
Loads targets as patterns from file.
|
def error_handler(_, err, arg):
arg.value = err.error
return libnl.handlers.NL_STOP
|
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement attribute attribute identifier identifier identifier
|
Update the mutable integer `arg` with the error code.
|
def _decrypt(self, data, key):
seed1 = key
seed2 = 0xEEEEEEEE
result = BytesIO()
for i in range(len(data) // 4):
seed2 += self.encryption_table[0x400 + (seed1 & 0xFF)]
seed2 &= 0xFFFFFFFF
value = struct.unpack("<I", data[i*4:i*4+4])[0]
value = (value ^ (seed1 + seed2)) & 0xFFFFFFFF
seed1 = ((~seed1 << 0x15) + 0x11111111) | (seed1 >> 0x0B)
seed1 &= 0xFFFFFFFF
seed2 = value + seed2 + (seed2 << 5) + 3 & 0xFFFFFFFF
result.write(struct.pack("<I", value))
return result.getvalue()
|
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier identifier expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list for_statement identifier call identifier argument_list binary_operator call identifier argument_list identifier integer block expression_statement augmented_assignment identifier subscript attribute identifier identifier binary_operator integer parenthesized_expression binary_operator identifier integer expression_statement augmented_assignment identifier integer expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier slice binary_operator identifier integer binary_operator binary_operator identifier integer integer integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier parenthesized_expression binary_operator identifier identifier integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator parenthesized_expression binary_operator unary_operator identifier integer integer parenthesized_expression binary_operator identifier integer expression_statement augmented_assignment identifier integer expression_statement assignment identifier binary_operator binary_operator binary_operator binary_operator identifier identifier parenthesized_expression binary_operator identifier integer integer integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list
|
Decrypt hash or block table or a sector.
|
def setBottomRight(self, loc):
offset = self.getBottomRight().getOffset(loc)
return self.setLocation(self.getTopLeft().offset(offset))
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list identifier return_statement call attribute identifier identifier argument_list call attribute call attribute identifier identifier argument_list identifier argument_list identifier
|
Move this region so its bottom right corner is on ``loc``
|
def signature(secret, parts):
if not isinstance(secret, six.binary_type):
secret = secret.encode('utf-8')
newparts = []
for part in parts:
if not isinstance(part, six.binary_type):
part = part.encode('utf-8')
newparts.append(part)
parts = newparts
if sys.version_info >= (2, 5):
csum = hmac.new(secret, digestmod=hashlib.sha1)
else:
csum = hmac.new(secret, digestmod=sha)
for part in parts:
csum.update(part)
return csum.hexdigest()
|
module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier identifier if_statement comparison_operator attribute identifier identifier tuple integer integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list
|
Generates a signature. All strings are assumed to be utf-8
|
def ipv6(self, network=False):
address = str(ip_address(self.generator.random.randint(
2 ** IPV4LENGTH, (2 ** IPV6LENGTH) - 1)))
if network:
address += '/' + str(self.generator.random.randint(0, IPV6LENGTH))
address = str(ip_network(address, strict=False))
return address
|
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list binary_operator integer identifier binary_operator parenthesized_expression binary_operator integer identifier integer if_statement identifier block expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end call identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list integer identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier keyword_argument identifier false return_statement identifier
|
Produce a random IPv6 address or network with a valid CIDR
|
def install_translations(config):
if not config:
return
from . import _translation
checks_translation = gettext.translation(domain=config["domain"],
localedir=internal.check_dir / config["localedir"],
fallback=True)
_translation.add_fallback(checks_translation)
|
module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement import_from_statement relative_import import_prefix dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier binary_operator attribute identifier identifier subscript identifier string string_start string_content string_end keyword_argument identifier true expression_statement call attribute identifier identifier argument_list identifier
|
Add check translations according to ``config`` as a fallback to existing translations
|
def _autocomplete_default(self, text: str, line: str, begidx: int, endidx: int,
argparser: argparse.ArgumentParser) -> List[str]:
completer = AutoCompleter(argparser, self)
tokens, _ = self.tokens_for_completion(line, begidx, endidx)
if not tokens:
return []
return completer.complete_command(tokens, text, line, begidx, endidx)
|
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type attribute identifier identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier identifier if_statement not_operator identifier block return_statement list return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier identifier
|
Default completion function for argparse commands.
|
def populate_database():
if User.fetch_by(username='admin'):
return
admin = User(name='Administrator', password='password',
username='admin', is_admin=True)
class_ = Class(name='CS32')
Session.add(class_)
Session.flush()
project = Project(name='Project 1', class_id=class_.id)
Session.add(project)
Session.flush()
fv = FileVerifier(filename='test.c', min_size=3, min_lines=1,
project_id=project.id)
Session.add_all([admin, fv])
try:
transaction.commit()
print('Admin user created')
except IntegrityError:
transaction.abort()
|
module function_definition identifier parameters block if_statement call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end block return_statement expression_statement assignment identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier true expression_statement assignment identifier call identifier argument_list keyword_argument 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 assignment identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list list identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list
|
Populate the database with some data useful for development.
|
def one_way_portal(self, other, **stats):
return self.character.new_portal(
self, other, symmetrical=False, **stats
)
|
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier false dictionary_splat identifier
|
Connect a portal from here to another node, and return it.
|
def parse(self):
try:
return self.parse_top_level()
except PartpyError as ex:
self.error = True
print(ex.pretty_print())
|
module function_definition identifier parameters identifier block try_statement block return_statement call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment attribute identifier identifier true expression_statement call identifier argument_list call attribute identifier identifier argument_list
|
Run the parser over the entire sourestring and return the results.
|
def update_callback(self, handle, events):
if self._poll is None:
raise RuntimeError('poll instance is closed')
if not has_callback(self, handle):
raise ValueError('no such callback')
if events & ~(READABLE|WRITABLE):
raise ValueError('illegal event mask: {}'.format(events))
if handle.extra == events:
return
if handle.extra & READABLE:
self._readers -= 1
if handle.extra & WRITABLE:
self._writers -= 1
if events & READABLE:
self._readers += 1
if events & WRITABLE:
self._writers += 1
handle.extra = events
self._sync()
|
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement binary_operator identifier unary_operator parenthesized_expression binary_operator identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator attribute identifier identifier identifier block return_statement if_statement binary_operator attribute identifier identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer if_statement binary_operator attribute identifier identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer if_statement binary_operator identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer if_statement binary_operator identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list
|
Update the event mask for a callback.
|
def StartGdb(self):
if self.inferior.is_running:
self.inferior.ShutDownGdb()
program_arg = 'program %d ' % self.inferior.pid
else:
program_arg = ''
os.system('gdb ' + program_arg + ' '.join(self.gdb_args))
reset_position = raw_input('Reset debugger position? [y]/n ')
if not reset_position or reset_position == 'y' or reset_position == 'yes':
self.position = None
|
module function_definition identifier parameters identifier block if_statement attribute attribute identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier else_clause block expression_statement assignment identifier string string_start string_end expression_statement call attribute identifier identifier argument_list binary_operator binary_operator string string_start string_content string_end identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement boolean_operator boolean_operator not_operator identifier comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier none
|
Hands control over to a new gdb process.
|
def _bind(self):
credentials = pika.PlainCredentials(self.user, self.password)
params = pika.ConnectionParameters(credentials=credentials,
host=self.server,
virtual_host=self.vhost,
port=self.port)
self.connection = pika.BlockingConnection(params)
self.channel = self.connection.channel()
self.channel.exchange_declare(exchange=self.topic_exchange,
exchange_type="topic")
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end
|
Create socket and bind
|
def message(self) -> str:
if self.is_error:
assert self._error
return self._error.human
else:
return self._stage.value.human
|
module function_definition identifier parameters identifier type identifier block if_statement attribute identifier identifier block assert_statement attribute identifier identifier return_statement attribute attribute identifier identifier identifier else_clause block return_statement attribute attribute attribute identifier identifier identifier identifier
|
The human readable message of the current stage
|
def fixchars(self, text):
keys = ''.join(Config.CHARFIXES.keys())
values = ''.join(Config.CHARFIXES.values())
fixed = text.translate(str.maketrans(keys, values))
if fixed != text:
self.modified = True
return fixed
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute string string_start string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment attribute identifier identifier true return_statement identifier
|
Find and replace problematic characters.
|
def id(self):
id = ''
if (self.server_and_prefix is not None and
self.server_and_prefix != ''):
id += self.server_and_prefix + '/'
if (self.identifier is not None):
id += self.identifier
return id
|
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement parenthesized_expression boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier string string_start string_end block expression_statement augmented_assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end if_statement parenthesized_expression comparison_operator attribute identifier identifier none block expression_statement augmented_assignment identifier attribute identifier identifier return_statement identifier
|
id property based on server_and_prefix and identifier.
|
def make_default_short_help(help, max_length=45):
words = help.split()
total_length = 0
result = []
done = False
for word in words:
if word[-1:] == '.':
done = True
new_length = result and 1 + len(word) or len(word)
if total_length + new_length > max_length:
result.append('...')
done = True
else:
if result:
result.append(' ')
result.append(word)
if done:
break
total_length += new_length
return ''.join(result)
|
module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier integer expression_statement assignment identifier list expression_statement assignment identifier false for_statement identifier identifier block if_statement comparison_operator subscript identifier slice unary_operator integer string string_start string_content string_end block expression_statement assignment identifier true expression_statement assignment identifier boolean_operator boolean_operator identifier binary_operator integer call identifier argument_list identifier call identifier argument_list identifier if_statement comparison_operator binary_operator identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier true else_clause 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 if_statement identifier block break_statement expression_statement augmented_assignment identifier identifier return_statement call attribute string string_start string_end identifier argument_list identifier
|
Return a condensed version of help string.
|
def _parse_date(self, cell_value):
date_tuple = xlrd.xldate_as_tuple(cell_value, self.raw_sheet.book.datemode)
return self.tuple_to_datetime(date_tuple)
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute attribute attribute identifier identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier
|
Attempts to parse a cell_value as a date.
|
def sink(self):
op = Operator(
_generate_uuid(),
OpType.Sink,
"Sink",
num_instances=self.env.config.parallelism)
return self.__register(op)
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list attribute identifier identifier string string_start string_content string_end keyword_argument identifier attribute attribute attribute identifier identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier
|
Closes the stream with a sink operator.
|
def call_purge_doc(cls, kb_app, sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docname: str):
for callback in EventAction.get_callbacks(kb_app, SphinxEvent.EPD):
callback(kb_app, sphinx_app, sphinx_env, docname)
|
module function_definition identifier parameters identifier identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block for_statement identifier call attribute identifier identifier argument_list identifier attribute identifier identifier block expression_statement call identifier argument_list identifier identifier identifier identifier
|
On env-purge-doc, do callbacks
|
def _get_baseline_string_from_file(filename):
try:
with open(filename) as f:
return f.read()
except IOError:
log.error(
'Unable to open baseline file: {}\n'
'Please create it via\n'
' `detect-secrets scan > {}`\n'
.format(filename, filename),
)
raise
|
module function_definition identifier parameters identifier block try_statement block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block return_statement call attribute identifier identifier argument_list except_clause identifier block expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content escape_sequence string_end string string_start string_content escape_sequence string_end string string_start string_content escape_sequence string_end identifier argument_list identifier identifier raise_statement
|
Breaking this function up for mockability.
|
def getName(self):
name=self.findattr('name')
if not name:
name="_directinput_"
if self.classname().lower()=="line":
name+="."+str(self).replace(" ","_").lower()
else:
name=name.replace('.txt','')
while name.startswith("."):
name=name[1:]
return name
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end block expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end call attribute call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end while_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier subscript identifier slice integer return_statement identifier
|
Return a Name string for this object.
|
def dwrap(kx,nc):
q1 = np.mod(kx, nc)
q2 = np.minimum(q1, nc-q1)
return q2
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator identifier identifier return_statement identifier
|
compute a wrapped distance
|
def to_json(self):
new_pos = self._blob_reader.tell()
if self._has_iterated:
new_pos -= 1
return {self.BLOB_KEY_PARAM: self._blob_key,
self.INITIAL_POSITION_PARAM: new_pos,
self.END_POSITION_PARAM: self._end_position}
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement attribute identifier identifier block expression_statement augmented_assignment identifier integer return_statement dictionary pair attribute identifier identifier attribute identifier identifier pair attribute identifier identifier identifier pair attribute identifier identifier attribute identifier identifier
|
Returns an json-compatible input shard spec for remaining inputs.
|
def witnesses(ctx):
t = [
[
"weight",
"account",
"signing_key",
"vote_id",
"url",
"total_missed",
"last_confirmed_block_num",
]
]
for witness in sorted(Witnesses(), key=lambda x: x.weight, reverse=True):
witness.refresh()
t.append(
[
"{:.2f}%".format(witness.weight * 100),
witness.account["name"],
witness["signing_key"],
witness["vote_id"],
witness["url"],
witness["total_missed"],
witness["last_confirmed_block_num"],
]
)
print_table(t)
|
module function_definition identifier parameters identifier block expression_statement assignment identifier list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end for_statement identifier call identifier argument_list call identifier argument_list keyword_argument identifier lambda lambda_parameters identifier attribute identifier identifier keyword_argument identifier true block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list list call attribute string string_start string_content string_end identifier argument_list binary_operator attribute identifier identifier integer subscript attribute identifier identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call identifier argument_list identifier
|
List witnesses and relevant information
|
def OnSelChanged(self, event):
item = event.GetItem()
obj = self.leftPanel.model.ItemToObject(item)
if isinstance(obj, compass.Survey):
l = [
'Survey Name: %s' % obj.name,
'Survey Date: %s' % obj.date,
'Comment: %s' % obj.comment,
'Team: %s' % ', '.join(obj.team),
'Surveyed Footage: %0.1f' % obj.length,
'',
]
l.extend([' '.join(['%s: %s' % (k,v) for (k,v) in shot.items()]) for shot in obj.shots])
self.display.SetLabel(str('\n'.join(l)))
else:
self.display.SetLabel('')
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier list binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier string string_start string_end expression_statement call attribute identifier identifier argument_list list_comprehension call attribute string string_start string_content string_end identifier argument_list list_comprehension binary_operator string string_start string_content string_end tuple identifier identifier for_in_clause tuple_pattern identifier identifier call attribute identifier identifier argument_list for_in_clause identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_end
|
Method called when selected item is changed
|
def select(self, *cluster_ids):
if cluster_ids and isinstance(cluster_ids[0], (tuple, list)):
cluster_ids = list(cluster_ids[0]) + list(cluster_ids[1:])
cluster_ids = self._keep_existing_clusters(cluster_ids)
self.cluster_view.select(cluster_ids)
|
module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement boolean_operator identifier call identifier argument_list subscript identifier integer tuple identifier identifier block expression_statement assignment identifier binary_operator call identifier argument_list subscript identifier integer call identifier argument_list subscript identifier slice integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier
|
Select a list of clusters.
|
def relation_to_intermediary(fk):
return Relation(
right_col=format_name(fk.parent.table.fullname),
left_col=format_name(fk._column_tokens[1]),
right_cardinality='?',
left_cardinality='*',
)
|
module function_definition identifier parameters identifier block return_statement call identifier argument_list keyword_argument identifier call identifier argument_list attribute attribute attribute identifier identifier identifier identifier keyword_argument identifier call identifier argument_list subscript attribute identifier identifier integer keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end
|
Transform an SQLAlchemy ForeignKey object to it's intermediary representation.
|
def _check_free_space(self):
def get_folder_size(path):
total_size = 0
for item in walk(path):
for file in item[2]:
try:
total_size = total_size + getsize(join(item[0], file))
except (OSError, PermissionError) as e:
self.log("error with file: " + join(item[0], file), e)
return total_size
for name, checkpoint in self.config.locations.items():
try:
stats = statvfs(checkpoint['location'])
except (OSError, PermissionError) as e:
self.log('Location unavailable:', name, e, type(e),
lvl=error, exc=True)
continue
free_space = stats.f_frsize * stats.f_bavail
used_space = get_folder_size(
checkpoint['location']
) / 1024.0 / 1024
self.log('Location %s uses %.2f MB' % (name, used_space))
if free_space < checkpoint['minimum']:
self.log('Short of free space on %s: %.2f MB left' % (
name, free_space / 1024.0 / 1024 / 1024),
lvl=warn)
|
module function_definition identifier parameters identifier block function_definition identifier parameters identifier block expression_statement assignment identifier integer for_statement identifier call identifier argument_list identifier block for_statement identifier subscript identifier integer block try_statement block expression_statement assignment identifier binary_operator identifier call identifier argument_list call identifier argument_list subscript identifier integer 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 string_end call identifier argument_list subscript identifier integer identifier identifier return_statement identifier for_statement pattern_list identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block try_statement block expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end except_clause as_pattern tuple identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier true continue_statement expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier binary_operator binary_operator call identifier argument_list subscript identifier string string_start string_content string_end float integer expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier if_statement comparison_operator identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier binary_operator binary_operator binary_operator identifier float integer integer keyword_argument identifier identifier
|
Checks used filesystem storage sizes
|
def write_defaults(self):
self.defaults.write()
self.reset_defaults(self.defaults.filename)
|
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier
|
Create default config file and reload.
|
def save(self):
if self.rater is not None:
self.rater.set('modified', datetime.now().isoformat())
xml = parseString(tostring(self.root))
with open(self.xml_file, 'w') as f:
f.write(xml.toxml())
|
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier call identifier argument_list call identifier argument_list attribute identifier identifier 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 call attribute identifier identifier argument_list
|
Save xml to file.
|
def adapt_meta(self, meta):
surge = meta.get('surge_confirmation')
href = surge.get('href')
surge_id = surge.get('surge_confirmation_id')
return href, surge_id
|
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 identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement expression_list identifier identifier
|
Convert meta from error response to href and surge_id attributes.
|
def parse_yaml_file(self, path):
with open(path, 'r') as fp:
data = yaml.safe_load(fp)
if not data:
return {}
def traverse(namespace, d):
cfg = {}
for key, val in d.items():
if isinstance(d[key], dict):
cfg.update(traverse(namespace + [key], d[key]))
else:
if not isinstance(val, str):
raise ConfigurationError(
'Invalid value %r in file %s: values must be double-quoted strings' % (
val, path
)
)
cfg['_'.join(namespace + [key]).upper()] = val
return cfg
return traverse([], data)
|
module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block return_statement dictionary function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list subscript identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list binary_operator identifier list identifier subscript identifier identifier else_clause block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment subscript identifier call attribute call attribute string string_start string_content string_end identifier argument_list binary_operator identifier list identifier identifier argument_list identifier return_statement identifier return_statement call identifier argument_list list identifier
|
Parse yaml file at ``path`` and return a dict.
|
def make(self):
if self._entry_point is None:
raise error.Error('Attempting to make deprecated env {}. (HINT: is there a newer registered version of this env?)'.format(self.id))
cls = load(self._entry_point)
env = cls(**self._kwargs)
env.spec = self
env = env.build(extra_wrappers=self._wrappers)
return env
|
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list dictionary_splat attribute identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier return_statement identifier
|
Instantiates an instance of the environment with appropriate kwargs
|
def prefixed(self, prefix):
old_prefix = self._prefix
if old_prefix is None:
self._prefix = prefix
else:
self._prefix = "{}{}".format(old_prefix, prefix)
yield self
self._prefix = old_prefix
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier identifier else_clause block expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement yield identifier expression_statement assignment attribute identifier identifier identifier
|
Context manager for parsing envvars with a common prefix.
|
def adjustMargins(self):
y = 0
height = 0
if self._titleLabel.text():
height += self._titleLabel.height() + 3
y += height
if self._subTitleLabel.text():
self._subTitleLabel.move(0, y)
height += self._subTitleLabel.height() + 3
self.setContentsMargins(0, height, 0, 0)
|
module function_definition identifier parameters identifier block expression_statement assignment identifier integer expression_statement assignment identifier integer if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement augmented_assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list integer expression_statement augmented_assignment identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list integer identifier expression_statement augmented_assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list integer identifier integer integer
|
Adjusts the margins to incorporate enough room for the widget's title and sub-title.
|
def style(self):
style = mapnik.Style()
rule = mapnik.Rule()
self._symbolizer = self.symbolizer()
rule.symbols.append(self._symbolizer)
style.rules.append(rule)
return style
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier
|
Returns a default Style.
|
def subscribe(self, subscription):
url = urljoin(self._url, '/subscriptions')
return subscription.post(url)
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier
|
Create the given `Subscription` for this existing account.
|
def _update_netrc(self, netrc_path, auth_token, account_email):
import re
record_end = '(\n\n|\n\w|$)'
heroku_regex = re.compile('(machine\sapi\.heroku\.com.*?\nmachine\sgit\.heroku\.com.*?)%s' % record_end, re.S)
netrc_text = open(netrc_path).read().strip()
new_heroku = 'machine api.heroku.com\n password %s\n login %s\n' % (auth_token, account_email)
new_heroku += 'machine git.heroku.com\n password %s\n login %s\n\n' % (auth_token, account_email)
heroku_search = heroku_regex.findall(netrc_text)
if heroku_search:
if re.match('\n\w', heroku_search[0][1]):
new_heroku = new_heroku[:-1]
new_heroku += heroku_search[0][1]
netrc_text = heroku_regex.sub(new_heroku, netrc_text)
else:
netrc_text += '\n\n' + new_heroku
with open(netrc_path, 'wt') as f:
f.write(netrc_text)
f.close()
return netrc_text
|
module function_definition identifier parameters identifier identifier identifier identifier block import_statement dotted_name identifier expression_statement assignment identifier string string_start string_content escape_sequence escape_sequence escape_sequence string_end expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end identifier attribute identifier identifier expression_statement assignment identifier call attribute call attribute call identifier argument_list identifier identifier argument_list identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence escape_sequence string_end tuple identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence string_end tuple identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block if_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end subscript subscript identifier integer integer block expression_statement assignment identifier subscript identifier slice unary_operator integer expression_statement augmented_assignment identifier subscript subscript identifier integer integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier else_clause block expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement identifier
|
a method to replace heroku login details in netrc file
|
def setMimeTypeByName(self, name):
" Guess the mime type "
mimetype = mimetypes.guess_type(name)[0]
if mimetype is not None:
self.mimetype = mimetypes.guess_type(name)[0].split(";")[0]
|
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier integer if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier subscript call attribute subscript call attribute identifier identifier argument_list identifier integer identifier argument_list string string_start string_content string_end integer
|
Guess the mime type
|
def load(template):
try:
data = load_json(template)
return data, "json"
except ValueError as e:
try:
data = load_yaml(template)
return data, "yaml"
except Exception:
raise e
|
module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier return_statement expression_list identifier string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier return_statement expression_list identifier string string_start string_content string_end except_clause identifier block raise_statement identifier
|
Try to guess the input format
|
def parse_options(cls, options):
if (not options.putty_select and not options.putty_ignore and
not options.putty_auto_ignore):
return
options._orig_select = options.select
options._orig_ignore = options.ignore
options.putty_select = Parser(options.putty_select)._rules
options.putty_ignore = Parser(options.putty_ignore)._rules
if options.putty_auto_ignore:
options.putty_ignore.append(AutoLineDisableRule())
options.ignore_code = functools.partial(
putty_ignore_code,
options,
)
options.report._ignore_code = options.ignore_code
|
module function_definition identifier parameters identifier identifier block if_statement parenthesized_expression boolean_operator boolean_operator not_operator attribute identifier identifier not_operator attribute identifier identifier not_operator attribute identifier identifier block return_statement expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier attribute call identifier argument_list attribute identifier identifier identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier
|
Parse options and activate `ignore_code` handler.
|
def shutdown(self):
self.stop_all_periodic_tasks()
for channel in self._bcm_sockets:
log.debug("Closing bcm socket for channel {}".format(channel))
bcm_socket = self._bcm_sockets[channel]
bcm_socket.close()
log.debug("Closing raw can socket")
self.socket.close()
|
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list
|
Stops all active periodic tasks and closes the socket.
|
def call_fn_name(token):
if token.attr is not None:
return '%s_%i' % (token.kind, token.attr)
else:
return '%s_0' % (token.kind)
|
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier else_clause block return_statement binary_operator string string_start string_content string_end parenthesized_expression attribute identifier identifier
|
Customize CALL_FUNCTION to add the number of positional arguments
|
def precompile_python_code(context: Context):
from compileall import compile_dir
kwargs = {}
if context.verbosity < 2:
kwargs['quiet'] = True
compile_dir(context.app.django_app_name, **kwargs)
|
module function_definition identifier parameters typed_parameter identifier type identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier dictionary if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end true expression_statement call identifier argument_list attribute attribute identifier identifier identifier dictionary_splat identifier
|
Pre-compiles python modules
|
def show_doc_from_name(mod_name, ft_name:str, doc_string:bool=True, arg_comments:dict={}, alt_doc_string:str=''):
"Show documentation for `ft_name`, see `show_doc`."
mod = import_mod(mod_name)
splits = str.split(ft_name, '.')
assert hasattr(mod, splits[0]), print(f"Module {mod_name} doesn't have a function named {splits[0]}.")
elt = getattr(mod, splits[0])
for i,split in enumerate(splits[1:]):
assert hasattr(elt, split), print(f"Class {'.'.join(splits[:i+1])} doesn't have a function named {split}.")
elt = getattr(elt, split)
show_doc(elt, doc_string, ft_name, arg_comments, alt_doc_string)
|
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier true typed_default_parameter identifier type identifier dictionary typed_default_parameter identifier type identifier string string_start string_end block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end assert_statement call identifier argument_list identifier subscript identifier integer call identifier argument_list string string_start string_content interpolation identifier string_content interpolation subscript identifier integer string_content string_end expression_statement assignment identifier call identifier argument_list identifier subscript identifier integer for_statement pattern_list identifier identifier call identifier argument_list subscript identifier slice integer block assert_statement call identifier argument_list identifier identifier call identifier argument_list string string_start string_content interpolation call attribute string string_start string_content string_end identifier argument_list subscript identifier slice binary_operator identifier integer string_content interpolation identifier string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call identifier argument_list identifier identifier identifier identifier identifier
|
Show documentation for `ft_name`, see `show_doc`.
|
def _createunbound(kls, **info):
if issubclass(kls, Bitfield):
nodetype = UnboundBitfieldNode
elif hasattr(kls, '_fields_'):
nodetype = UnboundStructureNode
elif issubclass(kls, ctypes.Array):
nodetype = UnboundArrayNode
else:
nodetype = UnboundSimpleNode
return nodetype(type=kls, **info)
|
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier elif_clause call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier identifier elif_clause call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier identifier return_statement call identifier argument_list keyword_argument identifier identifier dictionary_splat identifier
|
Create a new UnboundNode representing a given class.
|
def _cb_inform_sensor_status(self, msg):
timestamp = msg.arguments[0]
num_sensors = int(msg.arguments[1])
assert len(msg.arguments) == 2 + num_sensors * 3
for n in xrange(num_sensors):
name = msg.arguments[2 + n * 3]
status = msg.arguments[3 + n * 3]
value = msg.arguments[4 + n * 3]
self.update_sensor(name, timestamp, status, value)
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier integer assert_statement comparison_operator call identifier argument_list attribute identifier identifier binary_operator integer binary_operator identifier integer for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier subscript attribute identifier identifier binary_operator integer binary_operator identifier integer expression_statement assignment identifier subscript attribute identifier identifier binary_operator integer binary_operator identifier integer expression_statement assignment identifier subscript attribute identifier identifier binary_operator integer binary_operator identifier integer expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier
|
Update received for an sensor.
|
def example():
ldata = 200
degrees = np.arange(ldata+1, dtype=float)
degrees[0] = np.inf
power = degrees**(-1)
clm1 = pyshtools.SHCoeffs.from_random(power, exact_power=False)
clm2 = pyshtools.SHCoeffs.from_random(power, exact_power=True)
fig, ax = plt.subplots()
ax.plot(clm1.spectrum(unit='per_l'), label='Normal distributed power')
ax.plot(clm2.spectrum(unit='per_l'), label='Exact power')
ax.set(xscale='log', yscale='log', xlabel='degree l',
ylabel='power per degree l')
ax.grid(which='both')
ax.legend()
plt.show()
|
module function_definition identifier parameters block expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator identifier integer keyword_argument identifier identifier expression_statement assignment subscript identifier integer attribute identifier identifier expression_statement assignment identifier binary_operator identifier parenthesized_expression unary_operator integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier false expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier true expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list
|
Plot random phase and Gaussian random variable spectra.
|
def ds_cT(ds, x, y, xy_srs=wgs_srs):
ds_srs = get_ds_srs(ds)
mX = x
mY = y
if xy_srs is not None:
if not ds_srs.IsSame(xy_srs):
mX, mY, mZ = cT_helper(x, y, 0, xy_srs, ds_srs)
return mX, mY
|
module function_definition identifier parameters identifier identifier identifier default_parameter identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier identifier expression_statement assignment identifier identifier if_statement comparison_operator identifier none block if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier identifier integer identifier identifier return_statement expression_list identifier identifier
|
Convert input point coordinates to map coordinates that match input dataset
|
def _handle_errors(errors):
if not errors:
return
log_all = True
err_msg = "T2T: skipped importing {num_missing} data_generators modules."
print(err_msg.format(num_missing=len(errors)))
for module, err in errors:
err_str = str(err)
if not _is_import_err_msg(err_str, module):
print("From module %s" % module)
raise err
if log_all:
print("Did not import module: %s; Cause: %s" % (module, err_str))
|
module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement expression_statement assignment identifier true expression_statement assignment identifier string string_start string_content string_end expression_statement call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier call identifier argument_list identifier for_statement pattern_list identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator call identifier argument_list identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier raise_statement identifier if_statement identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier
|
Log out and possibly reraise errors during import.
|
def rewrite_exception(old_name, new_name):
try:
yield
except Exception as e:
msg = e.args[0]
msg = msg.replace(old_name, new_name)
args = (msg,)
if len(e.args) > 1:
args = args + e.args[1:]
e.args = args
raise
|
module function_definition identifier parameters identifier identifier block try_statement block expression_statement yield except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier subscript attribute identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier tuple identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier binary_operator identifier subscript attribute identifier identifier slice integer expression_statement assignment attribute identifier identifier identifier raise_statement
|
Rewrite the message of an exception.
|
def update_bgp_peer(self, bgp_peer_id, body=None):
return self.put(self.bgp_peer_path % bgp_peer_id, body=body)
|
module function_definition identifier parameters identifier identifier default_parameter identifier none block return_statement call attribute identifier identifier argument_list binary_operator attribute identifier identifier identifier keyword_argument identifier identifier
|
Update a BGP peer.
|
def cli(env, identifier):
mgr = SoftLayer.NetworkManager(env.client)
global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier,
name='global ip')
mgr.unassign_global_ip(global_ip_id)
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier
|
Unassigns a global IP from a target.
|
def _pack_cwl(unpacked_cwl):
out_file = "%s-pack%s" % os.path.splitext(unpacked_cwl)
cmd = "cwltool --pack {unpacked_cwl} > {out_file}"
_run_tool(cmd.format(**locals()))
return out_file
|
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier string string_start string_content string_end expression_statement call identifier argument_list call attribute identifier identifier argument_list dictionary_splat call identifier argument_list return_statement identifier
|
Pack CWL into a single document for submission.
|
def to_jd2(year, month, day):
legal_date(year, month, day)
if month <= 2:
year = year - 1
month = month + 12
a = floor(year / 100)
b = floor(a / 4)
c = 2 - a + b
e = floor(365.25 * (year + 4716))
f = floor(30.6001 * (month + 1))
return c + day + e + f - 1524.5
|
module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list identifier identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier call identifier argument_list binary_operator identifier integer expression_statement assignment identifier call identifier argument_list binary_operator identifier integer expression_statement assignment identifier binary_operator binary_operator integer identifier identifier expression_statement assignment identifier call identifier argument_list binary_operator float parenthesized_expression binary_operator identifier integer expression_statement assignment identifier call identifier argument_list binary_operator float parenthesized_expression binary_operator identifier integer return_statement binary_operator binary_operator binary_operator binary_operator identifier identifier identifier identifier float
|
Gregorian to Julian Day Count for years between 1801-2099
|
def _write_avg_gradient(self)->None:
"Writes the average of the gradients to Tensorboard."
avg_gradient = sum(x.data.mean() for x in self.gradients)/len(self.gradients)
self._add_gradient_scalar('avg_gradient', scalar_value=avg_gradient)
|
module function_definition identifier parameters identifier type none block expression_statement string string_start string_content string_end expression_statement assignment identifier binary_operator call identifier generator_expression call attribute attribute identifier identifier identifier argument_list for_in_clause identifier attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier
|
Writes the average of the gradients to Tensorboard.
|
def prt_summary(self, prt=sys.stdout):
desc = "NtGoeaResults" if self.is_goterm else "namedtuple"
prt.write("{N} GOEA results from {O}. P-values stored in {P}.\n".format(
N=len(self.go2res), O=desc, P=self.pval_name))
|
module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list keyword_argument identifier call identifier argument_list attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier
|
Print summary of GOEA plotting object.
|
def refactor(self, items, write=False, doctests_only=False):
for dir_or_file in items:
if os.path.isdir(dir_or_file):
self.refactor_dir(dir_or_file, write, doctests_only)
else:
self.refactor_file(dir_or_file, write, doctests_only)
|
module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false block for_statement identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier identifier identifier
|
Refactor a list of files and directories.
|
def add_partition(self, partition):
assert(partition not in self._partitions)
self._partitions.add(partition)
partition.add_replica(self)
|
module function_definition identifier parameters identifier identifier block assert_statement parenthesized_expression comparison_operator identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier
|
Add partition to partition list.
|
def share_with_names(self):
for container in self.share_with:
if isinstance(container, six.string_types):
yield container
else:
yield container.container_name
|
module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement yield identifier else_clause block expression_statement yield attribute identifier identifier
|
The names of the containers that we share with the running container
|
def CreateEventMetadata(metric_name,
bins=None,
fields=None,
docstring=None,
units=None):
return rdf_stats.MetricMetadata(
varname=metric_name,
bins=bins or [],
metric_type=rdf_stats.MetricMetadata.MetricType.EVENT,
value_type=rdf_stats.MetricMetadata.ValueType.DISTRIBUTION,
fields_defs=FieldDefinitionProtosFromTuples(fields or []),
docstring=docstring,
units=units)
|
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier boolean_operator identifier list keyword_argument identifier attribute attribute attribute identifier identifier identifier identifier keyword_argument identifier attribute attribute attribute identifier identifier identifier identifier keyword_argument identifier call identifier argument_list boolean_operator identifier list keyword_argument identifier identifier keyword_argument identifier identifier
|
Helper function for creating MetricMetadata for event metrics.
|
def search(self):
matches = []
for pattern in Config.patterns:
matches += self.termfinder(pattern)
return sorted(set(matches), key=int)
|
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list call identifier argument_list identifier keyword_argument identifier identifier
|
Search srt in project for cells matching list of terms.
|
def apply(self, axes="gca"):
if axes == "gca": axes = _pylab.gca()
self.reset()
lines = axes.get_lines()
for l in lines:
l.set_color(self.get_line_color(1))
l.set_mfc(self.get_face_color(1))
l.set_marker(self.get_marker(1))
l.set_mec(self.get_edge_color(1))
l.set_linestyle(self.get_linestyle(1))
_pylab.draw()
|
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier 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 expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list
|
Applies the style cycle to the lines in the axes specified
|
def observe_scanner(self, scanner):
scanner.observe(scanner.ALL_EVENTS,
self.absorb_args(self.modules.restore))
if self.clear:
scanner.observe(scanner.ALL_EVENTS,
self.absorb_args(self.clear_on_run))
scanner.observe(scanner.ALL_EVENTS, self.absorb_args(self._run))
if self.debug:
scanner.observe('created', echo("callback - created %(file)s"))
scanner.observe('modified', echo("callback - changed %(file)s"))
scanner.observe('deleted', echo("callback - deleted %(file)s"))
self._scanners.append(scanner)
|
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call 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 call 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 call identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier
|
Hooks into multiple events of a scanner.
|
def converged(self):
return (self.iter == self.n_iter or
(len(self.history) == 2 and
self.history[1] - self.history[0] < self.tol))
|
module function_definition identifier parameters identifier block return_statement parenthesized_expression boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier parenthesized_expression boolean_operator comparison_operator call identifier argument_list attribute identifier identifier integer comparison_operator binary_operator subscript attribute identifier identifier integer subscript attribute identifier identifier integer attribute identifier identifier
|
``True`` if the EM algorithm converged and ``False`` otherwise.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.