code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def initialize():
app = qapplication()
app.setWindowIcon(APP_ICON)
class FakeQApplication(QApplication):
def __init__(self, args):
self = app
@staticmethod
def exec_():
pass
from qtpy import QtWidgets
QtWidgets.QApplication = FakeQApplication
def fake_sys_exit(arg=[]):
pass
sys.exit = fake_sys_exit
if PYQT5:
def spy_excepthook(type_, value, tback):
sys.__excepthook__(type_, value, tback)
sys.excepthook = spy_excepthook
sys.argv = ['']
try:
from enthought.etsconfig.api import ETSConfig
ETSConfig.toolkit = 'qt4'
except ImportError:
pass
return app | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier class_definition identifier argument_list identifier block function_definition identifier parameters identifier identifier block expression_statement assignment identifier identifier decorated_definition decorator identifier function_definition identifier parameters block pass_statement import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment attribute identifier identifier identifier function_definition identifier parameters default_parameter identifier list block pass_statement expression_statement assignment attribute identifier identifier identifier if_statement identifier block function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier list string string_start string_end try_statement block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment attribute identifier identifier string string_start string_content string_end except_clause identifier block pass_statement return_statement identifier | Initialize Qt, patching sys.exit and eventually setting up ETS |
def _npiter(arr):
for a in np.nditer(arr, flags=["refs_ok"]):
c = a.item()
if c is not None:
yield c | module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list identifier keyword_argument identifier list string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement yield identifier | Wrapper for iterating numpy array |
def crude_tokenizer(line):
tokens = []
buffer = ''
for c in line.strip():
if c == ' ' or c in string.punctuation:
if buffer:
tokens.append(buffer)
buffer = ''
else:
buffer += c
if buffer: tokens.append(buffer)
return tokens | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier string string_start string_end for_statement identifier call attribute identifier identifier argument_list block if_statement boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier attribute identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier string string_start string_end else_clause block expression_statement augmented_assignment identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | This is a very crude tokenizer from pynlpl |
def tdecode(pkt, *args):
if not args:
args = [ "-V" ]
fname = get_temp_file()
wrpcap(fname,[pkt])
subprocess.call(["tshark", "-r", fname] + list(args)) | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement not_operator identifier block expression_statement assignment identifier list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement call identifier argument_list identifier list identifier expression_statement call attribute identifier identifier argument_list binary_operator list string string_start string_content string_end string string_start string_content string_end identifier call identifier argument_list identifier | Run tshark to decode and display the packet. If no args defined uses -V |
def convertfields(key_comm, obj, inblock=None):
convinidd = ConvInIDD()
if not inblock:
inblock = ['does not start with N'] * len(obj)
for i, (f_comm, f_val, f_iddname) in enumerate(zip(key_comm, obj, inblock)):
if i == 0:
pass
else:
obj[i] = convertafield(f_comm, f_val, f_iddname)
return obj | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list if_statement not_operator identifier block expression_statement assignment identifier binary_operator list string string_start string_content string_end call identifier argument_list identifier for_statement pattern_list identifier tuple_pattern identifier identifier identifier call identifier argument_list call identifier argument_list identifier identifier identifier block if_statement comparison_operator identifier integer block pass_statement else_clause block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier identifier return_statement identifier | convert based on float, integer, and A1, N1 |
def __add_symbols(self, cmd):
if self.__config.define_symbols:
symbols = self.__config.define_symbols
cmd.append(''.join(
[' -D"%s"' % def_symbol for def_symbol in symbols]))
if self.__config.undefine_symbols:
un_symbols = self.__config.undefine_symbols
cmd.append(''.join(
[' -U"%s"' % undef_symbol for undef_symbol in un_symbols]))
return cmd | module function_definition identifier parameters identifier identifier block if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_end identifier argument_list list_comprehension binary_operator string string_start string_content string_end identifier for_in_clause identifier identifier if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_end identifier argument_list list_comprehension binary_operator string string_start string_content string_end identifier for_in_clause identifier identifier return_statement identifier | Add all additional defined and undefined symbols. |
def _format_sha1(graph, node):
try:
submodules = node.submodules
if submodules:
submodule = ':'.join(submodules)
return click.style(submodule, fg='green') + '@' + click.style(
node.commit.hexsha[:8], fg='yellow'
)
except KeyError:
pass
return click.style(node.commit.hexsha[:8], fg='yellow') | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement binary_operator binary_operator call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list subscript attribute attribute identifier identifier identifier slice integer keyword_argument identifier string string_start string_content string_end except_clause identifier block pass_statement return_statement call attribute identifier identifier argument_list subscript attribute attribute identifier identifier identifier slice integer keyword_argument identifier string string_start string_content string_end | Return formatted text with the submodule information. |
def build_java_docs(app):
java_path = app.builder.srcdir + '/../scala-package'
java_doc_sources = 'find . -type f -name "*.scala" | egrep \"\.\/core|\.\/infer\" | egrep \"\/javaapi\" | egrep -v \"Suite\"'
java_doc_classpath = ':'.join([
'`find native -name "*.jar" | grep "target/lib/" | tr "\\n" ":" `',
'`find macros -name "*.jar" | tr "\\n" ":" `',
'`find core -name "*.jar" | tr "\\n" ":" `',
'`find infer -name "*.jar" | tr "\\n" ":" `'
])
_run_cmd('cd {}; scaladoc `{}` -classpath {} -feature -deprecation'
.format(java_path, java_doc_sources, java_doc_classpath))
dest_path = app.builder.outdir + '/api/java/docs'
_run_cmd('rm -rf ' + dest_path)
_run_cmd('mkdir -p ' + dest_path)
javadocs = ['index', 'index.html', 'org', 'lib', 'index.js', 'package.html']
for doc_file in javadocs:
_run_cmd('cd ' + java_path + ' && mv -f ' + doc_file + ' ' + dest_path + '; exit 0') | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence escape_sequence escape_sequence string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list 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 string string_start string_content escape_sequence string_end expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier expression_statement assignment identifier binary_operator attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement call identifier argument_list binary_operator binary_operator binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end identifier string string_start string_content string_end identifier string string_start string_content string_end | build java docs and then move the outdir |
def format(self, record):
message_dict = {}
if isinstance(record.msg, dict):
message_dict = record.msg
record.message = None
else:
record.message = record.getMessage()
if "asctime" in self._required_fields:
record.asctime = self.formatTime(record, self.datefmt)
if record.exc_info and not message_dict.get('exc_info'):
message_dict['exc_info'] = self.formatException(record.exc_info)
if not message_dict.get('exc_info') and record.exc_text:
message_dict['exc_info'] = record.exc_text
try:
if record.stack_info and not message_dict.get('stack_info'):
message_dict['stack_info'] = self.formatStack(record.stack_info)
except AttributeError:
pass
try:
log_record = OrderedDict()
except NameError:
log_record = {}
self.add_fields(log_record, record, message_dict)
log_record = self.process_log_record(log_record)
return "%s%s" % (self.prefix, self.jsonify_log_record(log_record)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement call identifier argument_list attribute identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier none else_clause block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier attribute identifier identifier if_statement boolean_operator attribute identifier identifier not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier if_statement boolean_operator not_operator call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier try_statement block if_statement boolean_operator attribute identifier identifier not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier except_clause identifier block pass_statement try_statement block expression_statement assignment identifier call identifier argument_list except_clause identifier block expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement binary_operator string string_start string_content string_end tuple attribute identifier identifier call attribute identifier identifier argument_list identifier | Formats a log record and serializes to json |
def dump(self):
print("Relation " + self.relation)
print(" With attributes")
for n in self.attributes:
if self.attribute_types[n] != TYPE_NOMINAL:
print(" %s of type %s" % (n, self.attribute_types[n]))
else:
print(" " + n + " of type nominal with values " + ', '.join(self.attribute_data[n]))
for d in self.data:
print(d) | module function_definition identifier parameters identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end for_statement identifier attribute identifier identifier block if_statement comparison_operator subscript attribute identifier identifier identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier subscript attribute identifier identifier identifier else_clause block expression_statement call identifier argument_list binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list subscript attribute identifier identifier identifier for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list identifier | Print an overview of the ARFF file. |
def write_packets(self):
while self.running:
if len(self.write_queue) > 0:
self.write_queue[0].send(self.client)
self.write_queue.pop(0) | module function_definition identifier parameters identifier block while_statement attribute identifier identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute subscript attribute identifier identifier integer identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list integer | Write packets from the queue |
def format_additional_features_server_configurations(result):
from collections import OrderedDict
order_dict = OrderedDict()
if result.is_rservices_enabled is not None:
order_dict['isRServicesEnabled'] = result.is_rservices_enabled
if result.backup_permissions_for_azure_backup_svc is not None:
order_dict['backupPermissionsForAzureBackupSvc'] = result.backup_permissions_for_azure_backup_svc
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 if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement identifier | Formats the AdditionalFeaturesServerConfigurations object removing arguments that are empty |
def args(parsed_args, name=None):
strings = parsed_args.arg_strings(name)
files = [s for s in strings if os.path.isfile(s)]
if files:
streams = [open(f) for f in files]
else:
streams = []
if getattr(parsed_args, 'paste', not files):
streams.append(clipboard_stream())
if getattr(parsed_args, 'stdin', False):
streams.append(sys.stdin)
elif not streams:
streams = [sys.stdin]
return streams | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause call attribute attribute identifier identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier else_clause block expression_statement assignment identifier list if_statement call identifier argument_list identifier string string_start string_content string_end not_operator identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list if_statement call identifier argument_list identifier string string_start string_content string_end false block expression_statement call attribute identifier identifier argument_list attribute identifier identifier elif_clause not_operator identifier block expression_statement assignment identifier list attribute identifier identifier return_statement identifier | Interpret parsed args to streams |
def process_all(self):
results = []
veto_info = []
while 1:
result, veto = self._process_batch()
if result is False: return False
if result is None: break
results.append(result)
veto_info += veto
result = self.combine_results(results)
if self.max_triggers_in_batch:
sort = result['snr'].argsort()[::-1][:self.max_triggers_in_batch]
for key in result:
result[key] = result[key][sort]
tmp = veto_info
veto_info = [tmp[i] for i in sort]
result = self._process_vetoes(result, veto_info)
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier list while_statement integer block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier false block return_statement false if_statement comparison_operator identifier none block break_statement expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement attribute identifier identifier block expression_statement assignment identifier subscript subscript call attribute subscript identifier string string_start string_content string_end identifier argument_list slice unary_operator integer slice attribute identifier identifier for_statement identifier identifier block expression_statement assignment subscript identifier identifier subscript subscript identifier identifier identifier expression_statement assignment identifier identifier expression_statement assignment identifier list_comprehension subscript identifier identifier for_in_clause identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier | Process every batch group and return as single result |
def create_path_env_var(new_entries, env=None, env_var='PATH', delimiter=':', prepend=False):
if env is None:
env = {}
prev_path = env.get(env_var, None)
if prev_path is None:
path_dirs = list()
else:
path_dirs = list(prev_path.split(delimiter))
new_entries_list = list(new_entries)
if prepend:
path_dirs = new_entries_list + path_dirs
else:
path_dirs += new_entries_list
return delimiter.join(path_dirs) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier false block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list identifier none if_statement comparison_operator identifier none 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 expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier binary_operator identifier identifier else_clause block expression_statement augmented_assignment identifier identifier return_statement call attribute identifier identifier argument_list identifier | Join path entries, combining with an environment variable if specified. |
def transfer_request_notifications(user):
orgs = [o for o in user.organizations if o.is_member(user)]
notifications = []
qs = Transfer.objects(recipient__in=[user] + orgs, status='pending')
qs = qs.only('id', 'created', 'subject')
for transfer in qs.no_dereference():
notifications.append((transfer.created, {
'id': transfer.id,
'subject': {
'class': transfer.subject['_cls'].lower(),
'id': transfer.subject['_ref'].id
}
}))
return notifications | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause call attribute identifier identifier argument_list identifier expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier binary_operator list identifier identifier keyword_argument 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 string string_start string_content string_end string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list tuple attribute identifier identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end dictionary pair string string_start string_content string_end call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list pair string string_start string_content string_end attribute subscript attribute identifier identifier string string_start string_content string_end identifier return_statement identifier | Notify user about pending transfer requests |
def __access(self, ts):
with self.connection:
self.connection.execute("INSERT OR REPLACE INTO access_timestamp (timestamp, domain) VALUES (?, ?)",
(ts, self.domain)) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end tuple identifier attribute identifier identifier | Record an API access. |
def main():
if "--help" in sys.argv or "-h" in sys.argv or len(sys.argv) > 3:
raise SystemExit(__doc__)
try:
discordian_calendar(*sys.argv[1:])
except ValueError as error:
raise SystemExit("Error: {}".format("\n".join(error.args))) | module function_definition identifier parameters block if_statement boolean_operator 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 comparison_operator call identifier argument_list attribute identifier identifier integer block raise_statement call identifier argument_list identifier try_statement block expression_statement call identifier argument_list list_splat subscript attribute identifier identifier slice integer except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list attribute identifier identifier | Command line entry point for dcal. |
def format_sql_storage_update_settings(result):
from collections import OrderedDict
order_dict = OrderedDict()
if result.disk_count is not None:
order_dict['diskCount'] = result.disk_count
if result.disk_configuration_type is not None:
order_dict['diskConfigurationType'] = result.disk_configuration_type
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 if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement identifier | Formats the SqlStorageUpdateSettings object removing arguments that are empty |
def sort_data(data, cols):
return data.sort_values(cols)[cols + ['value']].reset_index(drop=True) | module function_definition identifier parameters identifier identifier block return_statement call attribute subscript call attribute identifier identifier argument_list identifier binary_operator identifier list string string_start string_content string_end identifier argument_list keyword_argument identifier true | Sort `data` rows and order columns |
def build_benchmark_plugin(name: str) -> LaserPlugin:
from mythril.laser.ethereum.plugins.implementations.benchmark import (
BenchmarkPlugin,
)
return BenchmarkPlugin(name) | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block import_from_statement dotted_name identifier identifier identifier identifier identifier identifier dotted_name identifier return_statement call identifier argument_list identifier | Creates an instance of the benchmark plugin with the given name |
def _canonical_int(self, interface):
if self.use_canonical_interface is True:
return napalm.base.helpers.canonical_interface_name(
interface, addl_name_map=None
)
else:
return interface | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier true block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier keyword_argument identifier none else_clause block return_statement identifier | Expose the helper function within this class. |
def write(self, client):
assert(isinstance(self._bytearray, DB))
assert(self.row_size >= 0)
db_nr = self._bytearray.db_number
offset = self.db_offset
data = self.get_bytearray()[offset:offset+self.row_size]
db_offset = self.db_offset
if self.row_offset:
data = data[self.row_offset:]
db_offset += self.row_offset
client.db_write(db_nr, db_offset, data) | module function_definition identifier parameters identifier identifier block assert_statement parenthesized_expression call identifier argument_list attribute identifier identifier identifier assert_statement parenthesized_expression comparison_operator attribute identifier identifier integer expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list slice identifier binary_operator identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier subscript identifier slice attribute identifier identifier expression_statement augmented_assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier | Write current data to db in plc |
def safe_call(cls, method, *args):
return cls.call(method, *args, safe=True) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block return_statement call attribute identifier identifier argument_list identifier list_splat identifier keyword_argument identifier true | Call a remote api method but don't raise if an error occurred. |
def load_config(path=None):
head_sha = get_sha1_from("HEAD")
revision = head_sha
saved_config_path = load_val_from_git_cfg("config_path")
if not path and saved_config_path is not None:
path = saved_config_path
if path is None:
path = find_config(revision=revision)
else:
if ":" not in path:
path = f"{head_sha}:{path}"
revision, _col, _path = path.partition(":")
if not revision:
revision = head_sha
config = DEFAULT_CONFIG
if path is not None:
config_text = from_git_rev_read(path)
d = toml.loads(config_text)
config = config.new_child(d)
return path, config | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement boolean_operator not_operator identifier comparison_operator identifier none block expression_statement assignment identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier else_clause block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier string string_start interpolation identifier string_content interpolation identifier string_end expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier identifier expression_statement assignment identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier | Choose and return the config path and it's contents as dict. |
def read(path, saltenv='base'):
ret = []
files = find(path, saltenv)
for fn_ in files:
full = next(six.iterkeys(fn_))
form = fn_[full]
if form == 'txt':
with salt.utils.files.fopen(full, 'rb') as fp_:
ret.append(
{full: salt.utils.stringutils.to_unicode(fp_.read())}
)
return ret | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list identifier identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block with_statement with_clause with_item as_pattern call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list dictionary pair identifier call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier | Read the contents of a text file, if the file is binary then |
def gateway(self):
url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway'
response = requests.get(url, headers=self._headers())
response.raise_for_status()
return response.json() | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list | Return the detail of the gateway. |
def generate_type_validator(type_, **kwargs):
if is_non_string_iterable(type_):
types = tuple(type_)
else:
types = (type_,)
if kwargs.get('x-nullable', False) and NULL not in types:
types = types + (NULL,)
return functools.partial(validate_type, types=types) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier tuple identifier if_statement boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end false comparison_operator identifier identifier block expression_statement assignment identifier binary_operator identifier tuple identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | Generates a callable validator for the given type or iterable of types. |
def rescue(env, identifier):
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
if not (env.skip_confirmations or
formatting.confirm("This action will reboot this VSI. Continue?")):
raise exceptions.CLIAbort('Aborted')
vsi.rescue(vs_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 string string_start string_content string_end if_statement not_operator parenthesized_expression boolean_operator attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | Reboot into a rescue image. |
def _reset(self):
self._in_declare = False
self._is_create = False
self._begin_depth = 0
self.consume_ws = False
self.tokens = []
self.level = 0 | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier integer | Set the filter attributes to its default values |
def uand(self):
return reduce(operator.and_, self._items, self.ftype.box(1)) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier call attribute attribute identifier identifier identifier argument_list integer | Unary AND reduction operator |
def _get_last_worker_died(self):
for service_id in list(self._running_services.keys()):
processes = list(self._running_services[service_id].items())
for process, worker_id in processes:
if not process.is_alive():
self._run_hooks('dead_worker', service_id, worker_id,
process.exitcode)
if process.exitcode < 0:
sig = _utils.signal_to_name(process.exitcode)
LOG.info('Child %(pid)d killed by signal %(sig)s',
dict(pid=process.pid, sig=sig))
else:
LOG.info('Child %(pid)d exited with status %(code)d',
dict(pid=process.pid, code=process.exitcode))
del self._running_services[service_id][process]
return service_id, worker_id | module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list call attribute subscript attribute identifier identifier identifier identifier argument_list for_statement pattern_list identifier identifier identifier block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier delete_statement subscript subscript attribute identifier identifier identifier identifier return_statement expression_list identifier identifier | Return the last died worker information or None |
def get(self, block=True, timeout=None):
return self._queue.get(block, timeout) | module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier none block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Get item from underlying queue. |
def _gen_jid(cur):
jid = salt.utils.jid.gen_jid(__opts__)
sql =
cur.execute(sql, (jid,))
data = cur.fetchall()
if not data:
return jid
return None | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier tuple identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block return_statement identifier return_statement none | Generate an unique job id |
def define_passive_branch_flows_with_kirchhoff(network,snapshots,skip_vars=False):
for sub_network in network.sub_networks.obj:
find_tree(sub_network)
find_cycles(sub_network)
find_bus_controls(sub_network)
if len(sub_network.branches_i()) > 0:
calculate_B_H(sub_network)
passive_branches = network.passive_branches()
if not skip_vars:
network.model.passive_branch_p = Var(list(passive_branches.index), snapshots)
cycle_index = []
cycle_constraints = {}
for subnetwork in network.sub_networks.obj:
branches = subnetwork.branches()
attribute = "r_pu_eff" if network.sub_networks.at[subnetwork.name,"carrier"] == "DC" else "x_pu_eff"
sub_network_cycle_index, sub_network_cycle_constraints = define_sub_network_cycle_constraints( subnetwork,
snapshots,
network.model.passive_branch_p, attribute)
cycle_index.extend( sub_network_cycle_index)
cycle_constraints.update( sub_network_cycle_constraints)
l_constraint(network.model, "cycle_constraints", cycle_constraints,
cycle_index, snapshots) | module function_definition identifier parameters identifier identifier default_parameter identifier false block for_statement identifier attribute attribute identifier identifier identifier block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier if_statement comparison_operator call identifier argument_list call attribute identifier identifier argument_list integer block expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment attribute attribute identifier identifier identifier call identifier argument_list call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier list expression_statement assignment identifier dictionary for_statement identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator subscript attribute attribute identifier identifier identifier attribute identifier identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier attribute attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end identifier identifier identifier | define passive branch flows with the kirchoff method |
def integer(self, x):
if type(x) is str:
hex = binascii.unhexlify(x)
return int.from_bytes(hex, 'big')
return x.value if isinstance(x, FiniteField.Value) else x | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end return_statement conditional_expression attribute identifier identifier call identifier argument_list identifier attribute identifier identifier identifier | returns a plain integer |
def _get_module_name_from_fname(fname):
fname = fname.replace(".pyc", ".py")
for mobj in sys.modules.values():
if (
hasattr(mobj, "__file__")
and mobj.__file__
and (mobj.__file__.replace(".pyc", ".py") == fname)
):
module_name = mobj.__name__
return module_name
raise RuntimeError("Module could not be found") | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement parenthesized_expression boolean_operator boolean_operator call identifier argument_list identifier string string_start string_content string_end attribute identifier identifier parenthesized_expression comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier block expression_statement assignment identifier attribute identifier identifier return_statement identifier raise_statement call identifier argument_list string string_start string_content string_end | Get module name from module file name. |
def close(self):
for handle in self._handles:
if not handle.closed:
handle.close()
del self._handles[:]
for transport, _ in self.connections:
transport.close()
self._all_closed.wait() | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list delete_statement subscript attribute identifier identifier slice for_statement pattern_list identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list | Close the listening sockets and all accepted connections. |
def formatTime(self, record, datefmt=None):
formatted = super(PalletFormatter, self).formatTime(
record, datefmt=datefmt)
return formatted + '.%03dZ' % record.msecs | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier keyword_argument identifier identifier return_statement binary_operator identifier binary_operator string string_start string_content string_end attribute identifier identifier | Format time, including milliseconds. |
async def send_event(self, client_id, service_name, event_name, event_info, directed_client=None):
if directed_client is not None and directed_client != client_id:
return
client_info = self.clients.get(client_id)
if client_info is None:
self._logger.warning("Attempted to send event to invalid client id: %s", client_id)
return
conn = client_info['connection']
event = dict(service=service_name)
if event_info is not None:
event['payload'] = event_info
self._logger.debug("Sending event: %s", event)
await self.server.send_event(conn, event_name, event) | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none block if_statement boolean_operator comparison_operator identifier none comparison_operator identifier identifier block return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier return_statement expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement await call attribute attribute identifier identifier identifier argument_list identifier identifier identifier | Send an event to a client. |
def ignore_directories(self, project):
project_list = False
try:
ignore_directories = il['ignore_directories']
except KeyError:
logger.error('Key Error processing ignore_directories list values')
try:
project_exceptions = il.get('project_exceptions')
for item in project_exceptions:
if project in item:
exception_file = item.get(project)
with open(exception_file, 'r') as f:
test_list = yaml.safe_load(f)
project_list = test_list['ignore_directories']
except KeyError:
logger.info('No ignore_directories for %s', project)
if project_list:
ignore_directories = ignore_directories + project_list
return ignore_directories
else:
return ignore_directories | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier false try_statement block expression_statement assignment identifier subscript identifier string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement identifier block expression_statement assignment identifier binary_operator identifier identifier return_statement identifier else_clause block return_statement identifier | Gathers a list of directories to ignore |
def signal_to_exception(signum, frame):
if signum == signal.SIGALRM:
raise SIGALRMException()
if signum == signal.SIGHUP:
raise SIGHUPException()
if signum == signal.SIGUSR1:
raise SIGUSR1Exception()
if signum == signal.SIGUSR2:
raise SIGUSR2Exception()
raise SignalException(signum) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list raise_statement call identifier argument_list identifier | Called by the timeout alarm during the collector run time |
def _FieldToJsonObject(self, field, value):
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return self._MessageToJsonObject(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
enum_value = field.enum_type.values_by_number.get(value, None)
if enum_value is not None:
return enum_value.name
else:
raise SerializeToJsonError('Enum field contains an integer value '
'which can not mapped to an enum value.')
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
return base64.b64encode(value).decode('utf-8')
else:
return value
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return bool(value)
elif field.cpp_type in _INT64_TYPES:
return str(value)
elif field.cpp_type in _FLOAT_TYPES:
if math.isinf(value):
if value < 0.0:
return _NEG_INFINITY
else:
return _INFINITY
if math.isnan(value):
return _NAN
return value | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block return_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier none if_statement comparison_operator identifier none block return_statement attribute identifier identifier else_clause block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end elif_clause comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block if_statement comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block return_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end else_clause block return_statement identifier elif_clause comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block return_statement call identifier argument_list identifier elif_clause comparison_operator attribute identifier identifier identifier block return_statement call identifier argument_list identifier elif_clause comparison_operator attribute identifier identifier identifier block if_statement call attribute identifier identifier argument_list identifier block if_statement comparison_operator identifier float block return_statement identifier else_clause block return_statement identifier if_statement call attribute identifier identifier argument_list identifier block return_statement identifier return_statement identifier | Converts field value according to Proto3 JSON Specification. |
def add(self, type):
try:
if isinstance(type, SetType):
if EMPTY_SET_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_SET_TYPE)
elif isinstance(type, ListType):
if EMPTY_LIST_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_LIST_TYPE)
elif isinstance(type, IteratorType):
if EMPTY_ITERATOR_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_ITERATOR_TYPE)
elif isinstance(type, DictType):
if EMPTY_DICT_TYPE in self.types_hashable:
self.types_hashable.remove(EMPTY_DICT_TYPE)
for item in self.types_hashable:
if isinstance(item, DictType):
if item.key_type == type.key_type:
item.val_type.merge(type.val_type)
return
self.types_hashable.add(type)
except (TypeError, AttributeError):
try:
if type not in self.types:
self.types.append(type)
except AttributeError:
if TypeWasIncomparable not in self.types:
self.types.append(TypeWasIncomparable) | module function_definition identifier parameters identifier identifier block try_statement block if_statement call identifier argument_list identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement expression_statement call attribute attribute identifier identifier identifier argument_list identifier except_clause tuple identifier identifier block try_statement block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Add type to the runtime type samples. |
def explain_weights_lightning(estimator, vec=None, top=20, target_names=None,
targets=None, feature_names=None,
coef_scale=None):
return explain_weights_lightning_not_supported(estimator) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier integer default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block return_statement call identifier argument_list identifier | Return an explanation of a lightning estimator weights |
def resizeTile(index, size):
resized = tiles[index].resize(size, Image.ANTIALIAS)
return sImage(resized.tostring(), resized.size, resized.mode) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute subscript identifier identifier identifier argument_list identifier attribute identifier identifier return_statement call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Apply Antialiasing resizing to tile |
def add_module_definition(self, module_definition):
if module_definition.identity not in self._module_definitions.keys():
self._module_definitions[module_definition.identity] = module_definition
else:
raise ValueError("{} has already been defined".format(module_definition.identity)) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment subscript attribute identifier identifier attribute identifier identifier identifier else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier | Add a ModuleDefinition to the document |
def sequences_to_string(self):
return {k: ''.join(self.states[v]) for (k, v) in self.sequences.items()} | module function_definition identifier parameters identifier block return_statement dictionary_comprehension pair identifier call attribute string string_start string_end identifier argument_list subscript attribute identifier identifier identifier for_in_clause tuple_pattern identifier identifier call attribute attribute identifier identifier identifier argument_list | Convert state indices to a string of characters |
def remove_html_tag(input_str='', tag=None):
result = input_str
if tag is not None:
pattern = re.compile('<{tag}[\s\S]+?/{tag}>'.format(tag=tag))
result = re.sub(pattern, '', str(input_str))
return result | module function_definition identifier parameters default_parameter identifier string string_start string_end default_parameter identifier none block expression_statement assignment identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_end call identifier argument_list identifier return_statement identifier | Returns a string with the html tag and all its contents from a string |
def calcHorizonPoints(self):
ydiff = math.tan(math.radians(-self.roll))*float(self.ratio)
pitchdiff = self.dist10deg*(self.pitch/10.0)
vertsTop = [(-self.ratio,ydiff-pitchdiff),(-self.ratio,1),(self.ratio,1),(self.ratio,-ydiff-pitchdiff),(-self.ratio,ydiff-pitchdiff)]
self.topPolygon.set_xy(vertsTop)
vertsBot = [(-self.ratio,ydiff-pitchdiff),(-self.ratio,-1),(self.ratio,-1),(self.ratio,-ydiff-pitchdiff),(-self.ratio,ydiff-pitchdiff)]
self.botPolygon.set_xy(vertsBot) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list unary_operator attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier float expression_statement assignment identifier list tuple unary_operator attribute identifier identifier binary_operator identifier identifier tuple unary_operator attribute identifier identifier integer tuple attribute identifier identifier integer tuple attribute identifier identifier binary_operator unary_operator identifier identifier tuple unary_operator attribute identifier identifier binary_operator identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier list tuple unary_operator attribute identifier identifier binary_operator identifier identifier tuple unary_operator attribute identifier identifier unary_operator integer tuple attribute identifier identifier unary_operator integer tuple attribute identifier identifier binary_operator unary_operator identifier identifier tuple unary_operator attribute identifier identifier binary_operator identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Updates the verticies of the patches for the ground and sky. |
def lookup_comments(self, reverse=False):
"Implement as required by parent to lookup comments in file system."
comments = []
if self.thread_id is None:
self.thread_id = self.lookup_thread_id()
path = self.thread_id
with open(self.thread_id, 'r', newline='') as fdesc:
reader = csv.reader(fdesc)
header = reader.__next__()
assert header == self.header
for num, line in enumerate(reader):
if not line:
continue
assert len(line) == len(header), (
'Line %i in path %s misformatted' % (num+1, path))
line_kw = dict(zip(header, line))
comments.append(SingleComment(**line_kw))
if reverse:
comments = list(reversed(comments))
return CommentSection(comments) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement string string_start string_content string_end expression_statement assignment identifier list if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier 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 keyword_argument identifier string string_start string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list assert_statement comparison_operator identifier attribute identifier identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement not_operator identifier block continue_statement assert_statement comparison_operator call identifier argument_list identifier call identifier argument_list identifier parenthesized_expression binary_operator string string_start string_content string_end tuple binary_operator identifier integer identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list dictionary_splat identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier return_statement call identifier argument_list identifier | Implement as required by parent to lookup comments in file system. |
def print_series_info(self, series_info, minimal_series_number=1):
strinfo = ''
if len(series_info) > minimal_series_number:
for serie_number in series_info.keys():
strl = get_one_serie_info(series_info, serie_number)
strinfo = strinfo + strl + '\n'
return strinfo | module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement assignment identifier string string_start string_end if_statement comparison_operator call identifier argument_list identifier identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier identifier string string_start string_content escape_sequence string_end return_statement identifier | Print series_info from dcmdirstats |
def truthtable2expr(tt, conj=False):
if conj:
outer, inner = (And, Or)
nums = tt.pcdata.iter_zeros()
else:
outer, inner = (Or, And)
nums = tt.pcdata.iter_ones()
inputs = [exprvar(v.names, v.indices) for v in tt.inputs]
terms = [boolfunc.num2term(num, inputs, conj) for num in nums]
return outer(*[inner(*term) for term in terms]) | module function_definition identifier parameters identifier default_parameter identifier false block if_statement identifier block expression_statement assignment pattern_list identifier identifier tuple identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement assignment pattern_list identifier identifier tuple identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier list_comprehension call identifier argument_list attribute identifier identifier attribute identifier identifier for_in_clause identifier attribute identifier identifier expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier identifier identifier for_in_clause identifier identifier return_statement call identifier argument_list list_splat list_comprehension call identifier argument_list list_splat identifier for_in_clause identifier identifier | Convert a truth table into an expression. |
def _server_begin_response_callback(self, response: Response):
self._item_session.response = response
if self._cookie_jar:
self._cookie_jar.extract_cookies(response, self._item_session.request)
action = self._result_rule.handle_pre_response(self._item_session)
self._file_writer_session.process_response(response)
return action == Actions.NORMAL | module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment attribute attribute identifier identifier identifier identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement comparison_operator identifier attribute identifier identifier | Pre-response callback handler. |
def print_tree(root, space=' '):
if isinstance(root, Leaf):
print(space + "Prediction: " + str(root.most_frequent))
return
print(space + str(root.question))
print(space + "--> True:")
print_tree(root.true_branch, space+' ')
print(space + "--> False:")
print_tree(root.false_branch, space+' ') | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block expression_statement call identifier argument_list binary_operator binary_operator identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier return_statement expression_statement call identifier argument_list binary_operator identifier call identifier argument_list attribute identifier identifier expression_statement call identifier argument_list binary_operator identifier string string_start string_content string_end expression_statement call identifier argument_list attribute identifier identifier binary_operator identifier string string_start string_content string_end expression_statement call identifier argument_list binary_operator identifier string string_start string_content string_end expression_statement call identifier argument_list attribute identifier identifier binary_operator identifier string string_start string_content string_end | Prints the Decision Tree in a pretty way. |
def start_thread(self, target, args=(), kwargs=None, priority=0):
return self.add_task(target, args, kwargs, priority) | module function_definition identifier parameters identifier identifier default_parameter identifier tuple default_parameter identifier none default_parameter identifier integer block return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier | To make sure applications work with the old name |
def backward(self, loss):
with mx.autograd.record():
if isinstance(loss, (tuple, list)):
ls = [l * self._scaler.loss_scale for l in loss]
else:
ls = loss * self._scaler.loss_scale
mx.autograd.backward(ls) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item call attribute attribute identifier identifier identifier argument_list block if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier list_comprehension binary_operator identifier attribute attribute identifier identifier identifier for_in_clause identifier identifier else_clause block expression_statement assignment identifier binary_operator identifier attribute attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | backward propagation with loss |
def _increment(self, *args):
value = self._var.get()
if self._resolution:
value = self._start + int(round((value - self._start) / self._resolution)) * self._resolution
self._var.set(value)
self.display_value(value) | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement attribute identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier binary_operator call identifier argument_list call identifier argument_list binary_operator parenthesized_expression binary_operator identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Move the slider only by increment given by resolution. |
def setup_block_and_grid(problem_size, grid_div, params, block_size_names=None):
threads = get_thread_block_dimensions(params, block_size_names)
current_problem_size = get_problem_size(problem_size, params)
grid = get_grid_dimensions(current_problem_size, params, grid_div, block_size_names)
return threads, grid | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier return_statement expression_list identifier identifier | compute problem size, thread block and grid dimensions for this kernel |
def histogram(self, column='r', filename=None, log10=False, **kwargs):
return_dict = HS.plot_histograms(self.data, column)
if filename is not None:
return_dict['all'].savefig(filename, dpi=300)
return return_dict | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier false dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier keyword_argument identifier integer return_statement identifier | Plot a histogram of one data column |
def lock(self, block=True):
self._locked = True
return self._lock.acquire(block) | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment attribute identifier identifier true return_statement call attribute attribute identifier identifier identifier argument_list identifier | Lock connection from being used else where |
def tune_pair(self, pair):
self._save_bm_state()
self.pair = pair
self.update_disparity_map() | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list | Tune a pair of images. |
def timecode(time_now, interval):
i = time.mktime(time_now.timetuple())
return int(i / interval) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement call identifier argument_list binary_operator identifier identifier | make integer and divide by time interval of valid OTP |
def _config_sortable(self, sortable):
for col in self["columns"]:
command = (lambda c=col: self._sort_column(c, True)) if sortable else ""
self.heading(col, command=command)
self._sortable = sortable | module function_definition identifier parameters identifier identifier block for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier conditional_expression parenthesized_expression lambda lambda_parameters default_parameter identifier identifier call attribute identifier identifier argument_list identifier true identifier string string_start string_end expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment attribute identifier identifier identifier | Configure a new sortable state |
def penn_to_wn(tag):
if tag.startswith('N'):
return 'n'
if tag.startswith('V'):
return 'v'
if tag.startswith('J'):
return 'a'
if tag.startswith('R'):
return 'r'
return None | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement string string_start string_content string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement string string_start string_content string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement string string_start string_content string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement string string_start string_content string_end return_statement none | Convert between a Penn Treebank tag to a simplified Wordnet tag |
def _toolkits_select_columns(dataset, columns):
try:
return dataset.select_columns(columns)
except RuntimeError:
missing_features = list(set(columns).difference(set(dataset.column_names())))
raise ToolkitError("Input data does not contain the following columns: " +
"{}".format(missing_features)) | module function_definition identifier parameters identifier identifier block try_statement block return_statement call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement assignment identifier call identifier argument_list call attribute call identifier argument_list identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list raise_statement call identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier | Same as select columns but redirect runtime error to ToolkitError. |
def request(self, method, resource, params=None):
url = self.get_url(resource, params)
headers = {
'Content-Type': 'application/json'
}
auth = requests.auth.HTTPBasicAuth(self.username, self.password)
log.info('Request to %s. Data: %s' % (url, params))
response = requests.request(method, url, data=json.dumps(params), headers=headers, auth=auth)
response.raise_for_status()
log.info('Response from %s: %s' % (url, response.text))
content = response.json()
self.parse_status(content.get('status'))
return content | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Make request to the server and parse response |
def string_to_identity(identity_str):
m = _identity_regexp.match(identity_str)
result = m.groupdict()
log.debug('parsed identity: %s', result)
return {k: v for k, v in result.items() if v} | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list if_clause identifier | Parse string into Identity dictionary. |
def make_input(self):
all_files ={"ddkfile_" + str(n + 1): ddk for n, ddk in enumerate(self.ddk_filepaths)}
all_files.update({"wfkfile": self.wfk_filepath})
files_nml = {"FILES": all_files}
files= nmltostring(files_nml)
user_file = nmltostring(self.input.as_dict())
return files + user_file | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary_comprehension pair binary_operator string string_start string_content string_end call identifier argument_list binary_operator identifier integer identifier for_in_clause pattern_list identifier identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list return_statement binary_operator identifier identifier | Construct and write the input file of the calculation. |
def handle_modifier_up(self, modifier):
_logger.debug("%s released", modifier)
if modifier not in (Key.CAPSLOCK, Key.NUMLOCK):
self.modifiers[modifier] = False | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier tuple attribute identifier identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier false | Updates the state of the given modifier key to 'released'. |
def confirm_operation(prompt, prefix=None, assume_yes=False, err=False):
if assume_yes:
return True
prefix = prefix or click.style(
"Are you %s certain you want to" % (click.style("absolutely", bold=True))
)
prompt = "%(prefix)s %(prompt)s?" % {"prefix": prefix, "prompt": prompt}
if click.confirm(prompt, err=err):
return True
click.echo(err=err)
click.secho("OK, phew! Close call. :-)", fg="green", err=err)
return False | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false default_parameter identifier false block if_statement identifier block return_statement true expression_statement assignment identifier boolean_operator identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true expression_statement assignment identifier binary_operator string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier block return_statement true expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement false | Prompt the user for confirmation for dangerous actions. |
def _cors_headers(self, environ):
if isinstance(self.cors_allowed_origins, six.string_types):
if self.cors_allowed_origins == '*':
allowed_origins = None
else:
allowed_origins = [self.cors_allowed_origins]
else:
allowed_origins = self.cors_allowed_origins
if allowed_origins is not None and \
environ.get('HTTP_ORIGIN', '') not in allowed_origins:
return []
if 'HTTP_ORIGIN' in environ:
headers = [('Access-Control-Allow-Origin', environ['HTTP_ORIGIN'])]
else:
headers = [('Access-Control-Allow-Origin', '*')]
if environ['REQUEST_METHOD'] == 'OPTIONS':
headers += [('Access-Control-Allow-Methods', 'OPTIONS, GET, POST')]
if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in environ:
headers += [('Access-Control-Allow-Headers',
environ['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])]
if self.cors_credentials:
headers += [('Access-Control-Allow-Credentials', 'true')]
return headers | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list attribute identifier identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier none else_clause block expression_statement assignment identifier list attribute identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier if_statement boolean_operator comparison_operator identifier none line_continuation comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier block return_statement list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier list tuple string string_start string_content string_end subscript identifier string string_start string_content string_end else_clause block expression_statement assignment identifier list tuple string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement augmented_assignment identifier list tuple string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement augmented_assignment identifier list tuple string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement attribute identifier identifier block expression_statement augmented_assignment identifier list tuple string string_start string_content string_end string string_start string_content string_end return_statement identifier | Return the cross-origin-resource-sharing headers. |
def _get_node(response, *ancestors):
document = response
for ancestor in ancestors:
if ancestor not in document:
return {}
else:
document = document[ancestor]
return document | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier identifier for_statement identifier identifier block if_statement comparison_operator identifier identifier block return_statement dictionary else_clause block expression_statement assignment identifier subscript identifier identifier return_statement identifier | Traverse tree to node |
def isgood(name):
if not isbad(name):
if name.endswith('.py') or name.endswith('.json') or name.endswith('.tar'):
return True
return False | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier block if_statement boolean_operator boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end block return_statement true return_statement false | Whether name should be installed |
def as_dict(self):
odict = OrderedDict()
for name in self._order:
attr_value = getattr(self, name)
if isinstance(attr_value, List):
_list = []
for item in attr_value:
_list.append((item.as_dict() if isinstance(item, Entity) else item))
odict[name] = _list
elif isinstance(attr_value, Entity):
odict[name] = attr_value.as_dict()
else:
odict[name] = getattr(self, name)
return odict | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list parenthesized_expression conditional_expression call attribute identifier identifier argument_list call identifier argument_list identifier identifier identifier expression_statement assignment subscript identifier identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier return_statement identifier | create a dict based on class attributes |
def find_function_by_name(self, name):
cfg_rv = None
for cfg in self._cfgs:
if cfg.name == name:
cfg_rv = cfg
break
return cfg_rv | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier identifier break_statement return_statement identifier | Return the cfg of the requested function by name. |
def color_interp(data):
from rasterio.enums import ColorInterp as ci
modes = {'L': [ci.gray],
'LA': [ci.gray, ci.alpha],
'YCbCr': [ci.Y, ci.Cb, ci.Cr],
'YCbCrA': [ci.Y, ci.Cb, ci.Cr, ci.alpha]}
try:
mode = ''.join(data['bands'].values)
return modes[mode]
except KeyError:
colors = {'R': ci.red,
'G': ci.green,
'B': ci.blue,
'A': ci.alpha,
'C': ci.cyan,
'M': ci.magenta,
'Y': ci.yellow,
'H': ci.hue,
'S': ci.saturation,
'L': ci.lightness,
'K': ci.black,
}
return [colors[band] for band in data['bands'].values] | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier aliased_import dotted_name identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end list attribute identifier identifier pair string string_start string_content string_end list attribute identifier identifier attribute identifier identifier pair string string_start string_content string_end list attribute identifier identifier attribute identifier identifier attribute identifier identifier pair string string_start string_content string_end list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier try_statement block expression_statement assignment identifier call attribute string string_start string_end identifier argument_list attribute subscript identifier string string_start string_content string_end identifier return_statement subscript identifier identifier except_clause identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier return_statement list_comprehension subscript identifier identifier for_in_clause identifier attribute subscript identifier string string_start string_content string_end identifier | Get the color interpretation for this image. |
def _update_schema_to_aws_notation(self, schema):
result = {}
for k, v in schema.items():
if k == '$ref':
v = self._aws_model_ref_from_swagger_ref(v)
if isinstance(v, dict):
v = self._update_schema_to_aws_notation(v)
result[k] = v
return result | module 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 comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier | Helper function to map model schema to aws notation |
def packet_loss(self):
if self.mav_count == 0:
return 0
return (100.0*self.mav_loss)/(self.mav_count+self.mav_loss) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier integer block return_statement integer return_statement binary_operator parenthesized_expression binary_operator float attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier attribute identifier identifier | packet loss as a percentage |
def _from_dict(cls, _dict):
args = {}
if 'environments' in _dict:
args['environments'] = [
Environment._from_dict(x) for x in (_dict.get('environments'))
]
return cls(**args) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list dictionary_splat identifier | Initialize a ListEnvironmentsResponse object from a json dictionary. |
def badRequestMethod(self, environ, start_response):
response = "400 Bad Request\n\nTo access this PyAMF gateway you " \
"must use POST requests (%s received)" % environ['REQUEST_METHOD']
start_response('400 Bad Request', [
('Content-Type', 'text/plain'),
('Content-Length', str(len(response))),
('Server', gateway.SERVER_NAME),
])
return [response] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator concatenated_string string string_start string_content escape_sequence escape_sequence string_end string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end list tuple string string_start string_content string_end string string_start string_content string_end tuple string string_start string_content string_end call identifier argument_list call identifier argument_list identifier tuple string string_start string_content string_end attribute identifier identifier return_statement list identifier | Return HTTP 400 Bad Request. |
def _process_gradient_args(f, kwargs):
axes = kwargs.get('axes', range(f.ndim))
def _check_length(positions):
if 'axes' in kwargs and len(positions) < len(axes):
raise ValueError('Length of "coordinates" or "deltas" cannot be less than that '
'of "axes".')
elif 'axes' not in kwargs and len(positions) != len(axes):
raise ValueError('Length of "coordinates" or "deltas" must match the number of '
'dimensions of "f" when "axes" is not given.')
if 'deltas' in kwargs:
if 'coordinates' in kwargs or 'x' in kwargs:
raise ValueError('Cannot specify both "coordinates" and "deltas".')
_check_length(kwargs['deltas'])
return 'delta', kwargs['deltas'], axes
elif 'coordinates' in kwargs:
_check_length(kwargs['coordinates'])
return 'x', kwargs['coordinates'], axes
elif 'x' in kwargs:
warnings.warn('The use of "x" as a parameter for coordinate values has been '
'deprecated. Use "coordinates" instead.', metpyDeprecation)
_check_length(kwargs['x'])
return 'x', kwargs['x'], axes
elif isinstance(f, xr.DataArray):
return 'pass', axes, axes
else:
raise ValueError('Must specify either "coordinates" or "deltas" for value positions '
'when "f" is not a DataArray.') | 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 call identifier argument_list attribute identifier identifier function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator call identifier argument_list identifier call identifier argument_list identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end elif_clause boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator call identifier argument_list identifier call identifier argument_list 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 comparison_operator string string_start string_content string_end identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list subscript identifier string string_start string_content string_end return_statement expression_list string string_start string_content string_end subscript identifier string string_start string_content string_end identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement call identifier argument_list subscript identifier string string_start string_content string_end return_statement expression_list string string_start string_content string_end subscript identifier string string_start string_content string_end identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end identifier expression_statement call identifier argument_list subscript identifier string string_start string_content string_end return_statement expression_list string string_start string_content string_end subscript identifier string string_start string_content string_end identifier elif_clause call identifier argument_list identifier attribute identifier identifier block return_statement expression_list string string_start string_content string_end identifier identifier else_clause block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end | Handle common processing of arguments for gradient and gradient-like functions. |
def _get_allowed_sections(self, dashboard):
allowed_titles = [x[0] for x in dashboard]
allowed_sections = [x[2] for x in dashboard]
return tuple(allowed_sections), tuple(allowed_titles) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension subscript identifier integer for_in_clause identifier identifier expression_statement assignment identifier list_comprehension subscript identifier integer for_in_clause identifier identifier return_statement expression_list call identifier argument_list identifier call identifier argument_list identifier | Get the sections to display based on dashboard |
def _get_selected_item(self):
selection = self.get_selection()
if selection.get_mode() != gtk.SELECTION_SINGLE:
raise AttributeError('selected_item not valid for select_multiple')
model, selected = selection.get_selected()
if selected is not None:
return self._object_at_sort_iter(selected) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator call attribute identifier identifier argument_list attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block return_statement call attribute identifier identifier argument_list identifier | The currently selected item |
def _constraint_lb_and_ub_to_gurobi_sense_rhs_and_range_value(lb, ub):
if lb is None and ub is None:
raise Exception("Free constraint ...")
elif lb is None:
sense = '<'
rhs = float(ub)
range_value = 0.
elif ub is None:
sense = '>'
rhs = float(lb)
range_value = 0.
elif lb == ub:
sense = '='
rhs = float(lb)
range_value = 0.
elif lb > ub:
raise ValueError("Lower bound is larger than upper bound.")
else:
sense = '='
rhs = float(lb)
range_value = float(ub - lb)
return sense, rhs, range_value | module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end elif_clause comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier float elif_clause comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier float elif_clause comparison_operator identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier float elif_clause comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list binary_operator identifier identifier return_statement expression_list identifier identifier identifier | Helper function used by Constraint and Model |
def value(self, raw_value):
if raw_value in self._FALSE_VALUES:
return False
elif raw_value in self._TRUE_VALUES:
return True
else:
raise ValueError(
"Could not parse '{}' value as boolean".format(raw_value)
) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement false elif_clause comparison_operator identifier attribute identifier identifier block return_statement true else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Decode param as bool value. |
def _get_ip_address(self, request):
ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None)
if ipaddr:
return ipaddr.split(",")[0].strip()
return request.META.get("REMOTE_ADDR", "") | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none if_statement identifier block return_statement call attribute subscript call attribute identifier identifier argument_list string string_start string_content string_end integer identifier argument_list return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end | Get the remote ip address the request was generated from. |
def add_references(self, other_names):
if not other_names:
return
with open(self.outfile, 'rt') as fp:
header, body = self.split_header(fp)
with open(self.outfile, 'wt') as fp:
fp.writelines(header)
fp.writelines(
'-r {0}.{1}\n'.format(other_name, OPTIONS['out_ext'])
for other_name in sorted(other_names)
)
fp.writelines(body) | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list 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 identifier expression_statement call attribute identifier identifier generator_expression call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier subscript identifier string string_start string_content string_end for_in_clause identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Add references to other_names in outfile |
def from_name(cls, name):
result = cls.list({'items_per_page': 500})
webaccs = {}
for webacc in result:
webaccs[webacc['name']] = webacc['id']
return webaccs.get(name) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end integer expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment subscript identifier subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier | Retrieve webacc id associated to a webacc name. |
def onDragSelection(self, event):
if self.grid.GetSelectionBlockTopLeft():
bottom_right = eval(repr(self.grid.GetSelectionBlockBottomRight()).replace("GridCellCoordsArray: ", "").replace("GridCellCoords", ""))
top_left = eval(repr(self.grid.GetSelectionBlockTopLeft()).replace("GridCellCoordsArray: ", "").replace("GridCellCoords", ""))
top_left = top_left[0]
bottom_right = bottom_right[0]
else:
return
min_col = top_left[1]
max_col = bottom_right[1]
min_row = top_left[0]
max_row = bottom_right[0]
self.df_slice = self.contribution.tables[self.grid_type].df.iloc[min_row:max_row+1, min_col:max_col+1] | module function_definition identifier parameters identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list call attribute call attribute call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier call identifier argument_list call attribute call attribute call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer else_clause block return_statement expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier integer expression_statement assignment attribute identifier identifier subscript attribute attribute subscript attribute attribute identifier identifier identifier attribute identifier identifier identifier identifier slice identifier binary_operator identifier integer slice identifier binary_operator identifier integer | Set self.df_slice based on user's selection |
def createNewICM():
data = json.loads(request.data)
G = AnalysisGraph.from_uncharted_json_serialized_dict(data)
G.assemble_transition_model_from_gradable_adjectives()
G.sample_from_prior()
G.to_sql(app=current_app)
_metadata = ICMMetadata.query.filter_by(id=G.id).first().deserialize()
del _metadata["model_id"]
return jsonify(_metadata) | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier identifier argument_list identifier argument_list delete_statement subscript identifier string string_start string_content string_end return_statement call identifier argument_list identifier | Create a new ICM |
def handle_status(self):
status = self.get_status()
if status:
self.zones['main'].update_status(status) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier | Handle status from device |
def wait(self):
d = defer.Deferred()
if self._result is None:
self._waiters.append(d)
else:
self._fire_deferred(d)
return d | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Return a deferred that will be fired when the event is fired. |
def use_active_composition_view(self):
self._operable_views['composition'] = ACTIVE
for session in self._get_provider_sessions():
try:
session.use_active_composition_view()
except AttributeError:
pass | module function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block pass_statement | Pass through to provider CompositionLookupSession.use_active_composition_view |
def create(self, ticket, payload=None, expires=None):
if not payload:
payload = True
self._client.set(str(ticket), payload, expires) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier true expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier identifier identifier | Create a session identifier in memcache associated with ``ticket``. |
def format_status_json(self):
status_json = {}
status_json['code'] = self.code
status_json['message'] = self.message
if self.details is not None:
status_json['details'] = self.details
return status_json | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement identifier | Convert a Status object to json format. |
def stretch(self, scale_factor, callback=True):
self.scale_pct *= scale_factor
self.scale_and_shift(self.scale_pct, 0.0, callback=callback) | module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement augmented_assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier float keyword_argument identifier identifier | Stretch the color map via altering the shift map. |
def _makeButtons(self):
self.button = button = urwid.Button(u"OK")
urwid.connect_signal(button, "click", self._completed)
return [self.button] | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end attribute identifier identifier return_statement list attribute identifier identifier | Makes buttons and wires them up. |
def change_view(self, *args, **kwargs):
Hierarchy.init_hierarchy(self)
self.hierarchy.hook_change_view(self, args, kwargs)
return super(HierarchicalModelAdmin, self).change_view(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier | Renders detailed model edit page. |
def print(*a):
try:
_print(*a)
return a[0] if len(a) == 1 else a
except:
_print(*a) | module function_definition identifier parameters list_splat_pattern identifier block try_statement block expression_statement call identifier argument_list list_splat identifier return_statement conditional_expression subscript identifier integer comparison_operator call identifier argument_list identifier integer identifier except_clause block expression_statement call identifier argument_list list_splat identifier | print just one that returns what you give it instead of None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.