nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fortharris/Pcode | 147962d160a834c219e12cb456abc130826468e4 | rope/base/fscommands.py | python | unicode_to_file_data | (contents, encoding=None) | [] | def unicode_to_file_data(contents, encoding=None):
if not isinstance(contents, str):
return contents
if encoding is None:
encoding = read_str_coding(contents)
if encoding is not None:
return contents.encode(encoding)
try:
return contents.encode()
except UnicodeEncodeError:
return contents.encode('utf-8') | [
"def",
"unicode_to_file_data",
"(",
"contents",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"contents",
",",
"str",
")",
":",
"return",
"contents",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"read_str_coding",
"(",
"c... | https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/base/fscommands.py#L190-L200 | ||||
libertysoft3/saidit | 271c7d03adb369f82921d811360b00812e42da24 | r2/r2/models/builder.py | python | CommentOrdererBase.get_comment_order | (self) | return comment_tuples | Return a list of CommentTuples in tree insertion order.
Also add a MissingChildrenTuple to the end of the list if there
are missing root level comments. | Return a list of CommentTuples in tree insertion order. | [
"Return",
"a",
"list",
"of",
"CommentTuples",
"in",
"tree",
"insertion",
"order",
"."
] | def get_comment_order(self):
"""Return a list of CommentTuples in tree insertion order.
Also add a MissingChildrenTuple to the end of the list if there
are missing root level comments.
"""
with g.stats.get_timer('comment_tree.get.1') as comment_tree_timer:
comment_tree = CommentTree.by_link(self.link, comment_tree_timer)
sort_name = self.sort.col
sorter = get_comment_scores(
self.link, sort_name, comment_tree.cids, comment_tree_timer)
comment_tree_timer.intermediate('get_scores')
if isinstance(self.sort, operators.shuffled):
# randomize the scores of top level comments
top_level_ids = comment_tree.tree.get(None, [])
top_level_scores = [
sorter[comment_id] for comment_id in top_level_ids]
shuffle(top_level_scores)
for i, comment_id in enumerate(top_level_ids):
sorter[comment_id] = top_level_scores[i]
self.timer.intermediate("load_storage")
comment_tree = self.modify_comment_tree(comment_tree)
self.timer.intermediate("modify_comment_tree")
initial_candidates, offset_depth = self.get_initial_candidates(comment_tree)
comment_tuples = self.get_initial_comment_list(comment_tree)
if comment_tuples:
# some comments have bypassed the sorting/inserting process, remove
# them from `initial_candidates` so they won't be inserted again
comment_tuple_ids = {
comment_tuple.comment_id for comment_tuple in comment_tuples}
initial_candidates = [
comment_id for comment_id in initial_candidates
if comment_id not in comment_tuple_ids
]
candidates = []
self.update_candidates(candidates, sorter, initial_candidates)
self.timer.intermediate("pick_candidates")
# choose which comments to show
while candidates and len(comment_tuples) < self.max_comments:
sort_val, comment_id = heapq.heappop(candidates)
if comment_id not in comment_tree.cids:
continue
comment_depth = comment_tree.depth[comment_id] - offset_depth
if comment_depth >= self.max_depth:
continue
child_ids = comment_tree.tree.get(comment_id, [])
comment_tuples.append(CommentTuple(
comment_id=comment_id,
depth=comment_depth,
parent_id=comment_tree.parents[comment_id],
num_children=comment_tree.num_children[comment_id],
child_ids=child_ids,
))
child_depth = comment_depth + 1
if child_depth < self.max_depth:
self.update_candidates(candidates, sorter, child_ids)
self.timer.intermediate("pick_comments")
# add all not-selected top level comments to the comment_tuples list
# so we can make MoreChildren for them later
top_level_not_visible = {
comment_id for sort_val, comment_id in candidates
if comment_tree.depth.get(comment_id, 0) - offset_depth == 0
}
if top_level_not_visible:
num_children_not_visible = sum(
1 + comment_tree.num_children[comment_id]
for comment_id in top_level_not_visible
)
comment_tuples.append(MissingChildrenTuple(
num_children=num_children_not_visible,
child_ids=top_level_not_visible,
))
self.timer.intermediate("handle_morechildren")
return comment_tuples | [
"def",
"get_comment_order",
"(",
"self",
")",
":",
"with",
"g",
".",
"stats",
".",
"get_timer",
"(",
"'comment_tree.get.1'",
")",
"as",
"comment_tree_timer",
":",
"comment_tree",
"=",
"CommentTree",
".",
"by_link",
"(",
"self",
".",
"link",
",",
"comment_tree_... | https://github.com/libertysoft3/saidit/blob/271c7d03adb369f82921d811360b00812e42da24/r2/r2/models/builder.py#L862-L952 | |
yangxudong/deeplearning | 1b925c2171902d9a352d3747495030e058220204 | wdl/beidian_cart_wdl_v2.py | python | build_estimator | (model_dir, model_type) | Build an estimator appropriate for the given model type. | Build an estimator appropriate for the given model type. | [
"Build",
"an",
"estimator",
"appropriate",
"for",
"the",
"given",
"model",
"type",
"."
] | def build_estimator(model_dir, model_type):
"""Build an estimator appropriate for the given model type."""
wide_columns, deep_columns = build_model_columns()
print(wide_columns)
print(deep_columns)
hidden_units = [256, 128, 64]
# Create a tf.estimator.RunConfig to ensure the model is run on CPU, which
# trains faster than GPU for this model.
#run_config = tf.estimator.RunConfig().replace(
# session_config=tf.ConfigProto(device_count={'GPU': 0}))
if model_type == 'wide':
return tf.estimator.LinearClassifier(
model_dir=model_dir,
feature_columns=wide_columns)
#config=run_config)
elif model_type == 'deep':
return tf.estimator.DNNClassifier(
model_dir=model_dir,
feature_columns=deep_columns,
hidden_units=hidden_units)
#config=run_config)
else:
return tf.estimator.DNNLinearCombinedClassifier(
model_dir=model_dir,
linear_feature_columns=wide_columns,
dnn_feature_columns=deep_columns,
dnn_hidden_units=hidden_units) | [
"def",
"build_estimator",
"(",
"model_dir",
",",
"model_type",
")",
":",
"wide_columns",
",",
"deep_columns",
"=",
"build_model_columns",
"(",
")",
"print",
"(",
"wide_columns",
")",
"print",
"(",
"deep_columns",
")",
"hidden_units",
"=",
"[",
"256",
",",
"128... | https://github.com/yangxudong/deeplearning/blob/1b925c2171902d9a352d3747495030e058220204/wdl/beidian_cart_wdl_v2.py#L235-L263 | ||
ShichenLiu/CondenseNet | 833a91d5f859df25579f70a2439dfd62f7fefb29 | main.py | python | validate | (val_loader, model, criterion) | return 100. - top1.avg, 100. - top5.avg | [] | def validate(val_loader, model, criterion):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
### Switch to evaluate mode
model.eval()
end = time.time()
for i, (input, target) in enumerate(val_loader):
target = target.cuda(non_blocking=True)
input_var = torch.autograd.Variable(input, volatile=True)
target_var = torch.autograd.Variable(target, volatile=True)
### Compute output
output = model(input_var)
loss = criterion(output, target_var)
### Measure accuracy and record loss
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
losses.update(loss.data.item(), input.size(0))
top1.update(prec1.item(), input.size(0))
top5.update(prec5.item(), input.size(0))
### Measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Test: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'
'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(
i, len(val_loader), batch_time=batch_time, loss=losses,
top1=top1, top5=top5))
print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return 100. - top1.avg, 100. - top5.avg | [
"def",
"validate",
"(",
"val_loader",
",",
"model",
",",
"criterion",
")",
":",
"batch_time",
"=",
"AverageMeter",
"(",
")",
"losses",
"=",
"AverageMeter",
"(",
")",
"top1",
"=",
"AverageMeter",
"(",
")",
"top5",
"=",
"AverageMeter",
"(",
")",
"### Switch ... | https://github.com/ShichenLiu/CondenseNet/blob/833a91d5f859df25579f70a2439dfd62f7fefb29/main.py#L341-L382 | |||
Tautulli/Tautulli | 2410eb33805aaac4bd1c5dad0f71e4f15afaf742 | lib/twitter/api.py | python | Api._RequestUrl | (self, url, verb, data=None, json=None, enforce_auth=True) | return resp | Request a url.
Args:
url:
The web location we want to retrieve.
verb:
Either POST or GET.
data:
A dict of (str, unicode) key/value pairs.
Returns:
A JSON object. | Request a url. | [
"Request",
"a",
"url",
"."
] | def _RequestUrl(self, url, verb, data=None, json=None, enforce_auth=True):
"""Request a url.
Args:
url:
The web location we want to retrieve.
verb:
Either POST or GET.
data:
A dict of (str, unicode) key/value pairs.
Returns:
A JSON object.
"""
if enforce_auth:
if not self.__auth:
raise TwitterError("The twitter.Api instance must be authenticated.")
if url and self.sleep_on_rate_limit:
limit = self.CheckRateLimit(url)
if limit.remaining == 0:
try:
stime = max(int(limit.reset - time.time()) + 10, 0)
logger.debug('Rate limited requesting [%s], sleeping for [%s]', url, stime)
time.sleep(stime)
except ValueError:
pass
if not data:
data = {}
if verb == 'POST':
if data:
if 'media_ids' in data:
url = self._BuildUrl(url, extra_params={'media_ids': data['media_ids']})
resp = self._session.post(url, data=data, auth=self.__auth, timeout=self._timeout, proxies=self.proxies)
elif 'media' in data:
resp = self._session.post(url, files=data, auth=self.__auth, timeout=self._timeout, proxies=self.proxies)
else:
resp = self._session.post(url, data=data, auth=self.__auth, timeout=self._timeout, proxies=self.proxies)
elif json:
resp = self._session.post(url, json=json, auth=self.__auth, timeout=self._timeout, proxies=self.proxies)
else:
resp = 0 # POST request, but without data or json
elif verb == 'GET':
data['tweet_mode'] = self.tweet_mode
url = self._BuildUrl(url, extra_params=data)
resp = self._session.get(url, auth=self.__auth, timeout=self._timeout, proxies=self.proxies)
else:
resp = 0 # if not a POST or GET request
if url and self.rate_limit:
limit = resp.headers.get('x-rate-limit-limit', 0)
remaining = resp.headers.get('x-rate-limit-remaining', 0)
reset = resp.headers.get('x-rate-limit-reset', 0)
self.rate_limit.set_limit(url, limit, remaining, reset)
return resp | [
"def",
"_RequestUrl",
"(",
"self",
",",
"url",
",",
"verb",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"enforce_auth",
"=",
"True",
")",
":",
"if",
"enforce_auth",
":",
"if",
"not",
"self",
".",
"__auth",
":",
"raise",
"TwitterError",
"... | https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/twitter/api.py#L4943-L5004 | |
realpython/book2-exercises | cde325eac8e6d8cff2316601c2e5b36bb46af7d0 | py2manager/gluon/contrib/aes.py | python | AES.sub_bytes | (self, block, sbox) | SubBytes step, apply S-box to all bytes
Depending on whether encrypting or decrypting, a different sbox array
is passed in. | SubBytes step, apply S-box to all bytes | [
"SubBytes",
"step",
"apply",
"S",
"-",
"box",
"to",
"all",
"bytes"
] | def sub_bytes(self, block, sbox):
"""SubBytes step, apply S-box to all bytes
Depending on whether encrypting or decrypting, a different sbox array
is passed in.
"""
for i in xrange(16):
block[i] = sbox[block[i]] | [
"def",
"sub_bytes",
"(",
"self",
",",
"block",
",",
"sbox",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"16",
")",
":",
"block",
"[",
"i",
"]",
"=",
"sbox",
"[",
"block",
"[",
"i",
"]",
"]"
] | https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/py2manager/gluon/contrib/aes.py#L174-L182 | ||
plastex/plastex | af1628719b50cf25fbe80f16a3e100d566e9bc32 | plasTeX/Packages/xcolor.py | python | Color.complement | (self) | The complement of this color, computed in this color model.
(c.f. Section 6.3, pg 47, xcolor v2.12, 2016/05/11) | The complement of this color, computed in this color model. | [
"The",
"complement",
"of",
"this",
"color",
"computed",
"in",
"this",
"color",
"model",
"."
] | def complement(self) -> 'Color':
"""The complement of this color, computed in this color model.
(c.f. Section 6.3, pg 47, xcolor v2.12, 2016/05/11)
"""
raise NotImplementedError() | [
"def",
"complement",
"(",
"self",
")",
"->",
"'Color'",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/plastex/plastex/blob/af1628719b50cf25fbe80f16a3e100d566e9bc32/plasTeX/Packages/xcolor.py#L789-L794 | ||
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-35/fabmetheus_utilities/settings.py | python | IntSpinNotOnMenu.getFromValueOnlyAddToRepository | ( self, name, repository, value ) | return self.getFromValueOnly( name, repository, value ) | Initialize. | Initialize. | [
"Initialize",
"."
] | def getFromValueOnlyAddToRepository( self, name, repository, value ):
"Initialize."
repository.displayEntities.append(self)
repository.preferences.append(self)
return self.getFromValueOnly( name, repository, value ) | [
"def",
"getFromValueOnlyAddToRepository",
"(",
"self",
",",
"name",
",",
"repository",
",",
"value",
")",
":",
"repository",
".",
"displayEntities",
".",
"append",
"(",
"self",
")",
"repository",
".",
"preferences",
".",
"append",
"(",
"self",
")",
"return",
... | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/settings.py#L1247-L1251 | |
skylander86/lambda-text-extractor | 6da52d077a2fc571e38bfe29c33ae68f6443cd5a | lib-linux_x64/urllib3/util/selectors.py | python | BaseSelector.select | (self, timeout=None) | Perform the actual selection until some monitored file objects
are ready or the timeout expires. | Perform the actual selection until some monitored file objects
are ready or the timeout expires. | [
"Perform",
"the",
"actual",
"selection",
"until",
"some",
"monitored",
"file",
"objects",
"are",
"ready",
"or",
"the",
"timeout",
"expires",
"."
] | def select(self, timeout=None):
""" Perform the actual selection until some monitored file objects
are ready or the timeout expires. """
raise NotImplementedError() | [
"def",
"select",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/urllib3/util/selectors.py#L245-L248 | ||
Qiskit/qiskit-terra | b66030e3b9192efdd3eb95cf25c6545fe0a13da4 | qiskit/opflow/state_fns/state_fn.py | python | StateFn.is_measurement | (self) | return self._is_measurement | Whether the StateFn object is a measurement Operator. | Whether the StateFn object is a measurement Operator. | [
"Whether",
"the",
"StateFn",
"object",
"is",
"a",
"measurement",
"Operator",
"."
] | def is_measurement(self) -> bool:
"""Whether the StateFn object is a measurement Operator."""
return self._is_measurement | [
"def",
"is_measurement",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"_is_measurement"
] | https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/opflow/state_fns/state_fn.py#L153-L155 | |
Jiramew/spoon | a301f8e9fe6956b44b02861a3931143b987693b0 | spoon_server/main/manager.py | python | Manager.__init__ | (self, database=None, url_prefix=None, fetcher=None, checker=None) | [] | def __init__(self, database=None, url_prefix=None, fetcher=None, checker=None):
if not database:
self.database = RedisWrapper("127.0.0.1", 6379, 0)
else:
self.database = RedisWrapper(database.host, database.port, database.db, database.password)
self._origin_prefix = 'origin_proxy'
self._useful_prefix = 'useful_proxy'
self._hundred_prefix = 'hundred_proxy'
self._current_prefix = 'current_proxy'
if not url_prefix:
self._url_prefix = "default"
else:
self._url_prefix = url_prefix
if not fetcher: # validater
self._fetcher = Fetcher()
else: # refresher
self._fetcher = fetcher
self._fetcher.backup_provider()
log.info("REFRESH FETCHER BACKUP PROVIDER {0}".format(str(self._fetcher)))
if not checker:
self._checker = Checker()
else:
self._checker = checker
self.log = log | [
"def",
"__init__",
"(",
"self",
",",
"database",
"=",
"None",
",",
"url_prefix",
"=",
"None",
",",
"fetcher",
"=",
"None",
",",
"checker",
"=",
"None",
")",
":",
"if",
"not",
"database",
":",
"self",
".",
"database",
"=",
"RedisWrapper",
"(",
"\"127.0.... | https://github.com/Jiramew/spoon/blob/a301f8e9fe6956b44b02861a3931143b987693b0/spoon_server/main/manager.py#L11-L39 | ||||
bwohlberg/sporco | df67462abcf83af6ab1961bcb0d51b87a66483fa | docs/source/automodule.py | python | sort_module_names | (modlst) | return sorted(modlst, key=lambda x: x.count('.')) | Sort a list of module names in order of subpackage depth.
Parameters
----------
modlst : list
List of module names
Returns
-------
srtlst : list
Sorted list of module names | Sort a list of module names in order of subpackage depth. | [
"Sort",
"a",
"list",
"of",
"module",
"names",
"in",
"order",
"of",
"subpackage",
"depth",
"."
] | def sort_module_names(modlst):
"""
Sort a list of module names in order of subpackage depth.
Parameters
----------
modlst : list
List of module names
Returns
-------
srtlst : list
Sorted list of module names
"""
return sorted(modlst, key=lambda x: x.count('.')) | [
"def",
"sort_module_names",
"(",
"modlst",
")",
":",
"return",
"sorted",
"(",
"modlst",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"count",
"(",
"'.'",
")",
")"
] | https://github.com/bwohlberg/sporco/blob/df67462abcf83af6ab1961bcb0d51b87a66483fa/docs/source/automodule.py#L128-L143 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/states/statuspage.py | python | _default_ret | (name) | return {"name": name, "result": False, "comment": "", "changes": {}} | Default dictionary returned. | Default dictionary returned. | [
"Default",
"dictionary",
"returned",
"."
] | def _default_ret(name):
"""
Default dictionary returned.
"""
return {"name": name, "result": False, "comment": "", "changes": {}} | [
"def",
"_default_ret",
"(",
"name",
")",
":",
"return",
"{",
"\"name\"",
":",
"name",
",",
"\"result\"",
":",
"False",
",",
"\"comment\"",
":",
"\"\"",
",",
"\"changes\"",
":",
"{",
"}",
"}"
] | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/statuspage.py#L51-L55 | |
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/sklearn/linear_model/randomized_l1.py | python | BaseRandomizedLinearModel.fit | (self, X, y) | return self | Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training data.
y : array-like, shape = [n_samples]
Target values.
Returns
-------
self : object
Returns an instance of self. | Fit the model using X, y as training data. | [
"Fit",
"the",
"model",
"using",
"X",
"y",
"as",
"training",
"data",
"."
] | def fit(self, X, y):
"""Fit the model using X, y as training data.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training data.
y : array-like, shape = [n_samples]
Target values.
Returns
-------
self : object
Returns an instance of self.
"""
X, y = check_X_y(X, y, ['csr', 'csc'], y_numeric=True,
ensure_min_samples=2, estimator=self)
X = as_float_array(X, copy=False)
n_samples, n_features = X.shape
X, y, X_offset, y_offset, X_scale = \
self._preprocess_data(X, y, self.fit_intercept, self.normalize)
estimator_func, params = self._make_estimator_and_params(X, y)
memory = self.memory
if isinstance(memory, six.string_types):
memory = Memory(cachedir=memory)
scores_ = memory.cache(
_resample_model, ignore=['verbose', 'n_jobs', 'pre_dispatch']
)(
estimator_func, X, y,
scaling=self.scaling, n_resampling=self.n_resampling,
n_jobs=self.n_jobs, verbose=self.verbose,
pre_dispatch=self.pre_dispatch, random_state=self.random_state,
sample_fraction=self.sample_fraction, **params)
if scores_.ndim == 1:
scores_ = scores_[:, np.newaxis]
self.all_scores_ = scores_
self.scores_ = np.max(self.all_scores_, axis=1)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"X",
",",
"y",
"=",
"check_X_y",
"(",
"X",
",",
"y",
",",
"[",
"'csr'",
",",
"'csc'",
"]",
",",
"y_numeric",
"=",
"True",
",",
"ensure_min_samples",
"=",
"2",
",",
"estimator",
"=",
"self... | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/linear_model/randomized_l1.py#L76-L118 | |
windelbouwman/ppci | 915c069e0667042c085ec42c78e9e3c9a5295324 | ppci/lang/c/parser.py | python | CParser.skip_initializer_lists | (self) | Skip superfluous initial values. | Skip superfluous initial values. | [
"Skip",
"superfluous",
"initial",
"values",
"."
] | def skip_initializer_lists(self):
""" Skip superfluous initial values. """
while self.peek != "}":
self.next_token() | [
"def",
"skip_initializer_lists",
"(",
"self",
")",
":",
"while",
"self",
".",
"peek",
"!=",
"\"}\"",
":",
"self",
".",
"next_token",
"(",
")"
] | https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/lang/c/parser.py#L659-L662 | ||
los-cocos/cocos | 3b47281f95d6ee52bb2a357a767f213e670bd601 | cocos/tiles.py | python | RectMap.__init__ | (self, id, tw, th, cells, origin=None, properties=None) | :Parameters:
`id` : xml id
node id
`tw` : int
number of colums in cells
`th` : int
number of rows in cells
`cells` : container that supports cells[i][j]
elements are stored in column-major order with y increasing up
`origin` : (int, int, int)
cell block offset x,y,z ; default is (0,0,0)
`properties` : dict
arbitrary properties
if saving to XML, keys must be unicode or 8-bit ASCII strings | :Parameters:
`id` : xml id
node id
`tw` : int
number of colums in cells
`th` : int
number of rows in cells
`cells` : container that supports cells[i][j]
elements are stored in column-major order with y increasing up
`origin` : (int, int, int)
cell block offset x,y,z ; default is (0,0,0)
`properties` : dict
arbitrary properties
if saving to XML, keys must be unicode or 8-bit ASCII strings | [
":",
"Parameters",
":",
"id",
":",
"xml",
"id",
"node",
"id",
"tw",
":",
"int",
"number",
"of",
"colums",
"in",
"cells",
"th",
":",
"int",
"number",
"of",
"rows",
"in",
"cells",
"cells",
":",
"container",
"that",
"supports",
"cells",
"[",
"i",
"]",
... | def __init__(self, id, tw, th, cells, origin=None, properties=None):
"""
:Parameters:
`id` : xml id
node id
`tw` : int
number of colums in cells
`th` : int
number of rows in cells
`cells` : container that supports cells[i][j]
elements are stored in column-major order with y increasing up
`origin` : (int, int, int)
cell block offset x,y,z ; default is (0,0,0)
`properties` : dict
arbitrary properties
if saving to XML, keys must be unicode or 8-bit ASCII strings
"""
self.properties = properties or {}
self.id = id
self.tw, self.th = tw, th
if origin is None:
origin = (0, 0, 0)
self.origin_x, self.origin_y, self.origin_z = origin
self.cells = cells
self.px_width = len(cells) * tw
self.px_height = len(cells[0]) * th | [
"def",
"__init__",
"(",
"self",
",",
"id",
",",
"tw",
",",
"th",
",",
"cells",
",",
"origin",
"=",
"None",
",",
"properties",
"=",
"None",
")",
":",
"self",
".",
"properties",
"=",
"properties",
"or",
"{",
"}",
"self",
".",
"id",
"=",
"id",
"self... | https://github.com/los-cocos/cocos/blob/3b47281f95d6ee52bb2a357a767f213e670bd601/cocos/tiles.py#L1045-L1070 | ||
JulianEberius/SublimePythonIDE | d70e40abc0c9f347af3204c7b910e0d6bfd6e459 | server/lib/python_all/jedi/parser/tree.py | python | _create_params | (parent, argslist_list) | `argslist_list` is a list that can contain an argslist as a first item, but
most not. It's basically the items between the parameter brackets (which is
at most one item).
This function modifies the parser structure. It generates `Param` objects
from the normal ast. Those param objects do not exist in a normal ast, but
make the evaluation of the ast tree so much easier.
You could also say that this function replaces the argslist node with a
list of Param objects. | `argslist_list` is a list that can contain an argslist as a first item, but
most not. It's basically the items between the parameter brackets (which is
at most one item).
This function modifies the parser structure. It generates `Param` objects
from the normal ast. Those param objects do not exist in a normal ast, but
make the evaluation of the ast tree so much easier.
You could also say that this function replaces the argslist node with a
list of Param objects. | [
"argslist_list",
"is",
"a",
"list",
"that",
"can",
"contain",
"an",
"argslist",
"as",
"a",
"first",
"item",
"but",
"most",
"not",
".",
"It",
"s",
"basically",
"the",
"items",
"between",
"the",
"parameter",
"brackets",
"(",
"which",
"is",
"at",
"most",
"o... | def _create_params(parent, argslist_list):
"""
`argslist_list` is a list that can contain an argslist as a first item, but
most not. It's basically the items between the parameter brackets (which is
at most one item).
This function modifies the parser structure. It generates `Param` objects
from the normal ast. Those param objects do not exist in a normal ast, but
make the evaluation of the ast tree so much easier.
You could also say that this function replaces the argslist node with a
list of Param objects.
"""
def check_python2_nested_param(node):
"""
Python 2 allows params to look like ``def x(a, (b, c))``, which is
basically a way of unpacking tuples in params. Python 3 has ditched
this behavior. Jedi currently just ignores those constructs.
"""
return node.type == 'tfpdef' and node.children[0] == '('
try:
first = argslist_list[0]
except IndexError:
return []
if first.type in ('name', 'tfpdef'):
if check_python2_nested_param(first):
return []
else:
return [Param([first], parent)]
else: # argslist is a `typedargslist` or a `varargslist`.
children = first.children
params = []
start = 0
# Start with offset 1, because the end is higher.
for end, child in enumerate(children + [None], 1):
if child is None or child == ',':
new_children = children[start:end]
if new_children: # Could as well be comma and then end.
if check_python2_nested_param(new_children[0]):
continue
params.append(Param(new_children, parent))
start = end
return params | [
"def",
"_create_params",
"(",
"parent",
",",
"argslist_list",
")",
":",
"def",
"check_python2_nested_param",
"(",
"node",
")",
":",
"\"\"\"\n Python 2 allows params to look like ``def x(a, (b, c))``, which is\n basically a way of unpacking tuples in params. Python 3 has dit... | https://github.com/JulianEberius/SublimePythonIDE/blob/d70e40abc0c9f347af3204c7b910e0d6bfd6e459/server/lib/python_all/jedi/parser/tree.py#L703-L745 | ||
pilotmoon/PopClip-Extensions | 29fc472befc09ee350092ac70283bd9fdb456cb6 | source/Trello/requests/packages/urllib3/filepost.py | python | iter_field_objects | (fields) | Iterate over fields.
Supports list of (k, v) tuples and dicts, and lists of
:class:`~urllib3.fields.RequestField`. | Iterate over fields. | [
"Iterate",
"over",
"fields",
"."
] | def iter_field_objects(fields):
"""
Iterate over fields.
Supports list of (k, v) tuples and dicts, and lists of
:class:`~urllib3.fields.RequestField`.
"""
if isinstance(fields, dict):
i = six.iteritems(fields)
else:
i = iter(fields)
for field in i:
if isinstance(field, RequestField):
yield field
else:
yield RequestField.from_tuples(*field) | [
"def",
"iter_field_objects",
"(",
"fields",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"dict",
")",
":",
"i",
"=",
"six",
".",
"iteritems",
"(",
"fields",
")",
"else",
":",
"i",
"=",
"iter",
"(",
"fields",
")",
"for",
"field",
"in",
"i",
":"... | https://github.com/pilotmoon/PopClip-Extensions/blob/29fc472befc09ee350092ac70283bd9fdb456cb6/source/Trello/requests/packages/urllib3/filepost.py#L20-L37 | ||
numenta/nupic | b9ebedaf54f49a33de22d8d44dff7c765cdb5548 | src/nupic/swarming/hypersearch/permutation_helpers.py | python | PermuteChoices.__repr__ | (self) | return "PermuteChoices(choices=%s) [position=%s]" % (self.choices,
self.choices[self._positionIdx]) | See comments in base class. | See comments in base class. | [
"See",
"comments",
"in",
"base",
"class",
"."
] | def __repr__(self):
"""See comments in base class."""
return "PermuteChoices(choices=%s) [position=%s]" % (self.choices,
self.choices[self._positionIdx]) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"\"PermuteChoices(choices=%s) [position=%s]\"",
"%",
"(",
"self",
".",
"choices",
",",
"self",
".",
"choices",
"[",
"self",
".",
"_positionIdx",
"]",
")"
] | https://github.com/numenta/nupic/blob/b9ebedaf54f49a33de22d8d44dff7c765cdb5548/src/nupic/swarming/hypersearch/permutation_helpers.py#L333-L336 | |
Blizzard/heroprotocol | 3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c | heroprotocol/versions/protocol53965.py | python | decode_replay_initdata | (contents) | return decoder.instance(replay_initdata_typeid) | Decodes and return the replay init data from the contents byte string. | Decodes and return the replay init data from the contents byte string. | [
"Decodes",
"and",
"return",
"the",
"replay",
"init",
"data",
"from",
"the",
"contents",
"byte",
"string",
"."
] | def decode_replay_initdata(contents):
"""Decodes and return the replay init data from the contents byte string."""
decoder = BitPackedDecoder(contents, typeinfos)
return decoder.instance(replay_initdata_typeid) | [
"def",
"decode_replay_initdata",
"(",
"contents",
")",
":",
"decoder",
"=",
"BitPackedDecoder",
"(",
"contents",
",",
"typeinfos",
")",
"return",
"decoder",
".",
"instance",
"(",
"replay_initdata_typeid",
")"
] | https://github.com/Blizzard/heroprotocol/blob/3d36eaf44fc4c8ff3331c2ae2f1dc08a94535f1c/heroprotocol/versions/protocol53965.py#L443-L446 | |
renpy/pygame_sdl2 | c8c732109c38da2453b85270882115a24b71b238 | src/pygame_sdl2/sprite.py | python | collide_rect_ratio.__init__ | (self, ratio) | create a new collide_rect_ratio callable
Ratio is expected to be a floating point value used to scale
the underlying sprite rect before checking for collisions. | create a new collide_rect_ratio callable | [
"create",
"a",
"new",
"collide_rect_ratio",
"callable"
] | def __init__(self, ratio):
"""create a new collide_rect_ratio callable
Ratio is expected to be a floating point value used to scale
the underlying sprite rect before checking for collisions.
"""
self.ratio = ratio | [
"def",
"__init__",
"(",
"self",
",",
"ratio",
")",
":",
"self",
".",
"ratio",
"=",
"ratio"
] | https://github.com/renpy/pygame_sdl2/blob/c8c732109c38da2453b85270882115a24b71b238/src/pygame_sdl2/sprite.py#L1314-L1321 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/dis.py | python | _get_code_object | (x) | Helper to handle methods, compiled or raw code objects, and strings. | Helper to handle methods, compiled or raw code objects, and strings. | [
"Helper",
"to",
"handle",
"methods",
"compiled",
"or",
"raw",
"code",
"objects",
"and",
"strings",
"."
] | def _get_code_object(x):
"""Helper to handle methods, compiled or raw code objects, and strings."""
# Extract functions from methods.
if hasattr(x, '__func__'):
x = x.__func__
# Extract compiled code objects from...
if hasattr(x, '__code__'): # ...a function, or
x = x.__code__
elif hasattr(x, 'gi_code'): #...a generator object, or
x = x.gi_code
elif hasattr(x, 'ag_code'): #...an asynchronous generator object, or
x = x.ag_code
elif hasattr(x, 'cr_code'): #...a coroutine.
x = x.cr_code
# Handle source code.
if isinstance(x, str):
x = _try_compile(x, "<disassembly>")
# By now, if we don't have a code object, we can't disassemble x.
if hasattr(x, 'co_code'):
return x
raise TypeError("don't know how to disassemble %s objects" %
type(x).__name__) | [
"def",
"_get_code_object",
"(",
"x",
")",
":",
"# Extract functions from methods.",
"if",
"hasattr",
"(",
"x",
",",
"'__func__'",
")",
":",
"x",
"=",
"x",
".",
"__func__",
"# Extract compiled code objects from...",
"if",
"hasattr",
"(",
"x",
",",
"'__code__'",
"... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/dis.py#L119-L140 | ||
out0fmemory/GoAgent-Always-Available | c4254984fea633ce3d1893fe5901debd9f22c2a9 | server/lib/google/appengine/tools/appcfg.py | python | AppCfgApp.ResourceLimitsInfo | (self, output=None) | Outputs the current resource limits.
Args:
output: The file handle to write the output to (used for testing). | Outputs the current resource limits. | [
"Outputs",
"the",
"current",
"resource",
"limits",
"."
] | def ResourceLimitsInfo(self, output=None):
"""Outputs the current resource limits.
Args:
output: The file handle to write the output to (used for testing).
"""
rpcserver = self._GetRpcServer()
appyaml = self._ParseAppInfoFromYaml(self.basepath)
request_params = {'app_id': appyaml.application, 'version': appyaml.version}
logging_context = _ClientDeployLoggingContext(rpcserver, request_params,
usage_reporting=False)
resource_limits = GetResourceLimits(logging_context, self.error_fh)
for attr_name in sorted(resource_limits):
print >>output, '%s: %s' % (attr_name, resource_limits[attr_name]) | [
"def",
"ResourceLimitsInfo",
"(",
"self",
",",
"output",
"=",
"None",
")",
":",
"rpcserver",
"=",
"self",
".",
"_GetRpcServer",
"(",
")",
"appyaml",
"=",
"self",
".",
"_ParseAppInfoFromYaml",
"(",
"self",
".",
"basepath",
")",
"request_params",
"=",
"{",
"... | https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/tools/appcfg.py#L4978-L4993 | ||
kuri65536/python-for-android | 26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891 | tools/androidhelper.py | python | Android.wakeLockAcquireFull | (self) | return self._rpc("wakeLockAcquireFull") | wakeLockAcquireFull(self)
Acquires a full wake lock (CPU on, screen bright, keyboard bright). | wakeLockAcquireFull(self)
Acquires a full wake lock (CPU on, screen bright, keyboard bright). | [
"wakeLockAcquireFull",
"(",
"self",
")",
"Acquires",
"a",
"full",
"wake",
"lock",
"(",
"CPU",
"on",
"screen",
"bright",
"keyboard",
"bright",
")",
"."
] | def wakeLockAcquireFull(self):
'''
wakeLockAcquireFull(self)
Acquires a full wake lock (CPU on, screen bright, keyboard bright).
'''
return self._rpc("wakeLockAcquireFull") | [
"def",
"wakeLockAcquireFull",
"(",
"self",
")",
":",
"return",
"self",
".",
"_rpc",
"(",
"\"wakeLockAcquireFull\"",
")"
] | https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/tools/androidhelper.py#L2097-L2102 | |
tensorflow/lattice | 784eca50cbdfedf39f183cc7d298c9fe376b69c0 | tensorflow_lattice/python/premade_lib.py | python | _output_range | (layer_output_range, model_config, feature_config=None) | return output_min, output_max, output_init_min, output_init_max | Returns min/max/init_min/init_max for a given output range. | Returns min/max/init_min/init_max for a given output range. | [
"Returns",
"min",
"/",
"max",
"/",
"init_min",
"/",
"init_max",
"for",
"a",
"given",
"output",
"range",
"."
] | def _output_range(layer_output_range, model_config, feature_config=None):
"""Returns min/max/init_min/init_max for a given output range."""
if layer_output_range == LayerOutputRange.INPUT_TO_LATTICE:
if feature_config is None:
raise ValueError('Expecting feature config for lattice inputs.')
output_init_min = output_min = 0.0
output_init_max = output_max = feature_config.lattice_size - 1.0
elif layer_output_range == LayerOutputRange.MODEL_OUTPUT:
output_min = model_config.output_min
output_max = model_config.output_max
# Note: due to the multiplicative nature of KroneckerFactoredLattice layers,
# the initialization min/max do not correspond directly to the output
# min/max. Thus we follow the same scheme as the KroneckerFactoredLattice
# lattice layer to properly initialize the kernel and scale such that
# the output does in fact respect the requested bounds.
if ((isinstance(model_config, configs.CalibratedLatticeEnsembleConfig) or
isinstance(model_config, configs.CalibratedLatticeConfig)) and
model_config.parameterization == 'kronecker_factored'):
output_init_min, output_init_max = kfl_lib.default_init_params(
output_min, output_max)
else:
output_init_min = np.min(model_config.output_initialization)
output_init_max = np.max(model_config.output_initialization)
elif layer_output_range == LayerOutputRange.INPUT_TO_FINAL_CALIBRATION:
output_init_min = output_min = 0.0
output_init_max = output_max = 1.0
else:
raise ValueError('Unsupported layer output range.')
return output_min, output_max, output_init_min, output_init_max | [
"def",
"_output_range",
"(",
"layer_output_range",
",",
"model_config",
",",
"feature_config",
"=",
"None",
")",
":",
"if",
"layer_output_range",
"==",
"LayerOutputRange",
".",
"INPUT_TO_LATTICE",
":",
"if",
"feature_config",
"is",
"None",
":",
"raise",
"ValueError"... | https://github.com/tensorflow/lattice/blob/784eca50cbdfedf39f183cc7d298c9fe376b69c0/tensorflow_lattice/python/premade_lib.py#L137-L165 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/mako/runtime.py | python | Context.__getitem__ | (self, key) | [] | def __getitem__(self, key):
if key in self._data:
return self._data[key]
else:
return compat_builtins.__dict__[key] | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_data",
":",
"return",
"self",
".",
"_data",
"[",
"key",
"]",
"else",
":",
"return",
"compat_builtins",
".",
"__dict__",
"[",
"key",
"]"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/mako/runtime.py#L97-L101 | ||||
ankush-me/SynthText | e694abf03f298ce0e362cfbc5f67cf0ce6cbf301 | colorize3_poisson.py | python | FontColor.triangle_color | (self, col1, col2) | return np.squeeze(cv.cvtColor(col1[None,None,:],cv.COLOR_HSV2RGB)) | Returns a color which is "opposite" to both col1 and col2. | Returns a color which is "opposite" to both col1 and col2. | [
"Returns",
"a",
"color",
"which",
"is",
"opposite",
"to",
"both",
"col1",
"and",
"col2",
"."
] | def triangle_color(self, col1, col2):
"""
Returns a color which is "opposite" to both col1 and col2.
"""
col1, col2 = np.array(col1), np.array(col2)
col1 = np.squeeze(cv.cvtColor(col1[None,None,:], cv.COLOR_RGB2HSV))
col2 = np.squeeze(cv.cvtColor(col2[None,None,:], cv.COLOR_RGB2HSV))
h1, h2 = col1[0], col2[0]
if h2 < h1 : h1,h2 = h2,h1 #swap
dh = h2-h1
if dh < 127: dh = 255-dh
col1[0] = h1 + dh/2
return np.squeeze(cv.cvtColor(col1[None,None,:],cv.COLOR_HSV2RGB)) | [
"def",
"triangle_color",
"(",
"self",
",",
"col1",
",",
"col2",
")",
":",
"col1",
",",
"col2",
"=",
"np",
".",
"array",
"(",
"col1",
")",
",",
"np",
".",
"array",
"(",
"col2",
")",
"col1",
"=",
"np",
".",
"squeeze",
"(",
"cv",
".",
"cvtColor",
... | https://github.com/ankush-me/SynthText/blob/e694abf03f298ce0e362cfbc5f67cf0ce6cbf301/colorize3_poisson.py#L113-L125 | |
google/trax | d6cae2067dedd0490b78d831033607357e975015 | trax/tf_numpy/extensions/extensions.py | python | _seed2key | (a) | return tf_np.asarray(int32s_to_int64(a)) | Converts an RNG seed to an RNG key.
Args:
a: an RNG seed, a tensor of shape [2] and dtype `tf.int32`.
Returns:
an RNG key, an ndarray of shape [] and dtype `np.int64`. | Converts an RNG seed to an RNG key. | [
"Converts",
"an",
"RNG",
"seed",
"to",
"an",
"RNG",
"key",
"."
] | def _seed2key(a):
"""Converts an RNG seed to an RNG key.
Args:
a: an RNG seed, a tensor of shape [2] and dtype `tf.int32`.
Returns:
an RNG key, an ndarray of shape [] and dtype `np.int64`.
"""
def int32s_to_int64(a):
"""Converts an int32 tensor of shape [2] to an int64 tensor of shape []."""
a = tf.bitwise.bitwise_or(
tf.cast(a[0], tf.uint64),
tf.bitwise.left_shift(
tf.cast(a[1], tf.uint64), tf.constant(32, tf.uint64)))
a = tf.cast(a, tf.int64)
return a
return tf_np.asarray(int32s_to_int64(a)) | [
"def",
"_seed2key",
"(",
"a",
")",
":",
"def",
"int32s_to_int64",
"(",
"a",
")",
":",
"\"\"\"Converts an int32 tensor of shape [2] to an int64 tensor of shape [].\"\"\"",
"a",
"=",
"tf",
".",
"bitwise",
".",
"bitwise_or",
"(",
"tf",
".",
"cast",
"(",
"a",
"[",
"... | https://github.com/google/trax/blob/d6cae2067dedd0490b78d831033607357e975015/trax/tf_numpy/extensions/extensions.py#L1300-L1319 | |
gkrizek/bash-lambda-layer | 703b0ade8174022d44779d823172ab7ac33a5505 | bin/rsa/cli.py | python | CryptoOperation.read_key | (self, filename, keyform) | return self.key_class.load_pkcs1(keydata, keyform) | Reads a public or private key. | Reads a public or private key. | [
"Reads",
"a",
"public",
"or",
"private",
"key",
"."
] | def read_key(self, filename, keyform):
"""Reads a public or private key."""
print('Reading %s key from %s' % (self.keyname, filename), file=sys.stderr)
with open(filename, 'rb') as keyfile:
keydata = keyfile.read()
return self.key_class.load_pkcs1(keydata, keyform) | [
"def",
"read_key",
"(",
"self",
",",
"filename",
",",
"keyform",
")",
":",
"print",
"(",
"'Reading %s key from %s'",
"%",
"(",
"self",
".",
"keyname",
",",
"filename",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"with",
"open",
"(",
"filename",
"... | https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/rsa/cli.py#L164-L171 | |
cisco/mindmeld | 809c36112e9ea8019fe29d54d136ca14eb4fd8db | mindmeld/components/nlp.py | python | Processor._process_list | (self, items, func, *args, **kwargs) | return tuple([getattr(self, func)(itm, *args, **kwargs) for itm in items]) | Processes a list of items in parallel if possible using the executor.
Args:
items (list): Items to process.
func (str): Function name to call for processing.
Returns:
(tuple): Results of the processing. | Processes a list of items in parallel if possible using the executor.
Args:
items (list): Items to process.
func (str): Function name to call for processing. | [
"Processes",
"a",
"list",
"of",
"items",
"in",
"parallel",
"if",
"possible",
"using",
"the",
"executor",
".",
"Args",
":",
"items",
"(",
"list",
")",
":",
"Items",
"to",
"process",
".",
"func",
"(",
"str",
")",
":",
"Function",
"name",
"to",
"call",
... | def _process_list(self, items, func, *args, **kwargs):
"""Processes a list of items in parallel if possible using the executor.
Args:
items (list): Items to process.
func (str): Function name to call for processing.
Returns:
(tuple): Results of the processing.
"""
if executor:
try:
results = list(items)
future_to_idx_map = {}
for idx, item in enumerate(items):
future = executor.submit(
subproc_call_instance_function,
id(self),
func,
item,
*args,
**kwargs
)
future_to_idx_map[future] = idx
tasks = wait(future_to_idx_map, timeout=SUBPROCESS_WAIT_TIME)
if tasks.not_done:
raise Exception()
for future in tasks.done:
item = future.result()
item_idx = future_to_idx_map[future]
results[item_idx] = item
return tuple(results)
except (Exception, SystemExit): # pylint: disable=broad-except
# process pool is broken, restart it and process current request in series
restart_subprocesses()
# process the list in series
return tuple([getattr(self, func)(itm, *args, **kwargs) for itm in items]) | [
"def",
"_process_list",
"(",
"self",
",",
"items",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"executor",
":",
"try",
":",
"results",
"=",
"list",
"(",
"items",
")",
"future_to_idx_map",
"=",
"{",
"}",
"for",
"idx",
","... | https://github.com/cisco/mindmeld/blob/809c36112e9ea8019fe29d54d136ca14eb4fd8db/mindmeld/components/nlp.py#L315-L350 | |
intel/virtual-storage-manager | 00706ab9701acbd0d5e04b19cc80c6b66a2973b8 | source/vsm/vsm/api/v1/mdses.py | python | Controller.delete | (self, req, id) | delete a mds. | delete a mds. | [
"delete",
"a",
"mds",
"."
] | def delete(self, req, id):
"""delete a mds."""
LOG.info("mds_delete")
context = req.environ['vsm.context']
mds = self._get_mds(context, req, id)
self.conductor_api.mds_delete(context, mds['id']) | [
"def",
"delete",
"(",
"self",
",",
"req",
",",
"id",
")",
":",
"LOG",
".",
"info",
"(",
"\"mds_delete\"",
")",
"context",
"=",
"req",
".",
"environ",
"[",
"'vsm.context'",
"]",
"mds",
"=",
"self",
".",
"_get_mds",
"(",
"context",
",",
"req",
",",
"... | https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/api/v1/mdses.py#L137-L142 | ||
limodou/uliweb | 8bc827fa6bf7bf58aa8136b6c920fe2650c52422 | uliweb/core/template.py | python | to_basestring | (value) | Converts a string argument to a subclass of basestring.
In python2, byte and unicode strings are mostly interchangeable,
so functions that deal with a user-supplied argument in combination
with ascii string constants can use either and should return the type
the user supplied. In python3, the two types are not interchangeable,
so this method is needed to convert byte strings to unicode. | Converts a string argument to a subclass of basestring. | [
"Converts",
"a",
"string",
"argument",
"to",
"a",
"subclass",
"of",
"basestring",
"."
] | def to_basestring(value):
"""Converts a string argument to a subclass of basestring.
In python2, byte and unicode strings are mostly interchangeable,
so functions that deal with a user-supplied argument in combination
with ascii string constants can use either and should return the type
the user supplied. In python3, the two types are not interchangeable,
so this method is needed to convert byte strings to unicode.
"""
if value is None:
return 'None'
if isinstance(value, _BASESTRING_TYPES):
return value
elif isinstance(value, unicode_type):
return value.decode("utf-8")
else:
return str(value) | [
"def",
"to_basestring",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"'None'",
"if",
"isinstance",
"(",
"value",
",",
"_BASESTRING_TYPES",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"unicode_type",
")",
":"... | https://github.com/limodou/uliweb/blob/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/core/template.py#L293-L309 | ||
open-cogsci/OpenSesame | c4a3641b097a80a76937edbd8c365f036bcc9705 | openexp/canvas.py | python | init_display | (experiment) | desc:
Calls the back-end specific init_display function.
arguments:
experiment: The experiment object.
type: experiment | desc:
Calls the back-end specific init_display function. | [
"desc",
":",
"Calls",
"the",
"back",
"-",
"end",
"specific",
"init_display",
"function",
"."
] | def init_display(experiment):
"""
desc:
Calls the back-end specific init_display function.
arguments:
experiment: The experiment object.
type: experiment
"""
cls = backend.get_backend_class(experiment, u'canvas')
cls.init_display(experiment) | [
"def",
"init_display",
"(",
"experiment",
")",
":",
"cls",
"=",
"backend",
".",
"get_backend_class",
"(",
"experiment",
",",
"u'canvas'",
")",
"cls",
".",
"init_display",
"(",
"experiment",
")"
] | https://github.com/open-cogsci/OpenSesame/blob/c4a3641b097a80a76937edbd8c365f036bcc9705/openexp/canvas.py#L52-L64 | ||
TensorSpeech/TensorflowTTS | 34358d82a4c91fd70344872f8ea8a405ea84aedb | tensorflow_tts/models/mb_melgan.py | python | design_prototype_filter | (taps=62, cutoff_ratio=0.15, beta=9.0) | return h | Design prototype filter for PQMF.
This method is based on `A Kaiser window approach for the design of prototype
filters of cosine modulated filterbanks`_.
Args:
taps (int): The number of filter taps.
cutoff_ratio (float): Cut-off frequency ratio.
beta (float): Beta coefficient for kaiser window.
Returns:
ndarray: Impluse response of prototype filter (taps + 1,).
.. _`A Kaiser window approach for the design of prototype filters of cosine modulated filterbanks`:
https://ieeexplore.ieee.org/abstract/document/681427 | Design prototype filter for PQMF.
This method is based on `A Kaiser window approach for the design of prototype
filters of cosine modulated filterbanks`_.
Args:
taps (int): The number of filter taps.
cutoff_ratio (float): Cut-off frequency ratio.
beta (float): Beta coefficient for kaiser window.
Returns:
ndarray: Impluse response of prototype filter (taps + 1,).
.. _`A Kaiser window approach for the design of prototype filters of cosine modulated filterbanks`:
https://ieeexplore.ieee.org/abstract/document/681427 | [
"Design",
"prototype",
"filter",
"for",
"PQMF",
".",
"This",
"method",
"is",
"based",
"on",
"A",
"Kaiser",
"window",
"approach",
"for",
"the",
"design",
"of",
"prototype",
"filters",
"of",
"cosine",
"modulated",
"filterbanks",
"_",
".",
"Args",
":",
"taps",
... | def design_prototype_filter(taps=62, cutoff_ratio=0.15, beta=9.0):
"""Design prototype filter for PQMF.
This method is based on `A Kaiser window approach for the design of prototype
filters of cosine modulated filterbanks`_.
Args:
taps (int): The number of filter taps.
cutoff_ratio (float): Cut-off frequency ratio.
beta (float): Beta coefficient for kaiser window.
Returns:
ndarray: Impluse response of prototype filter (taps + 1,).
.. _`A Kaiser window approach for the design of prototype filters of cosine modulated filterbanks`:
https://ieeexplore.ieee.org/abstract/document/681427
"""
# check the arguments are valid
assert taps % 2 == 0, "The number of taps mush be even number."
assert 0.0 < cutoff_ratio < 1.0, "Cutoff ratio must be > 0.0 and < 1.0."
# make initial filter
omega_c = np.pi * cutoff_ratio
with np.errstate(invalid="ignore"):
h_i = np.sin(omega_c * (np.arange(taps + 1) - 0.5 * taps)) / (
np.pi * (np.arange(taps + 1) - 0.5 * taps)
)
# fix nan due to indeterminate form
h_i[taps // 2] = np.cos(0) * cutoff_ratio
# apply kaiser window
w = kaiser(taps + 1, beta)
h = h_i * w
return h | [
"def",
"design_prototype_filter",
"(",
"taps",
"=",
"62",
",",
"cutoff_ratio",
"=",
"0.15",
",",
"beta",
"=",
"9.0",
")",
":",
"# check the arguments are valid",
"assert",
"taps",
"%",
"2",
"==",
"0",
",",
"\"The number of taps mush be even number.\"",
"assert",
"... | https://github.com/TensorSpeech/TensorflowTTS/blob/34358d82a4c91fd70344872f8ea8a405ea84aedb/tensorflow_tts/models/mb_melgan.py#L28-L58 | |
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | bin/x86/Debug/scripting_engine/Lib/mailbox.py | python | MHMessage.set_sequences | (self, sequences) | Set the list of sequences that include the message. | Set the list of sequences that include the message. | [
"Set",
"the",
"list",
"of",
"sequences",
"that",
"include",
"the",
"message",
"."
] | def set_sequences(self, sequences):
"""Set the list of sequences that include the message."""
self._sequences = list(sequences) | [
"def",
"set_sequences",
"(",
"self",
",",
"sequences",
")",
":",
"self",
".",
"_sequences",
"=",
"list",
"(",
"sequences",
")"
] | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/mailbox.py#L1655-L1657 | ||
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/win32com/decimal_23.py | python | Decimal.__rsub__ | (self, other, context=None) | return other.__add__(tmp, context=context) | Return other + (-self) | Return other + (-self) | [
"Return",
"other",
"+",
"(",
"-",
"self",
")"
] | def __rsub__(self, other, context=None):
"""Return other + (-self)"""
other = _convert_other(other)
tmp = Decimal(self)
tmp._sign = 1 - tmp._sign
return other.__add__(tmp, context=context) | [
"def",
"__rsub__",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
")",
"tmp",
"=",
"Decimal",
"(",
"self",
")",
"tmp",
".",
"_sign",
"=",
"1",
"-",
"tmp",
".",
"_sign",
"return",
"oth... | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/win32com/decimal_23.py#L1027-L1033 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/combinat/root_system/cartan_type.py | python | CartanType_abstract._default_folded_cartan_type | (self) | return CartanTypeFolded(self, self, [[i] for i in self.index_set()]) | r"""
Return the default folded Cartan type.
In general, this just returns ``self`` in ``self`` with `\sigma` as
the identity map.
EXAMPLES::
sage: D = CartanMatrix([[2, -3], [-2, 2]]).dynkin_diagram()
sage: D._default_folded_cartan_type()
Dynkin diagram of rank 2 as a folding of Dynkin diagram of rank 2 | r"""
Return the default folded Cartan type. | [
"r",
"Return",
"the",
"default",
"folded",
"Cartan",
"type",
"."
] | def _default_folded_cartan_type(self):
r"""
Return the default folded Cartan type.
In general, this just returns ``self`` in ``self`` with `\sigma` as
the identity map.
EXAMPLES::
sage: D = CartanMatrix([[2, -3], [-2, 2]]).dynkin_diagram()
sage: D._default_folded_cartan_type()
Dynkin diagram of rank 2 as a folding of Dynkin diagram of rank 2
"""
from sage.combinat.root_system.type_folded import CartanTypeFolded
return CartanTypeFolded(self, self, [[i] for i in self.index_set()]) | [
"def",
"_default_folded_cartan_type",
"(",
"self",
")",
":",
"from",
"sage",
".",
"combinat",
".",
"root_system",
".",
"type_folded",
"import",
"CartanTypeFolded",
"return",
"CartanTypeFolded",
"(",
"self",
",",
"self",
",",
"[",
"[",
"i",
"]",
"for",
"i",
"... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/root_system/cartan_type.py#L1509-L1523 | |
GustavePate/lycheesync | 043bc70d6f56ac791075bdc033b70d66f26ec60f | lycheesync/lycheesyncer.py | python | LycheeSyncer.adjustRotation | (self, photo) | Rotates photos according to the exif orientaion tag
Returns nothing DOIT BEFORE THUMBNAILS !!! | Rotates photos according to the exif orientaion tag
Returns nothing DOIT BEFORE THUMBNAILS !!! | [
"Rotates",
"photos",
"according",
"to",
"the",
"exif",
"orientaion",
"tag",
"Returns",
"nothing",
"DOIT",
"BEFORE",
"THUMBNAILS",
"!!!"
] | def adjustRotation(self, photo):
"""
Rotates photos according to the exif orientaion tag
Returns nothing DOIT BEFORE THUMBNAILS !!!
"""
if photo.exif.orientation != 1:
img = Image.open(photo.destfullpath)
if "exif" in img.info:
exif_dict = piexif.load(img.info["exif"])
if piexif.ImageIFD.Orientation in exif_dict["0th"]:
orientation = exif_dict["0th"][piexif.ImageIFD.Orientation]
if orientation == 2:
img = img.transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 3:
img = img.rotate(180)
elif orientation == 4:
img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 5:
img = img.rotate(-90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 6:
img = img.rotate(-90, expand=True)
elif orientation == 7:
img = img.rotate(90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
elif orientation == 8:
img = img.rotate(90, expand=True)
else:
if orientation != 1:
logger.warn("Orientation not defined {} for photo {}".format(orientation, photo.title))
if orientation in [5, 6, 7, 8]:
# invert width and height
h = photo.height
w = photo.width
photo.height = w
photo.width = h
exif_dict["0th"][piexif.ImageIFD.Orientation] = 1
exif_bytes = piexif.dump(exif_dict)
img.save(photo.destfullpath, exif=exif_bytes, quality=99)
img.close() | [
"def",
"adjustRotation",
"(",
"self",
",",
"photo",
")",
":",
"if",
"photo",
".",
"exif",
".",
"orientation",
"!=",
"1",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"photo",
".",
"destfullpath",
")",
"if",
"\"exif\"",
"in",
"img",
".",
"info",
":",
... | https://github.com/GustavePate/lycheesync/blob/043bc70d6f56ac791075bdc033b70d66f26ec60f/lycheesync/lycheesyncer.py#L210-L252 | ||
Netflix/dispatch | f734b7cb91cba0e3a95b4d0adaa7198bfc94552b | src/dispatch/plugins/base/v1.py | python | IPlugin.get_title | (self) | return self.title | Returns the general title for this plugin.
>>> plugin.get_title() | Returns the general title for this plugin.
>>> plugin.get_title() | [
"Returns",
"the",
"general",
"title",
"for",
"this",
"plugin",
".",
">>>",
"plugin",
".",
"get_title",
"()"
] | def get_title(self) -> Optional[str]:
"""
Returns the general title for this plugin.
>>> plugin.get_title()
"""
return self.title | [
"def",
"get_title",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"return",
"self",
".",
"title"
] | https://github.com/Netflix/dispatch/blob/f734b7cb91cba0e3a95b4d0adaa7198bfc94552b/src/dispatch/plugins/base/v1.py#L82-L87 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/motech/openmrs/workflow_tasks.py | python | UpdatePersonPropertiesTask.__init__ | (self, requests, info, openmrs_config, person) | [] | def __init__(self, requests, info, openmrs_config, person):
self.requests = requests
self.info = info
self.openmrs_config = openmrs_config
self.person = person | [
"def",
"__init__",
"(",
"self",
",",
"requests",
",",
"info",
",",
"openmrs_config",
",",
"person",
")",
":",
"self",
".",
"requests",
"=",
"requests",
"self",
".",
"info",
"=",
"info",
"self",
".",
"openmrs_config",
"=",
"openmrs_config",
"self",
".",
"... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/motech/openmrs/workflow_tasks.py#L632-L636 | ||||
aws-samples/aws-kube-codesuite | ab4e5ce45416b83bffb947ab8d234df5437f4fca | src/kubernetes/client/models/v1beta1_daemon_set_spec.py | python | V1beta1DaemonSetSpec.template_generation | (self, template_generation) | Sets the template_generation of this V1beta1DaemonSetSpec.
DEPRECATED. A sequence number representing a specific generation of the template. Populated by the system. It can be set only during the creation.
:param template_generation: The template_generation of this V1beta1DaemonSetSpec.
:type: int | Sets the template_generation of this V1beta1DaemonSetSpec.
DEPRECATED. A sequence number representing a specific generation of the template. Populated by the system. It can be set only during the creation. | [
"Sets",
"the",
"template_generation",
"of",
"this",
"V1beta1DaemonSetSpec",
".",
"DEPRECATED",
".",
"A",
"sequence",
"number",
"representing",
"a",
"specific",
"generation",
"of",
"the",
"template",
".",
"Populated",
"by",
"the",
"system",
".",
"It",
"can",
"be"... | def template_generation(self, template_generation):
"""
Sets the template_generation of this V1beta1DaemonSetSpec.
DEPRECATED. A sequence number representing a specific generation of the template. Populated by the system. It can be set only during the creation.
:param template_generation: The template_generation of this V1beta1DaemonSetSpec.
:type: int
"""
self._template_generation = template_generation | [
"def",
"template_generation",
"(",
"self",
",",
"template_generation",
")",
":",
"self",
".",
"_template_generation",
"=",
"template_generation"
] | https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1beta1_daemon_set_spec.py#L164-L173 | ||
TuuuNya/WebPocket | e0ba36be22e9aee0fd95f6e0a9bd716619629bf4 | lib/cmd2/cmd2.py | python | Cmd.ppaged | (self, msg: str, end: str='\n', chop: bool=False) | Print output using a pager if it would go off screen and stdout isn't currently being redirected.
Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when
stdout or stdin are not a fully functional terminal.
:param msg: message to print to current stdout (anything convertible to a str with '{}'.format() is OK)
:param end: string appended after the end of the message if not already present, default a newline
:param chop: True -> causes lines longer than the screen width to be chopped (truncated) rather than wrapped
- truncated text is still accessible by scrolling with the right & left arrow keys
- chopping is ideal for displaying wide tabular data as is done in utilities like pgcli
False -> causes lines longer than the screen width to wrap to the next line
- wrapping is ideal when you want to keep users from having to use horizontal scrolling
WARNING: On Windows, the text always wraps regardless of what the chop argument is set to | Print output using a pager if it would go off screen and stdout isn't currently being redirected. | [
"Print",
"output",
"using",
"a",
"pager",
"if",
"it",
"would",
"go",
"off",
"screen",
"and",
"stdout",
"isn",
"t",
"currently",
"being",
"redirected",
"."
] | def ppaged(self, msg: str, end: str='\n', chop: bool=False) -> None:
"""Print output using a pager if it would go off screen and stdout isn't currently being redirected.
Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when
stdout or stdin are not a fully functional terminal.
:param msg: message to print to current stdout (anything convertible to a str with '{}'.format() is OK)
:param end: string appended after the end of the message if not already present, default a newline
:param chop: True -> causes lines longer than the screen width to be chopped (truncated) rather than wrapped
- truncated text is still accessible by scrolling with the right & left arrow keys
- chopping is ideal for displaying wide tabular data as is done in utilities like pgcli
False -> causes lines longer than the screen width to wrap to the next line
- wrapping is ideal when you want to keep users from having to use horizontal scrolling
WARNING: On Windows, the text always wraps regardless of what the chop argument is set to
"""
import subprocess
if msg is not None and msg != '':
try:
msg_str = '{}'.format(msg)
if not msg_str.endswith(end):
msg_str += end
# Attempt to detect if we are not running within a fully functional terminal.
# Don't try to use the pager when being run by a continuous integration system like Jenkins + pexpect.
functional_terminal = False
if self.stdin.isatty() and self.stdout.isatty():
if sys.platform.startswith('win') or os.environ.get('TERM') is not None:
functional_terminal = True
# Don't attempt to use a pager that can block if redirecting or running a script (either text or Python)
# Also only attempt to use a pager if actually running in a real fully functional terminal
if functional_terminal and not self.redirecting and not self._in_py and not self._script_dir:
if self.colors.lower() == constants.COLORS_NEVER.lower():
msg_str = utils.strip_ansi(msg_str)
pager = self.pager
if chop:
pager = self.pager_chop
self.pipe_proc = subprocess.Popen(pager, shell=True, stdin=subprocess.PIPE)
try:
self.pipe_proc.stdin.write(msg_str.encode('utf-8', 'replace'))
self.pipe_proc.stdin.close()
except (OSError, KeyboardInterrupt):
pass
# Less doesn't respect ^C, but catches it for its own UI purposes (aborting search etc. inside less)
while True:
try:
self.pipe_proc.wait()
except KeyboardInterrupt:
pass
else:
break
self.pipe_proc = None
else:
self.decolorized_write(self.stdout, msg_str)
except BrokenPipeError:
# This occurs if a command's output is being piped to another process and that process closes before the
# command is finished. If you would like your application to print a warning message, then set the
# broken_pipe_warning attribute to the message you want printed.`
if self.broken_pipe_warning:
sys.stderr.write(self.broken_pipe_warning) | [
"def",
"ppaged",
"(",
"self",
",",
"msg",
":",
"str",
",",
"end",
":",
"str",
"=",
"'\\n'",
",",
"chop",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"import",
"subprocess",
"if",
"msg",
"is",
"not",
"None",
"and",
"msg",
"!=",
"''",
":",
... | https://github.com/TuuuNya/WebPocket/blob/e0ba36be22e9aee0fd95f6e0a9bd716619629bf4/lib/cmd2/cmd2.py#L645-L708 | ||
mozillazg/pypy | 2ff5cd960c075c991389f842c6d59e71cf0cb7d0 | pypy/module/thread/os_lock.py | python | Lock.descr_lock_release | (self, space) | Release the lock, allowing another thread that is blocked waiting for
the lock to acquire the lock. The lock must be in the locked state,
but it needn't be locked by the same thread that unlocks it. | Release the lock, allowing another thread that is blocked waiting for
the lock to acquire the lock. The lock must be in the locked state,
but it needn't be locked by the same thread that unlocks it. | [
"Release",
"the",
"lock",
"allowing",
"another",
"thread",
"that",
"is",
"blocked",
"waiting",
"for",
"the",
"lock",
"to",
"acquire",
"the",
"lock",
".",
"The",
"lock",
"must",
"be",
"in",
"the",
"locked",
"state",
"but",
"it",
"needn",
"t",
"be",
"locke... | def descr_lock_release(self, space):
"""Release the lock, allowing another thread that is blocked waiting for
the lock to acquire the lock. The lock must be in the locked state,
but it needn't be locked by the same thread that unlocks it."""
try_release(space, self.lock) | [
"def",
"descr_lock_release",
"(",
"self",
",",
"space",
")",
":",
"try_release",
"(",
"space",
",",
"self",
".",
"lock",
")"
] | https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/thread/os_lock.py#L102-L106 | ||
SpriteLink/NIPAP | de09cd7c4c55521f26f00201d694ea9e388b21a9 | nipap/nipap/backend.py | python | Nipap.list_pool | (self, auth, spec=None) | return res | Return a list of pools.
* `auth` [BaseAuth]
AAA options.
* `spec` [pool_spec]
Specifies what pool(s) to list. Of omitted, all will be listed.
Returns a list of dicts.
This is the documentation of the internal backend function. It's
exposed over XML-RPC, please also see the XML-RPC documentation for
:py:func:`nipap.xmlrpc.NipapXMLRPC.list_pool` for full
understanding. | Return a list of pools. | [
"Return",
"a",
"list",
"of",
"pools",
"."
] | def list_pool(self, auth, spec=None):
""" Return a list of pools.
* `auth` [BaseAuth]
AAA options.
* `spec` [pool_spec]
Specifies what pool(s) to list. Of omitted, all will be listed.
Returns a list of dicts.
This is the documentation of the internal backend function. It's
exposed over XML-RPC, please also see the XML-RPC documentation for
:py:func:`nipap.xmlrpc.NipapXMLRPC.list_pool` for full
understanding.
"""
if spec is None:
spec = {}
self._logger.debug("list_pool called; spec: %s" % unicode(spec))
sql = """SELECT DISTINCT (po.id),
po.id,
po.name,
po.description,
po.default_type,
po.ipv4_default_prefix_length,
po.ipv6_default_prefix_length,
po.member_prefixes_v4,
po.member_prefixes_v6,
po.used_prefixes_v4,
po.used_prefixes_v6,
po.free_prefixes_v4,
po.free_prefixes_v6,
po.total_prefixes_v4,
po.total_prefixes_v6,
po.total_addresses_v4,
po.total_addresses_v6,
po.used_addresses_v4,
po.used_addresses_v6,
po.free_addresses_v4,
po.free_addresses_v6,
po.tags,
po.avps,
vrf.id AS vrf_id,
vrf.rt AS vrf_rt,
vrf.name AS vrf_name,
(SELECT array_agg(prefix::text) FROM (SELECT prefix FROM ip_net_plan WHERE pool_id=po.id ORDER BY prefix) AS a) AS prefixes
FROM ip_net_pool AS po
LEFT OUTER JOIN ip_net_plan AS inp ON (inp.pool_id = po.id)
LEFT OUTER JOIN ip_net_vrf AS vrf ON (vrf.id = inp.vrf_id)"""
params = list()
# expand spec
where, params = self._expand_pool_spec(spec)
if len(where) > 0:
sql += " WHERE " + where
sql += " ORDER BY name"
self._execute(sql, params)
res = list()
for row in self._curs_pg:
p = dict(row)
# Make sure that prefixes is a list, even if there are no prefixes
if p['prefixes'] is None:
p['prefixes'] = []
res.append(p)
return res | [
"def",
"list_pool",
"(",
"self",
",",
"auth",
",",
"spec",
"=",
"None",
")",
":",
"if",
"spec",
"is",
"None",
":",
"spec",
"=",
"{",
"}",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"list_pool called; spec: %s\"",
"%",
"unicode",
"(",
"spec",
")",
"... | https://github.com/SpriteLink/NIPAP/blob/de09cd7c4c55521f26f00201d694ea9e388b21a9/nipap/nipap/backend.py#L1898-L1969 | |
F-Secure/mittn | 7808552dc85a7998895038fdb2fa5c5bbed90c3e | mittn/httpfuzzer/steps.py | python | step_impl | (context, auth_id) | Store the authentication flow identifier. Tests in the feature file
can use different authentication flows, and this can be used to
select one of them in authenticate.py. | Store the authentication flow identifier. Tests in the feature file
can use different authentication flows, and this can be used to
select one of them in authenticate.py. | [
"Store",
"the",
"authentication",
"flow",
"identifier",
".",
"Tests",
"in",
"the",
"feature",
"file",
"can",
"use",
"different",
"authentication",
"flows",
"and",
"this",
"can",
"be",
"used",
"to",
"select",
"one",
"of",
"them",
"in",
"authenticate",
".",
"p... | def step_impl(context, auth_id):
"""Store the authentication flow identifier. Tests in the feature file
can use different authentication flows, and this can be used to
select one of them in authenticate.py.
"""
context.authentication_id = auth_id
assert True | [
"def",
"step_impl",
"(",
"context",
",",
"auth_id",
")",
":",
"context",
".",
"authentication_id",
"=",
"auth_id",
"assert",
"True"
] | https://github.com/F-Secure/mittn/blob/7808552dc85a7998895038fdb2fa5c5bbed90c3e/mittn/httpfuzzer/steps.py#L34-L41 | ||
nvaccess/nvda | 20d5a25dced4da34338197f0ef6546270ebca5d0 | source/oleacc.py | python | WindowFromAccessibleObject | (pacc) | return hwnd.value | Retreaves the handle of the window this IAccessible object belongs to.
@param pacc: the IAccessible object who's window you want to fetch.
@type pacc: POINTER(IAccessible)
@return: the window handle.
@rtype: int | Retreaves the handle of the window this IAccessible object belongs to. | [
"Retreaves",
"the",
"handle",
"of",
"the",
"window",
"this",
"IAccessible",
"object",
"belongs",
"to",
"."
] | def WindowFromAccessibleObject(pacc):
"""
Retreaves the handle of the window this IAccessible object belongs to.
@param pacc: the IAccessible object who's window you want to fetch.
@type pacc: POINTER(IAccessible)
@return: the window handle.
@rtype: int
"""
hwnd=c_int()
oledll.oleacc.WindowFromAccessibleObject(pacc,byref(hwnd))
return hwnd.value | [
"def",
"WindowFromAccessibleObject",
"(",
"pacc",
")",
":",
"hwnd",
"=",
"c_int",
"(",
")",
"oledll",
".",
"oleacc",
".",
"WindowFromAccessibleObject",
"(",
"pacc",
",",
"byref",
"(",
"hwnd",
")",
")",
"return",
"hwnd",
".",
"value"
] | https://github.com/nvaccess/nvda/blob/20d5a25dced4da34338197f0ef6546270ebca5d0/source/oleacc.py#L284-L294 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/domain/views/base.py | python | _domains_to_links | (domain_objects, view_name) | return sorted([{
'name': o.name,
'display_name': o.display_name(),
'url': reverse(view_name, args=[o.name]),
} for o in domain_objects if o], key=lambda link: link['display_name'].lower()) | [] | def _domains_to_links(domain_objects, view_name):
return sorted([{
'name': o.name,
'display_name': o.display_name(),
'url': reverse(view_name, args=[o.name]),
} for o in domain_objects if o], key=lambda link: link['display_name'].lower()) | [
"def",
"_domains_to_links",
"(",
"domain_objects",
",",
"view_name",
")",
":",
"return",
"sorted",
"(",
"[",
"{",
"'name'",
":",
"o",
".",
"name",
",",
"'display_name'",
":",
"o",
".",
"display_name",
"(",
")",
",",
"'url'",
":",
"reverse",
"(",
"view_na... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/domain/views/base.py#L114-L119 | |||
sfyc23/EverydayWechat | 6b81d03dde92cfef584428bc1e59d2858e94204e | everyday_wechat/control/bot/tuling123.py | python | get_tuling123 | (text, userId) | 接口地址:(https://www.kancloud.cn/turing/www-tuling123-com/718227)
获取图灵机器人对话
:param text: 发送的话
:param userId: 用户唯一标识(最好用微信好友uuid)
:return: 对白 | 接口地址:(https://www.kancloud.cn/turing/www-tuling123-com/718227)
获取图灵机器人对话
:param text: 发送的话
:param userId: 用户唯一标识(最好用微信好友uuid)
:return: 对白 | [
"接口地址:",
"(",
"https",
":",
"//",
"www",
".",
"kancloud",
".",
"cn",
"/",
"turing",
"/",
"www",
"-",
"tuling123",
"-",
"com",
"/",
"718227",
")",
"获取图灵机器人对话",
":",
"param",
"text",
":",
"发送的话",
":",
"param",
"userId",
":",
"用户唯一标识(最好用微信好友uuid)",
":",
... | def get_tuling123(text, userId):
"""
接口地址:(https://www.kancloud.cn/turing/www-tuling123-com/718227)
获取图灵机器人对话
:param text: 发送的话
:param userId: 用户唯一标识(最好用微信好友uuid)
:return: 对白
"""
try:
# config.init()
info = config.get('auto_reply_info')['turing_conf']
apiKey = info['apiKey']
if not apiKey:
print('图灵机器人 apikey 为空,请求出错')
return None
userId = md5_encode(userId if userId else '250')
content = {
'perception': {
'inputText': {
'text': text
}
},
'userInfo': {
'apiKey': apiKey,
'userId': userId
}
}
# print('发出消息:{}'.format(text))
resp = requests.post(URL, json=content)
if resp.status_code == 200 and is_json(resp):
# print(resp.text)
re_data = resp.json()
if re_data['intent']['code'] not in TULING_ERROR_CODE_LIST:
return_text = re_data['results'][0]['values']['text']
return return_text
error_text = re_data['results'][0]['values']['text']
print('图灵机器人错误信息:{}'.format(error_text))
return None
print('图灵机器人获取数据失败')
except Exception as exception:
print(str(exception))
print('图灵机器人获取数据失败') | [
"def",
"get_tuling123",
"(",
"text",
",",
"userId",
")",
":",
"try",
":",
"# config.init()",
"info",
"=",
"config",
".",
"get",
"(",
"'auto_reply_info'",
")",
"[",
"'turing_conf'",
"]",
"apiKey",
"=",
"info",
"[",
"'apiKey'",
"]",
"if",
"not",
"apiKey",
... | https://github.com/sfyc23/EverydayWechat/blob/6b81d03dde92cfef584428bc1e59d2858e94204e/everyday_wechat/control/bot/tuling123.py#L29-L74 | ||
saltstack/raet | 54858029568115550c7cb7d93e999d9c52b1494a | raet/road/keeping.py | python | RoadKeep.dumpLocalRole | (self, local) | Dump role data for local | Dump role data for local | [
"Dump",
"role",
"data",
"for",
"local"
] | def dumpLocalRole(self, local):
'''
Dump role data for local
'''
data = odict([
('role', local.role),
('sighex', local.signer.keyhex),
('prihex', local.priver.keyhex),
])
if self.verifyLocalData(data, localFields=self.LocalRoleFields):
self.dumpLocalRoleData(data) | [
"def",
"dumpLocalRole",
"(",
"self",
",",
"local",
")",
":",
"data",
"=",
"odict",
"(",
"[",
"(",
"'role'",
",",
"local",
".",
"role",
")",
",",
"(",
"'sighex'",
",",
"local",
".",
"signer",
".",
"keyhex",
")",
",",
"(",
"'prihex'",
",",
"local",
... | https://github.com/saltstack/raet/blob/54858029568115550c7cb7d93e999d9c52b1494a/raet/road/keeping.py#L278-L288 | ||
Qiskit/qiskit-terra | b66030e3b9192efdd3eb95cf25c6545fe0a13da4 | qiskit/qobj/qasm_qobj.py | python | QasmQobj.from_dict | (cls, data) | return cls(
qobj_id=data.get("qobj_id"), config=config, experiments=experiments, header=header
) | Create a new QASMQobj object from a dictionary.
Args:
data (dict): A dictionary representing the QasmQobj to create. It
will be in the same format as output by :func:`to_dict`.
Returns:
QasmQobj: The QasmQobj from the input dictionary. | Create a new QASMQobj object from a dictionary. | [
"Create",
"a",
"new",
"QASMQobj",
"object",
"from",
"a",
"dictionary",
"."
] | def from_dict(cls, data):
"""Create a new QASMQobj object from a dictionary.
Args:
data (dict): A dictionary representing the QasmQobj to create. It
will be in the same format as output by :func:`to_dict`.
Returns:
QasmQobj: The QasmQobj from the input dictionary.
"""
config = None
if "config" in data:
config = QasmQobjConfig.from_dict(data["config"])
experiments = None
if "experiments" in data:
experiments = [QasmQobjExperiment.from_dict(exp) for exp in data["experiments"]]
header = None
if "header" in data:
header = QobjHeader.from_dict(data["header"])
return cls(
qobj_id=data.get("qobj_id"), config=config, experiments=experiments, header=header
) | [
"def",
"from_dict",
"(",
"cls",
",",
"data",
")",
":",
"config",
"=",
"None",
"if",
"\"config\"",
"in",
"data",
":",
"config",
"=",
"QasmQobjConfig",
".",
"from_dict",
"(",
"data",
"[",
"\"config\"",
"]",
")",
"experiments",
"=",
"None",
"if",
"\"experim... | https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/qobj/qasm_qobj.py#L634-L656 | |
Q2h1Cg/CMS-Exploit-Framework | 6bc54e33f316c81f97e16e10b12c7da589efbbd4 | lib/requests/packages/charade/__init__.py | python | charade_cli | () | Script which takes one or more file paths and reports on their detected
encodings
Example::
% chardetect.py somefile someotherfile
somefile: windows-1252 with confidence 0.5
someotherfile: ascii with confidence 1.0 | Script which takes one or more file paths and reports on their detected
encodings | [
"Script",
"which",
"takes",
"one",
"or",
"more",
"file",
"paths",
"and",
"reports",
"on",
"their",
"detected",
"encodings"
] | def charade_cli():
"""
Script which takes one or more file paths and reports on their detected
encodings
Example::
% chardetect.py somefile someotherfile
somefile: windows-1252 with confidence 0.5
someotherfile: ascii with confidence 1.0
"""
from sys import argv
for path in argv[1:]:
print(_description_of(path)) | [
"def",
"charade_cli",
"(",
")",
":",
"from",
"sys",
"import",
"argv",
"for",
"path",
"in",
"argv",
"[",
"1",
":",
"]",
":",
"print",
"(",
"_description_of",
"(",
"path",
")",
")"
] | https://github.com/Q2h1Cg/CMS-Exploit-Framework/blob/6bc54e33f316c81f97e16e10b12c7da589efbbd4/lib/requests/packages/charade/__init__.py#L51-L65 | ||
bslatkin/effectivepython | 4ae6f3141291ea137eb29a245bf889dbc8091713 | example_code/item_24.py | python | decode | (data, default={}) | [] | def decode(data, default={}):
try:
return json.loads(data)
except ValueError:
return default | [
"def",
"decode",
"(",
"data",
",",
"default",
"=",
"{",
"}",
")",
":",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"data",
")",
"except",
"ValueError",
":",
"return",
"default"
] | https://github.com/bslatkin/effectivepython/blob/4ae6f3141291ea137eb29a245bf889dbc8091713/example_code/item_24.py#L84-L88 | ||||
sschuhmann/Helium | 861700f120d7e7a4187419e1cb27be78bd368fda | lib/client/jupyter_client/multikernelmanager.py | python | MultiKernelManager.add_restart_callback | (self, kernel_id, callback, event='restart') | add a callback for the KernelRestarter | add a callback for the KernelRestarter | [
"add",
"a",
"callback",
"for",
"the",
"KernelRestarter"
] | def add_restart_callback(self, kernel_id, callback, event='restart'):
"""add a callback for the KernelRestarter""" | [
"def",
"add_restart_callback",
"(",
"self",
",",
"kernel_id",
",",
"callback",
",",
"event",
"=",
"'restart'",
")",
":"
] | https://github.com/sschuhmann/Helium/blob/861700f120d7e7a4187419e1cb27be78bd368fda/lib/client/jupyter_client/multikernelmanager.py#L230-L231 | ||
scott-griffiths/bitstring | c84ad7f02818caf7102d556c6dcbdef153b0cf11 | bitstring.py | python | Bits.join | (self, sequence) | return s | Return concatenation of bitstrings joined by self.
sequence -- A sequence of bitstrings. | Return concatenation of bitstrings joined by self. | [
"Return",
"concatenation",
"of",
"bitstrings",
"joined",
"by",
"self",
"."
] | def join(self, sequence):
"""Return concatenation of bitstrings joined by self.
sequence -- A sequence of bitstrings.
"""
s = self.__class__()
i = iter(sequence)
try:
s._addright(Bits(next(i)))
while True:
n = next(i)
s._addright(self)
s._addright(Bits(n))
except StopIteration:
pass
return s | [
"def",
"join",
"(",
"self",
",",
"sequence",
")",
":",
"s",
"=",
"self",
".",
"__class__",
"(",
")",
"i",
"=",
"iter",
"(",
"sequence",
")",
"try",
":",
"s",
".",
"_addright",
"(",
"Bits",
"(",
"next",
"(",
"i",
")",
")",
")",
"while",
"True",
... | https://github.com/scott-griffiths/bitstring/blob/c84ad7f02818caf7102d556c6dcbdef153b0cf11/bitstring.py#L2738-L2754 | |
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/ssm/v20190923/ssm_client.py | python | SsmClient.RestoreSecret | (self, request) | 该接口用于恢复计划删除(PendingDelete状态)中的凭据,取消计划删除。取消计划删除的凭据将处于Disabled 状态,如需恢复使用,通过EnableSecret 接口开启凭据。
:param request: Request instance for RestoreSecret.
:type request: :class:`tencentcloud.ssm.v20190923.models.RestoreSecretRequest`
:rtype: :class:`tencentcloud.ssm.v20190923.models.RestoreSecretResponse` | 该接口用于恢复计划删除(PendingDelete状态)中的凭据,取消计划删除。取消计划删除的凭据将处于Disabled 状态,如需恢复使用,通过EnableSecret 接口开启凭据。 | [
"该接口用于恢复计划删除(PendingDelete状态)中的凭据,取消计划删除。取消计划删除的凭据将处于Disabled",
"状态,如需恢复使用,通过EnableSecret",
"接口开启凭据。"
] | def RestoreSecret(self, request):
"""该接口用于恢复计划删除(PendingDelete状态)中的凭据,取消计划删除。取消计划删除的凭据将处于Disabled 状态,如需恢复使用,通过EnableSecret 接口开启凭据。
:param request: Request instance for RestoreSecret.
:type request: :class:`tencentcloud.ssm.v20190923.models.RestoreSecretRequest`
:rtype: :class:`tencentcloud.ssm.v20190923.models.RestoreSecretResponse`
"""
try:
params = request._serialize()
body = self.call("RestoreSecret", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.RestoreSecretResponse()
model._deserialize(response["Response"])
return model
else:
code = response["Response"]["Error"]["Code"]
message = response["Response"]["Error"]["Message"]
reqid = response["Response"]["RequestId"]
raise TencentCloudSDKException(code, message, reqid)
except Exception as e:
if isinstance(e, TencentCloudSDKException):
raise
else:
raise TencentCloudSDKException(e.message, e.message) | [
"def",
"RestoreSecret",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"params",
"=",
"request",
".",
"_serialize",
"(",
")",
"body",
"=",
"self",
".",
"call",
"(",
"\"RestoreSecret\"",
",",
"params",
")",
"response",
"=",
"json",
".",
"loads",
"("... | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/ssm/v20190923/ssm_client.py#L566-L591 | ||
jython/jython3 | def4f8ec47cb7a9c799ea4c745f12badf92c5769 | lib-python/3.5.1/multiprocessing/context.py | python | BaseContext.set_forkserver_preload | (self, module_names) | Set list of module names to try to load in forkserver process.
This is really just a hint. | Set list of module names to try to load in forkserver process.
This is really just a hint. | [
"Set",
"list",
"of",
"module",
"names",
"to",
"try",
"to",
"load",
"in",
"forkserver",
"process",
".",
"This",
"is",
"really",
"just",
"a",
"hint",
"."
] | def set_forkserver_preload(self, module_names):
'''Set list of module names to try to load in forkserver process.
This is really just a hint.
'''
from .forkserver import set_forkserver_preload
set_forkserver_preload(module_names) | [
"def",
"set_forkserver_preload",
"(",
"self",
",",
"module_names",
")",
":",
"from",
".",
"forkserver",
"import",
"set_forkserver_preload",
"set_forkserver_preload",
"(",
"module_names",
")"
] | https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/multiprocessing/context.py#L178-L183 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/idlelib/configDialog.py | python | ConfigDialog.SetThemeType | (self) | [] | def SetThemeType(self):
if self.themeIsBuiltin.get():
self.optMenuThemeBuiltin.config(state=NORMAL)
self.optMenuThemeCustom.config(state=DISABLED)
self.buttonDeleteCustomTheme.config(state=DISABLED)
else:
self.optMenuThemeBuiltin.config(state=DISABLED)
self.radioThemeCustom.config(state=NORMAL)
self.optMenuThemeCustom.config(state=NORMAL)
self.buttonDeleteCustomTheme.config(state=NORMAL) | [
"def",
"SetThemeType",
"(",
"self",
")",
":",
"if",
"self",
".",
"themeIsBuiltin",
".",
"get",
"(",
")",
":",
"self",
".",
"optMenuThemeBuiltin",
".",
"config",
"(",
"state",
"=",
"NORMAL",
")",
"self",
".",
"optMenuThemeCustom",
".",
"config",
"(",
"sta... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/idlelib/configDialog.py#L570-L579 | ||||
emmetio/livestyle-sublime-old | c42833c046e9b2f53ebce3df3aa926528f5a33b5 | tornado/util.py | python | Configurable.configurable_default | (cls) | Returns the implementation class to be used if none is configured. | Returns the implementation class to be used if none is configured. | [
"Returns",
"the",
"implementation",
"class",
"to",
"be",
"used",
"if",
"none",
"is",
"configured",
"."
] | def configurable_default(cls):
"""Returns the implementation class to be used if none is configured."""
raise NotImplementedError() | [
"def",
"configurable_default",
"(",
"cls",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/emmetio/livestyle-sublime-old/blob/c42833c046e9b2f53ebce3df3aa926528f5a33b5/tornado/util.py#L185-L187 | ||
shazow/unstdlib.py | 53998edbca80be175c62d4d01b7f433e3b67dd2c | unstdlib/html.py | python | tag | (tagname, content='', attrs=None) | return literal('<%s>%s</%s>' % (open_tag, content, tagname)) | Helper for programmatically building HTML tags.
Note that this barely does any escaping, and will happily spit out
dangerous user input if used as such.
:param tagname:
Tag name of the DOM element we want to return.
:param content:
Optional content of the DOM element. If `None`, then the element is
self-closed. By default, the content is an empty string. Supports
iterables like generators.
:param attrs:
Optional dictionary-like collection of attributes for the DOM element.
Example::
>>> tag('div', content='Hello, world.')
u'<div>Hello, world.</div>'
>>> tag('script', attrs={'src': '/static/js/core.js'})
u'<script src="/static/js/core.js"></script>'
>>> tag('script', attrs=[('src', '/static/js/core.js'), ('type', 'text/javascript')])
u'<script src="/static/js/core.js" type="text/javascript"></script>'
>>> tag('meta', content=None, attrs=dict(content='"quotedquotes"'))
u'<meta content="\\\\"quotedquotes\\\\"" />'
>>> tag('ul', (tag('li', str(i)) for i in xrange(3)))
u'<ul><li>0</li><li>1</li><li>2</li></ul>' | Helper for programmatically building HTML tags. | [
"Helper",
"for",
"programmatically",
"building",
"HTML",
"tags",
"."
] | def tag(tagname, content='', attrs=None):
""" Helper for programmatically building HTML tags.
Note that this barely does any escaping, and will happily spit out
dangerous user input if used as such.
:param tagname:
Tag name of the DOM element we want to return.
:param content:
Optional content of the DOM element. If `None`, then the element is
self-closed. By default, the content is an empty string. Supports
iterables like generators.
:param attrs:
Optional dictionary-like collection of attributes for the DOM element.
Example::
>>> tag('div', content='Hello, world.')
u'<div>Hello, world.</div>'
>>> tag('script', attrs={'src': '/static/js/core.js'})
u'<script src="/static/js/core.js"></script>'
>>> tag('script', attrs=[('src', '/static/js/core.js'), ('type', 'text/javascript')])
u'<script src="/static/js/core.js" type="text/javascript"></script>'
>>> tag('meta', content=None, attrs=dict(content='"quotedquotes"'))
u'<meta content="\\\\"quotedquotes\\\\"" />'
>>> tag('ul', (tag('li', str(i)) for i in xrange(3)))
u'<ul><li>0</li><li>1</li><li>2</li></ul>'
"""
attrs_str = attrs and ' '.join(_generate_dom_attrs(attrs))
open_tag = tagname
if attrs_str:
open_tag += ' ' + attrs_str
if content is None:
return literal('<%s />' % open_tag)
content = ''.join(iterate(content, unless=string_types + (literal,)))
return literal('<%s>%s</%s>' % (open_tag, content, tagname)) | [
"def",
"tag",
"(",
"tagname",
",",
"content",
"=",
"''",
",",
"attrs",
"=",
"None",
")",
":",
"attrs_str",
"=",
"attrs",
"and",
"' '",
".",
"join",
"(",
"_generate_dom_attrs",
"(",
"attrs",
")",
")",
"open_tag",
"=",
"tagname",
"if",
"attrs_str",
":",
... | https://github.com/shazow/unstdlib.py/blob/53998edbca80be175c62d4d01b7f433e3b67dd2c/unstdlib/html.py#L110-L149 | |
dipy/dipy | be956a529465b28085f8fc435a756947ddee1c89 | dipy/reconst/fwdti.py | python | FreeWaterTensorFit.f | (self) | return self.model_params[..., 12] | Returns the free water diffusion volume fraction f | Returns the free water diffusion volume fraction f | [
"Returns",
"the",
"free",
"water",
"diffusion",
"volume",
"fraction",
"f"
] | def f(self):
""" Returns the free water diffusion volume fraction f """
return self.model_params[..., 12] | [
"def",
"f",
"(",
"self",
")",
":",
"return",
"self",
".",
"model_params",
"[",
"...",
",",
"12",
"]"
] | https://github.com/dipy/dipy/blob/be956a529465b28085f8fc435a756947ddee1c89/dipy/reconst/fwdti.py#L205-L207 | |
xyou365/AutoRclone | f90853a989b3773b188fe7501a574800c6ef1145 | gen_sa_accounts.py | python | _delete_sas | (iam,project) | [] | def _delete_sas(iam,project):
sas = _list_sas(iam,project)
batch = iam.new_batch_http_request(callback=_def_batch_resp)
for i in sas:
batch.add(iam.projects().serviceAccounts().delete(name=i['name']))
batch.execute() | [
"def",
"_delete_sas",
"(",
"iam",
",",
"project",
")",
":",
"sas",
"=",
"_list_sas",
"(",
"iam",
",",
"project",
")",
"batch",
"=",
"iam",
".",
"new_batch_http_request",
"(",
"callback",
"=",
"_def_batch_resp",
")",
"for",
"i",
"in",
"sas",
":",
"batch",... | https://github.com/xyou365/AutoRclone/blob/f90853a989b3773b188fe7501a574800c6ef1145/gen_sa_accounts.py#L139-L144 | ||||
wxWidgets/Phoenix | b2199e299a6ca6d866aa6f3d0888499136ead9d6 | wx/py/filling.py | python | FillingFrame.__init__ | (self, parent=None, id=-1, title='PyFilling',
pos=wx.DefaultPosition, size=(600, 400),
style=wx.DEFAULT_FRAME_STYLE, rootObject=None,
rootLabel=None, rootIsNamespace=False, static=False) | Create FillingFrame instance. | Create FillingFrame instance. | [
"Create",
"FillingFrame",
"instance",
"."
] | def __init__(self, parent=None, id=-1, title='PyFilling',
pos=wx.DefaultPosition, size=(600, 400),
style=wx.DEFAULT_FRAME_STYLE, rootObject=None,
rootLabel=None, rootIsNamespace=False, static=False):
"""Create FillingFrame instance."""
wx.Frame.__init__(self, parent, id, title, pos, size, style)
intro = 'PyFilling - The Tastiest Namespace Inspector'
self.CreateStatusBar()
self.SetStatusText(intro)
self.SetIcon(images.getPyIcon())
self.filling = Filling(parent=self, rootObject=rootObject,
rootLabel=rootLabel,
rootIsNamespace=rootIsNamespace,
static=static)
# Override so that status messages go to the status bar.
self.filling.tree.setStatusText = self.SetStatusText | [
"def",
"__init__",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"id",
"=",
"-",
"1",
",",
"title",
"=",
"'PyFilling'",
",",
"pos",
"=",
"wx",
".",
"DefaultPosition",
",",
"size",
"=",
"(",
"600",
",",
"400",
")",
",",
"style",
"=",
"wx",
".",
... | https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/py/filling.py#L332-L347 | ||
cmbruns/pyopenvr | ac4847a8a05cda0d4bcf7c4f243008b2a191c7a5 | src/openvr/__init__.py | python | IVRSettings.getSettingsErrorNameFromEnum | (self, error) | return result.decode('utf-8') | [] | def getSettingsErrorNameFromEnum(self, error):
fn = self.function_table.getSettingsErrorNameFromEnum
result = fn(error)
return result.decode('utf-8') | [
"def",
"getSettingsErrorNameFromEnum",
"(",
"self",
",",
"error",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getSettingsErrorNameFromEnum",
"result",
"=",
"fn",
"(",
"error",
")",
"return",
"result",
".",
"decode",
"(",
"'utf-8'",
")"
] | https://github.com/cmbruns/pyopenvr/blob/ac4847a8a05cda0d4bcf7c4f243008b2a191c7a5/src/openvr/__init__.py#L3790-L3793 | |||
Liusifei/UVC | 36bc6b2c99366a6d1a6033229d395f3c88ff656b | libs/track_utils.py | python | calc_center | (arr, mode='mean', sigma=10) | return mass_center | INPUTS:
- arr: an array with coordinates, shape: n
- mode: 'mean' to calculate Euclean center, 'mass' to calculate mass center
- sigma: Gaussian parameter if calculating mass center | INPUTS:
- arr: an array with coordinates, shape: n
- mode: 'mean' to calculate Euclean center, 'mass' to calculate mass center
- sigma: Gaussian parameter if calculating mass center | [
"INPUTS",
":",
"-",
"arr",
":",
"an",
"array",
"with",
"coordinates",
"shape",
":",
"n",
"-",
"mode",
":",
"mean",
"to",
"calculate",
"Euclean",
"center",
"mass",
"to",
"calculate",
"mass",
"center",
"-",
"sigma",
":",
"Gaussian",
"parameter",
"if",
"cal... | def calc_center(arr, mode='mean', sigma=10):
"""
INPUTS:
- arr: an array with coordinates, shape: n
- mode: 'mean' to calculate Euclean center, 'mass' to calculate mass center
- sigma: Gaussian parameter if calculating mass center
"""
eu_center = torch.mean(arr)
if(mode == 'mean'):
return eu_center
# calculate weight center
eu_center = eu_center.view(1,1).repeat(1,arr.size(0)).squeeze()
diff = eu_center - arr
weight = gaussin(diff, sigma)
mass_center = torch.sum(weight * arr / (torch.sum(weight)))
return mass_center | [
"def",
"calc_center",
"(",
"arr",
",",
"mode",
"=",
"'mean'",
",",
"sigma",
"=",
"10",
")",
":",
"eu_center",
"=",
"torch",
".",
"mean",
"(",
"arr",
")",
"if",
"(",
"mode",
"==",
"'mean'",
")",
":",
"return",
"eu_center",
"# calculate weight center",
"... | https://github.com/Liusifei/UVC/blob/36bc6b2c99366a6d1a6033229d395f3c88ff656b/libs/track_utils.py#L159-L174 | |
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | modules/s3cfg.py | python | S3Config.get_auth_registration_link_user_to_default | (self) | return self.auth.get("registration_link_user_to_default") | Link User accounts to none or more of:
* staff
* volunteer
* member
Should be an iterable. | Link User accounts to none or more of:
* staff
* volunteer
* member
Should be an iterable. | [
"Link",
"User",
"accounts",
"to",
"none",
"or",
"more",
"of",
":",
"*",
"staff",
"*",
"volunteer",
"*",
"member",
"Should",
"be",
"an",
"iterable",
"."
] | def get_auth_registration_link_user_to_default(self):
"""
Link User accounts to none or more of:
* staff
* volunteer
* member
Should be an iterable.
"""
return self.auth.get("registration_link_user_to_default") | [
"def",
"get_auth_registration_link_user_to_default",
"(",
"self",
")",
":",
"return",
"self",
".",
"auth",
".",
"get",
"(",
"\"registration_link_user_to_default\"",
")"
] | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3cfg.py#L775-L783 | |
tomerfiliba/plumbum | 20cdda5e8bbd9f83d64b154f6b4fcd28216c63e1 | plumbum/colorlib/styles.py | python | Style.ansi_sequence | (self) | This is the string ANSI sequence. | This is the string ANSI sequence. | [
"This",
"is",
"the",
"string",
"ANSI",
"sequence",
"."
] | def ansi_sequence(self):
"""This is the string ANSI sequence."""
codes = self.ansi_codes
if codes:
return "\033[" + ";".join(map(str, self.ansi_codes)) + "m"
else:
return "" | [
"def",
"ansi_sequence",
"(",
"self",
")",
":",
"codes",
"=",
"self",
".",
"ansi_codes",
"if",
"codes",
":",
"return",
"\"\\033[\"",
"+",
"\";\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"self",
".",
"ansi_codes",
")",
")",
"+",
"\"m\"",
"else",
":"... | https://github.com/tomerfiliba/plumbum/blob/20cdda5e8bbd9f83d64b154f6b4fcd28216c63e1/plumbum/colorlib/styles.py#L570-L576 | ||
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/bdf/cards/thermal/loads.py | python | TEMPD.uncross_reference | (self) | Removes cross-reference links | Removes cross-reference links | [
"Removes",
"cross",
"-",
"reference",
"links"
] | def uncross_reference(self) -> None:
"""Removes cross-reference links"""
pass | [
"def",
"uncross_reference",
"(",
"self",
")",
"->",
"None",
":",
"pass"
] | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/thermal/loads.py#L1608-L1610 | ||
huntfx/MouseTracks | 4dfab6386f9461be77cb19b54c9c498d74fb4ef6 | mousetracks/utils/qt/main.py | python | QtLayout.__init__ | (self, func, parent=None, *args, **kwargs) | [] | def __init__(self, func, parent=None, *args, **kwargs):
super(QtLayout, self).__init__(func, parent, *args, **kwargs)
if parent is not None:
if isinstance(parent, QtRoot):
if isinstance(parent.QObject, QtWidgets.QMainWindow):
print('{}.setCentralWidget(layoutToWidget({}))'.format(parent.QObject.__class__.__name__, self.QObject.__class__.__name__))
parent.QObject.setCentralWidget(layoutToWidget(self.QObject))
elif isinstance(parent.QObject, (QtWidgets.QToolBar, QtWidgets.QDockWidget)):
raise NotImplementedError('{} is not yet supported'.format(parent.QObject.__class__.__name__))
elif isinstance(parent, (QtTabLayout, QtTabWidget, QtGroupBoxWidget, QtSplitterLayoutWidget)):
print('{}.setLayout({})'.format(parent.QObject.__class__.__name__, self.QObject.__class__.__name__))
parent.QObject.setLayout(self.QObject)
elif isinstance(parent, QtScrollWidget):
print('{}.setWidget(layoutToWidget({}))'.format(parent.QObject.__class__.__name__, self.QObject.__class__.__name__))
parent.QObject.setWidget(layoutToWidget(self.QObject))
elif isinstance(parent, QtLayout):
print('{}.addLayout({})'.format(parent.QObject.__class__.__name__, self.QObject.__class__.__name__))
parent.QObject.addLayout(self.QObject)
else:
print('Unknown parent (layout): {}'.format(parent)) | [
"def",
"__init__",
"(",
"self",
",",
"func",
",",
"parent",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"QtLayout",
",",
"self",
")",
".",
"__init__",
"(",
"func",
",",
"parent",
",",
"*",
"args",
",",
"*",
"... | https://github.com/huntfx/MouseTracks/blob/4dfab6386f9461be77cb19b54c9c498d74fb4ef6/mousetracks/utils/qt/main.py#L194-L214 | ||||
Pyomo/pyomo | dbd4faee151084f343b893cc2b0c04cf2b76fd92 | pyomo/core/base/component.py | python | _ComponentBase.is_component_type | (self) | return True | Return True if this class is a Pyomo component | Return True if this class is a Pyomo component | [
"Return",
"True",
"if",
"this",
"class",
"is",
"a",
"Pyomo",
"component"
] | def is_component_type(self):
"""Return True if this class is a Pyomo component"""
return True | [
"def",
"is_component_type",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/core/base/component.py#L82-L84 | |
reviewboard/rbtools | b4838a640b458641ffd233093ae65971d0b4d529 | rbtools/api/cache.py | python | APICache._row_factory | (cursor, row) | return CacheEntry(
url=row[0],
vary_headers=json.loads(row[1]),
max_age=row[2],
etag=row[3],
local_date=datetime.datetime.strptime(row[4],
CacheEntry.DATE_FORMAT),
last_modified=row[5],
mime_type=row[6],
item_mime_type=row[7],
response_body=six.binary_type(row[8]),
) | A factory for creating individual Cache Entries from db rows. | A factory for creating individual Cache Entries from db rows. | [
"A",
"factory",
"for",
"creating",
"individual",
"Cache",
"Entries",
"from",
"db",
"rows",
"."
] | def _row_factory(cursor, row):
"""A factory for creating individual Cache Entries from db rows."""
return CacheEntry(
url=row[0],
vary_headers=json.loads(row[1]),
max_age=row[2],
etag=row[3],
local_date=datetime.datetime.strptime(row[4],
CacheEntry.DATE_FORMAT),
last_modified=row[5],
mime_type=row[6],
item_mime_type=row[7],
response_body=six.binary_type(row[8]),
) | [
"def",
"_row_factory",
"(",
"cursor",
",",
"row",
")",
":",
"return",
"CacheEntry",
"(",
"url",
"=",
"row",
"[",
"0",
"]",
",",
"vary_headers",
"=",
"json",
".",
"loads",
"(",
"row",
"[",
"1",
"]",
")",
",",
"max_age",
"=",
"row",
"[",
"2",
"]",
... | https://github.com/reviewboard/rbtools/blob/b4838a640b458641ffd233093ae65971d0b4d529/rbtools/api/cache.py#L514-L527 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/build/lib.linux-x86_64-2.7/flaskbb/plugins/models.py | python | PluginRegistry.update_settings | (self, settings) | Updates the given settings of the plugin.
:param settings: A dictionary containing setting items. | Updates the given settings of the plugin. | [
"Updates",
"the",
"given",
"settings",
"of",
"the",
"plugin",
"."
] | def update_settings(self, settings):
"""Updates the given settings of the plugin.
:param settings: A dictionary containing setting items.
"""
pluginstore = PluginStore.query.filter(
PluginStore.plugin_id == self.id,
PluginStore.key.in_(settings.keys())
).all()
setting_list = []
for pluginsetting in pluginstore:
pluginsetting.value = settings[pluginsetting.key]
setting_list.append(pluginsetting)
db.session.add_all(setting_list)
db.session.commit() | [
"def",
"update_settings",
"(",
"self",
",",
"settings",
")",
":",
"pluginstore",
"=",
"PluginStore",
".",
"query",
".",
"filter",
"(",
"PluginStore",
".",
"plugin_id",
"==",
"self",
".",
"id",
",",
"PluginStore",
".",
"key",
".",
"in_",
"(",
"settings",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/build/lib.linux-x86_64-2.7/flaskbb/plugins/models.py#L98-L113 | ||
pynag/pynag | e72cf7ce2395263e2b3080cae0ece2b03dbbfa27 | pynag/Utils/metrics.py | python | PerfDataMetric.__str__ | (self) | return self.__repr__() | [] | def __str__(self):
return self.__repr__() | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"__repr__",
"(",
")"
] | https://github.com/pynag/pynag/blob/e72cf7ce2395263e2b3080cae0ece2b03dbbfa27/pynag/Utils/metrics.py#L88-L89 | |||
cloudera/impyla | 0c736af4cad2bade9b8e313badc08ec50e81c948 | impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py | python | Client.partition_name_to_vals | (self, part_name) | return self.recv_partition_name_to_vals() | Parameters:
- part_name | Parameters:
- part_name | [
"Parameters",
":",
"-",
"part_name"
] | def partition_name_to_vals(self, part_name):
"""
Parameters:
- part_name
"""
self.send_partition_name_to_vals(part_name)
return self.recv_partition_name_to_vals() | [
"def",
"partition_name_to_vals",
"(",
"self",
",",
"part_name",
")",
":",
"self",
".",
"send_partition_name_to_vals",
"(",
"part_name",
")",
"return",
"self",
".",
"recv_partition_name_to_vals",
"(",
")"
] | https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L3936-L3942 | |
iterative/dvc | 13238e97168007cb5ba21966368457776274b9ca | dvc/progress.py | python | Tqdm.__init__ | (
self,
iterable=None,
disable=None,
level=logging.ERROR,
desc=None,
leave=False,
bar_format=None,
bytes=False, # pylint: disable=redefined-builtin
file=None,
total=None,
postfix=None,
**kwargs,
) | bytes : shortcut for
`unit='B', unit_scale=True, unit_divisor=1024, miniters=1`
desc : persists after `close()`
level : effective logging level for determining `disable`;
used only if `disable` is unspecified
disable : If (default: None) or False,
will be determined by logging level.
May be overridden to `True` due to non-TTY status.
Skip override by specifying env var `DVC_IGNORE_ISATTY`.
kwargs : anything accepted by `tqdm.tqdm()` | bytes : shortcut for
`unit='B', unit_scale=True, unit_divisor=1024, miniters=1`
desc : persists after `close()`
level : effective logging level for determining `disable`;
used only if `disable` is unspecified
disable : If (default: None) or False,
will be determined by logging level.
May be overridden to `True` due to non-TTY status.
Skip override by specifying env var `DVC_IGNORE_ISATTY`.
kwargs : anything accepted by `tqdm.tqdm()` | [
"bytes",
":",
"shortcut",
"for",
"unit",
"=",
"B",
"unit_scale",
"=",
"True",
"unit_divisor",
"=",
"1024",
"miniters",
"=",
"1",
"desc",
":",
"persists",
"after",
"close",
"()",
"level",
":",
"effective",
"logging",
"level",
"for",
"determining",
"disable",
... | def __init__(
self,
iterable=None,
disable=None,
level=logging.ERROR,
desc=None,
leave=False,
bar_format=None,
bytes=False, # pylint: disable=redefined-builtin
file=None,
total=None,
postfix=None,
**kwargs,
):
"""
bytes : shortcut for
`unit='B', unit_scale=True, unit_divisor=1024, miniters=1`
desc : persists after `close()`
level : effective logging level for determining `disable`;
used only if `disable` is unspecified
disable : If (default: None) or False,
will be determined by logging level.
May be overridden to `True` due to non-TTY status.
Skip override by specifying env var `DVC_IGNORE_ISATTY`.
kwargs : anything accepted by `tqdm.tqdm()`
"""
kwargs = kwargs.copy()
if bytes:
kwargs = {**self.BYTES_DEFAULTS, **kwargs}
else:
kwargs.setdefault("unit_scale", total > 999 if total else True)
if file is None:
file = sys.stderr
# auto-disable based on `logger.level`
if not disable:
disable = logger.getEffectiveLevel() > level
# auto-disable based on TTY
if (
not disable
and not env2bool(DVC_IGNORE_ISATTY)
and hasattr(file, "isatty")
):
disable = not file.isatty()
super().__init__(
iterable=iterable,
disable=disable,
leave=leave,
desc=desc,
bar_format="!",
lock_args=(False,),
total=total,
**kwargs,
)
self.postfix = postfix or {"info": ""}
if bar_format is None:
if self.__len__():
self.bar_format = (
self.BAR_FMT_DEFAULT_NESTED
if self.pos
else self.BAR_FMT_DEFAULT
)
else:
self.bar_format = self.BAR_FMT_NOTOTAL
else:
self.bar_format = bar_format
self.refresh() | [
"def",
"__init__",
"(",
"self",
",",
"iterable",
"=",
"None",
",",
"disable",
"=",
"None",
",",
"level",
"=",
"logging",
".",
"ERROR",
",",
"desc",
"=",
"None",
",",
"leave",
"=",
"False",
",",
"bar_format",
"=",
"None",
",",
"bytes",
"=",
"False",
... | https://github.com/iterative/dvc/blob/13238e97168007cb5ba21966368457776274b9ca/dvc/progress.py#L42-L107 | ||
googlearchive/PyDrive | 42022f9a1c48f435438fce74ad4032ec9f34cfd1 | pydrive/apiattr.py | python | ApiResource.UpdateMetadata | (self, metadata=None) | Update metadata and mark all of them to be clean. | Update metadata and mark all of them to be clean. | [
"Update",
"metadata",
"and",
"mark",
"all",
"of",
"them",
"to",
"be",
"clean",
"."
] | def UpdateMetadata(self, metadata=None):
"""Update metadata and mark all of them to be clean."""
if metadata:
self.update(metadata)
self.metadata = dict(self) | [
"def",
"UpdateMetadata",
"(",
"self",
",",
"metadata",
"=",
"None",
")",
":",
"if",
"metadata",
":",
"self",
".",
"update",
"(",
"metadata",
")",
"self",
".",
"metadata",
"=",
"dict",
"(",
"self",
")"
] | https://github.com/googlearchive/PyDrive/blob/42022f9a1c48f435438fce74ad4032ec9f34cfd1/pydrive/apiattr.py#L86-L90 | ||
wucng/TensorExpand | 4ea58f64f5c5082b278229b799c9f679536510b7 | TensorExpand/Object detection/SSD/balancap-SSD-Tensorflow/nets/vgg.py | python | vgg_19 | (inputs,
num_classes=1000,
is_training=True,
dropout_keep_prob=0.5,
spatial_squeeze=True,
scope='vgg_19') | Oxford Net VGG 19-Layers version E Example.
Note: All the fully_connected layers have been transformed to conv2d layers.
To use in classification mode, resize input to 224x224.
Args:
inputs: a tensor of size [batch_size, height, width, channels].
num_classes: number of predicted classes.
is_training: whether or not the model is being trained.
dropout_keep_prob: the probability that activations are kept in the dropout
layers during training.
spatial_squeeze: whether or not should squeeze the spatial dimensions of the
outputs. Useful to remove unnecessary dimensions for classification.
scope: Optional scope for the variables.
Returns:
the last op containing the log predictions and end_points dict. | Oxford Net VGG 19-Layers version E Example. | [
"Oxford",
"Net",
"VGG",
"19",
"-",
"Layers",
"version",
"E",
"Example",
"."
] | def vgg_19(inputs,
num_classes=1000,
is_training=True,
dropout_keep_prob=0.5,
spatial_squeeze=True,
scope='vgg_19'):
"""Oxford Net VGG 19-Layers version E Example.
Note: All the fully_connected layers have been transformed to conv2d layers.
To use in classification mode, resize input to 224x224.
Args:
inputs: a tensor of size [batch_size, height, width, channels].
num_classes: number of predicted classes.
is_training: whether or not the model is being trained.
dropout_keep_prob: the probability that activations are kept in the dropout
layers during training.
spatial_squeeze: whether or not should squeeze the spatial dimensions of the
outputs. Useful to remove unnecessary dimensions for classification.
scope: Optional scope for the variables.
Returns:
the last op containing the log predictions and end_points dict.
"""
with tf.variable_scope(scope, 'vgg_19', [inputs]) as sc:
end_points_collection = sc.name + '_end_points'
# Collect outputs for conv2d, fully_connected and max_pool2d.
with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2d],
outputs_collections=end_points_collection):
net = slim.repeat(inputs, 2, slim.conv2d, 64, [3, 3], scope='conv1')
net = slim.max_pool2d(net, [2, 2], scope='pool1')
net = slim.repeat(net, 2, slim.conv2d, 128, [3, 3], scope='conv2')
net = slim.max_pool2d(net, [2, 2], scope='pool2')
net = slim.repeat(net, 4, slim.conv2d, 256, [3, 3], scope='conv3')
net = slim.max_pool2d(net, [2, 2], scope='pool3')
net = slim.repeat(net, 4, slim.conv2d, 512, [3, 3], scope='conv4')
net = slim.max_pool2d(net, [2, 2], scope='pool4')
net = slim.repeat(net, 4, slim.conv2d, 512, [3, 3], scope='conv5')
net = slim.max_pool2d(net, [2, 2], scope='pool5')
# Use conv2d instead of fully_connected layers.
net = slim.conv2d(net, 4096, [7, 7], padding='VALID', scope='fc6')
net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
scope='dropout6')
net = slim.conv2d(net, 4096, [1, 1], scope='fc7')
net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
scope='dropout7')
net = slim.conv2d(net, num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
scope='fc8')
# Convert end_points_collection into a end_point dict.
end_points = slim.utils.convert_collection_to_dict(end_points_collection)
if spatial_squeeze:
net = tf.squeeze(net, [1, 2], name='fc8/squeezed')
end_points[sc.name + '/fc8'] = net
return net, end_points | [
"def",
"vgg_19",
"(",
"inputs",
",",
"num_classes",
"=",
"1000",
",",
"is_training",
"=",
"True",
",",
"dropout_keep_prob",
"=",
"0.5",
",",
"spatial_squeeze",
"=",
"True",
",",
"scope",
"=",
"'vgg_19'",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
... | https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/Object detection/SSD/balancap-SSD-Tensorflow/nets/vgg.py#L184-L239 | ||
junekihong/linkedInScraper | 5d728b5288a5d547bb88ade9a6387c71159a7fb8 | linkedIn/linkedIn/spiders/linkedIn_spider.py | python | linkedInSpider.parse | (self, response) | f = open("html.txt","w+")
f.write(response.url)
f.write("\n\n")
f.write(response.body)
f.close() | f = open("html.txt","w+")
f.write(response.url)
f.write("\n\n")
f.write(response.body)
f.close() | [
"f",
"=",
"open",
"(",
"html",
".",
"txt",
"w",
"+",
")",
"f",
".",
"write",
"(",
"response",
".",
"url",
")",
"f",
".",
"write",
"(",
"\\",
"n",
"\\",
"n",
")",
"f",
".",
"write",
"(",
"response",
".",
"body",
")",
"f",
".",
"close",
"()"
... | def parse(self, response):
# If you want to look at the HTML you are parsing, uncomment the next few lines and then look at the file
"""
f = open("html.txt","w+")
f.write(response.url)
f.write("\n\n")
f.write(response.body)
f.close()
"""
hxs = HtmlXPathSelector(response)
#if it is a directory
if hxs.select('//body[@id="pagekey-seo_people_directory"]'):
for url in hxs.select('//ul[@class="column dual-column"]/li/a/@href').extract(): #take all of the subdirectories that show up and request them
url = url.encode('utf-8')
#print url
if "linkedin.com" not in url:
url = "https://www.linkedin.com" + url
#print url
if randomSampling and random.random() > samplingProbability: #random sampling.
continue
yield Request(url, callback=self.parse)
#if it is not a directory (its a regular page)
elif hxs.select('//meta[@name="pageImpressionID"]'):
f = open("html.txt","w+")
f.write(response.url)
f.write("\n\n")
f.write(response.body)
f.close()
item = linkedInItem()
item['url'] = response.url
#print response.url
item['headlineTitle'] = striplist(hxs.select('//p[@class="headline title"]/text()').extract())
HTMLtitle = striplist(hxs.select('//title/text()').extract())
item['name'] = [HTMLtitle[0].split('|')[0].strip()]
item['location'] = striplist(hxs.select('//dd/span/text()').extract())
#if not checkLocation(item['location']):
#print item['location']
#sys.stdout.flush()
#else:
if not filterForUS or checkLocation(item['location']):
item['industry'] = striplist(hxs.select('//dd[@class="descriptor"]/text()').extract())
item['overviewCurrent'] = striplist(hxs.select('//li/span[@class="org"]/text()').extract())
item['overviewPast'] = striplist(hxs.select("//td/ol/li/text()").extract())
# TODO: overviewEducation and overviewPast have the same xpath...
item['overviewEducation'] = striplist(hxs.select('//td/ol/li/text()').extract())
#item['recommendations'] = striplist(hxs.select('').extract())
item['connections'] = striplist(hxs.select('//div[@class="member-connections"]/strong/text()').extract())
#item['websites'] = striplist(hxs.select('').extract())
item['descriptionSummary'] = striplist(hxs.select('//section/div[@class="description"]/p/text()').extract())
# TODO: broken from here on down.
item['summarySpecialties'] = striplist(hxs.select('//div[@id="profile-specialties"]/p/text()').extract())
# ------------------------------------------------------------------------------------------------------------------
# Education
# ------------------------------------------------------------------------------------------------------------------
# Education: School Names
firstEducationSchool = []
for scope in hxs.select('//div[@class="position first education vevent vcard"]/h3[@class="summary fn org"]'):
names1 = scope.xpath('a/text()').extract()
names2 = scope.xpath('text()').extract()
firstEducationSchool += names1 + names2
firstEducationSchool = striplist(firstEducationSchool)
schoolNames = []
for scope in hxs.select('//div[@class="position education vevent vcard"]/h3[@class="summary fn org"]'):
names1 = scope.xpath('a/text()').extract()
names2 = scope.xpath('text()').extract()
schoolNames += names1 + names2
"""
for x in names1:
x = x.strip()
if x:
schoolNames.append(x)
for x in names2:
x = x.strip()
if x:
schoolNames.append(x)
"""
schoolNames = striplist(schoolNames)
# Education: Degrees
firstDegree = striplist(
hxs.select('//div[@class="position first education vevent vcard"]/h4/span[@class="degree"]/text()').extract())
schoolDegrees = striplist(
hxs.select('//div[@class="position education vevent vcard"]/h4/span[@class="degree"]/text()').extract())
# Education: Majors
firstMajor = striplist(
hxs.select('//div[@class="position first education vevent vcard"]/h4/span[@class="major"]/text()').extract())
schoolMajors = striplist(
hxs.select('//div[@class="position education vevent vcard"]/h4/span[@class="major"]/text()').extract())
# Education: Time Start
firstEducationStart = striplist(
hxs.select('//div[@class="position first education vevent vcard"]/p[@class="period"]/abbr[@class="dtstart"]/text()').extract())
educationStarts = striplist(
hxs.select('//div[@class="position education vevent vcard"]/p[@class="period"]/abbr[@class="dtstart"]/text()').extract())
# Education: Time End
firstEducationEnd = striplist(
hxs.select('//div[@class="position first education vevent vcard"]/p[@class="period"]/abbr[@class="dtend"]/text()').extract())
educationEnds = striplist(
hxs.select('//div[@class="position education vevent vcard"]/p[@class="period"]/abbr[@class="dtend"]/text()').extract())
item['educationSchoolName1'] = []
item['educationDegree1'] = []
item['educationMajor1'] = []
item['eduTimeStart1'] = []
item['eduTimeEnd1'] = []
if firstEducationSchool:
item['educationSchoolName1'] = firstEducationSchool.pop(0)
if firstDegree:
item['educationDegree1'] = firstDegree.pop(0)
if firstMajor:
item['educationMajor1'] = firstMajor.pop(0)
if firstEducationStart:
item['eduTimeStart1'] = firstEducationStart.pop(0)
if firstEducationEnd:
item['eduTimeEnd1'] = firstEducationEnd.pop(0)
elif schoolNames:
item['educationSchoolName1'] = schoolNames.pop(0)
if schoolDegrees:
item['educationDegree1'] = schoolDegrees.pop(0)
if schoolMajors:
item['educationMajor1'] = schoolMajors.pop(0)
if educationStarts:
item['eduTimeStart1'] = educationStarts.pop(0)
if educationEnds:
item['eduTimeEnd1'] = educationEnds.pop(0)
if not schoolNames:
item['educationSchoolName2'] = []
else:
item['educationSchoolName2'] = schoolNames.pop(0)
if not schoolNames:
item['educationSchoolName3'] = []
else:
item['educationSchoolName3'] = schoolNames.pop(0)
if not schoolDegrees:
item['educationDegree2'] = []
else:
item['educationDegree2'] = schoolDegrees.pop(0)
if not schoolDegrees:
item['educationDegree3'] = []
else:
item['educationDegree3'] = schoolDegrees.pop(0)
if not schoolMajors:
item['educationMajor2'] = []
else:
item['educationMajor2'] = schoolMajors.pop(0)
if not schoolMajors:
item['educationMajor3'] = []
else:
item['educationMajor3'] = schoolMajors.pop(0)
if not educationStarts:
item['eduTimeStart2'] = []
else:
item['eduTimeStart2'] = educationStarts.pop(0)
if not educationStarts:
item['eduTimeStart3'] = []
else:
item['eduTimeStart3'] = educationStarts.pop(0)
if not educationEnds:
item['eduTimeEnd2'] = []
else:
item['eduTimeEnd2'] = educationEnds.pop(0)
if not educationEnds:
item['eduTimeEnd3'] = []
else:
item['eduTimeEnd3'] = educationEnds.pop(0)
#------------------------------------------------------------------------------------------------------------------
# Work Experience
#------------------------------------------------------------------------------------------------------------------
# Work Experience: Title
experienceHeads = striplist(
hxs.select('//h3/span[@class="title"]/text()').extract())
item['experienceHeads'] = experienceHeads
# Work Experience: Company
experienceCompany = []
for scope in hxs.select('//h4/strong'):
#print "current scope:", scope
companies1 = scope.xpath('span[@class="org summary"]/text()').extract()
companies2 = scope.xpath('a/span[@class="org summary"]/text()').extract()
experienceCompany += companies1 + companies2
experienceCompany = striplist(experienceCompany)
item['expCompany'] = experienceCompany
# Work Experience: Time started
expTimeStarts = striplist(
hxs.select('//div[contains(@class, "experience")]/p/abbr[@class="dtstart"]/text()').extract())
item['expTimeStarts'] = expTimeStarts
# Work Experience: Time ended
timePresent = striplist(
hxs.select('//div[contains(@class, "experience")]/p/abbr[@class="dtstamp"]/text()').extract())
expTimeEnds = striplist(
hxs.select('//div[contains(@class, "experience")]/p/abbr[@class="dtend"]/text()').extract())
expTimeEnds = timePresent + expTimeEnds
item['expTimeEnds'] = expTimeEnds
# Work Experience: Time duration
expTimeDurations = striplist(
hxs.select('//div[contains(@class, "experience")]/p/span[@class="duration"]/text()').extract())
item['expTimeDurations'] = expTimeDurations
# Work Experience: Description
#expDescriptions = striplist(
#hxs.select('//p[@class=" description past-position"]/text()').extract())
yield item | [
"def",
"parse",
"(",
"self",
",",
"response",
")",
":",
"# If you want to look at the HTML you are parsing, uncomment the next few lines and then look at the file",
"hxs",
"=",
"HtmlXPathSelector",
"(",
"response",
")",
"#if it is a directory",
"if",
"hxs",
".",
"select",
"("... | https://github.com/junekihong/linkedInScraper/blob/5d728b5288a5d547bb88ade9a6387c71159a7fb8/linkedIn/linkedIn/spiders/linkedIn_spider.py#L29-L282 | ||
Tautulli/Tautulli | 2410eb33805aaac4bd1c5dad0f71e4f15afaf742 | lib/plexapi/server.py | python | PlexServer.unclaim | (self) | return Account(self, data) | Unclaim the Plex server. This will remove the server from your
:class:`~plexapi.myplex.MyPlexAccount`. | Unclaim the Plex server. This will remove the server from your
:class:`~plexapi.myplex.MyPlexAccount`. | [
"Unclaim",
"the",
"Plex",
"server",
".",
"This",
"will",
"remove",
"the",
"server",
"from",
"your",
":",
"class",
":",
"~plexapi",
".",
"myplex",
".",
"MyPlexAccount",
"."
] | def unclaim(self):
""" Unclaim the Plex server. This will remove the server from your
:class:`~plexapi.myplex.MyPlexAccount`.
"""
data = self.query(Account.key, method=self._session.delete)
return Account(self, data) | [
"def",
"unclaim",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"query",
"(",
"Account",
".",
"key",
",",
"method",
"=",
"self",
".",
"_session",
".",
"delete",
")",
"return",
"Account",
"(",
"self",
",",
"data",
")"
] | https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/plexapi/server.py#L215-L220 | |
mozilla/TTS | e9e07844b77a43fb0864354791fb4cf72ffded11 | TTS/tts/utils/speakers.py | python | parse_speakers | (c, args, meta_data_train, OUT_PATH) | return num_speakers, speaker_embedding_dim, speaker_mapping | Returns number of speakers, speaker embedding shape and speaker mapping | Returns number of speakers, speaker embedding shape and speaker mapping | [
"Returns",
"number",
"of",
"speakers",
"speaker",
"embedding",
"shape",
"and",
"speaker",
"mapping"
] | def parse_speakers(c, args, meta_data_train, OUT_PATH):
""" Returns number of speakers, speaker embedding shape and speaker mapping"""
if c.use_speaker_embedding:
speakers = get_speakers(meta_data_train)
if args.restore_path:
if c.use_external_speaker_embedding_file: # if restore checkpoint and use External Embedding file
prev_out_path = os.path.dirname(args.restore_path)
speaker_mapping = load_speaker_mapping(prev_out_path)
if not speaker_mapping:
print("WARNING: speakers.json was not found in restore_path, trying to use CONFIG.external_speaker_embedding_file")
speaker_mapping = load_speaker_mapping(c.external_speaker_embedding_file)
if not speaker_mapping:
raise RuntimeError("You must copy the file speakers.json to restore_path, or set a valid file in CONFIG.external_speaker_embedding_file")
speaker_embedding_dim = len(speaker_mapping[list(speaker_mapping.keys())[0]]['embedding'])
elif not c.use_external_speaker_embedding_file: # if restore checkpoint and don't use External Embedding file
prev_out_path = os.path.dirname(args.restore_path)
speaker_mapping = load_speaker_mapping(prev_out_path)
speaker_embedding_dim = None
assert all([speaker in speaker_mapping
for speaker in speakers]), "As of now you, you cannot " \
"introduce new speakers to " \
"a previously trained model."
elif c.use_external_speaker_embedding_file and c.external_speaker_embedding_file: # if start new train using External Embedding file
speaker_mapping = load_speaker_mapping(c.external_speaker_embedding_file)
speaker_embedding_dim = len(speaker_mapping[list(speaker_mapping.keys())[0]]['embedding'])
elif c.use_external_speaker_embedding_file and not c.external_speaker_embedding_file: # if start new train using External Embedding file and don't pass external embedding file
raise "use_external_speaker_embedding_file is True, so you need pass a external speaker embedding file, run GE2E-Speaker_Encoder-ExtractSpeakerEmbeddings-by-sample.ipynb or AngularPrototypical-Speaker_Encoder-ExtractSpeakerEmbeddings-by-sample.ipynb notebook in notebooks/ folder"
else: # if start new train and don't use External Embedding file
speaker_mapping = {name: i for i, name in enumerate(speakers)}
speaker_embedding_dim = None
save_speaker_mapping(OUT_PATH, speaker_mapping)
num_speakers = len(speaker_mapping)
print(" > Training with {} speakers: {}".format(len(speakers),
", ".join(speakers)))
else:
num_speakers = 0
speaker_embedding_dim = None
speaker_mapping = None
return num_speakers, speaker_embedding_dim, speaker_mapping | [
"def",
"parse_speakers",
"(",
"c",
",",
"args",
",",
"meta_data_train",
",",
"OUT_PATH",
")",
":",
"if",
"c",
".",
"use_speaker_embedding",
":",
"speakers",
"=",
"get_speakers",
"(",
"meta_data_train",
")",
"if",
"args",
".",
"restore_path",
":",
"if",
"c",
... | https://github.com/mozilla/TTS/blob/e9e07844b77a43fb0864354791fb4cf72ffded11/TTS/tts/utils/speakers.py#L34-L73 | |
pyproj4/pyproj | 24eade78c52f8bf6717e56fb7c878f7da9892368 | pyproj/crs/_cf1x8.py | python | _try_list_if_string | (input_str) | return input_str | Attempt to convert string to list if it is a string | Attempt to convert string to list if it is a string | [
"Attempt",
"to",
"convert",
"string",
"to",
"list",
"if",
"it",
"is",
"a",
"string"
] | def _try_list_if_string(input_str):
"""
Attempt to convert string to list if it is a string
"""
if not isinstance(input_str, str):
return input_str
val_split = input_str.split(",")
if len(val_split) > 1:
return [float(sval.strip()) for sval in val_split]
return input_str | [
"def",
"_try_list_if_string",
"(",
"input_str",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_str",
",",
"str",
")",
":",
"return",
"input_str",
"val_split",
"=",
"input_str",
".",
"split",
"(",
"\",\"",
")",
"if",
"len",
"(",
"val_split",
")",
">",
"... | https://github.com/pyproj4/pyproj/blob/24eade78c52f8bf6717e56fb7c878f7da9892368/pyproj/crs/_cf1x8.py#L77-L86 | |
Kotti/Kotti | 771bc397698183ecba364b7b77635d5c094bbcf5 | kotti/views/edit/actions.py | python | includeme | (config) | Pyramid includeme hook.
:param config: app config
:type config: :class:`pyramid.config.Configurator` | Pyramid includeme hook. | [
"Pyramid",
"includeme",
"hook",
"."
] | def includeme(config):
""" Pyramid includeme hook.
:param config: app config
:type config: :class:`pyramid.config.Configurator`
"""
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
config.scan(__name__) | [
"def",
"includeme",
"(",
"config",
")",
":",
"import",
"warnings",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"config",
".",
"scan",
"(",
"__name__",
")"
] | https://github.com/Kotti/Kotti/blob/771bc397698183ecba364b7b77635d5c094bbcf5/kotti/views/edit/actions.py#L593-L604 | ||
kneufeld/alkali | 0b5d423ea584ae3d627fcf37b801898364e19c71 | alkali/query.py | python | Query.field_names | (self) | return self.fields.keys() | **property**: return our model field names
:rtype: ``list`` of ``str`` | **property**: return our model field names | [
"**",
"property",
"**",
":",
"return",
"our",
"model",
"field",
"names"
] | def field_names(self):
"""
**property**: return our model field names
:rtype: ``list`` of ``str``
"""
return self.fields.keys() | [
"def",
"field_names",
"(",
"self",
")",
":",
"return",
"self",
".",
"fields",
".",
"keys",
"(",
")"
] | https://github.com/kneufeld/alkali/blob/0b5d423ea584ae3d627fcf37b801898364e19c71/alkali/query.py#L163-L169 | |
trailofbits/manticore | b050fdf0939f6c63f503cdf87ec0ab159dd41159 | manticore/wasm/types.py | python | F64.cast | (cls, other) | return cls(other) | :param other: Value to convert to F64
:return: If other is symbolic, other. Otherwise, F64(other) | :param other: Value to convert to F64
:return: If other is symbolic, other. Otherwise, F64(other) | [
":",
"param",
"other",
":",
"Value",
"to",
"convert",
"to",
"F64",
":",
"return",
":",
"If",
"other",
"is",
"symbolic",
"other",
".",
"Otherwise",
"F64",
"(",
"other",
")"
] | def cast(cls, other):
"""
:param other: Value to convert to F64
:return: If other is symbolic, other. Otherwise, F64(other)
"""
if issymbolic(other):
return other
return cls(other) | [
"def",
"cast",
"(",
"cls",
",",
"other",
")",
":",
"if",
"issymbolic",
"(",
"other",
")",
":",
"return",
"other",
"return",
"cls",
"(",
"other",
")"
] | https://github.com/trailofbits/manticore/blob/b050fdf0939f6c63f503cdf87ec0ab159dd41159/manticore/wasm/types.py#L157-L164 | |
numba/numba | bf480b9e0da858a65508c2b17759a72ee6a44c51 | numba/core/byteflow.py | python | TraceRunner.op_STORE_FAST | (self, state, inst) | [] | def op_STORE_FAST(self, state, inst):
value = state.pop()
state.append(inst, value=value) | [
"def",
"op_STORE_FAST",
"(",
"self",
",",
"state",
",",
"inst",
")",
":",
"value",
"=",
"state",
".",
"pop",
"(",
")",
"state",
".",
"append",
"(",
"inst",
",",
"value",
"=",
"value",
")"
] | https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/byteflow.py#L370-L372 | ||||
napari/napari | dbf4158e801fa7a429de8ef1cdee73bf6d64c61e | napari/components/viewer_model.py | python | ViewerModel._on_cursor_position_change | (self) | Set the layer cursor position. | Set the layer cursor position. | [
"Set",
"the",
"layer",
"cursor",
"position",
"."
] | def _on_cursor_position_change(self):
"""Set the layer cursor position."""
with warnings.catch_warnings():
# Catch the deprecation warning on layer.position
warnings.filterwarnings(
'ignore',
message=str(
trans._('layer.position is deprecated', deferred=True)
),
)
for layer in self.layers:
layer.position = self.cursor.position
# Update status and help bar based on active layer
active = self.layers.selection.active
if active is not None:
self.status = active.get_status(
self.cursor.position,
view_direction=self.cursor._view_direction,
dims_displayed=list(self.dims.displayed),
world=True,
)
self.help = active.help
if self.tooltip.visible:
self.tooltip.text = active._get_tooltip_text(
self.cursor.position,
view_direction=self.cursor._view_direction,
dims_displayed=list(self.dims.displayed),
world=True,
) | [
"def",
"_on_cursor_position_change",
"(",
"self",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"# Catch the deprecation warning on layer.position",
"warnings",
".",
"filterwarnings",
"(",
"'ignore'",
",",
"message",
"=",
"str",
"(",
"trans",
"... | https://github.com/napari/napari/blob/dbf4158e801fa7a429de8ef1cdee73bf6d64c61e/napari/components/viewer_model.py#L370-L399 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/wagtail/wagtailadmin/edit_handlers.py | python | EditHandler.render_as_field | (self) | return self.render() | Render this object as it should appear within a <ul class="fields"> list item | Render this object as it should appear within a <ul class="fields"> list item | [
"Render",
"this",
"object",
"as",
"it",
"should",
"appear",
"within",
"a",
"<ul",
"class",
"=",
"fields",
">",
"list",
"item"
] | def render_as_field(self):
"""
Render this object as it should appear within a <ul class="fields"> list item
"""
# by default, assume that the subclass provides a catch-all render() method
return self.render() | [
"def",
"render_as_field",
"(",
"self",
")",
":",
"# by default, assume that the subclass provides a catch-all render() method",
"return",
"self",
".",
"render",
"(",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail/wagtailadmin/edit_handlers.py#L174-L179 | |
digidotcom/xbee-python | 0757f4be0017530c205175fbee8f9f61be9614d1 | digi/xbee/packets/socket.py | python | SocketClosePacket.needs_id | (self) | return True | Override method.
.. seealso::
| :meth:`.XBeeAPIPacket.needs_id` | Override method. | [
"Override",
"method",
"."
] | def needs_id(self):
"""
Override method.
.. seealso::
| :meth:`.XBeeAPIPacket.needs_id`
"""
return True | [
"def",
"needs_id",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/digidotcom/xbee-python/blob/0757f4be0017530c205175fbee8f9f61be9614d1/digi/xbee/packets/socket.py#L1299-L1306 | |
jimmysong/programmingbitcoin | 3fba6b992ece443e4256df057595cfbe91edda75 | code-ch09/ecc.py | python | S256Point.sec | (self, compressed=True) | returns the binary version of the SEC format | returns the binary version of the SEC format | [
"returns",
"the",
"binary",
"version",
"of",
"the",
"SEC",
"format"
] | def sec(self, compressed=True):
'''returns the binary version of the SEC format'''
# if compressed, starts with b'\x02' if self.y.num is even, b'\x03' if self.y is odd
# then self.x.num
# remember, you have to convert self.x.num/self.y.num to binary (some_integer.to_bytes(32, 'big'))
if compressed:
if self.y.num % 2 == 0:
return b'\x02' + self.x.num.to_bytes(32, 'big')
else:
return b'\x03' + self.x.num.to_bytes(32, 'big')
else:
# if non-compressed, starts with b'\x04' followod by self.x and then self.y
return b'\x04' + self.x.num.to_bytes(32, 'big') + \
self.y.num.to_bytes(32, 'big') | [
"def",
"sec",
"(",
"self",
",",
"compressed",
"=",
"True",
")",
":",
"# if compressed, starts with b'\\x02' if self.y.num is even, b'\\x03' if self.y is odd",
"# then self.x.num",
"# remember, you have to convert self.x.num/self.y.num to binary (some_integer.to_bytes(32, 'big'))",
"if",
... | https://github.com/jimmysong/programmingbitcoin/blob/3fba6b992ece443e4256df057595cfbe91edda75/code-ch09/ecc.py#L405-L418 | ||
scipy/scipy | e0a749f01e79046642ccfdc419edbf9e7ca141ad | benchmarks/benchmarks/optimize.py | python | _BenchOptimizers.accept_test | (self, x_new=None, *args, **kwargs) | return True | Does the new candidate vector lie in between the bounds?
Returns
-------
accept_test : bool
The candidate vector lies in between the bounds | Does the new candidate vector lie in between the bounds? | [
"Does",
"the",
"new",
"candidate",
"vector",
"lie",
"in",
"between",
"the",
"bounds?"
] | def accept_test(self, x_new=None, *args, **kwargs):
"""
Does the new candidate vector lie in between the bounds?
Returns
-------
accept_test : bool
The candidate vector lies in between the bounds
"""
if not hasattr(self.function, "xmin"):
return True
if np.any(x_new < self.function.xmin):
return False
if np.any(x_new > self.function.xmax):
return False
return True | [
"def",
"accept_test",
"(",
"self",
",",
"x_new",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"function",
",",
"\"xmin\"",
")",
":",
"return",
"True",
"if",
"np",
".",
"any",
"(",
"x_... | https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/benchmarks/benchmarks/optimize.py#L123-L138 | |
git-cola/git-cola | b48b8028e0c3baf47faf7b074b9773737358163d | qtpy/compat.py | python | getexistingdirectory | (parent=None, caption='', basedir='',
options=QFileDialog.ShowDirsOnly) | return result | Wrapper around QtGui.QFileDialog.getExistingDirectory static method
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0 | Wrapper around QtGui.QFileDialog.getExistingDirectory static method
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0 | [
"Wrapper",
"around",
"QtGui",
".",
"QFileDialog",
".",
"getExistingDirectory",
"static",
"method",
"Compatible",
"with",
"PyQt",
">",
"=",
"v4",
".",
"4",
"(",
"API",
"#1",
"and",
"#2",
")",
"and",
"PySide",
">",
"=",
"v1",
".",
"0"
] | def getexistingdirectory(parent=None, caption='', basedir='',
options=QFileDialog.ShowDirsOnly):
"""Wrapper around QtGui.QFileDialog.getExistingDirectory static method
Compatible with PyQt >=v4.4 (API #1 and #2) and PySide >=v1.0"""
# Calling QFileDialog static method
if sys.platform == "win32":
# On Windows platforms: redirect standard outputs
_temp1, _temp2 = sys.stdout, sys.stderr
sys.stdout, sys.stderr = None, None
try:
result = QFileDialog.getExistingDirectory(parent, caption, basedir,
options)
finally:
if sys.platform == "win32":
# On Windows platforms: restore standard outputs
sys.stdout, sys.stderr = _temp1, _temp2
if not is_text_string(result):
# PyQt API #1
result = to_text_string(result)
return result | [
"def",
"getexistingdirectory",
"(",
"parent",
"=",
"None",
",",
"caption",
"=",
"''",
",",
"basedir",
"=",
"''",
",",
"options",
"=",
"QFileDialog",
".",
"ShowDirsOnly",
")",
":",
"# Calling QFileDialog static method",
"if",
"sys",
".",
"platform",
"==",
"\"wi... | https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/qtpy/compat.py#L79-L98 | |
fatiando/fatiando | ac2afbcb2d99b18f145cc1ed40075beb5f92dd5a | fatiando/seismic/ttime2d.py | python | _crosses | (x, y, x1, x2, y1, y2, maxx, minx, maxy, miny) | return incell and inray | Check if (x, y) is inside both the cell and the rectangle with the ray path
as a diagonal. | Check if (x, y) is inside both the cell and the rectangle with the ray path
as a diagonal. | [
"Check",
"if",
"(",
"x",
"y",
")",
"is",
"inside",
"both",
"the",
"cell",
"and",
"the",
"rectangle",
"with",
"the",
"ray",
"path",
"as",
"a",
"diagonal",
"."
] | def _crosses(x, y, x1, x2, y1, y2, maxx, minx, maxy, miny):
"""
Check if (x, y) is inside both the cell and the rectangle with the ray path
as a diagonal.
"""
incell = x <= x2 and x >= x1 and y <= y2 and y >= y1
inray = x <= maxx and x >= minx and y <= maxy and y >= miny
return incell and inray | [
"def",
"_crosses",
"(",
"x",
",",
"y",
",",
"x1",
",",
"x2",
",",
"y1",
",",
"y2",
",",
"maxx",
",",
"minx",
",",
"maxy",
",",
"miny",
")",
":",
"incell",
"=",
"x",
"<=",
"x2",
"and",
"x",
">=",
"x1",
"and",
"y",
"<=",
"y2",
"and",
"y",
"... | https://github.com/fatiando/fatiando/blob/ac2afbcb2d99b18f145cc1ed40075beb5f92dd5a/fatiando/seismic/ttime2d.py#L188-L195 | |
panpanpandas/ultrafinance | ce3594dbfef747cba0c39f059316df7c208aac40 | deprecated/ultrafinance/processChain/configuration.py | python | Configuration.getConfiguration | (self, section) | load all configuration | load all configuration | [
"load",
"all",
"configuration"
] | def getConfiguration(self, section):
''' load all configuration '''
configs = {}
parser = ConfigParser.SafeConfigParser()
parser.read(self.configFilePath)
if parser.has_section(section):
for name, value in parser.items(section):
configs[name] = value
return configs
else:
return None | [
"def",
"getConfiguration",
"(",
"self",
",",
"section",
")",
":",
"configs",
"=",
"{",
"}",
"parser",
"=",
"ConfigParser",
".",
"SafeConfigParser",
"(",
")",
"parser",
".",
"read",
"(",
"self",
".",
"configFilePath",
")",
"if",
"parser",
".",
"has_section"... | https://github.com/panpanpandas/ultrafinance/blob/ce3594dbfef747cba0c39f059316df7c208aac40/deprecated/ultrafinance/processChain/configuration.py#L23-L33 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/getopt.py | python | GetoptError.__init__ | (self, msg, opt='') | [] | def __init__(self, msg, opt=''):
self.msg = msg
self.opt = opt
Exception.__init__(self, msg, opt) | [
"def",
"__init__",
"(",
"self",
",",
"msg",
",",
"opt",
"=",
"''",
")",
":",
"self",
".",
"msg",
"=",
"msg",
"self",
".",
"opt",
"=",
"opt",
"Exception",
".",
"__init__",
"(",
"self",
",",
"msg",
",",
"opt",
")"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/getopt.py#L41-L44 | ||||
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/optimize/zeros.py | python | TOMS748Solver.solve | (self, f, a, b, args=(),
xtol=_xtol, rtol=_rtol, k=2, maxiter=_iter, disp=True) | r"""Solve f(x) = 0 given an interval containing a zero. | r"""Solve f(x) = 0 given an interval containing a zero. | [
"r",
"Solve",
"f",
"(",
"x",
")",
"=",
"0",
"given",
"an",
"interval",
"containing",
"a",
"zero",
"."
] | def solve(self, f, a, b, args=(),
xtol=_xtol, rtol=_rtol, k=2, maxiter=_iter, disp=True):
r"""Solve f(x) = 0 given an interval containing a zero."""
self.configure(xtol=xtol, rtol=rtol, maxiter=maxiter, disp=disp, k=k)
status, xn = self.start(f, a, b, args)
if status == _ECONVERGED:
return self.get_result(xn)
# The first step only has two x-values.
c = _secant(self.ab, self.fab)
if not self.ab[0] < c < self.ab[1]:
c = sum(self.ab) / 2.0
fc = self._callf(c)
if fc == 0:
return self.get_result(c)
self.d, self.fd = self._update_bracket(c, fc)
self.e, self.fe = None, None
self.iterations += 1
while True:
status, xn = self.iterate()
if status == _ECONVERGED:
return self.get_result(xn)
if status == _ECONVERR:
fmt = "Failed to converge after %d iterations, bracket is %s"
if disp:
msg = fmt % (self.iterations + 1, self.ab)
raise RuntimeError(msg)
return self.get_result(xn, _ECONVERR) | [
"def",
"solve",
"(",
"self",
",",
"f",
",",
"a",
",",
"b",
",",
"args",
"=",
"(",
")",
",",
"xtol",
"=",
"_xtol",
",",
"rtol",
"=",
"_rtol",
",",
"k",
"=",
"2",
",",
"maxiter",
"=",
"_iter",
",",
"disp",
"=",
"True",
")",
":",
"self",
".",
... | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/optimize/zeros.py#L1209-L1238 | ||
Georce/lepus | 5b01bae82b5dc1df00c9e058989e2eb9b89ff333 | lepus/pymongo-2.7/pymongo/pool.py | python | Pool.__init__ | (self, pair, max_size, net_timeout, conn_timeout, use_ssl,
use_greenlets, ssl_keyfile=None, ssl_certfile=None,
ssl_cert_reqs=None, ssl_ca_certs=None,
wait_queue_timeout=None, wait_queue_multiple=None) | :Parameters:
- `pair`: a (hostname, port) tuple
- `max_size`: The maximum number of open sockets. Calls to
`get_socket` will block if this is set, this pool has opened
`max_size` sockets, and there are none idle. Set to `None` to
disable.
- `net_timeout`: timeout in seconds for operations on open connection
- `conn_timeout`: timeout in seconds for establishing connection
- `use_ssl`: bool, if True use an encrypted connection
- `use_greenlets`: bool, if True then start_request() assigns a
socket to the current greenlet - otherwise it is assigned to the
current thread
- `ssl_keyfile`: The private keyfile used to identify the local
connection against mongod. If included with the ``certfile` then
only the ``ssl_certfile`` is needed. Implies ``ssl=True``.
- `ssl_certfile`: The certificate file used to identify the local
connection against mongod. Implies ``ssl=True``.
- `ssl_cert_reqs`: Specifies whether a certificate is required from
the other side of the connection, and whether it will be validated
if provided. It must be one of the three values ``ssl.CERT_NONE``
(certificates ignored), ``ssl.CERT_OPTIONAL``
(not required, but validated if provided), or ``ssl.CERT_REQUIRED``
(required and validated). If the value of this parameter is not
``ssl.CERT_NONE``, then the ``ssl_ca_certs`` parameter must point
to a file of CA certificates. Implies ``ssl=True``.
- `ssl_ca_certs`: The ca_certs file contains a set of concatenated
"certification authority" certificates, which are used to validate
certificates passed from the other end of the connection.
Implies ``ssl=True``.
- `wait_queue_timeout`: (integer) How long (in seconds) a
thread will wait for a socket from the pool if the pool has no
free sockets.
- `wait_queue_multiple`: (integer) Multiplied by max_pool_size to give
the number of threads allowed to wait for a socket at one time. | :Parameters:
- `pair`: a (hostname, port) tuple
- `max_size`: The maximum number of open sockets. Calls to
`get_socket` will block if this is set, this pool has opened
`max_size` sockets, and there are none idle. Set to `None` to
disable.
- `net_timeout`: timeout in seconds for operations on open connection
- `conn_timeout`: timeout in seconds for establishing connection
- `use_ssl`: bool, if True use an encrypted connection
- `use_greenlets`: bool, if True then start_request() assigns a
socket to the current greenlet - otherwise it is assigned to the
current thread
- `ssl_keyfile`: The private keyfile used to identify the local
connection against mongod. If included with the ``certfile` then
only the ``ssl_certfile`` is needed. Implies ``ssl=True``.
- `ssl_certfile`: The certificate file used to identify the local
connection against mongod. Implies ``ssl=True``.
- `ssl_cert_reqs`: Specifies whether a certificate is required from
the other side of the connection, and whether it will be validated
if provided. It must be one of the three values ``ssl.CERT_NONE``
(certificates ignored), ``ssl.CERT_OPTIONAL``
(not required, but validated if provided), or ``ssl.CERT_REQUIRED``
(required and validated). If the value of this parameter is not
``ssl.CERT_NONE``, then the ``ssl_ca_certs`` parameter must point
to a file of CA certificates. Implies ``ssl=True``.
- `ssl_ca_certs`: The ca_certs file contains a set of concatenated
"certification authority" certificates, which are used to validate
certificates passed from the other end of the connection.
Implies ``ssl=True``.
- `wait_queue_timeout`: (integer) How long (in seconds) a
thread will wait for a socket from the pool if the pool has no
free sockets.
- `wait_queue_multiple`: (integer) Multiplied by max_pool_size to give
the number of threads allowed to wait for a socket at one time. | [
":",
"Parameters",
":",
"-",
"pair",
":",
"a",
"(",
"hostname",
"port",
")",
"tuple",
"-",
"max_size",
":",
"The",
"maximum",
"number",
"of",
"open",
"sockets",
".",
"Calls",
"to",
"get_socket",
"will",
"block",
"if",
"this",
"is",
"set",
"this",
"pool... | def __init__(self, pair, max_size, net_timeout, conn_timeout, use_ssl,
use_greenlets, ssl_keyfile=None, ssl_certfile=None,
ssl_cert_reqs=None, ssl_ca_certs=None,
wait_queue_timeout=None, wait_queue_multiple=None):
"""
:Parameters:
- `pair`: a (hostname, port) tuple
- `max_size`: The maximum number of open sockets. Calls to
`get_socket` will block if this is set, this pool has opened
`max_size` sockets, and there are none idle. Set to `None` to
disable.
- `net_timeout`: timeout in seconds for operations on open connection
- `conn_timeout`: timeout in seconds for establishing connection
- `use_ssl`: bool, if True use an encrypted connection
- `use_greenlets`: bool, if True then start_request() assigns a
socket to the current greenlet - otherwise it is assigned to the
current thread
- `ssl_keyfile`: The private keyfile used to identify the local
connection against mongod. If included with the ``certfile` then
only the ``ssl_certfile`` is needed. Implies ``ssl=True``.
- `ssl_certfile`: The certificate file used to identify the local
connection against mongod. Implies ``ssl=True``.
- `ssl_cert_reqs`: Specifies whether a certificate is required from
the other side of the connection, and whether it will be validated
if provided. It must be one of the three values ``ssl.CERT_NONE``
(certificates ignored), ``ssl.CERT_OPTIONAL``
(not required, but validated if provided), or ``ssl.CERT_REQUIRED``
(required and validated). If the value of this parameter is not
``ssl.CERT_NONE``, then the ``ssl_ca_certs`` parameter must point
to a file of CA certificates. Implies ``ssl=True``.
- `ssl_ca_certs`: The ca_certs file contains a set of concatenated
"certification authority" certificates, which are used to validate
certificates passed from the other end of the connection.
Implies ``ssl=True``.
- `wait_queue_timeout`: (integer) How long (in seconds) a
thread will wait for a socket from the pool if the pool has no
free sockets.
- `wait_queue_multiple`: (integer) Multiplied by max_pool_size to give
the number of threads allowed to wait for a socket at one time.
"""
# Only check a socket's health with _closed() every once in a while.
# Can override for testing: 0 to always check, None to never check.
self._check_interval_seconds = 1
self.sockets = set()
self.lock = threading.Lock()
# Keep track of resets, so we notice sockets created before the most
# recent reset and close them.
self.pool_id = 0
self.pid = os.getpid()
self.pair = pair
self.max_size = max_size
self.net_timeout = net_timeout
self.conn_timeout = conn_timeout
self.wait_queue_timeout = wait_queue_timeout
self.wait_queue_multiple = wait_queue_multiple
self.use_ssl = use_ssl
self.ssl_keyfile = ssl_keyfile
self.ssl_certfile = ssl_certfile
self.ssl_cert_reqs = ssl_cert_reqs
self.ssl_ca_certs = ssl_ca_certs
if HAS_SSL and use_ssl and not ssl_cert_reqs:
self.ssl_cert_reqs = ssl.CERT_NONE
# Map self._ident.get() -> request socket
self._tid_to_sock = {}
if use_greenlets and not thread_util.have_gevent:
raise ConfigurationError(
"The Gevent module is not available. "
"Install the gevent package from PyPI."
)
self._ident = thread_util.create_ident(use_greenlets)
# Count the number of calls to start_request() per thread or greenlet
self._request_counter = thread_util.Counter(use_greenlets)
if self.wait_queue_multiple is None or self.max_size is None:
max_waiters = None
else:
max_waiters = self.max_size * self.wait_queue_multiple
self._socket_semaphore = thread_util.create_semaphore(
self.max_size, max_waiters, use_greenlets) | [
"def",
"__init__",
"(",
"self",
",",
"pair",
",",
"max_size",
",",
"net_timeout",
",",
"conn_timeout",
",",
"use_ssl",
",",
"use_greenlets",
",",
"ssl_keyfile",
"=",
"None",
",",
"ssl_certfile",
"=",
"None",
",",
"ssl_cert_reqs",
"=",
"None",
",",
"ssl_ca_ce... | https://github.com/Georce/lepus/blob/5b01bae82b5dc1df00c9e058989e2eb9b89ff333/lepus/pymongo-2.7/pymongo/pool.py#L100-L186 | ||
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/matrices/inverse.py | python | _pinv | (M, method='RD') | Calculate the Moore-Penrose pseudoinverse of the matrix.
The Moore-Penrose pseudoinverse exists and is unique for any matrix.
If the matrix is invertible, the pseudoinverse is the same as the
inverse.
Parameters
==========
method : String, optional
Specifies the method for computing the pseudoinverse.
If ``'RD'``, Rank-Decomposition will be used.
If ``'ED'``, Diagonalization will be used.
Examples
========
Computing pseudoinverse by rank decomposition :
>>> from sympy import Matrix
>>> A = Matrix([[1, 2, 3], [4, 5, 6]])
>>> A.pinv()
Matrix([
[-17/18, 4/9],
[ -1/9, 1/9],
[ 13/18, -2/9]])
Computing pseudoinverse by diagonalization :
>>> B = A.pinv(method='ED')
>>> B.simplify()
>>> B
Matrix([
[-17/18, 4/9],
[ -1/9, 1/9],
[ 13/18, -2/9]])
See Also
========
inv
pinv_solve
References
==========
.. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse | Calculate the Moore-Penrose pseudoinverse of the matrix. | [
"Calculate",
"the",
"Moore",
"-",
"Penrose",
"pseudoinverse",
"of",
"the",
"matrix",
"."
] | def _pinv(M, method='RD'):
"""Calculate the Moore-Penrose pseudoinverse of the matrix.
The Moore-Penrose pseudoinverse exists and is unique for any matrix.
If the matrix is invertible, the pseudoinverse is the same as the
inverse.
Parameters
==========
method : String, optional
Specifies the method for computing the pseudoinverse.
If ``'RD'``, Rank-Decomposition will be used.
If ``'ED'``, Diagonalization will be used.
Examples
========
Computing pseudoinverse by rank decomposition :
>>> from sympy import Matrix
>>> A = Matrix([[1, 2, 3], [4, 5, 6]])
>>> A.pinv()
Matrix([
[-17/18, 4/9],
[ -1/9, 1/9],
[ 13/18, -2/9]])
Computing pseudoinverse by diagonalization :
>>> B = A.pinv(method='ED')
>>> B.simplify()
>>> B
Matrix([
[-17/18, 4/9],
[ -1/9, 1/9],
[ 13/18, -2/9]])
See Also
========
inv
pinv_solve
References
==========
.. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse
"""
# Trivial case: pseudoinverse of all-zero matrix is its transpose.
if M.is_zero_matrix:
return M.H
if method == 'RD':
return _pinv_rank_decomposition(M)
elif method == 'ED':
return _pinv_diagonalization(M)
else:
raise ValueError('invalid pinv method %s' % repr(method)) | [
"def",
"_pinv",
"(",
"M",
",",
"method",
"=",
"'RD'",
")",
":",
"# Trivial case: pseudoinverse of all-zero matrix is its transpose.",
"if",
"M",
".",
"is_zero_matrix",
":",
"return",
"M",
".",
"H",
"if",
"method",
"==",
"'RD'",
":",
"return",
"_pinv_rank_decomposi... | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/matrices/inverse.py#L75-L137 | ||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | external/Scripting Engine/Xenotix Python Scripting Engine/Lib/Queue.py | python | Queue.join | (self) | Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks. | Blocks until all items in the Queue have been gotten and processed. | [
"Blocks",
"until",
"all",
"items",
"in",
"the",
"Queue",
"have",
"been",
"gotten",
"and",
"processed",
"."
] | def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release() | [
"def",
"join",
"(",
"self",
")",
":",
"self",
".",
"all_tasks_done",
".",
"acquire",
"(",
")",
"try",
":",
"while",
"self",
".",
"unfinished_tasks",
":",
"self",
".",
"all_tasks_done",
".",
"wait",
"(",
")",
"finally",
":",
"self",
".",
"all_tasks_done",... | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/Queue.py#L70-L84 | ||
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/ceilometer/ceilometer/openstack/common/policy.py | python | TrueCheck.__str__ | (self) | return "@" | Return a string representation of this check. | Return a string representation of this check. | [
"Return",
"a",
"string",
"representation",
"of",
"this",
"check",
"."
] | def __str__(self):
"""Return a string representation of this check."""
return "@" | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"\"@\""
] | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/ceilometer/ceilometer/openstack/common/policy.py#L315-L318 | |
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v8/services/services/ad_group_asset_service/client.py | python | AdGroupAssetServiceClient.common_project_path | (project: str,) | return "projects/{project}".format(project=project,) | Return a fully-qualified project string. | Return a fully-qualified project string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"project",
"string",
"."
] | def common_project_path(project: str,) -> str:
"""Return a fully-qualified project string."""
return "projects/{project}".format(project=project,) | [
"def",
"common_project_path",
"(",
"project",
":",
"str",
",",
")",
"->",
"str",
":",
"return",
"\"projects/{project}\"",
".",
"format",
"(",
"project",
"=",
"project",
",",
")"
] | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/ad_group_asset_service/client.py#L247-L249 | |
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/genericpath.py | python | getsize | (filename) | return os.stat(filename).st_size | Return the size of a file, reported by os.stat(). | Return the size of a file, reported by os.stat(). | [
"Return",
"the",
"size",
"of",
"a",
"file",
"reported",
"by",
"os",
".",
"stat",
"()",
"."
] | def getsize(filename):
"""Return the size of a file, reported by os.stat()."""
return os.stat(filename).st_size | [
"def",
"getsize",
"(",
"filename",
")",
":",
"return",
"os",
".",
"stat",
"(",
"filename",
")",
".",
"st_size"
] | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/genericpath.py#L47-L49 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.