Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
13,300 | def write_file_to_zip_with_neutral_metadata(zfile, filename, content):
info = zipfile.ZipInfo(filename, date_time=(2015, 10, 21, 7, 28, 0))
info.compress_type = zipfile.ZIP_DEFLATED
info.comment = "".encode()
info.create_system = 0
zfile.writestr(info, content) | Write the string `content` to `filename` in the open ZipFile `zfile`.
Args:
zfile (ZipFile): open ZipFile to write the content into
filename (str): the file path within the zip file to write into
content (str): the content to write into the zip
Returns: None |
13,301 | def next(cls):
try:
with db.session.begin_nested():
obj = cls()
db.session.add(obj)
except IntegrityError:
with db.session.begin_nested():
cls._set_sequence(cls.max())
obj... | Return next available record identifier. |
13,302 | def upload_html(destination, html, name=None):
[project, path, n] = parse_destination(destination)
try:
dxfile = dxpy.upload_string(html, media_type="text/html", project=project, folder=path, hidden=True, name=name or None)
return dxfile.get_id()
except dxpy.DXAPIError as ex:
pa... | Uploads the HTML to a file on the server |
13,303 | def call_for_each_tower(
towers, func, devices=None, use_vs=None):
ret = []
if devices is not None:
assert len(devices) == len(towers)
if use_vs is not None:
assert len(use_vs) == len(towers)
tower_names = [.format(idx) for idx in range(len(... | Run `func` on all GPUs (towers) and return the results.
Args:
towers (list[int]): a list of GPU id.
func: a lambda to be called inside each tower
devices: a list of devices to be used. By default will use '/gpu:{tower}'
use_vs (list[bool]): list of use_vs to pass... |
13,304 | def split_and_strip_without(string, exclude, separator_regexp=None):
result = split_and_strip(string, separator_regexp)
if not exclude:
return result
return [x for x in result if x not in exclude] | Split a string into items, and trim any excess spaces
Any items in exclude are not in the returned list
>>> split_and_strip_without('fred, was, here ', ['was'])
['fred', 'here'] |
13,305 | def dfs_postorder(self, reverse=False):
stack = deque()
stack.append(self)
visited = set()
while stack:
node = stack.pop()
if node in visited:
yield node
else:
visited.add(node)
stack.append(node... | Generator that returns each element of the tree in Postorder order.
Keyword arguments:
reverse -- if true, the search is done from right to left. |
13,306 | def match(self, pattern):
m = pattern.match(self._string, self._index)
if m:
self._index = m.end()
return m | Perform regex match at index. |
13,307 | def tredparse(args):
p = OptionParser(tredparse.__doc__)
p.add_option(, default=300, type="int",
help="Maximum number of repeats")
add_simulate_options(p)
opts, args, iopts = p.set_image_options(args, figsize="10x10")
if len(args) != 0:
sys.exit(not p.print_help())
... | %prog tredparse
Compare performances of various variant callers on simulated STR datasets.
Adds coverage comparisons as panel C and D. |
13,308 | def _common_query_parameters(self, doc_type, includes, owner,
promulgated_only, series, sort):
queries = []
if includes is not None:
queries.extend([(, include) for include in includes])
if doc_type is not None:
queries.append((, ... | Extract common query parameters between search and list into slice.
@param includes What metadata to return in results (e.g. charm-config).
@param doc_type Filter to this type: bundle or charm.
@param promulgated_only Whether to filter to only promulgated charms.
@param sort Sorting the... |
13,309 | def divrank_scipy(G, alpha=0.25, d=0.85, personalization=None,
max_iter=100, tol=1.0e-6, nstart=None, weight=,
dangling=None):
import scipy.sparse
N = len(G)
if N == 0:
return {}
nodelist = G.nodes()
M = nx.to_scipy_sparse_matrix(G, nodelist=nodelis... | Returns the DivRank (Diverse Rank) of the nodes in the graph.
This code is based on networkx.pagerank_scipy |
13,310 | def compare(self, statement_a, statement_b):
document_a = self.nlp(statement_a.text.lower())
document_b = self.nlp(statement_b.text.lower())
statement_a_lemmas = set([
token.lemma_ for token in document_a if not token.is_stop
])
statement_b_lemmas =... | Return the calculated similarity of two
statements based on the Jaccard index. |
13,311 | def run(self, cmd, sudo=False, ignore_error=False, success_status=(0,),
error_callback=None, custom_log=None, retry=0):
self._check_started()
cmd_output = io.StringIO()
channel = self._get_channel()
cmd = self._prepare_cmd(cmd, sudo=sudo)
if not custom_log:
... | Run a command on the remote host.
The command is run on the remote host, if there is a redirected host
then the command will be run on that redirected host. See __init__.
:param cmd: the command to run
:type cmd: str
:param sudo: True if the command should be run with sudo, thi... |
13,312 | def plot(result_pickle_file_path, show, plot_save_file):
import pandas as pd
from .plot import plot_result
result_dict = pd.read_pickle(result_pickle_file_path)
plot_result(result_dict, show, plot_save_file) | [sys_analyser] draw result DataFrame |
13,313 | def generate_config_set(self, config):
if isinstance(config, dict):
self.config = [(config, 1.0)]
elif isinstance(config, list):
total_weight = 0.
self.config = []
for params in config:
weight = params[]
... | Generates a list of magnitude frequency distributions and renders as
a tuple
:param dict/list config:
Configuration paramters of magnitude frequency distribution |
13,314 | def parse_on_condition(self, node):
try:
test = node.lattrib[]
except:
self.raise_error()
event_handler = OnCondition(test)
self.current_regime.add_event_handler(event_handler)
self.current_event_handler = event_handler
sel... | Parses <OnCondition>
@param node: Node containing the <OnCondition> element
@type node: xml.etree.Element |
13,315 | def timebinlc_worker(task):
outdirlcformatlcformatdirtimecolsmagcolserrcolsminbinelems
lcfile, binsizesec, kwargs = task
try:
binnedlc = timebinlc(lcfile, binsizesec, **kwargs)
LOGINFO( %
(lcfile, binsizesec, binnedlc))
return binnedlc
except Exception as e:
... | This is a parallel worker for the function below.
Parameters
----------
task : tuple
This is of the form::
task[0] = lcfile
task[1] = binsizesec
task[3] = {'outdir','lcformat','lcformatdir',
'timecols','magcols','errcols','minbinelems'}
... |
13,316 | def T11(word, rules):
WORD = word
offset = 0
for vvv in precedence_sequences(WORD):
i = vvv.start(1) + (1 if vvv.group(1)[-1] in else 2) + offset
WORD = WORD[:i] + + WORD[i:]
offset += 1
rules += if word != WORD else
return WORD, rules | If a VVV sequence contains a /u,y/-final diphthong, insert a syllable
boundary between the diphthong and the third vowel. |
13,317 | def asterisk_to_min_max(field, time_filter, search_engine_endpoint, actual_params=None):
if actual_params:
raise NotImplemented("actual_params")
start, end = parse_solr_time_range_as_pair(time_filter)
if start == or end == :
params_stats = {
"q": "*:*",
"rows"... | traduce [* TO *] to something like [MIN-INDEXED-DATE TO MAX-INDEXED-DATE]
:param field: map the stats to this field.
:param time_filter: this is the value to be translated. think in "[* TO 2000]"
:param search_engine_endpoint: solr core
:param actual_params: (not implemented) to merge with other params.... |
13,318 | def populate_branch(self, editor, root_item, tree_cache=None):
if tree_cache is None:
tree_cache = {}
for _l in list(tree_cache.keys()):
if _l >= editor.get_line_count():
if _l in tree_cache:
... | Generates an outline of the editor's content and stores the result
in a cache. |
13,319 | def from_filename(cls, filename):
if not filename:
logger.error()
return None
if not os.path.exists(filename):
logger.error("Err: File does not exist", filename)
return None
if os.path.isdir(filename):
logger.error("Err: Fil... | Class constructor using the path to the corresponding mp3 file. The
metadata will be read from this file to create the song object, so it
must at least contain valid ID3 tags for artist and title. |
13,320 | def run(self, N=100):
th = self.proposal.rvs(size=N)
self.X = ThetaParticles(theta=th, lpost=None)
self.X.lpost = self.model.logpost(th)
lw = self.X.lpost - self.proposal.logpdf(th)
self.wgts = rs.Weights(lw=lw)
self.norm_cst = rs.log_mean_exp(lw) | Parameter
---------
N: int
number of particles
Returns
-------
wgts: Weights object
The importance weights (with attributes lw, W, and ESS)
X: ThetaParticles object
The N particles (with attributes theta, logpost)
norm_cst: flo... |
13,321 | def do_forceescape(value):
if hasattr(value, ):
value = value.__html__()
return escape(text_type(value)) | Enforce HTML escaping. This will probably double escape variables. |
13,322 | async def rset(self, timeout: DefaultNumType = _default) -> SMTPResponse:
await self._ehlo_or_helo_if_needed()
async with self._command_lock:
response = await self.execute_command(b"RSET", timeout=timeout)
if response.code != SMTPStatus.completed:
raise SMTPResp... | Send an SMTP RSET command, which resets the server's envelope
(the envelope contains the sender, recipient, and mail data).
:raises SMTPResponseException: on unexpected server response code |
13,323 | def format_output(self, rendered_widgets):
ret = [u]
for i, field in enumerate(self.fields):
label = self.format_label(field, i)
help_text = self.format_help_text(field, i)
ret.append(u % (
label, rendered_widgets[i], field.help_text and help_... | This output will yeild all widgets grouped in a un-ordered list |
13,324 | def get_events(self, start_time, end_time, ignore_cancelled = True, get_recurring_events_as_instances = True, restrict_to_calendars = []):
es = []
calendar_ids = restrict_to_calendars or self.calendar_ids
for calendar_id in calendar_ids:
now = datetime.now(tz = self.timezone... | A wrapper for events().list. Returns the events from the calendar within the specified times. Some of the interesting fields are:
description, end, htmlLink, location, organizer, start, summary
Note: "Cancelled instances of recurring events (but not the underlying recurring event) will ... |
13,325 | def _auth_req_callback_func(self, context, internal_request):
state = context.state
state[STATE_KEY] = {"requester": internal_request.requester}
try:
state_dict = context.state[consent.STATE_KEY]
except KeyError:
state_dict = context.state[consen... | This function is called by a frontend module when an authorization request has been
processed.
:type context: satosa.context.Context
:type internal_request: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal... |
13,326 | def rename(self, name, **kwargs):
return self._rename(self._dxid, {"project": self._proj,
"name": name}, **kwargs) | :param name: New name for the object
:type name: string
Renames the remote object.
The name is changed on the copy of the object in the project
associated with the handler. |
13,327 | def getIncludeAndRuntime():
include_dirs, library_dirs = [], []
py_include = distutils.sysconfig.get_python_inc()
plat_py_include = distutils.sysconfig.get_python_inc(plat_specific=1)
include_dirs.append(py_include)
if plat_py_include != py_include:
include_dirs.append(plat_py_include... | A function from distutils' build_ext.py that was updated and changed
to ACTUALLY WORK |
13,328 | def versions_request(self):
ret = self.handle_api_exceptions(, , api_ver=)
return [str_dict(x) for x in ret.json()] | List Available REST API Versions |
13,329 | def compare_digest(a, b):
py_version = sys.version_info[0]
if py_version >= 3:
return _compare_digest_py3(a, b)
return _compare_digest_py2(a, b) | Compare 2 hash digest. |
13,330 | def extract_docs():
methods = []
def _key(entry):
return
sorted_entries = sorted(Client.__dict__.items(), key=lambda x: x[0])
tree = {}
meta_key =
for attr_name, attr_value in sorted_entries:
if not hasattr(attr_value, meta_key):
continue
func = a... | Parses the nano.rpc.Client for methods that have a __doc_meta__ attribute
and saves generated docs |
13,331 | def parse_eggs_list(path):
with open(path, ) as script:
data = script.readlines()
start = 0
end = 0
for counter, line in enumerate(data):
if not start:
if in line:
start = counter + 1
if counter >= start and not end:
... | Parse eggs list from the script at the given path |
13,332 | def run_powerflow_onthefly(components, components_data, grid, export_pypsa_dir=None, debug=False):
scenario = cfg_ding0.get("powerflow", "test_grid_stability_scenario")
start_hour = cfg_ding0.get("powerflow", "start_hour")
end_hour = cfg_ding0.get("powerflow", "end_hour")
temp_id_set = 1
... | Run powerflow to test grid stability
Two cases are defined to be tested here:
i) load case
ii) feed-in case
Parameters
----------
components: dict of pandas.DataFrame
components_data: dict of pandas.DataFrame
export_pypsa_dir: str
Sub-directory in output/debug/grid/ where csv... |
13,333 | def is_spontaneous(gene, custom_id=None):
spont = re.compile("[Ss](_|)0001")
if spont.match(gene.id):
return True
elif gene.id == custom_id:
return True
else:
return False | Input a COBRApy Gene object and check if the ID matches a spontaneous ID regex.
Args:
gene (Gene): COBRApy Gene
custom_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``
Returns:
bool: If gene ID matches spontaneous ID |
13,334 | def run(self):
try:
self.owner.start_event()
while True:
while not self.incoming:
time.sleep(0.01)
while self.incoming:
command = self.incoming.popleft()
if command is None:
... | The actual event loop.
Calls the ``owner``'s :py:meth:`~Component.start_event` method,
then calls its :py:meth:`~Component.new_frame_event` and
:py:meth:`~Component.new_config_event` methods as required until
:py:meth:`~Component.stop` is called. Finally the ``owner``'s
:py:meth... |
13,335 | def home_mode_set_state(self, state, **kwargs):
if state not in (HOME_MODE_ON, HOME_MODE_OFF):
raise ValueError()
api = self._api_info[]
payload = dict({
: api[],
: ,
: api[],
: state,
: self._si... | Set the state of Home Mode |
13,336 | def keys(self):
result = []
if self.fresh_index is not None:
result += self.fresh_index.keys()
if self.opt_index is not None:
result += self.opt_index.keys()
return result | Return ids of all indexed documents. |
13,337 | def mean_return_by_quantile(factor_data,
by_date=False,
by_group=False,
demeaned=True,
group_adjust=False):
if group_adjust:
grouper = [factor_data.index.get_level_values()] + []
fac... | Computes mean returns for factor quantiles across
provided forward returns columns.
Parameters
----------
factor_data : pd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1),
containing the values for a single alpha factor, forward returns for
... |
13,338 | async def unset_lock(self, resource, lock_identifier):
try:
with await self.connect() as redis:
await redis.eval(
self.unset_lock_script,
keys=[resource],
args=[lock_identifier]
)
except aior... | Unlock this instance
:param resource: redis key to set
:param lock_identifier: uniquie id of lock
:raises: LockError if the lock resource acquired with different lock_identifier |
13,339 | def registIssue(self, CorpNum, taxinvoice, writeSpecification=False, forceIssue=False, dealInvoiceMgtKey=None,
memo=None, emailSubject=None, UserID=None):
if writeSpecification:
taxinvoice.writeSpecification = True
if forceIssue:
taxinvoice.forceIssu... | 즉시 발행
args
CorpNum : 팝빌회원 사업자번호
taxinvoice : 세금계산서 객체
writeSpecification : 거래명세서 동시작성 여부
forceIssue : 지연발행 강제여부
dealInvoiceMgtKey : 거래명세서 문서관리번호
memo : 메모
emailSubject : 메일제목, 미기재시 기본제목으로 전송
... |
13,340 | def get_border_phase(self, idn=0, idr=0):
assert idn in [-1, 0, 1]
assert idr in [-1, 0, 1]
n = self.sphere_index + self.dn * idn
r = self.radius + self.dr * idr
idn += 1
idr += 1
if self._n_border[idn, idr] == n and self._r_border[idn... | Return one of nine border fields
Parameters
----------
idn: int
Index for refractive index.
One of -1 (left), 0 (center), 1 (right)
idr: int
Index for radius.
One of -1 (left), 0 (center), 1 (right) |
13,341 | def helical_turbulent_fd_Mori_Nakayama(Re, Di, Dc):
r
term = (Re*(Di/Dc)**2)**-0.2
return 0.3*(Dc/Di)**-0.5*term*(1. + 0.112*term) | r'''Calculates Darcy friction factor for a fluid flowing inside a curved
pipe such as a helical coil under turbulent conditions, using the method of
Mori and Nakayama [1]_, also shown in [2]_ and [3]_.
.. math::
f_{curv} = 0.3\left(\frac{D_i}{D_c}\right)^{0.5}
\left[Re\left(\frac{... |
13,342 | def verbose_message(self):
if self.threshold is None:
return
return % (self.value,
self.adjective,
self.threshold) | return more complete message |
13,343 | def validate_path(ctx, param, value):
client = ctx.obj
if value is None:
from renku.models.provenance import ProcessRun
activity = client.process_commit()
if not isinstance(activity, ProcessRun):
raise click.BadParameter()
return activity.path
return valu... | Detect a workflow path if it is not passed. |
13,344 | def macro_body(self, node, frame, children=None):
frame = self.function_scoping(node, frame, children)
frame.require_output_check = False
args = frame.arguments
self.indent()
self.buffer(frame)
self.pull_locals(frame)
s... | Dump the function def of a macro or call block. |
13,345 | def srcnode(self):
srcdir_list = self.dir.srcdir_list()
if srcdir_list:
srcnode = srcdir_list[0].Entry(self.name)
srcnode.must_be_same(self.__class__)
return srcnode
return self | If this node is in a build path, return the node
corresponding to its source file. Otherwise, return
ourself. |
13,346 | def get(self, metric_id=None, **kwargs):
path =
if metric_id is not None:
path += % metric_id
return self.paginate_get(path, data=kwargs) | Get metrics
:param int metric_id: Metric ID
:return: Metrics data (:class:`dict`)
Additional named arguments may be passed and are directly transmitted
to API. It is useful to use the API search features.
.. seealso:: https://docs.cachethq.io/reference#get-metrics
.. s... |
13,347 | async def _deploy(self, charm_url, application, series, config,
constraints, endpoint_bindings, resources, storage,
channel=None, num_units=None, placement=None,
devices=None):
log.info(, charm_url)
config = {k: str(v) ... | Logic shared between `Model.deploy` and `BundleHandler.deploy`. |
13,348 | def get_code(self, timestamp=None):
return generate_twofactor_code_for_time(b64decode(self.shared_secret),
self.get_time() if timestamp is None else timestamp) | :param timestamp: time to use for code generation
:type timestamp: int
:return: two factor code
:rtype: str |
13,349 | def retrieve(self, session, lookup_keys, *args, **kwargs):
model = self._get_model(lookup_keys, session)
return self.serialize_model(model) | Retrieves a model using the lookup keys provided.
Only one model should be returned by the lookup_keys
or else the manager will fail.
:param Session session: The SQLAlchemy session to use
:param dict lookup_keys: A dictionary mapping the fields
and their expected values
... |
13,350 | def share_file(comm, path):
localrank, _ = get_local_rank_size(comm)
if comm.Get_rank() == 0:
with open(path, ) as fh:
data = fh.read()
comm.bcast(data)
else:
data = comm.bcast(None)
if localrank == 0:
os.makedirs(os.path.dirname(path), exist_ok=T... | Copies the file from rank 0 to all other ranks
Puts it in the same place on all machines |
13,351 | def iter_islast(iterable):
it = iter(iterable)
prev = next(it)
for item in it:
yield prev, False
prev = item
yield prev, True | Generate (item, islast) pairs for an iterable.
Generates pairs where the first element is an item from the iterable
source and the second element is a boolean flag indicating if it is
the last item in the sequence. |
13,352 | def path_size(path, total=False, ext=, level=None, verbosity=0):
dict_of_path_sizes = dict((d[], d[]) for d in util.find_files(path, ext=ext, level=level, verbosity=0))
if total:
return reduce(lambda tot, size: tot + size, dict_of_path_sizes.values(), 0)
return dict_of_path_sizes | Walk the file tree and query the file.stat object(s) to compute their total (or individual) size in bytes
Returns:
dict: {relative_path: file_size_in_bytes, ...}
Examples:
>>> all(d >= 0 for d in path_size(__file__).values())
True
>>> sum(path_size(os.path.dirname(__file__)).values()) ... |
13,353 | def _writeXputMaps(self, session, directory, mapCards,
name=None, replaceParamFile=None):
if self.mapType in self.MAP_TYPES_SUPPORTED:
for card in self.projectCards:
if (card.name in mapCards) and self._noneOrNumValue(card.value):
f... | GSSHAPY Project Write Map Files to File Method |
13,354 | def header(self, sheet, name):
header = sheet.row(0)
for i, column in enumerate(self.headers[name]):
header.write(i, self.headers[name][i]) | Write sheet header.
Args:
sheet: (xlwt.Worksheet.Worksheet) instance of xlwt sheet.
name: (unicode) name of sheet. |
13,355 | def select(self, *features):
for feature_name in features:
feature_module = importlib.import_module(feature_name)
try:
feature_spec_module = importlib.import_module(
feature_name +
)
if not hasattr... | selects the features given as string
e.g
passing 'hello' and 'world' will result in imports of
'hello' and 'world'. Then, if possible 'hello.feature'
and 'world.feature' are imported and select is called
in each feature module. |
13,356 | def commit(name,
repository,
tag=,
message=None,
author=None):
if not isinstance(repository, six.string_types):
repository = six.text_type(repository)
if not isinstance(tag, six.string_types):
tag = six.text_type(tag)
time_started = time.time... | .. versionchanged:: 2018.3.0
The repository and tag must now be passed separately using the
``repository`` and ``tag`` arguments, rather than together in the (now
deprecated) ``image`` argument.
Commits a container, thereby promoting it to an image. Equivalent to
running the ``docker co... |
13,357 | def unindent_selection(self, cursor):
doc = self.editor.document()
tab_len = self.editor.tab_length
nb_lines = len(cursor.selection().toPlainText().splitlines())
if nb_lines == 0:
nb_lines = 1
block = doc.findBlock(cursor.selectionStart())
assert isin... | Un-indents selected text
:param cursor: QTextCursor |
13,358 | def get_table_list(self, cursor):
"Returns a list of table names in the current database."
result = [TableInfo(SfProtectName(x[]), ) for x in self.table_list_cache[]]
return result | Returns a list of table names in the current database. |
13,359 | def object_to_json(obj, indent=2):
instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder)
return instance_json | transform object to json |
13,360 | def _DecodeUnrecognizedFields(message, pair_type):
new_values = []
codec = _ProtoJsonApiTools.Get()
for unknown_field in message.all_unrecognized_fields():
if isinstance(value_type, messages.MessageField):
decoded_value = DictToMessage(value, pair_type.value.messag... | Process unrecognized fields in message. |
13,361 | def get_salic_url(item, prefix, df_values=None):
url_keys = {
: ,
: ,
: ,
: ,
: ,
: ,
}
if df_values:
values = [item[v] for v in df_values]
url_values = dict(
zip(url_keys.keys(), values)
)
else:
url_values... | Mount a salic url for the given item. |
13,362 | def diff(self, container):
return self._result(
self._get(self._url("/containers/{0}/changes", container)), True
) | Inspect changes on a container's filesystem.
Args:
container (str): The container to diff
Returns:
(str)
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error. |
13,363 | def RemoveMethod(self, function):
self.added_methods = [dm for dm in self.added_methods if not dm.method is function] | Removes the specified function's MethodWrapper from the
added_methods list, so we don't re-bind it when making a clone. |
13,364 | def capture_heroku_database(self):
self.print_message("Capturing database backup for app " % self.args.source_app)
args = [
"heroku",
"pg:backups:capture",
"--app=%s" % self.args.source_app,
]
if self.args.use_pgbackups:
args = [
... | Capture Heroku database backup. |
13,365 | def trim_decimals(s, precision=-3):
encoded = s.encode(, )
str_val = ""
if six.PY3:
str_val = str(encoded, encoding=, errors=)[:precision]
else:
if precision == 0:
str_val = str(encoded)
else:
str_v... | Convert from scientific notation using precision |
13,366 | def _compile_mapping(self, schema, invalid_msg=None):
invalid_msg = invalid_msg or
all_required_keys = set(key for key in schema
if key is not Extra and
((self.required and not isinstance(key, (Optional, Remove))) or
... | Create validator for given mapping. |
13,367 | def _parse_hextet(self, hextet_str):
if not self._HEX_DIGITS.issuperset(hextet_str):
raise ValueError
if len(hextet_str) > 4:
raise ValueError
hextet_int = int(hextet_str, 16)
if hextet_int > 0xFFFF:
raise ValueError
return hext... | Convert an IPv6 hextet string into an integer.
Args:
hextet_str: A string, the number to parse.
Returns:
The hextet as an integer.
Raises:
ValueError: if the input isn't strictly a hex number from [0..FFFF]. |
13,368 | def code_almost_equal(a, b):
split_a = split_and_strip_non_empty_lines(a)
split_b = split_and_strip_non_empty_lines(b)
if len(split_a) != len(split_b):
return False
for (index, _) in enumerate(split_a):
if .join(split_a[index].split()) != .join(split_b[index].split()):
... | Return True if code is similar.
Ignore whitespace when comparing specific line. |
13,369 | def add_fields(self, fields = None, **kwargs):
if fields != None:
for field in fields:
self.fields.append(field) | Add the fields into the list of fields. |
13,370 | def get_keypair_name():
username = get_username()
assert not in username, "username must not contain -, change $USER"
validate_aws_name(username)
assert len(username) < 30
return get_prefix() + + username | Returns current keypair name. |
13,371 | def encode_network(root):
def fix_values(obj):
if isinstance(obj, Container):
obj.update((k, get_ref(v)) for (k, v) in obj.items()
if k != )
fixed_obj = obj
elif isinstance(obj, Dictionary):
fixed_obj = obj.__class__(di... | Yield ref-containing obj table entries from object network |
13,372 | def Append(self, **kw):
kw = copy_non_reserved_keywords(kw)
for key, val in kw.items():
update_dict = orig.update
except AttributeError:
try:
... | Append values to existing construction variables
in an Environment. |
13,373 | def patch(self, patched_value):
try:
if self.getter:
setattr(self.getter_class, self.attr_name, patched_value)
else:
setattr(self.orig_object, self.attr_name, patched_value)
except TypeError:
proxy_name = % (
... | Set a new value for the attribute of the object. |
13,374 | def validation_scatter(self, log_lam, b, masks, pre_v, gp, flux,
time, med):
self.lam[b] = 10 ** log_lam
scatter = [None for i in range(len(masks))]
for i in range(len(masks)):
model = self.cv_compute(b, *pre_v[i])
t... | Computes the scatter in the validation set. |
13,375 | def remove_connection(self, id_interface, back_or_front):
msg_err = u
if not is_valid_0_1(back_or_front):
raise InvalidParameterError(
msg_err %
(, back_or_front))
if not is_valid_int_param(id_interface):
raise InvalidParameterE... | Remove a connection between two interfaces
:param id_interface: One side of relation
:param back_or_front: This side of relation is back(0) or front(1)
:return: None
:raise InterfaceInvalidBackFrontError: Front or Back of interfaces not match to remove connection
:raise Invali... |
13,376 | def txn_data2schema_key(self, txn: dict) -> SchemaKey:
rv = None
if self == Protocol.V_13:
rv = SchemaKey(txn[], txn[][], txn[][])
else:
txn_txn = txn.get(, None) or txn
rv = SchemaKey(
txn_txn[][],
txn_txn[][][],
... | Return schema key from ledger transaction data.
:param txn: get-schema transaction (by sequence number)
:return: schema key identified |
13,377 | def _assign_name(self, obj, name, shaders):
if self._is_global(obj):
assert name not in self._global_ns
self._global_ns[name] = obj
else:
for shader in shaders:
ns = self._shader_ns[shader]
assert name not in ns
... | Assign *name* to *obj* in *shaders*. |
13,378 | def authorize(self, ip_protocol=None, from_port=None, to_port=None,
cidr_ip=None, src_group=None):
if src_group:
cidr_ip = None
src_group_name = src_group.name
src_group_owner_id = src_group.owner_id
else:
src_group_name = None
... | Add a new rule to this security group.
You need to pass in either src_group_name
OR ip_protocol, from_port, to_port,
and cidr_ip. In other words, either you are authorizing another
group or you are authorizing some ip-based rule.
:type ip_protocol: string
:param... |
13,379 | def push(self, *args, **kwargs):
ref = {
: ,
: ,
: [
{
: ,
: False,
: ,
},
{
: False,
: ,
},
... | GitHub push Event
When a GitHub push event is posted it will be broadcast on this
exchange with the designated `organization` and `repository`
in the routing-key along with event specific metadata in the payload.
This exchange outputs: ``v1/github-push-message.json#``This exchange take... |
13,380 | def textContent(self, text: str) -> None:
self._set_text_content(text)
if self.connected:
self._set_text_content_web(text) | Set textContent both on this node and related browser node. |
13,381 | def get_instances(feature_name):
feats = []
for ft in AncillaryFeature.features:
if ft.feature_name == feature_name:
feats.append(ft)
return feats | Return all all instances that compute `feature_name` |
13,382 | def call_fset(self, obj, value) -> None:
vars(obj)[self.name] = self.fset(obj, value) | Store the given custom value and call the setter function. |
13,383 | def handle_stream(self, stream, address):
log.trace(, address)
self.clients.append((stream, address))
unpacker = msgpack.Unpacker()
try:
while True:
wire_bytes = yield stream.read_bytes(4096, partial=True)
unpacker.feed(wire_bytes)
... | Handle incoming streams and add messages to the incoming queue |
13,384 | def open(self):
if self._status == "opened":
return
self.reset()
self._loading = True
self._status = "opened"
path = self._topology_file()
if not os.path.exists(path):
self._loading = False
return
try:
shu... | Load topology elements |
13,385 | def get_previous_character(self):
cursor = self.textCursor()
cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor)
return cursor.selectedText() | Returns the character before the cursor.
:return: Previous cursor character.
:rtype: QString |
13,386 | def build(self):
for detail_view in self.detail_views:
view = self._get_view(detail_view)
view().build_object(self)
self._build_extra()
self._build_related() | Iterates through the views pointed to by self.detail_views, runs
build_object with `self`, and calls _build_extra()
and _build_related(). |
13,387 | def _nonzero_counter_hook(module, inputs, output):
if not hasattr(module, "__counter_nonzero__"):
raise ValueError("register_counter_nonzero was not called for this network")
if module.training:
return
size = module.__counter_nonzero__.get("input", 0)
size += sum([torch.nonzero(i).size(0) for i in ... | Module hook used to count the number of nonzero floating point values from
all the tensors used by the given network during inference. This hook will be
called every time before :func:`forward` is invoked.
See :func:`torch.nn.Module.register_forward_hook` |
13,388 | def histogram_info(self) -> dict:
return {
: self.support_atoms,
: self.atom_delta,
: self.vmin,
: self.vmax,
: self.atoms
} | Return extra information about histogram |
13,389 | def list_member_topics(self, member_id):
title = % self.__class__.__name__
input_fields = {
: member_id
}
for key, value in input_fields.items():
if value:
object_title = % (title, key, str(value))
... | a method to retrieve a list of topics member follows
:param member_id: integer with meetup member id
:return: dictionary with list of topic details inside [json] key
topic_details = self.objects.topic.schema |
13,390 | def animate(self, duration = None, easing = None, on_complete = None,
on_update = None, round = False, **kwargs):
scene = self.get_scene()
if scene:
return scene.animate(self, duration, easing, on_complete,
on_update, round, **kwargs)... | Request parent Scene to Interpolate attributes using the internal tweener.
Specify sprite's attributes that need changing.
`duration` defaults to 0.4 seconds and `easing` to cubic in-out
(for others see pytweener.Easing class).
Example::
# tween some_sprite to c... |
13,391 | def diff_files(left, right, diff_options=None, formatter=None):
return _diff(etree.parse, left, right,
diff_options=diff_options, formatter=formatter) | Takes two filenames or streams, and diffs the XML in those files |
13,392 | def unicode_decode(data, encoding_list):
assert encoding_list,
xs = distinct(encoding_list if isinstance(encoding_list, list) else [encoding_list])
first_exp = None
for i, encoding in enumerate(xs):
try:
return data.decode(encoding)
except UnicodeDecodeError as e:
... | Decode string data with one or more encodings, trying sequentially
:param data: bytes: encoded string data
:param encoding_list: list[string] or string: encoding names
:return: string: decoded string |
13,393 | def build_keyjar(key_conf, kid_template="", keyjar=None, owner=):
if keyjar is None:
keyjar = KeyJar()
tot_kb = build_key_bundle(key_conf, kid_template)
keyjar.add_kb(owner, tot_kb)
return keyjar | Builds a :py:class:`oidcmsg.key_jar.KeyJar` instance or adds keys to
an existing KeyJar based on a key specification.
An example of such a specification::
keys = [
{"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]},
{"type": "EC", "crv": "P-256", "use": ["sig"... |
13,394 | def from_plugin_classname(plugin_classname, exclude_lines_regex=None, **kwargs):
klass = globals()[plugin_classname]
if not issubclass(klass, BasePlugin):
raise TypeError
try:
instance = klass(exclude_lines_regex=exclude_lines_regex, **kwargs)
except TypeError:
log.wa... | Initializes a plugin class, given a classname and kwargs.
:type plugin_classname: str
:param plugin_classname: subclass of BasePlugin.
:type exclude_lines_regex: str|None
:param exclude_lines_regex: optional regex for ignored lines. |
13,395 | def find_objects(config=None, config_path=None, regex=None, saltenv=):
ciscoconfparse.find_objectssalt://path/to/config.txtGigabit
ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv)
lines = ccp.find_objects(regex)
return lines | Return all the line objects that match the expression in the ``regex``
argument.
.. warning::
This function is mostly valuable when invoked from other Salt
components (i.e., execution modules, states, templates etc.). For CLI
usage, please consider using
:py:func:`ciscoconfparse... |
13,396 | def register(self, cmd: Type[Command]) -> None:
self.commands[cmd.command] = cmd | Register a new IMAP command.
Args:
cmd: The new command type. |
13,397 | def get(url, params={}):
request_url = url
if len(params):
request_url = "{}?{}".format(url, urlencode(params))
try:
req = Request(request_url, headers={: })
response = json.loads(urlopen(req).read().decode("utf-8"))
return response
... | Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary |
13,398 | def remove_all(self, item):
item = self.ref(item)
while list.__contains__(self, item):
list.remove(self, item) | Remove all occurrence of the parameter.
:param item: Value to delete from the WeakList. |
13,399 | def gtlike_spectrum_to_vectors(spectrum):
parameters = pyLike.ParameterVector()
spectrum.getParams(parameters)
npar = max(parameters.size(), 10)
o = {: np.zeros(npar, dtype=),
: np.empty(npar, dtype=float) * np.nan,
: np.empty(npar, dtype=float) * np.nan,
}
for i,... | Convert a pyLikelihood object to a python dictionary which can
be easily saved to a file. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.