code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def unregister_model(self, model):
if model not in self._model_registry:
raise NotRegistered('The model %s is not registered' % model)
del self._model_registry[model] | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier delete_statement subscript attribute ident... | Unregisters the given model. |
def open(self, path, binary=False):
if binary:
return open(path, "rb")
return open(path, encoding="utf-8") | module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement identifier block return_statement call identifier argument_list identifier string string_start string_content string_end return_statement call identifier argument_list identifier keyword_argument... | Open file and return a stream. |
def make_user_config_dir():
config_path = get_user_config_dir()
if not user_config_dir_exists():
try:
os.mkdir(config_path)
os.mkdir(os.path.join(config_path, 'hooks.d'))
except OSError:
return None
return config_path | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list if_statement not_operator call identifier argument_list block try_statement block expression_statement call attribute identifier identifier argument_list identifier expression_statement call a... | Create the user s-tui config directory if it doesn't exist |
def _read_input_urls(cls, session: AppSession, default_scheme='http'):
url_string_iter = session.args.urls or ()
url_rewriter = session.factory.get('URLRewriter')
if session.args.input_file:
if session.args.force_html:
lines = cls._input_file_as_html_links(session)
... | module function_definition identifier parameters identifier typed_parameter identifier type identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier boolean_operator attribute attribute identifier identifier identifier tuple expression_statem... | Read the URLs provided by the user. |
def scene_remove(frames):
reader = MessageReader(frames)
results = reader.string("command").uint32("scene_id").assert_end().get()
if results.command != "scene.rm":
raise MessageParserError("Command is not 'scene.rm'")
return (results.scene_id,) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute call attribute call attribute call attribute identifier identifier argument_list string string_start string_cont... | parse a scene.rm message |
def arguments(function, extra_arguments=0):
if not hasattr(function, '__code__'):
return ()
return function.__code__.co_varnames[:function.__code__.co_argcount + extra_arguments] | module function_definition identifier parameters identifier default_parameter identifier integer block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block return_statement tuple return_statement subscript attribute attribute identifier identifier identi... | Returns the name of all arguments a function takes |
def _fromset(cls, values, key=None):
sorted_set = object.__new__(cls)
sorted_set._set = values
sorted_set.__init__(key=key)
return sorted_set | 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 attribute identifier identifier identifier expression_statement call att... | Initialize sorted set from existing set. |
def db_file(self, value):
assert not os.path.isfile(value), "%s already exists" % value
self._db_file = value | module function_definition identifier parameters identifier identifier block assert_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier binary_operator string string_start string_content string_end identifier expression_statement assignment attribute identifier iden... | Setter for _db_file attribute |
def check_outputs(self):
self.outputs = self.expand_filenames(self.outputs)
result = False
if self.files_exist(self.outputs):
if self.dependencies_are_newer(self.outputs, self.inputs):
result = True
print("Dependencies are newer than outputs.")
... | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier false if_statement call attribute identifier identifier argument... | Check for the existence of output files |
def read_ssh_config(path):
with open(path, "r") as fh_:
lines = fh_.read().splitlines()
return SshConfig(lines) | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute call attribute identifier ... | Read ssh config file and return parsed SshConfig |
def _get_argname_value(self, argname):
argvalue = getattr(self, '__get_{0}__'.format(argname), None)
if argvalue is not None and callable(argvalue):
argvalue = argvalue()
if argvalue is None:
argvalue = getattr(self, argname, None)
if argvalue is None:
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier none if_statement boolean_operator comparison_operator identif... | Return the argname value looking up on all possible attributes |
def dnld_goa(self, species, ext='gaf', item=None, fileout=None):
basename = self.get_basename(species, ext, item)
src = os.path.join(self.ftp_src_goa, species.upper(), "{F}.gz".format(F=basename))
dst = os.path.join(os.getcwd(), basename) if fileout is None else fileout
dnld_file(src, ds... | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identi... | Download GOA source file name on EMBL-EBI ftp server. |
def _assemble_conversion(stmt):
reactants = _join_list([_assemble_agent_str(r) for r in stmt.obj_from])
products = _join_list([_assemble_agent_str(r) for r in stmt.obj_to])
if stmt.subj is not None:
subj_str = _assemble_agent_str(stmt.subj)
stmt_str = '%s catalyzes the conversion of %s into ... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement assignment identifier call identifier argum... | Assemble a Conversion statement into text. |
def _connect(self):
try:
if sys.version_info[:2] >= (2,6):
self._conn = telnetlib.Telnet(self._amihost, self._amiport,
connTimeout)
else:
self._conn = telnetlib.Telnet(self._amihost, self._amiport)
exc... | module function_definition identifier parameters identifier block try_statement block if_statement comparison_operator subscript attribute identifier identifier slice integer tuple integer integer block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list at... | Connect to Asterisk Manager Interface. |
def adjustMask(self):
if self.currentMode() == XPopupWidget.Mode.Dialog:
self.clearMask()
return
path = self.borderPath()
bitmap = QBitmap(self.width(), self.height())
bitmap.fill(QColor('white'))
with XPainter(bitmap) as painter:
paint... | module function_definition identifier parameters identifier block if_statement comparison_operator call attribute identifier identifier argument_list attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list return_statement expression_statement a... | Updates the alpha mask for this popup widget. |
def decode(bstr):
bstr = bstr.replace(b':', b'')
if len(bstr) != 12:
raise ValueError('not a valid MAC address: {!r}'.format(bstr))
try:
return int(bstr, 16)
except ValueError:
raise ValueError('not a valid MAC address: {!r}'.format(bstr)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end if_statement comparison_operator call identifier argument_list identifier integer b... | Decodes an ASCII encoded binary MAC address tring into a number. |
def check_webhook_secret(app_configs=None, **kwargs):
from . import settings as djstripe_settings
messages = []
secret = djstripe_settings.WEBHOOK_SECRET
if secret and not secret.startswith("whsec_"):
messages.append(
checks.Warning(
"DJSTRIPE_WEBHOOK_SECRET does not look valid",
hint="It should start ... | module function_definition identifier parameters default_parameter identifier none dictionary_splat_pattern identifier block import_from_statement relative_import import_prefix aliased_import dotted_name identifier identifier expression_statement assignment identifier list expression_statement assignment identifier att... | Check that DJSTRIPE_WEBHOOK_SECRET looks correct |
def getSectionName(configObj,stepnum):
for key in configObj.keys():
if key.find('STEP '+str(stepnum)+':') >= 0:
return key | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator call attribute identifier identifier argument_list binary_operator binary_operator string string_start string_content string_end... | Return section label based on step number. |
def _make_reserved_tokens_re(reserved_tokens):
if not reserved_tokens:
return None
escaped_tokens = [_re_escape(rt) for rt in reserved_tokens]
pattern = "(%s)" % "|".join(escaped_tokens)
reserved_tokens_re = _re_compile(pattern)
return reserved_tokens_re | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement none expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier binary_... | Constructs compiled regex to parse out reserved tokens. |
def remove_null_proxy_kwarg(func):
def wrapper(*args, **kwargs):
if 'proxy' in kwargs:
del kwargs['proxy']
return func(*args, **kwargs)
return wrapper | module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator string string_start string_content string_end identifier block delete_statement subscript identifier string... | decorator, to remove a 'proxy' keyword argument. For wrapping certain Manager methods |
def stop_tracking_host(self):
try:
self.server.hosts.remove(self.client_address[0])
if hasattr(self.server.module, 'on_shutdown'):
self.server.module.on_shutdown(self.server.context, self.server.connection)
except ValueError:
pass | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list subscript attribute identifier identifier integer if_statement call identifier argument_list attribute attribute identif... | This gets called when a module has finshed executing, removes the host from the connection tracker list |
def copyproj(src_fn, dst_fn, gt=True):
src_ds = gdal.Open(src_fn, gdal.GA_ReadOnly)
dst_ds = gdal.Open(dst_fn, gdal.GA_Update)
dst_ds.SetProjection(src_ds.GetProjection())
if gt:
src_gt = np.array(src_ds.GetGeoTransform())
src_dim = np.array([src_ds.RasterXSize, src_ds.RasterYSize])
... | module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier ide... | Copy projection and geotransform from one raster file to another |
async def _scheduleLoop(self):
while True:
try:
timeout = None if not self.apptheap else self.apptheap[0].nexttime - time.time()
if timeout is None or timeout >= 0.0:
await asyncio.wait_for(self._wake_event.wait(), timeout=timeout)
exce... | module function_definition identifier parameters identifier block while_statement true block try_statement block expression_statement assignment identifier conditional_expression none not_operator attribute identifier identifier binary_operator attribute subscript attribute identifier identifier integer identifier call... | Task loop to issue query tasks at the right times. |
def to_binary(self):
node = self.node.to_binary()
if node is self.node:
return self
else:
return _expr(node) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block return_statement identifier else_clause block return_stat... | Convert N-ary operators to binary operators. |
def _error_if_symbol_unused(symbol_word,
technical_words_dictionary,
line_offset,
col_offset):
result = technical_words_dictionary.corrections(symbol_word,
distance=5,
... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier integer keyword_argument identifier integer if_statement not_operator attribute identifi... | Return SpellcheckError if this symbol is not used in the code. |
def render(obj):
def get_v(v):
return v % env if isinstance(v, basestring) else v
if isinstance(obj, types.StringType):
return obj % env
elif isinstance(obj, types.TupleType) or isinstance(obj, types.ListType):
rv = []
for v in obj:
rv.append(get_v(v))
elif is... | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block return_statement conditional_expression binary_operator identifier identifier call identifier argument_list identifier identifier identifier if_statement call identifier argument_list identifier ... | Convienently render strings with the fabric context |
def remove(self):
"Remove the hook from the model."
if not self.removed:
self.hook.remove()
self.removed=True | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement not_operator attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignmen... | Remove the hook from the model. |
def numeric(basetype, min_=None, max_=None):
min_ = basetype(min_) if min_ is not None else None
max_ = basetype(max_) if max_ is not None else None
def _numeric(string):
value = basetype(string)
if min_ is not None and value < min_ or max_ is not None and value > max_:
msg = "%r... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier conditional_expression call identifier argument_list identifier comparison_operator identifier none none expression_statement assignment identi... | Validator for numeric params |
def show_md5_view(md5):
if not WORKBENCH:
return flask.redirect('/')
md5_view = WORKBENCH.stream_sample(md5)
return flask.render_template('templates/md5_view.html', md5_view=list(md5_view), md5=md5) | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list ide... | Renders template with `stream_sample` of the md5. |
def obj2unicode(obj):
if isinstance(obj, unicode_type):
return obj
elif isinstance(obj, bytes_type):
try:
return unicode_type(obj, 'utf-8')
except UnicodeDecodeError as strerror:
sys.stderr.write("UnicodeDecodeError exception for string '%s': %s\n" % (obj, strerro... | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier elif_clause call identifier argument_list identifier identifier block try_statement block return_statement call identifier argument_list identifier string ... | Return a unicode representation of a python object |
def _add_tile(self, new_tile, ijk):
tile_label = "{0}_{1}".format(self.name, '-'.join(str(d) for d in ijk))
self.add(new_tile, label=tile_label, inherit_periodicity=False) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier... | Add a tile with a label indicating its tiling position. |
def NormalizeScopes(scope_spec):
if isinstance(scope_spec, six.string_types):
return set(scope_spec.split(' '))
elif isinstance(scope_spec, collections.Iterable):
return set(scope_spec)
raise exceptions.TypecheckError(
'NormalizeScopes expected string or iterable, found %s' % (
... | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier attribute identifier identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end elif_clause call i... | Normalize scope_spec to a set of strings. |
def _call(self, x):
out = x.asarray().ravel()[self._indices_flat]
if self.variant == 'point_eval':
weights = 1.0
elif self.variant == 'integrate':
weights = getattr(self.domain, 'cell_volume', 1.0)
else:
raise RuntimeError('bad variant {!r}'.format(sel... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript call attribute call attribute identifier identifier argument_list identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier st... | Return values at indices, possibly weighted. |
def generate_html_report(base_path, asset_id):
jenv = Environment(loader=PackageLoader('swchange', 'templates'))
s = Session()
asset = s.query(AssetList).filter_by(id=asset_id).first()
if not asset:
print 'Invalid Asset ID (%s)!' % asset_id
return
filename = os.path.join(base_path, '... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement... | Generates the HTML report and dumps it into the specified filename |
def extract_file_name(content_dispo):
content_dispo = content_dispo.decode('unicode-escape').strip('"')
file_name = ""
for key_val in content_dispo.split(';'):
param = key_val.strip().split('=')
if param[0] == "filename":
file_name = param[1].strip('"')
break
retu... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_content string_end expression_statement assignm... | Extract file name from the input request body |
def create_doc_jar(self, target, open_jar, version):
javadoc = self._java_doc(target)
scaladoc = self._scala_doc(target)
if javadoc or scaladoc:
jar_path = self.artifact_path(open_jar, version, suffix='-javadoc')
with self.open_jar(jar_path, overwrite=True, compressed=True) as open_jar:
... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statemen... | Returns a doc jar if either scala or java docs are available for the given target. |
def close(self):
if self.sock:
self.sock.close()
self.sock = None
if self.__response:
self.__response.close()
self.__response = None
self.__state = _CS_IDLE | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none if_statement attribute identifier identif... | Close the connection to the HTTP server. |
def log_connection_info(self):
_ctrl_c_lines = [
'NOTE: Ctrl-C does not work to exit from the command line.',
'To exit, just close the window, type "exit" or "quit" at the '
'qtconsole prompt, or use Ctrl-\\ in UNIX-like environments '
'(at the command prompt).']
... | module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end concatenated_string string string_start string_content string_end string string_start string_content escape_sequence string_end string string_start string_conte... | Overridden to customize the start-up message printed to the terminal |
def jinja_env(self) -> Environment:
if self._jinja_env is None:
self._jinja_env = self.create_jinja_environment()
return self._jinja_env | module function_definition identifier parameters identifier type identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list return_statement attribute identifier identifie... | The jinja environment used to load templates. |
def collapse_spaces(text):
if not isinstance(text, six.string_types):
return text
return COLLAPSE_RE.sub(WS, text).strip(WS) | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block return_statement identifier return_statement call attribute call attribute identifier identifier argument_list identifier identifier identifier argum... | Remove newlines, tabs and multiple spaces with single spaces. |
def copy(self):
return Eq(
self._lhs, self._rhs, tag=self._tag,
_prev_lhs=self._prev_lhs, _prev_rhs=self._prev_rhs,
_prev_tags=self._prev_tags) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identi... | Return a copy of the equation |
def fail_with_error(self, err_msg, err_operation=None):
if err_operation:
err_msg = 'ERROR: "{err_msg}", while: {err_operation}'.format(
err_msg=err_msg, err_operation=err_operation)
sys.stderr.write(err_msg)
sys.exit(1) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_arg... | log an error to std err for ansible-playbook to consume and exit |
def getmethattr(obj, meth):
if hasmethod(obj, meth):
return getattr(obj, meth)()
elif hasvar(obj, meth):
return getattr(obj, meth)
return None | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement call call identifier argument_list identifier identifier argument_list elif_clause call identifier argument_list identifier identifier block return_stateme... | Returns either the variable value or method invocation |
def print_result(result):
try:
print result
except UnicodeEncodeError:
if sys.stdout.encoding:
print result.encode(sys.stdout.encoding, 'replace')
else:
print result.encode('utf8')
except:
print "Unexpected error attempting to print result" | module function_definition identifier parameters identifier block try_statement block print_statement identifier except_clause identifier block if_statement attribute attribute identifier identifier identifier block print_statement call attribute identifier identifier argument_list attribute attribute identifier identi... | Print the result, ascii encode if necessary |
def _check_bios_resource(self, properties=[]):
system = self._get_host_details()
if ('links' in system['Oem']['Hp'] and
'BIOS' in system['Oem']['Hp']['links']):
bios_uri = system['Oem']['Hp']['links']['BIOS']['href']
status, headers, bios_settings = self._rest_get... | module function_definition identifier parameters identifier default_parameter identifier list block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement parenthesized_expression boolean_operator comparison_operator string string_start string_content string_end subsc... | Check if the bios resource exists. |
def arrays_to_hdf5(filename="cache.hdf5"):
return Registry(
types={
numpy.ndarray: SerNumpyArrayToHDF5(filename, "cache.lock")
},
hooks={
'<ufunc>': SerUFunc()
},
hook_fn=_numpy_hook
) | module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block return_statement call identifier argument_list keyword_argument identifier dictionary pair attribute identifier identifier call identifier argument_list identifier string string_start string... | Returns registry for serialising arrays to a HDF5 reference. |
def wait_for_browser_close(b):
if b:
if not __ACTIVE:
wait_failover(wait_for_browser_close)
return
wait_for_frame(b.GetBrowserImp().GetMainFrame()) | module function_definition identifier parameters identifier block if_statement identifier block if_statement not_operator identifier block expression_statement call identifier argument_list identifier return_statement expression_statement call identifier argument_list call attribute call attribute identifier identifier... | Can be used to wait until a TBrowser is closed |
def create_response_object(self, service_id, version_number, name, status="200", response="OK", content="", request_condition=None, cache_condition=None):
body = self._formdata({
"name": name,
"status": status,
"response": response,
"content": content,
"request_condition": request_condition,
"cache_... | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_end default_parameter... | Creates a new Response Object. |
def dump(self):
for seg in self.seglist:
print("==== %08x-%08x" % (seg.startea, seg.endea))
if seg.endea - seg.startea < 30:
for ea in range(seg.startea, seg.endea):
print(" %08x: %08x" % (ea, self.getFlags(ea)))
else:
... | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier if_state... | print first and last bits for each segment |
def load_data_subject_areas(subject_file):
lst = []
if os.path.exists(subject_file):
with open(subject_file, 'r') as f:
for line in f:
lst.append(line.strip())
else:
print('MISSING DATA FILE (subject_file) ' , subject_file)
print('update your config.py or ... | module function_definition identifier parameters identifier block expression_statement assignment identifier list if_statement call attribute attribute identifier identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_s... | reads the subject file to a list, to confirm config is setup |
def create(ctx, to, amount, symbol, secret, hash, account, expiration):
ctx.blockchain.blocking = True
tx = ctx.blockchain.htlc_create(
Amount(amount, symbol),
to,
secret,
hash_type=hash,
expiration=expiration,
account=account,
)
tx.pop("trx", None)
pr... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier true expression_statement assignment identifier call attribute attribute identifier identifi... | Create an HTLC contract |
def job(name, **kwargs):
return task(name=name, schedulable=True, base=JobTask,
bind=True, **kwargs) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier true keyword_argument identifier identifier keyword_argument identifier true dictionary_splat identifier | A shortcut decorator for declaring jobs |
def get(self, key, default=None):
for k, v in self:
if k == key:
return v
return default | module function_definition identifier parameters identifier identifier default_parameter identifier none block for_statement pattern_list identifier identifier identifier block if_statement comparison_operator identifier identifier block return_statement identifier return_statement identifier | Retrieve the first value for a marker or None. |
def _convert_punctuation(punctuation, conversion_table):
if punctuation in conversion_table:
return conversion_table[punctuation]
return re.escape(punctuation) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block return_statement subscript identifier identifier return_statement call attribute identifier identifier argument_list identifier | Return a regular expression for a punctuation string. |
def _start_date_of_year(year: int) -> datetime.date:
jan_one = datetime.date(year, 1, 1)
diff = 7 * (jan_one.isoweekday() > 3) - jan_one.isoweekday()
return jan_one + datetime.timedelta(days=diff) | module function_definition identifier parameters typed_parameter identifier type identifier type attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer integer expression_statement assignment identifier binary_operator binar... | Return start date of the year using MMWR week rules |
def icons(self, strip_ext=False):
result = [f for f in self._stripped_files if self._icons_pattern.match(f)]
if strip_ext:
result = [strip_suffix(f, '\.({ext})'.format(ext=self._icons_ext), regex=True) for f in result]
return result | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause call attribute attribute identifier identifier identifier argument_list identif... | Get all icons in this DAP, optionally strip extensions |
def delete_scheme(self):
scheme_name = self.current_scheme
answer = QMessageBox.warning(self, _("Warning"),
_("Are you sure you want to delete "
"this scheme?"),
QMessageBox.Yes | QMessageBox... | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list string string_start string_content string_en... | Deletes the currently selected custom color scheme. |
def shutdown(self):
if self._proxy:
os.sync()
self._proxy(*self._args) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list list_splat attribute identifier identifier | Call the dbus proxy to start the shutdown. |
def process_msg(self, msg):
jmsg = json.loads(msg)
msgtype = jmsg['MessageType']
msgdata = jmsg['Data']
_LOGGER.debug('New websocket message recieved of type: %s', msgtype)
if msgtype == 'Sessions':
self._sessions = msgdata
self.update_device_list(self._se... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignm... | Process messages from the event stream. |
def to_str(obj):
if isinstance(obj, str):
return obj
if isinstance(obj, unicode):
return obj.encode('utf-8')
return str(obj) | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list string string_st... | convert a object to string |
def parse_opml_bytes(data: bytes) -> OPML:
root = parse_xml(BytesIO(data)).getroot()
return _parse_opml(root) | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call attribute call identifier argument_list call identifier argument_list identifier identifier argument_list return_statement call identifier argument_list ident... | Parse an OPML document from a byte-string containing XML data. |
def _vertex_list_to_dataframe(ls, id_column_name):
assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.'
cols = reduce(set.union, (set(v.attr.keys()) for v in ls))
df = pd.DataFrame({id_column_name: [v.vid for v in ls]})
for c in cols:
df[c] = [v.attr.g... | module function_definition identifier parameters identifier identifier block assert_statement identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier generator_expression call identifier argument_list call attribut... | Convert a list of vertices into dataframe. |
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
_ = stderr, time_taken, args, knowledge_base
self.CheckReturn(cmd, return_val)
result = rdf_protodict.AttributedDict()
for k, v in iteritems(self.lexer.ParseToOrderedDict(stdout)):
key = k.replace(".", ... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier expression_list identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list id... | Parse the sysctl output. |
def _onLeftButtonUp(self, evt):
x = evt.GetX()
y = self.figure.bbox.height - evt.GetY()
evt.Skip()
if self.HasCapture(): self.ReleaseMouse()
FigureCanvasBase.button_release_event(self, x, y, 1, guiEvent=evt) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator attribute attribute attribute identifier identifier identifier identifier call attribute i... | End measuring on an axis. |
def make_scrape_request(session, url, mode='get', data=None):
try:
html = session.request(mode, url, data=data)
except RequestException:
raise VooblyError('failed to connect')
if SCRAPE_FETCH_ERROR in html.text:
raise VooblyError('not logged in')
if html.status_code != 200 or SCR... | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifie... | Make a request to URL. |
def _close(self):
self.client.stop()
self.open = False
self.waiting = False | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier false | Close the TCP connection. |
def insert(self, storagemodel) -> StorageTableModel:
modeldefinition = self.getmodeldefinition(storagemodel, True)
try:
modeldefinition['tableservice'].insert_or_replace_entity(modeldefinition['tablename'], storagemodel.entity())
storagemodel._exists = True
except AzureMi... | module function_definition identifier parameters identifier identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier true try_statement block expression_statement call attribute subscript identifier string string_start string_content strin... | insert model into storage |
def _gitignore_entry_to_regex(entry):
ret = entry.strip()
ret = ret.replace('.', '\.')
ret = ret.replace('*', '.*')
return ret | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start ... | Take a path that you might find in a .gitignore file and turn it into a regex |
def pack(self):
block = bytearray(self.size)
self.pack_into(block)
return block | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | convenience function for packing |
def _bulk_state(saltfunc, lbn, workers, profile):
ret = {'name': lbn,
'result': True,
'changes': {},
'comment': ''}
if not isinstance(workers, list):
ret['result'] = False
ret['comment'] = 'workers should be a list not a {0}'.format(
type(workers)
... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end true pair string string_start string_content string_en... | Generic function for bulk worker operation |
def cut_references(text_lines):
ref_sect_start = find_reference_section(text_lines)
if ref_sect_start is not None:
start = ref_sect_start["start_line"]
end = find_end_of_reference_section(text_lines, start,
ref_sect_start["marker"],
... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier subscript identifier string string_start string_content string_end expre... | Return the text lines with the references cut. |
def erase_lines(n=1):
for _ in range(n):
print(codes.cursor["up"], end="")
print(codes.cursor["eol"], end="") | module function_definition identifier parameters default_parameter identifier integer block for_statement identifier call identifier argument_list identifier block expression_statement call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end keyword_argument ... | Erases n lines from the screen and moves the cursor up to follow |
def _read_linguas_from_files(env, linguas_files=None):
import SCons.Util
import SCons.Environment
global _re_comment
global _re_lang
if not SCons.Util.is_List(linguas_files) \
and not SCons.Util.is_String(linguas_files) \
and not isinstance(linguas_files, SCons.Node.FS.Base) ... | module function_definition identifier parameters identifier default_parameter identifier none block import_statement dotted_name identifier identifier import_statement dotted_name identifier identifier global_statement identifier global_statement identifier if_statement boolean_operator boolean_operator boolean_operato... | Parse `LINGUAS` file and return list of extracted languages |
def _config():
status_url = __salt__['config.get']('nagios.status_url') or \
__salt__['config.get']('nagios:status_url')
if not status_url:
raise CommandExecutionError('Missing Nagios URL in the configuration.')
username = __salt__['config.get']('nagios.username') or \
__salt__['conf... | module function_definition identifier parameters block expression_statement assignment identifier boolean_operator call subscript identifier string string_start string_content string_end argument_list string string_start string_content string_end line_continuation call subscript identifier string string_start string_co... | Get configuration items for URL, Username and Password |
def _get_host_details(self):
status, headers, system = self._rest_get('/rest/v1/Systems/1')
if status < 300:
stype = self._get_type(system)
if stype not in ['ComputerSystem.0', 'ComputerSystem.1']:
msg = "%s is not a valid system type " % stype
rai... | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier integer block expression_statement ... | Get the system details. |
def reset(self):
with self.lock:
if self.cache:
if self.use_tmp:
shutil.rmtree(self.tmp_dir, ignore_errors=True)
else:
self.templates = {} | module function_definition identifier parameters identifier block with_statement with_clause with_item attribute identifier identifier block if_statement attribute identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attri... | Resets the cache of compiled templates. |
def log_exceptions(self, c, broker):
if c in broker.exceptions:
ex = broker.exceptions.get(c)
ex = "Exception in {0} - {1}".format(dr.get_name(c), str(ex))
self.logit(ex, self.pid, self.user, "insights-run", logging.ERROR) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement ass... | Gets exceptions to be logged and sends to logit function to be logged to syslog |
def from_file(cls, path, encoding, dialect, fields, converters, field_index):
return cls(open(path, 'r', encoding=encoding), dialect, fields, converters, field_index) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier block return_statement call identifier argument_list call identifier argument_list identifier string string_start string_content string_end keyword_argument identifier identifier identifier iden... | Read delimited text from a text file. |
def addAttachment(self, attachment):
if not isinstance(attachment, (list, tuple)):
attachment = [attachment]
original = self.getAttachment() or []
original = map(api.get_uid, original)
attachment = map(api.get_uid, attachment)
attachment = filter(lambda at: at not in ... | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier list identifier expression_statement assignment identifier boolean_operator call attribute identifi... | Adds an attachment or a list of attachments to the Analysis Request |
def contains_all(self, other):
dtype = getattr(other, 'dtype', None)
if dtype is None:
dtype = np.result_type(*other)
return is_numeric_dtype(dtype) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement comparison_operator identifier none block expression_statement assignment identifier call attri... | Return ``True`` if ``other`` is a sequence of complex numbers. |
def _BuildIndex(self):
self._index = {}
for i, k in enumerate(self._keys):
self._index[k] = i | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment subscript attribute identifier... | Recreate the key index. |
def launch(self, callback_function=None):
self._check_registered()
self._socket_client.receiver_controller.launch_app(
self.supporting_app_id, callback_function=callback_function) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier ke... | If set, launches app related to the controller. |
def _get_categorical_score(
self,
profile: List,
negated_classes: List,
categories: List,
negation_weight: Optional[float] = 1,
ic_map: Optional[Dict[str, float]] = None) -> float:
if ic_map is None:
ic_map = self.ic_store.get_p... | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier integer typed_default_parameter iden... | The average of the simple scores across a list of categories |
def _generate_validator(self, field):
validator = self._determine_validator_type(field.data_type,
fmt_var(field.name),
field.has_default)
value = fmt_var(
field.name) if not field.has_defaul... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement as... | Emits validator if data type has associated validator. |
def _run_atstart():
global _atstart
for callback, args, kwargs in _atstart:
callback(*args, **kwargs)
del _atstart[:] | module function_definition identifier parameters block global_statement identifier for_statement pattern_list identifier identifier identifier identifier block expression_statement call identifier argument_list list_splat identifier dictionary_splat identifier delete_statement subscript identifier slice | Hook frameworks must invoke this before running the main hook body. |
def _get_verts_and_connect(self, paths):
verts = np.vstack(paths)
gaps = np.add.accumulate(np.array([len(x) for x in paths])) - 1
connect = np.ones(gaps[-1], dtype=bool)
connect[gaps[:-1]] = False
return verts, connect | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list call at... | retrieve vertices and connects from given paths-list |
def pretty(self, indent=0, debug=False):
debug_details = ''
if debug:
debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)
obj = "'%s'" % self.obj if isinstance(self.obj, basestring) else repr(self.obj)
return (' ' * indent) + ('%s(%s%s)' % (... | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier false block expression_statement assignment identifier string string_start string_end if_statement identifier block expression_statement augmented_assignment identifier binary_operator string st... | Return a pretty formatted representation of self. |
def save(self):
kf = self._kf
for prop in self.properties:
self._DL[prop[0]].append(getattr(kf, prop[0]))
v = copy.deepcopy(kf.__dict__)
if self._skip_private:
for key in list(v.keys()):
if key.startswith('_'):
print('deleting',... | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement call attribute subscript attribute identifier identifier subscript identifier integer identifie... | save the current state of the Kalman filter |
def commit_all(self):
while self._transaction_nesting_level != 0:
if not self._auto_commit and self._transaction_nesting_level == 1:
return self.commit()
self.commit() | module function_definition identifier parameters identifier block while_statement comparison_operator attribute identifier identifier integer block if_statement boolean_operator not_operator attribute identifier identifier comparison_operator attribute identifier identifier integer block return_statement call attribute... | Commits all current nesting transactions. |
def create_image_list(self, dataset, fns_idxs):
"Create a list of images, filenames and labels but first removing files that are not supposed to be displayed."
items = dataset.x.items
if self._duplicates:
chunked_idxs = chunks(fns_idxs, 2)
chunked_idxs = [chunk for chunk ... | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement attribute identifier identifier block expression_stateme... | Create a list of images, filenames and labels but first removing files that are not supposed to be displayed. |
def decimal_round(number, num_digits, rounding=ROUND_HALF_UP):
exp = Decimal(10) ** -num_digits
if num_digits >= 0:
return number.quantize(exp, rounding)
else:
return exp * (number / exp).to_integral_value(rounding) | module function_definition identifier parameters identifier identifier default_parameter identifier identifier block expression_statement assignment identifier binary_operator call identifier argument_list integer unary_operator identifier if_statement comparison_operator identifier integer block return_statement call ... | Rounding for decimals with support for negative digits |
def max_electronegativity(self):
maximum = 0
for e1, e2 in combinations(self.elements, 2):
if abs(Element(e1).X - Element(e2).X) > maximum:
maximum = abs(Element(e1).X - Element(e2).X)
return maximum | module function_definition identifier parameters identifier block expression_statement assignment identifier integer for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier integer block if_statement comparison_operator call identifier argument_list binary_operator... | returns the maximum pairwise electronegativity difference |
def add_dependency(self, from_task_name, to_task_name):
logger.debug('Adding dependency from {0} to {1}'.format(from_task_name, to_task_name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: %s"
% self.st... | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement not_operator attribute attribute identi... | Add a dependency between two tasks. |
def bot_config(player_config_path: Path, team: Team) -> 'PlayerConfig':
bot_config = PlayerConfig()
bot_config.bot = True
bot_config.rlbot_controlled = True
bot_config.team = team.value
bot_config.config_path = str(player_config_path.absolute())
config_bundle = get_bot_co... | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier id... | A function to cover the common case of creating a config for a bot. |
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
_ = stderr, time_taken, args, knowledge_base
self.CheckReturn(cmd, return_val)
packages = []
for line in stdout.decode("utf-8").splitlines()[1:]:
cols = line.split()
name_arch, version, source = c... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier expression_list identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list id... | Parse the yum output. |
def transform(self, trans):
_data = deepcopy(self._data)
_data.data_block[:, 0:3] = trans(_data.data_block[:, 0:3])
return FstNeuron(_data, self.name) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment subscript attribute identifier identifier slice slice integer integer call identifier argument_list subscr... | Return a copy of this neuron with a 3D transformation applied |
def unnest(c, elem, ignore_whitespace=False):
parent = elem.getparent()
gparent = parent.getparent()
index = parent.index(elem)
preparent = etree.Element(parent.tag)
preparent.text, parent.text = (parent.text or ''), ''
for k in parent.attrib.keys():
pr... | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement... | unnest the element from its parent within doc. MUTABLE CHANGES |
def parse_combo(self, combo, modes_set, modifiers_set, pfx):
mode, mods, trigger = None, set([]), combo
if '+' in combo:
if combo.endswith('+'):
trigger, combo = '+', combo[:-1]
if '+' in combo:
items = set(combo.split('+'))
... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier expression_list none call identifier argument_list list identifier if_statement comparison_operator string string_start string_conte... | Parse a string into a mode, a set of modifiers and a trigger. |
def save(self):
try:
os.makedirs(os.path.dirname(self._configfile))
except:
pass
with open(self._configfile, 'w') as f:
self._config.write(f) | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier except_clause block pass_statement with_statement with_cla... | Store config back to file. |
def autoescape(filter_func):
@evalcontextfilter
@wraps(filter_func)
def _autoescape(eval_ctx, *args, **kwargs):
result = filter_func(*args, **kwargs)
if eval_ctx.autoescape:
result = Markup(result)
return result
return _autoescape | module function_definition identifier parameters identifier block decorated_definition decorator identifier decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment iden... | Decorator to autoescape result from filters. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.