nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
mgear-dev/mgear
06ddc26c5adb5eab07ca470c7fafa77404c8a1de
scripts/mgear/maya/shifter/component/__init__.py
python
Main.finalize
(self)
return
Finalize and clean the rig builing.
Finalize and clean the rig builing.
[ "Finalize", "and", "clean", "the", "rig", "builing", "." ]
def finalize(self): """Finalize and clean the rig builing.""" # locking the attributes for all the ctl parents that are not ctl # itself. for t in self.transform2Lock: attribute.lockAttribute(t) return
[ "def", "finalize", "(", "self", ")", ":", "# locking the attributes for all the ctl parents that are not ctl", "# itself.", "for", "t", "in", "self", ".", "transform2Lock", ":", "attribute", ".", "lockAttribute", "(", "t", ")", "return" ]
https://github.com/mgear-dev/mgear/blob/06ddc26c5adb5eab07ca470c7fafa77404c8a1de/scripts/mgear/maya/shifter/component/__init__.py#L1221-L1228
home-assistant/supervisor
69c2517d5211b483fdfe968b0a2b36b672ee7ab2
supervisor/resolution/fixups/store_execute_reset.py
python
FixupStoreExecuteReset.auto
(self)
return True
Return if a fixup can be apply as auto fix.
Return if a fixup can be apply as auto fix.
[ "Return", "if", "a", "fixup", "can", "be", "apply", "as", "auto", "fix", "." ]
def auto(self) -> bool: """Return if a fixup can be apply as auto fix.""" return True
[ "def", "auto", "(", "self", ")", "->", "bool", ":", "return", "True" ]
https://github.com/home-assistant/supervisor/blob/69c2517d5211b483fdfe968b0a2b36b672ee7ab2/supervisor/resolution/fixups/store_execute_reset.py#L60-L62
guillermooo/dart-sublime-bundle
d891fb36c98ca0b111a35cba109b05a16b6c4b83
out_there/yaml/__init__.py
python
dump_all
(documents, stream=None, Dumper=Dumper, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None)
Serialize a sequence of Python objects into a YAML stream. If stream is None, return the produced string instead.
Serialize a sequence of Python objects into a YAML stream. If stream is None, return the produced string instead.
[ "Serialize", "a", "sequence", "of", "Python", "objects", "into", "a", "YAML", "stream", ".", "If", "stream", "is", "None", "return", "the", "produced", "string", "instead", "." ]
def dump_all(documents, stream=None, Dumper=Dumper, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None): """ Serialize a sequence of Python objects into a YAML stream. If stream is None, return the produced string instead. """ getvalue = None if stream is None: if encoding is None: stream = io.StringIO() else: stream = io.BytesIO() getvalue = stream.getvalue dumper = Dumper(stream, default_style=default_style, default_flow_style=default_flow_style, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break, encoding=encoding, version=version, tags=tags, explicit_start=explicit_start, explicit_end=explicit_end) try: dumper.open() for data in documents: dumper.represent(data) dumper.close() finally: dumper.dispose() if getvalue: return getvalue()
[ "def", "dump_all", "(", "documents", ",", "stream", "=", "None", ",", "Dumper", "=", "Dumper", ",", "default_style", "=", "None", ",", "default_flow_style", "=", "None", ",", "canonical", "=", "None", ",", "indent", "=", "None", ",", "width", "=", "None"...
https://github.com/guillermooo/dart-sublime-bundle/blob/d891fb36c98ca0b111a35cba109b05a16b6c4b83/out_there/yaml/__init__.py#L162-L193
mirumee/ariadne
1b8b7ef0ed65cde95a6bd9e25500584a38393b71
ariadne/interfaces.py
python
InterfaceType.bind_to_schema
(self, schema: GraphQLSchema)
[]
def bind_to_schema(self, schema: GraphQLSchema) -> None: graphql_type = schema.type_map.get(self.name) self.validate_graphql_type(graphql_type) graphql_type = cast(GraphQLInterfaceType, graphql_type) graphql_type.resolve_type = self._resolve_type self.bind_resolvers_to_graphql_type(graphql_type) for object_type in schema.type_map.values(): if _type_implements_interface(self.name, object_type): self.bind_resolvers_to_graphql_type(object_type, replace_existing=False)
[ "def", "bind_to_schema", "(", "self", ",", "schema", ":", "GraphQLSchema", ")", "->", "None", ":", "graphql_type", "=", "schema", ".", "type_map", ".", "get", "(", "self", ".", "name", ")", "self", ".", "validate_graphql_type", "(", "graphql_type", ")", "g...
https://github.com/mirumee/ariadne/blob/1b8b7ef0ed65cde95a6bd9e25500584a38393b71/ariadne/interfaces.py#L28-L38
Qirky/FoxDot
76318f9630bede48ff3994146ed644affa27bfa4
FoxDot/lib/Effects/Util.py
python
EffectManager.values
(self)
return [self[key] for key in self.sort_by("synthdef")]
[]
def values(self): return [self[key] for key in self.sort_by("synthdef")]
[ "def", "values", "(", "self", ")", ":", "return", "[", "self", "[", "key", "]", "for", "key", "in", "self", ".", "sort_by", "(", "\"synthdef\"", ")", "]" ]
https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/Effects/Util.py#L206-L207
prody/ProDy
b24bbf58aa8fffe463c8548ae50e3955910e5b7f
prody/utilities/logger.py
python
PackageLogger.addHandler
(self, hdlr)
Add the specified handler to this logger.
Add the specified handler to this logger.
[ "Add", "the", "specified", "handler", "to", "this", "logger", "." ]
def addHandler(self, hdlr): """Add the specified handler to this logger.""" self._logger.addHandler(hdlr)
[ "def", "addHandler", "(", "self", ",", "hdlr", ")", ":", "self", ".", "_logger", ".", "addHandler", "(", "hdlr", ")" ]
https://github.com/prody/ProDy/blob/b24bbf58aa8fffe463c8548ae50e3955910e5b7f/prody/utilities/logger.py#L177-L180
zbarge/stocklook
d40bf60566681acd1e970818450228602bb7d8a5
stocklook/crypto/gdax/order.py
python
GdaxTrailingStop.sell
(self)
return o
Executes a market sell order liquidating the entire position. :return: (GdaxOrder) The posted GdaxOrder object reflecting the sell order.
Executes a market sell order liquidating the entire position. :return: (GdaxOrder) The posted GdaxOrder object reflecting the sell order.
[ "Executes", "a", "market", "sell", "order", "liquidating", "the", "entire", "position", ".", ":", "return", ":", "(", "GdaxOrder", ")", "The", "posted", "GdaxOrder", "object", "reflecting", "the", "sell", "order", "." ]
def sell(self): """ Executes a market sell order liquidating the entire position. :return: (GdaxOrder) The posted GdaxOrder object reflecting the sell order. """ if self.sell_order is not None: raise Exception("Existing sell order - " "cannot re-sell: " "{}".format(self.sell_order)) o = GdaxOrder(self.gdax, self.pair, order_type='market', side='sell', size=self.size) o.post() # Wait a few moments # and update the order with fill info. sleep(5) o.update() msg = '{} Trailing stop order @ price {} ' \ 'executed - {}'.format(now(), self.price, o) self.notify_user(msg) self.sell_order = o return o
[ "def", "sell", "(", "self", ")", ":", "if", "self", ".", "sell_order", "is", "not", "None", ":", "raise", "Exception", "(", "\"Existing sell order - \"", "\"cannot re-sell: \"", "\"{}\"", ".", "format", "(", "self", ".", "sell_order", ")", ")", "o", "=", "...
https://github.com/zbarge/stocklook/blob/d40bf60566681acd1e970818450228602bb7d8a5/stocklook/crypto/gdax/order.py#L763-L791
keras-team/keras
5caa668b6a415675064a730f5eb46ecc08e40f65
keras/engine/training_utils_v1.py
python
check_loss_and_target_compatibility
(targets, loss_fns, output_shapes)
Does validation on the compatibility of targets and loss functions. This helps prevent users from using loss functions incorrectly. This check is purely for UX purposes. Args: targets: list of Numpy arrays of targets. loss_fns: list of loss functions. output_shapes: list of shapes of model outputs. Raises: ValueError: if a loss function or target array is incompatible with an output.
Does validation on the compatibility of targets and loss functions.
[ "Does", "validation", "on", "the", "compatibility", "of", "targets", "and", "loss", "functions", "." ]
def check_loss_and_target_compatibility(targets, loss_fns, output_shapes): """Does validation on the compatibility of targets and loss functions. This helps prevent users from using loss functions incorrectly. This check is purely for UX purposes. Args: targets: list of Numpy arrays of targets. loss_fns: list of loss functions. output_shapes: list of shapes of model outputs. Raises: ValueError: if a loss function or target array is incompatible with an output. """ key_loss_fns = { losses.mean_squared_error, losses.binary_crossentropy, losses.categorical_crossentropy } key_loss_classes = (losses.MeanSquaredError, losses.BinaryCrossentropy, losses.CategoricalCrossentropy) for y, loss, shape in zip(targets, loss_fns, output_shapes): if y is None or loss is None or tf.is_tensor(y): continue if losses.is_categorical_crossentropy(loss): if y.shape[-1] == 1: raise ValueError('You are passing a target array of shape ' + str(y.shape) + ' while using as loss `categorical_crossentropy`. ' '`categorical_crossentropy` expects ' 'targets to be binary matrices (1s and 0s) ' 'of shape (samples, classes). ' 'If your targets are integer classes, ' 'you can convert them to the expected format via:\n' '```\n' 'from keras.utils import to_categorical\n' 'y_binary = to_categorical(y_int)\n' '```\n' '\n' 'Alternatively, you can use the loss function ' '`sparse_categorical_crossentropy` instead, ' 'which does expect integer targets.') is_loss_wrapper = isinstance(loss, losses.LossFunctionWrapper) if (isinstance(loss, key_loss_classes) or (is_loss_wrapper and (loss.fn in key_loss_fns))): for target_dim, out_dim in zip(y.shape[1:], shape[1:]): if out_dim is not None and target_dim != out_dim: loss_name = loss.name if loss_name is None: loss_type = loss.fn if is_loss_wrapper else type(loss) loss_name = loss_type.__name__ raise ValueError('A target array with shape ' + str(y.shape) + ' was passed for an output of shape ' + str(shape) + ' while using as loss `' + loss_name + '`. ' 'This loss expects targets to have the same shape ' 'as the output.')
[ "def", "check_loss_and_target_compatibility", "(", "targets", ",", "loss_fns", ",", "output_shapes", ")", ":", "key_loss_fns", "=", "{", "losses", ".", "mean_squared_error", ",", "losses", ".", "binary_crossentropy", ",", "losses", ".", "categorical_crossentropy", "}"...
https://github.com/keras-team/keras/blob/5caa668b6a415675064a730f5eb46ecc08e40f65/keras/engine/training_utils_v1.py#L759-L815
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/units/format/latex.py
python
Latex.format_exponential_notation
(cls, val, format_spec=".8g")
Formats a value in exponential notation for LaTeX. Parameters ---------- val : number The value to be formatted format_spec : str, optional Format used to split up mantissa and exponent Returns ------- latex_string : str The value in exponential notation in a format suitable for LaTeX.
Formats a value in exponential notation for LaTeX.
[ "Formats", "a", "value", "in", "exponential", "notation", "for", "LaTeX", "." ]
def format_exponential_notation(cls, val, format_spec=".8g"): """ Formats a value in exponential notation for LaTeX. Parameters ---------- val : number The value to be formatted format_spec : str, optional Format used to split up mantissa and exponent Returns ------- latex_string : str The value in exponential notation in a format suitable for LaTeX. """ if np.isfinite(val): m, ex = utils.split_mantissa_exponent(val, format_spec) parts = [] if m: parts.append(m) if ex: parts.append(f"10^{{{ex}}}") return r" \times ".join(parts) else: if np.isnan(val): return r'{\rm NaN}' elif val > 0: # positive infinity return r'\infty' else: # negative infinity return r'-\infty'
[ "def", "format_exponential_notation", "(", "cls", ",", "val", ",", "format_spec", "=", "\".8g\"", ")", ":", "if", "np", ".", "isfinite", "(", "val", ")", ":", "m", ",", "ex", "=", "utils", ".", "split_mantissa_exponent", "(", "val", ",", "format_spec", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/units/format/latex.py#L95-L130
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/jinja2-2.6/jinja2/filters.py
python
do_forceescape
(value)
return escape(unicode(value))
Enforce HTML escaping. This will probably double escape variables.
Enforce HTML escaping. This will probably double escape variables.
[ "Enforce", "HTML", "escaping", ".", "This", "will", "probably", "double", "escape", "variables", "." ]
def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(unicode(value))
[ "def", "do_forceescape", "(", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'__html__'", ")", ":", "value", "=", "value", ".", "__html__", "(", ")", "return", "escape", "(", "unicode", "(", "value", ")", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/jinja2-2.6/jinja2/filters.py#L66-L70
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/asyncio/transports.py
python
WriteTransport.writelines
(self, list_of_data)
Write a list (or any iterable) of data bytes to the transport. The default implementation concatenates the arguments and calls write() on the result.
Write a list (or any iterable) of data bytes to the transport.
[ "Write", "a", "list", "(", "or", "any", "iterable", ")", "of", "data", "bytes", "to", "the", "transport", "." ]
def writelines(self, list_of_data): """Write a list (or any iterable) of data bytes to the transport. The default implementation concatenates the arguments and calls write() on the result. """ data = b''.join(list_of_data) self.write(data)
[ "def", "writelines", "(", "self", ",", "list_of_data", ")", ":", "data", "=", "b''", ".", "join", "(", "list_of_data", ")", "self", ".", "write", "(", "data", ")" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/asyncio/transports.py#L110-L117
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/volatility/obj.py
python
Profile.metadata
(self)
return result
Returns a read-only dictionary copy of the metadata associated with a profile
Returns a read-only dictionary copy of the metadata associated with a profile
[ "Returns", "a", "read", "-", "only", "dictionary", "copy", "of", "the", "metadata", "associated", "with", "a", "profile" ]
def metadata(self): """ Returns a read-only dictionary copy of the metadata associated with a profile """ prefix = '_md_' result = {} for i in dir(self): if i.startswith(prefix): result[i[len(prefix):]] = getattr(self, i) return result
[ "def", "metadata", "(", "self", ")", ":", "prefix", "=", "'_md_'", "result", "=", "{", "}", "for", "i", "in", "dir", "(", "self", ")", ":", "if", "i", ".", "startswith", "(", "prefix", ")", ":", "result", "[", "i", "[", "len", "(", "prefix", ")...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/volatility/obj.py#L956-L963
mrjoes/tornadio2
c251c65b2f6921feafc72e39ece647cfe05e9909
tornadio2/conn.py
python
SocketConnection.deque_ack
(self, msg_id, ack_data)
Dequeue acknowledgment callback
Dequeue acknowledgment callback
[ "Dequeue", "acknowledgment", "callback" ]
def deque_ack(self, msg_id, ack_data): """Dequeue acknowledgment callback""" if msg_id in self.ack_queue: time_stamp, callback, message = self.ack_queue.pop(msg_id) callback(message, ack_data) else: logger.error('Received invalid msg_id for ACK: %s' % msg_id)
[ "def", "deque_ack", "(", "self", ",", "msg_id", ",", "ack_data", ")", ":", "if", "msg_id", "in", "self", ".", "ack_queue", ":", "time_stamp", ",", "callback", ",", "message", "=", "self", ".", "ack_queue", ".", "pop", "(", "msg_id", ")", "callback", "(...
https://github.com/mrjoes/tornadio2/blob/c251c65b2f6921feafc72e39ece647cfe05e9909/tornadio2/conn.py#L294-L301
scikit-hep/awkward-0.x
dd885bef15814f588b58944d2505296df4aaae0e
awkward0/generate.py
python
typeof
(obj)
[]
def typeof(obj): if obj is None: return None elif isinstance(obj, (bool, numpy.bool_)): return BoolFillable elif isinstance(obj, (numbers.Number, awkward0.numpy.number)): return NumberFillable elif isinstance(obj, bytes): return BytesFillable elif isinstance(obj, awkward0.util.string): return StringFillable elif isinstance(obj, dict): if any(not isinstance(x, str) for x in obj): raise TypeError("only dicts with str-typed keys may be converted") if len(obj) == 0: return None else: return set(obj) elif isinstance(obj, tuple) and hasattr(obj, "_fields") and obj._fields is type(obj)._fields: return obj._fields, type(obj) elif isinstance(obj, Iterable): return JaggedFillable else: return set(n for n in obj.__dict__ if not n.startswith("_")), type(obj)
[ "def", "typeof", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "obj", ",", "(", "bool", ",", "numpy", ".", "bool_", ")", ")", ":", "return", "BoolFillable", "elif", "isinstance", "(", "obj", ",", ...
https://github.com/scikit-hep/awkward-0.x/blob/dd885bef15814f588b58944d2505296df4aaae0e/awkward0/generate.py#L18-L46
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/pyparsing.py
python
locatedExpr
(expr)
return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end"))
Helper to decorate a returned token with its starting and ending locations in the input string. This helper adds the following results names: - locn_start = location where matched expression begins - locn_end = location where matched expression ends - value = the actual parsed results Be careful if the input text contains C{<TAB>} characters, you may want to call C{L{ParserElement.parseWithTabs}} Example:: wd = Word(alphas) for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"): print(match) prints:: [[0, 'ljsdf', 5]] [[8, 'lksdjjf', 15]] [[18, 'lkkjj', 23]]
Helper to decorate a returned token with its starting and ending locations in the input string. This helper adds the following results names: - locn_start = location where matched expression begins - locn_end = location where matched expression ends - value = the actual parsed results
[ "Helper", "to", "decorate", "a", "returned", "token", "with", "its", "starting", "and", "ending", "locations", "in", "the", "input", "string", ".", "This", "helper", "adds", "the", "following", "results", "names", ":", "-", "locn_start", "=", "location", "wh...
def locatedExpr(expr): """ Helper to decorate a returned token with its starting and ending locations in the input string. This helper adds the following results names: - locn_start = location where matched expression begins - locn_end = location where matched expression ends - value = the actual parsed results Be careful if the input text contains C{<TAB>} characters, you may want to call C{L{ParserElement.parseWithTabs}} Example:: wd = Word(alphas) for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"): print(match) prints:: [[0, 'ljsdf', 5]] [[8, 'lksdjjf', 15]] [[18, 'lkkjj', 23]] """ locator = Empty().setParseAction(lambda s,l,t: l) return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end"))
[ "def", "locatedExpr", "(", "expr", ")", ":", "locator", "=", "Empty", "(", ")", ".", "setParseAction", "(", "lambda", "s", ",", "l", ",", "t", ":", "l", ")", "return", "Group", "(", "locator", "(", "\"locn_start\"", ")", "+", "expr", "(", "\"value\""...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/pyparsing.py#L4684-L4705
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/cmd/manage.py
python
methods_of
(obj)
return result
Return non-private methods from an object. Get all callable methods of an object that don't start with underscore :return: a list of tuples of the form (method_name, method)
Return non-private methods from an object.
[ "Return", "non", "-", "private", "methods", "from", "an", "object", "." ]
def methods_of(obj): """Return non-private methods from an object. Get all callable methods of an object that don't start with underscore :return: a list of tuples of the form (method_name, method) """ result = [] for i in dir(obj): if isinstance(getattr(obj, i), collections_abc.Callable) and not i.startswith('_'): result.append((i, getattr(obj, i))) return result
[ "def", "methods_of", "(", "obj", ")", ":", "result", "=", "[", "]", "for", "i", "in", "dir", "(", "obj", ")", ":", "if", "isinstance", "(", "getattr", "(", "obj", ",", "i", ")", ",", "collections_abc", ".", "Callable", ")", "and", "not", "i", "."...
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/cmd/manage.py#L964-L975
iclavera/learning_to_adapt
bd7d99ba402521c96631e7d09714128f549db0f1
learning_to_adapt/spaces/box.py
python
Box.contains
(self, x)
return x.shape == self.shape and (x >= self.low).all() and (x <= self.high).all()
[]
def contains(self, x): return x.shape == self.shape and (x >= self.low).all() and (x <= self.high).all()
[ "def", "contains", "(", "self", ",", "x", ")", ":", "return", "x", ".", "shape", "==", "self", ".", "shape", "and", "(", "x", ">=", "self", ".", "low", ")", ".", "all", "(", ")", "and", "(", "x", "<=", "self", ".", "high", ")", ".", "all", ...
https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/learning_to_adapt/spaces/box.py#L32-L33
Scalsol/mega.pytorch
a6aa6e0537b82d70da94228100a51e6a53d98f82
mega_core/modeling/roi_heads/box_head/roi_box_feature_extractors.py
python
AttentionExtractor.__init__
(self, cfg, in_channels)
[]
def __init__(self, cfg, in_channels): super(AttentionExtractor, self).__init__()
[ "def", "__init__", "(", "self", ",", "cfg", ",", "in_channels", ")", ":", "super", "(", "AttentionExtractor", ",", "self", ")", ".", "__init__", "(", ")" ]
https://github.com/Scalsol/mega.pytorch/blob/a6aa6e0537b82d70da94228100a51e6a53d98f82/mega_core/modeling/roi_heads/box_head/roi_box_feature_extractors.py#L122-L123
504ensicsLabs/DAMM
60e7ec7dacd6087cd6320b3615becca9b4cf9b24
volatility/addrspace.py
python
BaseAddressSpace.zread
(self, addr, length)
Read data from a certain offset padded with \x00 where data is not available
Read data from a certain offset padded with \x00 where data is not available
[ "Read", "data", "from", "a", "certain", "offset", "padded", "with", "\\", "x00", "where", "data", "is", "not", "available" ]
def zread(self, addr, length): """ Read data from a certain offset padded with \x00 where data is not available """
[ "def", "zread", "(", "self", ",", "addr", ",", "length", ")", ":" ]
https://github.com/504ensicsLabs/DAMM/blob/60e7ec7dacd6087cd6320b3615becca9b4cf9b24/volatility/addrspace.py#L130-L131
Arelle/Arelle
20f3d8a8afd41668e1520799acd333349ce0ba17
arelle/webserver/bottle-no2to3.py
python
BaseResponse.add_header
(self, name, value)
Add an additional response header, not removing duplicates.
Add an additional response header, not removing duplicates.
[ "Add", "an", "additional", "response", "header", "not", "removing", "duplicates", "." ]
def add_header(self, name, value): ''' Add an additional response header, not removing duplicates. ''' self._headers.setdefault(_hkey(name), []).append(str(value))
[ "def", "add_header", "(", "self", ",", "name", ",", "value", ")", ":", "self", ".", "_headers", ".", "setdefault", "(", "_hkey", "(", "name", ")", ",", "[", "]", ")", ".", "append", "(", "str", "(", "value", ")", ")" ]
https://github.com/Arelle/Arelle/blob/20f3d8a8afd41668e1520799acd333349ce0ba17/arelle/webserver/bottle-no2to3.py#L1300-L1302
skarra/ASynK
e908a1ad670a2d79f791a6a7539392e078a64add
asynk/pimdb_cd.py
python
CDPIMDB.prep_for_sync
(self, dbid, pname, dr)
See the documentation in class PIMDB
See the documentation in class PIMDB
[ "See", "the", "documentation", "in", "class", "PIMDB" ]
def prep_for_sync (self, dbid, pname, dr): """See the documentation in class PIMDB""" ## FIXME: Can do stuff like ensure if the folder is still there, and ## such error checking. pass
[ "def", "prep_for_sync", "(", "self", ",", "dbid", ",", "pname", ",", "dr", ")", ":", "## FIXME: Can do stuff like ensure if the folder is still there, and", "## such error checking.", "pass" ]
https://github.com/skarra/ASynK/blob/e908a1ad670a2d79f791a6a7539392e078a64add/asynk/pimdb_cd.py#L146-L151
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/mailbox.py
python
MH._dump_sequences
(self, message, key)
Inspect a new MHMessage and update sequences appropriately.
Inspect a new MHMessage and update sequences appropriately.
[ "Inspect", "a", "new", "MHMessage", "and", "update", "sequences", "appropriately", "." ]
def _dump_sequences(self, message, key): """Inspect a new MHMessage and update sequences appropriately.""" pending_sequences = message.get_sequences() all_sequences = self.get_sequences() for name, key_list in all_sequences.iteritems(): if name in pending_sequences: key_list.append(key) elif key in key_list: del key_list[key_list.index(key)] for sequence in pending_sequences: if sequence not in all_sequences: all_sequences[sequence] = [key] self.set_sequences(all_sequences)
[ "def", "_dump_sequences", "(", "self", ",", "message", ",", "key", ")", ":", "pending_sequences", "=", "message", ".", "get_sequences", "(", ")", "all_sequences", "=", "self", ".", "get_sequences", "(", ")", "for", "name", ",", "key_list", "in", "all_sequenc...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/mailbox.py#L1153-L1165
mozilla/addons-server
cbfb29e5be99539c30248d70b93bb15e1c1bc9d7
src/olympia/api/authentication.py
python
JWTKeyAuthentication.authenticate_credentials
(self, payload)
return api_key.user
Returns a verified AMO user who is active and allowed to make API requests.
Returns a verified AMO user who is active and allowed to make API requests.
[ "Returns", "a", "verified", "AMO", "user", "who", "is", "active", "and", "allowed", "to", "make", "API", "requests", "." ]
def authenticate_credentials(self, payload): """ Returns a verified AMO user who is active and allowed to make API requests. """ if 'orig_iat' in payload: msg = ( "API key based tokens are not refreshable, don't include " '`orig_iat` in their payload.' ) raise exceptions.AuthenticationFailed(msg) try: api_key = APIKey.get_jwt_key(key=payload['iss']) except APIKey.DoesNotExist: msg = 'Invalid API Key.' raise exceptions.AuthenticationFailed(msg) if api_key.user.deleted: msg = 'User account is disabled.' raise exceptions.AuthenticationFailed(msg) if not api_key.user.read_dev_agreement: msg = 'User has not read developer agreement.' raise exceptions.AuthenticationFailed(msg) core.set_user(api_key.user) return api_key.user
[ "def", "authenticate_credentials", "(", "self", ",", "payload", ")", ":", "if", "'orig_iat'", "in", "payload", ":", "msg", "=", "(", "\"API key based tokens are not refreshable, don't include \"", "'`orig_iat` in their payload.'", ")", "raise", "exceptions", ".", "Authent...
https://github.com/mozilla/addons-server/blob/cbfb29e5be99539c30248d70b93bb15e1c1bc9d7/src/olympia/api/authentication.py#L226-L251
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/plugins/nutritional_information/nutritionDisplay.py
python
SimpleIngredientCalculator.setup_boxes
(self)
[]
def setup_boxes (self): self.hbb = Gtk.HBox() self.vbox.add(self.hbb) self.amtBox = Gtk.SpinButton() self.amtBox.set_range(0.075,5000) self.amtBox.set_increments(0.5,5) self.amtBox.set_sensitive(True) self.amtBox.set_value(1) self.amtBox.connect('changed',self.nutBoxCB) self.unitBox = Gtk.ComboBox() self.unitBox.set_model(self.umodel) cell = Gtk.CellRendererText() self.unitBox.pack_start(cell, True) self.unitBox.add_attribute(cell, 'text', 1) cb.setup_typeahead(self.unitBox) self.itmBox = Gtk.Entry() self.nutBox = Gtk.ComboBox() self.nutBox.pack_start(cell, True) self.nutBox.add_attribute(cell,'text',0) self.nutBox.connect('changed',self.nutBoxCB) self.unitBox.connect('changed',self.nutBoxCB) self.refreshButton = Gtk.Button('Update Nutritional Items') self.refreshButton.connect('clicked',self.updateCombo) self.hbb.add(self.amtBox) self.hbb.add(self.unitBox) self.hbb.add(self.itmBox) self.hbb.add(self.refreshButton) self.vbox.add(self.nutBox) self.nutLabel=Gtk.Label() self.vbox.add(self.nutLabel) self.vbox.show_all()
[ "def", "setup_boxes", "(", "self", ")", ":", "self", ".", "hbb", "=", "Gtk", ".", "HBox", "(", ")", "self", ".", "vbox", ".", "add", "(", "self", ".", "hbb", ")", "self", ".", "amtBox", "=", "Gtk", ".", "SpinButton", "(", ")", "self", ".", "amt...
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/plugins/nutritional_information/nutritionDisplay.py#L82-L112
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/Toggl-Time-Tracking/alp/request/requests_cache/core.py
python
configure
(cache_name='cache', backend='sqlite', expire_after=None, allowable_codes=(200,), allowable_methods=('GET',), monkey_patch=True, **backend_options)
Configure cache storage and patch ``requests`` library to transparently cache responses :param cache_name: for ``sqlite`` backend: cache file will start with this prefix, e.g ``cache.sqlite`` for ``mongodb``: it's used as database name :param backend: cache backend e.g ``'sqlite'``, ``'mongodb'``, ``'memory'``. See :ref:`persistence` :param expire_after: number of minutes after cache will be expired or `None` (default) to ignore expiration :type expire_after: int, float or None :param allowable_codes: limit caching only for response with this codes (default: 200) :type allowable_codes: tuple :param allowable_methods: cache only requests of this methods (default: 'GET') :type allowable_methods: tuple :param monkey_patch: patch ``requests.Request.send`` if `True` (default), otherwise cache will not work until calling :func:`redo_patch` or using :func:`enabled` context manager :kwarg backend_options: options for chosen backend. See corresponding :ref:`sqlite <backends_sqlite>` and :ref:`mongo <backends_mongo>` backends API documentation
Configure cache storage and patch ``requests`` library to transparently cache responses
[ "Configure", "cache", "storage", "and", "patch", "requests", "library", "to", "transparently", "cache", "responses" ]
def configure(cache_name='cache', backend='sqlite', expire_after=None, allowable_codes=(200,), allowable_methods=('GET',), monkey_patch=True, **backend_options): """ Configure cache storage and patch ``requests`` library to transparently cache responses :param cache_name: for ``sqlite`` backend: cache file will start with this prefix, e.g ``cache.sqlite`` for ``mongodb``: it's used as database name :param backend: cache backend e.g ``'sqlite'``, ``'mongodb'``, ``'memory'``. See :ref:`persistence` :param expire_after: number of minutes after cache will be expired or `None` (default) to ignore expiration :type expire_after: int, float or None :param allowable_codes: limit caching only for response with this codes (default: 200) :type allowable_codes: tuple :param allowable_methods: cache only requests of this methods (default: 'GET') :type allowable_methods: tuple :param monkey_patch: patch ``requests.Request.send`` if `True` (default), otherwise cache will not work until calling :func:`redo_patch` or using :func:`enabled` context manager :kwarg backend_options: options for chosen backend. See corresponding :ref:`sqlite <backends_sqlite>` and :ref:`mongo <backends_mongo>` backends API documentation """ try: global _cache _cache = backends.registry[backend](cache_name, **backend_options) except KeyError: raise ValueError('Unsupported backend "%s" try one of: %s' % (backend, ', '.join(backends.registry.keys()))) if monkey_patch: redo_patch() _config['expire_after'] = expire_after _config['allowable_codes'] = allowable_codes _config['allowable_methods'] = allowable_methods
[ "def", "configure", "(", "cache_name", "=", "'cache'", ",", "backend", "=", "'sqlite'", ",", "expire_after", "=", "None", ",", "allowable_codes", "=", "(", "200", ",", ")", ",", "allowable_methods", "=", "(", "'GET'", ",", ")", ",", "monkey_patch", "=", ...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/Toggl-Time-Tracking/alp/request/requests_cache/core.py#L27-L62
Yuliang-Liu/Box_Discretization_Network
5b3a30c97429ef8e5c5e1c4e2476c7d9abdc03e6
maskrcnn_benchmark/modeling/backbone/fbnet_builder.py
python
unify_arch_def
(arch_def)
return ret
unify the arch_def to: { ..., "arch": [ { "stage_idx": idx, "block_idx": idx, ... }, {}, ... ] }
unify the arch_def to: { ..., "arch": [ { "stage_idx": idx, "block_idx": idx, ... }, {}, ... ] }
[ "unify", "the", "arch_def", "to", ":", "{", "...", "arch", ":", "[", "{", "stage_idx", ":", "idx", "block_idx", ":", "idx", "...", "}", "{}", "...", "]", "}" ]
def unify_arch_def(arch_def): """ unify the arch_def to: { ..., "arch": [ { "stage_idx": idx, "block_idx": idx, ... }, {}, ... ] } """ ret = copy.deepcopy(arch_def) assert "block_cfg" in arch_def and "stages" in arch_def["block_cfg"] assert "stages" not in ret # copy 'first', 'last' etc. inside arch_def['block_cfg'] to ret ret.update({x: arch_def["block_cfg"][x] for x in arch_def["block_cfg"]}) ret["stages"] = _block_cfgs_to_list(arch_def["block_cfg"]["stages"]) del ret["block_cfg"] assert "block_op_type" in arch_def _add_to_arch(ret["stages"], arch_def["block_op_type"], "block_op_type") del ret["block_op_type"] return ret
[ "def", "unify_arch_def", "(", "arch_def", ")", ":", "ret", "=", "copy", ".", "deepcopy", "(", "arch_def", ")", "assert", "\"block_cfg\"", "in", "arch_def", "and", "\"stages\"", "in", "arch_def", "[", "\"block_cfg\"", "]", "assert", "\"stages\"", "not", "in", ...
https://github.com/Yuliang-Liu/Box_Discretization_Network/blob/5b3a30c97429ef8e5c5e1c4e2476c7d9abdc03e6/maskrcnn_benchmark/modeling/backbone/fbnet_builder.py#L641-L668
mjq11302010044/RRPN_pytorch
a966f6f238c03498514742cde5cd98e51efb440c
maskrcnn_benchmark/modeling/roi_heads/mask_head/loss.py
python
project_masks_on_boxes
(segmentation_masks, proposals, discretization_size)
return torch.stack(masks, dim=0).to(device, dtype=torch.float32)
Given segmentation masks and the bounding boxes corresponding to the location of the masks in the image, this function crops and resizes the masks in the position defined by the boxes. This prepares the masks for them to be fed to the loss computation as the targets. Arguments: segmentation_masks: an instance of SegmentationMask proposals: an instance of BoxList
Given segmentation masks and the bounding boxes corresponding to the location of the masks in the image, this function crops and resizes the masks in the position defined by the boxes. This prepares the masks for them to be fed to the loss computation as the targets.
[ "Given", "segmentation", "masks", "and", "the", "bounding", "boxes", "corresponding", "to", "the", "location", "of", "the", "masks", "in", "the", "image", "this", "function", "crops", "and", "resizes", "the", "masks", "in", "the", "position", "defined", "by", ...
def project_masks_on_boxes(segmentation_masks, proposals, discretization_size): """ Given segmentation masks and the bounding boxes corresponding to the location of the masks in the image, this function crops and resizes the masks in the position defined by the boxes. This prepares the masks for them to be fed to the loss computation as the targets. Arguments: segmentation_masks: an instance of SegmentationMask proposals: an instance of BoxList """ masks = [] M = discretization_size device = proposals.bbox.device proposals = proposals.convert("xyxy") assert segmentation_masks.size == proposals.size, "{}, {}".format( segmentation_masks, proposals ) # TODO put the proposals on the CPU, as the representation for the # masks is not efficient GPU-wise (possibly several small tensors for # representing a single instance mask) proposals = proposals.bbox.to(torch.device("cpu")) for segmentation_mask, proposal in zip(segmentation_masks, proposals): # crop the masks, resize them to the desired resolution and # then convert them to the tensor representation, # instead of the list representation that was used cropped_mask = segmentation_mask.crop(proposal) scaled_mask = cropped_mask.resize((M, M)) mask = scaled_mask.convert(mode="mask") masks.append(mask) if len(masks) == 0: return torch.empty(0, dtype=torch.float32, device=device) return torch.stack(masks, dim=0).to(device, dtype=torch.float32)
[ "def", "project_masks_on_boxes", "(", "segmentation_masks", ",", "proposals", ",", "discretization_size", ")", ":", "masks", "=", "[", "]", "M", "=", "discretization_size", "device", "=", "proposals", ".", "bbox", ".", "device", "proposals", "=", "proposals", "....
https://github.com/mjq11302010044/RRPN_pytorch/blob/a966f6f238c03498514742cde5cd98e51efb440c/maskrcnn_benchmark/modeling/roi_heads/mask_head/loss.py#L11-L44
sunnyxiaohu/R-C3D.pytorch
e8731af7b95f1dc934f6604f9c09e3c4ead74db5
lib/tf_model_zoo/models/differential_privacy/multiple_teachers/aggregation.py
python
noisy_max
(logits, lap_scale, return_clean_votes=False)
This aggregation mechanism takes the softmax/logit output of several models resulting from inference on identical inputs and computes the noisy-max of the votes for candidate classes to select a label for each sample: it adds Laplacian noise to label counts and returns the most frequent label. :param logits: logits or probabilities for each sample :param lap_scale: scale of the Laplacian noise to be added to counts :param return_clean_votes: if set to True, also returns clean votes (without Laplacian noise). This can be used to perform the privacy analysis of this aggregation mechanism. :return: pair of result and (if clean_votes is set to True) the clean counts for each class per sample and the the original labels produced by the teachers.
This aggregation mechanism takes the softmax/logit output of several models resulting from inference on identical inputs and computes the noisy-max of the votes for candidate classes to select a label for each sample: it adds Laplacian noise to label counts and returns the most frequent label. :param logits: logits or probabilities for each sample :param lap_scale: scale of the Laplacian noise to be added to counts :param return_clean_votes: if set to True, also returns clean votes (without Laplacian noise). This can be used to perform the privacy analysis of this aggregation mechanism. :return: pair of result and (if clean_votes is set to True) the clean counts for each class per sample and the the original labels produced by the teachers.
[ "This", "aggregation", "mechanism", "takes", "the", "softmax", "/", "logit", "output", "of", "several", "models", "resulting", "from", "inference", "on", "identical", "inputs", "and", "computes", "the", "noisy", "-", "max", "of", "the", "votes", "for", "candid...
def noisy_max(logits, lap_scale, return_clean_votes=False): """ This aggregation mechanism takes the softmax/logit output of several models resulting from inference on identical inputs and computes the noisy-max of the votes for candidate classes to select a label for each sample: it adds Laplacian noise to label counts and returns the most frequent label. :param logits: logits or probabilities for each sample :param lap_scale: scale of the Laplacian noise to be added to counts :param return_clean_votes: if set to True, also returns clean votes (without Laplacian noise). This can be used to perform the privacy analysis of this aggregation mechanism. :return: pair of result and (if clean_votes is set to True) the clean counts for each class per sample and the the original labels produced by the teachers. """ # Compute labels from logits/probs and reshape array properly labels = labels_from_probs(logits) labels_shape = np.shape(labels) labels = labels.reshape((labels_shape[0], labels_shape[1])) # Initialize array to hold final labels result = np.zeros(int(labels_shape[1])) if return_clean_votes: # Initialize array to hold clean votes for each sample clean_votes = np.zeros((int(labels_shape[1]), 10)) # Parse each sample for i in xrange(int(labels_shape[1])): # Count number of votes assigned to each class label_counts = np.bincount(labels[:, i], minlength=10) if return_clean_votes: # Store vote counts for export clean_votes[i] = label_counts # Cast in float32 to prepare before addition of Laplacian noise label_counts = np.asarray(label_counts, dtype=np.float32) # Sample independent Laplacian noise for each class for item in xrange(10): label_counts[item] += np.random.laplace(loc=0.0, scale=float(lap_scale)) # Result is the most frequent label result[i] = np.argmax(label_counts) # Cast labels to np.int32 for compatibility with deep_cnn.py feed dictionaries result = np.asarray(result, dtype=np.int32) if return_clean_votes: # Returns several array, which are later saved: # result: labels obtained from the noisy aggregation # clean_votes: the number of teacher votes assigned to each sample and class # labels: the labels assigned by teachers (before the noisy aggregation) return result, clean_votes, labels else: # Only return labels resulting from noisy aggregation return result
[ "def", "noisy_max", "(", "logits", ",", "lap_scale", ",", "return_clean_votes", "=", "False", ")", ":", "# Compute labels from logits/probs and reshape array properly", "labels", "=", "labels_from_probs", "(", "logits", ")", "labels_shape", "=", "np", ".", "shape", "(...
https://github.com/sunnyxiaohu/R-C3D.pytorch/blob/e8731af7b95f1dc934f6604f9c09e3c4ead74db5/lib/tf_model_zoo/models/differential_privacy/multiple_teachers/aggregation.py#L42-L100
OpenIDC/pyoidc
bd510e49ebd6d8816e3ee94e62a3e86e907a0f8d
src/oic/oauth2/message.py
python
Message.from_dict
(self, dictionary, **kwargs)
return self
Direct translation so the value for one key might be a list or a single value. :param dictionary: The info :return: A class instance or raise an exception on error
Direct translation so the value for one key might be a list or a single value.
[ "Direct", "translation", "so", "the", "value", "for", "one", "key", "might", "be", "a", "list", "or", "a", "single", "value", "." ]
def from_dict(self, dictionary, **kwargs): """ Direct translation so the value for one key might be a list or a single value. :param dictionary: The info :return: A class instance or raise an exception on error """ _spec = self.c_param for key, val in dictionary.items(): if val in ("", [""]): continue cparam = self._extract_cparam(key, _spec) if cparam is not None: self._add_value( key, cparam.type, key, val, cparam.deserializer, cparam.null_allowed ) else: self._dict[key] = val return self
[ "def", "from_dict", "(", "self", ",", "dictionary", ",", "*", "*", "kwargs", ")", ":", "_spec", "=", "self", ".", "c_param", "for", "key", ",", "val", "in", "dictionary", ".", "items", "(", ")", ":", "if", "val", "in", "(", "\"\"", ",", "[", "\"\...
https://github.com/OpenIDC/pyoidc/blob/bd510e49ebd6d8816e3ee94e62a3e86e907a0f8d/src/oic/oauth2/message.py#L330-L349
mattloper/chumpy
8c777ce1650a0c48dc74c43bd8b7b3176ebcd8f9
chumpy/monitor.py
python
DrWrtProfiler.show_tree
(self, label)
show tree from the root node
show tree from the root node
[ "show", "tree", "from", "the", "root", "node" ]
def show_tree(self, label): ''' show tree from the root node ''' self.root.show_tree_cache(label)
[ "def", "show_tree", "(", "self", ",", "label", ")", ":", "self", ".", "root", ".", "show_tree_cache", "(", "label", ")" ]
https://github.com/mattloper/chumpy/blob/8c777ce1650a0c48dc74c43bd8b7b3176ebcd8f9/chumpy/monitor.py#L133-L137
dirn/When.py
25d40a8bc4610f052d41e13c0a4baac2b2f03185
when.py
python
today
()
return datetime.date.today()
Get a date representing the current date. :returns: datetime.date -- the current date.
Get a date representing the current date.
[ "Get", "a", "date", "representing", "the", "current", "date", "." ]
def today(): """Get a date representing the current date. :returns: datetime.date -- the current date. """ return datetime.date.today()
[ "def", "today", "(", ")", ":", "return", "datetime", ".", "date", ".", "today", "(", ")" ]
https://github.com/dirn/When.py/blob/25d40a8bc4610f052d41e13c0a4baac2b2f03185/when.py#L737-L743
seanbell/opensurfaces
7f3e987560faa62cd37f821760683ccd1e053c7c
prefilter/generate-materials-vwd.py
python
cmd
(command)
Run system command and exit on failure
Run system command and exit on failure
[ "Run", "system", "command", "and", "exit", "on", "failure" ]
def cmd(command): """ Run system command and exit on failure """ print command if os.system(command) != 0: print 'Error running "%s"' % command print 'Exiting' sys.exit(1)
[ "def", "cmd", "(", "command", ")", ":", "print", "command", "if", "os", ".", "system", "(", "command", ")", "!=", "0", ":", "print", "'Error running \"%s\"'", "%", "command", "print", "'Exiting'", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/seanbell/opensurfaces/blob/7f3e987560faa62cd37f821760683ccd1e053c7c/prefilter/generate-materials-vwd.py#L7-L13
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/computers.py
python
Computer._hostname_validator
(cls, hostname: str)
Validates the hostname.
Validates the hostname.
[ "Validates", "the", "hostname", "." ]
def _hostname_validator(cls, hostname: str) -> None: """ Validates the hostname. """ if not (hostname or hostname.strip()): raise exceptions.ValidationError('No hostname specified')
[ "def", "_hostname_validator", "(", "cls", ",", "hostname", ":", "str", ")", "->", "None", ":", "if", "not", "(", "hostname", "or", "hostname", ".", "strip", "(", ")", ")", ":", "raise", "exceptions", ".", "ValidationError", "(", "'No hostname specified'", ...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/computers.py#L136-L141
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/db/backends/__init__.py
python
BaseDatabaseOperations.date_trunc_sql
(self, lookup_type, field_name)
Given a lookup_type of 'year', 'month' or 'day', returns the SQL that truncates the given date field field_name to a DATE object with only the given specificity.
Given a lookup_type of 'year', 'month' or 'day', returns the SQL that truncates the given date field field_name to a DATE object with only the given specificity.
[ "Given", "a", "lookup_type", "of", "year", "month", "or", "day", "returns", "the", "SQL", "that", "truncates", "the", "given", "date", "field", "field_name", "to", "a", "DATE", "object", "with", "only", "the", "given", "specificity", "." ]
def date_trunc_sql(self, lookup_type, field_name): """ Given a lookup_type of 'year', 'month' or 'day', returns the SQL that truncates the given date field field_name to a DATE object with only the given specificity. """ raise NotImplementedError()
[ "def", "date_trunc_sql", "(", "self", ",", "lookup_type", ",", "field_name", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/db/backends/__init__.py#L523-L529
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/decimal.py
python
Decimal.shift
(self, other, context=None)
return _dec_from_triple(self._sign, shifted.lstrip('0') or '0', self._exp)
Returns a shifted copy of self, value-of-other times.
Returns a shifted copy of self, value-of-other times.
[ "Returns", "a", "shifted", "copy", "of", "self", "value", "-", "of", "-", "other", "times", "." ]
def shift(self, other, context=None): """Returns a shifted copy of self, value-of-other times.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) ans = self._check_nans(other, context) if ans: return ans if other._exp != 0: return context._raise_error(InvalidOperation) if not (-context.prec <= int(other) <= context.prec): return context._raise_error(InvalidOperation) if self._isinfinity(): return Decimal(self) # get values, pad if necessary torot = int(other) rotdig = self._int topad = context.prec - len(rotdig) if topad > 0: rotdig = '0'*topad + rotdig elif topad < 0: rotdig = rotdig[-topad:] # let's shift! if torot < 0: shifted = rotdig[:torot] else: shifted = rotdig + '0'*torot shifted = shifted[-context.prec:] return _dec_from_triple(self._sign, shifted.lstrip('0') or '0', self._exp)
[ "def", "shift", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "other", "=", "_convert_other", "(", "other", ",", "raiseit", "=", "True", ")", "ans", "=", ...
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/decimal.py#L3568-L3604
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/state_plugins/callstack.py
python
CallStack.__getitem__
(self, k)
Returns the CallStack at index k, indexing from the top of the stack.
Returns the CallStack at index k, indexing from the top of the stack.
[ "Returns", "the", "CallStack", "at", "index", "k", "indexing", "from", "the", "top", "of", "the", "stack", "." ]
def __getitem__(self, k): """ Returns the CallStack at index k, indexing from the top of the stack. """ orig_k = k for i in self: if k == 0: return i k -= 1 raise IndexError(orig_k)
[ "def", "__getitem__", "(", "self", ",", "k", ")", ":", "orig_k", "=", "k", "for", "i", "in", "self", ":", "if", "k", "==", "0", ":", "return", "i", "k", "-=", "1", "raise", "IndexError", "(", "orig_k", ")" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/state_plugins/callstack.py#L81-L90
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/html5lib/treewalkers/__init__.py
python
concatenateCharacterTokens
(tokens)
[]
def concatenateCharacterTokens(tokens): pendingCharacters = [] for token in tokens: type = token["type"] if type in ("Characters", "SpaceCharacters"): pendingCharacters.append(token["data"]) else: if pendingCharacters: yield {"type": "Characters", "data": "".join(pendingCharacters)} pendingCharacters = [] yield token if pendingCharacters: yield {"type": "Characters", "data": "".join(pendingCharacters)}
[ "def", "concatenateCharacterTokens", "(", "tokens", ")", ":", "pendingCharacters", "=", "[", "]", "for", "token", "in", "tokens", ":", "type", "=", "token", "[", "\"type\"", "]", "if", "type", "in", "(", "\"Characters\"", ",", "\"SpaceCharacters\"", ")", ":"...
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/html5lib/treewalkers/__init__.py#L60-L72
marcosfede/algorithms
1ee7c815f9d556c9cef4d4b0d21ee3a409d21629
maths/is_strobogrammatic.py
python
is_strobogrammatic2
(num: str)
return num == num[::-1].replace('6', '#').replace('9', '6').replace('#', '9')
Another implementation.
Another implementation.
[ "Another", "implementation", "." ]
def is_strobogrammatic2(num: str): """Another implementation.""" return num == num[::-1].replace('6', '#').replace('9', '6').replace('#', '9')
[ "def", "is_strobogrammatic2", "(", "num", ":", "str", ")", ":", "return", "num", "==", "num", "[", ":", ":", "-", "1", "]", ".", "replace", "(", "'6'", ",", "'#'", ")", ".", "replace", "(", "'9'", ",", "'6'", ")", ".", "replace", "(", "'#'", ",...
https://github.com/marcosfede/algorithms/blob/1ee7c815f9d556c9cef4d4b0d21ee3a409d21629/maths/is_strobogrammatic.py#L29-L31
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
opy/byterun/pyvm2.py
python
debug
(msg, *args)
[]
def debug(msg, *args): if not VERBOSE: return debug1(msg, *args)
[ "def", "debug", "(", "msg", ",", "*", "args", ")", ":", "if", "not", "VERBOSE", ":", "return", "debug1", "(", "msg", ",", "*", "args", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/opy/byterun/pyvm2.py#L29-L33
facebookresearch/votenet
2f6d6d36ff98d96901182e935afe48ccee82d566
sunrgbd/sunrgbd_utils.py
python
rotz
(t)
return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
Rotation about the z-axis.
Rotation about the z-axis.
[ "Rotation", "about", "the", "z", "-", "axis", "." ]
def rotz(t): """Rotation about the z-axis.""" c = np.cos(t) s = np.sin(t) return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
[ "def", "rotz", "(", "t", ")", ":", "c", "=", "np", ".", "cos", "(", "t", ")", "s", "=", "np", ".", "sin", "(", "t", ")", "return", "np", ".", "array", "(", "[", "[", "c", ",", "-", "s", ",", "0", "]", ",", "[", "s", ",", "c", ",", "...
https://github.com/facebookresearch/votenet/blob/2f6d6d36ff98d96901182e935afe48ccee82d566/sunrgbd/sunrgbd_utils.py#L158-L164
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/github/Reaction.py
python
Reaction.delete
(self)
:calls: `DELETE /reactions/:id <https://developer.github.com/v3/reactions/#delete-a-reaction>`_ :rtype: None
:calls: `DELETE /reactions/:id <https://developer.github.com/v3/reactions/#delete-a-reaction>`_ :rtype: None
[ ":", "calls", ":", "DELETE", "/", "reactions", "/", ":", "id", "<https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "reactions", "/", "#delete", "-", "a", "-", "reaction", ">", "_", ":", "rtype", ":", "None" ]
def delete(self): """ :calls: `DELETE /reactions/:id <https://developer.github.com/v3/reactions/#delete-a-reaction>`_ :rtype: None """ self._requester.requestJsonAndCheck( "DELETE", self._parentUrl("") + "/reactions/" + str(self.id), headers={"Accept": Consts.mediaTypeReactionsPreview}, )
[ "def", "delete", "(", "self", ")", ":", "self", ".", "_requester", ".", "requestJsonAndCheck", "(", "\"DELETE\"", ",", "self", ".", "_parentUrl", "(", "\"\"", ")", "+", "\"/reactions/\"", "+", "str", "(", "self", ".", "id", ")", ",", "headers", "=", "{...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/github/Reaction.py#L75-L84
cloudant/bigcouch
8e9c1ec0ed1676ff152f10658f5c83a1a91fa8fe
couchjs/scons/scons-local-2.0.1/SCons/Node/FS.py
python
EntryProxy.__get_rsrcdir
(self)
return EntryProxy(self.get().srcnode().rfile().dir)
Returns the directory containing the source node linked to this node via VariantDir(), or the directory of this node if not linked.
Returns the directory containing the source node linked to this node via VariantDir(), or the directory of this node if not linked.
[ "Returns", "the", "directory", "containing", "the", "source", "node", "linked", "to", "this", "node", "via", "VariantDir", "()", "or", "the", "directory", "of", "this", "node", "if", "not", "linked", "." ]
def __get_rsrcdir(self): """Returns the directory containing the source node linked to this node via VariantDir(), or the directory of this node if not linked.""" return EntryProxy(self.get().srcnode().rfile().dir)
[ "def", "__get_rsrcdir", "(", "self", ")", ":", "return", "EntryProxy", "(", "self", ".", "get", "(", ")", ".", "srcnode", "(", ")", ".", "rfile", "(", ")", ".", "dir", ")" ]
https://github.com/cloudant/bigcouch/blob/8e9c1ec0ed1676ff152f10658f5c83a1a91fa8fe/couchjs/scons/scons-local-2.0.1/SCons/Node/FS.py#L469-L472
JasperSnoek/spearmint
b37a541be1ea035f82c7c82bbd93f5b4320e7d91
spearmint/spearmint/chooser/cma.py
python
FitnessFunctions.lineard
(self, x)
return -sum(x)
[]
def lineard(self, x): if 1 < 3 and any(array(x) < 0): return np.nan if 1 < 3 and sum([ (10 + i) * x[i] for i in xrange(len(x))]) > 50e3: return np.nan return -sum(x)
[ "def", "lineard", "(", "self", ",", "x", ")", ":", "if", "1", "<", "3", "and", "any", "(", "array", "(", "x", ")", "<", "0", ")", ":", "return", "np", ".", "nan", "if", "1", "<", "3", "and", "sum", "(", "[", "(", "10", "+", "i", ")", "*...
https://github.com/JasperSnoek/spearmint/blob/b37a541be1ea035f82c7c82bbd93f5b4320e7d91/spearmint/spearmint/chooser/cma.py#L6474-L6479
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/cloud/clouds/xen.py
python
vdi_list
(call=None, kwargs=None)
return ret
Return available Xen VDI images If this function is called with the ``-f`` or ``--function`` then it can return a list with minimal deatil using the ``terse=True`` keyword argument. .. code-block:: bash salt-cloud -f vdi_list myxen terse=True
Return available Xen VDI images
[ "Return", "available", "Xen", "VDI", "images" ]
def vdi_list(call=None, kwargs=None): """ Return available Xen VDI images If this function is called with the ``-f`` or ``--function`` then it can return a list with minimal deatil using the ``terse=True`` keyword argument. .. code-block:: bash salt-cloud -f vdi_list myxen terse=True """ if call == "action": raise SaltCloudException("This function must be called with -f or --function.") log.debug("kwargs is %s", kwargs) if kwargs is not None: if "terse" in kwargs: if kwargs["terse"] == "True": terse = True else: terse = False else: terse = False else: kwargs = {} terse = False session = _get_session() vdis = session.xenapi.VDI.get_all() ret = {} for vdi in vdis: data = session.xenapi.VDI.get_record(vdi) log.debug(type(terse)) if terse is True: ret[data.get("name_label")] = {"uuid": data.get("uuid"), "OpqueRef": vdi} else: data.update({"OpaqueRef": vdi}) ret[data.get("name_label")] = data return ret
[ "def", "vdi_list", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "call", "==", "\"action\"", ":", "raise", "SaltCloudException", "(", "\"This function must be called with -f or --function.\"", ")", "log", ".", "debug", "(", "\"kwargs is %s\...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/cloud/clouds/xen.py#L351-L389
scipy/scipy
e0a749f01e79046642ccfdc419edbf9e7ca141ad
scipy/fft/_helper.py
python
_init_nd_shape_and_axes
(x, shape, axes)
return _helper._init_nd_shape_and_axes(x, shape, axes)
Handle shape and axes arguments for N-D transforms. Returns the shape and axes in a standard form, taking into account negative values and checking for various potential errors. Parameters ---------- x : array_like The input array. shape : int or array_like of ints or None The shape of the result. If both `shape` and `axes` (see below) are None, `shape` is ``x.shape``; if `shape` is None but `axes` is not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``. If `shape` is -1, the size of the corresponding dimension of `x` is used. axes : int or array_like of ints or None Axes along which the calculation is computed. The default is over all axes. Negative indices are automatically converted to their positive counterparts. Returns ------- shape : array The shape of the result. It is a 1-D integer array. axes : array The shape of the result. It is a 1-D integer array.
Handle shape and axes arguments for N-D transforms.
[ "Handle", "shape", "and", "axes", "arguments", "for", "N", "-", "D", "transforms", "." ]
def _init_nd_shape_and_axes(x, shape, axes): """Handle shape and axes arguments for N-D transforms. Returns the shape and axes in a standard form, taking into account negative values and checking for various potential errors. Parameters ---------- x : array_like The input array. shape : int or array_like of ints or None The shape of the result. If both `shape` and `axes` (see below) are None, `shape` is ``x.shape``; if `shape` is None but `axes` is not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``. If `shape` is -1, the size of the corresponding dimension of `x` is used. axes : int or array_like of ints or None Axes along which the calculation is computed. The default is over all axes. Negative indices are automatically converted to their positive counterparts. Returns ------- shape : array The shape of the result. It is a 1-D integer array. axes : array The shape of the result. It is a 1-D integer array. """ return _helper._init_nd_shape_and_axes(x, shape, axes)
[ "def", "_init_nd_shape_and_axes", "(", "x", ",", "shape", ",", "axes", ")", ":", "return", "_helper", ".", "_init_nd_shape_and_axes", "(", "x", ",", "shape", ",", "axes", ")" ]
https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/fft/_helper.py#L70-L100
PaddlePaddle/Research
2da0bd6c72d60e9df403aff23a7802779561c4a1
ST_DM/KDD2021-MSTPAC/code/MST-PAC/frame/core/cpu_predictor.py
python
CPUPredictor.pred
(self, FLAGS, net_output)
run predict with datafeed
run predict with datafeed
[ "run", "predict", "with", "datafeed" ]
def pred(self, FLAGS, net_output): """ run predict with datafeed """ net_instance = self.paddle_env["factory"]["net"] #pre process net_instance.pred_format('_PRE_', frame_env=self) if FLAGS.data_reader == "dataset": logging.info("current worker file_list: %s" % FLAGS.file_list) self.paddle_env['dataset'].set_filelist(FLAGS.file_list.split(',')) if FLAGS.num_gpus > 0: #gpu mode: set thread num as 1 self.paddle_env['dataset'].set_thread(1) if FLAGS.dataset_mode == "InMemoryDataset": self.paddle_env['dataset'].load_into_memory() fetch_info = [x.name for x in self.paddle_env['fetch_targets']] self.paddle_env['exe'].infer_from_dataset(program=self.paddle_env['program'], dataset=self.paddle_env['dataset'], fetch_list=self.paddle_env['fetch_targets'], fetch_info=fetch_info, print_period=1) #FIXME: dataset not support batch level step #net_instance.pred_format(None) elif (FLAGS.data_reader == "async" or FLAGS.data_reader == "pyreader") \ and not FLAGS.py_reader_iterable: prog = self.paddle_env['program'] #exe_strategy = fluid.ExecutionStrategy() ## to clear tensor array after each iteration #exe_strategy.num_iteration_per_drop_scope = 1 #prog = fluid.CompiledProgram(prog).with_data_parallel( # exec_strategy=exe_strategy, places=self.create_places(FLAGS)[0]) #Before the start of every epoch, call start() to invoke PyReader; self.paddle_env["data_reader"].start() try: while True: result = self.paddle_env["exe"].run(program=prog, fetch_list=self.paddle_env['fetch_targets'], return_numpy=False) net_instance.pred_format(result) except fluid.core.EOFException: """ At the end of every epoch, read_file throws exception fluid.core.EOFException . Call reset() after catching up exception to reset the state of PyReader in order to start next epoch. """ self.paddle_env["data_reader"].reset() else: for sample in self.paddle_env["data_reader"](): if self.paddle_env["data_feeder"] is not None: sample = self.paddle_env["data_feeder"].feed(sample) result = self.paddle_env["exe"].run(program=self.paddle_env['program'], feed=sample, fetch_list=self.paddle_env['fetch_targets'], return_numpy=False) net_instance.pred_format(result) #post process net_instance.pred_format('_POST_', frame_env=self)
[ "def", "pred", "(", "self", ",", "FLAGS", ",", "net_output", ")", ":", "net_instance", "=", "self", ".", "paddle_env", "[", "\"factory\"", "]", "[", "\"net\"", "]", "#pre process", "net_instance", ".", "pred_format", "(", "'_PRE_'", ",", "frame_env", "=", ...
https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/ST_DM/KDD2021-MSTPAC/code/MST-PAC/frame/core/cpu_predictor.py#L117-L176
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/ssl.py
python
SSLObject.get_channel_binding
(self, cb_type="tls-unique")
return self._sslobj.tls_unique_cb()
Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake).
Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake).
[ "Get", "channel", "binding", "data", "for", "current", "connection", ".", "Raise", "ValueError", "if", "the", "requested", "cb_type", "is", "not", "supported", ".", "Return", "bytes", "of", "the", "data", "or", "None", "if", "the", "data", "is", "not", "av...
def get_channel_binding(self, cb_type="tls-unique"): """Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake).""" if cb_type not in CHANNEL_BINDING_TYPES: raise ValueError("Unsupported channel binding type") if cb_type != "tls-unique": raise NotImplementedError( "{0} channel binding type not implemented" .format(cb_type)) return self._sslobj.tls_unique_cb()
[ "def", "get_channel_binding", "(", "self", ",", "cb_type", "=", "\"tls-unique\"", ")", ":", "if", "cb_type", "not", "in", "CHANNEL_BINDING_TYPES", ":", "raise", "ValueError", "(", "\"Unsupported channel binding type\"", ")", "if", "cb_type", "!=", "\"tls-unique\"", ...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/ssl.py#L644-L654
facebookresearch/synsin
501ec49b11030a41207e7b923b949fab8fd6e1b5
models/networks/sync_batchnorm/replicate.py
python
execute_replication_callbacks
(modules)
Execute an replication callback `__data_parallel_replicate__` on each module created by original replication. The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)` Note that, as all modules are isomorphism, we assign each sub-module with a context (shared among multiple copies of this module on different devices). Through this context, different copies can share some information. We guarantee that the callback on the master copy (the first copy) will be called ahead of calling the callback of any slave copies.
Execute an replication callback `__data_parallel_replicate__` on each module created by original replication.
[ "Execute", "an", "replication", "callback", "__data_parallel_replicate__", "on", "each", "module", "created", "by", "original", "replication", "." ]
def execute_replication_callbacks(modules): """ Execute an replication callback `__data_parallel_replicate__` on each module created by original replication. The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)` Note that, as all modules are isomorphism, we assign each sub-module with a context (shared among multiple copies of this module on different devices). Through this context, different copies can share some information. We guarantee that the callback on the master copy (the first copy) will be called ahead of calling the callback of any slave copies. """ master_copy = modules[0] nr_modules = len(list(master_copy.modules())) ctxs = [CallbackContext() for _ in range(nr_modules)] for i, module in enumerate(modules): for j, m in enumerate(module.modules()): if hasattr(m, "__data_parallel_replicate__"): m.__data_parallel_replicate__(ctxs[j], i)
[ "def", "execute_replication_callbacks", "(", "modules", ")", ":", "master_copy", "=", "modules", "[", "0", "]", "nr_modules", "=", "len", "(", "list", "(", "master_copy", ".", "modules", "(", ")", ")", ")", "ctxs", "=", "[", "CallbackContext", "(", ")", ...
https://github.com/facebookresearch/synsin/blob/501ec49b11030a41207e7b923b949fab8fd6e1b5/models/networks/sync_batchnorm/replicate.py#L27-L47
bashtage/linearmodels
9256269f01ff8c5f85e65342d66149a5636661b6
versioneer.py
python
get_versions
(verbose=False)
return { "version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None, }
Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'.
Get the project version from whatever source is available.
[ "Get", "the", "project", "version", "from", "whatever", "source", "is", "available", "." ]
def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert ( cfg.versionfile_source is not None ), "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return { "version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None, }
[ "def", "get_versions", "(", "verbose", "=", "False", ")", ":", "if", "\"versioneer\"", "in", "sys", ".", "modules", ":", "# see the discussion in cmdclass.py:get_cmdclass()", "del", "sys", ".", "modules", "[", "\"versioneer\"", "]", "root", "=", "get_root", "(", ...
https://github.com/bashtage/linearmodels/blob/9256269f01ff8c5f85e65342d66149a5636661b6/versioneer.py#L1441-L1519
nschloe/pygmsh
3e7eea6fae3b4cd5e9f2c2d52b3686d3e5a1a725
src/pygmsh/common/surface.py
python
Surface.__init__
(self, env, curve_loop)
[]
def __init__(self, env, curve_loop): assert isinstance(curve_loop, CurveLoop) self.curve_loop = curve_loop self.num_edges = len(curve_loop) self._id = env.addSurfaceFilling([self.curve_loop._id]) self.dim_tag = (2, self._id) self.dim_tags = [self.dim_tag]
[ "def", "__init__", "(", "self", ",", "env", ",", "curve_loop", ")", ":", "assert", "isinstance", "(", "curve_loop", ",", "CurveLoop", ")", "self", ".", "curve_loop", "=", "curve_loop", "self", ".", "num_edges", "=", "len", "(", "curve_loop", ")", "self", ...
https://github.com/nschloe/pygmsh/blob/3e7eea6fae3b4cd5e9f2c2d52b3686d3e5a1a725/src/pygmsh/common/surface.py#L25-L31
peterbrittain/asciimatics
9a490faddf484ee5b9b845316f921f5888b23b18
asciimatics/screen.py
python
TemporaryCanvas.__init__
(self, height, width)
:param height: The height of the screen buffer to be used. :param width: The width of the screen buffer to be used.
:param height: The height of the screen buffer to be used. :param width: The width of the screen buffer to be used.
[ ":", "param", "height", ":", "The", "height", "of", "the", "screen", "buffer", "to", "be", "used", ".", ":", "param", "width", ":", "The", "width", "of", "the", "screen", "buffer", "to", "be", "used", "." ]
def __init__(self, height, width): """ :param height: The height of the screen buffer to be used. :param width: The width of the screen buffer to be used. """ # Colours and unicode rendering are up to the user. Pick defaults that won't limit them. super(TemporaryCanvas, self).__init__(height, width, None, 256, True)
[ "def", "__init__", "(", "self", ",", "height", ",", "width", ")", ":", "# Colours and unicode rendering are up to the user. Pick defaults that won't limit them.", "super", "(", "TemporaryCanvas", ",", "self", ")", ".", "__init__", "(", "height", ",", "width", ",", "N...
https://github.com/peterbrittain/asciimatics/blob/9a490faddf484ee5b9b845316f921f5888b23b18/asciimatics/screen.py#L1119-L1125
abedavis/visbeat
e6b7c5da1d2007b98fd53ba4b5ca6d58c75f17c0
visbeat/Audio.py
python
Audio.pickOnsets
(self, pre_max_time=0.03, post_max_time=0.0, pre_avg_time=0.1, post_avg_time=0.1, wait_time=0.03, delta=0.07, force_recompute=True, **kwargs)
return self.getOnsets(force_recompute=force_recompute, **dparams)
:param pre_max_time: :param post_max_time: :param pre_avg_time: :param post_avg_time: :param wait_time: :param force_recompute: :param kwargs: :return:
[]
def pickOnsets(self, pre_max_time=0.03, post_max_time=0.0, pre_avg_time=0.1, post_avg_time=0.1, wait_time=0.03, delta=0.07, force_recompute=True, **kwargs): """ :param pre_max_time: :param post_max_time: :param pre_avg_time: :param post_avg_time: :param wait_time: :param force_recompute: :param kwargs: :return: """ # kwargs.setdefault('pre_max', 0.03 * sr // hop_length) # 30ms # kwargs.setdefault('post_max', 0.00 * sr // hop_length + 1) # 0ms # kwargs.setdefault('pre_avg', 0.10 * sr // hop_length) # 100ms # kwargs.setdefault('post_avg', 0.10 * sr // hop_length + 1) # 100ms # kwargs.setdefault('wait', 0.03 * sr // hop_length) # 30ms # kwargs.setdefault('delta', 0.07) pick_params = dict( pre_max_time=pre_max_time, post_max_time=post_max_time, pre_avg_time=pre_avg_time, post_avg_time=post_avg_time, wait_time=wait_time, delta=delta, ) tp_keys = pick_params.keys(); for p in tp_keys: pick_params[p] = int(round(self.getOnsetSamplingRate() * pick_params[p])); dparams = dict( pre_max=pick_params['pre_max_time'], post_max=pick_params['post_max_time'] + 1, pre_avg=pick_params['pre_avg_time'], post_avg=pick_params['post_avg_time'] + 1, wait=pick_params['wait_time'], delta=delta ) return self.getOnsets(force_recompute=force_recompute, **dparams);
[ "def", "pickOnsets", "(", "self", ",", "pre_max_time", "=", "0.03", ",", "post_max_time", "=", "0.0", ",", "pre_avg_time", "=", "0.1", ",", "post_avg_time", "=", "0.1", ",", "wait_time", "=", "0.03", ",", "delta", "=", "0.07", ",", "force_recompute", "=", ...
https://github.com/abedavis/visbeat/blob/e6b7c5da1d2007b98fd53ba4b5ca6d58c75f17c0/visbeat/Audio.py#L529-L576
matrix-org/synapse
8e57584a5859a9002759963eb546d523d2498a01
synapse/http/server.py
python
JsonResource.register_paths
( self, method: str, path_patterns: Iterable[Pattern], callback: ServletCallback, servlet_classname: str, )
Registers a request handler against a regular expression. Later request URLs are checked against these regular expressions in order to identify an appropriate handler for that request. Args: method: GET, POST etc path_patterns: A list of regular expressions to which the request URLs are compared. callback: The handler for the request. Usually a Servlet servlet_classname: The name of the handler to be used in prometheus and opentracing logs.
Registers a request handler against a regular expression. Later request URLs are checked against these regular expressions in order to identify an appropriate handler for that request.
[ "Registers", "a", "request", "handler", "against", "a", "regular", "expression", ".", "Later", "request", "URLs", "are", "checked", "against", "these", "regular", "expressions", "in", "order", "to", "identify", "an", "appropriate", "handler", "for", "that", "req...
def register_paths( self, method: str, path_patterns: Iterable[Pattern], callback: ServletCallback, servlet_classname: str, ) -> None: """ Registers a request handler against a regular expression. Later request URLs are checked against these regular expressions in order to identify an appropriate handler for that request. Args: method: GET, POST etc path_patterns: A list of regular expressions to which the request URLs are compared. callback: The handler for the request. Usually a Servlet servlet_classname: The name of the handler to be used in prometheus and opentracing logs. """ method_bytes = method.encode("utf-8") for path_pattern in path_patterns: logger.debug("Registering for %s %s", method, path_pattern.pattern) self.path_regexs.setdefault(method_bytes, []).append( _PathEntry(path_pattern, callback, servlet_classname) )
[ "def", "register_paths", "(", "self", ",", "method", ":", "str", ",", "path_patterns", ":", "Iterable", "[", "Pattern", "]", ",", "callback", ":", "ServletCallback", ",", "servlet_classname", ":", "str", ",", ")", "->", "None", ":", "method_bytes", "=", "m...
https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/http/server.py#L391-L420
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/图片项目/6-B、Layers API/main.py
python
print_test_accuracy
(show_example_errors=False, show_confusion_matrix=False)
[]
def print_test_accuracy(show_example_errors=False, show_confusion_matrix=False): # Number of images in the test-set. num_test = len(data.test.images) # Allocate an array for the predicted classes which # will be calculated in batches and filled into this array. cls_pred = np.zeros(shape=num_test, dtype=np.int) # Now calculate the predicted classes for the batches. # We will just iterate through all the batches. # There might be a more clever and Pythonic way of doing this. # The starting index for the next batch is denoted i. i = 0 while i < num_test: # The ending index for the next batch is denoted j. j = min(i + test_batch_size, num_test) # Get the images from the test-set between index i and j. images = data.test.images[i:j, :] # Get the associated labels. labels = data.test.labels[i:j, :] # Create a feed-dict with these images and labels. feed_dict = {x: images, y_true: labels} # Calculate the predicted class using TensorFlow. cls_pred[i:j] = session.run(y_pred_cls, feed_dict=feed_dict) # Set the start-index for the next batch to the # end-index of the current batch. i = j # Convenience variable for the true class-numbers of the test-set. cls_true = data.test.cls # Create a boolean array whether each image is correctly classified. correct = (cls_true == cls_pred) # Calculate the number of correctly classified images. # When summing a boolean array, False means 0 and True means 1. correct_sum = correct.sum() # Classification accuracy is the number of correctly classified # images divided by the total number of images in the test-set. acc = float(correct_sum) / num_test # Print the accuracy. msg = "Accuracy on Test-Set: {0:.1%} ({1} / {2})" print(msg.format(acc, correct_sum, num_test)) # Plot some examples of mis-classifications, if desired. if show_example_errors: print("Example errors:") plot_example_errors(cls_pred=cls_pred, correct=correct) # Plot the confusion matrix, if desired. if show_confusion_matrix: print("Confusion Matrix:") plot_confusion_matrix(cls_pred=cls_pred)
[ "def", "print_test_accuracy", "(", "show_example_errors", "=", "False", ",", "show_confusion_matrix", "=", "False", ")", ":", "# Number of images in the test-set.", "num_test", "=", "len", "(", "data", ".", "test", ".", "images", ")", "# Allocate an array for the predic...
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/图片项目/6-B、Layers API/main.py#L274-L338
chubin/wttr.in
eb562660c996592e4a8f00dba3513abe30bf7186
lib/buttons.py
python
add_buttons
(output)
return output.replace('</body>', (TWITTER_BUTTON + GITHUB_BUTTON + GITHUB_BUTTON_3 + GITHUB_BUTTON_2 + GITHUB_BUTTON_FOOTER) + '</body>')
Add buttons to html output
Add buttons to html output
[ "Add", "buttons", "to", "html", "output" ]
def add_buttons(output): """ Add buttons to html output """ return output.replace('</body>', (TWITTER_BUTTON + GITHUB_BUTTON + GITHUB_BUTTON_3 + GITHUB_BUTTON_2 + GITHUB_BUTTON_FOOTER) + '</body>')
[ "def", "add_buttons", "(", "output", ")", ":", "return", "output", ".", "replace", "(", "'</body>'", ",", "(", "TWITTER_BUTTON", "+", "GITHUB_BUTTON", "+", "GITHUB_BUTTON_3", "+", "GITHUB_BUTTON_2", "+", "GITHUB_BUTTON_FOOTER", ")", "+", "'</body>'", ")" ]
https://github.com/chubin/wttr.in/blob/eb562660c996592e4a8f00dba3513abe30bf7186/lib/buttons.py#L24-L34
wummel/patool
723006abd43d0926581b11df0cd37e46a30525eb
patoolib/programs/arj.py
python
list_arj
(archive, compression, cmd, verbosity, interactive, password=None)
return cmdlist
List an ARJ archive.
List an ARJ archive.
[ "List", "an", "ARJ", "archive", "." ]
def list_arj (archive, compression, cmd, verbosity, interactive, password=None): """List an ARJ archive.""" cmdlist = [cmd] _maybe_add_password(cmdlist, password) if verbosity > 1: cmdlist.append('v') else: cmdlist.append('l') if not interactive: cmdlist.append('-y') cmdlist.extend(['-r', archive]) return cmdlist
[ "def", "list_arj", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "password", "=", "None", ")", ":", "cmdlist", "=", "[", "cmd", "]", "_maybe_add_password", "(", "cmdlist", ",", "password", ")", "if", "verbosity"...
https://github.com/wummel/patool/blob/723006abd43d0926581b11df0cd37e46a30525eb/patoolib/programs/arj.py#L40-L51
safe-graph/DGFraud
4d017a5ae9c44287215f52470e1aef5ee99a5d9d
algorithms/GraphSage/supervised_models.py
python
SupervisedGraphsage.__init__
(self, num_classes, placeholders, features, adj, degrees, layer_infos, concat=True, aggregator_type="mean", model_size="small", sigmoid_loss=False, identity_dim=0, **kwargs)
Args: - placeholders: Stanford TensorFlow placeholder object. - features: Numpy array with node features. - adj: Numpy array with adjacency lists (padded with random re-samples) - degrees: Numpy array with node degrees. - layer_infos: List of SAGEInfo namedtuples that describe the parameters of all the recursive layers. See SAGEInfo definition above. - concat: whether to concatenate during recursive iterations - aggregator_type: how to aggregate neighbor information - model_size: one of "small" and "big" - sigmoid_loss: Set to true if nodes can belong to multiple classes
Args: - placeholders: Stanford TensorFlow placeholder object. - features: Numpy array with node features. - adj: Numpy array with adjacency lists (padded with random re-samples) - degrees: Numpy array with node degrees. - layer_infos: List of SAGEInfo namedtuples that describe the parameters of all the recursive layers. See SAGEInfo definition above. - concat: whether to concatenate during recursive iterations - aggregator_type: how to aggregate neighbor information - model_size: one of "small" and "big" - sigmoid_loss: Set to true if nodes can belong to multiple classes
[ "Args", ":", "-", "placeholders", ":", "Stanford", "TensorFlow", "placeholder", "object", ".", "-", "features", ":", "Numpy", "array", "with", "node", "features", ".", "-", "adj", ":", "Numpy", "array", "with", "adjacency", "lists", "(", "padded", "with", ...
def __init__(self, num_classes, placeholders, features, adj, degrees, layer_infos, concat=True, aggregator_type="mean", model_size="small", sigmoid_loss=False, identity_dim=0, **kwargs): ''' Args: - placeholders: Stanford TensorFlow placeholder object. - features: Numpy array with node features. - adj: Numpy array with adjacency lists (padded with random re-samples) - degrees: Numpy array with node degrees. - layer_infos: List of SAGEInfo namedtuples that describe the parameters of all the recursive layers. See SAGEInfo definition above. - concat: whether to concatenate during recursive iterations - aggregator_type: how to aggregate neighbor information - model_size: one of "small" and "big" - sigmoid_loss: Set to true if nodes can belong to multiple classes ''' models.GeneralizedModel.__init__(self, **kwargs) if aggregator_type == "mean": self.aggregator_cls = MeanAggregator elif aggregator_type == "seq": self.aggregator_cls = SeqAggregator elif aggregator_type == "meanpool": self.aggregator_cls = MeanPoolingAggregator elif aggregator_type == "maxpool": self.aggregator_cls = MaxPoolingAggregator elif aggregator_type == "gcn": self.aggregator_cls = GCNAggregator else: raise Exception("Unknown aggregator: ", self.aggregator_cls) # get info from placeholders... self.inputs1 = placeholders["batch"] self.model_size = model_size self.adj_info = adj if identity_dim > 0: self.embeds = tf.get_variable("node_embeddings", [adj.get_shape().as_list()[0], identity_dim]) else: self.embeds = None if features is None: if identity_dim == 0: raise Exception("Must have a positive value for identity feature dimension if no input features given.") self.features = self.embeds else: self.features = tf.Variable(tf.constant(features, dtype=tf.float32), trainable=False) if not self.embeds is None: self.features = tf.concat([self.embeds, self.features], axis=1) self.degrees = degrees self.concat = concat self.num_classes = num_classes self.sigmoid_loss = sigmoid_loss self.dims = [(0 if features is None else features.shape[1]) + identity_dim] self.dims.extend([layer_infos[i].output_dim for i in range(len(layer_infos))]) self.batch_size = placeholders["batch_size"] self.placeholders = placeholders self.layer_infos = layer_infos self.optimizer = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate) self.build()
[ "def", "__init__", "(", "self", ",", "num_classes", ",", "placeholders", ",", "features", ",", "adj", ",", "degrees", ",", "layer_infos", ",", "concat", "=", "True", ",", "aggregator_type", "=", "\"mean\"", ",", "model_size", "=", "\"small\"", ",", "sigmoid_...
https://github.com/safe-graph/DGFraud/blob/4d017a5ae9c44287215f52470e1aef5ee99a5d9d/algorithms/GraphSage/supervised_models.py#L13-L75
googleapis/python-ndb
e780c81cde1016651afbfcad8180d9912722cf1b
google/cloud/ndb/metadata.py
python
Property.key_to_kind
(cls, key)
Return the kind specified by a given __property__ key. Args: key (key.Key): key whose kind name is requested. Returns: str: The kind specified by key.
Return the kind specified by a given __property__ key.
[ "Return", "the", "kind", "specified", "by", "a", "given", "__property__", "key", "." ]
def key_to_kind(cls, key): """Return the kind specified by a given __property__ key. Args: key (key.Key): key whose kind name is requested. Returns: str: The kind specified by key. """ if key.kind() == Kind.KIND_NAME: return key.id() else: return key.parent().id()
[ "def", "key_to_kind", "(", "cls", ",", "key", ")", ":", "if", "key", ".", "kind", "(", ")", "==", "Kind", ".", "KIND_NAME", ":", "return", "key", ".", "id", "(", ")", "else", ":", "return", "key", ".", "parent", "(", ")", ".", "id", "(", ")" ]
https://github.com/googleapis/python-ndb/blob/e780c81cde1016651afbfcad8180d9912722cf1b/google/cloud/ndb/metadata.py#L213-L225
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/partners/v20180321/models.py
python
DescribeRebateInfosResponse.__init__
(self)
r""" :param RebateInfoSet: 返佣信息列表 :type RebateInfoSet: list of RebateInfoElem :param TotalCount: 符合查询条件返佣信息数目 :type TotalCount: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param RebateInfoSet: 返佣信息列表 :type RebateInfoSet: list of RebateInfoElem :param TotalCount: 符合查询条件返佣信息数目 :type TotalCount: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "RebateInfoSet", ":", "返佣信息列表", ":", "type", "RebateInfoSet", ":", "list", "of", "RebateInfoElem", ":", "param", "TotalCount", ":", "符合查询条件返佣信息数目", ":", "type", "TotalCount", ":", "int", ":", "param", "RequestId", ":", "唯一请求", "ID,每次请求都会返回。定...
def __init__(self): r""" :param RebateInfoSet: 返佣信息列表 :type RebateInfoSet: list of RebateInfoElem :param TotalCount: 符合查询条件返佣信息数目 :type TotalCount: int :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RebateInfoSet = None self.TotalCount = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "RebateInfoSet", "=", "None", "self", ".", "TotalCount", "=", "None", "self", ".", "RequestId", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/partners/v20180321/models.py#L1822-L1833
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/mako/codegen.py
python
_GenerateRenderMethod.write_cache_decorator
( self, node_or_pagetag, name, args, buffered, identifiers, inline=False, toplevel=False, )
write a post-function decorator to replace a rendering callable with a cached version of itself.
write a post-function decorator to replace a rendering callable with a cached version of itself.
[ "write", "a", "post", "-", "function", "decorator", "to", "replace", "a", "rendering", "callable", "with", "a", "cached", "version", "of", "itself", "." ]
def write_cache_decorator( self, node_or_pagetag, name, args, buffered, identifiers, inline=False, toplevel=False, ): """write a post-function decorator to replace a rendering callable with a cached version of itself.""" self.printer.writeline("__M_%s = %s" % (name, name)) cachekey = node_or_pagetag.parsed_attributes.get( "cache_key", repr(name) ) cache_args = {} if self.compiler.pagetag is not None: cache_args.update( (pa[6:], self.compiler.pagetag.parsed_attributes[pa]) for pa in self.compiler.pagetag.parsed_attributes if pa.startswith("cache_") and pa != "cache_key" ) cache_args.update( (pa[6:], node_or_pagetag.parsed_attributes[pa]) for pa in node_or_pagetag.parsed_attributes if pa.startswith("cache_") and pa != "cache_key" ) if "timeout" in cache_args: cache_args["timeout"] = int(eval(cache_args["timeout"])) self.printer.writeline("def %s(%s):" % (name, ",".join(args))) # form "arg1, arg2, arg3=arg3, arg4=arg4", etc. pass_args = [ "%s=%s" % ((a.split("=")[0],) * 2) if "=" in a else a for a in args ] self.write_variable_declares( identifiers, toplevel=toplevel, limit=node_or_pagetag.undeclared_identifiers(), ) if buffered: s = ( "context.get('local')." "cache._ctx_get_or_create(" "%s, lambda:__M_%s(%s), context, %s__M_defname=%r)" % ( cachekey, name, ",".join(pass_args), "".join( ["%s=%s, " % (k, v) for k, v in cache_args.items()] ), name, ) ) # apply buffer_filters s = self.create_filter_callable( self.compiler.buffer_filters, s, False ) self.printer.writelines("return " + s, None) else: self.printer.writelines( "__M_writer(context.get('local')." "cache._ctx_get_or_create(" "%s, lambda:__M_%s(%s), context, %s__M_defname=%r))" % ( cachekey, name, ",".join(pass_args), "".join( ["%s=%s, " % (k, v) for k, v in cache_args.items()] ), name, ), "return ''", None, )
[ "def", "write_cache_decorator", "(", "self", ",", "node_or_pagetag", ",", "name", ",", "args", ",", "buffered", ",", "identifiers", ",", "inline", "=", "False", ",", "toplevel", "=", "False", ",", ")", ":", "self", ".", "printer", ".", "writeline", "(", ...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/mako/codegen.py#L706-L787
CGATOxford/cgat
326aad4694bdfae8ddc194171bb5d73911243947
CGAT/scripts/annotator_distance.py
python
plotCounts
(counter, options, transform=lambda x: x)
create plots from counter.
create plots from counter.
[ "create", "plots", "from", "counter", "." ]
def plotCounts(counter, options, transform=lambda x: x): """create plots from counter.""" num_bins = options.num_bins resolution = options.resolution bins = numpy.array(range(num_bins)) * resolution for label in counter.getLabels(): fig = plt.figure() if options.plot_samples: for x in range(options.num_samples): counts = transform(counter.mSimulatedCounts[x][ label], counter.mSimulatedCounts[x].mOutOfBounds[label]) plt.plot(bins, counts / t, label="sample_%i" % x) if options.plot_envelope: # counts per sample are in row mmin, mmax, mmean = counter.getEnvelope(label, transform) plt.plot(bins, mmin, label="min") plt.plot(bins, mmax, label="max") plt.plot(bins, mmean, label="mean") plt.plot(bins, transform(counter.mObservedCounts[ label], counter.mObservedCounts.mOutOfBounds[label]), label="observed") plt.xlim(options.xrange) plt.legend() plt.title(counter.mName) plt.xlabel("distance from gene / bp") plt.ylabel("frequency") fig.suptitle(str(label)) if options.logscale: if "x" in options.logscale: plt.gca().set_xscale('log') if "y" in options.logscale: plt.gca().set_yscale('log') if options.hardcopy: plt.savefig(os.path.expanduser(options.hardcopy % label))
[ "def", "plotCounts", "(", "counter", ",", "options", ",", "transform", "=", "lambda", "x", ":", "x", ")", ":", "num_bins", "=", "options", ".", "num_bins", "resolution", "=", "options", ".", "resolution", "bins", "=", "numpy", ".", "array", "(", "range",...
https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/scripts/annotator_distance.py#L661-L702
PaddlePaddle/Research
2da0bd6c72d60e9df403aff23a7802779561c4a1
NLP/Text2SQL-BASELINE/text2sql/utils/dusql_evaluation.py
python
parse_having
(toks, start_idx, tables_with_alias, schema, default_tables)
return idx, conds
Args: Returns:
Args:
[ "Args", ":" ]
def parse_having(toks, start_idx, tables_with_alias, schema, default_tables): """ Args: Returns: """ idx = start_idx len_ = len(toks) if idx >= len_ or toks[idx] != 'having': return idx, [] idx += 1 idx, conds = parse_condition(toks, idx, tables_with_alias, schema, default_tables) return idx, conds
[ "def", "parse_having", "(", "toks", ",", "start_idx", ",", "tables_with_alias", ",", "schema", ",", "default_tables", ")", ":", "idx", "=", "start_idx", "len_", "=", "len", "(", "toks", ")", "if", "idx", ">=", "len_", "or", "toks", "[", "idx", "]", "!=...
https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/NLP/Text2SQL-BASELINE/text2sql/utils/dusql_evaluation.py#L548-L562
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_gcloud/library/gcloud_compute_zones.py
python
main
()
ansible module for gcloud compute zones
ansible module for gcloud compute zones
[ "ansible", "module", "for", "gcloud", "compute", "zones" ]
def main(): ''' ansible module for gcloud compute zones''' module = AnsibleModule( argument_spec=dict( # credentials state=dict(default='list', type='str', choices=['list']), region=dict(default=None, type='str'), ), supports_check_mode=True, ) gcloud = GcloudComputeZones(module.params['region']) state = module.params['state'] api_rval = gcloud.list_zones() ##### # Get ##### if state == 'list': if api_rval['returncode'] != 0: module.fail_json(msg=api_rval, state="list") module.exit_json(changed=False, results=api_rval['results'], state="list") module.exit_json(failed=True, changed=False, results='Unknown state passed. %s' % state, state="unknown")
[ "def", "main", "(", ")", ":", "module", "=", "AnsibleModule", "(", "argument_spec", "=", "dict", "(", "# credentials", "state", "=", "dict", "(", "default", "=", "'list'", ",", "type", "=", "'str'", ",", "choices", "=", "[", "'list'", "]", ")", ",", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_gcloud/library/gcloud_compute_zones.py#L543-L573
open-mmlab/mmskeleton
b4c076baa9e02e69b5876c49fa7c509866d902c7
deprecated/origin_stgcn_repo/net/st_gcn.py
python
st_gcn.forward
(self, x, A)
return self.relu(x), A
[]
def forward(self, x, A): res = self.residual(x) x, A = self.gcn(x, A) x = self.tcn(x) + res return self.relu(x), A
[ "def", "forward", "(", "self", ",", "x", ",", "A", ")", ":", "res", "=", "self", ".", "residual", "(", "x", ")", "x", ",", "A", "=", "self", ".", "gcn", "(", "x", ",", "A", ")", "x", "=", "self", ".", "tcn", "(", "x", ")", "+", "res", "...
https://github.com/open-mmlab/mmskeleton/blob/b4c076baa9e02e69b5876c49fa7c509866d902c7/deprecated/origin_stgcn_repo/net/st_gcn.py#L192-L198
yulequan/PU-Net
c8bb205689dd508d145c406feff8878b39b12a2d
code/utils/plyfile.py
python
PlyElement.dtype
(self, byte_order='=')
return [(prop.name, prop.dtype(byte_order)) for prop in self.properties]
Return the numpy dtype of the in-memory representation of the data. (If there are no list properties, and the PLY format is binary, then this also accurately describes the on-disk representation of the element.)
Return the numpy dtype of the in-memory representation of the data. (If there are no list properties, and the PLY format is binary, then this also accurately describes the on-disk representation of the element.)
[ "Return", "the", "numpy", "dtype", "of", "the", "in", "-", "memory", "representation", "of", "the", "data", ".", "(", "If", "there", "are", "no", "list", "properties", "and", "the", "PLY", "format", "is", "binary", "then", "this", "also", "accurately", "...
def dtype(self, byte_order='='): ''' Return the numpy dtype of the in-memory representation of the data. (If there are no list properties, and the PLY format is binary, then this also accurately describes the on-disk representation of the element.) ''' return [(prop.name, prop.dtype(byte_order)) for prop in self.properties]
[ "def", "dtype", "(", "self", ",", "byte_order", "=", "'='", ")", ":", "return", "[", "(", "prop", ".", "name", ",", "prop", ".", "dtype", "(", "byte_order", ")", ")", "for", "prop", "in", "self", ".", "properties", "]" ]
https://github.com/yulequan/PU-Net/blob/c8bb205689dd508d145c406feff8878b39b12a2d/code/utils/plyfile.py#L446-L455
metabrainz/picard
535bf8c7d9363ffc7abb3f69418ec11823c38118
picard/ui/colors.py
python
InterfaceColors.__init__
(self, dark_theme=None)
[]
def __init__(self, dark_theme=None): self._dark_theme = dark_theme self.set_default_colors()
[ "def", "__init__", "(", "self", ",", "dark_theme", "=", "None", ")", ":", "self", ".", "_dark_theme", "=", "dark_theme", "self", ".", "set_default_colors", "(", ")" ]
https://github.com/metabrainz/picard/blob/535bf8c7d9363ffc7abb3f69418ec11823c38118/picard/ui/colors.py#L87-L89
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/infinity.py
python
InfinityRing_class.gen
(self, n=0)
The two generators are plus and minus infinity. EXAMPLES:: sage: InfinityRing.gen(0) +Infinity sage: InfinityRing.gen(1) -Infinity sage: InfinityRing.gen(2) Traceback (most recent call last): ... IndexError: n must be 0 or 1
The two generators are plus and minus infinity.
[ "The", "two", "generators", "are", "plus", "and", "minus", "infinity", "." ]
def gen(self, n=0): """ The two generators are plus and minus infinity. EXAMPLES:: sage: InfinityRing.gen(0) +Infinity sage: InfinityRing.gen(1) -Infinity sage: InfinityRing.gen(2) Traceback (most recent call last): ... IndexError: n must be 0 or 1 """ try: if n == 0: return self._gen0 elif n == 1: return self._gen1 else: raise IndexError("n must be 0 or 1") except AttributeError: if n == 0: self._gen0 = PlusInfinity() return self._gen0 elif n == 1: self._gen1 = MinusInfinity() return self._gen1
[ "def", "gen", "(", "self", ",", "n", "=", "0", ")", ":", "try", ":", "if", "n", "==", "0", ":", "return", "self", ".", "_gen0", "elif", "n", "==", "1", ":", "return", "self", ".", "_gen1", "else", ":", "raise", "IndexError", "(", "\"n must be 0 o...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/infinity.py#L1044-L1072
lazylibrarian/LazyLibrarian
ae3c14e9db9328ce81765e094ab2a14ed7155624
lib/requests/adapters.py
python
HTTPAdapter.request_url
(self, request, proxies)
return url
Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str
Obtain the url to use when making the final request.
[ "Obtain", "the", "url", "to", "use", "when", "making", "the", "final", "request", "." ]
def request_url(self, request, proxies): """Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. :rtype: str """ proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = (proxy and scheme != 'https') using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith('socks') url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url
[ "def", "request_url", "(", "self", ",", "request", ",", "proxies", ")", ":", "proxy", "=", "select_proxy", "(", "request", ".", "url", ",", "proxies", ")", "scheme", "=", "urlparse", "(", "request", ".", "url", ")", ".", "scheme", "is_proxied_http_request"...
https://github.com/lazylibrarian/LazyLibrarian/blob/ae3c14e9db9328ce81765e094ab2a14ed7155624/lib/requests/adapters.py#L310-L337
fluentpython/example-code
d5133ad6e4a48eac0980d2418ed39d7ff693edbe
05-1class-func/tagger.py
python
tag
(name, *content, cls=None, **attrs)
Generate one or more HTML tags
Generate one or more HTML tags
[ "Generate", "one", "or", "more", "HTML", "tags" ]
def tag(name, *content, cls=None, **attrs): """Generate one or more HTML tags""" if cls is not None: attrs['class'] = cls if attrs: attr_str = ''.join(' %s="%s"' % (attr, value) for attr, value in sorted(attrs.items())) else: attr_str = '' if content: return '\n'.join('<%s%s>%s</%s>' % (name, attr_str, c, name) for c in content) else: return '<%s%s />' % (name, attr_str)
[ "def", "tag", "(", "name", ",", "*", "content", ",", "cls", "=", "None", ",", "*", "*", "attrs", ")", ":", "if", "cls", "is", "not", "None", ":", "attrs", "[", "'class'", "]", "=", "cls", "if", "attrs", ":", "attr_str", "=", "''", ".", "join", ...
https://github.com/fluentpython/example-code/blob/d5133ad6e4a48eac0980d2418ed39d7ff693edbe/05-1class-func/tagger.py#L29-L43
hwalsuklee/tensorflow-generative-model-collections
3abde8a9bcfe31815da50347d14641ec95096f62
WGAN_GP.py
python
WGAN_GP.visualize_results
(self, epoch)
random condition, random noise
random condition, random noise
[ "random", "condition", "random", "noise" ]
def visualize_results(self, epoch): tot_num_samples = min(self.sample_num, self.batch_size) image_frame_dim = int(np.floor(np.sqrt(tot_num_samples))) """ random condition, random noise """ z_sample = np.random.uniform(-1, 1, size=(self.batch_size, self.z_dim)) samples = self.sess.run(self.fake_images, feed_dict={self.z: z_sample}) save_images(samples[:image_frame_dim * image_frame_dim, :, :, :], [image_frame_dim, image_frame_dim], check_folder(self.result_dir + '/' + self.model_dir) + '/' + self.model_name + '_epoch%03d' % epoch + '_test_all_classes.png')
[ "def", "visualize_results", "(", "self", ",", "epoch", ")", ":", "tot_num_samples", "=", "min", "(", "self", ".", "sample_num", ",", "self", ".", "batch_size", ")", "image_frame_dim", "=", "int", "(", "np", ".", "floor", "(", "np", ".", "sqrt", "(", "t...
https://github.com/hwalsuklee/tensorflow-generative-model-collections/blob/3abde8a9bcfe31815da50347d14641ec95096f62/WGAN_GP.py#L226-L237
RasaHQ/rasa_core
48cb1cf263044e323691a7b3f5a71d2da0172b38
rasa/core/training/interactive.py
python
_write_stories_to_file
( export_story_path: Text, evts: List[Dict[Text, Any]] )
Write the conversation of the sender_id to the file paths.
Write the conversation of the sender_id to the file paths.
[ "Write", "the", "conversation", "of", "the", "sender_id", "to", "the", "file", "paths", "." ]
async def _write_stories_to_file( export_story_path: Text, evts: List[Dict[Text, Any]] ) -> None: """Write the conversation of the sender_id to the file paths.""" sub_conversations = _split_conversation_at_restarts(evts) with open(export_story_path, 'a', encoding="utf-8") as f: for conversation in sub_conversations: parsed_events = events.deserialise_events(conversation) s = Story.from_events(parsed_events) f.write(s.as_story_string(flat=True) + "\n")
[ "async", "def", "_write_stories_to_file", "(", "export_story_path", ":", "Text", ",", "evts", ":", "List", "[", "Dict", "[", "Text", ",", "Any", "]", "]", ")", "->", "None", ":", "sub_conversations", "=", "_split_conversation_at_restarts", "(", "evts", ")", ...
https://github.com/RasaHQ/rasa_core/blob/48cb1cf263044e323691a7b3f5a71d2da0172b38/rasa/core/training/interactive.py#L713-L725
titu1994/Fast-Neural-Style
3ab125a5a999e4c28ec77c6ebec8bb5372585626
img_utils.py
python
_check_image
(path, i, nb_images)
Test if image can be loaded by PIL. If image cannot be loaded, delete it from dataset. Args: path: path to image i: iteration number nb_images: total number of images
Test if image can be loaded by PIL. If image cannot be loaded, delete it from dataset.
[ "Test", "if", "image", "can", "be", "loaded", "by", "PIL", ".", "If", "image", "cannot", "be", "loaded", "delete", "it", "from", "dataset", "." ]
def _check_image(path, i, nb_images): ''' Test if image can be loaded by PIL. If image cannot be loaded, delete it from dataset. Args: path: path to image i: iteration number nb_images: total number of images ''' try: im = Image.open(path) im.verify() im = Image.open(path) im.load() if i % 1000 == 0: print('%0.2f percent images are checked.' % (i * 100 / nb_images)) except: os.remove(path) print("Image number %d is corrupt (path = %s). Deleting from dataset." % (i, path))
[ "def", "_check_image", "(", "path", ",", "i", ",", "nb_images", ")", ":", "try", ":", "im", "=", "Image", ".", "open", "(", "path", ")", "im", ".", "verify", "(", ")", "im", "=", "Image", ".", "open", "(", "path", ")", "im", ".", "load", "(", ...
https://github.com/titu1994/Fast-Neural-Style/blob/3ab125a5a999e4c28ec77c6ebec8bb5372585626/img_utils.py#L127-L145
BigBrotherBot/big-brother-bot
848823c71413c86e7f1ff9584f43e08d40a7f2c0
b3/parsers/ravaged/__init__.py
python
RavagedParser.getNextMap
(self)
Return the next map in the map rotation list.
Return the next map in the map rotation list.
[ "Return", "the", "next", "map", "in", "the", "map", "rotation", "list", "." ]
def getNextMap(self): """ Return the next map in the map rotation list. """ re_next_map = re.compile(r"^1 (?P<map_name>\S+)$", re.MULTILINE) m = re.search(re_next_map, self.output.write("getmaplist false")) if m: return m.group('map_name')
[ "def", "getNextMap", "(", "self", ")", ":", "re_next_map", "=", "re", ".", "compile", "(", "r\"^1 (?P<map_name>\\S+)$\"", ",", "re", ".", "MULTILINE", ")", "m", "=", "re", ".", "search", "(", "re_next_map", ",", "self", ".", "output", ".", "write", "(", ...
https://github.com/BigBrotherBot/big-brother-bot/blob/848823c71413c86e7f1ff9584f43e08d40a7f2c0/b3/parsers/ravaged/__init__.py#L461-L468
sybrenstuvel/flickrapi
4de81d85dcdd73e4e1d19b112a0ff93feb0d10f7
flickrapi/core.py
python
FlickrAPI.parse_etree
(self, rest_xml)
Parses a REST XML response from Flickr into an ElementTree object.
Parses a REST XML response from Flickr into an ElementTree object.
[ "Parses", "a", "REST", "XML", "response", "from", "Flickr", "into", "an", "ElementTree", "object", "." ]
def parse_etree(self, rest_xml): """Parses a REST XML response from Flickr into an ElementTree object.""" try: from lxml import etree as ElementTree LOG.info('REST Parser: using lxml.etree') except ImportError: try: import xml.etree.cElementTree as ElementTree LOG.info('REST Parser: using xml.etree.cElementTree') except ImportError: try: import xml.etree.ElementTree as ElementTree LOG.info('REST Parser: using xml.etree.ElementTree') except ImportError: try: import elementtree.cElementTree as ElementTree LOG.info('REST Parser: elementtree.cElementTree') except ImportError: try: import elementtree.ElementTree as ElementTree except ImportError: raise ImportError("You need to install " "ElementTree to use the etree format") rsp = ElementTree.fromstring(rest_xml) if rsp.attrib['stat'] == 'ok': return rsp err = rsp.find('err') code = err.attrib.get('code', None) if int(code) == 9: dup_id = rsp.find('duplicate_photo_id') raise FlickrDuplicate('Duplicate photo', duplicate_photo_id=dup_id.text) raise FlickrError('Error: %(code)s: %(msg)s' % err.attrib, code=code)
[ "def", "parse_etree", "(", "self", ",", "rest_xml", ")", ":", "try", ":", "from", "lxml", "import", "etree", "as", "ElementTree", "LOG", ".", "info", "(", "'REST Parser: using lxml.etree'", ")", "except", "ImportError", ":", "try", ":", "import", "xml", ".",...
https://github.com/sybrenstuvel/flickrapi/blob/4de81d85dcdd73e4e1d19b112a0ff93feb0d10f7/flickrapi/core.py#L271-L307
openstack/octavia
27e5b27d31c695ba72fb6750de2bdafd76e0d7d9
octavia/controller/worker/v2/tasks/network_tasks.py
python
UnPlugNetworks.execute
(self, amphora, delta)
Unplug the networks.
Unplug the networks.
[ "Unplug", "the", "networks", "." ]
def execute(self, amphora, delta): """Unplug the networks.""" LOG.debug("Unplug network for amphora") if not delta: LOG.debug("No network deltas for amphora id: %s", amphora[constants.ID]) return for nic in delta[constants.DELETE_NICS]: try: self.network_driver.unplug_network( amphora[constants.COMPUTE_ID], nic[constants.NETWORK_ID]) except base.NetworkNotFound: LOG.debug("Network %d not found", nic[constants.NETWORK_ID]) except Exception: LOG.exception("Unable to unplug network")
[ "def", "execute", "(", "self", ",", "amphora", ",", "delta", ")", ":", "LOG", ".", "debug", "(", "\"Unplug network for amphora\"", ")", "if", "not", "delta", ":", "LOG", ".", "debug", "(", "\"No network deltas for amphora id: %s\"", ",", "amphora", "[", "const...
https://github.com/openstack/octavia/blob/27e5b27d31c695ba72fb6750de2bdafd76e0d7d9/octavia/controller/worker/v2/tasks/network_tasks.py#L210-L226
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3/s3widgets.py
python
S3AddPersonWidget.split_names
(name)
return name.first, name.middle, name.last
Split a full name into first/middle/last Args: name: the full name Returns: tuple (first, middle, last)
Split a full name into first/middle/last
[ "Split", "a", "full", "name", "into", "first", "/", "middle", "/", "last" ]
def split_names(name): """ Split a full name into first/middle/last Args: name: the full name Returns: tuple (first, middle, last) """ # https://github.com/derek73/python-nameparser from nameparser import HumanName name = HumanName(name) return name.first, name.middle, name.last
[ "def", "split_names", "(", "name", ")", ":", "# https://github.com/derek73/python-nameparser", "from", "nameparser", "import", "HumanName", "name", "=", "HumanName", "(", "name", ")", "return", "name", ".", "first", ",", "name", ".", "middle", ",", "name", ".", ...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3widgets.py#L1327-L1342
dayorbyte/MongoAlchemy
e64ef0c87feff385637459707fe6090bd789e116
mongoalchemy/query.py
python
Query.filter_by
(self, **filters)
return self
Filter for the names in ``filters`` being equal to the associated values. Cannot be used for sub-objects since keys must be strings
Filter for the names in ``filters`` being equal to the associated values. Cannot be used for sub-objects since keys must be strings
[ "Filter", "for", "the", "names", "in", "filters", "being", "equal", "to", "the", "associated", "values", ".", "Cannot", "be", "used", "for", "sub", "-", "objects", "since", "keys", "must", "be", "strings" ]
def filter_by(self, **filters): ''' Filter for the names in ``filters`` being equal to the associated values. Cannot be used for sub-objects since keys must be strings''' for name, value in filters.items(): self.filter(resolve_name(self.type, name) == value) return self
[ "def", "filter_by", "(", "self", ",", "*", "*", "filters", ")", ":", "for", "name", ",", "value", "in", "filters", ".", "items", "(", ")", ":", "self", ".", "filter", "(", "resolve_name", "(", "self", ".", "type", ",", "name", ")", "==", "value", ...
https://github.com/dayorbyte/MongoAlchemy/blob/e64ef0c87feff385637459707fe6090bd789e116/mongoalchemy/query.py#L205-L210
CoinCheung/pytorch-loss
00c83cd588e6327715276ca784d06f050adbc761
label_smooth.py
python
LabelSmoothSoftmaxCEV1.forward
(self, logits, label)
return loss
Same usage method as nn.CrossEntropyLoss: >>> criteria = LabelSmoothSoftmaxCEV1() >>> logits = torch.randn(8, 19, 384, 384) # nchw, float/half >>> lbs = torch.randint(0, 19, (8, 384, 384)) # nhw, int64_t >>> loss = criteria(logits, lbs)
Same usage method as nn.CrossEntropyLoss: >>> criteria = LabelSmoothSoftmaxCEV1() >>> logits = torch.randn(8, 19, 384, 384) # nchw, float/half >>> lbs = torch.randint(0, 19, (8, 384, 384)) # nhw, int64_t >>> loss = criteria(logits, lbs)
[ "Same", "usage", "method", "as", "nn", ".", "CrossEntropyLoss", ":", ">>>", "criteria", "=", "LabelSmoothSoftmaxCEV1", "()", ">>>", "logits", "=", "torch", ".", "randn", "(", "8", "19", "384", "384", ")", "#", "nchw", "float", "/", "half", ">>>", "lbs", ...
def forward(self, logits, label): ''' Same usage method as nn.CrossEntropyLoss: >>> criteria = LabelSmoothSoftmaxCEV1() >>> logits = torch.randn(8, 19, 384, 384) # nchw, float/half >>> lbs = torch.randint(0, 19, (8, 384, 384)) # nhw, int64_t >>> loss = criteria(logits, lbs) ''' # overcome ignored label logits = logits.float() # use fp32 to avoid nan with torch.no_grad(): num_classes = logits.size(1) label = label.clone().detach() ignore = label.eq(self.lb_ignore) n_valid = ignore.eq(0).sum() label[ignore] = 0 lb_pos, lb_neg = 1. - self.lb_smooth, self.lb_smooth / num_classes lb_one_hot = torch.empty_like(logits).fill_( lb_neg).scatter_(1, label.unsqueeze(1), lb_pos).detach() logs = self.log_softmax(logits) loss = -torch.sum(logs * lb_one_hot, dim=1) loss[ignore] = 0 if self.reduction == 'mean': loss = loss.sum() / n_valid if self.reduction == 'sum': loss = loss.sum() return loss
[ "def", "forward", "(", "self", ",", "logits", ",", "label", ")", ":", "# overcome ignored label", "logits", "=", "logits", ".", "float", "(", ")", "# use fp32 to avoid nan", "with", "torch", ".", "no_grad", "(", ")", ":", "num_classes", "=", "logits", ".", ...
https://github.com/CoinCheung/pytorch-loss/blob/00c83cd588e6327715276ca784d06f050adbc761/label_smooth.py#L26-L54
saltstack/salt-contrib
062355938ad1cced273056e9c23dc344c6a2c858
modules/circusctl.py
python
signal
(name, signum, pid=None, childpid=None, children=False, recursive=False)
return result["status"]
Send a signal ============= This command allows you to send a signal to all processes in a watcher, a specific process in a watcher or its children. CLI Example: salt '*' circusctl.signal name SIGHUB salt '*' circusctl.signal <name> [<pid>] [children] [recursive] <signum>
Send a signal =============
[ "Send", "a", "signal", "=============" ]
def signal(name, signum, pid=None, childpid=None, children=False, recursive=False): ''' Send a signal ============= This command allows you to send a signal to all processes in a watcher, a specific process in a watcher or its children. CLI Example: salt '*' circusctl.signal name SIGHUB salt '*' circusctl.signal <name> [<pid>] [children] [recursive] <signum> ''' result = _send_message( "signal", name=name, signum=signum, pid=pid, childpid=childpid, recursive=recursive, ) return result["status"]
[ "def", "signal", "(", "name", ",", "signum", ",", "pid", "=", "None", ",", "childpid", "=", "None", ",", "children", "=", "False", ",", "recursive", "=", "False", ")", ":", "result", "=", "_send_message", "(", "\"signal\"", ",", "name", "=", "name", ...
https://github.com/saltstack/salt-contrib/blob/062355938ad1cced273056e9c23dc344c6a2c858/modules/circusctl.py#L240-L263
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/mixture.py
python
Mixture.Hvapms
(self)
return [i.Hvapm for i in self.Chemicals]
r'''Pure component enthalpies of vaporization of the chemicals in the mixture at its current temperature, in units of [J/mol]. Examples -------- >>> Mixture(['benzene', 'toluene'], ws=[0.5, 0.5], T=320).Hvapms [32639.806783391632, 36851.7902195611]
r'''Pure component enthalpies of vaporization of the chemicals in the mixture at its current temperature, in units of [J/mol].
[ "r", "Pure", "component", "enthalpies", "of", "vaporization", "of", "the", "chemicals", "in", "the", "mixture", "at", "its", "current", "temperature", "in", "units", "of", "[", "J", "/", "mol", "]", "." ]
def Hvapms(self): r'''Pure component enthalpies of vaporization of the chemicals in the mixture at its current temperature, in units of [J/mol]. Examples -------- >>> Mixture(['benzene', 'toluene'], ws=[0.5, 0.5], T=320).Hvapms [32639.806783391632, 36851.7902195611] ''' return [i.Hvapm for i in self.Chemicals]
[ "def", "Hvapms", "(", "self", ")", ":", "return", "[", "i", ".", "Hvapm", "for", "i", "in", "self", ".", "Chemicals", "]" ]
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/mixture.py#L1615-L1624
meraki/dashboard-api-python
aef5e6fe5d23a40d435d5c64ff30580a28af07f1
meraki_v0/aio/api/switch_settings.py
python
AsyncSwitchSettings.updateNetworkSwitchSettingsMtu
(self, networkId: str, **kwargs)
return await self._session.put(metadata, resource, payload)
**Update the MTU configuration** https://developer.cisco.com/meraki/api/#!update-network-switch-settings-mtu - networkId (string) - defaultMtuSize (integer): MTU size for the entire network. Default value is 9578. - overrides (array): Override MTU size for individual switches or switch profiles. An empty array will clear overrides.
**Update the MTU configuration** https://developer.cisco.com/meraki/api/#!update-network-switch-settings-mtu - networkId (string) - defaultMtuSize (integer): MTU size for the entire network. Default value is 9578. - overrides (array): Override MTU size for individual switches or switch profiles. An empty array will clear overrides.
[ "**", "Update", "the", "MTU", "configuration", "**", "https", ":", "//", "developer", ".", "cisco", ".", "com", "/", "meraki", "/", "api", "/", "#!update", "-", "network", "-", "switch", "-", "settings", "-", "mtu", "-", "networkId", "(", "string", ")"...
async def updateNetworkSwitchSettingsMtu(self, networkId: str, **kwargs): """ **Update the MTU configuration** https://developer.cisco.com/meraki/api/#!update-network-switch-settings-mtu - networkId (string) - defaultMtuSize (integer): MTU size for the entire network. Default value is 9578. - overrides (array): Override MTU size for individual switches or switch profiles. An empty array will clear overrides. """ kwargs.update(locals()) metadata = { 'tags': ['Switch settings'], 'operation': 'updateNetworkSwitchSettingsMtu', } resource = f'/networks/{networkId}/switch/settings/mtu' body_params = ['defaultMtuSize', 'overrides'] payload = {k.strip(): v for (k, v) in kwargs.items() if k.strip() in body_params} return await self._session.put(metadata, resource, payload)
[ "async", "def", "updateNetworkSwitchSettingsMtu", "(", "self", ",", "networkId", ":", "str", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "locals", "(", ")", ")", "metadata", "=", "{", "'tags'", ":", "[", "'Switch settings'", "]", ","...
https://github.com/meraki/dashboard-api-python/blob/aef5e6fe5d23a40d435d5c64ff30580a28af07f1/meraki_v0/aio/api/switch_settings.py#L144-L165
greatscottgadgets/luna
08b035c9c2b053d7edffb0d220d948b5c2ca927e
luna/gateware/usb/usb3/link/receiver.py
python
RawHeaderPacketReceiverTest.provide_data
(self, *tuples)
Provides the receiver with a sequence of (data, ctrl) values.
Provides the receiver with a sequence of (data, ctrl) values.
[ "Provides", "the", "receiver", "with", "a", "sequence", "of", "(", "data", "ctrl", ")", "values", "." ]
def provide_data(self, *tuples): """ Provides the receiver with a sequence of (data, ctrl) values. """ # Provide each word of our data to our receiver... for data, ctrl in tuples: yield self.dut.sink.data.eq(data) yield self.dut.sink.ctrl.eq(ctrl) yield
[ "def", "provide_data", "(", "self", ",", "*", "tuples", ")", ":", "# Provide each word of our data to our receiver...", "for", "data", ",", "ctrl", "in", "tuples", ":", "yield", "self", ".", "dut", ".", "sink", ".", "data", ".", "eq", "(", "data", ")", "yi...
https://github.com/greatscottgadgets/luna/blob/08b035c9c2b053d7edffb0d220d948b5c2ca927e/luna/gateware/usb/usb3/link/receiver.py#L175-L182
hyperspy/hyperspy
1ffb3fab33e607045a37f30c1463350b72617e10
hyperspy/models/edsmodel.py
python
_get_sigma
(E, E_ref, units_factor, return_f=False)
Calculates an approximate sigma value, accounting for peak broadening due to the detector, for a peak at energy E given a known width at a reference energy. The factor 2.5 is a constant derived by Fiori & Newbury as references below. Parameters ---------- energy_resolution_MnKa : float Energy resolution of Mn Ka in eV E : float Energy of the peak in keV Returns ------- float : FWHM of the peak in keV Notes ----- This method implements the equation derived by Fiori and Newbury as is documented in the following: Fiori, C. E., and Newbury, D. E. (1978). In SEM/1978/I, SEM, Inc., AFM O'Hare, Illinois, p. 401. Goldstein et al. (2003). "Scanning Electron Microscopy & X-ray Microanalysis", Plenum, third edition, p 315.
Calculates an approximate sigma value, accounting for peak broadening due to the detector, for a peak at energy E given a known width at a reference energy.
[ "Calculates", "an", "approximate", "sigma", "value", "accounting", "for", "peak", "broadening", "due", "to", "the", "detector", "for", "a", "peak", "at", "energy", "E", "given", "a", "known", "width", "at", "a", "reference", "energy", "." ]
def _get_sigma(E, E_ref, units_factor, return_f=False): """ Calculates an approximate sigma value, accounting for peak broadening due to the detector, for a peak at energy E given a known width at a reference energy. The factor 2.5 is a constant derived by Fiori & Newbury as references below. Parameters ---------- energy_resolution_MnKa : float Energy resolution of Mn Ka in eV E : float Energy of the peak in keV Returns ------- float : FWHM of the peak in keV Notes ----- This method implements the equation derived by Fiori and Newbury as is documented in the following: Fiori, C. E., and Newbury, D. E. (1978). In SEM/1978/I, SEM, Inc., AFM O'Hare, Illinois, p. 401. Goldstein et al. (2003). "Scanning Electron Microscopy & X-ray Microanalysis", Plenum, third edition, p 315. """ energy2sigma_factor = 2.5 / (eV2keV * (sigma2fwhm**2)) if return_f: return lambda sig_ref: math.sqrt(abs( energy2sigma_factor * (E - E_ref) * units_factor + np.power(sig_ref, 2))) else: return "sqrt(abs({} * ({} - {}) * {} + sig_ref ** 2))".format( energy2sigma_factor, E, E_ref, units_factor)
[ "def", "_get_sigma", "(", "E", ",", "E_ref", ",", "units_factor", ",", "return_f", "=", "False", ")", ":", "energy2sigma_factor", "=", "2.5", "/", "(", "eV2keV", "*", "(", "sigma2fwhm", "**", "2", ")", ")", "if", "return_f", ":", "return", "lambda", "s...
https://github.com/hyperspy/hyperspy/blob/1ffb3fab33e607045a37f30c1463350b72617e10/hyperspy/models/edsmodel.py#L50-L88
archesproject/arches
bdb6b3fec9eaa1289957471d5e86b4a5e7c8fa97
arches/app/models/graph.py
python
Graph.add_edge
(self, edge)
return edge
Adds an edge to this graph will throw an error if the domain or range nodes referenced in this edge haven't already been added to this graph Arguments: edge -- a dictionary representing a Edge instance or an actual models.Edge instance
Adds an edge to this graph
[ "Adds", "an", "edge", "to", "this", "graph" ]
def add_edge(self, edge): """ Adds an edge to this graph will throw an error if the domain or range nodes referenced in this edge haven't already been added to this graph Arguments: edge -- a dictionary representing a Edge instance or an actual models.Edge instance """ if not isinstance(edge, models.Edge): egdeobj = edge.copy() edge = models.Edge() edge.edgeid = egdeobj.get("edgeid", None) edge.rangenode = self.nodes[uuid.UUID(str(egdeobj.get("rangenode_id")))] edge.domainnode = self.nodes[uuid.UUID(str(egdeobj.get("domainnode_id")))] edge.ontologyproperty = egdeobj.get("ontologyproperty", "") edge.graph = self if edge.pk is None: edge.pk = uuid.uuid1() if self.ontology is None: edge.ontologyproperty = None self.edges[edge.pk] = edge return edge
[ "def", "add_edge", "(", "self", ",", "edge", ")", ":", "if", "not", "isinstance", "(", "edge", ",", "models", ".", "Edge", ")", ":", "egdeobj", "=", "edge", ".", "copy", "(", ")", "edge", "=", "models", ".", "Edge", "(", ")", "edge", ".", "edgeid...
https://github.com/archesproject/arches/blob/bdb6b3fec9eaa1289957471d5e86b4a5e7c8fa97/arches/app/models/graph.py#L216-L243
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/util/context_processors.py
python
mobile_experience
(request)
return { 'show_mobile_ux_warning': show_mobile_ux_warning, 'mobile_ux_cookie_name': mobile_ux_cookie_name, }
[]
def mobile_experience(request): show_mobile_ux_warning = False mobile_ux_cookie_name = '' if (hasattr(request, 'couch_user') and hasattr(request, 'user_agent') and settings.SERVER_ENVIRONMENT in ['production', 'staging', settings.LOCAL_SERVER_ENVIRONMENT]): mobile_ux_cookie_name = '{}-has-seen-mobile-ux-warning'.format(request.couch_user.get_id) show_mobile_ux_warning = ( not request.COOKIES.get(mobile_ux_cookie_name) and request.user_agent.is_mobile and request.user.is_authenticated and request.user.is_active and not mobile_experience_hidden_by_toggle(request) ) return { 'show_mobile_ux_warning': show_mobile_ux_warning, 'mobile_ux_cookie_name': mobile_ux_cookie_name, }
[ "def", "mobile_experience", "(", "request", ")", ":", "show_mobile_ux_warning", "=", "False", "mobile_ux_cookie_name", "=", "''", "if", "(", "hasattr", "(", "request", ",", "'couch_user'", ")", "and", "hasattr", "(", "request", ",", "'user_agent'", ")", "and", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/util/context_processors.py#L204-L221
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/contrib/gis/gdal/geometries.py
python
OGRGeometry.dimension
(self)
return capi.get_dims(self.ptr)
Returns 0 for points, 1 for lines, and 2 for surfaces.
Returns 0 for points, 1 for lines, and 2 for surfaces.
[ "Returns", "0", "for", "points", "1", "for", "lines", "and", "2", "for", "surfaces", "." ]
def dimension(self): "Returns 0 for points, 1 for lines, and 2 for surfaces." return capi.get_dims(self.ptr)
[ "def", "dimension", "(", "self", ")", ":", "return", "capi", ".", "get_dims", "(", "self", ".", "ptr", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/gis/gdal/geometries.py#L191-L193
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/tiling.py
python
Polyomino.bounding_box
(self)
return [[min(_) for _ in zip(*self)], [max(_) for _ in zip(*self)]]
r""" EXAMPLES:: sage: from sage.combinat.tiling import Polyomino sage: p = Polyomino([(0,0,0),(1,0,0),(1,1,0),(1,1,1),(1,2,0)], color='deeppink') sage: p.bounding_box() [[0, 0, 0], [1, 2, 1]]
r""" EXAMPLES::
[ "r", "EXAMPLES", "::" ]
def bounding_box(self): r""" EXAMPLES:: sage: from sage.combinat.tiling import Polyomino sage: p = Polyomino([(0,0,0),(1,0,0),(1,1,0),(1,1,1),(1,2,0)], color='deeppink') sage: p.bounding_box() [[0, 0, 0], [1, 2, 1]] """ return [[min(_) for _ in zip(*self)], [max(_) for _ in zip(*self)]]
[ "def", "bounding_box", "(", "self", ")", ":", "return", "[", "[", "min", "(", "_", ")", "for", "_", "in", "zip", "(", "*", "self", ")", "]", ",", "[", "max", "(", "_", ")", "for", "_", "in", "zip", "(", "*", "self", ")", "]", "]" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/tiling.py#L625-L635
pdm-project/pdm
34ba2ea48bf079044b0ca8c0017f3c0e7d9e198b
pdm/cli/actions.py
python
do_use
( project: Project, python: str = "", first: bool = False, ignore_remembered: bool = False, )
Use the specified python version and save in project config. The python can be a version string or interpreter path.
Use the specified python version and save in project config. The python can be a version string or interpreter path.
[ "Use", "the", "specified", "python", "version", "and", "save", "in", "project", "config", ".", "The", "python", "can", "be", "a", "version", "string", "or", "interpreter", "path", "." ]
def do_use( project: Project, python: str = "", first: bool = False, ignore_remembered: bool = False, ) -> None: """Use the specified python version and save in project config. The python can be a version string or interpreter path. """ if python: python = python.strip() def version_matcher(py_version: PythonInfo) -> bool: return project.python_requires.contains(str(py_version.version)) use_cache: JSONFileCache[str, str] = JSONFileCache( project.cache_dir / "use_cache.json" ) selected_python: PythonInfo | None = None if python and not ignore_remembered: if use_cache.has_key(python): cached_python = PythonInfo.from_path(use_cache.get(python)) if version_matcher(cached_python): project.core.ui.echo( "Using the last selection, add '-i' to ignore it.", fg="yellow", err=True, ) selected_python = cached_python if selected_python is None: found_interpreters = list(dict.fromkeys(project.find_interpreters(python))) matching_interperters = list(filter(version_matcher, found_interpreters)) if not found_interpreters: raise NoPythonVersion("Python interpreter is not found on the system.") if not matching_interperters: project.core.ui.echo("Interpreters found but not matching:", err=True) for py in found_interpreters: project.core.ui.echo(f" - {py.executable} ({py.identifier})", err=True) raise NoPythonVersion( "No python is found meeting the requirement " f"{termui.green('python' + str(project.python_requires))}" ) if first or len(found_interpreters) == 1: selected_python = found_interpreters[0] else: project.core.ui.echo("Please enter the Python interpreter to use") for i, py_version in enumerate(found_interpreters): project.core.ui.echo( f"{i}. {termui.green(py_version.executable)} " f"({py_version.identifier})" ) selection = click.prompt( "Please select:", type=click.Choice([str(i) for i in range(len(found_interpreters))]), default="0", show_choices=False, ) selected_python = found_interpreters[int(selection)] if python: use_cache.set(python, selected_python.path) old_python = project.python if "python.path" in project.config else None project.core.ui.echo( "Using Python interpreter: {} ({})".format( termui.green(str(selected_python.executable)), selected_python.identifier, ) ) project.python = selected_python if ( old_python and Path(old_python.path) != Path(selected_python.path) and not project.environment.is_global ): project.core.ui.echo(termui.cyan("Updating executable scripts...")) project.environment.update_shebangs(selected_python.executable)
[ "def", "do_use", "(", "project", ":", "Project", ",", "python", ":", "str", "=", "\"\"", ",", "first", ":", "bool", "=", "False", ",", "ignore_remembered", ":", "bool", "=", "False", ",", ")", "->", "None", ":", "if", "python", ":", "python", "=", ...
https://github.com/pdm-project/pdm/blob/34ba2ea48bf079044b0ca8c0017f3c0e7d9e198b/pdm/cli/actions.py#L519-L594
intelxed/xed
d57a3bd0a8ad7a1f0c6e2a1b58060d9014021098
pysrc/generator.py
python
all_generator_info_t.close_output_files
(self)
Close the major output files
Close the major output files
[ "Close", "the", "major", "output", "files" ]
def close_output_files(self): "Close the major output files" self.common.close_output_files()
[ "def", "close_output_files", "(", "self", ")", ":", "self", ".", "common", ".", "close_output_files", "(", ")" ]
https://github.com/intelxed/xed/blob/d57a3bd0a8ad7a1f0c6e2a1b58060d9014021098/pysrc/generator.py#L5149-L5151
OpenMDAO/OpenMDAO1
791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317
openmdao/examples/cokriging_forrester.py
python
model_hifi
(x)
return ((6*x-2)**2)*np.sin((6*x-2)*2)
[]
def model_hifi(x): return ((6*x-2)**2)*np.sin((6*x-2)*2)
[ "def", "model_hifi", "(", "x", ")", ":", "return", "(", "(", "6", "*", "x", "-", "2", ")", "**", "2", ")", "*", "np", ".", "sin", "(", "(", "6", "*", "x", "-", "2", ")", "*", "2", ")" ]
https://github.com/OpenMDAO/OpenMDAO1/blob/791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317/openmdao/examples/cokriging_forrester.py#L10-L11
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
ExternalDriveBackupPolicy.is_disabled
(self)
return self._tag == 'disabled'
Check if the union tag is ``disabled``. :rtype: bool
Check if the union tag is ``disabled``.
[ "Check", "if", "the", "union", "tag", "is", "disabled", "." ]
def is_disabled(self): """ Check if the union tag is ``disabled``. :rtype: bool """ return self._tag == 'disabled'
[ "def", "is_disabled", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'disabled'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L44020-L44026
Tencent/GAutomator
0ac9f849d1ca2c59760a91c5c94d3db375a380cd
GAutomatorAndroid/libs/urllib3/util/url.py
python
Url.url
(self)
return url
Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment'
Convert self into a url
[ "Convert", "self", "into", "a", "url" ]
def url(self): """ Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment' """ scheme, auth, host, port, path, query, fragment = self url = '' # We use "is not None" we want things to happen with empty strings (or 0 port) if scheme is not None: url += scheme + '://' if auth is not None: url += auth + '@' if host is not None: url += host if port is not None: url += ':' + str(port) if path is not None: url += path if query is not None: url += '?' + query if fragment is not None: url += '#' + fragment return url
[ "def", "url", "(", "self", ")", ":", "scheme", ",", "auth", ",", "host", ",", "port", ",", "path", ",", "query", ",", "fragment", "=", "self", "url", "=", "''", "# We use \"is not None\" we want things to happen with empty strings (or 0 port)", "if", "scheme", "...
https://github.com/Tencent/GAutomator/blob/0ac9f849d1ca2c59760a91c5c94d3db375a380cd/GAutomatorAndroid/libs/urllib3/util/url.py#L47-L84
dropbox/PyHive
b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0
TCLIService/TCLIService.py
python
Processor.process_ExecuteStatement
(self, seqid, iprot, oprot)
[]
def process_ExecuteStatement(self, seqid, iprot, oprot): args = ExecuteStatement_args() args.read(iprot) iprot.readMessageEnd() result = ExecuteStatement_result() try: result.success = self._handler.ExecuteStatement(args.req) msg_type = TMessageType.REPLY except (TTransport.TTransportException, KeyboardInterrupt, SystemExit): raise except Exception as ex: msg_type = TMessageType.EXCEPTION logging.exception(ex) result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error') oprot.writeMessageBegin("ExecuteStatement", msg_type, seqid) result.write(oprot) oprot.writeMessageEnd() oprot.trans.flush()
[ "def", "process_ExecuteStatement", "(", "self", ",", "seqid", ",", "iprot", ",", "oprot", ")", ":", "args", "=", "ExecuteStatement_args", "(", ")", "args", ".", "read", "(", "iprot", ")", "iprot", ".", "readMessageEnd", "(", ")", "result", "=", "ExecuteSta...
https://github.com/dropbox/PyHive/blob/b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0/TCLIService/TCLIService.py#L963-L980
mtivadar/qiew
87a3b96b43f1745a6b3f1fcfebce5164d2a40a14
DisasmViewMode.py
python
ASMLine.hex
(self)
return self._hexstr
[]
def hex(self): return self._hexstr
[ "def", "hex", "(", "self", ")", ":", "return", "self", ".", "_hexstr" ]
https://github.com/mtivadar/qiew/blob/87a3b96b43f1745a6b3f1fcfebce5164d2a40a14/DisasmViewMode.py#L276-L277
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/iotcloud/v20180614/models.py
python
DescribeResourceTasksRequest.__init__
(self)
r""" :param ProductID: 产品ID :type ProductID: str :param Name: 资源名称 :type Name: str :param Offset: 查询偏移量 :type Offset: int :param Limit: 返回查询结果条数 :type Limit: int :param Filters: 搜索过滤条件 :type Filters: list of SearchKeyword
r""" :param ProductID: 产品ID :type ProductID: str :param Name: 资源名称 :type Name: str :param Offset: 查询偏移量 :type Offset: int :param Limit: 返回查询结果条数 :type Limit: int :param Filters: 搜索过滤条件 :type Filters: list of SearchKeyword
[ "r", ":", "param", "ProductID", ":", "产品ID", ":", "type", "ProductID", ":", "str", ":", "param", "Name", ":", "资源名称", ":", "type", "Name", ":", "str", ":", "param", "Offset", ":", "查询偏移量", ":", "type", "Offset", ":", "int", ":", "param", "Limit", "...
def __init__(self): r""" :param ProductID: 产品ID :type ProductID: str :param Name: 资源名称 :type Name: str :param Offset: 查询偏移量 :type Offset: int :param Limit: 返回查询结果条数 :type Limit: int :param Filters: 搜索过滤条件 :type Filters: list of SearchKeyword """ self.ProductID = None self.Name = None self.Offset = None self.Limit = None self.Filters = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ProductID", "=", "None", "self", ".", "Name", "=", "None", "self", ".", "Offset", "=", "None", "self", ".", "Limit", "=", "None", "self", ".", "Filters", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/iotcloud/v20180614/models.py#L2635-L2652
0vercl0k/stuffz
2ff82f4739d7e215c6140d4987efa8310db39d55
download_youtube_playlists_videos.py
python
UserPlaylistsDownloader.__sanitize_title
(self, s)
return filter(lambda c: c in white_list, s)
Only keep the alphanum characters on the filename
Only keep the alphanum characters on the filename
[ "Only", "keep", "the", "alphanum", "characters", "on", "the", "filename" ]
def __sanitize_title(self, s): """ Only keep the alphanum characters on the filename """ white_list = list(string.letters + string.digits + ' ') return filter(lambda c: c in white_list, s)
[ "def", "__sanitize_title", "(", "self", ",", "s", ")", ":", "white_list", "=", "list", "(", "string", ".", "letters", "+", "string", ".", "digits", "+", "' '", ")", "return", "filter", "(", "lambda", "c", ":", "c", "in", "white_list", ",", "s", ")" ]
https://github.com/0vercl0k/stuffz/blob/2ff82f4739d7e215c6140d4987efa8310db39d55/download_youtube_playlists_videos.py#L204-L207
openedx/ecommerce
db6c774e239e5aa65e5a6151995073d364e8c896
ecommerce/core/models.py
python
User._get_lms_user_id_from_social_auth
(self)
return None, None
Find the LMS user_id passed through social auth. Because a single user_id can be associated with multiple provider/uid combinations, start by checking the most recently saved social auth entry. Returns: (lms_user_id, social_auth_id): a tuple containing the LMS user id and the id of the social auth entry where the LMS user id was found. Returns None, None if the LMS user id was not found.
Find the LMS user_id passed through social auth. Because a single user_id can be associated with multiple provider/uid combinations, start by checking the most recently saved social auth entry.
[ "Find", "the", "LMS", "user_id", "passed", "through", "social", "auth", ".", "Because", "a", "single", "user_id", "can", "be", "associated", "with", "multiple", "provider", "/", "uid", "combinations", "start", "by", "checking", "the", "most", "recently", "save...
def _get_lms_user_id_from_social_auth(self): """ Find the LMS user_id passed through social auth. Because a single user_id can be associated with multiple provider/uid combinations, start by checking the most recently saved social auth entry. Returns: (lms_user_id, social_auth_id): a tuple containing the LMS user id and the id of the social auth entry where the LMS user id was found. Returns None, None if the LMS user id was not found. """ try: auth_entries = self.social_auth.order_by('-id') if auth_entries: for auth_entry in auth_entries: lms_user_id_social_auth = auth_entry.extra_data.get(u'user_id') if lms_user_id_social_auth: return lms_user_id_social_auth, auth_entry.id except Exception: # pylint: disable=broad-except log.warning(u'Exception retrieving lms_user_id from social_auth for user %s.', self.id, exc_info=True) return None, None
[ "def", "_get_lms_user_id_from_social_auth", "(", "self", ")", ":", "try", ":", "auth_entries", "=", "self", ".", "social_auth", ".", "order_by", "(", "'-id'", ")", "if", "auth_entries", ":", "for", "auth_entry", "in", "auth_entries", ":", "lms_user_id_social_auth"...
https://github.com/openedx/ecommerce/blob/db6c774e239e5aa65e5a6151995073d364e8c896/ecommerce/core/models.py#L643-L661
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/UserDict.py
python
DictMixin.items
(self)
return list(self.iteritems())
[]
def items(self): return list(self.iteritems())
[ "def", "items", "(", "self", ")", ":", "return", "list", "(", "self", ".", "iteritems", "(", ")", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/UserDict.py#L154-L155
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
plugins/snippets/snippets/libs/jinja2/visitor.py
python
NodeTransformer.visit_list
(self, node, *args, **kwargs)
return rv
As transformers may return lists in some places this method can be used to enforce a list as return value.
As transformers may return lists in some places this method can be used to enforce a list as return value.
[ "As", "transformers", "may", "return", "lists", "in", "some", "places", "this", "method", "can", "be", "used", "to", "enforce", "a", "list", "as", "return", "value", "." ]
def visit_list(self, node, *args, **kwargs): """As transformers may return lists in some places this method can be used to enforce a list as return value. """ rv = self.visit(node, *args, **kwargs) if not isinstance(rv, list): rv = [rv] return rv
[ "def", "visit_list", "(", "self", ",", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "rv", "=", "self", ".", "visit", "(", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "isinstance", "(", "rv", ",", "list",...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/plugins/snippets/snippets/libs/jinja2/visitor.py#L80-L87
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.2/django/utils/tree.py
python
Node.__init__
(self, children=None, connector=None, negated=False)
Constructs a new Node. If no connector is given, the default will be used. Warning: You probably don't want to pass in the 'negated' parameter. It is NOT the same as constructing a node and calling negate() on the result.
Constructs a new Node. If no connector is given, the default will be used.
[ "Constructs", "a", "new", "Node", ".", "If", "no", "connector", "is", "given", "the", "default", "will", "be", "used", "." ]
def __init__(self, children=None, connector=None, negated=False): """ Constructs a new Node. If no connector is given, the default will be used. Warning: You probably don't want to pass in the 'negated' parameter. It is NOT the same as constructing a node and calling negate() on the result. """ self.children = children and children[:] or [] self.connector = connector or self.default self.subtree_parents = [] self.negated = negated
[ "def", "__init__", "(", "self", ",", "children", "=", "None", ",", "connector", "=", "None", ",", "negated", "=", "False", ")", ":", "self", ".", "children", "=", "children", "and", "children", "[", ":", "]", "or", "[", "]", "self", ".", "connector",...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.2/django/utils/tree.py#L18-L30