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
sequence | function
stringlengths 18
4.83M
| function_tokens
sequence | url
stringlengths 83
304
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wallix/PEPS | b7a95f8108967ebbc5f87d70f051e9233dfc6def | scripts/python/webmail.py | python | WebmailApi.tag_delete | (self, id) | return self._extract(result, 'tag.delete') | [] | def tag_delete(self, id):
result = self.session.delete('{}/users/me/tags/{}'.format(self._base_url, id), verify=verify)
return self._extract(result, 'tag.delete') | [
"def",
"tag_delete",
"(",
"self",
",",
"id",
")",
":",
"result",
"=",
"self",
".",
"session",
".",
"delete",
"(",
"'{}/users/me/tags/{}'",
".",
"format",
"(",
"self",
".",
"_base_url",
",",
"id",
")",
",",
"verify",
"=",
"verify",
")",
"return",
"self",
".",
"_extract",
"(",
"result",
",",
"'tag.delete'",
")"
] | https://github.com/wallix/PEPS/blob/b7a95f8108967ebbc5f87d70f051e9233dfc6def/scripts/python/webmail.py#L198-L200 |
|||
wistbean/learn_python3_spider | 73c873f4845f4385f097e5057407d03dd37a117b | stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/interfaces.py | python | IProducer.stopProducing | () | Stop producing data.
This tells a producer that its consumer has died, so it must stop
producing data for good. | Stop producing data. | [
"Stop",
"producing",
"data",
"."
] | def stopProducing():
"""
Stop producing data.
This tells a producer that its consumer has died, so it must stop
producing data for good.
""" | [
"def",
"stopProducing",
"(",
")",
":"
] | https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/interfaces.py#L1900-L1906 |
||
HymanLiuTS/flaskTs | 286648286976e85d9b9a5873632331efcafe0b21 | flasky/lib/python2.7/site-packages/markdown/blockparser.py | python | BlockParser.parseChunk | (self, parent, text) | Parse a chunk of markdown text and attach to given etree node.
While the ``text`` argument is generally assumed to contain multiple
blocks which will be split on blank lines, it could contain only one
block. Generally, this method would be called by extensions when
block parsing is required.
The ``parent`` etree Element passed in is altered in place.
Nothing is returned. | Parse a chunk of markdown text and attach to given etree node. | [
"Parse",
"a",
"chunk",
"of",
"markdown",
"text",
"and",
"attach",
"to",
"given",
"etree",
"node",
"."
] | def parseChunk(self, parent, text):
""" Parse a chunk of markdown text and attach to given etree node.
While the ``text`` argument is generally assumed to contain multiple
blocks which will be split on blank lines, it could contain only one
block. Generally, this method would be called by extensions when
block parsing is required.
The ``parent`` etree Element passed in is altered in place.
Nothing is returned.
"""
self.parseBlocks(parent, text.split('\n\n')) | [
"def",
"parseChunk",
"(",
"self",
",",
"parent",
",",
"text",
")",
":",
"self",
".",
"parseBlocks",
"(",
"parent",
",",
"text",
".",
"split",
"(",
"'\\n\\n'",
")",
")"
] | https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/markdown/blockparser.py#L68-L80 |
||
rbaron/omr | 3d4b7dd53b272b195e872663673fb6098976dcd7 | omr.py | python | perspective_transform | (img, points) | return warped | Applies a 4-point perspective transformation in `img` so that `points`
are the new corners. | Applies a 4-point perspective transformation in `img` so that `points`
are the new corners. | [
"Applies",
"a",
"4",
"-",
"point",
"perspective",
"transformation",
"in",
"img",
"so",
"that",
"points",
"are",
"the",
"new",
"corners",
"."
] | def perspective_transform(img, points):
"""Applies a 4-point perspective transformation in `img` so that `points`
are the new corners."""
source = np.array(
points,
dtype="float32")
dest = np.array([
[TRANSF_SIZE, TRANSF_SIZE],
[0, TRANSF_SIZE],
[0, 0],
[TRANSF_SIZE, 0]],
dtype="float32")
transf = cv2.getPerspectiveTransform(source, dest)
warped = cv2.warpPerspective(img, transf, (TRANSF_SIZE, TRANSF_SIZE))
return warped | [
"def",
"perspective_transform",
"(",
"img",
",",
"points",
")",
":",
"source",
"=",
"np",
".",
"array",
"(",
"points",
",",
"dtype",
"=",
"\"float32\"",
")",
"dest",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"TRANSF_SIZE",
",",
"TRANSF_SIZE",
"]",
",",
"[",
"0",
",",
"TRANSF_SIZE",
"]",
",",
"[",
"0",
",",
"0",
"]",
",",
"[",
"TRANSF_SIZE",
",",
"0",
"]",
"]",
",",
"dtype",
"=",
"\"float32\"",
")",
"transf",
"=",
"cv2",
".",
"getPerspectiveTransform",
"(",
"source",
",",
"dest",
")",
"warped",
"=",
"cv2",
".",
"warpPerspective",
"(",
"img",
",",
"transf",
",",
"(",
"TRANSF_SIZE",
",",
"TRANSF_SIZE",
")",
")",
"return",
"warped"
] | https://github.com/rbaron/omr/blob/3d4b7dd53b272b195e872663673fb6098976dcd7/omr.py#L176-L192 |
|
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/packages/site-packages/sqlalchemy/orm/persistence.py | python | _finalize_insert_update_commands | (base_mapper, uowtransaction, states) | finalize state on states that have been inserted or updated,
including calling after_insert/after_update events. | finalize state on states that have been inserted or updated,
including calling after_insert/after_update events. | [
"finalize",
"state",
"on",
"states",
"that",
"have",
"been",
"inserted",
"or",
"updated",
"including",
"calling",
"after_insert",
"/",
"after_update",
"events",
"."
] | def _finalize_insert_update_commands(base_mapper, uowtransaction, states):
"""finalize state on states that have been inserted or updated,
including calling after_insert/after_update events.
"""
for state, state_dict, mapper, connection, has_identity in states:
if mapper._readonly_props:
readonly = state.unmodified_intersection(
[p.key for p in mapper._readonly_props
if p.expire_on_flush or p.key not in state.dict]
)
if readonly:
state._expire_attributes(state.dict, readonly)
# if eager_defaults option is enabled, load
# all expired cols. Else if we have a version_id_col, make sure
# it isn't expired.
toload_now = []
if base_mapper.eager_defaults:
toload_now.extend(state._unloaded_non_object)
elif mapper.version_id_col is not None and \
mapper.version_id_generator is False:
if mapper._version_id_prop.key in state.unloaded:
toload_now.extend([mapper._version_id_prop.key])
if toload_now:
state.key = base_mapper._identity_key_from_state(state)
loading.load_on_ident(
uowtransaction.session.query(base_mapper),
state.key, refresh_state=state,
only_load_props=toload_now)
# call after_XXX extensions
if not has_identity:
mapper.dispatch.after_insert(mapper, connection, state)
else:
mapper.dispatch.after_update(mapper, connection, state) | [
"def",
"_finalize_insert_update_commands",
"(",
"base_mapper",
",",
"uowtransaction",
",",
"states",
")",
":",
"for",
"state",
",",
"state_dict",
",",
"mapper",
",",
"connection",
",",
"has_identity",
"in",
"states",
":",
"if",
"mapper",
".",
"_readonly_props",
":",
"readonly",
"=",
"state",
".",
"unmodified_intersection",
"(",
"[",
"p",
".",
"key",
"for",
"p",
"in",
"mapper",
".",
"_readonly_props",
"if",
"p",
".",
"expire_on_flush",
"or",
"p",
".",
"key",
"not",
"in",
"state",
".",
"dict",
"]",
")",
"if",
"readonly",
":",
"state",
".",
"_expire_attributes",
"(",
"state",
".",
"dict",
",",
"readonly",
")",
"# if eager_defaults option is enabled, load",
"# all expired cols. Else if we have a version_id_col, make sure",
"# it isn't expired.",
"toload_now",
"=",
"[",
"]",
"if",
"base_mapper",
".",
"eager_defaults",
":",
"toload_now",
".",
"extend",
"(",
"state",
".",
"_unloaded_non_object",
")",
"elif",
"mapper",
".",
"version_id_col",
"is",
"not",
"None",
"and",
"mapper",
".",
"version_id_generator",
"is",
"False",
":",
"if",
"mapper",
".",
"_version_id_prop",
".",
"key",
"in",
"state",
".",
"unloaded",
":",
"toload_now",
".",
"extend",
"(",
"[",
"mapper",
".",
"_version_id_prop",
".",
"key",
"]",
")",
"if",
"toload_now",
":",
"state",
".",
"key",
"=",
"base_mapper",
".",
"_identity_key_from_state",
"(",
"state",
")",
"loading",
".",
"load_on_ident",
"(",
"uowtransaction",
".",
"session",
".",
"query",
"(",
"base_mapper",
")",
",",
"state",
".",
"key",
",",
"refresh_state",
"=",
"state",
",",
"only_load_props",
"=",
"toload_now",
")",
"# call after_XXX extensions",
"if",
"not",
"has_identity",
":",
"mapper",
".",
"dispatch",
".",
"after_insert",
"(",
"mapper",
",",
"connection",
",",
"state",
")",
"else",
":",
"mapper",
".",
"dispatch",
".",
"after_update",
"(",
"mapper",
",",
"connection",
",",
"state",
")"
] | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/sqlalchemy/orm/persistence.py#L937-L975 |
||
LGE-ARC-AdvancedAI/auptimizer | 50f6e3b4e0cb9146ca90fd74b9b24ca97ae22617 | Examples/cai_eas/eas/data_providers/cifar.py | python | CifarDataProvider.__init__ | (self, save_path=None, validation_size=None, shuffle=None, normalization=None,
one_hot=True, **kwargs) | Args:
save_path: `str`
validation_set: `bool`.
validation_split: `float` or None
float: chunk of `train set` will be marked as `validation set`.
None: if 'validation set' == True, `validation set` will be
copy of `test set`
shuffle: `str` or None
None: no any shuffling
once_prior_train: shuffle train data only once prior train
every_epoch: shuffle train data prior every epoch
normalization: `str` or None
None: no any normalization
divide_255: divide all pixels by 255
divide_256: divide all pixels by 256
by_channels: substract mean of every chanel and divide each
chanel data by it's standard deviation
one_hot: `bool`, return laels one hot encoded | Args:
save_path: `str`
validation_set: `bool`.
validation_split: `float` or None
float: chunk of `train set` will be marked as `validation set`.
None: if 'validation set' == True, `validation set` will be
copy of `test set`
shuffle: `str` or None
None: no any shuffling
once_prior_train: shuffle train data only once prior train
every_epoch: shuffle train data prior every epoch
normalization: `str` or None
None: no any normalization
divide_255: divide all pixels by 255
divide_256: divide all pixels by 256
by_channels: substract mean of every chanel and divide each
chanel data by it's standard deviation
one_hot: `bool`, return laels one hot encoded | [
"Args",
":",
"save_path",
":",
"str",
"validation_set",
":",
"bool",
".",
"validation_split",
":",
"float",
"or",
"None",
"float",
":",
"chunk",
"of",
"train",
"set",
"will",
"be",
"marked",
"as",
"validation",
"set",
".",
"None",
":",
"if",
"validation",
"set",
"==",
"True",
"validation",
"set",
"will",
"be",
"copy",
"of",
"test",
"set",
"shuffle",
":",
"str",
"or",
"None",
"None",
":",
"no",
"any",
"shuffling",
"once_prior_train",
":",
"shuffle",
"train",
"data",
"only",
"once",
"prior",
"train",
"every_epoch",
":",
"shuffle",
"train",
"data",
"prior",
"every",
"epoch",
"normalization",
":",
"str",
"or",
"None",
"None",
":",
"no",
"any",
"normalization",
"divide_255",
":",
"divide",
"all",
"pixels",
"by",
"255",
"divide_256",
":",
"divide",
"all",
"pixels",
"by",
"256",
"by_channels",
":",
"substract",
"mean",
"of",
"every",
"chanel",
"and",
"divide",
"each",
"chanel",
"data",
"by",
"it",
"s",
"standard",
"deviation",
"one_hot",
":",
"bool",
"return",
"laels",
"one",
"hot",
"encoded"
] | def __init__(self, save_path=None, validation_size=None, shuffle=None, normalization=None,
one_hot=True, **kwargs):
"""
Args:
save_path: `str`
validation_set: `bool`.
validation_split: `float` or None
float: chunk of `train set` will be marked as `validation set`.
None: if 'validation set' == True, `validation set` will be
copy of `test set`
shuffle: `str` or None
None: no any shuffling
once_prior_train: shuffle train data only once prior train
every_epoch: shuffle train data prior every epoch
normalization: `str` or None
None: no any normalization
divide_255: divide all pixels by 255
divide_256: divide all pixels by 256
by_channels: substract mean of every chanel and divide each
chanel data by it's standard deviation
one_hot: `bool`, return laels one hot encoded
"""
self._save_path = save_path
self.one_hot = one_hot
download_data_url(self.data_url, self.save_path)
train_fnames, test_fnames = self.get_filenames(self.save_path)
# add train and validations datasets
images, labels = self.read_cifar(train_fnames)
train_meanstd = ImagesDataSet.measure_mean_and_std(images)
if validation_size is not None:
np.random.seed(DataProvider._SEED)
rand_indexes = np.random.permutation(images.shape[0])
valid_indexes = rand_indexes[:validation_size]
train_indexes = rand_indexes[validation_size:]
self.train = CifarDataSet(
images=images[train_indexes], labels=labels[train_indexes],
n_classes=self.n_classes, shuffle=shuffle,
normalization=normalization,
augmentation=self.data_augmentation, meanstd=train_meanstd)
self.validation = CifarDataSet(
images=images[valid_indexes], labels=labels[valid_indexes],
n_classes=self.n_classes, shuffle=None,
normalization=normalization,
augmentation=False, meanstd=train_meanstd)
else:
self.train = CifarDataSet(
images=images, labels=labels,
n_classes=self.n_classes, shuffle=shuffle,
normalization=normalization,
augmentation=self.data_augmentation, meanstd=train_meanstd)
# add test set
images, labels = self.read_cifar(test_fnames)
self.test = CifarDataSet(
images=images, labels=labels,
shuffle=None, n_classes=self.n_classes,
normalization=normalization,
augmentation=False, meanstd=train_meanstd)
if validation_size is None:
self.validation = self.test | [
"def",
"__init__",
"(",
"self",
",",
"save_path",
"=",
"None",
",",
"validation_size",
"=",
"None",
",",
"shuffle",
"=",
"None",
",",
"normalization",
"=",
"None",
",",
"one_hot",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_save_path",
"=",
"save_path",
"self",
".",
"one_hot",
"=",
"one_hot",
"download_data_url",
"(",
"self",
".",
"data_url",
",",
"self",
".",
"save_path",
")",
"train_fnames",
",",
"test_fnames",
"=",
"self",
".",
"get_filenames",
"(",
"self",
".",
"save_path",
")",
"# add train and validations datasets",
"images",
",",
"labels",
"=",
"self",
".",
"read_cifar",
"(",
"train_fnames",
")",
"train_meanstd",
"=",
"ImagesDataSet",
".",
"measure_mean_and_std",
"(",
"images",
")",
"if",
"validation_size",
"is",
"not",
"None",
":",
"np",
".",
"random",
".",
"seed",
"(",
"DataProvider",
".",
"_SEED",
")",
"rand_indexes",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"images",
".",
"shape",
"[",
"0",
"]",
")",
"valid_indexes",
"=",
"rand_indexes",
"[",
":",
"validation_size",
"]",
"train_indexes",
"=",
"rand_indexes",
"[",
"validation_size",
":",
"]",
"self",
".",
"train",
"=",
"CifarDataSet",
"(",
"images",
"=",
"images",
"[",
"train_indexes",
"]",
",",
"labels",
"=",
"labels",
"[",
"train_indexes",
"]",
",",
"n_classes",
"=",
"self",
".",
"n_classes",
",",
"shuffle",
"=",
"shuffle",
",",
"normalization",
"=",
"normalization",
",",
"augmentation",
"=",
"self",
".",
"data_augmentation",
",",
"meanstd",
"=",
"train_meanstd",
")",
"self",
".",
"validation",
"=",
"CifarDataSet",
"(",
"images",
"=",
"images",
"[",
"valid_indexes",
"]",
",",
"labels",
"=",
"labels",
"[",
"valid_indexes",
"]",
",",
"n_classes",
"=",
"self",
".",
"n_classes",
",",
"shuffle",
"=",
"None",
",",
"normalization",
"=",
"normalization",
",",
"augmentation",
"=",
"False",
",",
"meanstd",
"=",
"train_meanstd",
")",
"else",
":",
"self",
".",
"train",
"=",
"CifarDataSet",
"(",
"images",
"=",
"images",
",",
"labels",
"=",
"labels",
",",
"n_classes",
"=",
"self",
".",
"n_classes",
",",
"shuffle",
"=",
"shuffle",
",",
"normalization",
"=",
"normalization",
",",
"augmentation",
"=",
"self",
".",
"data_augmentation",
",",
"meanstd",
"=",
"train_meanstd",
")",
"# add test set",
"images",
",",
"labels",
"=",
"self",
".",
"read_cifar",
"(",
"test_fnames",
")",
"self",
".",
"test",
"=",
"CifarDataSet",
"(",
"images",
"=",
"images",
",",
"labels",
"=",
"labels",
",",
"shuffle",
"=",
"None",
",",
"n_classes",
"=",
"self",
".",
"n_classes",
",",
"normalization",
"=",
"normalization",
",",
"augmentation",
"=",
"False",
",",
"meanstd",
"=",
"train_meanstd",
")",
"if",
"validation_size",
"is",
"None",
":",
"self",
".",
"validation",
"=",
"self",
".",
"test"
] | https://github.com/LGE-ARC-AdvancedAI/auptimizer/blob/50f6e3b4e0cb9146ca90fd74b9b24ca97ae22617/Examples/cai_eas/eas/data_providers/cifar.py#L111-L172 |
||
rucio/rucio | 6d0d358e04f5431f0b9a98ae40f31af0ddff4833 | lib/rucio/core/permission/atlas.py | python | perm_add_did | (issuer, kwargs) | return _is_root(issuer)\
or has_account_attribute(account=issuer, key='admin')\
or rucio.core.scope.is_scope_owner(scope=kwargs['scope'], account=issuer)\
or kwargs['scope'].external == u'mock' | Checks if an account can add an data identifier to a scope.
:param issuer: Account identifier which issues the command.
:param kwargs: List of arguments for the action.
:returns: True if account is allowed, otherwise False | Checks if an account can add an data identifier to a scope. | [
"Checks",
"if",
"an",
"account",
"can",
"add",
"an",
"data",
"identifier",
"to",
"a",
"scope",
"."
] | def perm_add_did(issuer, kwargs):
"""
Checks if an account can add an data identifier to a scope.
:param issuer: Account identifier which issues the command.
:param kwargs: List of arguments for the action.
:returns: True if account is allowed, otherwise False
"""
# Check the accounts of the issued rules
if not _is_root(issuer) and not has_account_attribute(account=issuer, key='admin'):
for rule in kwargs.get('rules', []):
if rule['account'] != issuer:
return False
return _is_root(issuer)\
or has_account_attribute(account=issuer, key='admin')\
or rucio.core.scope.is_scope_owner(scope=kwargs['scope'], account=issuer)\
or kwargs['scope'].external == u'mock' | [
"def",
"perm_add_did",
"(",
"issuer",
",",
"kwargs",
")",
":",
"# Check the accounts of the issued rules",
"if",
"not",
"_is_root",
"(",
"issuer",
")",
"and",
"not",
"has_account_attribute",
"(",
"account",
"=",
"issuer",
",",
"key",
"=",
"'admin'",
")",
":",
"for",
"rule",
"in",
"kwargs",
".",
"get",
"(",
"'rules'",
",",
"[",
"]",
")",
":",
"if",
"rule",
"[",
"'account'",
"]",
"!=",
"issuer",
":",
"return",
"False",
"return",
"_is_root",
"(",
"issuer",
")",
"or",
"has_account_attribute",
"(",
"account",
"=",
"issuer",
",",
"key",
"=",
"'admin'",
")",
"or",
"rucio",
".",
"core",
".",
"scope",
".",
"is_scope_owner",
"(",
"scope",
"=",
"kwargs",
"[",
"'scope'",
"]",
",",
"account",
"=",
"issuer",
")",
"or",
"kwargs",
"[",
"'scope'",
"]",
".",
"external",
"==",
"u'mock'"
] | https://github.com/rucio/rucio/blob/6d0d358e04f5431f0b9a98ae40f31af0ddff4833/lib/rucio/core/permission/atlas.py#L397-L414 |
|
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/pydoc.py | python | stripid | (text) | return _re_stripid.sub(r'\1', text) | Remove the hexadecimal id from a Python object representation. | Remove the hexadecimal id from a Python object representation. | [
"Remove",
"the",
"hexadecimal",
"id",
"from",
"a",
"Python",
"object",
"representation",
"."
] | def stripid(text):
"""Remove the hexadecimal id from a Python object representation."""
# The behaviour of %p is implementation-dependent in terms of case.
return _re_stripid.sub(r'\1', text) | [
"def",
"stripid",
"(",
"text",
")",
":",
"# The behaviour of %p is implementation-dependent in terms of case.",
"return",
"_re_stripid",
".",
"sub",
"(",
"r'\\1'",
",",
"text",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/pydoc.py#L125-L128 |
|
secdev/scapy | 65089071da1acf54622df0b4fa7fc7673d47d3cd | scapy/contrib/automotive/ccp.py | python | DTO.answers | (self, other) | return 1 | In CCP, the payload of a DTO packet is dependent on the cmd field
of a corresponding CRO packet. Two packets correspond, if there
ctr field is equal. If answers detect the corresponding CRO, it will
interpret the payload of a DTO with the correct class. In CCP, there is
no other way, to determine the class of a DTO payload. Since answers is
called on sr and sr1, this modification of the original answers
implementation will give a better user experience. | In CCP, the payload of a DTO packet is dependent on the cmd field
of a corresponding CRO packet. Two packets correspond, if there
ctr field is equal. If answers detect the corresponding CRO, it will
interpret the payload of a DTO with the correct class. In CCP, there is
no other way, to determine the class of a DTO payload. Since answers is
called on sr and sr1, this modification of the original answers
implementation will give a better user experience. | [
"In",
"CCP",
"the",
"payload",
"of",
"a",
"DTO",
"packet",
"is",
"dependent",
"on",
"the",
"cmd",
"field",
"of",
"a",
"corresponding",
"CRO",
"packet",
".",
"Two",
"packets",
"correspond",
"if",
"there",
"ctr",
"field",
"is",
"equal",
".",
"If",
"answers",
"detect",
"the",
"corresponding",
"CRO",
"it",
"will",
"interpret",
"the",
"payload",
"of",
"a",
"DTO",
"with",
"the",
"correct",
"class",
".",
"In",
"CCP",
"there",
"is",
"no",
"other",
"way",
"to",
"determine",
"the",
"class",
"of",
"a",
"DTO",
"payload",
".",
"Since",
"answers",
"is",
"called",
"on",
"sr",
"and",
"sr1",
"this",
"modification",
"of",
"the",
"original",
"answers",
"implementation",
"will",
"give",
"a",
"better",
"user",
"experience",
"."
] | def answers(self, other):
"""In CCP, the payload of a DTO packet is dependent on the cmd field
of a corresponding CRO packet. Two packets correspond, if there
ctr field is equal. If answers detect the corresponding CRO, it will
interpret the payload of a DTO with the correct class. In CCP, there is
no other way, to determine the class of a DTO payload. Since answers is
called on sr and sr1, this modification of the original answers
implementation will give a better user experience. """
if not hasattr(other, "ctr"):
return 0
if self.ctr != other.ctr:
return 0
if not hasattr(other, "cmd"):
return 0
new_pl_cls = self.get_dto_cls(other.cmd)
if self.payload_cls != new_pl_cls and \
self.payload_cls == DEFAULT_DTO:
data = bytes(self.load)
self.remove_payload()
self.add_payload(new_pl_cls(data))
self.payload_cls = new_pl_cls
return 1 | [
"def",
"answers",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"hasattr",
"(",
"other",
",",
"\"ctr\"",
")",
":",
"return",
"0",
"if",
"self",
".",
"ctr",
"!=",
"other",
".",
"ctr",
":",
"return",
"0",
"if",
"not",
"hasattr",
"(",
"other",
",",
"\"cmd\"",
")",
":",
"return",
"0",
"new_pl_cls",
"=",
"self",
".",
"get_dto_cls",
"(",
"other",
".",
"cmd",
")",
"if",
"self",
".",
"payload_cls",
"!=",
"new_pl_cls",
"and",
"self",
".",
"payload_cls",
"==",
"DEFAULT_DTO",
":",
"data",
"=",
"bytes",
"(",
"self",
".",
"load",
")",
"self",
".",
"remove_payload",
"(",
")",
"self",
".",
"add_payload",
"(",
"new_pl_cls",
"(",
"data",
")",
")",
"self",
".",
"payload_cls",
"=",
"new_pl_cls",
"return",
"1"
] | https://github.com/secdev/scapy/blob/65089071da1acf54622df0b4fa7fc7673d47d3cd/scapy/contrib/automotive/ccp.py#L564-L586 |
|
domlysz/BlenderGIS | 0c00bc361d05599467174b8721d4cfeb4c3db608 | core/georaster/georef.py | python | GeoRef.pxFromGeo | (self, x, y, reverseY=False, round2Floor=False) | return xy(xPx, yPx) | Affine transformation (cf. ESRI WorldFile spec.)
Return pixel position of given geographic coords
use reverseY option to get y pixels counting from bottom
Pixels position is range from 0 (not 1) | Affine transformation (cf. ESRI WorldFile spec.)
Return pixel position of given geographic coords
use reverseY option to get y pixels counting from bottom
Pixels position is range from 0 (not 1) | [
"Affine",
"transformation",
"(",
"cf",
".",
"ESRI",
"WorldFile",
"spec",
".",
")",
"Return",
"pixel",
"position",
"of",
"given",
"geographic",
"coords",
"use",
"reverseY",
"option",
"to",
"get",
"y",
"pixels",
"counting",
"from",
"bottom",
"Pixels",
"position",
"is",
"range",
"from",
"0",
"(",
"not",
"1",
")"
] | def pxFromGeo(self, x, y, reverseY=False, round2Floor=False):
"""
Affine transformation (cf. ESRI WorldFile spec.)
Return pixel position of given geographic coords
use reverseY option to get y pixels counting from bottom
Pixels position is range from 0 (not 1)
"""
# aliases for more readability
pxSizex, pxSizey = self.pxSize
rotx, roty = self.rotation
offx = self.origin.x - abs(self.pxSize.x/2)
offy = self.origin.y + abs(self.pxSize.y/2)
# transfo
xPx = (pxSizey*x - rotx*y + rotx*offy - pxSizey*offx) / (pxSizex*pxSizey - rotx*roty)
yPx = (-roty*x + pxSizex*y + roty*offx - pxSizex*offy) / (pxSizex*pxSizey - rotx*roty)
if reverseY:#the users want y pixel position counting from bottom
yPxRange = self.rSize.y - 1
yPx = yPxRange - yPx
yPx += 1 #adjust because the coord start at pixel's top left coord
#round to floor
if round2Floor:
xPx, yPx = math.floor(xPx), math.floor(yPx)
return xy(xPx, yPx) | [
"def",
"pxFromGeo",
"(",
"self",
",",
"x",
",",
"y",
",",
"reverseY",
"=",
"False",
",",
"round2Floor",
"=",
"False",
")",
":",
"# aliases for more readability",
"pxSizex",
",",
"pxSizey",
"=",
"self",
".",
"pxSize",
"rotx",
",",
"roty",
"=",
"self",
".",
"rotation",
"offx",
"=",
"self",
".",
"origin",
".",
"x",
"-",
"abs",
"(",
"self",
".",
"pxSize",
".",
"x",
"/",
"2",
")",
"offy",
"=",
"self",
".",
"origin",
".",
"y",
"+",
"abs",
"(",
"self",
".",
"pxSize",
".",
"y",
"/",
"2",
")",
"# transfo",
"xPx",
"=",
"(",
"pxSizey",
"*",
"x",
"-",
"rotx",
"*",
"y",
"+",
"rotx",
"*",
"offy",
"-",
"pxSizey",
"*",
"offx",
")",
"/",
"(",
"pxSizex",
"*",
"pxSizey",
"-",
"rotx",
"*",
"roty",
")",
"yPx",
"=",
"(",
"-",
"roty",
"*",
"x",
"+",
"pxSizex",
"*",
"y",
"+",
"roty",
"*",
"offx",
"-",
"pxSizex",
"*",
"offy",
")",
"/",
"(",
"pxSizex",
"*",
"pxSizey",
"-",
"rotx",
"*",
"roty",
")",
"if",
"reverseY",
":",
"#the users want y pixel position counting from bottom",
"yPxRange",
"=",
"self",
".",
"rSize",
".",
"y",
"-",
"1",
"yPx",
"=",
"yPxRange",
"-",
"yPx",
"yPx",
"+=",
"1",
"#adjust because the coord start at pixel's top left coord",
"#round to floor",
"if",
"round2Floor",
":",
"xPx",
",",
"yPx",
"=",
"math",
".",
"floor",
"(",
"xPx",
")",
",",
"math",
".",
"floor",
"(",
"yPx",
")",
"return",
"xy",
"(",
"xPx",
",",
"yPx",
")"
] | https://github.com/domlysz/BlenderGIS/blob/0c00bc361d05599467174b8721d4cfeb4c3db608/core/georaster/georef.py#L321-L343 |
|
ClusterLabs/pcs | 1f225199e02c8d20456bb386f4c913c3ff21ac78 | pcs/config.py | python | config_checkpoint_diff | (lib, argv, modifiers) | Commandline options:
* -f - CIB file | Commandline options:
* -f - CIB file | [
"Commandline",
"options",
":",
"*",
"-",
"f",
"-",
"CIB",
"file"
] | def config_checkpoint_diff(lib, argv, modifiers):
"""
Commandline options:
* -f - CIB file
"""
modifiers.ensure_only_supported("-f")
if len(argv) != 2:
print_to_stderr(usage.config(["checkpoint diff"]))
sys.exit(1)
if argv[0] == argv[1]:
utils.err("cannot diff a checkpoint against itself")
errors = []
checkpoints_lines = []
for checkpoint in argv:
if checkpoint == "live":
lines = _config_show_cib_lines(lib)
if not lines:
errors.append("unable to read live configuration")
else:
checkpoints_lines.append(lines)
else:
loaded, lines = _checkpoint_to_lines(lib, checkpoint)
if not loaded:
errors.append(
"unable to read checkpoint '{0}'".format(checkpoint)
)
else:
checkpoints_lines.append(lines)
if errors:
utils.err("\n".join(errors))
print(
"Differences between {0} (-) and {1} (+):".format(
*[
"live configuration"
if label == "live"
else f"checkpoint {label}"
for label in argv
]
)
)
print(
"\n".join(
[
line.rstrip()
for line in difflib.Differ().compare(
checkpoints_lines[0], checkpoints_lines[1]
)
]
)
) | [
"def",
"config_checkpoint_diff",
"(",
"lib",
",",
"argv",
",",
"modifiers",
")",
":",
"modifiers",
".",
"ensure_only_supported",
"(",
"\"-f\"",
")",
"if",
"len",
"(",
"argv",
")",
"!=",
"2",
":",
"print_to_stderr",
"(",
"usage",
".",
"config",
"(",
"[",
"\"checkpoint diff\"",
"]",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"argv",
"[",
"0",
"]",
"==",
"argv",
"[",
"1",
"]",
":",
"utils",
".",
"err",
"(",
"\"cannot diff a checkpoint against itself\"",
")",
"errors",
"=",
"[",
"]",
"checkpoints_lines",
"=",
"[",
"]",
"for",
"checkpoint",
"in",
"argv",
":",
"if",
"checkpoint",
"==",
"\"live\"",
":",
"lines",
"=",
"_config_show_cib_lines",
"(",
"lib",
")",
"if",
"not",
"lines",
":",
"errors",
".",
"append",
"(",
"\"unable to read live configuration\"",
")",
"else",
":",
"checkpoints_lines",
".",
"append",
"(",
"lines",
")",
"else",
":",
"loaded",
",",
"lines",
"=",
"_checkpoint_to_lines",
"(",
"lib",
",",
"checkpoint",
")",
"if",
"not",
"loaded",
":",
"errors",
".",
"append",
"(",
"\"unable to read checkpoint '{0}'\"",
".",
"format",
"(",
"checkpoint",
")",
")",
"else",
":",
"checkpoints_lines",
".",
"append",
"(",
"lines",
")",
"if",
"errors",
":",
"utils",
".",
"err",
"(",
"\"\\n\"",
".",
"join",
"(",
"errors",
")",
")",
"print",
"(",
"\"Differences between {0} (-) and {1} (+):\"",
".",
"format",
"(",
"*",
"[",
"\"live configuration\"",
"if",
"label",
"==",
"\"live\"",
"else",
"f\"checkpoint {label}\"",
"for",
"label",
"in",
"argv",
"]",
")",
")",
"print",
"(",
"\"\\n\"",
".",
"join",
"(",
"[",
"line",
".",
"rstrip",
"(",
")",
"for",
"line",
"in",
"difflib",
".",
"Differ",
"(",
")",
".",
"compare",
"(",
"checkpoints_lines",
"[",
"0",
"]",
",",
"checkpoints_lines",
"[",
"1",
"]",
")",
"]",
")",
")"
] | https://github.com/ClusterLabs/pcs/blob/1f225199e02c8d20456bb386f4c913c3ff21ac78/pcs/config.py#L716-L769 |
||
antonylesuisse/qweb | 2d6964a3e5cae90414c4f873eb770591f569dfe0 | qweb_python/qweb/static.py | python | WSGIStaticServe.__init__ | (self, urlroot="/", root=".", listdir=1, banner='') | [] | def __init__(self, urlroot="/", root=".", listdir=1, banner=''):
self.urlroot=urlroot
self.root="."
self.listdir=listdir
self.banner=banner
self.type_map=mimetypes.types_map.copy()
self.type_map['.csv']='text/csv' | [
"def",
"__init__",
"(",
"self",
",",
"urlroot",
"=",
"\"/\"",
",",
"root",
"=",
"\".\"",
",",
"listdir",
"=",
"1",
",",
"banner",
"=",
"''",
")",
":",
"self",
".",
"urlroot",
"=",
"urlroot",
"self",
".",
"root",
"=",
"\".\"",
"self",
".",
"listdir",
"=",
"listdir",
"self",
".",
"banner",
"=",
"banner",
"self",
".",
"type_map",
"=",
"mimetypes",
".",
"types_map",
".",
"copy",
"(",
")",
"self",
".",
"type_map",
"[",
"'.csv'",
"]",
"=",
"'text/csv'"
] | https://github.com/antonylesuisse/qweb/blob/2d6964a3e5cae90414c4f873eb770591f569dfe0/qweb_python/qweb/static.py#L197-L203 |
||||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-0.96/django/core/validators.py | python | isCommaSeparatedEmailList | (field_data, all_data) | Checks that field_data is a string of e-mail addresses separated by commas.
Blank field_data values will not throw a validation error, and whitespace
is allowed around the commas. | Checks that field_data is a string of e-mail addresses separated by commas.
Blank field_data values will not throw a validation error, and whitespace
is allowed around the commas. | [
"Checks",
"that",
"field_data",
"is",
"a",
"string",
"of",
"e",
"-",
"mail",
"addresses",
"separated",
"by",
"commas",
".",
"Blank",
"field_data",
"values",
"will",
"not",
"throw",
"a",
"validation",
"error",
"and",
"whitespace",
"is",
"allowed",
"around",
"the",
"commas",
"."
] | def isCommaSeparatedEmailList(field_data, all_data):
"""
Checks that field_data is a string of e-mail addresses separated by commas.
Blank field_data values will not throw a validation error, and whitespace
is allowed around the commas.
"""
for supposed_email in field_data.split(','):
try:
isValidEmail(supposed_email.strip(), '')
except ValidationError:
raise ValidationError, gettext("Enter valid e-mail addresses separated by commas.") | [
"def",
"isCommaSeparatedEmailList",
"(",
"field_data",
",",
"all_data",
")",
":",
"for",
"supposed_email",
"in",
"field_data",
".",
"split",
"(",
"','",
")",
":",
"try",
":",
"isValidEmail",
"(",
"supposed_email",
".",
"strip",
"(",
")",
",",
"''",
")",
"except",
"ValidationError",
":",
"raise",
"ValidationError",
",",
"gettext",
"(",
"\"Enter valid e-mail addresses separated by commas.\"",
")"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-0.96/django/core/validators.py#L89-L99 |
||
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | source/addons/purchase_requisition/purchase_requisition.py | python | purchase_requisition.make_purchase_order | (self, cr, uid, ids, partner_id, context=None) | return res | Create New RFQ for Supplier | Create New RFQ for Supplier | [
"Create",
"New",
"RFQ",
"for",
"Supplier"
] | def make_purchase_order(self, cr, uid, ids, partner_id, context=None):
"""
Create New RFQ for Supplier
"""
context = dict(context or {})
assert partner_id, 'Supplier should be specified'
purchase_order = self.pool.get('purchase.order')
purchase_order_line = self.pool.get('purchase.order.line')
res_partner = self.pool.get('res.partner')
supplier = res_partner.browse(cr, uid, partner_id, context=context)
res = {}
for requisition in self.browse(cr, uid, ids, context=context):
if not requisition.multiple_rfq_per_supplier and supplier.id in filter(lambda x: x, [rfq.state != 'cancel' and rfq.partner_id.id or None for rfq in requisition.purchase_ids]):
raise osv.except_osv(_('Warning!'), _('You have already one %s purchase order for this partner, you must cancel this purchase order to create a new quotation.') % rfq.state)
context.update({'mail_create_nolog': True})
purchase_id = purchase_order.create(cr, uid, self._prepare_purchase_order(cr, uid, requisition, supplier, context=context), context=context)
purchase_order.message_post(cr, uid, [purchase_id], body=_("RFQ created"), context=context)
res[requisition.id] = purchase_id
for line in requisition.line_ids:
purchase_order_line.create(cr, uid, self._prepare_purchase_order_line(cr, uid, requisition, line, purchase_id, supplier, context=context), context=context)
return res | [
"def",
"make_purchase_order",
"(",
"self",
",",
"cr",
",",
"uid",
",",
"ids",
",",
"partner_id",
",",
"context",
"=",
"None",
")",
":",
"context",
"=",
"dict",
"(",
"context",
"or",
"{",
"}",
")",
"assert",
"partner_id",
",",
"'Supplier should be specified'",
"purchase_order",
"=",
"self",
".",
"pool",
".",
"get",
"(",
"'purchase.order'",
")",
"purchase_order_line",
"=",
"self",
".",
"pool",
".",
"get",
"(",
"'purchase.order.line'",
")",
"res_partner",
"=",
"self",
".",
"pool",
".",
"get",
"(",
"'res.partner'",
")",
"supplier",
"=",
"res_partner",
".",
"browse",
"(",
"cr",
",",
"uid",
",",
"partner_id",
",",
"context",
"=",
"context",
")",
"res",
"=",
"{",
"}",
"for",
"requisition",
"in",
"self",
".",
"browse",
"(",
"cr",
",",
"uid",
",",
"ids",
",",
"context",
"=",
"context",
")",
":",
"if",
"not",
"requisition",
".",
"multiple_rfq_per_supplier",
"and",
"supplier",
".",
"id",
"in",
"filter",
"(",
"lambda",
"x",
":",
"x",
",",
"[",
"rfq",
".",
"state",
"!=",
"'cancel'",
"and",
"rfq",
".",
"partner_id",
".",
"id",
"or",
"None",
"for",
"rfq",
"in",
"requisition",
".",
"purchase_ids",
"]",
")",
":",
"raise",
"osv",
".",
"except_osv",
"(",
"_",
"(",
"'Warning!'",
")",
",",
"_",
"(",
"'You have already one %s purchase order for this partner, you must cancel this purchase order to create a new quotation.'",
")",
"%",
"rfq",
".",
"state",
")",
"context",
".",
"update",
"(",
"{",
"'mail_create_nolog'",
":",
"True",
"}",
")",
"purchase_id",
"=",
"purchase_order",
".",
"create",
"(",
"cr",
",",
"uid",
",",
"self",
".",
"_prepare_purchase_order",
"(",
"cr",
",",
"uid",
",",
"requisition",
",",
"supplier",
",",
"context",
"=",
"context",
")",
",",
"context",
"=",
"context",
")",
"purchase_order",
".",
"message_post",
"(",
"cr",
",",
"uid",
",",
"[",
"purchase_id",
"]",
",",
"body",
"=",
"_",
"(",
"\"RFQ created\"",
")",
",",
"context",
"=",
"context",
")",
"res",
"[",
"requisition",
".",
"id",
"]",
"=",
"purchase_id",
"for",
"line",
"in",
"requisition",
".",
"line_ids",
":",
"purchase_order_line",
".",
"create",
"(",
"cr",
",",
"uid",
",",
"self",
".",
"_prepare_purchase_order_line",
"(",
"cr",
",",
"uid",
",",
"requisition",
",",
"line",
",",
"purchase_id",
",",
"supplier",
",",
"context",
"=",
"context",
")",
",",
"context",
"=",
"context",
")",
"return",
"res"
] | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/source/addons/purchase_requisition/purchase_requisition.py#L177-L197 |
|
tariqdaouda/pyGeno | 6311c9cd94443e05b130d8b4babc24c374a77d7c | pyGeno/tools/parsers/FastaTools.py | python | FastaFile.__setitem__ | (self, i, v) | sets the value of the ith entry | sets the value of the ith entry | [
"sets",
"the",
"value",
"of",
"the",
"ith",
"entry"
] | def __setitem__(self, i, v) :
"""sets the value of the ith entry"""
if len(v) != 2:
raise TypeError("v must have a len of 2 : (header, data)")
self.data[i] = v | [
"def",
"__setitem__",
"(",
"self",
",",
"i",
",",
"v",
")",
":",
"if",
"len",
"(",
"v",
")",
"!=",
"2",
":",
"raise",
"TypeError",
"(",
"\"v must have a len of 2 : (header, data)\"",
")",
"self",
".",
"data",
"[",
"i",
"]",
"=",
"v"
] | https://github.com/tariqdaouda/pyGeno/blob/6311c9cd94443e05b130d8b4babc24c374a77d7c/pyGeno/tools/parsers/FastaTools.py#L91-L96 |
||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/inspect.py | python | getsourcefile | (object) | Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source. | Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source. | [
"Return",
"the",
"filename",
"that",
"can",
"be",
"used",
"to",
"locate",
"an",
"object",
"s",
"source",
".",
"Return",
"None",
"if",
"no",
"way",
"can",
"be",
"identified",
"to",
"get",
"the",
"source",
"."
] | def getsourcefile(object):
"""Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source.
"""
filename = getfile(object)
if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
filename = filename[:-4] + '.py'
for suffix, mode, kind in imp.get_suffixes():
if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
# Looks like a binary file. We want to only return a text file.
return None
if os.path.exists(filename):
return filename
# only return a non-existent filename if the module has a PEP 302 loader
if hasattr(getmodule(object, filename), '__loader__'):
return filename
# or it is in the linecache
if filename in linecache.cache:
return filename | [
"def",
"getsourcefile",
"(",
"object",
")",
":",
"filename",
"=",
"getfile",
"(",
"object",
")",
"if",
"string",
".",
"lower",
"(",
"filename",
"[",
"-",
"4",
":",
"]",
")",
"in",
"(",
"'.pyc'",
",",
"'.pyo'",
")",
":",
"filename",
"=",
"filename",
"[",
":",
"-",
"4",
"]",
"+",
"'.py'",
"for",
"suffix",
",",
"mode",
",",
"kind",
"in",
"imp",
".",
"get_suffixes",
"(",
")",
":",
"if",
"'b'",
"in",
"mode",
"and",
"string",
".",
"lower",
"(",
"filename",
"[",
"-",
"len",
"(",
"suffix",
")",
":",
"]",
")",
"==",
"suffix",
":",
"# Looks like a binary file. We want to only return a text file.",
"return",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"return",
"filename",
"# only return a non-existent filename if the module has a PEP 302 loader",
"if",
"hasattr",
"(",
"getmodule",
"(",
"object",
",",
"filename",
")",
",",
"'__loader__'",
")",
":",
"return",
"filename",
"# or it is in the linecache",
"if",
"filename",
"in",
"linecache",
".",
"cache",
":",
"return",
"filename"
] | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/inspect.py#L442-L460 |
||
sametmax/Django--an-app-at-a-time | 99eddf12ead76e6dfbeb09ce0bae61e282e22f8a | ignore_this_directory/django/core/serializers/xml_serializer.py | python | Deserializer._make_parser | (self) | return DefusedExpatParser() | Create a hardened XML parser (no custom/external entities). | Create a hardened XML parser (no custom/external entities). | [
"Create",
"a",
"hardened",
"XML",
"parser",
"(",
"no",
"custom",
"/",
"external",
"entities",
")",
"."
] | def _make_parser(self):
"""Create a hardened XML parser (no custom/external entities)."""
return DefusedExpatParser() | [
"def",
"_make_parser",
"(",
"self",
")",
":",
"return",
"DefusedExpatParser",
"(",
")"
] | https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/core/serializers/xml_serializer.py#L160-L162 |
|
jonathanslenders/asyncio-redis | 50d71a53798967f7fdf1be36b8447e322dedc5ee | asyncio_redis/protocol.py | python | RedisProtocol.bitop_not | (self, tr, destkey: NativeType, key: NativeType) | return self._query(
tr,
b"bitop",
b"not",
self.encode_from_native(destkey),
self.encode_from_native(key),
) | Perform a bitwise NOT operation between multiple keys | Perform a bitwise NOT operation between multiple keys | [
"Perform",
"a",
"bitwise",
"NOT",
"operation",
"between",
"multiple",
"keys"
] | def bitop_not(self, tr, destkey: NativeType, key: NativeType) -> int:
"""Perform a bitwise NOT operation between multiple keys
"""
return self._query(
tr,
b"bitop",
b"not",
self.encode_from_native(destkey),
self.encode_from_native(key),
) | [
"def",
"bitop_not",
"(",
"self",
",",
"tr",
",",
"destkey",
":",
"NativeType",
",",
"key",
":",
"NativeType",
")",
"->",
"int",
":",
"return",
"self",
".",
"_query",
"(",
"tr",
",",
"b\"bitop\"",
",",
"b\"not\"",
",",
"self",
".",
"encode_from_native",
"(",
"destkey",
")",
",",
"self",
".",
"encode_from_native",
"(",
"key",
")",
",",
")"
] | https://github.com/jonathanslenders/asyncio-redis/blob/50d71a53798967f7fdf1be36b8447e322dedc5ee/asyncio_redis/protocol.py#L1384-L1393 |
|
w3h/isf | 6faf0a3df185465ec17369c90ccc16e2a03a1870 | lib/thirdparty/pyreadline/modes/notemacs.py | python | NotEmacsMode.delete_char_or_list | (self, e) | Deletes the character under the cursor if not at the beginning or
end of the line (like delete-char). If at the end of the line,
behaves identically to possible-completions. This command is unbound
by default. | Deletes the character under the cursor if not at the beginning or
end of the line (like delete-char). If at the end of the line,
behaves identically to possible-completions. This command is unbound
by default. | [
"Deletes",
"the",
"character",
"under",
"the",
"cursor",
"if",
"not",
"at",
"the",
"beginning",
"or",
"end",
"of",
"the",
"line",
"(",
"like",
"delete",
"-",
"char",
")",
".",
"If",
"at",
"the",
"end",
"of",
"the",
"line",
"behaves",
"identically",
"to",
"possible",
"-",
"completions",
".",
"This",
"command",
"is",
"unbound",
"by",
"default",
"."
] | def delete_char_or_list(self, e): # ()
'''Deletes the character under the cursor if not at the beginning or
end of the line (like delete-char). If at the end of the line,
behaves identically to possible-completions. This command is unbound
by default.'''
pass | [
"def",
"delete_char_or_list",
"(",
"self",
",",
"e",
")",
":",
"# ()",
"pass"
] | https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/pyreadline/modes/notemacs.py#L458-L463 |
||
pywinauto/pywinauto | 7235e6f83edfd96a7aeb8bbf9fef7b8f3d912512 | pywinauto/handleprops.py | python | dumpwindow | (handle) | return props | Dump a window to a set of properties | Dump a window to a set of properties | [
"Dump",
"a",
"window",
"to",
"a",
"set",
"of",
"properties"
] | def dumpwindow(handle):
"""Dump a window to a set of properties"""
props = {}
for func in (text,
classname,
rectangle,
clientrect,
style,
exstyle,
contexthelpid,
controlid,
userdata,
font,
parent,
processid,
isenabled,
isunicode,
isvisible,
children,
):
props[func.__name__] = func(handle)
return props | [
"def",
"dumpwindow",
"(",
"handle",
")",
":",
"props",
"=",
"{",
"}",
"for",
"func",
"in",
"(",
"text",
",",
"classname",
",",
"rectangle",
",",
"clientrect",
",",
"style",
",",
"exstyle",
",",
"contexthelpid",
",",
"controlid",
",",
"userdata",
",",
"font",
",",
"parent",
",",
"processid",
",",
"isenabled",
",",
"isunicode",
",",
"isvisible",
",",
"children",
",",
")",
":",
"props",
"[",
"func",
".",
"__name__",
"]",
"=",
"func",
"(",
"handle",
")",
"return",
"props"
] | https://github.com/pywinauto/pywinauto/blob/7235e6f83edfd96a7aeb8bbf9fef7b8f3d912512/pywinauto/handleprops.py#L383-L407 |
|
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/models/v1beta1_mutating_webhook.py | python | V1beta1MutatingWebhook.__init__ | (self, admission_review_versions=None, client_config=None, failure_policy=None, match_policy=None, name=None, namespace_selector=None, object_selector=None, reinvocation_policy=None, rules=None, side_effects=None, timeout_seconds=None, local_vars_configuration=None) | V1beta1MutatingWebhook - a model defined in OpenAPI | V1beta1MutatingWebhook - a model defined in OpenAPI | [
"V1beta1MutatingWebhook",
"-",
"a",
"model",
"defined",
"in",
"OpenAPI"
] | def __init__(self, admission_review_versions=None, client_config=None, failure_policy=None, match_policy=None, name=None, namespace_selector=None, object_selector=None, reinvocation_policy=None, rules=None, side_effects=None, timeout_seconds=None, local_vars_configuration=None): # noqa: E501
"""V1beta1MutatingWebhook - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._admission_review_versions = None
self._client_config = None
self._failure_policy = None
self._match_policy = None
self._name = None
self._namespace_selector = None
self._object_selector = None
self._reinvocation_policy = None
self._rules = None
self._side_effects = None
self._timeout_seconds = None
self.discriminator = None
if admission_review_versions is not None:
self.admission_review_versions = admission_review_versions
self.client_config = client_config
if failure_policy is not None:
self.failure_policy = failure_policy
if match_policy is not None:
self.match_policy = match_policy
self.name = name
if namespace_selector is not None:
self.namespace_selector = namespace_selector
if object_selector is not None:
self.object_selector = object_selector
if reinvocation_policy is not None:
self.reinvocation_policy = reinvocation_policy
if rules is not None:
self.rules = rules
if side_effects is not None:
self.side_effects = side_effects
if timeout_seconds is not None:
self.timeout_seconds = timeout_seconds | [
"def",
"__init__",
"(",
"self",
",",
"admission_review_versions",
"=",
"None",
",",
"client_config",
"=",
"None",
",",
"failure_policy",
"=",
"None",
",",
"match_policy",
"=",
"None",
",",
"name",
"=",
"None",
",",
"namespace_selector",
"=",
"None",
",",
"object_selector",
"=",
"None",
",",
"reinvocation_policy",
"=",
"None",
",",
"rules",
"=",
"None",
",",
"side_effects",
"=",
"None",
",",
"timeout_seconds",
"=",
"None",
",",
"local_vars_configuration",
"=",
"None",
")",
":",
"# noqa: E501",
"# noqa: E501",
"if",
"local_vars_configuration",
"is",
"None",
":",
"local_vars_configuration",
"=",
"Configuration",
"(",
")",
"self",
".",
"local_vars_configuration",
"=",
"local_vars_configuration",
"self",
".",
"_admission_review_versions",
"=",
"None",
"self",
".",
"_client_config",
"=",
"None",
"self",
".",
"_failure_policy",
"=",
"None",
"self",
".",
"_match_policy",
"=",
"None",
"self",
".",
"_name",
"=",
"None",
"self",
".",
"_namespace_selector",
"=",
"None",
"self",
".",
"_object_selector",
"=",
"None",
"self",
".",
"_reinvocation_policy",
"=",
"None",
"self",
".",
"_rules",
"=",
"None",
"self",
".",
"_side_effects",
"=",
"None",
"self",
".",
"_timeout_seconds",
"=",
"None",
"self",
".",
"discriminator",
"=",
"None",
"if",
"admission_review_versions",
"is",
"not",
"None",
":",
"self",
".",
"admission_review_versions",
"=",
"admission_review_versions",
"self",
".",
"client_config",
"=",
"client_config",
"if",
"failure_policy",
"is",
"not",
"None",
":",
"self",
".",
"failure_policy",
"=",
"failure_policy",
"if",
"match_policy",
"is",
"not",
"None",
":",
"self",
".",
"match_policy",
"=",
"match_policy",
"self",
".",
"name",
"=",
"name",
"if",
"namespace_selector",
"is",
"not",
"None",
":",
"self",
".",
"namespace_selector",
"=",
"namespace_selector",
"if",
"object_selector",
"is",
"not",
"None",
":",
"self",
".",
"object_selector",
"=",
"object_selector",
"if",
"reinvocation_policy",
"is",
"not",
"None",
":",
"self",
".",
"reinvocation_policy",
"=",
"reinvocation_policy",
"if",
"rules",
"is",
"not",
"None",
":",
"self",
".",
"rules",
"=",
"rules",
"if",
"side_effects",
"is",
"not",
"None",
":",
"self",
".",
"side_effects",
"=",
"side_effects",
"if",
"timeout_seconds",
"is",
"not",
"None",
":",
"self",
".",
"timeout_seconds",
"=",
"timeout_seconds"
] | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1beta1_mutating_webhook.py#L63-L101 |
||
gammapy/gammapy | 735b25cd5bbed35e2004d633621896dcd5295e8b | dev/authors.py | python | get_full_name | (author_data) | return " ".join(parts) | Get full name from CITATION.cff parts | Get full name from CITATION.cff parts | [
"Get",
"full",
"name",
"from",
"CITATION",
".",
"cff",
"parts"
] | def get_full_name(author_data):
"""Get full name from CITATION.cff parts"""
parts = []
parts.append(author_data["given-names"])
name_particle = author_data.get("name-particle", None)
if name_particle:
parts.append(name_particle)
parts.append(author_data["family-names"])
return " ".join(parts) | [
"def",
"get_full_name",
"(",
"author_data",
")",
":",
"parts",
"=",
"[",
"]",
"parts",
".",
"append",
"(",
"author_data",
"[",
"\"given-names\"",
"]",
")",
"name_particle",
"=",
"author_data",
".",
"get",
"(",
"\"name-particle\"",
",",
"None",
")",
"if",
"name_particle",
":",
"parts",
".",
"append",
"(",
"name_particle",
")",
"parts",
".",
"append",
"(",
"author_data",
"[",
"\"family-names\"",
"]",
")",
"return",
"\" \"",
".",
"join",
"(",
"parts",
")"
] | https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/dev/authors.py#L39-L50 |
|
phaethon/kamene | bf679a65d456411942ee4a907818ba3d6a183bfe | kamene/layers/ipsec.py | python | AuthAlgo.check_key | (self, key) | Check that the key length is valid.
@param key: a byte string | Check that the key length is valid. | [
"Check",
"that",
"the",
"key",
"length",
"is",
"valid",
"."
] | def check_key(self, key):
"""
Check that the key length is valid.
@param key: a byte string
"""
if self.key_size and len(key) not in self.key_size:
raise TypeError('invalid key size %s, must be one of %s' %
(len(key), self.key_size)) | [
"def",
"check_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"key_size",
"and",
"len",
"(",
"key",
")",
"not",
"in",
"self",
".",
"key_size",
":",
"raise",
"TypeError",
"(",
"'invalid key size %s, must be one of %s'",
"%",
"(",
"len",
"(",
"key",
")",
",",
"self",
".",
"key_size",
")",
")"
] | https://github.com/phaethon/kamene/blob/bf679a65d456411942ee4a907818ba3d6a183bfe/kamene/layers/ipsec.py#L476-L484 |
||
nosmokingbandit/watcher | dadacd21a5790ee609058a98a17fcc8954d24439 | lib/cherrypy/wsgiserver/__init__.py | python | HTTPServer.bind | (self, family, type, proto=0) | Create (or recreate) the actual socket object. | Create (or recreate) the actual socket object. | [
"Create",
"(",
"or",
"recreate",
")",
"the",
"actual",
"socket",
"object",
"."
] | def bind(self, family, type, proto=0):
"""Create (or recreate) the actual socket object."""
self.socket = socket.socket(family, type, proto)
prevent_socket_inheritance(self.socket)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if self.nodelay and not isinstance(self.bind_addr, str):
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if self.ssl_adapter is not None:
self.socket = self.ssl_adapter.bind(self.socket)
# If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
# activate dual-stack. See
# https://github.com/cherrypy/cherrypy/issues/871.
if (hasattr(socket, 'AF_INET6') and family == socket.AF_INET6
and self.bind_addr[0] in ('::', '::0', '::0.0.0.0')):
try:
self.socket.setsockopt(
socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
except (AttributeError, socket.error):
# Apparently, the socket option is not available in
# this machine's TCP stack
pass
self.socket.bind(self.bind_addr) | [
"def",
"bind",
"(",
"self",
",",
"family",
",",
"type",
",",
"proto",
"=",
"0",
")",
":",
"self",
".",
"socket",
"=",
"socket",
".",
"socket",
"(",
"family",
",",
"type",
",",
"proto",
")",
"prevent_socket_inheritance",
"(",
"self",
".",
"socket",
")",
"self",
".",
"socket",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_REUSEADDR",
",",
"1",
")",
"if",
"self",
".",
"nodelay",
"and",
"not",
"isinstance",
"(",
"self",
".",
"bind_addr",
",",
"str",
")",
":",
"self",
".",
"socket",
".",
"setsockopt",
"(",
"socket",
".",
"IPPROTO_TCP",
",",
"socket",
".",
"TCP_NODELAY",
",",
"1",
")",
"if",
"self",
".",
"ssl_adapter",
"is",
"not",
"None",
":",
"self",
".",
"socket",
"=",
"self",
".",
"ssl_adapter",
".",
"bind",
"(",
"self",
".",
"socket",
")",
"# If listening on the IPV6 any address ('::' = IN6ADDR_ANY),",
"# activate dual-stack. See",
"# https://github.com/cherrypy/cherrypy/issues/871.",
"if",
"(",
"hasattr",
"(",
"socket",
",",
"'AF_INET6'",
")",
"and",
"family",
"==",
"socket",
".",
"AF_INET6",
"and",
"self",
".",
"bind_addr",
"[",
"0",
"]",
"in",
"(",
"'::'",
",",
"'::0'",
",",
"'::0.0.0.0'",
")",
")",
":",
"try",
":",
"self",
".",
"socket",
".",
"setsockopt",
"(",
"socket",
".",
"IPPROTO_IPV6",
",",
"socket",
".",
"IPV6_V6ONLY",
",",
"0",
")",
"except",
"(",
"AttributeError",
",",
"socket",
".",
"error",
")",
":",
"# Apparently, the socket option is not available in",
"# this machine's TCP stack",
"pass",
"self",
".",
"socket",
".",
"bind",
"(",
"self",
".",
"bind_addr",
")"
] | https://github.com/nosmokingbandit/watcher/blob/dadacd21a5790ee609058a98a17fcc8954d24439/lib/cherrypy/wsgiserver/__init__.py#L2042-L2066 |
||
microsoft/MASS | a72a74e5cab150f75cd4e241afa4681bfb92b721 | MASS-unsupNMT/translate.py | python | get_parser | () | return parser | Generate a parameters parser. | Generate a parameters parser. | [
"Generate",
"a",
"parameters",
"parser",
"."
] | def get_parser():
"""
Generate a parameters parser.
"""
# parse parameters
parser = argparse.ArgumentParser(description="Translate sentences")
# main parameters
parser.add_argument("--dump_path", type=str, default="./dumped/", help="Experiment dump path")
parser.add_argument("--exp_name", type=str, default="", help="Experiment name")
parser.add_argument("--exp_id", type=str, default="", help="Experiment ID")
parser.add_argument("--fp16", type=bool_flag, default=False, help="Run model with float16")
parser.add_argument("--batch_size", type=int, default=32, help="Number of sentences per batch")
# model / output paths
parser.add_argument("--model_path", type=str, default="", help="Model path")
parser.add_argument("--output_path", type=str, default="", help="Output path")
parser.add_argument("--beam", type=int, default=1, help="Beam size")
parser.add_argument("--length_penalty", type=float, default=1, help="length penalty")
# parser.add_argument("--max_vocab", type=int, default=-1, help="Maximum vocabulary size (-1 to disable)")
# parser.add_argument("--min_count", type=int, default=0, help="Minimum vocabulary count")
# source language / target language
parser.add_argument("--src_lang", type=str, default="", help="Source language")
parser.add_argument("--tgt_lang", type=str, default="", help="Target language")
return parser | [
"def",
"get_parser",
"(",
")",
":",
"# parse parameters",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Translate sentences\"",
")",
"# main parameters",
"parser",
".",
"add_argument",
"(",
"\"--dump_path\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"\"./dumped/\"",
",",
"help",
"=",
"\"Experiment dump path\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--exp_name\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"\"\"",
",",
"help",
"=",
"\"Experiment name\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--exp_id\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"\"\"",
",",
"help",
"=",
"\"Experiment ID\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--fp16\"",
",",
"type",
"=",
"bool_flag",
",",
"default",
"=",
"False",
",",
"help",
"=",
"\"Run model with float16\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--batch_size\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"32",
",",
"help",
"=",
"\"Number of sentences per batch\"",
")",
"# model / output paths",
"parser",
".",
"add_argument",
"(",
"\"--model_path\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"\"\"",
",",
"help",
"=",
"\"Model path\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--output_path\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"\"\"",
",",
"help",
"=",
"\"Output path\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--beam\"",
",",
"type",
"=",
"int",
",",
"default",
"=",
"1",
",",
"help",
"=",
"\"Beam size\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--length_penalty\"",
",",
"type",
"=",
"float",
",",
"default",
"=",
"1",
",",
"help",
"=",
"\"length penalty\"",
")",
"# parser.add_argument(\"--max_vocab\", type=int, default=-1, help=\"Maximum vocabulary size (-1 to disable)\")",
"# parser.add_argument(\"--min_count\", type=int, default=0, help=\"Minimum vocabulary count\")",
"# source language / target language",
"parser",
".",
"add_argument",
"(",
"\"--src_lang\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"\"\"",
",",
"help",
"=",
"\"Source language\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--tgt_lang\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"\"\"",
",",
"help",
"=",
"\"Target language\"",
")",
"return",
"parser"
] | https://github.com/microsoft/MASS/blob/a72a74e5cab150f75cd4e241afa4681bfb92b721/MASS-unsupNMT/translate.py#L32-L60 |
|
FSecureLABS/Jandroid | e31d0dab58a2bfd6ed8e0a387172b8bd7c893436 | gui/appJar.py | python | gui.addEmptyLabel | (self, title, row=None, column=0, colspan=0, rowspan=0) | return self.addLabel(title=title, text='', row=row, column=column, colspan=colspan, rowspan=rowspan) | adds an empty label | adds an empty label | [
"adds",
"an",
"empty",
"label"
] | def addEmptyLabel(self, title, row=None, column=0, colspan=0, rowspan=0):
''' adds an empty label '''
return self.addLabel(title=title, text='', row=row, column=column, colspan=colspan, rowspan=rowspan) | [
"def",
"addEmptyLabel",
"(",
"self",
",",
"title",
",",
"row",
"=",
"None",
",",
"column",
"=",
"0",
",",
"colspan",
"=",
"0",
",",
"rowspan",
"=",
"0",
")",
":",
"return",
"self",
".",
"addLabel",
"(",
"title",
"=",
"title",
",",
"text",
"=",
"''",
",",
"row",
"=",
"row",
",",
"column",
"=",
"column",
",",
"colspan",
"=",
"colspan",
",",
"rowspan",
"=",
"rowspan",
")"
] | https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/gui/appJar.py#L9116-L9118 |
|
gramps-project/gramps | 04d4651a43eb210192f40a9f8c2bad8ee8fa3753 | gramps/gui/widgets/statusbar.py | python | Statusbar.clear_filter | (self) | Clear the filter status text. | Clear the filter status text. | [
"Clear",
"the",
"filter",
"status",
"text",
"."
] | def clear_filter(self):
"""Clear the filter status text."""
self.__filter.set_text('') | [
"def",
"clear_filter",
"(",
"self",
")",
":",
"self",
".",
"__filter",
".",
"set_text",
"(",
"''",
")"
] | https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/widgets/statusbar.py#L112-L114 |
||
naftaliharris/tauthon | 5587ceec329b75f7caf6d65a036db61ac1bae214 | Lib/plat-mac/macresource.py | python | open_error_resource | () | Open the resource file containing the error code to error message
mapping. | Open the resource file containing the error code to error message
mapping. | [
"Open",
"the",
"resource",
"file",
"containing",
"the",
"error",
"code",
"to",
"error",
"message",
"mapping",
"."
] | def open_error_resource():
"""Open the resource file containing the error code to error message
mapping."""
need('Estr', 1, filename="errors.rsrc", modname=__name__) | [
"def",
"open_error_resource",
"(",
")",
":",
"need",
"(",
"'Estr'",
",",
"1",
",",
"filename",
"=",
"\"errors.rsrc\"",
",",
"modname",
"=",
"__name__",
")"
] | https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/plat-mac/macresource.py#L114-L117 |
||
angr/claripy | 4c961b4dc664706be8142fe4868f27655bc8da77 | claripy/ast/bv.py | python | BVS | (name, size, min=None, max=None, stride=None, uninitialized=False, #pylint:disable=redefined-builtin
explicit_name=None, discrete_set=False, discrete_set_max_card=None, **kwargs) | return BV('BVS', (n, min, max, stride, uninitialized, discrete_set, discrete_set_max_card), variables={n},
length=size, symbolic=True, eager_backends=None, uninitialized=uninitialized, encoded_name=encoded_name,
**kwargs) | Creates a bit-vector symbol (i.e., a variable).
If you want to specify the maximum or minimum value of a normal symbol that is not part of value-set analysis, you
should manually add constraints to that effect. **Do not use ``min`` and ``max`` for symbolic execution.**
:param name: The name of the symbol.
:param size: The size (in bits) of the bit-vector.
:param min: The minimum value of the symbol, used only for value-set analysis
:param max: The maximum value of the symbol, used only for value-set analysis
:param stride: The stride of the symbol, used only for value-set analysis
:param uninitialized: Whether this value should be counted as an "uninitialized" value in the course of an
analysis.
:param bool explicit_name: If False, an identifier is appended to the name to ensure uniqueness.
:param bool discrete_set: If True, a DiscreteStridedIntervalSet will be used instead of a normal StridedInterval.
:param int discrete_set_max_card: The maximum cardinality of the discrete set. It is ignored if discrete_set is set
to False or None.
:returns: a BV object representing this symbol. | Creates a bit-vector symbol (i.e., a variable). | [
"Creates",
"a",
"bit",
"-",
"vector",
"symbol",
"(",
"i",
".",
"e",
".",
"a",
"variable",
")",
"."
] | def BVS(name, size, min=None, max=None, stride=None, uninitialized=False, #pylint:disable=redefined-builtin
explicit_name=None, discrete_set=False, discrete_set_max_card=None, **kwargs):
"""
Creates a bit-vector symbol (i.e., a variable).
If you want to specify the maximum or minimum value of a normal symbol that is not part of value-set analysis, you
should manually add constraints to that effect. **Do not use ``min`` and ``max`` for symbolic execution.**
:param name: The name of the symbol.
:param size: The size (in bits) of the bit-vector.
:param min: The minimum value of the symbol, used only for value-set analysis
:param max: The maximum value of the symbol, used only for value-set analysis
:param stride: The stride of the symbol, used only for value-set analysis
:param uninitialized: Whether this value should be counted as an "uninitialized" value in the course of an
analysis.
:param bool explicit_name: If False, an identifier is appended to the name to ensure uniqueness.
:param bool discrete_set: If True, a DiscreteStridedIntervalSet will be used instead of a normal StridedInterval.
:param int discrete_set_max_card: The maximum cardinality of the discrete set. It is ignored if discrete_set is set
to False or None.
:returns: a BV object representing this symbol.
"""
if stride == 0 and max != min:
raise ClaripyValueError("BVSes of stride 0 should have max == min")
if type(name) is bytes:
name = name.decode()
if type(name) is not str:
raise TypeError("Name value for BVS must be a str, got %r" % type(name))
n = _make_name(name, size, False if explicit_name is None else explicit_name)
encoded_name = n.encode()
if not discrete_set:
discrete_set_max_card = None
return BV('BVS', (n, min, max, stride, uninitialized, discrete_set, discrete_set_max_card), variables={n},
length=size, symbolic=True, eager_backends=None, uninitialized=uninitialized, encoded_name=encoded_name,
**kwargs) | [
"def",
"BVS",
"(",
"name",
",",
"size",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"stride",
"=",
"None",
",",
"uninitialized",
"=",
"False",
",",
"#pylint:disable=redefined-builtin",
"explicit_name",
"=",
"None",
",",
"discrete_set",
"=",
"False",
",",
"discrete_set_max_card",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"stride",
"==",
"0",
"and",
"max",
"!=",
"min",
":",
"raise",
"ClaripyValueError",
"(",
"\"BVSes of stride 0 should have max == min\"",
")",
"if",
"type",
"(",
"name",
")",
"is",
"bytes",
":",
"name",
"=",
"name",
".",
"decode",
"(",
")",
"if",
"type",
"(",
"name",
")",
"is",
"not",
"str",
":",
"raise",
"TypeError",
"(",
"\"Name value for BVS must be a str, got %r\"",
"%",
"type",
"(",
"name",
")",
")",
"n",
"=",
"_make_name",
"(",
"name",
",",
"size",
",",
"False",
"if",
"explicit_name",
"is",
"None",
"else",
"explicit_name",
")",
"encoded_name",
"=",
"n",
".",
"encode",
"(",
")",
"if",
"not",
"discrete_set",
":",
"discrete_set_max_card",
"=",
"None",
"return",
"BV",
"(",
"'BVS'",
",",
"(",
"n",
",",
"min",
",",
"max",
",",
"stride",
",",
"uninitialized",
",",
"discrete_set",
",",
"discrete_set_max_card",
")",
",",
"variables",
"=",
"{",
"n",
"}",
",",
"length",
"=",
"size",
",",
"symbolic",
"=",
"True",
",",
"eager_backends",
"=",
"None",
",",
"uninitialized",
"=",
"uninitialized",
",",
"encoded_name",
"=",
"encoded_name",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/angr/claripy/blob/4c961b4dc664706be8142fe4868f27655bc8da77/claripy/ast/bv.py#L197-L236 |
|
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/smtplib.py | python | SMTP.set_debuglevel | (self, debuglevel) | Set the debug output level.
A non-false value results in debug messages for connection and for all
messages sent to and received from the server. | Set the debug output level. | [
"Set",
"the",
"debug",
"output",
"level",
"."
] | def set_debuglevel(self, debuglevel):
"""Set the debug output level.
A non-false value results in debug messages for connection and for all
messages sent to and received from the server.
"""
self.debuglevel = debuglevel | [
"def",
"set_debuglevel",
"(",
"self",
",",
"debuglevel",
")",
":",
"self",
".",
"debuglevel",
"=",
"debuglevel"
] | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/smtplib.py#L285-L292 |
||
tensorflow/models | 6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3 | official/recommendation/ranking/task.py | python | RankingTask.validation_step | (
self,
inputs: Dict[str, tf.Tensor],
model: tf.keras.Model,
metrics: Optional[List[tf.keras.metrics.Metric]] = None) | return model.test_step(inputs) | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def validation_step(
self,
inputs: Dict[str, tf.Tensor],
model: tf.keras.Model,
metrics: Optional[List[tf.keras.metrics.Metric]] = None) -> tf.Tensor:
"""See base class."""
# All metrics need to be passed through the RankingModel.
assert metrics == model.metrics
return model.test_step(inputs) | [
"def",
"validation_step",
"(",
"self",
",",
"inputs",
":",
"Dict",
"[",
"str",
",",
"tf",
".",
"Tensor",
"]",
",",
"model",
":",
"tf",
".",
"keras",
".",
"Model",
",",
"metrics",
":",
"Optional",
"[",
"List",
"[",
"tf",
".",
"keras",
".",
"metrics",
".",
"Metric",
"]",
"]",
"=",
"None",
")",
"->",
"tf",
".",
"Tensor",
":",
"# All metrics need to be passed through the RankingModel.",
"assert",
"metrics",
"==",
"model",
".",
"metrics",
"return",
"model",
".",
"test_step",
"(",
"inputs",
")"
] | https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/recommendation/ranking/task.py#L190-L198 |
|
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/bdf/subcase.py | python | Subcase.finish_subcase | (self) | Removes the subcase parameter from the subcase to avoid printing
it in a funny spot | Removes the subcase parameter from the subcase to avoid printing
it in a funny spot | [
"Removes",
"the",
"subcase",
"parameter",
"from",
"the",
"subcase",
"to",
"avoid",
"printing",
"it",
"in",
"a",
"funny",
"spot"
] | def finish_subcase(self):
"""
Removes the subcase parameter from the subcase to avoid printing
it in a funny spot
"""
if 'SUBCASE' in self.params:
del self.params['SUBCASE'] | [
"def",
"finish_subcase",
"(",
"self",
")",
":",
"if",
"'SUBCASE'",
"in",
"self",
".",
"params",
":",
"del",
"self",
".",
"params",
"[",
"'SUBCASE'",
"]"
] | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/subcase.py#L1044-L1050 |
||
statsmodels/statsmodels | debbe7ea6ba28fe5bdb78f09f8cac694bef98722 | statsmodels/genmod/families/links.py | python | CDFLink.inverse_deriv2 | (self, z) | return _approx_fprime_scalar(z, self.inverse_deriv, centered=True) | Second derivative of the inverse link function g^(-1)(z).
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g^(-1)''(z) : ndarray
The value of the second derivative of the inverse of the link
function
Notes
-----
This method should be overwritten by subclasses.
The inherited method is implemented through numerical differentiation. | Second derivative of the inverse link function g^(-1)(z). | [
"Second",
"derivative",
"of",
"the",
"inverse",
"link",
"function",
"g^",
"(",
"-",
"1",
")",
"(",
"z",
")",
"."
] | def inverse_deriv2(self, z):
"""
Second derivative of the inverse link function g^(-1)(z).
Parameters
----------
z : array_like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g^(-1)''(z) : ndarray
The value of the second derivative of the inverse of the link
function
Notes
-----
This method should be overwritten by subclasses.
The inherited method is implemented through numerical differentiation.
"""
from statsmodels.tools.numdiff import _approx_fprime_scalar
z = np.atleast_1d(z)
# Note: special function for norm.ppf does not support complex
return _approx_fprime_scalar(z, self.inverse_deriv, centered=True) | [
"def",
"inverse_deriv2",
"(",
"self",
",",
"z",
")",
":",
"from",
"statsmodels",
".",
"tools",
".",
"numdiff",
"import",
"_approx_fprime_scalar",
"z",
"=",
"np",
".",
"atleast_1d",
"(",
"z",
")",
"# Note: special function for norm.ppf does not support complex",
"return",
"_approx_fprime_scalar",
"(",
"z",
",",
"self",
".",
"inverse_deriv",
",",
"centered",
"=",
"True",
")"
] | https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/genmod/families/links.py#L710-L735 |
|
plasticityai/supersqlite | d74da749c6fa5df021df3968b854b9a59f829e17 | setup.py | python | source_for_module_with_pyinit | (module, parent_module='') | return os.path.relpath(source_file, PROJ_PATH) | Create PyInit symbols for shared objects compiled with Python's
Extension() | Create PyInit symbols for shared objects compiled with Python's
Extension() | [
"Create",
"PyInit",
"symbols",
"for",
"shared",
"objects",
"compiled",
"with",
"Python",
"s",
"Extension",
"()"
] | def source_for_module_with_pyinit(module, parent_module=''):
""" Create PyInit symbols for shared objects compiled with Python's
Extension()"""
source_path = os.path.join(BUILD_PATH, 'entrypoints')
try:
os.makedirs(source_path)
except BaseException:
pass
source_file = os.path.join(source_path, module + '.c')
with open(source_file, 'w+') as outfile:
outfile.write('''
void init''' + (parent_module + module) + '''(void) {} //Python 2.7
void PyInit_''' + (parent_module + module) + '''(void) {} //Python 3.5
''')
return os.path.relpath(source_file, PROJ_PATH) | [
"def",
"source_for_module_with_pyinit",
"(",
"module",
",",
"parent_module",
"=",
"''",
")",
":",
"source_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"BUILD_PATH",
",",
"'entrypoints'",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"source_path",
")",
"except",
"BaseException",
":",
"pass",
"source_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"source_path",
",",
"module",
"+",
"'.c'",
")",
"with",
"open",
"(",
"source_file",
",",
"'w+'",
")",
"as",
"outfile",
":",
"outfile",
".",
"write",
"(",
"'''\n void init'''",
"+",
"(",
"parent_module",
"+",
"module",
")",
"+",
"'''(void) {} //Python 2.7\n void PyInit_'''",
"+",
"(",
"parent_module",
"+",
"module",
")",
"+",
"'''(void) {} //Python 3.5\n '''",
")",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"source_file",
",",
"PROJ_PATH",
")"
] | https://github.com/plasticityai/supersqlite/blob/d74da749c6fa5df021df3968b854b9a59f829e17/setup.py#L798-L812 |
|
daoluan/decode-Django | d46a858b45b56de48b0355f50dd9e45402d04cfd | Django-1.5.1/django/contrib/gis/db/backends/oracle/operations.py | python | OracleOperations.spatial_lookup_sql | (self, lvalue, lookup_type, value, field, qn) | Returns the SQL WHERE clause for use in Oracle spatial SQL construction. | Returns the SQL WHERE clause for use in Oracle spatial SQL construction. | [
"Returns",
"the",
"SQL",
"WHERE",
"clause",
"for",
"use",
"in",
"Oracle",
"spatial",
"SQL",
"construction",
"."
] | def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
"Returns the SQL WHERE clause for use in Oracle spatial SQL construction."
alias, col, db_type = lvalue
# Getting the quoted table name as `geo_col`.
geo_col = '%s.%s' % (qn(alias), qn(col))
# See if a Oracle Geometry function matches the lookup type next
lookup_info = self.geometry_functions.get(lookup_type, False)
if lookup_info:
# Lookup types that are tuples take tuple arguments, e.g., 'relate' and
# 'dwithin' lookup types.
if isinstance(lookup_info, tuple):
# First element of tuple is lookup type, second element is the type
# of the expected argument (e.g., str, float)
sdo_op, arg_type = lookup_info
geom = value[0]
# Ensuring that a tuple _value_ was passed in from the user
if not isinstance(value, tuple):
raise ValueError('Tuple required for `%s` lookup type.' % lookup_type)
if len(value) != 2:
raise ValueError('2-element tuple required for %s lookup type.' % lookup_type)
# Ensuring the argument type matches what we expect.
if not isinstance(value[1], arg_type):
raise ValueError('Argument type should be %s, got %s instead.' % (arg_type, type(value[1])))
if lookup_type == 'relate':
# The SDORelate class handles construction for these queries,
# and verifies the mask argument.
return sdo_op(value[1]).as_sql(geo_col, self.get_geom_placeholder(field, geom))
else:
# Otherwise, just call the `as_sql` method on the SDOOperation instance.
return sdo_op.as_sql(geo_col, self.get_geom_placeholder(field, geom))
else:
# Lookup info is a SDOOperation instance, whose `as_sql` method returns
# the SQL necessary for the geometry function call. For example:
# SDO_CONTAINS("geoapp_country"."poly", SDO_GEOMTRY('POINT(5 23)', 4326)) = 'TRUE'
return lookup_info.as_sql(geo_col, self.get_geom_placeholder(field, value))
elif lookup_type == 'isnull':
# Handling 'isnull' lookup type
return "%s IS %sNULL" % (geo_col, (not value and 'NOT ' or ''))
raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type)) | [
"def",
"spatial_lookup_sql",
"(",
"self",
",",
"lvalue",
",",
"lookup_type",
",",
"value",
",",
"field",
",",
"qn",
")",
":",
"alias",
",",
"col",
",",
"db_type",
"=",
"lvalue",
"# Getting the quoted table name as `geo_col`.",
"geo_col",
"=",
"'%s.%s'",
"%",
"(",
"qn",
"(",
"alias",
")",
",",
"qn",
"(",
"col",
")",
")",
"# See if a Oracle Geometry function matches the lookup type next",
"lookup_info",
"=",
"self",
".",
"geometry_functions",
".",
"get",
"(",
"lookup_type",
",",
"False",
")",
"if",
"lookup_info",
":",
"# Lookup types that are tuples take tuple arguments, e.g., 'relate' and",
"# 'dwithin' lookup types.",
"if",
"isinstance",
"(",
"lookup_info",
",",
"tuple",
")",
":",
"# First element of tuple is lookup type, second element is the type",
"# of the expected argument (e.g., str, float)",
"sdo_op",
",",
"arg_type",
"=",
"lookup_info",
"geom",
"=",
"value",
"[",
"0",
"]",
"# Ensuring that a tuple _value_ was passed in from the user",
"if",
"not",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"raise",
"ValueError",
"(",
"'Tuple required for `%s` lookup type.'",
"%",
"lookup_type",
")",
"if",
"len",
"(",
"value",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'2-element tuple required for %s lookup type.'",
"%",
"lookup_type",
")",
"# Ensuring the argument type matches what we expect.",
"if",
"not",
"isinstance",
"(",
"value",
"[",
"1",
"]",
",",
"arg_type",
")",
":",
"raise",
"ValueError",
"(",
"'Argument type should be %s, got %s instead.'",
"%",
"(",
"arg_type",
",",
"type",
"(",
"value",
"[",
"1",
"]",
")",
")",
")",
"if",
"lookup_type",
"==",
"'relate'",
":",
"# The SDORelate class handles construction for these queries,",
"# and verifies the mask argument.",
"return",
"sdo_op",
"(",
"value",
"[",
"1",
"]",
")",
".",
"as_sql",
"(",
"geo_col",
",",
"self",
".",
"get_geom_placeholder",
"(",
"field",
",",
"geom",
")",
")",
"else",
":",
"# Otherwise, just call the `as_sql` method on the SDOOperation instance.",
"return",
"sdo_op",
".",
"as_sql",
"(",
"geo_col",
",",
"self",
".",
"get_geom_placeholder",
"(",
"field",
",",
"geom",
")",
")",
"else",
":",
"# Lookup info is a SDOOperation instance, whose `as_sql` method returns",
"# the SQL necessary for the geometry function call. For example:",
"# SDO_CONTAINS(\"geoapp_country\".\"poly\", SDO_GEOMTRY('POINT(5 23)', 4326)) = 'TRUE'",
"return",
"lookup_info",
".",
"as_sql",
"(",
"geo_col",
",",
"self",
".",
"get_geom_placeholder",
"(",
"field",
",",
"value",
")",
")",
"elif",
"lookup_type",
"==",
"'isnull'",
":",
"# Handling 'isnull' lookup type",
"return",
"\"%s IS %sNULL\"",
"%",
"(",
"geo_col",
",",
"(",
"not",
"value",
"and",
"'NOT '",
"or",
"''",
")",
")",
"raise",
"TypeError",
"(",
"\"Got invalid lookup_type: %s\"",
"%",
"repr",
"(",
"lookup_type",
")",
")"
] | https://github.com/daoluan/decode-Django/blob/d46a858b45b56de48b0355f50dd9e45402d04cfd/Django-1.5.1/django/contrib/gis/db/backends/oracle/operations.py#L223-L267 |
||
wistbean/learn_python3_spider | 73c873f4845f4385f097e5057407d03dd37a117b | stackoverflow/venv/lib/python3.6/site-packages/twisted/trial/_dist/disttrial.py | python | DistTrialRunner.run | (self, suite, reactor=None, cooperate=cooperate,
untilFailure=False) | return result | Spawn local worker processes and load tests. After that, run them.
@param suite: A tests suite to be run.
@param reactor: The reactor to use, to be customized in tests.
@type reactor: A provider of
L{twisted.internet.interfaces.IReactorProcess}
@param cooperate: The cooperate function to use, to be customized in
tests.
@type cooperate: C{function}
@param untilFailure: If C{True}, continue to run the tests until they
fail.
@type untilFailure: C{bool}.
@return: The test result.
@rtype: L{DistReporter} | Spawn local worker processes and load tests. After that, run them. | [
"Spawn",
"local",
"worker",
"processes",
"and",
"load",
"tests",
".",
"After",
"that",
"run",
"them",
"."
] | def run(self, suite, reactor=None, cooperate=cooperate,
untilFailure=False):
"""
Spawn local worker processes and load tests. After that, run them.
@param suite: A tests suite to be run.
@param reactor: The reactor to use, to be customized in tests.
@type reactor: A provider of
L{twisted.internet.interfaces.IReactorProcess}
@param cooperate: The cooperate function to use, to be customized in
tests.
@type cooperate: C{function}
@param untilFailure: If C{True}, continue to run the tests until they
fail.
@type untilFailure: C{bool}.
@return: The test result.
@rtype: L{DistReporter}
"""
if reactor is None:
from twisted.internet import reactor
result = self._makeResult()
count = suite.countTestCases()
self._stream.write("Running %d tests.\n" % (count,))
if not count:
# Take a shortcut if there is no test
suite.run(result.original)
self.writeResults(result)
return result
testDir, testDirLock = _unusedTestDirectory(
FilePath(self._workingDirectory))
workerNumber = min(count, self._workerNumber)
ampWorkers = [LocalWorkerAMP() for x in range(workerNumber)]
workers = self.createLocalWorkers(ampWorkers, testDir.path)
processEndDeferreds = [worker.endDeferred for worker in workers]
self.launchWorkerProcesses(reactor.spawnProcess, workers,
self._workerArguments)
def runTests():
testCases = iter(list(_iterateTests(suite)))
workerDeferreds = []
for worker in ampWorkers:
workerDeferreds.append(
self._driveWorker(worker, result, testCases,
cooperate=cooperate))
return DeferredList(workerDeferreds, consumeErrors=True,
fireOnOneErrback=True)
stopping = []
def nextRun(ign):
self.writeResults(result)
if not untilFailure:
return
if not result.wasSuccessful():
return
d = runTests()
return d.addCallback(nextRun)
def stop(ign):
testDirLock.unlock()
if not stopping:
stopping.append(None)
reactor.stop()
def beforeShutDown():
if not stopping:
stopping.append(None)
d = DeferredList(processEndDeferreds, consumeErrors=True)
return d.addCallback(continueShutdown)
def continueShutdown(ign):
self.writeResults(result)
return ign
d = runTests()
d.addCallback(nextRun)
d.addBoth(stop)
reactor.addSystemEventTrigger('before', 'shutdown', beforeShutDown)
reactor.run()
return result | [
"def",
"run",
"(",
"self",
",",
"suite",
",",
"reactor",
"=",
"None",
",",
"cooperate",
"=",
"cooperate",
",",
"untilFailure",
"=",
"False",
")",
":",
"if",
"reactor",
"is",
"None",
":",
"from",
"twisted",
".",
"internet",
"import",
"reactor",
"result",
"=",
"self",
".",
"_makeResult",
"(",
")",
"count",
"=",
"suite",
".",
"countTestCases",
"(",
")",
"self",
".",
"_stream",
".",
"write",
"(",
"\"Running %d tests.\\n\"",
"%",
"(",
"count",
",",
")",
")",
"if",
"not",
"count",
":",
"# Take a shortcut if there is no test",
"suite",
".",
"run",
"(",
"result",
".",
"original",
")",
"self",
".",
"writeResults",
"(",
"result",
")",
"return",
"result",
"testDir",
",",
"testDirLock",
"=",
"_unusedTestDirectory",
"(",
"FilePath",
"(",
"self",
".",
"_workingDirectory",
")",
")",
"workerNumber",
"=",
"min",
"(",
"count",
",",
"self",
".",
"_workerNumber",
")",
"ampWorkers",
"=",
"[",
"LocalWorkerAMP",
"(",
")",
"for",
"x",
"in",
"range",
"(",
"workerNumber",
")",
"]",
"workers",
"=",
"self",
".",
"createLocalWorkers",
"(",
"ampWorkers",
",",
"testDir",
".",
"path",
")",
"processEndDeferreds",
"=",
"[",
"worker",
".",
"endDeferred",
"for",
"worker",
"in",
"workers",
"]",
"self",
".",
"launchWorkerProcesses",
"(",
"reactor",
".",
"spawnProcess",
",",
"workers",
",",
"self",
".",
"_workerArguments",
")",
"def",
"runTests",
"(",
")",
":",
"testCases",
"=",
"iter",
"(",
"list",
"(",
"_iterateTests",
"(",
"suite",
")",
")",
")",
"workerDeferreds",
"=",
"[",
"]",
"for",
"worker",
"in",
"ampWorkers",
":",
"workerDeferreds",
".",
"append",
"(",
"self",
".",
"_driveWorker",
"(",
"worker",
",",
"result",
",",
"testCases",
",",
"cooperate",
"=",
"cooperate",
")",
")",
"return",
"DeferredList",
"(",
"workerDeferreds",
",",
"consumeErrors",
"=",
"True",
",",
"fireOnOneErrback",
"=",
"True",
")",
"stopping",
"=",
"[",
"]",
"def",
"nextRun",
"(",
"ign",
")",
":",
"self",
".",
"writeResults",
"(",
"result",
")",
"if",
"not",
"untilFailure",
":",
"return",
"if",
"not",
"result",
".",
"wasSuccessful",
"(",
")",
":",
"return",
"d",
"=",
"runTests",
"(",
")",
"return",
"d",
".",
"addCallback",
"(",
"nextRun",
")",
"def",
"stop",
"(",
"ign",
")",
":",
"testDirLock",
".",
"unlock",
"(",
")",
"if",
"not",
"stopping",
":",
"stopping",
".",
"append",
"(",
"None",
")",
"reactor",
".",
"stop",
"(",
")",
"def",
"beforeShutDown",
"(",
")",
":",
"if",
"not",
"stopping",
":",
"stopping",
".",
"append",
"(",
"None",
")",
"d",
"=",
"DeferredList",
"(",
"processEndDeferreds",
",",
"consumeErrors",
"=",
"True",
")",
"return",
"d",
".",
"addCallback",
"(",
"continueShutdown",
")",
"def",
"continueShutdown",
"(",
"ign",
")",
":",
"self",
".",
"writeResults",
"(",
"result",
")",
"return",
"ign",
"d",
"=",
"runTests",
"(",
")",
"d",
".",
"addCallback",
"(",
"nextRun",
")",
"d",
".",
"addBoth",
"(",
"stop",
")",
"reactor",
".",
"addSystemEventTrigger",
"(",
"'before'",
",",
"'shutdown'",
",",
"beforeShutDown",
")",
"reactor",
".",
"run",
"(",
")",
"return",
"result"
] | https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/trial/_dist/disttrial.py#L161-L249 |
|
Jack-Cherish/python-spider | 0d3b56b3ec179cac93155fc14cec815b3c963083 | bilibili/xml2ass.py | python | main | () | [] | def main():
if len(sys.argv) == 1:
sys.argv.append('--help')
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', metavar=_('OUTPUT'), help=_('Output file'))
parser.add_argument('-s', '--size', metavar=_('WIDTHxHEIGHT'), required=True, help=_('Stage size in pixels'))
parser.add_argument('-fn', '--font', metavar=_('FONT'), help=_('Specify font face [default: %s]') % _('(FONT) sans-serif')[7:], default=_('(FONT) sans-serif')[7:])
parser.add_argument('-fs', '--fontsize', metavar=_('SIZE'), help=(_('Default font size [default: %s]') % 25), type=float, default=25.0)
parser.add_argument('-a', '--alpha', metavar=_('ALPHA'), help=_('Text opacity'), type=float, default=1.0)
parser.add_argument('-l', '--lifetime', metavar=_('SECONDS'), help=_('Duration of comment display [default: %s]') % 5, type=float, default=5.0)
parser.add_argument('-p', '--protect', metavar=_('HEIGHT'), help=_('Reserve blank on the bottom of the stage'), type=int, default=0)
parser.add_argument('-r', '--reduce', action='store_true', help=_('Reduce the amount of comments if stage is full'))
parser.add_argument('file', metavar=_('FILE'), nargs='+', help=_('Comment file to be processed'))
args = parser.parse_args()
try:
width, height = str(args.size).split('x', 1)
width = int(width)
height = int(height)
except ValueError:
raise ValueError(_('Invalid stage size: %r') % args.size)
Danmaku2ASS(args.file, args.output, width, height, args.protect, args.font, args.fontsize, args.alpha, args.lifetime, args.reduce) | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"1",
":",
"sys",
".",
"argv",
".",
"append",
"(",
"'--help'",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-o'",
",",
"'--output'",
",",
"metavar",
"=",
"_",
"(",
"'OUTPUT'",
")",
",",
"help",
"=",
"_",
"(",
"'Output file'",
")",
")",
"parser",
".",
"add_argument",
"(",
"'-s'",
",",
"'--size'",
",",
"metavar",
"=",
"_",
"(",
"'WIDTHxHEIGHT'",
")",
",",
"required",
"=",
"True",
",",
"help",
"=",
"_",
"(",
"'Stage size in pixels'",
")",
")",
"parser",
".",
"add_argument",
"(",
"'-fn'",
",",
"'--font'",
",",
"metavar",
"=",
"_",
"(",
"'FONT'",
")",
",",
"help",
"=",
"_",
"(",
"'Specify font face [default: %s]'",
")",
"%",
"_",
"(",
"'(FONT) sans-serif'",
")",
"[",
"7",
":",
"]",
",",
"default",
"=",
"_",
"(",
"'(FONT) sans-serif'",
")",
"[",
"7",
":",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'-fs'",
",",
"'--fontsize'",
",",
"metavar",
"=",
"_",
"(",
"'SIZE'",
")",
",",
"help",
"=",
"(",
"_",
"(",
"'Default font size [default: %s]'",
")",
"%",
"25",
")",
",",
"type",
"=",
"float",
",",
"default",
"=",
"25.0",
")",
"parser",
".",
"add_argument",
"(",
"'-a'",
",",
"'--alpha'",
",",
"metavar",
"=",
"_",
"(",
"'ALPHA'",
")",
",",
"help",
"=",
"_",
"(",
"'Text opacity'",
")",
",",
"type",
"=",
"float",
",",
"default",
"=",
"1.0",
")",
"parser",
".",
"add_argument",
"(",
"'-l'",
",",
"'--lifetime'",
",",
"metavar",
"=",
"_",
"(",
"'SECONDS'",
")",
",",
"help",
"=",
"_",
"(",
"'Duration of comment display [default: %s]'",
")",
"%",
"5",
",",
"type",
"=",
"float",
",",
"default",
"=",
"5.0",
")",
"parser",
".",
"add_argument",
"(",
"'-p'",
",",
"'--protect'",
",",
"metavar",
"=",
"_",
"(",
"'HEIGHT'",
")",
",",
"help",
"=",
"_",
"(",
"'Reserve blank on the bottom of the stage'",
")",
",",
"type",
"=",
"int",
",",
"default",
"=",
"0",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--reduce'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"_",
"(",
"'Reduce the amount of comments if stage is full'",
")",
")",
"parser",
".",
"add_argument",
"(",
"'file'",
",",
"metavar",
"=",
"_",
"(",
"'FILE'",
")",
",",
"nargs",
"=",
"'+'",
",",
"help",
"=",
"_",
"(",
"'Comment file to be processed'",
")",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"try",
":",
"width",
",",
"height",
"=",
"str",
"(",
"args",
".",
"size",
")",
".",
"split",
"(",
"'x'",
",",
"1",
")",
"width",
"=",
"int",
"(",
"width",
")",
"height",
"=",
"int",
"(",
"height",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"_",
"(",
"'Invalid stage size: %r'",
")",
"%",
"args",
".",
"size",
")",
"Danmaku2ASS",
"(",
"args",
".",
"file",
",",
"args",
".",
"output",
",",
"width",
",",
"height",
",",
"args",
".",
"protect",
",",
"args",
".",
"font",
",",
"args",
".",
"fontsize",
",",
"args",
".",
"alpha",
",",
"args",
".",
"lifetime",
",",
"args",
".",
"reduce",
")"
] | https://github.com/Jack-Cherish/python-spider/blob/0d3b56b3ec179cac93155fc14cec815b3c963083/bilibili/xml2ass.py#L778-L798 |
||||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/wake_on_lan/switch.py | python | WolSwitch.is_on | (self) | return self._state | Return true if switch is on. | Return true if switch is on. | [
"Return",
"true",
"if",
"switch",
"is",
"on",
"."
] | def is_on(self):
"""Return true if switch is on."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/wake_on_lan/switch.py#L104-L106 |
|
hzlzh/AlfredWorkflow.com | 7055f14f6922c80ea5943839eb0caff11ae57255 | Sources/Workflows/ONE「一个」/workflow/update.py | python | get_valid_releases | (github_slug, prereleases=False) | return releases | Return list of all valid releases
:param github_slug: ``username/repo`` for workflow's GitHub repo
:param prereleases: Whether to include pre-releases.
:returns: list of dicts. Each :class:`dict` has the form
``{'version': '1.1', 'download_url': 'http://github.com/...',
'prerelease': False }``
A valid release is one that contains one ``.alfredworkflow`` file.
If the GitHub version (i.e. tag) is of the form ``v1.1``, the leading
``v`` will be stripped. | Return list of all valid releases | [
"Return",
"list",
"of",
"all",
"valid",
"releases"
] | def get_valid_releases(github_slug, prereleases=False):
"""Return list of all valid releases
:param github_slug: ``username/repo`` for workflow's GitHub repo
:param prereleases: Whether to include pre-releases.
:returns: list of dicts. Each :class:`dict` has the form
``{'version': '1.1', 'download_url': 'http://github.com/...',
'prerelease': False }``
A valid release is one that contains one ``.alfredworkflow`` file.
If the GitHub version (i.e. tag) is of the form ``v1.1``, the leading
``v`` will be stripped.
"""
api_url = build_api_url(github_slug)
releases = []
wf().logger.debug('Retrieving releases list from `{0}` ...'.format(
api_url))
def retrieve_releases():
wf().logger.info(
'Retrieving releases for `{0}` ...'.format(github_slug))
return web.get(api_url).json()
slug = github_slug.replace('/', '-')
for release in wf().cached_data('gh-releases-{0}'.format(slug),
retrieve_releases):
version = release['tag_name']
download_urls = []
for asset in release.get('assets', []):
url = asset.get('browser_download_url')
if not url or not url.endswith('.alfredworkflow'):
continue
download_urls.append(url)
# Validate release
if release['prerelease'] and not prereleases:
wf().logger.warning(
'Invalid release {0} : pre-release detected'.format(version))
continue
if not download_urls:
wf().logger.warning(
'Invalid release {0} : No workflow file'.format(version))
continue
if len(download_urls) > 1:
wf().logger.warning(
'Invalid release {0} : multiple workflow files'.format(version))
continue
wf().logger.debug('Release `{0}` : {1}'.format(version, url))
releases.append({
'version': version,
'download_url': download_urls[0],
'prerelease': release['prerelease']
})
return releases | [
"def",
"get_valid_releases",
"(",
"github_slug",
",",
"prereleases",
"=",
"False",
")",
":",
"api_url",
"=",
"build_api_url",
"(",
"github_slug",
")",
"releases",
"=",
"[",
"]",
"wf",
"(",
")",
".",
"logger",
".",
"debug",
"(",
"'Retrieving releases list from `{0}` ...'",
".",
"format",
"(",
"api_url",
")",
")",
"def",
"retrieve_releases",
"(",
")",
":",
"wf",
"(",
")",
".",
"logger",
".",
"info",
"(",
"'Retrieving releases for `{0}` ...'",
".",
"format",
"(",
"github_slug",
")",
")",
"return",
"web",
".",
"get",
"(",
"api_url",
")",
".",
"json",
"(",
")",
"slug",
"=",
"github_slug",
".",
"replace",
"(",
"'/'",
",",
"'-'",
")",
"for",
"release",
"in",
"wf",
"(",
")",
".",
"cached_data",
"(",
"'gh-releases-{0}'",
".",
"format",
"(",
"slug",
")",
",",
"retrieve_releases",
")",
":",
"version",
"=",
"release",
"[",
"'tag_name'",
"]",
"download_urls",
"=",
"[",
"]",
"for",
"asset",
"in",
"release",
".",
"get",
"(",
"'assets'",
",",
"[",
"]",
")",
":",
"url",
"=",
"asset",
".",
"get",
"(",
"'browser_download_url'",
")",
"if",
"not",
"url",
"or",
"not",
"url",
".",
"endswith",
"(",
"'.alfredworkflow'",
")",
":",
"continue",
"download_urls",
".",
"append",
"(",
"url",
")",
"# Validate release",
"if",
"release",
"[",
"'prerelease'",
"]",
"and",
"not",
"prereleases",
":",
"wf",
"(",
")",
".",
"logger",
".",
"warning",
"(",
"'Invalid release {0} : pre-release detected'",
".",
"format",
"(",
"version",
")",
")",
"continue",
"if",
"not",
"download_urls",
":",
"wf",
"(",
")",
".",
"logger",
".",
"warning",
"(",
"'Invalid release {0} : No workflow file'",
".",
"format",
"(",
"version",
")",
")",
"continue",
"if",
"len",
"(",
"download_urls",
")",
">",
"1",
":",
"wf",
"(",
")",
".",
"logger",
".",
"warning",
"(",
"'Invalid release {0} : multiple workflow files'",
".",
"format",
"(",
"version",
")",
")",
"continue",
"wf",
"(",
")",
".",
"logger",
".",
"debug",
"(",
"'Release `{0}` : {1}'",
".",
"format",
"(",
"version",
",",
"url",
")",
")",
"releases",
".",
"append",
"(",
"{",
"'version'",
":",
"version",
",",
"'download_url'",
":",
"download_urls",
"[",
"0",
"]",
",",
"'prerelease'",
":",
"release",
"[",
"'prerelease'",
"]",
"}",
")",
"return",
"releases"
] | https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/ONE「一个」/workflow/update.py#L211-L271 |
|
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/docutils-0.14/docutils/utils/math/math2html.py | python | Link.setmutualdestination | (self, destination) | Set another link as destination, and set its destination to this one. | Set another link as destination, and set its destination to this one. | [
"Set",
"another",
"link",
"as",
"destination",
"and",
"set",
"its",
"destination",
"to",
"this",
"one",
"."
] | def setmutualdestination(self, destination):
"Set another link as destination, and set its destination to this one."
self.destination = destination
destination.destination = self | [
"def",
"setmutualdestination",
"(",
"self",
",",
"destination",
")",
":",
"self",
".",
"destination",
"=",
"destination",
"destination",
".",
"destination",
"=",
"self"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/docutils-0.14/docutils/utils/math/math2html.py#L3799-L3802 |
||
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | lib-python/2.7/idlelib/configSectionNameDialog.py | python | GetCfgSectionNameDialog.__init__ | (self, parent, title, message, used_names, _htest=False) | message - string, informational message to display
used_names - string collection, names already in use for validity check
_htest - bool, change box location when running htest | message - string, informational message to display
used_names - string collection, names already in use for validity check
_htest - bool, change box location when running htest | [
"message",
"-",
"string",
"informational",
"message",
"to",
"display",
"used_names",
"-",
"string",
"collection",
"names",
"already",
"in",
"use",
"for",
"validity",
"check",
"_htest",
"-",
"bool",
"change",
"box",
"location",
"when",
"running",
"htest"
] | def __init__(self, parent, title, message, used_names, _htest=False):
"""
message - string, informational message to display
used_names - string collection, names already in use for validity check
_htest - bool, change box location when running htest
"""
Toplevel.__init__(self, parent)
self.configure(borderwidth=5)
self.resizable(height=FALSE, width=FALSE)
self.title(title)
self.transient(parent)
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self.Cancel)
self.parent = parent
self.message = message
self.used_names = used_names
self.create_widgets()
self.withdraw() #hide while setting geometry
self.update_idletasks()
#needs to be done here so that the winfo_reqwidth is valid
self.messageInfo.config(width=self.frameMain.winfo_reqwidth())
self.geometry(
"+%d+%d" % (
parent.winfo_rootx() +
(parent.winfo_width()/2 - self.winfo_reqwidth()/2),
parent.winfo_rooty() +
((parent.winfo_height()/2 - self.winfo_reqheight()/2)
if not _htest else 100)
) ) #centre dialog over parent (or below htest box)
self.deiconify() #geometry set, unhide
self.wait_window() | [
"def",
"__init__",
"(",
"self",
",",
"parent",
",",
"title",
",",
"message",
",",
"used_names",
",",
"_htest",
"=",
"False",
")",
":",
"Toplevel",
".",
"__init__",
"(",
"self",
",",
"parent",
")",
"self",
".",
"configure",
"(",
"borderwidth",
"=",
"5",
")",
"self",
".",
"resizable",
"(",
"height",
"=",
"FALSE",
",",
"width",
"=",
"FALSE",
")",
"self",
".",
"title",
"(",
"title",
")",
"self",
".",
"transient",
"(",
"parent",
")",
"self",
".",
"grab_set",
"(",
")",
"self",
".",
"protocol",
"(",
"\"WM_DELETE_WINDOW\"",
",",
"self",
".",
"Cancel",
")",
"self",
".",
"parent",
"=",
"parent",
"self",
".",
"message",
"=",
"message",
"self",
".",
"used_names",
"=",
"used_names",
"self",
".",
"create_widgets",
"(",
")",
"self",
".",
"withdraw",
"(",
")",
"#hide while setting geometry",
"self",
".",
"update_idletasks",
"(",
")",
"#needs to be done here so that the winfo_reqwidth is valid",
"self",
".",
"messageInfo",
".",
"config",
"(",
"width",
"=",
"self",
".",
"frameMain",
".",
"winfo_reqwidth",
"(",
")",
")",
"self",
".",
"geometry",
"(",
"\"+%d+%d\"",
"%",
"(",
"parent",
".",
"winfo_rootx",
"(",
")",
"+",
"(",
"parent",
".",
"winfo_width",
"(",
")",
"/",
"2",
"-",
"self",
".",
"winfo_reqwidth",
"(",
")",
"/",
"2",
")",
",",
"parent",
".",
"winfo_rooty",
"(",
")",
"+",
"(",
"(",
"parent",
".",
"winfo_height",
"(",
")",
"/",
"2",
"-",
"self",
".",
"winfo_reqheight",
"(",
")",
"/",
"2",
")",
"if",
"not",
"_htest",
"else",
"100",
")",
")",
")",
"#centre dialog over parent (or below htest box)",
"self",
".",
"deiconify",
"(",
")",
"#geometry set, unhide",
"self",
".",
"wait_window",
"(",
")"
] | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/idlelib/configSectionNameDialog.py#L10-L40 |
||
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/gunicorn-19.9.0/gunicorn/http/message.py | python | Request.proxy_protocol | (self, line) | return True | \
Detect, check and parse proxy protocol.
:raises: ForbiddenProxyRequest, InvalidProxyLine.
:return: True for proxy protocol line else False | \
Detect, check and parse proxy protocol. | [
"\\",
"Detect",
"check",
"and",
"parse",
"proxy",
"protocol",
"."
] | def proxy_protocol(self, line):
"""\
Detect, check and parse proxy protocol.
:raises: ForbiddenProxyRequest, InvalidProxyLine.
:return: True for proxy protocol line else False
"""
if not self.cfg.proxy_protocol:
return False
if self.req_number != 1:
return False
if not line.startswith("PROXY"):
return False
self.proxy_protocol_access_check()
self.parse_proxy_protocol(line)
return True | [
"def",
"proxy_protocol",
"(",
"self",
",",
"line",
")",
":",
"if",
"not",
"self",
".",
"cfg",
".",
"proxy_protocol",
":",
"return",
"False",
"if",
"self",
".",
"req_number",
"!=",
"1",
":",
"return",
"False",
"if",
"not",
"line",
".",
"startswith",
"(",
"\"PROXY\"",
")",
":",
"return",
"False",
"self",
".",
"proxy_protocol_access_check",
"(",
")",
"self",
".",
"parse_proxy_protocol",
"(",
"line",
")",
"return",
"True"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/gunicorn-19.9.0/gunicorn/http/message.py#L254-L273 |
|
alkaline-ml/pmdarima | cafd5c79f1e5696c609716eca1514f0aaaf2d317 | pmdarima/arima/seasonality.py | python | OCSBTest._do_lag | (y, lag, omit_na=True) | return out | Perform the TS lagging | Perform the TS lagging | [
"Perform",
"the",
"TS",
"lagging"
] | def _do_lag(y, lag, omit_na=True):
"""Perform the TS lagging"""
n = y.shape[0]
if lag == 1:
return y.reshape(n, 1)
# Create a 2d array of dims (n + (lag - 1), lag). This looks cryptic..
# If there are tons of lags, this may not be super efficient...
out = np.ones((n + (lag - 1), lag)) * np.nan
for i in range(lag):
out[i:i + n, i] = y
if omit_na:
out = out[~np.isnan(out).any(axis=1)]
return out | [
"def",
"_do_lag",
"(",
"y",
",",
"lag",
",",
"omit_na",
"=",
"True",
")",
":",
"n",
"=",
"y",
".",
"shape",
"[",
"0",
"]",
"if",
"lag",
"==",
"1",
":",
"return",
"y",
".",
"reshape",
"(",
"n",
",",
"1",
")",
"# Create a 2d array of dims (n + (lag - 1), lag). This looks cryptic..",
"# If there are tons of lags, this may not be super efficient...",
"out",
"=",
"np",
".",
"ones",
"(",
"(",
"n",
"+",
"(",
"lag",
"-",
"1",
")",
",",
"lag",
")",
")",
"*",
"np",
".",
"nan",
"for",
"i",
"in",
"range",
"(",
"lag",
")",
":",
"out",
"[",
"i",
":",
"i",
"+",
"n",
",",
"i",
"]",
"=",
"y",
"if",
"omit_na",
":",
"out",
"=",
"out",
"[",
"~",
"np",
".",
"isnan",
"(",
"out",
")",
".",
"any",
"(",
"axis",
"=",
"1",
")",
"]",
"return",
"out"
] | https://github.com/alkaline-ml/pmdarima/blob/cafd5c79f1e5696c609716eca1514f0aaaf2d317/pmdarima/arima/seasonality.py#L439-L453 |
|
openstack/python-neutronclient | 517bef2c5454dde2eba5cc2194ee857be6be7164 | neutronclient/v2_0/client.py | python | Client.create_router | (self, body=None) | return self.post(self.routers_path, body=body) | Creates a new router. | Creates a new router. | [
"Creates",
"a",
"new",
"router",
"."
] | def create_router(self, body=None):
"""Creates a new router."""
return self.post(self.routers_path, body=body) | [
"def",
"create_router",
"(",
"self",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"post",
"(",
"self",
".",
"routers_path",
",",
"body",
"=",
"body",
")"
] | https://github.com/openstack/python-neutronclient/blob/517bef2c5454dde2eba5cc2194ee857be6be7164/neutronclient/v2_0/client.py#L933-L935 |
|
KhronosGroup/OpenXR-SDK-Source | 76756e2e7849b15466d29bee7d80cada92865550 | external/python/jinja2/compiler.py | python | CodeGenerator.fail | (self, msg, lineno) | Fail with a :exc:`TemplateAssertionError`. | Fail with a :exc:`TemplateAssertionError`. | [
"Fail",
"with",
"a",
":",
"exc",
":",
"TemplateAssertionError",
"."
] | def fail(self, msg, lineno):
"""Fail with a :exc:`TemplateAssertionError`."""
raise TemplateAssertionError(msg, lineno, self.name, self.filename) | [
"def",
"fail",
"(",
"self",
",",
"msg",
",",
"lineno",
")",
":",
"raise",
"TemplateAssertionError",
"(",
"msg",
",",
"lineno",
",",
"self",
".",
"name",
",",
"self",
".",
"filename",
")"
] | https://github.com/KhronosGroup/OpenXR-SDK-Source/blob/76756e2e7849b15466d29bee7d80cada92865550/external/python/jinja2/compiler.py#L313-L315 |
||
kubernetes-client/python | 47b9da9de2d02b2b7a34fbe05afb44afd130d73a | kubernetes/client/models/v1_pod_spec.py | python | V1PodSpec.host_aliases | (self, host_aliases) | Sets the host_aliases of this V1PodSpec.
HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts file if specified. This is only valid for non-hostNetwork pods. # noqa: E501
:param host_aliases: The host_aliases of this V1PodSpec. # noqa: E501
:type: list[V1HostAlias] | Sets the host_aliases of this V1PodSpec. | [
"Sets",
"the",
"host_aliases",
"of",
"this",
"V1PodSpec",
"."
] | def host_aliases(self, host_aliases):
"""Sets the host_aliases of this V1PodSpec.
HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts file if specified. This is only valid for non-hostNetwork pods. # noqa: E501
:param host_aliases: The host_aliases of this V1PodSpec. # noqa: E501
:type: list[V1HostAlias]
"""
self._host_aliases = host_aliases | [
"def",
"host_aliases",
"(",
"self",
",",
"host_aliases",
")",
":",
"self",
".",
"_host_aliases",
"=",
"host_aliases"
] | https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_pod_spec.py#L418-L427 |
||
pwnieexpress/pwn_plug_sources | 1a23324f5dc2c3de20f9c810269b6a29b2758cad | src/wifitap/scapy.py | python | TracerouteResult.graph | (self, ASN=1, padding=0, **kargs) | x.graph(ASN=1, other args):
ASN=0 : no clustering
ASN=1 : use whois.cymru.net AS clustering
ASN=2 : use whois.ra.net AS clustering
graph: GraphViz graph description
type: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option
target: filename or redirect. Defaults pipe to Imagemagick's display program
prog: which graphviz program to use | x.graph(ASN=1, other args):
ASN=0 : no clustering
ASN=1 : use whois.cymru.net AS clustering
ASN=2 : use whois.ra.net AS clustering
graph: GraphViz graph description
type: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option
target: filename or redirect. Defaults pipe to Imagemagick's display program
prog: which graphviz program to use | [
"x",
".",
"graph",
"(",
"ASN",
"=",
"1",
"other",
"args",
")",
":",
"ASN",
"=",
"0",
":",
"no",
"clustering",
"ASN",
"=",
"1",
":",
"use",
"whois",
".",
"cymru",
".",
"net",
"AS",
"clustering",
"ASN",
"=",
"2",
":",
"use",
"whois",
".",
"ra",
".",
"net",
"AS",
"clustering",
"graph",
":",
"GraphViz",
"graph",
"description",
"type",
":",
"output",
"type",
"(",
"svg",
"ps",
"gif",
"jpg",
"etc",
".",
")",
"passed",
"to",
"dot",
"s",
"-",
"T",
"option",
"target",
":",
"filename",
"or",
"redirect",
".",
"Defaults",
"pipe",
"to",
"Imagemagick",
"s",
"display",
"program",
"prog",
":",
"which",
"graphviz",
"program",
"to",
"use"
] | def graph(self, ASN=1, padding=0, **kargs):
"""x.graph(ASN=1, other args):
ASN=0 : no clustering
ASN=1 : use whois.cymru.net AS clustering
ASN=2 : use whois.ra.net AS clustering
graph: GraphViz graph description
type: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option
target: filename or redirect. Defaults pipe to Imagemagick's display program
prog: which graphviz program to use"""
if (self.graphdef is None or
self.graphASN != ASN or
self.graphpadding != padding):
self.make_graph(ASN,padding)
do_graph(self.graphdef, **kargs) | [
"def",
"graph",
"(",
"self",
",",
"ASN",
"=",
"1",
",",
"padding",
"=",
"0",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"(",
"self",
".",
"graphdef",
"is",
"None",
"or",
"self",
".",
"graphASN",
"!=",
"ASN",
"or",
"self",
".",
"graphpadding",
"!=",
"padding",
")",
":",
"self",
".",
"make_graph",
"(",
"ASN",
",",
"padding",
")",
"do_graph",
"(",
"self",
".",
"graphdef",
",",
"*",
"*",
"kargs",
")"
] | https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/wifitap/scapy.py#L3597-L3611 |
||
yqyao/SSD_Pytorch | 6060bbb650e7a1df7c12d7c9650a38eaba4ab6a8 | utils/box_utils.py | python | intersect | (box_a, box_b) | return inter[:, :, 0] * inter[:, :, 1] | We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b.
Args:
box_a: (tensor) bounding boxes, Shape: [A,4].
box_b: (tensor) bounding boxes, Shape: [B,4].
Return:
(tensor) intersection area, Shape: [A,B]. | We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b.
Args:
box_a: (tensor) bounding boxes, Shape: [A,4].
box_b: (tensor) bounding boxes, Shape: [B,4].
Return:
(tensor) intersection area, Shape: [A,B]. | [
"We",
"resize",
"both",
"tensors",
"to",
"[",
"A",
"B",
"2",
"]",
"without",
"new",
"malloc",
":",
"[",
"A",
"2",
"]",
"-",
">",
"[",
"A",
"1",
"2",
"]",
"-",
">",
"[",
"A",
"B",
"2",
"]",
"[",
"B",
"2",
"]",
"-",
">",
"[",
"1",
"B",
"2",
"]",
"-",
">",
"[",
"A",
"B",
"2",
"]",
"Then",
"we",
"compute",
"the",
"area",
"of",
"intersect",
"between",
"box_a",
"and",
"box_b",
".",
"Args",
":",
"box_a",
":",
"(",
"tensor",
")",
"bounding",
"boxes",
"Shape",
":",
"[",
"A",
"4",
"]",
".",
"box_b",
":",
"(",
"tensor",
")",
"bounding",
"boxes",
"Shape",
":",
"[",
"B",
"4",
"]",
".",
"Return",
":",
"(",
"tensor",
")",
"intersection",
"area",
"Shape",
":",
"[",
"A",
"B",
"]",
"."
] | def intersect(box_a, box_b):
""" We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b.
Args:
box_a: (tensor) bounding boxes, Shape: [A,4].
box_b: (tensor) bounding boxes, Shape: [B,4].
Return:
(tensor) intersection area, Shape: [A,B].
"""
# print(box_a)
A = box_a.size(0)
B = box_b.size(0)
max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),
box_b[:, 2:].unsqueeze(0).expand(A, B, 2))
min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),
box_b[:, :2].unsqueeze(0).expand(A, B, 2))
inter = torch.clamp((max_xy - min_xy), min=0)
return inter[:, :, 0] * inter[:, :, 1] | [
"def",
"intersect",
"(",
"box_a",
",",
"box_b",
")",
":",
"# print(box_a)",
"A",
"=",
"box_a",
".",
"size",
"(",
"0",
")",
"B",
"=",
"box_b",
".",
"size",
"(",
"0",
")",
"max_xy",
"=",
"torch",
".",
"min",
"(",
"box_a",
"[",
":",
",",
"2",
":",
"]",
".",
"unsqueeze",
"(",
"1",
")",
".",
"expand",
"(",
"A",
",",
"B",
",",
"2",
")",
",",
"box_b",
"[",
":",
",",
"2",
":",
"]",
".",
"unsqueeze",
"(",
"0",
")",
".",
"expand",
"(",
"A",
",",
"B",
",",
"2",
")",
")",
"min_xy",
"=",
"torch",
".",
"max",
"(",
"box_a",
"[",
":",
",",
":",
"2",
"]",
".",
"unsqueeze",
"(",
"1",
")",
".",
"expand",
"(",
"A",
",",
"B",
",",
"2",
")",
",",
"box_b",
"[",
":",
",",
":",
"2",
"]",
".",
"unsqueeze",
"(",
"0",
")",
".",
"expand",
"(",
"A",
",",
"B",
",",
"2",
")",
")",
"inter",
"=",
"torch",
".",
"clamp",
"(",
"(",
"max_xy",
"-",
"min_xy",
")",
",",
"min",
"=",
"0",
")",
"return",
"inter",
"[",
":",
",",
":",
",",
"0",
"]",
"*",
"inter",
"[",
":",
",",
":",
",",
"1",
"]"
] | https://github.com/yqyao/SSD_Pytorch/blob/6060bbb650e7a1df7c12d7c9650a38eaba4ab6a8/utils/box_utils.py#L100-L119 |
|
Tencent/QT4A | cc99ce12bd10f864c95b7bf0675fd1b757bce4bb | qt4a/systemui.py | python | CrashWindow.close | (self) | 关闭 | 关闭 | [
"关闭"
] | def close(self):
'''关闭
'''
self.Controls['确定'].click() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"Controls",
"[",
"'确定'].cl",
"i",
"c",
"k()",
"",
""
] | https://github.com/Tencent/QT4A/blob/cc99ce12bd10f864c95b7bf0675fd1b757bce4bb/qt4a/systemui.py#L105-L108 |
||
tensorflow/models | 6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3 | official/vision/beta/serving/export_tflite_lib.py | python | representative_dataset | (
params: cfg.ExperimentConfig,
calibration_steps: int = 2000) | Creates representative dataset for input calibration.
Args:
params: An ExperimentConfig.
calibration_steps: The steps to do calibration.
Yields:
An input image tensor. | Creates representative dataset for input calibration. | [
"Creates",
"representative",
"dataset",
"for",
"input",
"calibration",
"."
] | def representative_dataset(
params: cfg.ExperimentConfig,
calibration_steps: int = 2000) -> Iterator[List[tf.Tensor]]:
""""Creates representative dataset for input calibration.
Args:
params: An ExperimentConfig.
calibration_steps: The steps to do calibration.
Yields:
An input image tensor.
"""
dataset = create_representative_dataset(params=params)
for image, _ in dataset.take(calibration_steps):
# Skip images that do not have 3 channels.
if image.shape[-1] != 3:
continue
yield [image] | [
"def",
"representative_dataset",
"(",
"params",
":",
"cfg",
".",
"ExperimentConfig",
",",
"calibration_steps",
":",
"int",
"=",
"2000",
")",
"->",
"Iterator",
"[",
"List",
"[",
"tf",
".",
"Tensor",
"]",
"]",
":",
"dataset",
"=",
"create_representative_dataset",
"(",
"params",
"=",
"params",
")",
"for",
"image",
",",
"_",
"in",
"dataset",
".",
"take",
"(",
"calibration_steps",
")",
":",
"# Skip images that do not have 3 channels.",
"if",
"image",
".",
"shape",
"[",
"-",
"1",
"]",
"!=",
"3",
":",
"continue",
"yield",
"[",
"image",
"]"
] | https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/official/vision/beta/serving/export_tflite_lib.py#L60-L77 |
||
matplotlib/matplotlib | 8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322 | lib/matplotlib/offsetbox.py | python | OffsetImage.get_offset | (self) | return self._offset | Return offset of the container. | Return offset of the container. | [
"Return",
"offset",
"of",
"the",
"container",
"."
] | def get_offset(self):
"""Return offset of the container."""
return self._offset | [
"def",
"get_offset",
"(",
"self",
")",
":",
"return",
"self",
".",
"_offset"
] | https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/offsetbox.py#L1234-L1236 |
|
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/datetime.py | python | datetime.isoformat | (self, sep='T', timespec='auto') | return s | Return the time formatted according to ISO.
The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmm'.
By default, the fractional part is omitted if self.microsecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM'.
Optional argument sep specifies the separator between date and
time, default 'T'.
The optional argument timespec specifies the number of additional
terms of the time to include. | Return the time formatted according to ISO. | [
"Return",
"the",
"time",
"formatted",
"according",
"to",
"ISO",
"."
] | def isoformat(self, sep='T', timespec='auto'):
"""Return the time formatted according to ISO.
The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmm'.
By default, the fractional part is omitted if self.microsecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM'.
Optional argument sep specifies the separator between date and
time, default 'T'.
The optional argument timespec specifies the number of additional
terms of the time to include.
"""
s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day, sep) +
_format_time(self._hour, self._minute, self._second,
self._microsecond, timespec))
off = self.utcoffset()
tz = _format_offset(off)
if tz:
s += tz
return s | [
"def",
"isoformat",
"(",
"self",
",",
"sep",
"=",
"'T'",
",",
"timespec",
"=",
"'auto'",
")",
":",
"s",
"=",
"(",
"\"%04d-%02d-%02d%c\"",
"%",
"(",
"self",
".",
"_year",
",",
"self",
".",
"_month",
",",
"self",
".",
"_day",
",",
"sep",
")",
"+",
"_format_time",
"(",
"self",
".",
"_hour",
",",
"self",
".",
"_minute",
",",
"self",
".",
"_second",
",",
"self",
".",
"_microsecond",
",",
"timespec",
")",
")",
"off",
"=",
"self",
".",
"utcoffset",
"(",
")",
"tz",
"=",
"_format_offset",
"(",
"off",
")",
"if",
"tz",
":",
"s",
"+=",
"tz",
"return",
"s"
] | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/datetime.py#L1892-L1916 |
|
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/core/numerictypes.py | python | obj2sctype | (rep, default=None) | return res.type | Return the scalar dtype or NumPy equivalent of Python type of an object.
Parameters
----------
rep : any
The object of which the type is returned.
default : any, optional
If given, this is returned for objects whose types can not be
determined. If not given, None is returned for those objects.
Returns
-------
dtype : dtype or Python type
The data type of `rep`.
See Also
--------
sctype2char, issctype, issubsctype, issubdtype, maximum_sctype
Examples
--------
>>> np.obj2sctype(np.int32)
<type 'numpy.int32'>
>>> np.obj2sctype(np.array([1., 2.]))
<type 'numpy.float64'>
>>> np.obj2sctype(np.array([1.j]))
<type 'numpy.complex128'>
>>> np.obj2sctype(dict)
<type 'numpy.object_'>
>>> np.obj2sctype('string')
<type 'numpy.string_'>
>>> np.obj2sctype(1, default=list)
<type 'list'> | Return the scalar dtype or NumPy equivalent of Python type of an object. | [
"Return",
"the",
"scalar",
"dtype",
"or",
"NumPy",
"equivalent",
"of",
"Python",
"type",
"of",
"an",
"object",
"."
] | def obj2sctype(rep, default=None):
"""
Return the scalar dtype or NumPy equivalent of Python type of an object.
Parameters
----------
rep : any
The object of which the type is returned.
default : any, optional
If given, this is returned for objects whose types can not be
determined. If not given, None is returned for those objects.
Returns
-------
dtype : dtype or Python type
The data type of `rep`.
See Also
--------
sctype2char, issctype, issubsctype, issubdtype, maximum_sctype
Examples
--------
>>> np.obj2sctype(np.int32)
<type 'numpy.int32'>
>>> np.obj2sctype(np.array([1., 2.]))
<type 'numpy.float64'>
>>> np.obj2sctype(np.array([1.j]))
<type 'numpy.complex128'>
>>> np.obj2sctype(dict)
<type 'numpy.object_'>
>>> np.obj2sctype('string')
<type 'numpy.string_'>
>>> np.obj2sctype(1, default=list)
<type 'list'>
"""
try:
if issubclass(rep, generic):
return rep
except TypeError:
pass
if isinstance(rep, dtype):
return rep.type
if isinstance(rep, type):
return _python_type(rep)
if isinstance(rep, ndarray):
return rep.dtype.type
try:
res = dtype(rep)
except:
return default
return res.type | [
"def",
"obj2sctype",
"(",
"rep",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"if",
"issubclass",
"(",
"rep",
",",
"generic",
")",
":",
"return",
"rep",
"except",
"TypeError",
":",
"pass",
"if",
"isinstance",
"(",
"rep",
",",
"dtype",
")",
":",
"return",
"rep",
".",
"type",
"if",
"isinstance",
"(",
"rep",
",",
"type",
")",
":",
"return",
"_python_type",
"(",
"rep",
")",
"if",
"isinstance",
"(",
"rep",
",",
"ndarray",
")",
":",
"return",
"rep",
".",
"dtype",
".",
"type",
"try",
":",
"res",
"=",
"dtype",
"(",
"rep",
")",
"except",
":",
"return",
"default",
"return",
"res",
".",
"type"
] | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/core/numerictypes.py#L611-L665 |
|
playframework/play1 | 0ecac3bc2421ae2dbec27a368bf671eda1c9cba5 | python/Lib/decimal.py | python | Decimal.__rpow__ | (self, other, context=None) | return other.__pow__(self, context=context) | Swaps self/other and returns __pow__. | Swaps self/other and returns __pow__. | [
"Swaps",
"self",
"/",
"other",
"and",
"returns",
"__pow__",
"."
] | def __rpow__(self, other, context=None):
"""Swaps self/other and returns __pow__."""
other = _convert_other(other)
if other is NotImplemented:
return other
return other.__pow__(self, context=context) | [
"def",
"__rpow__",
"(",
"self",
",",
"other",
",",
"context",
"=",
"None",
")",
":",
"other",
"=",
"_convert_other",
"(",
"other",
")",
"if",
"other",
"is",
"NotImplemented",
":",
"return",
"other",
"return",
"other",
".",
"__pow__",
"(",
"self",
",",
"context",
"=",
"context",
")"
] | https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/decimal.py#L2388-L2393 |
|
qiucheng025/zao- | 3a5edf3607b3a523f95746bc69b688090c76d89a | lib/gui/wrapper.py | python | FaceswapControl.execute_script | (self, command, args) | Execute the requested Faceswap Script | Execute the requested Faceswap Script | [
"Execute",
"the",
"requested",
"Faceswap",
"Script"
] | def execute_script(self, command, args):
""" Execute the requested Faceswap Script """
logger.debug("Executing Faceswap: (command: '%s', args: %s)", command, args)
self.thread = None
self.command = command
kwargs = {"stdout": PIPE,
"stderr": PIPE,
"bufsize": 1,
"universal_newlines": True}
self.process = Popen(args, **kwargs, stdin=PIPE)
self.thread_stdout()
self.thread_stderr()
logger.debug("Executed Faceswap") | [
"def",
"execute_script",
"(",
"self",
",",
"command",
",",
"args",
")",
":",
"logger",
".",
"debug",
"(",
"\"Executing Faceswap: (command: '%s', args: %s)\"",
",",
"command",
",",
"args",
")",
"self",
".",
"thread",
"=",
"None",
"self",
".",
"command",
"=",
"command",
"kwargs",
"=",
"{",
"\"stdout\"",
":",
"PIPE",
",",
"\"stderr\"",
":",
"PIPE",
",",
"\"bufsize\"",
":",
"1",
",",
"\"universal_newlines\"",
":",
"True",
"}",
"self",
".",
"process",
"=",
"Popen",
"(",
"args",
",",
"*",
"*",
"kwargs",
",",
"stdin",
"=",
"PIPE",
")",
"self",
".",
"thread_stdout",
"(",
")",
"self",
".",
"thread_stderr",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Executed Faceswap\"",
")"
] | https://github.com/qiucheng025/zao-/blob/3a5edf3607b3a523f95746bc69b688090c76d89a/lib/gui/wrapper.py#L158-L171 |
||
fluentpython/notebooks | 0f6e1e8d1686743dacd9281df7c5b5921812010a | 01-data-model/vector2d.py | python | Vector.__mul__ | (self, scalar) | return Vector(self.x * scalar, self.y * scalar) | [] | def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar) | [
"def",
"__mul__",
"(",
"self",
",",
"scalar",
")",
":",
"return",
"Vector",
"(",
"self",
".",
"x",
"*",
"scalar",
",",
"self",
".",
"y",
"*",
"scalar",
")"
] | https://github.com/fluentpython/notebooks/blob/0f6e1e8d1686743dacd9281df7c5b5921812010a/01-data-model/vector2d.py#L23-L24 |
|||
google/rekall | 55d1925f2df9759a989b35271b4fa48fc54a1c86 | rekall-core/rekall/plugins/overlays/windows/common.py | python | _EPROCESS.is_valid | (self) | return True | Validate the _EPROCESS. | Validate the _EPROCESS. | [
"Validate",
"the",
"_EPROCESS",
"."
] | def is_valid(self):
"""Validate the _EPROCESS."""
pid = self.pid
# PID must be in a reasonable range.
if pid < 0 or pid > 0xFFFF:
return False
# Since we're not validating memory pages anymore it's important
# to weed out zero'd structs.
if ((pid == 0 or self.CreateTime == 0) and
self.ImageFileName not in ("Idle", "System")):
return False
# Dispatch header must be for a process object.
if self.Pcb.Header.Type != "ProcessObject":
return False
return True | [
"def",
"is_valid",
"(",
"self",
")",
":",
"pid",
"=",
"self",
".",
"pid",
"# PID must be in a reasonable range.",
"if",
"pid",
"<",
"0",
"or",
"pid",
">",
"0xFFFF",
":",
"return",
"False",
"# Since we're not validating memory pages anymore it's important",
"# to weed out zero'd structs.",
"if",
"(",
"(",
"pid",
"==",
"0",
"or",
"self",
".",
"CreateTime",
"==",
"0",
")",
"and",
"self",
".",
"ImageFileName",
"not",
"in",
"(",
"\"Idle\"",
",",
"\"System\"",
")",
")",
":",
"return",
"False",
"# Dispatch header must be for a process object.",
"if",
"self",
".",
"Pcb",
".",
"Header",
".",
"Type",
"!=",
"\"ProcessObject\"",
":",
"return",
"False",
"return",
"True"
] | https://github.com/google/rekall/blob/55d1925f2df9759a989b35271b4fa48fc54a1c86/rekall-core/rekall/plugins/overlays/windows/common.py#L748-L766 |
|
naftaliharris/tauthon | 5587ceec329b75f7caf6d65a036db61ac1bae214 | Lib/typing.py | python | _TypeAlias.__init__ | (self, name, type_var, impl_type, type_checker) | Initializer.
Args:
name: The name, e.g. 'Pattern'.
type_var: The type parameter, e.g. AnyStr, or the
specific type, e.g. str.
impl_type: The implementation type.
type_checker: Function that takes an impl_type instance.
and returns a value that should be a type_var instance. | Initializer. | [
"Initializer",
"."
] | def __init__(self, name, type_var, impl_type, type_checker):
"""Initializer.
Args:
name: The name, e.g. 'Pattern'.
type_var: The type parameter, e.g. AnyStr, or the
specific type, e.g. str.
impl_type: The implementation type.
type_checker: Function that takes an impl_type instance.
and returns a value that should be a type_var instance.
"""
assert isinstance(name, basestring), repr(name)
assert isinstance(impl_type, type), repr(impl_type)
assert not isinstance(impl_type, TypingMeta), repr(impl_type)
assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
self.name = name
self.type_var = type_var
self.impl_type = impl_type
self.type_checker = type_checker | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"type_var",
",",
"impl_type",
",",
"type_checker",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
",",
"repr",
"(",
"name",
")",
"assert",
"isinstance",
"(",
"impl_type",
",",
"type",
")",
",",
"repr",
"(",
"impl_type",
")",
"assert",
"not",
"isinstance",
"(",
"impl_type",
",",
"TypingMeta",
")",
",",
"repr",
"(",
"impl_type",
")",
"assert",
"isinstance",
"(",
"type_var",
",",
"(",
"type",
",",
"_TypingBase",
")",
")",
",",
"repr",
"(",
"type_var",
")",
"self",
".",
"name",
"=",
"name",
"self",
".",
"type_var",
"=",
"type_var",
"self",
".",
"impl_type",
"=",
"impl_type",
"self",
".",
"type_checker",
"=",
"type_checker"
] | https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/typing.py#L245-L263 |
||
iiau-tracker/SPLT | a196e603798e9be969d9d985c087c11cad1cda43 | train_Verifier/experiments/triplet_pairs.py | python | get_two_samples | (type) | return (roi1,roi2) | instruction | instruction | [
"instruction"
] | def get_two_samples(type):
'''instruction'''
'''pick up 1 object from a specific type'''
object_idx = np.random.randint(0, type_video_dict[type]['num_track_ids'], 1)[0]
track_id = type_video_dict[type]['track_ids'][object_idx]
track_id_num_frames = type_video_dict[type]['num_frames'][object_idx]
'''pick up 2 frame from above video'''
chosen_frame_idx1,chosen_frame_idx2 = np.random.randint(0, track_id_num_frames, 2)
roi1 = get_roi(type, object_idx, chosen_frame_idx1, track_id)
roi2 = get_roi(type, object_idx, chosen_frame_idx2, track_id)
return (roi1,roi2) | [
"def",
"get_two_samples",
"(",
"type",
")",
":",
"'''pick up 1 object from a specific type'''",
"object_idx",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"type_video_dict",
"[",
"type",
"]",
"[",
"'num_track_ids'",
"]",
",",
"1",
")",
"[",
"0",
"]",
"track_id",
"=",
"type_video_dict",
"[",
"type",
"]",
"[",
"'track_ids'",
"]",
"[",
"object_idx",
"]",
"track_id_num_frames",
"=",
"type_video_dict",
"[",
"type",
"]",
"[",
"'num_frames'",
"]",
"[",
"object_idx",
"]",
"'''pick up 2 frame from above video'''",
"chosen_frame_idx1",
",",
"chosen_frame_idx2",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"track_id_num_frames",
",",
"2",
")",
"roi1",
"=",
"get_roi",
"(",
"type",
",",
"object_idx",
",",
"chosen_frame_idx1",
",",
"track_id",
")",
"roi2",
"=",
"get_roi",
"(",
"type",
",",
"object_idx",
",",
"chosen_frame_idx2",
",",
"track_id",
")",
"return",
"(",
"roi1",
",",
"roi2",
")"
] | https://github.com/iiau-tracker/SPLT/blob/a196e603798e9be969d9d985c087c11cad1cda43/train_Verifier/experiments/triplet_pairs.py#L104-L114 |
|
natashamjaques/neural_chat | ddb977bb4602a67c460d02231e7bbf7b2cb49a97 | ParlAI/parlai/agents/tfidf_retriever/utils.py | python | filter_ngram | (gram, mode='any') | Decide whether to keep or discard an n-gram.
Args:
gram: list of tokens (length N)
mode: Option to throw out ngram if
'any': any single token passes filter_word
'all': all tokens pass filter_word
'ends': book-ended by filterable tokens | Decide whether to keep or discard an n-gram. | [
"Decide",
"whether",
"to",
"keep",
"or",
"discard",
"an",
"n",
"-",
"gram",
"."
] | def filter_ngram(gram, mode='any'):
"""Decide whether to keep or discard an n-gram.
Args:
gram: list of tokens (length N)
mode: Option to throw out ngram if
'any': any single token passes filter_word
'all': all tokens pass filter_word
'ends': book-ended by filterable tokens
"""
filtered = [filter_word(w) for w in gram]
if mode == 'any':
return any(filtered)
elif mode == 'all':
return all(filtered)
elif mode == 'ends':
return filtered[0] or filtered[-1]
else:
raise ValueError('Invalid mode: %s' % mode) | [
"def",
"filter_ngram",
"(",
"gram",
",",
"mode",
"=",
"'any'",
")",
":",
"filtered",
"=",
"[",
"filter_word",
"(",
"w",
")",
"for",
"w",
"in",
"gram",
"]",
"if",
"mode",
"==",
"'any'",
":",
"return",
"any",
"(",
"filtered",
")",
"elif",
"mode",
"==",
"'all'",
":",
"return",
"all",
"(",
"filtered",
")",
"elif",
"mode",
"==",
"'ends'",
":",
"return",
"filtered",
"[",
"0",
"]",
"or",
"filtered",
"[",
"-",
"1",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid mode: %s'",
"%",
"mode",
")"
] | https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/agents/tfidf_retriever/utils.py#L261-L279 |
||
mars-project/mars | 6afd7ed86db77f29cc9470485698ef192ecc6d33 | mars/deploy/oscar/session.py | python | AbstractAsyncSession.execute | (self, *tileables, **kwargs) | Execute tileables.
Parameters
----------
tileables
Tileables.
kwargs | Execute tileables. | [
"Execute",
"tileables",
"."
] | async def execute(self, *tileables, **kwargs) -> ExecutionInfo:
"""
Execute tileables.
Parameters
----------
tileables
Tileables.
kwargs
""" | [
"async",
"def",
"execute",
"(",
"self",
",",
"*",
"tileables",
",",
"*",
"*",
"kwargs",
")",
"->",
"ExecutionInfo",
":"
] | https://github.com/mars-project/mars/blob/6afd7ed86db77f29cc9470485698ef192ecc6d33/mars/deploy/oscar/session.py#L228-L237 |
||
rndusr/stig | 334f03e2e3eda7c1856dd5489f0265a47b9861b6 | stig/tui/views/base.py | python | ListWidgetBase.sort | (self) | return self._sort | *Sorter object or `None` to keep list items unsorted | *Sorter object or `None` to keep list items unsorted | [
"*",
"Sorter",
"object",
"or",
"None",
"to",
"keep",
"list",
"items",
"unsorted"
] | def sort(self):
"""*Sorter object or `None` to keep list items unsorted"""
return self._sort | [
"def",
"sort",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sort"
] | https://github.com/rndusr/stig/blob/334f03e2e3eda7c1856dd5489f0265a47b9861b6/stig/tui/views/base.py#L346-L348 |
|
deanishe/alfred-fakeum | 12a7e64d9c099c0f11416ee99fae064d6360aab2 | src/libs/faker/providers/date_time/__init__.py | python | Provider.date_time_between_dates | (
self,
datetime_start=None,
datetime_end=None,
tzinfo=None) | return pick | Takes two DateTime objects and returns a random datetime between the two
given datetimes.
Accepts DateTime objects.
:param datetime_start: DateTime
:param datetime_end: DateTime
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('1999-02-02 11:42:52')
:return DateTime | Takes two DateTime objects and returns a random datetime between the two
given datetimes.
Accepts DateTime objects. | [
"Takes",
"two",
"DateTime",
"objects",
"and",
"returns",
"a",
"random",
"datetime",
"between",
"the",
"two",
"given",
"datetimes",
".",
"Accepts",
"DateTime",
"objects",
"."
] | def date_time_between_dates(
self,
datetime_start=None,
datetime_end=None,
tzinfo=None):
"""
Takes two DateTime objects and returns a random datetime between the two
given datetimes.
Accepts DateTime objects.
:param datetime_start: DateTime
:param datetime_end: DateTime
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('1999-02-02 11:42:52')
:return DateTime
"""
if datetime_start is None:
datetime_start = datetime.now(tzinfo)
if datetime_end is None:
datetime_end = datetime.now(tzinfo)
timestamp = self.generator.random.randint(
datetime_to_timestamp(datetime_start),
datetime_to_timestamp(datetime_end),
)
try:
if tzinfo is None:
pick = datetime.fromtimestamp(timestamp, tzlocal())
pick = pick.astimezone(tzutc()).replace(tzinfo=None)
else:
pick = datetime.fromtimestamp(timestamp, tzinfo)
except OverflowError:
raise OverflowError(
"You specified an end date with a timestamp bigger than the maximum allowed on this"
" system. Please specify an earlier date.",
)
return pick | [
"def",
"date_time_between_dates",
"(",
"self",
",",
"datetime_start",
"=",
"None",
",",
"datetime_end",
"=",
"None",
",",
"tzinfo",
"=",
"None",
")",
":",
"if",
"datetime_start",
"is",
"None",
":",
"datetime_start",
"=",
"datetime",
".",
"now",
"(",
"tzinfo",
")",
"if",
"datetime_end",
"is",
"None",
":",
"datetime_end",
"=",
"datetime",
".",
"now",
"(",
"tzinfo",
")",
"timestamp",
"=",
"self",
".",
"generator",
".",
"random",
".",
"randint",
"(",
"datetime_to_timestamp",
"(",
"datetime_start",
")",
",",
"datetime_to_timestamp",
"(",
"datetime_end",
")",
",",
")",
"try",
":",
"if",
"tzinfo",
"is",
"None",
":",
"pick",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
",",
"tzlocal",
"(",
")",
")",
"pick",
"=",
"pick",
".",
"astimezone",
"(",
"tzutc",
"(",
")",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"else",
":",
"pick",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
",",
"tzinfo",
")",
"except",
"OverflowError",
":",
"raise",
"OverflowError",
"(",
"\"You specified an end date with a timestamp bigger than the maximum allowed on this\"",
"\" system. Please specify an earlier date.\"",
",",
")",
"return",
"pick"
] | https://github.com/deanishe/alfred-fakeum/blob/12a7e64d9c099c0f11416ee99fae064d6360aab2/src/libs/faker/providers/date_time/__init__.py#L1645-L1682 |
|
python-attrs/cattrs | 50ba769c8349f5891b157d2bb7f06602822ac0a3 | src/cattr/converters.py | python | Converter.register_structure_hook_func | (
self,
check_func: Callable[[Type[T]], bool],
func: Callable[[Any, Type[T]], T],
) | Register a class-to-primitive converter function for a class, using
a function to check if it's a match. | Register a class-to-primitive converter function for a class, using
a function to check if it's a match. | [
"Register",
"a",
"class",
"-",
"to",
"-",
"primitive",
"converter",
"function",
"for",
"a",
"class",
"using",
"a",
"function",
"to",
"check",
"if",
"it",
"s",
"a",
"match",
"."
] | def register_structure_hook_func(
self,
check_func: Callable[[Type[T]], bool],
func: Callable[[Any, Type[T]], T],
):
"""Register a class-to-primitive converter function for a class, using
a function to check if it's a match.
"""
self._structure_func.register_func_list([(check_func, func)]) | [
"def",
"register_structure_hook_func",
"(",
"self",
",",
"check_func",
":",
"Callable",
"[",
"[",
"Type",
"[",
"T",
"]",
"]",
",",
"bool",
"]",
",",
"func",
":",
"Callable",
"[",
"[",
"Any",
",",
"Type",
"[",
"T",
"]",
"]",
",",
"T",
"]",
",",
")",
":",
"self",
".",
"_structure_func",
".",
"register_func_list",
"(",
"[",
"(",
"check_func",
",",
"func",
")",
"]",
")"
] | https://github.com/python-attrs/cattrs/blob/50ba769c8349f5891b157d2bb7f06602822ac0a3/src/cattr/converters.py#L271-L279 |
||
kbandla/ImmunityDebugger | 2abc03fb15c8f3ed0914e1175c4d8933977c73e3 | 1.83/Libs/immlib.py | python | Debugger.getCurrentAddress | (self) | return debugger.get_current_address() | Get the current address been focus on the disasm window
@rtype: DWORD
@return: Address | Get the current address been focus on the disasm window | [
"Get",
"the",
"current",
"address",
"been",
"focus",
"on",
"the",
"disasm",
"window"
] | def getCurrentAddress(self):
"""
Get the current address been focus on the disasm window
@rtype: DWORD
@return: Address
"""
return debugger.get_current_address() | [
"def",
"getCurrentAddress",
"(",
"self",
")",
":",
"return",
"debugger",
".",
"get_current_address",
"(",
")"
] | https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.83/Libs/immlib.py#L1112-L1119 |
|
realpython/book2-exercises | cde325eac8e6d8cff2316601c2e5b36bb46af7d0 | py2manager/gluon/contrib/simplejson/__init__.py | python | loads | (s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None,
use_decimal=False, **kw) | return cls(encoding=encoding, **kw).decode(s) | Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
*encoding* determines the encoding used to interpret any
:class:`str` objects decoded by this instance (``'utf-8'`` by
default). It has no effect when decoding :class:`unicode` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as :class:`unicode`.
*object_hook*, if specified, will be called with the result of every
JSON object decoded and its return value will be used in place of the
given :class:`dict`. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
*object_pairs_hook* is an optional function that will be called with
the result of any object literal decode with an ordered list of pairs.
The return value of *object_pairs_hook* will be used instead of the
:class:`dict`. This feature can be used to implement custom decoders
that rely on the order that the key and value pairs are decoded (for
example, :func:`collections.OrderedDict` will remember the order of
insertion). If *object_hook* is also defined, the *object_pairs_hook*
takes priority.
*parse_float*, if specified, will be called with the string of every
JSON float to be decoded. By default, this is equivalent to
``float(num_str)``. This can be used to use another datatype or parser
for JSON floats (e.g. :class:`decimal.Decimal`).
*parse_int*, if specified, will be called with the string of every
JSON int to be decoded. By default, this is equivalent to
``int(num_str)``. This can be used to use another datatype or parser
for JSON integers (e.g. :class:`float`).
*parse_constant*, if specified, will be called with one of the
following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This
can be used to raise an exception if invalid JSON numbers are
encountered.
If *use_decimal* is true (default: ``False``) then it implies
parse_float=decimal.Decimal for parity with ``dump``.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg. | Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object. | [
"Deserialize",
"s",
"(",
"a",
"str",
"or",
"unicode",
"instance",
"containing",
"a",
"JSON",
"document",
")",
"to",
"a",
"Python",
"object",
"."
] | def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None,
use_decimal=False, **kw):
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
*encoding* determines the encoding used to interpret any
:class:`str` objects decoded by this instance (``'utf-8'`` by
default). It has no effect when decoding :class:`unicode` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as :class:`unicode`.
*object_hook*, if specified, will be called with the result of every
JSON object decoded and its return value will be used in place of the
given :class:`dict`. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
*object_pairs_hook* is an optional function that will be called with
the result of any object literal decode with an ordered list of pairs.
The return value of *object_pairs_hook* will be used instead of the
:class:`dict`. This feature can be used to implement custom decoders
that rely on the order that the key and value pairs are decoded (for
example, :func:`collections.OrderedDict` will remember the order of
insertion). If *object_hook* is also defined, the *object_pairs_hook*
takes priority.
*parse_float*, if specified, will be called with the string of every
JSON float to be decoded. By default, this is equivalent to
``float(num_str)``. This can be used to use another datatype or parser
for JSON floats (e.g. :class:`decimal.Decimal`).
*parse_int*, if specified, will be called with the string of every
JSON int to be decoded. By default, this is equivalent to
``int(num_str)``. This can be used to use another datatype or parser
for JSON integers (e.g. :class:`float`).
*parse_constant*, if specified, will be called with one of the
following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This
can be used to raise an exception if invalid JSON numbers are
encountered.
If *use_decimal* is true (default: ``False``) then it implies
parse_float=decimal.Decimal for parity with ``dump``.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
if (cls is None and encoding is None and object_hook is None and
parse_int is None and parse_float is None and
parse_constant is None and object_pairs_hook is None
and not use_decimal and not kw):
return _default_decoder.decode(s)
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
if object_pairs_hook is not None:
kw['object_pairs_hook'] = object_pairs_hook
if parse_float is not None:
kw['parse_float'] = parse_float
if parse_int is not None:
kw['parse_int'] = parse_int
if parse_constant is not None:
kw['parse_constant'] = parse_constant
if use_decimal:
if parse_float is not None:
raise TypeError("use_decimal=True implies parse_float=Decimal")
kw['parse_float'] = Decimal
return cls(encoding=encoding, **kw).decode(s) | [
"def",
"loads",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"object_hook",
"=",
"None",
",",
"parse_float",
"=",
"None",
",",
"parse_int",
"=",
"None",
",",
"parse_constant",
"=",
"None",
",",
"object_pairs_hook",
"=",
"None",
",",
"use_decimal",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"if",
"(",
"cls",
"is",
"None",
"and",
"encoding",
"is",
"None",
"and",
"object_hook",
"is",
"None",
"and",
"parse_int",
"is",
"None",
"and",
"parse_float",
"is",
"None",
"and",
"parse_constant",
"is",
"None",
"and",
"object_pairs_hook",
"is",
"None",
"and",
"not",
"use_decimal",
"and",
"not",
"kw",
")",
":",
"return",
"_default_decoder",
".",
"decode",
"(",
"s",
")",
"if",
"cls",
"is",
"None",
":",
"cls",
"=",
"JSONDecoder",
"if",
"object_hook",
"is",
"not",
"None",
":",
"kw",
"[",
"'object_hook'",
"]",
"=",
"object_hook",
"if",
"object_pairs_hook",
"is",
"not",
"None",
":",
"kw",
"[",
"'object_pairs_hook'",
"]",
"=",
"object_pairs_hook",
"if",
"parse_float",
"is",
"not",
"None",
":",
"kw",
"[",
"'parse_float'",
"]",
"=",
"parse_float",
"if",
"parse_int",
"is",
"not",
"None",
":",
"kw",
"[",
"'parse_int'",
"]",
"=",
"parse_int",
"if",
"parse_constant",
"is",
"not",
"None",
":",
"kw",
"[",
"'parse_constant'",
"]",
"=",
"parse_constant",
"if",
"use_decimal",
":",
"if",
"parse_float",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"\"use_decimal=True implies parse_float=Decimal\"",
")",
"kw",
"[",
"'parse_float'",
"]",
"=",
"Decimal",
"return",
"cls",
"(",
"encoding",
"=",
"encoding",
",",
"*",
"*",
"kw",
")",
".",
"decode",
"(",
"s",
")"
] | https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/py2manager/gluon/contrib/simplejson/__init__.py#L333-L403 |
|
smicallef/spiderfoot | fd4bf9394c9ab3ecc90adc3115c56349fb23165b | sflib.py | python | SpiderFoot.urlFQDN | (self, url: str) | return baseurl.split('/')[count].lower() | Extract the FQDN from a URL.
Args:
url (str): URL
Returns:
str: FQDN | Extract the FQDN from a URL. | [
"Extract",
"the",
"FQDN",
"from",
"a",
"URL",
"."
] | def urlFQDN(self, url: str) -> str:
"""Extract the FQDN from a URL.
Args:
url (str): URL
Returns:
str: FQDN
"""
if not url:
self.error(f"Invalid URL: {url}")
return None
baseurl = self.urlBaseUrl(url)
if '://' in baseurl:
count = 2
else:
count = 0
# http://abc.com will split to ['http:', '', 'abc.com']
return baseurl.split('/')[count].lower() | [
"def",
"urlFQDN",
"(",
"self",
",",
"url",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"url",
":",
"self",
".",
"error",
"(",
"f\"Invalid URL: {url}\"",
")",
"return",
"None",
"baseurl",
"=",
"self",
".",
"urlBaseUrl",
"(",
"url",
")",
"if",
"'://'",
"in",
"baseurl",
":",
"count",
"=",
"2",
"else",
":",
"count",
"=",
"0",
"# http://abc.com will split to ['http:', '', 'abc.com']",
"return",
"baseurl",
".",
"split",
"(",
"'/'",
")",
"[",
"count",
"]",
".",
"lower",
"(",
")"
] | https://github.com/smicallef/spiderfoot/blob/fd4bf9394c9ab3ecc90adc3115c56349fb23165b/sflib.py#L696-L716 |
|
maas/maas | db2f89970c640758a51247c59bf1ec6f60cf4ab5 | src/maasserver/storage_custom.py | python | _get_size | (size: str) | return bytes_value | Return size in bytes from a string.
It supports M, G, T suffixes. | Return size in bytes from a string. | [
"Return",
"size",
"in",
"bytes",
"from",
"a",
"string",
"."
] | def _get_size(size: str) -> int:
"""Return size in bytes from a string.
It supports M, G, T suffixes.
"""
multipliers = {
"M": 1000 ** 2,
"G": 1000 ** 3,
"T": 1000 ** 4,
}
try:
value, multiplier = size[:-1], size[-1]
value = float(value)
bytes_value = int(value * multipliers[multiplier])
except (IndexError, KeyError, ValueError):
raise ConfigError(f"Invalid size '{size}'")
if bytes_value <= 0:
raise ConfigError(f"Invalid negative size '{size}'")
return bytes_value | [
"def",
"_get_size",
"(",
"size",
":",
"str",
")",
"->",
"int",
":",
"multipliers",
"=",
"{",
"\"M\"",
":",
"1000",
"**",
"2",
",",
"\"G\"",
":",
"1000",
"**",
"3",
",",
"\"T\"",
":",
"1000",
"**",
"4",
",",
"}",
"try",
":",
"value",
",",
"multiplier",
"=",
"size",
"[",
":",
"-",
"1",
"]",
",",
"size",
"[",
"-",
"1",
"]",
"value",
"=",
"float",
"(",
"value",
")",
"bytes_value",
"=",
"int",
"(",
"value",
"*",
"multipliers",
"[",
"multiplier",
"]",
")",
"except",
"(",
"IndexError",
",",
"KeyError",
",",
"ValueError",
")",
":",
"raise",
"ConfigError",
"(",
"f\"Invalid size '{size}'\"",
")",
"if",
"bytes_value",
"<=",
"0",
":",
"raise",
"ConfigError",
"(",
"f\"Invalid negative size '{size}'\"",
")",
"return",
"bytes_value"
] | https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/maasserver/storage_custom.py#L536-L554 |
|
HKUST-Aerial-Robotics/Stereo-RCNN | 63c6ab98b7a5e36c7bcfdec4529804fc940ee900 | lib/model/rpn/proposal_layer.py | python | _ProposalLayer._filter_boxes | (self, boxes, min_size) | return keep | Remove all boxes with any side smaller than min_size. | Remove all boxes with any side smaller than min_size. | [
"Remove",
"all",
"boxes",
"with",
"any",
"side",
"smaller",
"than",
"min_size",
"."
] | def _filter_boxes(self, boxes, min_size):
"""Remove all boxes with any side smaller than min_size."""
ws = boxes[:, :, 2] - boxes[:, :, 0] + 1
hs = boxes[:, :, 3] - boxes[:, :, 1] + 1
keep = ((ws >= min_size) & (hs >= min_size))
return keep | [
"def",
"_filter_boxes",
"(",
"self",
",",
"boxes",
",",
"min_size",
")",
":",
"ws",
"=",
"boxes",
"[",
":",
",",
":",
",",
"2",
"]",
"-",
"boxes",
"[",
":",
",",
":",
",",
"0",
"]",
"+",
"1",
"hs",
"=",
"boxes",
"[",
":",
",",
":",
",",
"3",
"]",
"-",
"boxes",
"[",
":",
",",
":",
",",
"1",
"]",
"+",
"1",
"keep",
"=",
"(",
"(",
"ws",
">=",
"min_size",
")",
"&",
"(",
"hs",
">=",
"min_size",
")",
")",
"return",
"keep"
] | https://github.com/HKUST-Aerial-Robotics/Stereo-RCNN/blob/63c6ab98b7a5e36c7bcfdec4529804fc940ee900/lib/model/rpn/proposal_layer.py#L155-L160 |
|
henkelis/sonospy | 841f52010fd6e1e932d8f1a8896ad4e5a0667b8a | web2py/gluon/sql.py | python | sqlhtml_validators | (field) | return requires | Field type validation, using web2py's validators mechanism.
makes sure the content of a field is in line with the declared
fieldtype | Field type validation, using web2py's validators mechanism. | [
"Field",
"type",
"validation",
"using",
"web2py",
"s",
"validators",
"mechanism",
"."
] | def sqlhtml_validators(field):
"""
Field type validation, using web2py's validators mechanism.
makes sure the content of a field is in line with the declared
fieldtype
"""
field_type, field_length = field.type, field.length
if isinstance(field_type, SQLCustomType):
if hasattr(field_type,'validator'):
return field_type.validator
else:
field_type = field_type.type
elif not isinstance(field_type,str):
return []
requires=[]
if field_type == 'string':
requires.append(validators.IS_LENGTH(field_length))
elif field_type == 'text':
requires.append(validators.IS_LENGTH(2 ** 16))
elif field_type == 'password':
requires.append(validators.IS_LENGTH(field_length))
elif field_type == 'double':
requires.append(validators.IS_FLOAT_IN_RANGE(-1e100, 1e100))
elif field_type == 'integer':
requires.append(validators.IS_INT_IN_RANGE(-1e100, 1e100))
elif field_type[:7] == 'decimal':
requires.append(validators.IS_DECIMAL_IN_RANGE(-10**10, 10**10))
elif field_type == 'date':
requires.append(validators.IS_DATE())
elif field_type == 'time':
requires.append(validators.IS_TIME())
elif field_type == 'datetime':
requires.append(validators.IS_DATETIME())
elif field._db and field_type[:9] == 'reference' and \
field_type.find('.')<0 and \
field_type[10:] in field._db.tables:
referenced = field._db[field_type[10:]]
if hasattr(referenced,'_format') and referenced._format:
def f(r,id):
row=r[id]
if not row:
return id
elif isinstance(r._format,str):
return r._format % row
else:
return r._format(row)
field.represent = lambda id, r=referenced, f=f: f(r,id)
requires = validators.IS_IN_DB(field._db,referenced.id,
referenced._format)
if field.unique:
requires._and = validators.IS_NOT_IN_DB(field._db,field)
return requires
if field.unique:
requires.insert(0,validators.IS_NOT_IN_DB(field._db,field))
sff=['in','do','da','ti','de']
if field.notnull and not field_type[:2] in sff:
requires.insert(0,validators.IS_NOT_EMPTY())
elif not field.notnull and field_type[:2] in sff and requires:
requires[-1]=validators.IS_EMPTY_OR(requires[-1])
return requires | [
"def",
"sqlhtml_validators",
"(",
"field",
")",
":",
"field_type",
",",
"field_length",
"=",
"field",
".",
"type",
",",
"field",
".",
"length",
"if",
"isinstance",
"(",
"field_type",
",",
"SQLCustomType",
")",
":",
"if",
"hasattr",
"(",
"field_type",
",",
"'validator'",
")",
":",
"return",
"field_type",
".",
"validator",
"else",
":",
"field_type",
"=",
"field_type",
".",
"type",
"elif",
"not",
"isinstance",
"(",
"field_type",
",",
"str",
")",
":",
"return",
"[",
"]",
"requires",
"=",
"[",
"]",
"if",
"field_type",
"==",
"'string'",
":",
"requires",
".",
"append",
"(",
"validators",
".",
"IS_LENGTH",
"(",
"field_length",
")",
")",
"elif",
"field_type",
"==",
"'text'",
":",
"requires",
".",
"append",
"(",
"validators",
".",
"IS_LENGTH",
"(",
"2",
"**",
"16",
")",
")",
"elif",
"field_type",
"==",
"'password'",
":",
"requires",
".",
"append",
"(",
"validators",
".",
"IS_LENGTH",
"(",
"field_length",
")",
")",
"elif",
"field_type",
"==",
"'double'",
":",
"requires",
".",
"append",
"(",
"validators",
".",
"IS_FLOAT_IN_RANGE",
"(",
"-",
"1e100",
",",
"1e100",
")",
")",
"elif",
"field_type",
"==",
"'integer'",
":",
"requires",
".",
"append",
"(",
"validators",
".",
"IS_INT_IN_RANGE",
"(",
"-",
"1e100",
",",
"1e100",
")",
")",
"elif",
"field_type",
"[",
":",
"7",
"]",
"==",
"'decimal'",
":",
"requires",
".",
"append",
"(",
"validators",
".",
"IS_DECIMAL_IN_RANGE",
"(",
"-",
"10",
"**",
"10",
",",
"10",
"**",
"10",
")",
")",
"elif",
"field_type",
"==",
"'date'",
":",
"requires",
".",
"append",
"(",
"validators",
".",
"IS_DATE",
"(",
")",
")",
"elif",
"field_type",
"==",
"'time'",
":",
"requires",
".",
"append",
"(",
"validators",
".",
"IS_TIME",
"(",
")",
")",
"elif",
"field_type",
"==",
"'datetime'",
":",
"requires",
".",
"append",
"(",
"validators",
".",
"IS_DATETIME",
"(",
")",
")",
"elif",
"field",
".",
"_db",
"and",
"field_type",
"[",
":",
"9",
"]",
"==",
"'reference'",
"and",
"field_type",
".",
"find",
"(",
"'.'",
")",
"<",
"0",
"and",
"field_type",
"[",
"10",
":",
"]",
"in",
"field",
".",
"_db",
".",
"tables",
":",
"referenced",
"=",
"field",
".",
"_db",
"[",
"field_type",
"[",
"10",
":",
"]",
"]",
"if",
"hasattr",
"(",
"referenced",
",",
"'_format'",
")",
"and",
"referenced",
".",
"_format",
":",
"def",
"f",
"(",
"r",
",",
"id",
")",
":",
"row",
"=",
"r",
"[",
"id",
"]",
"if",
"not",
"row",
":",
"return",
"id",
"elif",
"isinstance",
"(",
"r",
".",
"_format",
",",
"str",
")",
":",
"return",
"r",
".",
"_format",
"%",
"row",
"else",
":",
"return",
"r",
".",
"_format",
"(",
"row",
")",
"field",
".",
"represent",
"=",
"lambda",
"id",
",",
"r",
"=",
"referenced",
",",
"f",
"=",
"f",
":",
"f",
"(",
"r",
",",
"id",
")",
"requires",
"=",
"validators",
".",
"IS_IN_DB",
"(",
"field",
".",
"_db",
",",
"referenced",
".",
"id",
",",
"referenced",
".",
"_format",
")",
"if",
"field",
".",
"unique",
":",
"requires",
".",
"_and",
"=",
"validators",
".",
"IS_NOT_IN_DB",
"(",
"field",
".",
"_db",
",",
"field",
")",
"return",
"requires",
"if",
"field",
".",
"unique",
":",
"requires",
".",
"insert",
"(",
"0",
",",
"validators",
".",
"IS_NOT_IN_DB",
"(",
"field",
".",
"_db",
",",
"field",
")",
")",
"sff",
"=",
"[",
"'in'",
",",
"'do'",
",",
"'da'",
",",
"'ti'",
",",
"'de'",
"]",
"if",
"field",
".",
"notnull",
"and",
"not",
"field_type",
"[",
":",
"2",
"]",
"in",
"sff",
":",
"requires",
".",
"insert",
"(",
"0",
",",
"validators",
".",
"IS_NOT_EMPTY",
"(",
")",
")",
"elif",
"not",
"field",
".",
"notnull",
"and",
"field_type",
"[",
":",
"2",
"]",
"in",
"sff",
"and",
"requires",
":",
"requires",
"[",
"-",
"1",
"]",
"=",
"validators",
".",
"IS_EMPTY_OR",
"(",
"requires",
"[",
"-",
"1",
"]",
")",
"return",
"requires"
] | https://github.com/henkelis/sonospy/blob/841f52010fd6e1e932d8f1a8896ad4e5a0667b8a/web2py/gluon/sql.py#L417-L477 |
|
dulwich/dulwich | 1f66817d712e3563ce1ff53b1218491a2eae39da | dulwich/web.py | python | get_repo | (backend, mat) | return backend.open_repository(url_prefix(mat)) | Get a Repo instance for the given backend and URL regex match. | Get a Repo instance for the given backend and URL regex match. | [
"Get",
"a",
"Repo",
"instance",
"for",
"the",
"given",
"backend",
"and",
"URL",
"regex",
"match",
"."
] | def get_repo(backend, mat) -> BaseRepo:
"""Get a Repo instance for the given backend and URL regex match."""
return backend.open_repository(url_prefix(mat)) | [
"def",
"get_repo",
"(",
"backend",
",",
"mat",
")",
"->",
"BaseRepo",
":",
"return",
"backend",
".",
"open_repository",
"(",
"url_prefix",
"(",
"mat",
")",
")"
] | https://github.com/dulwich/dulwich/blob/1f66817d712e3563ce1ff53b1218491a2eae39da/dulwich/web.py#L119-L121 |
|
sethmlarson/virtualbox-python | 984a6e2cb0e8996f4df40f4444c1528849f1c70d | virtualbox/library.py | python | INetworkAdapter.boot_priority | (self) | return ret | Get or set int value for 'bootPriority'
Network boot priority of the adapter. Priority 1 is highest. If not set,
the priority is considered to be at the lowest possible setting. | Get or set int value for 'bootPriority'
Network boot priority of the adapter. Priority 1 is highest. If not set,
the priority is considered to be at the lowest possible setting. | [
"Get",
"or",
"set",
"int",
"value",
"for",
"bootPriority",
"Network",
"boot",
"priority",
"of",
"the",
"adapter",
".",
"Priority",
"1",
"is",
"highest",
".",
"If",
"not",
"set",
"the",
"priority",
"is",
"considered",
"to",
"be",
"at",
"the",
"lowest",
"possible",
"setting",
"."
] | def boot_priority(self):
"""Get or set int value for 'bootPriority'
Network boot priority of the adapter. Priority 1 is highest. If not set,
the priority is considered to be at the lowest possible setting.
"""
ret = self._get_attr("bootPriority")
return ret | [
"def",
"boot_priority",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"_get_attr",
"(",
"\"bootPriority\"",
")",
"return",
"ret"
] | https://github.com/sethmlarson/virtualbox-python/blob/984a6e2cb0e8996f4df40f4444c1528849f1c70d/virtualbox/library.py#L29545-L29551 |
|
mapnik/Cascadenik | 82f66859340a31dfcb24af127274f262d4f3ad85 | cascadenik/compile.py | python | Range.midpoint | (self) | Return a point guranteed to fall within this range, hopefully near the middle. | Return a point guranteed to fall within this range, hopefully near the middle. | [
"Return",
"a",
"point",
"guranteed",
"to",
"fall",
"within",
"this",
"range",
"hopefully",
"near",
"the",
"middle",
"."
] | def midpoint(self):
""" Return a point guranteed to fall within this range, hopefully near the middle.
"""
minpoint = self.leftedge
if self.leftop is gt:
minpoint += 1
maxpoint = self.rightedge
if self.rightop is lt:
maxpoint -= 1
if minpoint is None:
return maxpoint
elif maxpoint is None:
return minpoint
else:
return (minpoint + maxpoint) / 2 | [
"def",
"midpoint",
"(",
"self",
")",
":",
"minpoint",
"=",
"self",
".",
"leftedge",
"if",
"self",
".",
"leftop",
"is",
"gt",
":",
"minpoint",
"+=",
"1",
"maxpoint",
"=",
"self",
".",
"rightedge",
"if",
"self",
".",
"rightop",
"is",
"lt",
":",
"maxpoint",
"-=",
"1",
"if",
"minpoint",
"is",
"None",
":",
"return",
"maxpoint",
"elif",
"maxpoint",
"is",
"None",
":",
"return",
"minpoint",
"else",
":",
"return",
"(",
"minpoint",
"+",
"maxpoint",
")",
"/",
"2"
] | https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/compile.py#L186-L206 |
||
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/optimize/_linprog_rs.py | python | _get_more_basis_columns | (A, basis) | return np.concatenate((basis, new_basis)) | Called when the auxiliary problem terminates with artificial columns in
the basis, which must be removed and replaced with non-artificial
columns. Finds additional columns that do not make the matrix singular. | Called when the auxiliary problem terminates with artificial columns in
the basis, which must be removed and replaced with non-artificial
columns. Finds additional columns that do not make the matrix singular. | [
"Called",
"when",
"the",
"auxiliary",
"problem",
"terminates",
"with",
"artificial",
"columns",
"in",
"the",
"basis",
"which",
"must",
"be",
"removed",
"and",
"replaced",
"with",
"non",
"-",
"artificial",
"columns",
".",
"Finds",
"additional",
"columns",
"that",
"do",
"not",
"make",
"the",
"matrix",
"singular",
"."
] | def _get_more_basis_columns(A, basis):
"""
Called when the auxiliary problem terminates with artificial columns in
the basis, which must be removed and replaced with non-artificial
columns. Finds additional columns that do not make the matrix singular.
"""
m, n = A.shape
# options for inclusion are those that aren't already in the basis
a = np.arange(m+n)
bl = np.zeros(len(a), dtype=bool)
bl[basis] = 1
options = a[~bl]
options = options[options < n] # and they have to be non-artificial
# form basis matrix
B = np.zeros((m, m))
B[:, 0:len(basis)] = A[:, basis]
if (basis.size > 0 and
np.linalg.matrix_rank(B[:, :len(basis)]) < len(basis)):
raise Exception("Basis has dependent columns")
rank = 0 # just enter the loop
for i in range(n): # somewhat arbitrary, but we need another way out
# permute the options, and take as many as needed
new_basis = np.random.permutation(options)[:m-len(basis)]
B[:, len(basis):] = A[:, new_basis] # update the basis matrix
rank = np.linalg.matrix_rank(B) # check the rank
if rank == m:
break
return np.concatenate((basis, new_basis)) | [
"def",
"_get_more_basis_columns",
"(",
"A",
",",
"basis",
")",
":",
"m",
",",
"n",
"=",
"A",
".",
"shape",
"# options for inclusion are those that aren't already in the basis",
"a",
"=",
"np",
".",
"arange",
"(",
"m",
"+",
"n",
")",
"bl",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"a",
")",
",",
"dtype",
"=",
"bool",
")",
"bl",
"[",
"basis",
"]",
"=",
"1",
"options",
"=",
"a",
"[",
"~",
"bl",
"]",
"options",
"=",
"options",
"[",
"options",
"<",
"n",
"]",
"# and they have to be non-artificial",
"# form basis matrix",
"B",
"=",
"np",
".",
"zeros",
"(",
"(",
"m",
",",
"m",
")",
")",
"B",
"[",
":",
",",
"0",
":",
"len",
"(",
"basis",
")",
"]",
"=",
"A",
"[",
":",
",",
"basis",
"]",
"if",
"(",
"basis",
".",
"size",
">",
"0",
"and",
"np",
".",
"linalg",
".",
"matrix_rank",
"(",
"B",
"[",
":",
",",
":",
"len",
"(",
"basis",
")",
"]",
")",
"<",
"len",
"(",
"basis",
")",
")",
":",
"raise",
"Exception",
"(",
"\"Basis has dependent columns\"",
")",
"rank",
"=",
"0",
"# just enter the loop",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"# somewhat arbitrary, but we need another way out",
"# permute the options, and take as many as needed",
"new_basis",
"=",
"np",
".",
"random",
".",
"permutation",
"(",
"options",
")",
"[",
":",
"m",
"-",
"len",
"(",
"basis",
")",
"]",
"B",
"[",
":",
",",
"len",
"(",
"basis",
")",
":",
"]",
"=",
"A",
"[",
":",
",",
"new_basis",
"]",
"# update the basis matrix",
"rank",
"=",
"np",
".",
"linalg",
".",
"matrix_rank",
"(",
"B",
")",
"# check the rank",
"if",
"rank",
"==",
"m",
":",
"break",
"return",
"np",
".",
"concatenate",
"(",
"(",
"basis",
",",
"new_basis",
")",
")"
] | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/optimize/_linprog_rs.py#L99-L131 |
|
lisa-lab/pylearn2 | af81e5c362f0df4df85c3e54e23b2adeec026055 | pylearn2/monitor.py | python | get_channel | (model, dataset, channel, cost, batch_size) | return value | Make a temporary monitor and return the value of a channel in it.
Parameters
----------
model : pylearn2.models.model.Model
Will evaluate the channel for this Model.
dataset : pylearn2.datasets.Dataset
The Dataset to run on
channel : str
A string identifying the channel name to evaluate
cost : pylearn2.costs.Cost
The Cost to setup for monitoring
batch_size : int
The size of the batch to use when running the monitor
Returns
-------
value : WRITEME
The value of the requested channel.
Notes
-----
This doesn't modify the model (unless some of the channel prereqs do).
In particular, it does not change model.monitor. | Make a temporary monitor and return the value of a channel in it. | [
"Make",
"a",
"temporary",
"monitor",
"and",
"return",
"the",
"value",
"of",
"a",
"channel",
"in",
"it",
"."
] | def get_channel(model, dataset, channel, cost, batch_size):
"""
Make a temporary monitor and return the value of a channel in it.
Parameters
----------
model : pylearn2.models.model.Model
Will evaluate the channel for this Model.
dataset : pylearn2.datasets.Dataset
The Dataset to run on
channel : str
A string identifying the channel name to evaluate
cost : pylearn2.costs.Cost
The Cost to setup for monitoring
batch_size : int
The size of the batch to use when running the monitor
Returns
-------
value : WRITEME
The value of the requested channel.
Notes
-----
This doesn't modify the model (unless some of the channel prereqs do).
In particular, it does not change model.monitor.
"""
monitor = Monitor(model)
monitor.setup(dataset=dataset, cost=cost, batch_size=batch_size)
monitor()
channels = monitor.channels
channel = channels[channel]
val_record = channel.val_record
value, = val_record
return value | [
"def",
"get_channel",
"(",
"model",
",",
"dataset",
",",
"channel",
",",
"cost",
",",
"batch_size",
")",
":",
"monitor",
"=",
"Monitor",
"(",
"model",
")",
"monitor",
".",
"setup",
"(",
"dataset",
"=",
"dataset",
",",
"cost",
"=",
"cost",
",",
"batch_size",
"=",
"batch_size",
")",
"monitor",
"(",
")",
"channels",
"=",
"monitor",
".",
"channels",
"channel",
"=",
"channels",
"[",
"channel",
"]",
"val_record",
"=",
"channel",
".",
"val_record",
"value",
",",
"=",
"val_record",
"return",
"value"
] | https://github.com/lisa-lab/pylearn2/blob/af81e5c362f0df4df85c3e54e23b2adeec026055/pylearn2/monitor.py#L1212-L1246 |
|
JulianEberius/SublimeRope | c6ac5179ce8c1e7af0c2c1134589f945252c362d | rope/base/resourceobserver.py | python | ResourceObserver.resource_moved | (self, resource, new_resource) | It is called when a resource is moved | It is called when a resource is moved | [
"It",
"is",
"called",
"when",
"a",
"resource",
"is",
"moved"
] | def resource_moved(self, resource, new_resource):
"""It is called when a resource is moved"""
if self.moved is not None:
self.moved(resource, new_resource) | [
"def",
"resource_moved",
"(",
"self",
",",
"resource",
",",
"new_resource",
")",
":",
"if",
"self",
".",
"moved",
"is",
"not",
"None",
":",
"self",
".",
"moved",
"(",
"resource",
",",
"new_resource",
")"
] | https://github.com/JulianEberius/SublimeRope/blob/c6ac5179ce8c1e7af0c2c1134589f945252c362d/rope/base/resourceobserver.py#L32-L35 |
||
stephenmcd/mezzanine | e38ffc69f732000ce44b7ed5c9d0516d258b8af2 | mezzanine/utils/cache.py | python | cache_installed | () | return (
has_key
and settings.CACHES
and not settings.TESTING
and middlewares_or_subclasses_installed(
[
"mezzanine.core.middleware.UpdateCacheMiddleware",
"mezzanine.core.middleware.FetchFromCacheMiddleware",
]
)
) | Returns ``True`` if a cache backend is configured, and the
cache middleware classes or subclasses thereof are present.
This will be evaluated once per run, and then cached. | Returns ``True`` if a cache backend is configured, and the
cache middleware classes or subclasses thereof are present.
This will be evaluated once per run, and then cached. | [
"Returns",
"True",
"if",
"a",
"cache",
"backend",
"is",
"configured",
"and",
"the",
"cache",
"middleware",
"classes",
"or",
"subclasses",
"thereof",
"are",
"present",
".",
"This",
"will",
"be",
"evaluated",
"once",
"per",
"run",
"and",
"then",
"cached",
"."
] | def cache_installed():
"""
Returns ``True`` if a cache backend is configured, and the
cache middleware classes or subclasses thereof are present.
This will be evaluated once per run, and then cached.
"""
has_key = bool(getattr(settings, "NEVERCACHE_KEY", ""))
return (
has_key
and settings.CACHES
and not settings.TESTING
and middlewares_or_subclasses_installed(
[
"mezzanine.core.middleware.UpdateCacheMiddleware",
"mezzanine.core.middleware.FetchFromCacheMiddleware",
]
)
) | [
"def",
"cache_installed",
"(",
")",
":",
"has_key",
"=",
"bool",
"(",
"getattr",
"(",
"settings",
",",
"\"NEVERCACHE_KEY\"",
",",
"\"\"",
")",
")",
"return",
"(",
"has_key",
"and",
"settings",
".",
"CACHES",
"and",
"not",
"settings",
".",
"TESTING",
"and",
"middlewares_or_subclasses_installed",
"(",
"[",
"\"mezzanine.core.middleware.UpdateCacheMiddleware\"",
",",
"\"mezzanine.core.middleware.FetchFromCacheMiddleware\"",
",",
"]",
")",
")"
] | https://github.com/stephenmcd/mezzanine/blob/e38ffc69f732000ce44b7ed5c9d0516d258b8af2/mezzanine/utils/cache.py#L58-L76 |
|
snower/forsun | b90d9716b123d98f32575560850e7d8b74aa2612 | forsun/servers/processor/Forsun.py | python | Iface.getTime | (self, timestamp) | Parameters:
- timestamp | Parameters:
- timestamp | [
"Parameters",
":",
"-",
"timestamp"
] | def getTime(self, timestamp):
"""
Parameters:
- timestamp
"""
pass | [
"def",
"getTime",
"(",
"self",
",",
"timestamp",
")",
":",
"pass"
] | https://github.com/snower/forsun/blob/b90d9716b123d98f32575560850e7d8b74aa2612/forsun/servers/processor/Forsun.py#L73-L78 |
||
xuannianz/keras-CenterNet | 39cb123a94d7774490df28e637240de03577f912 | utils/visualization.py | python | draw_annotations | (image, annotations, color=(0, 255, 0), label_to_name=None) | Draws annotations in an image.
# Arguments
image : The image to draw on.
annotations : A [N, 5] matrix (x1, y1, x2, y2, label) or dictionary containing bboxes (shaped [N, 4]) and labels (shaped [N]).
color : The color of the boxes. By default the color from keras_retinanet.utils.colors.label_color will be used.
label_to_name : (optional) Functor for mapping a label to a name. | Draws annotations in an image. | [
"Draws",
"annotations",
"in",
"an",
"image",
"."
] | def draw_annotations(image, annotations, color=(0, 255, 0), label_to_name=None):
""" Draws annotations in an image.
# Arguments
image : The image to draw on.
annotations : A [N, 5] matrix (x1, y1, x2, y2, label) or dictionary containing bboxes (shaped [N, 4]) and labels (shaped [N]).
color : The color of the boxes. By default the color from keras_retinanet.utils.colors.label_color will be used.
label_to_name : (optional) Functor for mapping a label to a name.
"""
if isinstance(annotations, np.ndarray):
annotations = {'bboxes': annotations[:, :4], 'labels': annotations[:, 4]}
assert('bboxes' in annotations)
assert('labels' in annotations)
assert(annotations['bboxes'].shape[0] == annotations['labels'].shape[0])
for i in range(annotations['bboxes'].shape[0]):
label = annotations['labels'][i]
c = color if color is not None else label_color(label)
caption = '{}'.format(label_to_name(label) if label_to_name else label)
draw_caption(image, annotations['bboxes'][i], caption)
draw_box(image, annotations['bboxes'][i], color=c) | [
"def",
"draw_annotations",
"(",
"image",
",",
"annotations",
",",
"color",
"=",
"(",
"0",
",",
"255",
",",
"0",
")",
",",
"label_to_name",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"annotations",
",",
"np",
".",
"ndarray",
")",
":",
"annotations",
"=",
"{",
"'bboxes'",
":",
"annotations",
"[",
":",
",",
":",
"4",
"]",
",",
"'labels'",
":",
"annotations",
"[",
":",
",",
"4",
"]",
"}",
"assert",
"(",
"'bboxes'",
"in",
"annotations",
")",
"assert",
"(",
"'labels'",
"in",
"annotations",
")",
"assert",
"(",
"annotations",
"[",
"'bboxes'",
"]",
".",
"shape",
"[",
"0",
"]",
"==",
"annotations",
"[",
"'labels'",
"]",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"annotations",
"[",
"'bboxes'",
"]",
".",
"shape",
"[",
"0",
"]",
")",
":",
"label",
"=",
"annotations",
"[",
"'labels'",
"]",
"[",
"i",
"]",
"c",
"=",
"color",
"if",
"color",
"is",
"not",
"None",
"else",
"label_color",
"(",
"label",
")",
"caption",
"=",
"'{}'",
".",
"format",
"(",
"label_to_name",
"(",
"label",
")",
"if",
"label_to_name",
"else",
"label",
")",
"draw_caption",
"(",
"image",
",",
"annotations",
"[",
"'bboxes'",
"]",
"[",
"i",
"]",
",",
"caption",
")",
"draw_box",
"(",
"image",
",",
"annotations",
"[",
"'bboxes'",
"]",
"[",
"i",
"]",
",",
"color",
"=",
"c",
")"
] | https://github.com/xuannianz/keras-CenterNet/blob/39cb123a94d7774490df28e637240de03577f912/utils/visualization.py#L85-L106 |
||
opendatacube/datacube-core | b062184be61c140a168de94510bc3661748f112e | datacube/ui/click.py | python | pass_index | (app_name=None, expect_initialised=True) | return decorate | Get a connection to the index as the first argument.
:param str app_name:
A short name of the application for logging purposes.
:param bool expect_initialised:
Whether to connect immediately on startup. Useful to catch connection config issues immediately,
but if you're planning to fork before any usage (such as in the case of some web servers),
you may not want this. For more information on thread/process usage, see datacube.index.Index | Get a connection to the index as the first argument. | [
"Get",
"a",
"connection",
"to",
"the",
"index",
"as",
"the",
"first",
"argument",
"."
] | def pass_index(app_name=None, expect_initialised=True):
"""Get a connection to the index as the first argument.
:param str app_name:
A short name of the application for logging purposes.
:param bool expect_initialised:
Whether to connect immediately on startup. Useful to catch connection config issues immediately,
but if you're planning to fork before any usage (such as in the case of some web servers),
you may not want this. For more information on thread/process usage, see datacube.index.Index
"""
def decorate(f):
@pass_config
def with_index(local_config: config.LocalConfig,
*args,
**kwargs):
command_path = click.get_current_context().command_path
try:
index = index_connect(local_config,
application_name=app_name or command_path,
validate_connection=expect_initialised)
_LOG.debug("Connected to datacube index: %s", index)
except (OperationalError, ProgrammingError) as e:
handle_exception('Error Connecting to database: %s', e)
return
try:
return f(index, *args, **kwargs)
finally:
index.close()
del index
return functools.update_wrapper(with_index, f)
return decorate | [
"def",
"pass_index",
"(",
"app_name",
"=",
"None",
",",
"expect_initialised",
"=",
"True",
")",
":",
"def",
"decorate",
"(",
"f",
")",
":",
"@",
"pass_config",
"def",
"with_index",
"(",
"local_config",
":",
"config",
".",
"LocalConfig",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"command_path",
"=",
"click",
".",
"get_current_context",
"(",
")",
".",
"command_path",
"try",
":",
"index",
"=",
"index_connect",
"(",
"local_config",
",",
"application_name",
"=",
"app_name",
"or",
"command_path",
",",
"validate_connection",
"=",
"expect_initialised",
")",
"_LOG",
".",
"debug",
"(",
"\"Connected to datacube index: %s\"",
",",
"index",
")",
"except",
"(",
"OperationalError",
",",
"ProgrammingError",
")",
"as",
"e",
":",
"handle_exception",
"(",
"'Error Connecting to database: %s'",
",",
"e",
")",
"return",
"try",
":",
"return",
"f",
"(",
"index",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"finally",
":",
"index",
".",
"close",
"(",
")",
"del",
"index",
"return",
"functools",
".",
"update_wrapper",
"(",
"with_index",
",",
"f",
")",
"return",
"decorate"
] | https://github.com/opendatacube/datacube-core/blob/b062184be61c140a168de94510bc3661748f112e/datacube/ui/click.py#L205-L239 |
|
whoosh-community/whoosh | 5421f1ab3bb802114105b3181b7ce4f44ad7d0bb | src/whoosh/searching.py | python | Searcher.suggest | (self, fieldname, text, limit=5, maxdist=2, prefix=0) | return c.suggest(text, limit=limit, maxdist=maxdist, prefix=prefix) | Returns a sorted list of suggested corrections for the given
mis-typed word ``text`` based on the contents of the given field::
>>> searcher.suggest("content", "specail")
["special"]
This is a convenience method. If you are planning to get suggestions
for multiple words in the same field, it is more efficient to get a
:class:`~whoosh.spelling.Corrector` object and use it directly::
corrector = searcher.corrector("fieldname")
for word in words:
print(corrector.suggest(word))
:param limit: only return up to this many suggestions. If there are not
enough terms in the field within ``maxdist`` of the given word, the
returned list will be shorter than this number.
:param maxdist: the largest edit distance from the given word to look
at. Numbers higher than 2 are not very effective or efficient.
:param prefix: require suggestions to share a prefix of this length
with the given word. This is often justifiable since most
misspellings do not involve the first letter of the word. Using a
prefix dramatically decreases the time it takes to generate the
list of words. | Returns a sorted list of suggested corrections for the given
mis-typed word ``text`` based on the contents of the given field:: | [
"Returns",
"a",
"sorted",
"list",
"of",
"suggested",
"corrections",
"for",
"the",
"given",
"mis",
"-",
"typed",
"word",
"text",
"based",
"on",
"the",
"contents",
"of",
"the",
"given",
"field",
"::"
] | def suggest(self, fieldname, text, limit=5, maxdist=2, prefix=0):
"""Returns a sorted list of suggested corrections for the given
mis-typed word ``text`` based on the contents of the given field::
>>> searcher.suggest("content", "specail")
["special"]
This is a convenience method. If you are planning to get suggestions
for multiple words in the same field, it is more efficient to get a
:class:`~whoosh.spelling.Corrector` object and use it directly::
corrector = searcher.corrector("fieldname")
for word in words:
print(corrector.suggest(word))
:param limit: only return up to this many suggestions. If there are not
enough terms in the field within ``maxdist`` of the given word, the
returned list will be shorter than this number.
:param maxdist: the largest edit distance from the given word to look
at. Numbers higher than 2 are not very effective or efficient.
:param prefix: require suggestions to share a prefix of this length
with the given word. This is often justifiable since most
misspellings do not involve the first letter of the word. Using a
prefix dramatically decreases the time it takes to generate the
list of words.
"""
c = self.reader().corrector(fieldname)
return c.suggest(text, limit=limit, maxdist=maxdist, prefix=prefix) | [
"def",
"suggest",
"(",
"self",
",",
"fieldname",
",",
"text",
",",
"limit",
"=",
"5",
",",
"maxdist",
"=",
"2",
",",
"prefix",
"=",
"0",
")",
":",
"c",
"=",
"self",
".",
"reader",
"(",
")",
".",
"corrector",
"(",
"fieldname",
")",
"return",
"c",
".",
"suggest",
"(",
"text",
",",
"limit",
"=",
"limit",
",",
"maxdist",
"=",
"maxdist",
",",
"prefix",
"=",
"prefix",
")"
] | https://github.com/whoosh-community/whoosh/blob/5421f1ab3bb802114105b3181b7ce4f44ad7d0bb/src/whoosh/searching.py#L465-L493 |
|
yuvalpinter/Mimick | 8ad9dd8e957f92021526db4d2a639948a79c73f1 | model.py | python | LSTMTagger.loss | (self, sentence, word_chars, tags_set) | return errors | For use in training phase.
Tag sentence (all attributes) and compute loss based on probability of expected tags. | For use in training phase.
Tag sentence (all attributes) and compute loss based on probability of expected tags. | [
"For",
"use",
"in",
"training",
"phase",
".",
"Tag",
"sentence",
"(",
"all",
"attributes",
")",
"and",
"compute",
"loss",
"based",
"on",
"probability",
"of",
"expected",
"tags",
"."
] | def loss(self, sentence, word_chars, tags_set):
'''
For use in training phase.
Tag sentence (all attributes) and compute loss based on probability of expected tags.
'''
observations_set = self.build_tagging_graph(sentence, word_chars)
errors = {}
for att, tags in tags_set.items():
err = []
for obs, tag in zip(observations_set[att], tags):
err_t = dy.pickneglogsoftmax(obs, tag)
err.append(err_t)
errors[att] = dy.esum(err)
if self.att_props is not None:
for att, err in errors.items():
prop_vec = dy.inputVector([self.att_props[att]] * err.dim()[0])
err = dy.cmult(err, prop_vec)
return errors | [
"def",
"loss",
"(",
"self",
",",
"sentence",
",",
"word_chars",
",",
"tags_set",
")",
":",
"observations_set",
"=",
"self",
".",
"build_tagging_graph",
"(",
"sentence",
",",
"word_chars",
")",
"errors",
"=",
"{",
"}",
"for",
"att",
",",
"tags",
"in",
"tags_set",
".",
"items",
"(",
")",
":",
"err",
"=",
"[",
"]",
"for",
"obs",
",",
"tag",
"in",
"zip",
"(",
"observations_set",
"[",
"att",
"]",
",",
"tags",
")",
":",
"err_t",
"=",
"dy",
".",
"pickneglogsoftmax",
"(",
"obs",
",",
"tag",
")",
"err",
".",
"append",
"(",
"err_t",
")",
"errors",
"[",
"att",
"]",
"=",
"dy",
".",
"esum",
"(",
"err",
")",
"if",
"self",
".",
"att_props",
"is",
"not",
"None",
":",
"for",
"att",
",",
"err",
"in",
"errors",
".",
"items",
"(",
")",
":",
"prop_vec",
"=",
"dy",
".",
"inputVector",
"(",
"[",
"self",
".",
"att_props",
"[",
"att",
"]",
"]",
"*",
"err",
".",
"dim",
"(",
")",
"[",
"0",
"]",
")",
"err",
"=",
"dy",
".",
"cmult",
"(",
"err",
",",
"prop_vec",
")",
"return",
"errors"
] | https://github.com/yuvalpinter/Mimick/blob/8ad9dd8e957f92021526db4d2a639948a79c73f1/model.py#L142-L159 |
|
jamiesun/SublimeEvernote | 62eeccabca6c4051340f0b1b8f7c10548437a9e1 | lib/thrift/server/TNonblockingServer.py | python | Connection.read | (self) | Reads data from stream and switch state. | Reads data from stream and switch state. | [
"Reads",
"data",
"from",
"stream",
"and",
"switch",
"state",
"."
] | def read(self):
"""Reads data from stream and switch state."""
assert self.status in (WAIT_LEN, WAIT_MESSAGE)
if self.status == WAIT_LEN:
self._read_len()
# go back to the main loop here for simplicity instead of
# falling through, even though there is a good chance that
# the message is already available
elif self.status == WAIT_MESSAGE:
read = self.socket.recv(self.len - len(self.message))
if len(read) == 0:
logging.error("can't read frame from socket (get %d of %d bytes)" %
(len(self.message), self.len))
self.close()
return
self.message += read
if len(self.message) == self.len:
self.status = WAIT_PROCESS | [
"def",
"read",
"(",
"self",
")",
":",
"assert",
"self",
".",
"status",
"in",
"(",
"WAIT_LEN",
",",
"WAIT_MESSAGE",
")",
"if",
"self",
".",
"status",
"==",
"WAIT_LEN",
":",
"self",
".",
"_read_len",
"(",
")",
"# go back to the main loop here for simplicity instead of",
"# falling through, even though there is a good chance that",
"# the message is already available",
"elif",
"self",
".",
"status",
"==",
"WAIT_MESSAGE",
":",
"read",
"=",
"self",
".",
"socket",
".",
"recv",
"(",
"self",
".",
"len",
"-",
"len",
"(",
"self",
".",
"message",
")",
")",
"if",
"len",
"(",
"read",
")",
"==",
"0",
":",
"logging",
".",
"error",
"(",
"\"can't read frame from socket (get %d of %d bytes)\"",
"%",
"(",
"len",
"(",
"self",
".",
"message",
")",
",",
"self",
".",
"len",
")",
")",
"self",
".",
"close",
"(",
")",
"return",
"self",
".",
"message",
"+=",
"read",
"if",
"len",
"(",
"self",
".",
"message",
")",
"==",
"self",
".",
"len",
":",
"self",
".",
"status",
"=",
"WAIT_PROCESS"
] | https://github.com/jamiesun/SublimeEvernote/blob/62eeccabca6c4051340f0b1b8f7c10548437a9e1/lib/thrift/server/TNonblockingServer.py#L131-L148 |
||
openid/python-openid | afa6adacbe1a41d8f614c8bce2264dfbe9e76489 | openid/extensions/sreg.py | python | SRegRequest.__contains__ | (self, field_name) | return (field_name in self.required or field_name in self.optional) | Was this field in the request? | Was this field in the request? | [
"Was",
"this",
"field",
"in",
"the",
"request?"
] | def __contains__(self, field_name):
"""Was this field in the request?"""
return (field_name in self.required or field_name in self.optional) | [
"def",
"__contains__",
"(",
"self",
",",
"field_name",
")",
":",
"return",
"(",
"field_name",
"in",
"self",
".",
"required",
"or",
"field_name",
"in",
"self",
".",
"optional",
")"
] | https://github.com/openid/python-openid/blob/afa6adacbe1a41d8f614c8bce2264dfbe9e76489/openid/extensions/sreg.py#L294-L296 |
|
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/idlelib/PathBrowser.py | python | DirBrowserTreeItem.GetText | (self) | [] | def GetText(self):
if not self.packages:
return self.dir
else:
return self.packages[-1] + ": package" | [
"def",
"GetText",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"packages",
":",
"return",
"self",
".",
"dir",
"else",
":",
"return",
"self",
".",
"packages",
"[",
"-",
"1",
"]",
"+",
"\": package\""
] | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/idlelib/PathBrowser.py#L45-L49 |
||||
HazyResearch/fonduer | c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd | src/fonduer/candidates/models/figure_mention.py | python | TemporaryFigureMention.__gt__ | (self, other: object) | return self.__repr__() > other.__repr__() | Check if the mention is greater than another mention. | Check if the mention is greater than another mention. | [
"Check",
"if",
"the",
"mention",
"is",
"greater",
"than",
"another",
"mention",
"."
] | def __gt__(self, other: object) -> bool:
"""Check if the mention is greater than another mention."""
if not isinstance(other, TemporaryFigureMention):
return NotImplemented
# Allow sorting by comparing the string representations of each
return self.__repr__() > other.__repr__() | [
"def",
"__gt__",
"(",
"self",
",",
"other",
":",
"object",
")",
"->",
"bool",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"TemporaryFigureMention",
")",
":",
"return",
"NotImplemented",
"# Allow sorting by comparing the string representations of each",
"return",
"self",
".",
"__repr__",
"(",
")",
">",
"other",
".",
"__repr__",
"(",
")"
] | https://github.com/HazyResearch/fonduer/blob/c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd/src/fonduer/candidates/models/figure_mention.py#L37-L42 |
|
bitbrute/evillimiter | 46d2033b022f4a51fb2f419393a5344ad3edea4a | evillimiter/menus/main_menu.py | python | MainMenu._scan_handler | (self, args) | Handles 'scan' command-line argument
(Re)scans for hosts on the network | Handles 'scan' command-line argument
(Re)scans for hosts on the network | [
"Handles",
"scan",
"command",
"-",
"line",
"argument",
"(",
"Re",
")",
"scans",
"for",
"hosts",
"on",
"the",
"network"
] | def _scan_handler(self, args):
"""
Handles 'scan' command-line argument
(Re)scans for hosts on the network
"""
if args.iprange:
iprange = self._parse_iprange(args.iprange)
if iprange is None:
IO.error('invalid ip range.')
return
else:
iprange = None
with self.hosts_lock:
for host in self.hosts:
self._free_host(host)
IO.spacer()
hosts = self.host_scanner.scan(iprange)
self.hosts_lock.acquire()
self.hosts = hosts
self.hosts_lock.release()
IO.ok('{}{}{} hosts discovered.'.format(IO.Fore.LIGHTYELLOW_EX, len(hosts), IO.Style.RESET_ALL))
IO.spacer() | [
"def",
"_scan_handler",
"(",
"self",
",",
"args",
")",
":",
"if",
"args",
".",
"iprange",
":",
"iprange",
"=",
"self",
".",
"_parse_iprange",
"(",
"args",
".",
"iprange",
")",
"if",
"iprange",
"is",
"None",
":",
"IO",
".",
"error",
"(",
"'invalid ip range.'",
")",
"return",
"else",
":",
"iprange",
"=",
"None",
"with",
"self",
".",
"hosts_lock",
":",
"for",
"host",
"in",
"self",
".",
"hosts",
":",
"self",
".",
"_free_host",
"(",
"host",
")",
"IO",
".",
"spacer",
"(",
")",
"hosts",
"=",
"self",
".",
"host_scanner",
".",
"scan",
"(",
"iprange",
")",
"self",
".",
"hosts_lock",
".",
"acquire",
"(",
")",
"self",
".",
"hosts",
"=",
"hosts",
"self",
".",
"hosts_lock",
".",
"release",
"(",
")",
"IO",
".",
"ok",
"(",
"'{}{}{} hosts discovered.'",
".",
"format",
"(",
"IO",
".",
"Fore",
".",
"LIGHTYELLOW_EX",
",",
"len",
"(",
"hosts",
")",
",",
"IO",
".",
"Style",
".",
"RESET_ALL",
")",
")",
"IO",
".",
"spacer",
"(",
")"
] | https://github.com/bitbrute/evillimiter/blob/46d2033b022f4a51fb2f419393a5344ad3edea4a/evillimiter/menus/main_menu.py#L115-L140 |
||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/utils/dummy_tf_objects.py | python | TFGPT2ForSequenceClassification.call | (self, *args, **kwargs) | [] | def call(self, *args, **kwargs):
requires_backends(self, ["tf"]) | [
"def",
"call",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"requires_backends",
"(",
"self",
",",
"[",
"\"tf\"",
"]",
")"
] | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_tf_objects.py#L1500-L1501 |
||||
GoogleCloudPlatform/appengine-mapreduce | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | python/src/mapreduce/api/map_job/output_writer.py | python | OutputWriter.to_json | (self) | Returns writer state.
No RPC should take place in this method. Use start_slice/end_slice instead.
Returns:
A json-serializable state for the OutputWriter instance. | Returns writer state. | [
"Returns",
"writer",
"state",
"."
] | def to_json(self):
"""Returns writer state.
No RPC should take place in this method. Use start_slice/end_slice instead.
Returns:
A json-serializable state for the OutputWriter instance.
"""
raise NotImplementedError("to_json() not implemented in %s" %
type(self)) | [
"def",
"to_json",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"to_json() not implemented in %s\"",
"%",
"type",
"(",
"self",
")",
")"
] | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/output_writer.py#L80-L89 |
||
ganeti/ganeti | d340a9ddd12f501bef57da421b5f9b969a4ba905 | lib/hypervisor/hv_kvm/__init__.py | python | KVMHypervisor._InstancePidAlive | (cls, instance_name) | return (pidfile, pid, alive) | Returns the instance pidfile, pid, and liveness.
@type instance_name: string
@param instance_name: instance name
@rtype: tuple
@return: (pid file name, pid, liveness) | Returns the instance pidfile, pid, and liveness. | [
"Returns",
"the",
"instance",
"pidfile",
"pid",
"and",
"liveness",
"."
] | def _InstancePidAlive(cls, instance_name):
"""Returns the instance pidfile, pid, and liveness.
@type instance_name: string
@param instance_name: instance name
@rtype: tuple
@return: (pid file name, pid, liveness)
"""
pidfile = cls._InstancePidFile(instance_name)
pid = utils.ReadPidFile(pidfile)
alive = False
try:
cmd_instance = cls._InstancePidInfo(pid)[0]
alive = (cmd_instance == instance_name)
except errors.HypervisorError:
pass
return (pidfile, pid, alive) | [
"def",
"_InstancePidAlive",
"(",
"cls",
",",
"instance_name",
")",
":",
"pidfile",
"=",
"cls",
".",
"_InstancePidFile",
"(",
"instance_name",
")",
"pid",
"=",
"utils",
".",
"ReadPidFile",
"(",
"pidfile",
")",
"alive",
"=",
"False",
"try",
":",
"cmd_instance",
"=",
"cls",
".",
"_InstancePidInfo",
"(",
"pid",
")",
"[",
"0",
"]",
"alive",
"=",
"(",
"cmd_instance",
"==",
"instance_name",
")",
"except",
"errors",
".",
"HypervisorError",
":",
"pass",
"return",
"(",
"pidfile",
",",
"pid",
",",
"alive",
")"
] | https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/hypervisor/hv_kvm/__init__.py#L749-L768 |
|
VirtueSecurity/aws-extender | d123b7e1a845847709ba3a481f11996bddc68a1c | BappModules/boto/s3/key.py | python | Key.send_file | (self, fp, headers=None, cb=None, num_cb=10,
query_args=None, chunked_transfer=False, size=None) | Upload a file to a key into a bucket on S3.
:type fp: file
:param fp: The file pointer to upload. The file pointer must
point at the offset from which you wish to upload.
ie. if uploading the full file, it should point at the
start of the file. Normally when a file is opened for
reading, the fp will point at the first byte. See the
bytes parameter below for more info.
:type headers: dict
:param headers: The headers to pass along with the PUT request
:type num_cb: int
:param num_cb: (optional) If a callback is specified with the
cb parameter this parameter determines the granularity of
the callback by defining the maximum number of times the
callback will be called during the file
transfer. Providing a negative integer will cause your
callback to be called with each buffer read.
:type query_args: string
:param query_args: (optional) Arguments to pass in the query string.
:type chunked_transfer: boolean
:param chunked_transfer: (optional) If true, we use chunked
Transfer-Encoding.
:type size: int
:param size: (optional) The Maximum number of bytes to read
from the file pointer (fp). This is useful when uploading
a file in multiple parts where you are splitting the file
up into different ranges to be uploaded. If not specified,
the default behaviour is to read all bytes from the file
pointer. Less bytes may be available. | Upload a file to a key into a bucket on S3. | [
"Upload",
"a",
"file",
"to",
"a",
"key",
"into",
"a",
"bucket",
"on",
"S3",
"."
] | def send_file(self, fp, headers=None, cb=None, num_cb=10,
query_args=None, chunked_transfer=False, size=None):
"""
Upload a file to a key into a bucket on S3.
:type fp: file
:param fp: The file pointer to upload. The file pointer must
point at the offset from which you wish to upload.
ie. if uploading the full file, it should point at the
start of the file. Normally when a file is opened for
reading, the fp will point at the first byte. See the
bytes parameter below for more info.
:type headers: dict
:param headers: The headers to pass along with the PUT request
:type num_cb: int
:param num_cb: (optional) If a callback is specified with the
cb parameter this parameter determines the granularity of
the callback by defining the maximum number of times the
callback will be called during the file
transfer. Providing a negative integer will cause your
callback to be called with each buffer read.
:type query_args: string
:param query_args: (optional) Arguments to pass in the query string.
:type chunked_transfer: boolean
:param chunked_transfer: (optional) If true, we use chunked
Transfer-Encoding.
:type size: int
:param size: (optional) The Maximum number of bytes to read
from the file pointer (fp). This is useful when uploading
a file in multiple parts where you are splitting the file
up into different ranges to be uploaded. If not specified,
the default behaviour is to read all bytes from the file
pointer. Less bytes may be available.
"""
self._send_file_internal(fp, headers=headers, cb=cb, num_cb=num_cb,
query_args=query_args,
chunked_transfer=chunked_transfer, size=size) | [
"def",
"send_file",
"(",
"self",
",",
"fp",
",",
"headers",
"=",
"None",
",",
"cb",
"=",
"None",
",",
"num_cb",
"=",
"10",
",",
"query_args",
"=",
"None",
",",
"chunked_transfer",
"=",
"False",
",",
"size",
"=",
"None",
")",
":",
"self",
".",
"_send_file_internal",
"(",
"fp",
",",
"headers",
"=",
"headers",
",",
"cb",
"=",
"cb",
",",
"num_cb",
"=",
"num_cb",
",",
"query_args",
"=",
"query_args",
",",
"chunked_transfer",
"=",
"chunked_transfer",
",",
"size",
"=",
"size",
")"
] | https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/s3/key.py#L721-L762 |
||
ThomasKluiters/fetchy | dfe1a73aa72cad4338445bec370be064707bff0c | fetchy/plugins/packages/mirror.py | python | Mirror.url_with_locale | (self) | The base url for this mirror in which the locale is included
this url may be None if no locale can be determined. | The base url for this mirror in which the locale is included
this url may be None if no locale can be determined. | [
"The",
"base",
"url",
"for",
"this",
"mirror",
"in",
"which",
"the",
"locale",
"is",
"included",
"this",
"url",
"may",
"be",
"None",
"if",
"no",
"locale",
"can",
"be",
"determined",
"."
] | def url_with_locale(self):
"""
The base url for this mirror in which the locale is included
this url may be None if no locale can be determined.
"""
raise NotImplementedError() | [
"def",
"url_with_locale",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/ThomasKluiters/fetchy/blob/dfe1a73aa72cad4338445bec370be064707bff0c/fetchy/plugins/packages/mirror.py#L45-L50 |
||
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/CPython/27/Lib/distutils/util.py | python | rfc822_escape | (header) | return header | Return a version of the string escaped for inclusion in an
RFC-822 header, by ensuring there are 8 spaces space after each newline. | Return a version of the string escaped for inclusion in an
RFC-822 header, by ensuring there are 8 spaces space after each newline. | [
"Return",
"a",
"version",
"of",
"the",
"string",
"escaped",
"for",
"inclusion",
"in",
"an",
"RFC",
"-",
"822",
"header",
"by",
"ensuring",
"there",
"are",
"8",
"spaces",
"space",
"after",
"each",
"newline",
"."
] | def rfc822_escape (header):
"""Return a version of the string escaped for inclusion in an
RFC-822 header, by ensuring there are 8 spaces space after each newline.
"""
lines = string.split(header, '\n')
header = string.join(lines, '\n' + 8*' ')
return header | [
"def",
"rfc822_escape",
"(",
"header",
")",
":",
"lines",
"=",
"string",
".",
"split",
"(",
"header",
",",
"'\\n'",
")",
"header",
"=",
"string",
".",
"join",
"(",
"lines",
",",
"'\\n'",
"+",
"8",
"*",
"' '",
")",
"return",
"header"
] | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/distutils/util.py#L561-L567 |
|
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | python3.8.2/Lib/site-packages/pip/_internal/utils/misc.py | python | path_to_display | (path) | return display_path | Convert a bytes (or text) path to text (unicode in Python 2) for display
and logging purposes.
This function should never error out. Also, this function is mainly needed
for Python 2 since in Python 3 str paths are already text. | Convert a bytes (or text) path to text (unicode in Python 2) for display
and logging purposes. | [
"Convert",
"a",
"bytes",
"(",
"or",
"text",
")",
"path",
"to",
"text",
"(",
"unicode",
"in",
"Python",
"2",
")",
"for",
"display",
"and",
"logging",
"purposes",
"."
] | def path_to_display(path):
# type: (Optional[Union[str, Text]]) -> Optional[Text]
"""
Convert a bytes (or text) path to text (unicode in Python 2) for display
and logging purposes.
This function should never error out. Also, this function is mainly needed
for Python 2 since in Python 3 str paths are already text.
"""
if path is None:
return None
if isinstance(path, text_type):
return path
# Otherwise, path is a bytes object (str in Python 2).
try:
display_path = path.decode(sys.getfilesystemencoding(), 'strict')
except UnicodeDecodeError:
# Include the full bytes to make troubleshooting easier, even though
# it may not be very human readable.
if PY2:
# Convert the bytes to a readable str representation using
# repr(), and then convert the str to unicode.
# Also, we add the prefix "b" to the repr() return value both
# to make the Python 2 output look like the Python 3 output, and
# to signal to the user that this is a bytes representation.
display_path = str_to_display('b{!r}'.format(path))
else:
# Silence the "F821 undefined name 'ascii'" flake8 error since
# in Python 3 ascii() is a built-in.
display_path = ascii(path) # noqa: F821
return display_path | [
"def",
"path_to_display",
"(",
"path",
")",
":",
"# type: (Optional[Union[str, Text]]) -> Optional[Text]",
"if",
"path",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"path",
",",
"text_type",
")",
":",
"return",
"path",
"# Otherwise, path is a bytes object (str in Python 2).",
"try",
":",
"display_path",
"=",
"path",
".",
"decode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
",",
"'strict'",
")",
"except",
"UnicodeDecodeError",
":",
"# Include the full bytes to make troubleshooting easier, even though",
"# it may not be very human readable.",
"if",
"PY2",
":",
"# Convert the bytes to a readable str representation using",
"# repr(), and then convert the str to unicode.",
"# Also, we add the prefix \"b\" to the repr() return value both",
"# to make the Python 2 output look like the Python 3 output, and",
"# to signal to the user that this is a bytes representation.",
"display_path",
"=",
"str_to_display",
"(",
"'b{!r}'",
".",
"format",
"(",
"path",
")",
")",
"else",
":",
"# Silence the \"F821 undefined name 'ascii'\" flake8 error since",
"# in Python 3 ascii() is a built-in.",
"display_path",
"=",
"ascii",
"(",
"path",
")",
"# noqa: F821",
"return",
"display_path"
] | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/site-packages/pip/_internal/utils/misc.py#L184-L215 |
|
mchristopher/PokemonGo-DesktopMap | ec37575f2776ee7d64456e2a1f6b6b78830b4fe0 | app/pylibs/win32/gevent/_sslgte279.py | python | SSLSocket.accept | (self) | return newsock, addr | Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client. | Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client. | [
"Accepts",
"a",
"new",
"connection",
"from",
"a",
"remote",
"client",
"and",
"returns",
"a",
"tuple",
"containing",
"that",
"new",
"connection",
"wrapped",
"with",
"a",
"server",
"-",
"side",
"SSL",
"channel",
"and",
"the",
"address",
"of",
"the",
"remote",
"client",
"."
] | def accept(self):
"""Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client."""
newsock, addr = socket.accept(self)
newsock = self.context.wrap_socket(newsock,
do_handshake_on_connect=self.do_handshake_on_connect,
suppress_ragged_eofs=self.suppress_ragged_eofs,
server_side=True)
return newsock, addr | [
"def",
"accept",
"(",
"self",
")",
":",
"newsock",
",",
"addr",
"=",
"socket",
".",
"accept",
"(",
"self",
")",
"newsock",
"=",
"self",
".",
"context",
".",
"wrap_socket",
"(",
"newsock",
",",
"do_handshake_on_connect",
"=",
"self",
".",
"do_handshake_on_connect",
",",
"suppress_ragged_eofs",
"=",
"self",
".",
"suppress_ragged_eofs",
",",
"server_side",
"=",
"True",
")",
"return",
"newsock",
",",
"addr"
] | https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pylibs/win32/gevent/_sslgte279.py#L615-L625 |
|
rotki/rotki | aafa446815cdd5e9477436d1b02bee7d01b398c8 | rotkehlchen/utils/mixins/serializableenum.py | python | SerializableEnumMixin.deserialize | (cls: Type[T], value: str) | May raise DeserializationError if the given value can't be deserialized | May raise DeserializationError if the given value can't be deserialized | [
"May",
"raise",
"DeserializationError",
"if",
"the",
"given",
"value",
"can",
"t",
"be",
"deserialized"
] | def deserialize(cls: Type[T], value: str) -> T:
"""May raise DeserializationError if the given value can't be deserialized"""
if not isinstance(value, str):
raise DeserializationError(
f'Failed to deserialize {cls.__name__} value from non string value: {value}',
)
upper_value = value.replace(' ', '_').upper()
try:
return getattr(cls, upper_value)
except AttributeError as e:
raise DeserializationError(f'Failed to deserialize {cls.__name__} value {value}') from e | [
"def",
"deserialize",
"(",
"cls",
":",
"Type",
"[",
"T",
"]",
",",
"value",
":",
"str",
")",
"->",
"T",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"DeserializationError",
"(",
"f'Failed to deserialize {cls.__name__} value from non string value: {value}'",
",",
")",
"upper_value",
"=",
"value",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
".",
"upper",
"(",
")",
"try",
":",
"return",
"getattr",
"(",
"cls",
",",
"upper_value",
")",
"except",
"AttributeError",
"as",
"e",
":",
"raise",
"DeserializationError",
"(",
"f'Failed to deserialize {cls.__name__} value {value}'",
")",
"from",
"e"
] | https://github.com/rotki/rotki/blob/aafa446815cdd5e9477436d1b02bee7d01b398c8/rotkehlchen/utils/mixins/serializableenum.py#L18-L29 |
||
tensorflow/models | 6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3 | research/efficient-hrl/environments/maze_env.py | python | MazeEnv.get_range_sensor_obs | (self) | return sensor_readings | Returns egocentric range sensor observations of maze. | Returns egocentric range sensor observations of maze. | [
"Returns",
"egocentric",
"range",
"sensor",
"observations",
"of",
"maze",
"."
] | def get_range_sensor_obs(self):
"""Returns egocentric range sensor observations of maze."""
robot_x, robot_y, robot_z = self.wrapped_env.get_body_com("torso")[:3]
ori = self.get_ori()
structure = self.MAZE_STRUCTURE
size_scaling = self.MAZE_SIZE_SCALING
height = self.MAZE_HEIGHT
segments = []
# Get line segments (corresponding to outer boundary) of each immovable
# block or drop-off.
for i in range(len(structure)):
for j in range(len(structure[0])):
if structure[i][j] in [1, -1]: # There's a wall or drop-off.
cx = j * size_scaling - self._init_torso_x
cy = i * size_scaling - self._init_torso_y
x1 = cx - 0.5 * size_scaling
x2 = cx + 0.5 * size_scaling
y1 = cy - 0.5 * size_scaling
y2 = cy + 0.5 * size_scaling
struct_segments = [
((x1, y1), (x2, y1)),
((x2, y1), (x2, y2)),
((x2, y2), (x1, y2)),
((x1, y2), (x1, y1)),
]
for seg in struct_segments:
segments.append(dict(
segment=seg,
type=structure[i][j],
))
# Get line segments (corresponding to outer boundary) of each movable
# block within the agent's z-view.
for block_name, block_type in self.movable_blocks:
block_x, block_y, block_z = self.wrapped_env.get_body_com(block_name)[:3]
if (block_z + height * size_scaling / 2 >= robot_z and
robot_z >= block_z - height * size_scaling / 2): # Block in view.
x1 = block_x - 0.5 * size_scaling
x2 = block_x + 0.5 * size_scaling
y1 = block_y - 0.5 * size_scaling
y2 = block_y + 0.5 * size_scaling
struct_segments = [
((x1, y1), (x2, y1)),
((x2, y1), (x2, y2)),
((x2, y2), (x1, y2)),
((x1, y2), (x1, y1)),
]
for seg in struct_segments:
segments.append(dict(
segment=seg,
type=block_type,
))
sensor_readings = np.zeros((self._n_bins, 3)) # 3 for wall, drop-off, block
for ray_idx in range(self._n_bins):
ray_ori = (ori - self._sensor_span * 0.5 +
(2 * ray_idx + 1.0) / (2 * self._n_bins) * self._sensor_span)
ray_segments = []
# Get all segments that intersect with ray.
for seg in segments:
p = maze_env_utils.ray_segment_intersect(
ray=((robot_x, robot_y), ray_ori),
segment=seg["segment"])
if p is not None:
ray_segments.append(dict(
segment=seg["segment"],
type=seg["type"],
ray_ori=ray_ori,
distance=maze_env_utils.point_distance(p, (robot_x, robot_y)),
))
if len(ray_segments) > 0:
# Find out which segment is intersected first.
first_seg = sorted(ray_segments, key=lambda x: x["distance"])[0]
seg_type = first_seg["type"]
idx = (0 if seg_type == 1 else # Wall.
1 if seg_type == -1 else # Drop-off.
2 if maze_env_utils.can_move(seg_type) else # Block.
None)
if first_seg["distance"] <= self._sensor_range:
sensor_readings[ray_idx][idx] = (self._sensor_range - first_seg["distance"]) / self._sensor_range
return sensor_readings | [
"def",
"get_range_sensor_obs",
"(",
"self",
")",
":",
"robot_x",
",",
"robot_y",
",",
"robot_z",
"=",
"self",
".",
"wrapped_env",
".",
"get_body_com",
"(",
"\"torso\"",
")",
"[",
":",
"3",
"]",
"ori",
"=",
"self",
".",
"get_ori",
"(",
")",
"structure",
"=",
"self",
".",
"MAZE_STRUCTURE",
"size_scaling",
"=",
"self",
".",
"MAZE_SIZE_SCALING",
"height",
"=",
"self",
".",
"MAZE_HEIGHT",
"segments",
"=",
"[",
"]",
"# Get line segments (corresponding to outer boundary) of each immovable",
"# block or drop-off.",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"structure",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"structure",
"[",
"0",
"]",
")",
")",
":",
"if",
"structure",
"[",
"i",
"]",
"[",
"j",
"]",
"in",
"[",
"1",
",",
"-",
"1",
"]",
":",
"# There's a wall or drop-off.",
"cx",
"=",
"j",
"*",
"size_scaling",
"-",
"self",
".",
"_init_torso_x",
"cy",
"=",
"i",
"*",
"size_scaling",
"-",
"self",
".",
"_init_torso_y",
"x1",
"=",
"cx",
"-",
"0.5",
"*",
"size_scaling",
"x2",
"=",
"cx",
"+",
"0.5",
"*",
"size_scaling",
"y1",
"=",
"cy",
"-",
"0.5",
"*",
"size_scaling",
"y2",
"=",
"cy",
"+",
"0.5",
"*",
"size_scaling",
"struct_segments",
"=",
"[",
"(",
"(",
"x1",
",",
"y1",
")",
",",
"(",
"x2",
",",
"y1",
")",
")",
",",
"(",
"(",
"x2",
",",
"y1",
")",
",",
"(",
"x2",
",",
"y2",
")",
")",
",",
"(",
"(",
"x2",
",",
"y2",
")",
",",
"(",
"x1",
",",
"y2",
")",
")",
",",
"(",
"(",
"x1",
",",
"y2",
")",
",",
"(",
"x1",
",",
"y1",
")",
")",
",",
"]",
"for",
"seg",
"in",
"struct_segments",
":",
"segments",
".",
"append",
"(",
"dict",
"(",
"segment",
"=",
"seg",
",",
"type",
"=",
"structure",
"[",
"i",
"]",
"[",
"j",
"]",
",",
")",
")",
"# Get line segments (corresponding to outer boundary) of each movable",
"# block within the agent's z-view.",
"for",
"block_name",
",",
"block_type",
"in",
"self",
".",
"movable_blocks",
":",
"block_x",
",",
"block_y",
",",
"block_z",
"=",
"self",
".",
"wrapped_env",
".",
"get_body_com",
"(",
"block_name",
")",
"[",
":",
"3",
"]",
"if",
"(",
"block_z",
"+",
"height",
"*",
"size_scaling",
"/",
"2",
">=",
"robot_z",
"and",
"robot_z",
">=",
"block_z",
"-",
"height",
"*",
"size_scaling",
"/",
"2",
")",
":",
"# Block in view.",
"x1",
"=",
"block_x",
"-",
"0.5",
"*",
"size_scaling",
"x2",
"=",
"block_x",
"+",
"0.5",
"*",
"size_scaling",
"y1",
"=",
"block_y",
"-",
"0.5",
"*",
"size_scaling",
"y2",
"=",
"block_y",
"+",
"0.5",
"*",
"size_scaling",
"struct_segments",
"=",
"[",
"(",
"(",
"x1",
",",
"y1",
")",
",",
"(",
"x2",
",",
"y1",
")",
")",
",",
"(",
"(",
"x2",
",",
"y1",
")",
",",
"(",
"x2",
",",
"y2",
")",
")",
",",
"(",
"(",
"x2",
",",
"y2",
")",
",",
"(",
"x1",
",",
"y2",
")",
")",
",",
"(",
"(",
"x1",
",",
"y2",
")",
",",
"(",
"x1",
",",
"y1",
")",
")",
",",
"]",
"for",
"seg",
"in",
"struct_segments",
":",
"segments",
".",
"append",
"(",
"dict",
"(",
"segment",
"=",
"seg",
",",
"type",
"=",
"block_type",
",",
")",
")",
"sensor_readings",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"_n_bins",
",",
"3",
")",
")",
"# 3 for wall, drop-off, block",
"for",
"ray_idx",
"in",
"range",
"(",
"self",
".",
"_n_bins",
")",
":",
"ray_ori",
"=",
"(",
"ori",
"-",
"self",
".",
"_sensor_span",
"*",
"0.5",
"+",
"(",
"2",
"*",
"ray_idx",
"+",
"1.0",
")",
"/",
"(",
"2",
"*",
"self",
".",
"_n_bins",
")",
"*",
"self",
".",
"_sensor_span",
")",
"ray_segments",
"=",
"[",
"]",
"# Get all segments that intersect with ray.",
"for",
"seg",
"in",
"segments",
":",
"p",
"=",
"maze_env_utils",
".",
"ray_segment_intersect",
"(",
"ray",
"=",
"(",
"(",
"robot_x",
",",
"robot_y",
")",
",",
"ray_ori",
")",
",",
"segment",
"=",
"seg",
"[",
"\"segment\"",
"]",
")",
"if",
"p",
"is",
"not",
"None",
":",
"ray_segments",
".",
"append",
"(",
"dict",
"(",
"segment",
"=",
"seg",
"[",
"\"segment\"",
"]",
",",
"type",
"=",
"seg",
"[",
"\"type\"",
"]",
",",
"ray_ori",
"=",
"ray_ori",
",",
"distance",
"=",
"maze_env_utils",
".",
"point_distance",
"(",
"p",
",",
"(",
"robot_x",
",",
"robot_y",
")",
")",
",",
")",
")",
"if",
"len",
"(",
"ray_segments",
")",
">",
"0",
":",
"# Find out which segment is intersected first.",
"first_seg",
"=",
"sorted",
"(",
"ray_segments",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"\"distance\"",
"]",
")",
"[",
"0",
"]",
"seg_type",
"=",
"first_seg",
"[",
"\"type\"",
"]",
"idx",
"=",
"(",
"0",
"if",
"seg_type",
"==",
"1",
"else",
"# Wall.",
"1",
"if",
"seg_type",
"==",
"-",
"1",
"else",
"# Drop-off.",
"2",
"if",
"maze_env_utils",
".",
"can_move",
"(",
"seg_type",
")",
"else",
"# Block.",
"None",
")",
"if",
"first_seg",
"[",
"\"distance\"",
"]",
"<=",
"self",
".",
"_sensor_range",
":",
"sensor_readings",
"[",
"ray_idx",
"]",
"[",
"idx",
"]",
"=",
"(",
"self",
".",
"_sensor_range",
"-",
"first_seg",
"[",
"\"distance\"",
"]",
")",
"/",
"self",
".",
"_sensor_range",
"return",
"sensor_readings"
] | https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/research/efficient-hrl/environments/maze_env.py#L323-L405 |
|
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/django/db/models/fields/related.py | python | ForeignObject.__init__ | (self, to, on_delete, from_fields, to_fields, rel=None, related_name=None,
related_query_name=None, limit_choices_to=None, parent_link=False,
swappable=True, **kwargs) | [] | def __init__(self, to, on_delete, from_fields, to_fields, rel=None, related_name=None,
related_query_name=None, limit_choices_to=None, parent_link=False,
swappable=True, **kwargs):
if rel is None:
rel = self.rel_class(
self, to,
related_name=related_name,
related_query_name=related_query_name,
limit_choices_to=limit_choices_to,
parent_link=parent_link,
on_delete=on_delete,
)
super(ForeignObject, self).__init__(rel=rel, **kwargs)
self.from_fields = from_fields
self.to_fields = to_fields
self.swappable = swappable | [
"def",
"__init__",
"(",
"self",
",",
"to",
",",
"on_delete",
",",
"from_fields",
",",
"to_fields",
",",
"rel",
"=",
"None",
",",
"related_name",
"=",
"None",
",",
"related_query_name",
"=",
"None",
",",
"limit_choices_to",
"=",
"None",
",",
"parent_link",
"=",
"False",
",",
"swappable",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"rel",
"is",
"None",
":",
"rel",
"=",
"self",
".",
"rel_class",
"(",
"self",
",",
"to",
",",
"related_name",
"=",
"related_name",
",",
"related_query_name",
"=",
"related_query_name",
",",
"limit_choices_to",
"=",
"limit_choices_to",
",",
"parent_link",
"=",
"parent_link",
",",
"on_delete",
"=",
"on_delete",
",",
")",
"super",
"(",
"ForeignObject",
",",
"self",
")",
".",
"__init__",
"(",
"rel",
"=",
"rel",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"from_fields",
"=",
"from_fields",
"self",
".",
"to_fields",
"=",
"to_fields",
"self",
".",
"swappable",
"=",
"swappable"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/db/models/fields/related.py#L442-L460 |
||||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/coding/linear_code.py | python | LinearCodeNearestNeighborDecoder._latex_ | (self) | return "\\textnormal{Nearest neighbor decoder for }%s" % self.code()._latex_() | r"""
Return a latex representation of ``self``.
EXAMPLES::
sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])
sage: C = LinearCode(G)
sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C)
sage: latex(D)
\textnormal{Nearest neighbor decoder for }[7, 4]\textnormal{ Linear code over }\Bold{F}_{2} | r"""
Return a latex representation of ``self``. | [
"r",
"Return",
"a",
"latex",
"representation",
"of",
"self",
"."
] | def _latex_(self):
r"""
Return a latex representation of ``self``.
EXAMPLES::
sage: G = Matrix(GF(2), [[1,1,1,0,0,0,0],[1,0,0,1,1,0,0],[0,1,0,1,0,1,0],[1,1,0,1,0,0,1]])
sage: C = LinearCode(G)
sage: D = codes.decoders.LinearCodeNearestNeighborDecoder(C)
sage: latex(D)
\textnormal{Nearest neighbor decoder for }[7, 4]\textnormal{ Linear code over }\Bold{F}_{2}
"""
return "\\textnormal{Nearest neighbor decoder for }%s" % self.code()._latex_() | [
"def",
"_latex_",
"(",
"self",
")",
":",
"return",
"\"\\\\textnormal{Nearest neighbor decoder for }%s\"",
"%",
"self",
".",
"code",
"(",
")",
".",
"_latex_",
"(",
")"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/coding/linear_code.py#L2982-L2994 |
|
materialsproject/pymatgen | 8128f3062a334a2edd240e4062b5b9bdd1ae6f58 | pymatgen/core/tensors.py | python | Tensor.average_over_unit_sphere | (self, quad=None) | return sum(w * self.project(n) for w, n in zip(weights, points)) | Method for averaging the tensor projection over the unit
with option for custom quadrature.
Args:
quad (dict): quadrature for integration, should be
dictionary with "points" and "weights" keys defaults
to quadpy.sphere.Lebedev(19) as read from file
Returns:
Average of tensor projected into vectors on the unit sphere | Method for averaging the tensor projection over the unit
with option for custom quadrature. | [
"Method",
"for",
"averaging",
"the",
"tensor",
"projection",
"over",
"the",
"unit",
"with",
"option",
"for",
"custom",
"quadrature",
"."
] | def average_over_unit_sphere(self, quad=None):
"""
Method for averaging the tensor projection over the unit
with option for custom quadrature.
Args:
quad (dict): quadrature for integration, should be
dictionary with "points" and "weights" keys defaults
to quadpy.sphere.Lebedev(19) as read from file
Returns:
Average of tensor projected into vectors on the unit sphere
"""
quad = quad or DEFAULT_QUAD
weights, points = quad["weights"], quad["points"]
return sum(w * self.project(n) for w, n in zip(weights, points)) | [
"def",
"average_over_unit_sphere",
"(",
"self",
",",
"quad",
"=",
"None",
")",
":",
"quad",
"=",
"quad",
"or",
"DEFAULT_QUAD",
"weights",
",",
"points",
"=",
"quad",
"[",
"\"weights\"",
"]",
",",
"quad",
"[",
"\"points\"",
"]",
"return",
"sum",
"(",
"w",
"*",
"self",
".",
"project",
"(",
"n",
")",
"for",
"w",
",",
"n",
"in",
"zip",
"(",
"weights",
",",
"points",
")",
")"
] | https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/core/tensors.py#L174-L190 |