code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def infer_call_result(self, caller, context=None):
context = contextmod.bind_context_to_node(context, self)
inferred = False
for node in self._proxied.igetattr("__call__", context):
if node is util.Uninferable or not node.callable():
continue
for res in node.infer_call_result(caller, context):
inferred = True
yield res
if not inferred:
raise exceptions.InferenceError(node=self, caller=caller, context=context) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier false for_statement identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier block if_statement boolean_operator comparison_operator identifier attribute identifier identifier not_operator call attribute identifier identifier argument_list block continue_statement for_statement identifier call attribute identifier identifier argument_list identifier identifier block expression_statement assignment identifier true expression_statement yield identifier if_statement not_operator identifier block raise_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | infer what a class instance is returning when called |
def cmd_part(self, connection, sender, target, payload):
if payload:
connection.part(payload)
else:
raise ValueError("No channel given") | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Asks the bot to leave a channel |
def PrettyPrinter(obj):
if ndb and isinstance(obj, ndb.Model):
return six.iteritems(obj.to_dict()), 'ndb.Model(%s)' % type(obj).__name__
if messages and isinstance(obj, messages.Enum):
return [('name', obj.name), ('number', obj.number)], type(obj).__name__
return None | module function_definition identifier parameters identifier block if_statement boolean_operator identifier call identifier argument_list identifier attribute identifier identifier block return_statement expression_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute call identifier argument_list identifier identifier if_statement boolean_operator identifier call identifier argument_list identifier attribute identifier identifier block return_statement expression_list list tuple string string_start string_content string_end attribute identifier identifier tuple string string_start string_content string_end attribute identifier identifier attribute call identifier argument_list identifier identifier return_statement none | Pretty printers for AppEngine objects. |
def stop(host=None, port=None):
app.config['HOST'] = first_value(host, app.config.get('HOST',None), '0.0.0.0')
app.config['PORT'] = int(first_value(port, app.config.get('PORT',None), 5001))
if app.config['HOST'] == "0.0.0.0":
host="127.0.0.1"
else:
host = app.config['HOST']
port = app.config['PORT']
try:
if requests.get('http://%s:%s/api/status' % (host, port)).status_code == 200:
requests.get('http://%s:%s/api/stop' % (host,port))
print('web server is stopped', file=sys.stdinfo)
else:
print('web server is not flaskserver', file=sys.stderr)
except:
print('web server is not flaskserver or not start', file=sys.stderr) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call identifier argument_list call identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none integer if_statement comparison_operator subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end try_statement block if_statement comparison_operator attribute call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier identifier integer block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier else_clause block expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier except_clause block expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier | stop of web server |
def save_bookmark(self, slot_num):
bookmarks = CONF.get('editor', 'bookmarks')
editorstack = self.get_current_editorstack()
if slot_num in bookmarks:
filename, line_num, column = bookmarks[slot_num]
if osp.isfile(filename):
index = editorstack.has_filename(filename)
if index is not None:
block = (editorstack.tabs.widget(index).document()
.findBlockByNumber(line_num))
block.userData().bookmarks.remove((slot_num, column))
if editorstack is not None:
self.switch_to_plugin()
editorstack.set_bookmark(slot_num) | 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 string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier identifier block expression_statement assignment pattern_list identifier identifier identifier subscript identifier identifier if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier parenthesized_expression call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list identifier argument_list identifier expression_statement call attribute attribute call attribute identifier identifier argument_list identifier identifier argument_list tuple identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier | Save current line and position as bookmark. |
def deserialize(self,
node: SchemaNode,
cstruct: Union[str, ColanderNullType]) \
-> Optional[Pendulum]:
if not cstruct:
return colander.null
try:
result = coerce_to_pendulum(cstruct,
assume_local=self.use_local_tz)
except (ValueError, ParserError) as e:
raise Invalid(node, "Invalid date/time: value={!r}, error="
"{!r}".format(cstruct, e))
return result | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier line_continuation type generic_type identifier type_parameter type identifier block if_statement not_operator identifier block return_statement attribute identifier identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier attribute identifier identifier except_clause as_pattern tuple identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier identifier return_statement identifier | Deserializes string representation to Python object. |
def drp_load_data(package, data, confclass=None):
drpdict = yaml.safe_load(data)
ins = load_instrument(package, drpdict, confclass=confclass)
if ins.version == 'undefined':
pkg = importlib.import_module(package)
ins.version = getattr(pkg, '__version__', 'undefined')
return ins | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier string string_start string_content string_end string string_start string_content string_end return_statement identifier | Load the DRPS from data. |
def write_cache(cache, opts):
cache_file = get_cache(opts)
try:
_cache = salt.utils.stringutils.to_bytes(
salt.utils.yaml.safe_dump(cache)
)
with salt.utils.files.fopen(cache_file, 'wb+') as fp_:
fp_.write(_cache)
return True
except (IOError, OSError):
log.error('Failed to cache mounts',
exc_info_on_loglevel=logging.DEBUG)
return False | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list identifier 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 identifier return_statement true except_clause tuple identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier return_statement false | Write the mount cache file. |
def getAsWmsDatasetString(self, session):
FIRST_VALUE_INDEX = 12
if type(self.raster) != type(None):
valueGrassRasterString = self.getAsGrassAsciiGrid(session)
values = valueGrassRasterString.split()
wmsDatasetString = ''
for i in range(FIRST_VALUE_INDEX, len(values)):
wmsDatasetString += '{0:.6f}\r\n'.format(float(values[i]))
return wmsDatasetString
else:
wmsDatasetString = self.rasterText | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer if_statement comparison_operator call identifier argument_list attribute identifier identifier call identifier argument_list none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier string string_start string_end for_statement identifier call identifier argument_list identifier call identifier argument_list identifier block expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list call identifier argument_list subscript identifier identifier return_statement identifier else_clause block expression_statement assignment identifier attribute identifier identifier | Retrieve the WMS Raster as a string in the WMS Dataset format |
def prt_tsv_sections(prt, tsv_data, **kws):
prt_hdr_min = 10
num_items = 0
if tsv_data:
assert len(tsv_data[0]) == 2, "wr_tsv_sections EXPECTED: [(section, nts), ..."
assert tsv_data[0][1], \
"wr_tsv_sections EXPECTED SECTION({S}) LIST TO HAVE DATA".format(S=tsv_data[0][0])
hdrs_wrote = False
sep = "\t" if 'sep' not in kws else kws['sep']
prt_flds = kws['prt_flds'] if 'prt_flds' in kws else tsv_data[0]._fields
fill = sep*(len(prt_flds) - 1)
for section_text, data_nts in tsv_data:
prt.write("{SEC}{FILL}\n".format(SEC=section_text, FILL=fill))
if hdrs_wrote is False or len(data_nts) > prt_hdr_min:
prt_tsv_hdr(prt, data_nts, **kws)
hdrs_wrote = True
num_items += prt_tsv_dat(prt, data_nts, **kws)
return num_items
else:
return 0 | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier integer expression_statement assignment identifier integer if_statement identifier block assert_statement comparison_operator call identifier argument_list subscript identifier integer integer string string_start string_content string_end assert_statement subscript subscript identifier integer integer call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier subscript subscript identifier integer integer expression_statement assignment identifier false expression_statement assignment identifier conditional_expression string string_start string_content escape_sequence string_end comparison_operator string string_start string_content string_end identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier conditional_expression subscript identifier string string_start string_content string_end comparison_operator string string_start string_content string_end identifier attribute subscript identifier integer identifier expression_statement assignment identifier binary_operator identifier parenthesized_expression binary_operator call identifier argument_list identifier integer for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier if_statement boolean_operator comparison_operator identifier false comparison_operator call identifier argument_list identifier identifier block expression_statement call identifier argument_list identifier identifier dictionary_splat identifier expression_statement assignment identifier true expression_statement augmented_assignment identifier call identifier argument_list identifier identifier dictionary_splat identifier return_statement identifier else_clause block return_statement integer | Write tsv file containing section names followed by lines of namedtuple data. |
def usage():
l_bracket = clr.stringc("[", "dark gray")
r_bracket = clr.stringc("]", "dark gray")
pipe = clr.stringc("|", "dark gray")
app_name = clr.stringc("%prog", "bright blue")
commands = clr.stringc("{0}".format(pipe).join(c.VALID_ACTIONS), "normal")
help = clr.stringc("--help", "green")
options = clr.stringc("options", "yellow")
guide = "\n\n"
for action in c.VALID_ACTIONS:
guide += command_name(app_name, action,
c.MESSAGES["help_" + action])
guide = guide[:-1]
return "{0} {1}{2}{3} {1}{4}{3} {1}{5}{3}\n{6}".format(app_name,
l_bracket,
commands,
r_bracket,
help,
options,
guide) | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end 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 expression_statement assignment identifier call attribute identifier identifier argument_list call attribute call attribute string string_start string_content string_end identifier argument_list identifier identifier argument_list attribute identifier 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 expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier string string_start string_content escape_sequence escape_sequence string_end for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier call identifier argument_list identifier identifier subscript attribute identifier identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier subscript identifier slice unary_operator integer return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier identifier identifier identifier identifier identifier identifier | Return the usage for the help command. |
def plot_data(orig_data, data):
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
for dd, c in [(orig_data, 'r'), (data, 'b')]:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
xs = [ d.x for d in dd ]
ys = [ d.y for d in dd ]
zs = [ d.z for d in dd ]
ax.scatter(xs, ys, zs, c=c, marker='o')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show() | module function_definition identifier parameters identifier identifier block import_statement aliased_import dotted_name identifier identifier import_from_statement dotted_name identifier identifier dotted_name identifier import_statement aliased_import dotted_name identifier identifier identifier for_statement pattern_list identifier identifier list tuple identifier string string_start string_content string_end tuple identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list integer keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list | plot data in 3D |
def add_transform_columns(self):
for col in ["parval1","parlbnd","parubnd","increment"]:
if col not in self.parameter_data.columns:
continue
self.parameter_data.loc[:,col+"_trans"] = (self.parameter_data.loc[:,col] *
self.parameter_data.scale) +\
self.parameter_data.offset
islog = self.parameter_data.partrans == "log"
self.parameter_data.loc[islog,col+"_trans"] = \
self.parameter_data.loc[islog,col+"_trans"].\
apply(lambda x:np.log10(x)) | module function_definition identifier parameters identifier block for_statement 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 block if_statement comparison_operator identifier attribute attribute identifier identifier identifier block continue_statement expression_statement assignment subscript attribute attribute identifier identifier identifier slice binary_operator identifier string string_start string_content string_end binary_operator parenthesized_expression binary_operator subscript attribute attribute identifier identifier identifier slice identifier attribute attribute identifier identifier identifier line_continuation attribute attribute identifier identifier identifier expression_statement assignment identifier comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment subscript attribute attribute identifier identifier identifier identifier binary_operator identifier string string_start string_content string_end line_continuation call attribute subscript attribute attribute identifier identifier identifier identifier binary_operator identifier string string_start string_content string_end line_continuation identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier | add transformed values to the Pst.parameter_data attribute |
def minor_releases(self, manager):
return [
key for key, value in six.iteritems(manager)
if any(x for x in value if not x.startswith('unreleased'))
] | module function_definition identifier parameters identifier identifier block return_statement list_comprehension identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_clause call identifier generator_expression identifier for_in_clause identifier identifier if_clause not_operator call attribute identifier identifier argument_list string string_start string_content string_end | Return all minor release line labels found in ``manager``. |
def iq_query(self, message: str):
end_msg = '!ENDMSG!'
recv_buffer = 4096
self._send_cmd(message)
chunk = ""
data = ""
while True:
chunk = self._sock.recv(recv_buffer).decode('latin-1')
data += chunk
if chunk.startswith('E,'):
if chunk.startswith('E,!NO_DATA!'):
log.warn('No data available for the given symbol or dates')
return
else:
raise Exception(chunk)
elif end_msg in chunk:
break
data = data[:-1 * (len(end_msg) + 3)]
data = "".join(data.split("\r"))
data = data.replace(",\n", ",")[:-1]
data = data.split(",")
return data | module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier integer expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier string string_start string_end expression_statement assignment identifier string string_start string_end while_statement true block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end expression_statement augmented_assignment identifier identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement else_clause block raise_statement call identifier argument_list identifier elif_clause comparison_operator identifier identifier block break_statement expression_statement assignment identifier subscript identifier slice binary_operator unary_operator integer parenthesized_expression binary_operator call identifier argument_list identifier integer expression_statement assignment identifier call attribute string string_start string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content string_end slice unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Send data query to IQFeed API. |
def rm_tempdirs():
tempdirs = [Dir.BUILD, Dir.COCOA_BUILD, Dir.LIB]
for tempdir in tempdirs:
if os.path.exists(tempdir):
shutil.rmtree(tempdir, ignore_errors=True) | module function_definition identifier parameters block expression_statement assignment identifier list attribute identifier identifier attribute identifier identifier attribute identifier identifier for_statement identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true | Remove temporary build folders |
def _delay(self):
if self.next_request_timestamp is None:
return
sleep_seconds = self.next_request_timestamp - time.time()
if sleep_seconds <= 0:
return
time.sleep(sleep_seconds) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement assignment identifier binary_operator attribute identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier integer block return_statement expression_statement call attribute identifier identifier argument_list identifier | Pause before making the next HTTP request. |
def _save_password_in_keyring(credential_id, username, password):
try:
import keyring
return keyring.set_password(credential_id, username, password)
except ImportError:
log.error('Tried to store password in keyring, but no keyring module is installed')
return False | module function_definition identifier parameters identifier identifier identifier block try_statement block import_statement dotted_name identifier return_statement call attribute identifier identifier argument_list identifier identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false | Saves provider password in system keyring |
def as_bin(self, as_spendable=False):
f = io.BytesIO()
self.stream(f, as_spendable=as_spendable)
return f.getvalue() | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list | Return the txo as binary. |
def add_values(self, values):
if self.child.is_alive():
self.parent_pipe.send(values) | module function_definition identifier parameters identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | add some data to the graph |
def srcmdl_xml(self, **kwargs):
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
localpath = NameFactory.srcmdl_xml_format.format(**kwargs_copy)
if kwargs.get('fullpath', False):
return self.fullpath(localpath=localpath)
return localpath | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end false block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement identifier | return the file name for source model xml files |
def _totuple( x ):
if isinstance( x, basestring ):
out = x,
elif isinstance( x, ( int, long, float ) ):
out = str( x ),
elif x is None:
out = None,
else:
out = tuple( x )
return out | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier expression_list identifier elif_clause call identifier argument_list identifier tuple identifier identifier identifier block expression_statement assignment identifier expression_list call identifier argument_list identifier elif_clause comparison_operator identifier none block expression_statement assignment identifier expression_list none else_clause block expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | Utility stuff to convert string, int, long, float, None or anything to a usable tuple. |
def circular_contigs(self):
if self.assembler == 'spades':
if self.contigs_fastg is not None:
return self._circular_contigs_from_spades_before_3_6_1(self.contigs_fastg)
elif None not in [self.contigs_paths, self.assembly_graph_fastg]:
return self._circular_contigs_from_spades_after_3_6_1(self.assembly_graph_fastg, self.contigs_paths)
else:
return set()
elif self.assembler == 'canu':
return self._circular_contigs_from_canu_gfa(self.contigs_gfa)
else:
return set() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block if_statement comparison_operator attribute identifier identifier none block return_statement call attribute identifier identifier argument_list attribute identifier identifier elif_clause comparison_operator none list attribute identifier identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier else_clause block return_statement call identifier argument_list elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list attribute identifier identifier else_clause block return_statement call identifier argument_list | Returns a set of the contig names that are circular |
def depends(self, offset=0, count=25):
return self.client('jobs', 'depends', self.name, offset, count) | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer block return_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end attribute identifier identifier identifier identifier | Return all the currently dependent jobs |
def __clear_inplace_widgets(self):
cols = self.__get_display_columns()
for c in cols:
if c in self._inplace_widgets:
widget = self._inplace_widgets[c]
widget.place_forget()
self._inplace_widgets_show.pop(c, None) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier none | Remove all inplace edit widgets. |
def auto_levels_cb(self, setting, value):
method = self.t_['autocut_method']
params = self.t_.get('autocut_params', [])
params = dict(params)
if method != str(self.autocuts):
ac_class = AutoCuts.get_autocuts(method)
self.autocuts = ac_class(self.logger, **params)
else:
self.autocuts.update_params(**params)
self.auto_levels() | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end list expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier dictionary_splat identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list | Handle callback related to changes in auto-cut levels. |
def make(self):
eval = self.command.eval()
with open(self.filename, 'w') as f:
f.write(eval) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list 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 | Evaluate the command, and write it to a file. |
def construction_error(tot_items, block_shape, axes, e=None):
passed = tuple(map(int, [tot_items] + list(block_shape)))
if len(passed) <= 2:
passed = passed[::-1]
implied = tuple(len(ax) for ax in axes)
if len(implied) <= 2:
implied = implied[::-1]
if passed == implied and e is not None:
raise e
if block_shape[0] == 0:
raise ValueError("Empty data passed with indices specified.")
raise ValueError("Shape of passed values is {0}, indices imply {1}".format(
passed, implied)) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier binary_operator list identifier call identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript identifier slice unary_operator integer expression_statement assignment identifier call identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript identifier slice unary_operator integer if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier none block raise_statement identifier if_statement comparison_operator subscript identifier integer integer block raise_statement call identifier argument_list string string_start string_content string_end raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier | raise a helpful message about our construction |
def _get_cmaps(names):
import matplotlib.pyplot as plt
available_cmaps = list(
chain(plt.cm.cmap_d, _cmapnames, rcParams['colors.cmaps']))
names = list(names)
wrongs = []
for arg in (arg for arg in names if (not isinstance(arg, Colormap) and
arg not in available_cmaps)):
if isinstance(arg, str):
similarkeys = get_close_matches(arg, available_cmaps)
if similarkeys != []:
warn("Colormap %s not found in standard colormaps.\n"
"Similar colormaps are %s." % (arg, ', '.join(similarkeys)))
else:
warn("Colormap %s not found in standard colormaps.\n"
"Run function without arguments to see all colormaps" % arg)
names.remove(arg)
wrongs.append(arg)
if not names and not wrongs:
names = sorted(m for m in available_cmaps if not m.endswith("_r"))
return names | module function_definition identifier parameters identifier block import_statement aliased_import dotted_name identifier identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list attribute attribute identifier identifier identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list for_statement identifier generator_expression identifier for_in_clause identifier identifier if_clause parenthesized_expression boolean_operator not_operator call identifier argument_list identifier identifier comparison_operator identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement comparison_operator identifier list block expression_statement call identifier argument_list binary_operator concatenated_string string string_start string_content escape_sequence string_end string string_start string_content string_end tuple identifier call attribute string string_start string_content string_end identifier argument_list identifier else_clause block expression_statement call identifier argument_list binary_operator concatenated_string string string_start string_content escape_sequence string_end string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier if_statement boolean_operator not_operator identifier not_operator identifier block expression_statement assignment identifier call identifier generator_expression identifier for_in_clause identifier identifier if_clause not_operator call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Filter the given `names` for colormaps |
def get(self, value, cfg=None):
if value is None and cfg:
if self.option_type == 'list':
value = cfg.get_list(self.name, None)
else:
value = cfg.get(self.name, None)
if value is None:
value = self.default
else:
parse_method = getattr(self, 'parse_%s' % (self.option_type), None)
if parse_method:
value = parse_method(value)
return value | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement boolean_operator comparison_operator identifier none identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier none else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier none if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end parenthesized_expression attribute identifier identifier none if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | Returns value for this option from either cfg object or optparse option list, preferring the option list. |
def hash_coloured(text):
ansi_code = int(sha256(text.encode('utf-8')).hexdigest(), 16) % 230
return colored(text, ansi_code=ansi_code) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call identifier argument_list call attribute call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list integer integer return_statement call identifier argument_list identifier keyword_argument identifier identifier | Return a ANSI coloured text based on its hash |
def short_form_multiple_formats(jupytext_formats):
if not isinstance(jupytext_formats, list):
return jupytext_formats
jupytext_formats = [short_form_one_format(fmt) for fmt in jupytext_formats]
return ','.join(jupytext_formats) | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier identifier block return_statement identifier expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier | Convert jupytext formats, represented as a list of dictionaries, to a comma separated list |
def _warmest(self):
for _ in range(steps(self.temperature, 0.0,
self.command_set.temperature_steps)):
self._warmer() | module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list call identifier argument_list attribute identifier identifier float attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list | Group temperature as warm as possible. |
def show_subnetpool(self, subnetpool, **_params):
return self.get(self.subnetpool_path % (subnetpool), params=_params) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list binary_operator attribute identifier identifier parenthesized_expression identifier keyword_argument identifier identifier | Fetches information of a certain subnetpool. |
def setup_raven():
pcfg = AppBuilder.get_pcfg()
from raven.handlers.logging import SentryHandler
from raven import Client
from raven.conf import setup_logging
client = Client(pcfg['raven_dsn'])
handler = SentryHandler(client)
handler.setLevel(pcfg["raven_loglevel"])
setup_logging(handler)
return client | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list import_from_statement dotted_name identifier identifier identifier dotted_name identifier import_from_statement dotted_name identifier dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement call identifier argument_list identifier return_statement identifier | we setup sentry to get all stuff from our logs |
def reversed_graph(graph:dict) -> dict:
ret = defaultdict(set)
for node, succs in graph.items():
for succ in succs:
ret[succ].add(node)
return dict(ret) | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block for_statement identifier identifier block expression_statement call attribute subscript identifier identifier identifier argument_list identifier return_statement call identifier argument_list identifier | Return given graph reversed |
def write_pa11y_results(item, pa11y_results, data_dir):
data = dict(item)
data['pa11y'] = pa11y_results
hasher = hashlib.md5()
hasher.update(item["url"].encode('utf8'))
hasher.update(item["accessed_at"].isoformat().encode('utf8'))
basename = hasher.hexdigest()
filename = basename + ".json"
filepath = data_dir / filename
data_dir.makedirs_p()
text = json.dumps(data, cls=DateTimeEncoder)
filepath.write_text(text) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator identifier string string_start string_content string_end expression_statement assignment identifier binary_operator identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Write the output from pa11y into a data file. |
def Append(self, component=None, **kwarg):
if component is None:
component = self.__class__(**kwarg)
if self.HasField("pathtype"):
self.last.nested_path = component
else:
for k, v in iteritems(kwarg):
setattr(self, k, v)
self.SetRawData(component.GetRawData())
return self | module function_definition identifier parameters identifier default_parameter identifier none dictionary_splat_pattern identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment attribute attribute identifier identifier identifier identifier else_clause block for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier | Append a new pathspec component to this pathspec. |
def user_admin_urlname(action):
user = get_user_model()
return 'admin:%s_%s_%s' % (
user._meta.app_label, user._meta.model_name,
action) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list return_statement binary_operator string string_start string_content string_end tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier identifier | Return the admin URLs for the user app used. |
def render_file(self, filename):
dirname, basename = split(filename)
with changedir(dirname):
infile = abspath(basename)
outfile = abspath('.%s.html' % basename)
self.docutils.publish_file(infile, outfile, self.styles)
return outfile | module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier with_statement with_clause with_item call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier attribute identifier identifier return_statement identifier | Convert a reST file to HTML. |
def _validate_geometry(self, geometry):
if geometry is not None and geometry not in self.valid_geometries:
raise InvalidParameterError("{} is not a valid geometry".format(geometry))
return geometry | module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator identifier none comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Validates geometry, raising error if invalid. |
def tail_of_file(filename, n, ansi2html=False):
avg_line_length = 74
to_read = n
with open(filename) as f:
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
if ansi2html:
return convertAnsi2html('\n'.join(lines[-to_read:]))
return '\n'.join(lines[-to_read:]) + '\n'
avg_line_length *= 1.3 | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier integer expression_statement assignment identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block while_statement integer block try_statement block expression_statement call attribute identifier identifier argument_list unary_operator parenthesized_expression binary_operator identifier identifier integer except_clause identifier block expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list if_statement boolean_operator comparison_operator call identifier argument_list identifier identifier comparison_operator identifier integer block if_statement identifier block return_statement call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list subscript identifier slice unary_operator identifier return_statement binary_operator call attribute string string_start string_content escape_sequence string_end identifier argument_list subscript identifier slice unary_operator identifier string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier float | Reads a n lines from f with an offset of offset lines. |
def build_modules(is_training, vocab_size):
if is_training:
estimator_mode = tf.constant(bbb.EstimatorModes.sample)
else:
estimator_mode = tf.constant(bbb.EstimatorModes.mean)
lstm_bbb_custom_getter = bbb.bayes_by_backprop_getter(
posterior_builder=lstm_posterior_builder,
prior_builder=custom_scale_mixture_prior_builder,
kl_builder=bbb.stochastic_kl_builder,
sampling_mode_tensor=estimator_mode)
non_lstm_bbb_custom_getter = bbb.bayes_by_backprop_getter(
posterior_builder=non_lstm_posterior_builder,
prior_builder=custom_scale_mixture_prior_builder,
kl_builder=bbb.stochastic_kl_builder,
sampling_mode_tensor=estimator_mode)
embed_layer = snt.Embed(
vocab_size=vocab_size,
embed_dim=FLAGS.embedding_size,
custom_getter=non_lstm_bbb_custom_getter,
name="input_embedding")
cores = []
for i in range(FLAGS.n_layers):
cores.append(
snt.LSTM(FLAGS.hidden_size,
custom_getter=lstm_bbb_custom_getter,
forget_bias=0.0,
name="lstm_layer_{}".format(i)))
rnn_core = snt.DeepRNN(
cores,
skip_connections=False,
name="deep_lstm_core")
output_linear = snt.Linear(
vocab_size, custom_getter={"w": non_lstm_bbb_custom_getter})
return embed_layer, rnn_core, output_linear | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier list for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier float keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier false keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier dictionary pair string string_start string_content string_end identifier return_statement expression_list identifier identifier identifier | Construct the modules used in the graph. |
def pip_uninstall(package, **options):
command = ["uninstall", "-q", "-y"]
available_options = ('proxy', 'log', )
for option in parse_options(options, available_options):
command.append(option)
if isinstance(package, list):
command.extend(package)
else:
command.append(package)
log("Uninstalling {} package with options: {}".format(package,
command))
pip_execute(command) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier tuple string string_start string_content string_end string string_start string_content string_end for_statement identifier call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement call identifier argument_list identifier | Uninstall a python package |
def _create_cache_filename(self, cache_dir=None, **kwargs):
cache_dir = cache_dir or '.'
hash_str = self.get_hash(**kwargs)
return os.path.join(cache_dir, 'resample_lut-' + hash_str + '.npz') | module function_definition identifier parameters identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier boolean_operator identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end | Create filename for the cached resampling parameters |
def find_equals_true_or_false(node):
return (
isinstance(node, ast.Compare)
and len(node.ops) == 1
and isinstance(node.ops[0], ast.Eq)
and any(h.is_boolean(n) for n in node.comparators)
) | module function_definition identifier parameters identifier block return_statement parenthesized_expression boolean_operator boolean_operator boolean_operator call identifier argument_list identifier attribute identifier identifier comparison_operator call identifier argument_list attribute identifier identifier integer call identifier argument_list subscript attribute identifier identifier integer attribute identifier identifier call identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier attribute identifier identifier | Finds equals true or false |
def start_zap_daemon(zap_helper, start_options):
console.info('Starting ZAP daemon')
with helpers.zap_error_handler():
zap_helper.start(options=start_options) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end with_statement with_clause with_item call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | Helper to start the daemon using the current config. |
def _call(self, x, out=None):
if out is None:
return x ** self.exponent
elif self.__domain_is_field:
raise ValueError('cannot use `out` with field')
else:
out.assign(x)
out **= self.exponent | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block return_statement binary_operator identifier attribute identifier identifier elif_clause attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier attribute identifier identifier | Take the power of ``x`` and write to ``out`` if given. |
def triples(self, (s, p, o), context=None):
named_graph = _get_named_graph(context)
query_sets = _get_query_sets_for_object(o)
filter_parameters = dict()
if named_graph is not None:
filter_parameters['context_id'] = named_graph.id
if s:
filter_parameters['subject'] = s
if p:
filter_parameters['predicate'] = p
if o:
filter_parameters['object'] = o
query_sets = [qs.filter(**filter_parameters) for qs in query_sets]
for qs in query_sets:
for statement in qs:
triple = statement.as_triple()
yield triple, context | module function_definition identifier parameters identifier tuple_pattern identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list dictionary_splat identifier for_in_clause identifier identifier for_statement identifier identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement yield expression_list identifier identifier | Returns all triples in the current store. |
def enurlform_app(parser, cmd, args):
parser.add_argument('values', help='the key=value pairs to URL encode', nargs='+')
args = parser.parse_args(args)
return enurlform(dict(v.split('=', 1) for v in args.values)) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list call identifier generator_expression call attribute identifier identifier argument_list string string_start string_content string_end integer for_in_clause identifier attribute identifier identifier | encode a series of key=value pairs into a query string. |
def attrib(self):
return dict([
('aValue', str(self.a_val)),
('bValue', str(self.b_val)),
('minMag', str(self.min_mag)),
('maxMag', str(self.max_mag)),
]) | module function_definition identifier parameters identifier block return_statement call identifier argument_list list tuple string string_start string_content string_end call identifier argument_list attribute identifier identifier tuple string string_start string_content string_end call identifier argument_list attribute identifier identifier tuple string string_start string_content string_end call identifier argument_list attribute identifier identifier tuple string string_start string_content string_end call identifier argument_list attribute identifier identifier | An dict of XML element attributes for this MFD. |
def _init_fld2col_widths(self):
fld2col_widths = GoSubDagWr.fld2col_widths.copy()
for fld, wid in self.oprtfmt.default_fld2col_widths.items():
fld2col_widths[fld] = wid
for fld in get_hdridx_flds():
fld2col_widths[fld] = 2
return fld2col_widths | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement pattern_list identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block expression_statement assignment subscript identifier identifier identifier for_statement identifier call identifier argument_list block expression_statement assignment subscript identifier identifier integer return_statement identifier | Return default column widths for writing an Excel Spreadsheet. |
def _dbus_exception_to_reason(exc, args):
error = exc.get_dbus_name()
if error == 'error.unknown_config':
return "Unknown configuration '{0}'".format(args['config'])
elif error == 'error.illegal_snapshot':
return 'Invalid snapshot'
else:
return exc.get_dbus_name() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block return_statement call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end elif_clause comparison_operator identifier string string_start string_content string_end block return_statement string string_start string_content string_end else_clause block return_statement call attribute identifier identifier argument_list | Returns a error message from a snapper DBusException |
def stop(cls):
if AnimatedDecorator._enabled:
if cls.spinner.running:
cls.spinner.running = False
cls.animation.thread.join()
if any(cls.animation.messages):
cls.pop_message()
sys.stdout = sys.__stdout__ | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block if_statement attribute attribute identifier identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier false expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list if_statement call identifier argument_list attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier | Stop the thread animation gracefully and reset_message |
def row(self):
if self.parent is not None:
children = self.parent.getChildren()
return children.index(self)
else:
return 0 | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier else_clause block return_statement integer | Return the row of the child. |
def find(self, oid):
if not isinstance(oid, Oid):
raise TypeError("Need crytypescrypto.oid.Oid as argument")
found = []
index = -1
end = len(self)
while True:
index = libcrypto.X509_get_ext_by_NID(self.cert.cert, oid.nid,
index)
if index >= end or index < 0:
break
found.append(self[index])
return found | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier list expression_statement assignment identifier unary_operator integer expression_statement assignment identifier call identifier argument_list identifier while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier identifier if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier integer block break_statement expression_statement call attribute identifier identifier argument_list subscript identifier identifier return_statement identifier | Return list of extensions with given Oid |
def add(self, name, handler, group_by=None, aggregator=None):
assert self.batch is not None, "No active batch, call start() first"
items = self.batch.setdefault(name, collections.OrderedDict())
if group_by is None:
items.setdefault(group_by, []).append((None, handler))
elif aggregator is not None:
agg = items.get(group_by, [(None, None)])[0][0]
items[group_by] = [(aggregator(agg), handler)]
else:
items[group_by] = [(None, handler)] | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none block assert_statement comparison_operator attribute identifier identifier none string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement call attribute call attribute identifier identifier argument_list identifier list identifier argument_list tuple none identifier elif_clause comparison_operator identifier none block expression_statement assignment identifier subscript subscript call attribute identifier identifier argument_list identifier list tuple none none integer integer expression_statement assignment subscript identifier identifier list tuple call identifier argument_list identifier identifier else_clause block expression_statement assignment subscript identifier identifier list tuple none identifier | Add a new handler to the current batch. |
def shell(ctx, package, working_dir, sudo):
ctx.mode = CanariMode.LocalShellDebug
from canari.commands.shell import shell
shell(package, working_dir, sudo) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement call identifier argument_list identifier identifier identifier | Runs a Canari interactive python shell |
def check(self, url_data):
self.timer.check_w3_time()
session = url_data.session
try:
body = {'uri': url_data.url, 'output': 'soap12'}
response = session.post('http://validator.w3.org/check', data=body)
response.raise_for_status()
if response.headers.get('x-w3c-validator-status', 'Invalid') == 'Valid':
url_data.add_info(u"W3C Validator: %s" % _("valid HTML syntax"))
return
check_w3_errors(url_data, response.text, "W3C HTML")
except requests.exceptions.RequestException:
pass
except Exception as msg:
log.warn(LOG_PLUGIN, _("HTML syntax check plugin error: %(msg)s ") % {"msg": msg}) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier attribute identifier identifier try_statement 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 string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list string string_start string_content string_end return_statement expression_statement call identifier argument_list identifier attribute identifier identifier string string_start string_content string_end except_clause attribute attribute identifier identifier identifier block pass_statement except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier binary_operator call identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end identifier | Check HTML syntax of given URL. |
def render_countryfield(field, attrs):
choices = ((k, k.lower(), v)
for k, v in field.field._choices[1:])
return render_choicefield(
field, attrs, format_html_join("", wrappers.COUNTRY_TEMPLATE, choices)
) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier generator_expression tuple identifier call attribute identifier identifier argument_list identifier for_in_clause pattern_list identifier identifier subscript attribute attribute identifier identifier identifier slice integer return_statement call identifier argument_list identifier identifier call identifier argument_list string string_start string_end attribute identifier identifier identifier | Render a custom ChoiceField specific for CountryFields. |
def find_module(modpath):
module_path = modpath.replace('.', '/') + '.py'
init_path = modpath.replace('.', '/') + '/__init__.py'
for root_path in sys.path:
path = os.path.join(root_path, module_path)
if os.path.isfile(path):
return path
path = os.path.join(root_path, init_path)
if os.path.isfile(path):
return path | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator 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 expression_statement assignment identifier binary_operator 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 attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block return_statement identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block return_statement identifier | Determines whether a module exists with the given modpath. |
def pop_row(self, idr=None, tags=False):
idr = idr if idr is not None else len(self.body) - 1
row = self.body.pop(idr)
return row if tags else [cell.childs[0] for cell in row] | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier conditional_expression identifier comparison_operator identifier none binary_operator call identifier argument_list attribute identifier identifier integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement conditional_expression identifier identifier list_comprehension subscript attribute identifier identifier integer for_in_clause identifier identifier | Pops a row, default the last |
def _get_by_id(collection, id):
matches = [item for item in collection if item.id == id]
if not matches:
raise ValueError('Could not find a matching item')
elif len(matches) > 1:
raise ValueError('The id matched {0} items, not 1'.format(len(matches)))
return matches[0] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator attribute identifier identifier identifier if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end elif_clause comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier return_statement subscript identifier integer | Get item from a list by the id field |
def populate_resource_list(self):
minimum_needs = self.minimum_needs.get_full_needs()
for full_resource in minimum_needs["resources"]:
self.add_resource(full_resource)
self.provenance.setText(minimum_needs["provenance"]) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end | Populate the list resource list. |
def maxsize(self, size):
if size < 0:
raise ValueError('maxsize must be non-negative')
with self._lock:
self._enforce_size_limit(size)
self._maxsize = size | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier integer block raise_statement call identifier argument_list string string_start string_content string_end with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier | Resize the cache, evicting the oldest items if necessary. |
def parse_relative_path(root_path, experiment_config, key):
if experiment_config.get(key) and not os.path.isabs(experiment_config.get(key)):
absolute_path = os.path.join(root_path, experiment_config.get(key))
print_normal('expand %s: %s to %s ' % (key, experiment_config[key], absolute_path))
experiment_config[key] = absolute_path | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator call attribute identifier identifier argument_list identifier not_operator call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier subscript identifier identifier identifier expression_statement assignment subscript identifier identifier identifier | Change relative path to absolute path |
def auth(self, request):
client = self.get_evernote_client()
request_token = client.get_request_token(self.callback_url(request))
request.session['oauth_token'] = request_token['oauth_token']
request.session['oauth_token_secret'] = request_token['oauth_token_secret']
return client.get_authorize_url(request_token) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier 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 | let's auth the user to the Service |
def input_tray_status(self,
filter_supported: bool = True) -> Dict[int, Any]:
tray_status = {}
for i in range(1, 5):
try:
tray_stat = self.data.get('{}{}'.format(SyncThru.TRAY, i), {})
if filter_supported and tray_stat.get('opt', 0) == 0:
continue
else:
tray_status[i] = tray_stat
except (KeyError, AttributeError):
tray_status[i] = {}
return tray_status | module function_definition identifier parameters identifier typed_default_parameter identifier type identifier true type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list integer integer block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier dictionary if_statement boolean_operator identifier comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end integer integer block continue_statement else_clause block expression_statement assignment subscript identifier identifier identifier except_clause tuple identifier identifier block expression_statement assignment subscript identifier identifier dictionary return_statement identifier | Return the state of all input trays. |
def assert_string_list(dist, attr, value):
try:
assert ''.join(value) != value
except (TypeError, ValueError, AttributeError, AssertionError):
raise DistutilsSetupError(
"%r must be a list of strings (got %r)" % (attr, value)
) | module function_definition identifier parameters identifier identifier identifier block try_statement block assert_statement comparison_operator call attribute string string_start string_end identifier argument_list identifier identifier except_clause tuple identifier identifier identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier | Verify that value is a string list or None |
def _apply_incoming_copying_manipulators(self, son, collection):
for manipulator in self.__incoming_copying_manipulators:
son = manipulator.transform_incoming(son, collection)
return son | module function_definition identifier parameters identifier identifier identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier | Apply incoming copying manipulators to `son`. |
def complete(self):
if self._possible is None:
self._possible = []
for possible in self.names:
c = Completion(self.context, self.names[possible], len(self.context.symbol))
self._possible.append(c)
return self._possible | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier subscript attribute identifier identifier identifier call identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement attribute identifier identifier | Gets a list of completion objects for the symbol under the cursor. |
def randombytes(n):
if os.path.exists("/dev/urandom"):
f = open("/dev/urandom")
s = f.read(n)
f.close()
return s
else:
L = [chr(random.randrange(0, 256)) for i in range(n)]
return "".join(L) | module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement identifier else_clause block expression_statement assignment identifier list_comprehension call identifier argument_list call attribute identifier identifier argument_list integer integer for_in_clause identifier call identifier argument_list identifier return_statement call attribute string string_start string_end identifier argument_list identifier | Return n random bytes. |
def initial(self, request, *args, **kwargs):
self.format_kwarg = self.get_format_suffix(**kwargs)
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier expression_list identifier identifier | Runs anything that needs to occur prior to calling the method handler. |
def device_locked(self, device):
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_locked',
_('Device locked'),
_('{0.device_presentation} locked', device),
device.icon_name) | module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list string string_start string_content string_end call identifier argument_list string string_start string_content string_end identifier attribute identifier identifier | Show lock notification for specified device object. |
def extract_arj (archive, compression, cmd, verbosity, interactive, outdir):
cmdlist = [cmd, 'x', '-r']
if not interactive:
cmdlist.append('-y')
cmdlist.extend([archive, outdir])
return cmdlist | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier list identifier string string_start string_content string_end string string_start string_content string_end if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list identifier identifier return_statement identifier | Extract an ARJ archive. |
def _sort_converters(cls, app_ready=False):
cls._sorting_enabled = cls._sorting_enabled or app_ready
if cls._sorting_enabled:
for converter in cls.converters:
converter.prepare_sort_key()
cls.converters.sort(key=attrgetter('sort_key')) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment attribute identifier identifier boolean_operator attribute identifier identifier identifier if_statement attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call identifier argument_list string string_start string_content string_end | Sorts the converter functions |
def clear(self, exclude=None):
if exclude is None:
self.cache = {}
else:
self.cache = {k: v for k, v in self.cache.items()
if k in exclude} | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier dictionary else_clause block expression_statement assignment attribute identifier identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list if_clause comparison_operator identifier identifier | Remove all elements in the cache. |
def normalizer(text, exclusion=OPERATIONS_EXCLUSION, lower=True, separate_char='-', **kwargs):
clean_str = re.sub(r'[^\w{}]'.format(
"".join(exclusion)), separate_char, text.strip()) or ''
clean_lowerbar = clean_str_without_accents = strip_accents(clean_str)
if '_' not in exclusion:
clean_lowerbar = re.sub(r'\_', separate_char, clean_str_without_accents.strip())
limit_guion = re.sub(r'\-+', separate_char, clean_lowerbar.strip())
if limit_guion and separate_char and separate_char in limit_guion[0]:
limit_guion = limit_guion[1:]
if limit_guion and separate_char and separate_char in limit_guion[-1]:
limit_guion = limit_guion[:-1]
if lower:
limit_guion = limit_guion.lower()
return limit_guion | module function_definition identifier parameters identifier default_parameter identifier identifier default_parameter identifier true default_parameter identifier string string_start string_content string_end dictionary_splat_pattern identifier block expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_end identifier argument_list identifier identifier call attribute identifier identifier argument_list string string_start string_end expression_statement assignment identifier assignment identifier call identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier call attribute identifier identifier argument_list if_statement boolean_operator boolean_operator identifier identifier comparison_operator identifier subscript identifier integer block expression_statement assignment identifier subscript identifier slice integer if_statement boolean_operator boolean_operator identifier identifier comparison_operator identifier subscript identifier unary_operator integer block expression_statement assignment identifier subscript identifier slice unary_operator integer if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier | Clean text string of simbols only alphanumeric chars. |
def _handle_signal_gracefully(cls, signum, signame, traceback_lines):
formatted_traceback = cls._format_traceback(traceback_lines=traceback_lines,
should_print_backtrace=True)
signal_error_log_entry = cls._CATCHABLE_SIGNAL_ERROR_LOG_FORMAT.format(
signum=signum,
signame=signame,
formatted_traceback=formatted_traceback)
cls.log_exception(signal_error_log_entry)
formatted_traceback_for_terminal = cls._format_traceback(
traceback_lines=traceback_lines,
should_print_backtrace=cls._should_print_backtrace_to_terminal)
terminal_log_entry = cls._CATCHABLE_SIGNAL_ERROR_LOG_FORMAT.format(
signum=signum,
signame=signame,
formatted_traceback=formatted_traceback_for_terminal)
cls._exit_with_failure(terminal_log_entry) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier true expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Signal handler for non-fatal signals which raises or logs an error and exits with failure. |
def _unpack_model(self, om):
buses = om.case.connected_buses
branches = om.case.online_branches
gens = om.case.online_generators
cp = om.get_cost_params()
return buses, branches, gens, cp | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement expression_list identifier identifier identifier identifier | Returns data from the OPF model. |
def make_get_exception_details_message(self, seq, thread_id, topmost_frame):
try:
cmd_text = ['<xml><thread id="%s" ' % (thread_id,)]
if topmost_frame is not None:
try:
frame = topmost_frame
topmost_frame = None
while frame is not None:
if frame.f_code.co_name == 'do_wait_suspend' and frame.f_code.co_filename.endswith('pydevd.py'):
arg = frame.f_locals.get('arg', None)
if arg is not None:
exc_type, exc_desc, _thread_suspend_str, thread_stack_str = self._make_send_curr_exception_trace_str(
thread_id, *arg)
cmd_text.append('exc_type="%s" ' % (exc_type,))
cmd_text.append('exc_desc="%s" ' % (exc_desc,))
cmd_text.append('>')
cmd_text.append(thread_stack_str)
break
frame = frame.f_back
else:
cmd_text.append('>')
finally:
frame = None
cmd_text.append('</thread></xml>')
return NetCommand(CMD_GET_EXCEPTION_DETAILS, seq, ''.join(cmd_text))
except:
return self.make_error_message(seq, get_exception_traceback_str()) | module function_definition identifier parameters identifier identifier identifier identifier block try_statement block expression_statement assignment identifier list binary_operator string string_start string_content string_end tuple identifier if_statement comparison_operator identifier none block try_statement block expression_statement assignment identifier identifier expression_statement assignment identifier none while_statement comparison_operator identifier none block if_statement boolean_operator comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none if_statement comparison_operator identifier none block expression_statement assignment pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list identifier list_splat identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier break_statement expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end finally_clause block expression_statement assignment identifier none expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list identifier identifier call attribute string string_start string_end identifier argument_list identifier except_clause block return_statement call attribute identifier identifier argument_list identifier call identifier argument_list | Returns exception details as XML |
def __attrs_str(self, tag, attrs):
enabled = self.whitelist.get(tag, ['*'])
all_attrs = '*' in enabled
items = []
for attr in attrs:
key = attr[0]
value = attr[1] or ''
if all_attrs or key in enabled:
items.append( u'%s="%s"' % (key, value,) )
return u' '.join(items) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier list string string_start string_content string_end expression_statement assignment identifier comparison_operator string string_start string_content string_end identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier boolean_operator subscript identifier integer string string_start string_end if_statement boolean_operator identifier comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier | Build string of attributes list for tag |
def build(self):
if not self._output_tubes:
self._output_tubes.append(self._worker_class.getTubeClass()())
self._worker_class.assemble(
self._worker_args,
self._input_tube,
self._output_tubes,
self._size,
self._disable_result,
self._do_stop_task,
)
for stage in self._next_stages:
stage.build() | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call call attribute attribute identifier identifier identifier argument_list argument_list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list | Create and start up the internal workers. |
def icontinue(self):
if self.status != 'paused':
print_(
"No sampling to continue. Please initiate sampling with isample.")
return
def sample_and_finalize():
self._loop()
self._finalize()
self._sampling_thread = Thread(target=sample_and_finalize)
self.status = 'running'
self._sampling_thread.start()
self.iprompt() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call identifier argument_list string string_start string_content string_end return_statement function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Restarts thread in interactive mode |
def update_colors(self, colors):
self.colors = np.array(colors, dtype='uint8')
prim_colors = self._gen_colors(self.colors)
self._color_vbo.set_data(prim_colors)
self.widget.update() | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Update the colors inplace |
def _get_merge(self):
line = self.next_line()
if line is None:
return None
elif line.startswith(b'merge '):
return line[len(b'merge '):]
else:
self.push_line(line)
return None | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block return_statement none elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block return_statement subscript identifier slice call identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement none | Parse a merge section. |
def percentile(values=None, percentile=None):
if values in [None, tuple(), []] or len(values) < 1:
raise InsufficientData(
"Expected a sequence of at least 1 integers, got {0!r}".format(values))
if percentile is None:
raise ValueError("Expected a percentile choice, got {0}".format(percentile))
sorted_values = sorted(values)
rank = len(values) * percentile / 100
if rank > 0:
index = rank - 1
if index < 0:
return sorted_values[0]
else:
index = rank
if index % 1 == 0:
return sorted_values[int(index)]
else:
fractional = index % 1
integer = int(index - fractional)
lower = sorted_values[integer]
higher = sorted_values[integer + 1]
return lower + fractional * (higher - lower) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block if_statement boolean_operator comparison_operator identifier list none call identifier argument_list list comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator call identifier argument_list identifier identifier integer if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator identifier integer if_statement comparison_operator identifier integer block return_statement subscript identifier integer else_clause block expression_statement assignment identifier identifier if_statement comparison_operator binary_operator identifier integer integer block return_statement subscript identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier call identifier argument_list binary_operator identifier identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier subscript identifier binary_operator identifier integer return_statement binary_operator identifier binary_operator identifier parenthesized_expression binary_operator identifier identifier | Calculates a simplified weighted average percentile |
def getroot(self):
builder = ET.TreeBuilder()
self.build(builder)
return builder.close() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list | Build XML object, return the root |
def isActiveDashboardOverlay(self, ulOverlayHandle):
fn = self.function_table.isActiveDashboardOverlay
result = fn(ulOverlayHandle)
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | returns true if the dashboard is visible and the specified overlay is the active system Overlay |
def contains(self, x, y) -> bool:
if x < self._left or x > self._right or y < self._top or y > self._bottom:
return False
return True | module function_definition identifier parameters identifier identifier identifier type identifier block if_statement boolean_operator boolean_operator boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier block return_statement false return_statement true | Checks if the given x, y position is within the area of this region. |
def fn_minimum_argcount(callable):
fn = get_fn(callable)
available_argcount = fn_available_argcount(callable)
try:
return available_argcount - len(fn.__defaults__)
except TypeError:
return available_argcount | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier try_statement block return_statement binary_operator identifier call identifier argument_list attribute identifier identifier except_clause identifier block return_statement identifier | Returns the minimum number of arguments that must be provided for the call to succeed. |
def _draw_text(self, pos, text, font, **kw):
self.drawables.append((pos, text, font, kw)) | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier identifier identifier | Remember a single drawable tuple to paint later. |
def _alerter_thread_func(self) -> None:
self._alert_count = 0
self._next_alert_time = 0
while not self._stop_thread:
if self.terminal_lock.acquire(blocking=False):
alert_str = self._generate_alert_str()
new_prompt = self._generate_colored_prompt()
if alert_str:
self.async_alert(alert_str, new_prompt)
new_title = "Alerts Printed: {}".format(self._alert_count)
self.set_window_title(new_title)
elif new_prompt != self.prompt:
self.async_update_prompt(new_prompt)
self.terminal_lock.release()
time.sleep(0.5) | module function_definition identifier parameters identifier type none block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer while_statement not_operator attribute identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list float | Prints alerts and updates the prompt any time the prompt is showing |
def setValue(self, newText):
self.text = newText
self.cursorPosition = len(self.text)
self._updateImage() | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list | Sets new text into the field |
def _choice_format(self, occur):
middle = "%s" if self.rng_children() else "<empty/>%s"
fmt = self.start_tag() + middle + self.end_tag()
if self.occur != 2:
return "<optional>" + fmt + "</optional>"
else:
return fmt | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier integer block return_statement binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end else_clause block return_statement identifier | Return the serialization format for a choice node. |
def strip_HTML(s):
result = ''
total = 0
for c in s:
if c == '<':
total = 1
elif c == '>':
total = 0
result += ' '
elif total == 0:
result += c
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier integer for_statement identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier integer elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier integer expression_statement augmented_assignment identifier string string_start string_content string_end elif_clause comparison_operator identifier integer block expression_statement augmented_assignment identifier identifier return_statement identifier | Simple, clumsy, slow HTML tag stripper |
def create(self):
self.consul.create_bucket("%s-%s" % (self.stack.name, self.name)) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute attribute identifier identifier identifier attribute identifier identifier | Creates a new bucket |
def _sameFrag(f, g):
if (hasattr(f, 'cbDefn') or hasattr(g, 'cbDefn')
or hasattr(f, 'lineBreak') or hasattr(g, 'lineBreak')): return 0
for a in ('fontName', 'fontSize', 'textColor', 'backColor', 'rise', 'underline', 'strike', 'link'):
if getattr(f, a, None) != getattr(g, a, None): return 0
return 1 | module function_definition identifier parameters identifier identifier block if_statement parenthesized_expression boolean_operator boolean_operator boolean_operator call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end block return_statement integer for_statement identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block if_statement comparison_operator call identifier argument_list identifier identifier none call identifier argument_list identifier identifier none block return_statement integer return_statement integer | returns 1 if two ParaFrags map out the same |
def _callback(self, ch, method, properties, body):
get_logger().info("Message received! Calling listeners...")
topic = method.routing_key
dct = json.loads(body.decode('utf-8'))
for listener in self.listeners:
listener(self, topic, dct) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement call attribute call identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list identifier identifier identifier | Internal method that will be called when receiving message. |
def continuous_periods(self):
result = []
start_date = self.start_date
for gap in self.pot_data_gaps:
end_date = gap.start_date - timedelta(days=1)
result.append(PotPeriod(start_date, end_date))
start_date = gap.end_date + timedelta(days=1)
end_date = self.end_date
result.append(PotPeriod(start_date, end_date))
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier call identifier argument_list keyword_argument identifier integer expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier call identifier argument_list keyword_argument identifier integer expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier return_statement identifier | Return a list of continuous data periods by removing the data gaps from the overall record. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.