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
XuezheMax/flowseq
8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b
flownmt/modules/encoders/transformer.py
python
TransformerEncoder.__init__
(self, vocab_size, embed_dim, padding_idx, num_layers, latent_dim, hidden_size, heads, dropout=0.0, max_length=100)
[]
def __init__(self, vocab_size, embed_dim, padding_idx, num_layers, latent_dim, hidden_size, heads, dropout=0.0, max_length=100): super(TransformerEncoder, self).__init__(vocab_size, embed_dim, padding_idx) self.core = TransformerCore(self.embed, num_layers, latent_dim, hidden_size, heads, dropout=dropout, max_length=max_length)
[ "def", "__init__", "(", "self", ",", "vocab_size", ",", "embed_dim", ",", "padding_idx", ",", "num_layers", ",", "latent_dim", ",", "hidden_size", ",", "heads", ",", "dropout", "=", "0.0", ",", "max_length", "=", "100", ")", ":", "super", "(", "Transformer...
https://github.com/XuezheMax/flowseq/blob/8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b/flownmt/modules/encoders/transformer.py#L59-L61
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/idlelib/search.py
python
find_selection
(text)
return _setup(text).find_selection(text)
Handle the editor edit menu item and corresponding event.
Handle the editor edit menu item and corresponding event.
[ "Handle", "the", "editor", "edit", "menu", "item", "and", "corresponding", "event", "." ]
def find_selection(text): "Handle the editor edit menu item and corresponding event." return _setup(text).find_selection(text)
[ "def", "find_selection", "(", "text", ")", ":", "return", "_setup", "(", "text", ")", ".", "find_selection", "(", "text", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/idlelib/search.py#L23-L25
KhronosGroup/NNEF-Tools
c913758ca687dab8cb7b49e8f1556819a2d0ca25
nnef_tools/io/tf/lite/flatbuffers/Model.py
python
ModelStartMetadataBufferVector
(builder, numElems)
return builder.StartVector(4, numElems, 4)
[]
def ModelStartMetadataBufferVector(builder, numElems): return builder.StartVector(4, numElems, 4)
[ "def", "ModelStartMetadataBufferVector", "(", "builder", ",", "numElems", ")", ":", "return", "builder", ".", "StartVector", "(", "4", ",", "numElems", ",", "4", ")" ]
https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/io/tf/lite/flatbuffers/Model.py#L178-L178
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pywin/Lib/numbers.py
python
Real.__float__
(self)
Any Real can be converted to a native float object. Called for float(self).
Any Real can be converted to a native float object.
[ "Any", "Real", "can", "be", "converted", "to", "a", "native", "float", "object", "." ]
def __float__(self): """Any Real can be converted to a native float object. Called for float(self).""" raise NotImplementedError
[ "def", "__float__", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/numbers.py#L181-L185
poppy-project/pypot
c5d384fe23eef9f6ec98467f6f76626cdf20afb9
pypot/dynamixel/io/abstract_io.py
python
AbstractDxlIO.timeout
(self)
return self._serial.timeout
Timeout used by the :class:`~pypot.dynamixel.io.DxlIO`. If set, will re-open a new connection.
Timeout used by the :class:`~pypot.dynamixel.io.DxlIO`. If set, will re-open a new connection.
[ "Timeout", "used", "by", "the", ":", "class", ":", "~pypot", ".", "dynamixel", ".", "io", ".", "DxlIO", ".", "If", "set", "will", "re", "-", "open", "a", "new", "connection", "." ]
def timeout(self): """ Timeout used by the :class:`~pypot.dynamixel.io.DxlIO`. If set, will re-open a new connection. """ return self._serial.timeout
[ "def", "timeout", "(", "self", ")", ":", "return", "self", ".", "_serial", ".", "timeout" ]
https://github.com/poppy-project/pypot/blob/c5d384fe23eef9f6ec98467f6f76626cdf20afb9/pypot/dynamixel/io/abstract_io.py#L190-L192
selfteaching/selfteaching-python-camp
9982ee964b984595e7d664b07c389cddaf158f1e
19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/distlib/version.py
python
Matcher.match
(self, version)
return True
Check if the provided version matches the constraints. :param version: The version to match against this instance. :type version: String or :class:`Version` instance.
Check if the provided version matches the constraints.
[ "Check", "if", "the", "provided", "version", "matches", "the", "constraints", "." ]
def match(self, version): """ Check if the provided version matches the constraints. :param version: The version to match against this instance. :type version: String or :class:`Version` instance. """ if isinstance(version, string_types): version = self.version_class(version) for operator, constraint, prefix in self._parts: f = self._operators.get(operator) if isinstance(f, string_types): f = getattr(self, f) if not f: msg = ('%r not implemented ' 'for %s' % (operator, self.__class__.__name__)) raise NotImplementedError(msg) if not f(version, constraint, prefix): return False return True
[ "def", "match", "(", "self", ",", "version", ")", ":", "if", "isinstance", "(", "version", ",", "string_types", ")", ":", "version", "=", "self", ".", "version_class", "(", "version", ")", "for", "operator", ",", "constraint", ",", "prefix", "in", "self"...
https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/distlib/version.py#L129-L148
aws/aws-parallelcluster
f1fe5679a01c524e7ea904c329bd6d17318c6cd9
cli/src/pcluster3_config_converter/pcluster3_config_converter.py
python
_parse_args
(argv=None)
return convert_parser.parse_args(argv)
Parse command line args.
Parse command line args.
[ "Parse", "command", "line", "args", "." ]
def _parse_args(argv=None): """Parse command line args.""" convert_parser = argparse.ArgumentParser( description="Convert AWS ParallelCluster configuration file.", ) convert_parser.add_argument( "-c", "--config-file", help="Configuration file to be used as input.", required=True, ) convert_parser.add_argument( "-t", "--cluster-template", help=( "Indicates the 'cluster' section of the configuration file to convert. " "If not specified the script will look for the cluster_template parameter in the [global] section " "or will search for '[cluster default]'." ), required=False, ) convert_parser.add_argument( "-o", "--output-file", help="Configuration file to be written as output. By default the output will be written to stdout.", required=False, ) convert_parser.add_argument( "--force-convert", help="Convert parameters that are not officially supported and not recommended.", required=False, action="store_true", ) convert_parser.set_defaults(func=convert) return convert_parser.parse_args(argv)
[ "def", "_parse_args", "(", "argv", "=", "None", ")", ":", "convert_parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Convert AWS ParallelCluster configuration file.\"", ",", ")", "convert_parser", ".", "add_argument", "(", "\"-c\"", ",", "...
https://github.com/aws/aws-parallelcluster/blob/f1fe5679a01c524e7ea904c329bd6d17318c6cd9/cli/src/pcluster3_config_converter/pcluster3_config_converter.py#L1073-L1108
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/uuid.py
python
UUID.__init__
(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None)
r"""Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the 'bytes' argument, a string of 16 bytes in little-endian order as the 'bytes_le' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as the 'fields' argument, or a single 128-bit integer as the 'int' argument. When a string of hex digits is given, curly braces, hyphens, and a URN prefix are all optional. For example, these expressions all yield the same UUID: UUID('{12345678-1234-5678-1234-567812345678}') UUID('12345678123456781234567812345678') UUID('urn:uuid:12345678-1234-5678-1234-567812345678') UUID(bytes='\x12\x34\x56\x78'*4) UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' + '\x12\x34\x56\x78\x12\x34\x56\x78') UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) UUID(int=0x12345678123456781234567812345678) Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must be given. The 'version' argument is optional; if given, the resulting UUID will have its variant and version set according to RFC 4122, overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
r"""Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the 'bytes' argument, a string of 16 bytes in little-endian order as the 'bytes_le' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as the 'fields' argument, or a single 128-bit integer as the 'int' argument. When a string of hex digits is given, curly braces, hyphens, and a URN prefix are all optional. For example, these expressions all yield the same UUID:
[ "r", "Create", "a", "UUID", "from", "either", "a", "string", "of", "32", "hexadecimal", "digits", "a", "string", "of", "16", "bytes", "as", "the", "bytes", "argument", "a", "string", "of", "16", "bytes", "in", "little", "-", "endian", "order", "as", "t...
def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None): r"""Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the 'bytes' argument, a string of 16 bytes in little-endian order as the 'bytes_le' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as the 'fields' argument, or a single 128-bit integer as the 'int' argument. When a string of hex digits is given, curly braces, hyphens, and a URN prefix are all optional. For example, these expressions all yield the same UUID: UUID('{12345678-1234-5678-1234-567812345678}') UUID('12345678123456781234567812345678') UUID('urn:uuid:12345678-1234-5678-1234-567812345678') UUID(bytes='\x12\x34\x56\x78'*4) UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' + '\x12\x34\x56\x78\x12\x34\x56\x78') UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) UUID(int=0x12345678123456781234567812345678) Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must be given. The 'version' argument is optional; if given, the resulting UUID will have its variant and version set according to RFC 4122, overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'. """ if [hex, bytes, bytes_le, fields, int].count(None) != 4: raise TypeError('need one of hex, bytes, bytes_le, fields, or int') if hex is not None: hex = hex.replace('urn:', '').replace('uuid:', '') hex = hex.strip('{}').replace('-', '') if len(hex) != 32: raise ValueError('badly formed hexadecimal UUID string') int = long(hex, 16) if bytes_le is not None: if len(bytes_le) != 16: raise ValueError('bytes_le is not a 16-char string') bytes = (bytes_le[3] + bytes_le[2] + bytes_le[1] + bytes_le[0] + bytes_le[5] + bytes_le[4] + bytes_le[7] + bytes_le[6] + bytes_le[8:]) if bytes is not None: if len(bytes) != 16: raise ValueError('bytes is not a 16-char string') int = long(('%02x'*16) % tuple(map(ord, bytes)), 16) if fields is not None: if len(fields) != 6: raise ValueError('fields is not a 6-tuple') (time_low, time_mid, time_hi_version, clock_seq_hi_variant, clock_seq_low, node) = fields if not 0 <= time_low < 1<<32L: raise ValueError('field 1 out of range (need a 32-bit value)') if not 0 <= time_mid < 1<<16L: raise ValueError('field 2 out of range (need a 16-bit value)') if not 0 <= time_hi_version < 1<<16L: raise ValueError('field 3 out of range (need a 16-bit value)') if not 0 <= clock_seq_hi_variant < 1<<8L: raise ValueError('field 4 out of range (need an 8-bit value)') if not 0 <= clock_seq_low < 1<<8L: raise ValueError('field 5 out of range (need an 8-bit value)') if not 0 <= node < 1<<48L: raise ValueError('field 6 out of range (need a 48-bit value)') clock_seq = (clock_seq_hi_variant << 8L) | clock_seq_low int = ((time_low << 96L) | (time_mid << 80L) | (time_hi_version << 64L) | (clock_seq << 48L) | node) if int is not None: if not 0 <= int < 1<<128L: raise ValueError('int is out of range (need a 128-bit value)') if version is not None: if not 1 <= version <= 5: raise ValueError('illegal version number') # Set the variant to RFC 4122. int &= ~(0xc000 << 48L) int |= 0x8000 << 48L # Set the version number. int &= ~(0xf000 << 64L) int |= version << 76L self.__dict__['int'] = int
[ "def", "__init__", "(", "self", ",", "hex", "=", "None", ",", "bytes", "=", "None", ",", "bytes_le", "=", "None", ",", "fields", "=", "None", ",", "int", "=", "None", ",", "version", "=", "None", ")", ":", "if", "[", "hex", ",", "bytes", ",", "...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/uuid.py#L101-L178
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/pkg_resources/__init__.py
python
Environment.__add__
(self, other)
return new
Add an environment or distribution to an environment
Add an environment or distribution to an environment
[ "Add", "an", "environment", "or", "distribution", "to", "an", "environment" ]
def __add__(self, other): """Add an environment or distribution to an environment""" new = self.__class__([], platform=None, python=None) for env in self, other: new += env return new
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "new", "=", "self", ".", "__class__", "(", "[", "]", ",", "platform", "=", "None", ",", "python", "=", "None", ")", "for", "env", "in", "self", ",", "other", ":", "new", "+=", "env", "return"...
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/pkg_resources/__init__.py#L1095-L1100
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
examples/pytorch_lightning/graph_sage.py
python
main
()
[]
def main(): seed_everything(42) dataset = Reddit(osp.join('data', 'Reddit')) data = dataset[0] datamodule = LightningNodeData(data, data.train_mask, data.val_mask, data.test_mask, loader='neighbor', num_neighbors=[25, 10], batch_size=1024, num_workers=8) model = Model(dataset.num_node_features, dataset.num_classes) gpus = torch.cuda.device_count() strategy = pl.plugins.DDPSpawnPlugin(find_unused_parameters=False) checkpoint = pl.callbacks.ModelCheckpoint(monitor='val_acc', save_top_k=1) trainer = pl.Trainer(gpus=gpus, strategy=strategy, max_epochs=20, callbacks=[checkpoint]) trainer.fit(model, datamodule) trainer.test(ckpt_path='best', datamodule=datamodule)
[ "def", "main", "(", ")", ":", "seed_everything", "(", "42", ")", "dataset", "=", "Reddit", "(", "osp", ".", "join", "(", "'data'", ",", "'Reddit'", ")", ")", "data", "=", "dataset", "[", "0", "]", "datamodule", "=", "LightningNodeData", "(", "data", ...
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/examples/pytorch_lightning/graph_sage.py#L59-L79
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mFIZ/scripts/mFIZ_extern/serial/rfc2217.py
python
TelnetSubnegotiation.set
(self, value)
\ Request a change of the value. a request is sent to the server. if the client needs to know if the change is performed he has to check the state of this object.
\ Request a change of the value. a request is sent to the server. if the client needs to know if the change is performed he has to check the state of this object.
[ "\\", "Request", "a", "change", "of", "the", "value", ".", "a", "request", "is", "sent", "to", "the", "server", ".", "if", "the", "client", "needs", "to", "know", "if", "the", "change", "is", "performed", "he", "has", "to", "check", "the", "state", "...
def set(self, value): """\ Request a change of the value. a request is sent to the server. if the client needs to know if the change is performed he has to check the state of this object. """ self.value = value self.state = REQUESTED self.connection.rfc2217_send_subnegotiation(self.option, self.value) if self.connection.logger: self.connection.logger.debug("SB Requesting {} -> {!r}".format(self.name, self.value))
[ "def", "set", "(", "self", ",", "value", ")", ":", "self", ".", "value", "=", "value", "self", ".", "state", "=", "REQUESTED", "self", ".", "connection", ".", "rfc2217_send_subnegotiation", "(", "self", ".", "option", ",", "self", ".", "value", ")", "i...
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mFIZ/scripts/mFIZ_extern/serial/rfc2217.py#L325-L335
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
21-async/mojifinder/bottle.py
python
MultiDict.__delitem__
(self, key)
[]
def __delitem__(self, key): del self.dict[key]
[ "def", "__delitem__", "(", "self", ",", "key", ")", ":", "del", "self", ".", "dict", "[", "key", "]" ]
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/21-async/mojifinder/bottle.py#L1833-L1833
facebookresearch/ClassyVision
309d4f12431c6b4d8540010a781dc2aa25fe88e7
classy_vision/models/r2plus1_util.py
python
r2plus1_unit
( dim_in, dim_out, temporal_stride, spatial_stride, groups, inplace_relu, bn_eps, bn_mmt, dim_mid=None, )
return nn.Sequential(conv_middle, conv_middle_bn, conv_middle_relu, conv)
Implementation of `R(2+1)D unit <https://arxiv.org/abs/1711.11248>`_. Decompose one 3D conv into one 2D spatial conv and one 1D temporal conv. Choose the middle dimensionality so that the total No. of parameters in 2D spatial conv and 1D temporal conv is unchanged. Args: dim_in (int): the channel dimensions of the input. dim_out (int): the channel dimension of the output. temporal_stride (int): the temporal stride of the bottleneck. spatial_stride (int): the spatial_stride of the bottleneck. groups (int): number of groups for the convolution. inplace_relu (bool): calculate the relu on the original input without allocating new memory. bn_eps (float): epsilon for batch norm. bn_mmt (float): momentum for batch norm. Noted that BN momentum in PyTorch = 1 - BN momentum in Caffe2. dim_mid (Optional[int]): If not None, use the provided channel dimension for the output of the 2D spatial conv. If None, compute the output channel dimension of the 2D spatial conv so that the total No. of model parameters remains unchanged.
Implementation of `R(2+1)D unit <https://arxiv.org/abs/1711.11248>`_. Decompose one 3D conv into one 2D spatial conv and one 1D temporal conv. Choose the middle dimensionality so that the total No. of parameters in 2D spatial conv and 1D temporal conv is unchanged.
[ "Implementation", "of", "R", "(", "2", "+", "1", ")", "D", "unit", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1711", ".", "11248", ">", "_", ".", "Decompose", "one", "3D", "conv", "into", "one", "2D", "spatial", "conv", "and", "o...
def r2plus1_unit( dim_in, dim_out, temporal_stride, spatial_stride, groups, inplace_relu, bn_eps, bn_mmt, dim_mid=None, ): """ Implementation of `R(2+1)D unit <https://arxiv.org/abs/1711.11248>`_. Decompose one 3D conv into one 2D spatial conv and one 1D temporal conv. Choose the middle dimensionality so that the total No. of parameters in 2D spatial conv and 1D temporal conv is unchanged. Args: dim_in (int): the channel dimensions of the input. dim_out (int): the channel dimension of the output. temporal_stride (int): the temporal stride of the bottleneck. spatial_stride (int): the spatial_stride of the bottleneck. groups (int): number of groups for the convolution. inplace_relu (bool): calculate the relu on the original input without allocating new memory. bn_eps (float): epsilon for batch norm. bn_mmt (float): momentum for batch norm. Noted that BN momentum in PyTorch = 1 - BN momentum in Caffe2. dim_mid (Optional[int]): If not None, use the provided channel dimension for the output of the 2D spatial conv. If None, compute the output channel dimension of the 2D spatial conv so that the total No. of model parameters remains unchanged. """ if dim_mid is None: dim_mid = int(dim_out * dim_in * 3 * 3 * 3 / (dim_in * 3 * 3 + dim_out * 3)) logging.info( "dim_in: %d, dim_out: %d. Set dim_mid to %d" % (dim_in, dim_out, dim_mid) ) # 1x3x3 group conv, BN, ReLU conv_middle = nn.Conv3d( dim_in, dim_mid, [1, 3, 3], # kernel stride=[1, spatial_stride, spatial_stride], padding=[0, 1, 1], groups=groups, bias=False, ) conv_middle_bn = nn.BatchNorm3d(dim_mid, eps=bn_eps, momentum=bn_mmt) conv_middle_relu = nn.ReLU(inplace=inplace_relu) # 3x1x1 group conv conv = nn.Conv3d( dim_mid, dim_out, [3, 1, 1], # kernel stride=[temporal_stride, 1, 1], padding=[1, 0, 0], groups=groups, bias=False, ) return nn.Sequential(conv_middle, conv_middle_bn, conv_middle_relu, conv)
[ "def", "r2plus1_unit", "(", "dim_in", ",", "dim_out", ",", "temporal_stride", ",", "spatial_stride", ",", "groups", ",", "inplace_relu", ",", "bn_eps", ",", "bn_mmt", ",", "dim_mid", "=", "None", ",", ")", ":", "if", "dim_mid", "is", "None", ":", "dim_mid"...
https://github.com/facebookresearch/ClassyVision/blob/309d4f12431c6b4d8540010a781dc2aa25fe88e7/classy_vision/models/r2plus1_util.py#L12-L72
google/prettytensor
75daa0b11252590f548da5647addc0ea610c4c45
prettytensor/pretty_tensor_class.py
python
PrettyTensor.sequence
(self)
Returns the sequence for this layer.
Returns the sequence for this layer.
[ "Returns", "the", "sequence", "for", "this", "layer", "." ]
def sequence(self): """Returns the sequence for this layer.""" raise NotImplementedError('Not implemented')
[ "def", "sequence", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'Not implemented'", ")" ]
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_class.py#L627-L629
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
calendarserver/tools/dashboard.py
python
SystemWindow.update
(self)
[]
def update(self): records = defaultIfNone(self.clientData(), { "cpu use": 0.0, "memory percent": 0.0, "memory used": 0, "start time": time.time(), }) if len(records) != self.rowCount: self.needsReset = True return self.iter += 1 s = " {:<30}{:>18} ".format("Item", "Value") pt = self.tableHeader((s,), len(records)) records["cpu use"] = "{:.2f}".format(records["cpu use"]) records["memory percent"] = "{:.1f}".format(records["memory percent"]) records["memory used"] = "{:.2f} GB".format( records["memory used"] / (1000.0 * 1000.0 * 1000.0) ) records["uptime"] = int(time.time() - records["start time"]) hours, mins = divmod(records["uptime"] / 60, 60) records["uptime"] = "{}:{:02d} hh:mm".format(hours, mins) del records["start time"] for item, value in sorted(records.items(), key=lambda x: x[0]): changed = ( item in self.lastResult and self.lastResult[item] != value ) s = " {:<30}{:>18} ".format(item, value) self.tableRow( s, pt, curses.A_REVERSE if changed else curses.A_NORMAL, ) if self.usesCurses: self.window.refresh() self.lastResult = records
[ "def", "update", "(", "self", ")", ":", "records", "=", "defaultIfNone", "(", "self", ".", "clientData", "(", ")", ",", "{", "\"cpu use\"", ":", "0.0", ",", "\"memory percent\"", ":", "0.0", ",", "\"memory used\"", ":", "0", ",", "\"start time\"", ":", "...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/calendarserver/tools/dashboard.py#L685-L723
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/generic.py
python
NDFrame.to_dense
(self)
return self
Return dense representation of NDFrame (as opposed to sparse).
Return dense representation of NDFrame (as opposed to sparse).
[ "Return", "dense", "representation", "of", "NDFrame", "(", "as", "opposed", "to", "sparse", ")", "." ]
def to_dense(self): """ Return dense representation of NDFrame (as opposed to sparse). """ # compat return self
[ "def", "to_dense", "(", "self", ")", ":", "# compat", "return", "self" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/generic.py#L1919-L1924
bitcraze/crazyflie-clients-python
65d433a945b097333e5681a937354045dd4b66f4
src/cfclient/ui/tab.py
python
Tab.getTabName
(self)
return self.tabName
Return the name of the tab that will be shown in the tab
Return the name of the tab that will be shown in the tab
[ "Return", "the", "name", "of", "the", "tab", "that", "will", "be", "shown", "in", "the", "tab" ]
def getTabName(self): """Return the name of the tab that will be shown in the tab""" return self.tabName
[ "def", "getTabName", "(", "self", ")", ":", "return", "self", ".", "tabName" ]
https://github.com/bitcraze/crazyflie-clients-python/blob/65d433a945b097333e5681a937354045dd4b66f4/src/cfclient/ui/tab.py#L91-L93
andyzsf/TuShare
92787ad0cd492614bdb6389b71a19c80d1c8c9ae
tushare/futures/ctp/futures/__init__.py
python
TraderApi.ReqQryTradingAccount
(self, pQryTradingAccount, nRequestID)
return 0
请求查询资金账户
请求查询资金账户
[ "请求查询资金账户" ]
def ReqQryTradingAccount(self, pQryTradingAccount, nRequestID): """请求查询资金账户""" return 0
[ "def", "ReqQryTradingAccount", "(", "self", ",", "pQryTradingAccount", ",", "nRequestID", ")", ":", "return", "0" ]
https://github.com/andyzsf/TuShare/blob/92787ad0cd492614bdb6389b71a19c80d1c8c9ae/tushare/futures/ctp/futures/__init__.py#L262-L264
mit-han-lab/data-efficient-gans
6858275f08f43a33026844c8c2ac4e703e8a07ba
DiffAugment-biggan-cifar/datasets.py
python
ILSVRC_HDF5.__len__
(self)
return self.num_imgs
[]
def __len__(self): return self.num_imgs
[ "def", "__len__", "(", "self", ")", ":", "return", "self", ".", "num_imgs" ]
https://github.com/mit-han-lab/data-efficient-gans/blob/6858275f08f43a33026844c8c2ac4e703e8a07ba/DiffAugment-biggan-cifar/datasets.py#L242-L243
crdoconnor/strictyaml
b456066a763285532fd75cd274d4a275d8499d6c
strictyaml/representation.py
python
YAML.text
(self)
return self._text
Return string value of scalar, whatever value it was parsed as.
Return string value of scalar, whatever value it was parsed as.
[ "Return", "string", "value", "of", "scalar", "whatever", "value", "it", "was", "parsed", "as", "." ]
def text(self): """ Return string value of scalar, whatever value it was parsed as. """ if isinstance(self._value, CommentedMap): raise TypeError("{0} is a mapping, has no text value.".format(repr(self))) if isinstance(self._value, CommentedSeq): raise TypeError("{0} is a sequence, has no text value.".format(repr(self))) return self._text
[ "def", "text", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_value", ",", "CommentedMap", ")", ":", "raise", "TypeError", "(", "\"{0} is a mapping, has no text value.\"", ".", "format", "(", "repr", "(", "self", ")", ")", ")", "if", "isins...
https://github.com/crdoconnor/strictyaml/blob/b456066a763285532fd75cd274d4a275d8499d6c/strictyaml/representation.py#L316-L324
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/xml/sax/handler.py
python
ContentHandler.startDocument
(self)
Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator).
Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator).
[ "Receive", "notification", "of", "the", "beginning", "of", "a", "document", ".", "The", "SAX", "parser", "will", "invoke", "this", "method", "only", "once", "before", "any", "other", "methods", "in", "this", "interface", "or", "in", "DTDHandler", "(", "excep...
def startDocument(self): """Receive notification of the beginning of a document. The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator).""" pass
[ "def", "startDocument", "(", "self", ")", ":", "pass" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/xml/sax/handler.py#L75-L81
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
libs/platform-tools/platform-tools_linux/systrace/catapult/third_party/pyserial/serial/serialwin32.py
python
Win32Serial._close
(self)
internal close port helper
internal close port helper
[ "internal", "close", "port", "helper" ]
def _close(self): """internal close port helper""" if self.hComPort: # Restore original timeout values: win32.SetCommTimeouts(self.hComPort, self._orgTimeouts) # Close COM-Port: win32.CloseHandle(self.hComPort) if self._overlappedRead is not None: win32.CloseHandle(self._overlappedRead.hEvent) self._overlappedRead = None if self._overlappedWrite is not None: win32.CloseHandle(self._overlappedWrite.hEvent) self._overlappedWrite = None self.hComPort = None
[ "def", "_close", "(", "self", ")", ":", "if", "self", ".", "hComPort", ":", "# Restore original timeout values:", "win32", ".", "SetCommTimeouts", "(", "self", ".", "hComPort", ",", "self", ".", "_orgTimeouts", ")", "# Close COM-Port:", "win32", ".", "CloseHandl...
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_linux/systrace/catapult/third_party/pyserial/serial/serialwin32.py#L208-L221
marcospereirampj/python-keycloak
dd130a0365da390ae28d8a9cb6f76103ecb5c83f
keycloak/keycloak_admin.py
python
KeycloakAdmin.create_group
(self, payload, parent=None, skip_exists=False)
return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
Creates a group in the Realm :param payload: GroupRepresentation :param parent: parent group's id. Required to create a sub-group. :param skip_exists: If true then do not raise an error if it already exists GroupRepresentation https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation :return: Http response
Creates a group in the Realm
[ "Creates", "a", "group", "in", "the", "Realm" ]
def create_group(self, payload, parent=None, skip_exists=False): """ Creates a group in the Realm :param payload: GroupRepresentation :param parent: parent group's id. Required to create a sub-group. :param skip_exists: If true then do not raise an error if it already exists GroupRepresentation https://www.keycloak.org/docs-api/8.0/rest-api/#_grouprepresentation :return: Http response """ if parent is None: params_path = {"realm-name": self.realm_name} data_raw = self.raw_post(URL_ADMIN_GROUPS.format(**params_path), data=json.dumps(payload)) else: params_path = {"realm-name": self.realm_name, "id": parent, } data_raw = self.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path), data=json.dumps(payload)) return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201], skip_exists=skip_exists)
[ "def", "create_group", "(", "self", ",", "payload", ",", "parent", "=", "None", ",", "skip_exists", "=", "False", ")", ":", "if", "parent", "is", "None", ":", "params_path", "=", "{", "\"realm-name\"", ":", "self", ".", "realm_name", "}", "data_raw", "="...
https://github.com/marcospereirampj/python-keycloak/blob/dd130a0365da390ae28d8a9cb6f76103ecb5c83f/keycloak/keycloak_admin.py#L714-L737
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/importlib/_bootstrap_external.py
python
SourceLoader.get_source
(self, fullname)
return decode_source(source_bytes)
Concrete implementation of InspectLoader.get_source.
Concrete implementation of InspectLoader.get_source.
[ "Concrete", "implementation", "of", "InspectLoader", ".", "get_source", "." ]
def get_source(self, fullname): """Concrete implementation of InspectLoader.get_source.""" path = self.get_filename(fullname) try: source_bytes = self.get_data(path) except OSError as exc: raise ImportError('source not available through get_data()', name=fullname) from exc return decode_source(source_bytes)
[ "def", "get_source", "(", "self", ",", "fullname", ")", ":", "path", "=", "self", ".", "get_filename", "(", "fullname", ")", "try", ":", "source_bytes", "=", "self", ".", "get_data", "(", "path", ")", "except", "OSError", "as", "exc", ":", "raise", "Im...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/importlib/_bootstrap_external.py#L775-L783
tschellenbach/Django-facebook
fecbb5dd4931cc03a8425bde84e5e7b1ba22786d
docs/docs_env/Lib/codecs.py
python
StreamReader.readlines
(self, sizehint=None, keepends=True)
return data.splitlines(keepends)
Read all lines available on the input stream and return them as list of lines. Line breaks are implemented using the codec's decoder method and are included in the list entries. sizehint, if given, is ignored since there is no efficient way to finding the true end-of-line.
Read all lines available on the input stream and return them as list of lines.
[ "Read", "all", "lines", "available", "on", "the", "input", "stream", "and", "return", "them", "as", "list", "of", "lines", "." ]
def readlines(self, sizehint=None, keepends=True): """ Read all lines available on the input stream and return them as list of lines. Line breaks are implemented using the codec's decoder method and are included in the list entries. sizehint, if given, is ignored since there is no efficient way to finding the true end-of-line. """ data = self.read() return data.splitlines(keepends)
[ "def", "readlines", "(", "self", ",", "sizehint", "=", "None", ",", "keepends", "=", "True", ")", ":", "data", "=", "self", ".", "read", "(", ")", "return", "data", ".", "splitlines", "(", "keepends", ")" ]
https://github.com/tschellenbach/Django-facebook/blob/fecbb5dd4931cc03a8425bde84e5e7b1ba22786d/docs/docs_env/Lib/codecs.py#L523-L536
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
WorkingSet.find_plugins
(self, plugin_env, full_env=None, installer=None, fallback=True)
return distributions, error_info
Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) # add plugins+libs to sys.path map(working_set.add, distributions) # display errors print('Could not load', errors) The `plugin_env` should be an ``Environment`` instance that contains only distributions that are in the project's "plugin directory" or directories. The `full_env`, if supplied, should be an ``Environment`` contains all currently-available distributions. If `full_env` is not supplied, one is created automatically from the ``WorkingSet`` this method is called on, which will typically mean that every directory on ``sys.path`` will be scanned for distributions. `installer` is a standard installer callback as used by the ``resolve()`` method. The `fallback` flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved. This method returns a 2-tuple: (`distributions`, `error_info`), where `distributions` is a list of the distributions found in `plugin_env` that were loadable, along with any other distributions that are needed to resolve their dependencies. `error_info` is a dictionary mapping unloadable plugin distributions to an exception instance describing the error that occurred. Usually this will be a ``DistributionNotFound`` or ``VersionConflict`` instance.
Find all activatable distributions in `plugin_env`
[ "Find", "all", "activatable", "distributions", "in", "plugin_env" ]
def find_plugins(self, plugin_env, full_env=None, installer=None, fallback=True): """Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) # add plugins+libs to sys.path map(working_set.add, distributions) # display errors print('Could not load', errors) The `plugin_env` should be an ``Environment`` instance that contains only distributions that are in the project's "plugin directory" or directories. The `full_env`, if supplied, should be an ``Environment`` contains all currently-available distributions. If `full_env` is not supplied, one is created automatically from the ``WorkingSet`` this method is called on, which will typically mean that every directory on ``sys.path`` will be scanned for distributions. `installer` is a standard installer callback as used by the ``resolve()`` method. The `fallback` flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved. This method returns a 2-tuple: (`distributions`, `error_info`), where `distributions` is a list of the distributions found in `plugin_env` that were loadable, along with any other distributions that are needed to resolve their dependencies. `error_info` is a dictionary mapping unloadable plugin distributions to an exception instance describing the error that occurred. Usually this will be a ``DistributionNotFound`` or ``VersionConflict`` instance. """ plugin_projects = list(plugin_env) # scan project names in alphabetic order plugin_projects.sort() error_info = {} distributions = {} if full_env is None: env = Environment(self.entries) env += plugin_env else: env = full_env + plugin_env shadow_set = self.__class__([]) # put all our entries in shadow_set list(map(shadow_set.add, self)) for project_name in plugin_projects: for dist in plugin_env[project_name]: req = [dist.as_requirement()] try: resolvees = shadow_set.resolve(req, env, installer) except ResolutionError as v: # save error info error_info[dist] = v if fallback: # try the next older version of project continue else: # give up on this project, keep going break else: list(map(shadow_set.add, resolvees)) distributions.update(dict.fromkeys(resolvees)) # success, no need to try any more versions of this project break distributions = list(distributions) distributions.sort() return distributions, error_info
[ "def", "find_plugins", "(", "self", ",", "plugin_env", ",", "full_env", "=", "None", ",", "installer", "=", "None", ",", "fallback", "=", "True", ")", ":", "plugin_projects", "=", "list", "(", "plugin_env", ")", "# scan project names in alphabetic order", "plugi...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L875-L957
openstack/horizon
12bb9fe5184c9dd3329ba17b3d03c90887dbcc3d
horizon/tabs/base.py
python
TabGroup.tabs_not_available
(self)
The fallback handler if no tabs are either allowed or enabled. In the event that no tabs are either allowed or enabled, this method is the fallback handler. By default it's a no-op, but it exists to make redirecting or raising exceptions possible for subclasses.
The fallback handler if no tabs are either allowed or enabled.
[ "The", "fallback", "handler", "if", "no", "tabs", "are", "either", "allowed", "or", "enabled", "." ]
def tabs_not_available(self): """The fallback handler if no tabs are either allowed or enabled. In the event that no tabs are either allowed or enabled, this method is the fallback handler. By default it's a no-op, but it exists to make redirecting or raising exceptions possible for subclasses. """
[ "def", "tabs_not_available", "(", "self", ")", ":" ]
https://github.com/openstack/horizon/blob/12bb9fe5184c9dd3329ba17b3d03c90887dbcc3d/horizon/tabs/base.py#L195-L201
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/iotvideo/v20201215/models.py
python
DeviceInfo.__init__
(self)
r""" :param DeviceName: 设备名 :type DeviceName: str :param Online: 设备是否在线,0不在线,1在线,2获取失败,3未激活 :type Online: int :param LoginTime: 设备最后上线时间 :type LoginTime: int :param DevicePsk: 设备密钥 :type DevicePsk: str :param EnableState: 设备启用状态 0为停用 1为可用 :type EnableState: int :param ExpireTime: 设备过期时间 :type ExpireTime: int
r""" :param DeviceName: 设备名 :type DeviceName: str :param Online: 设备是否在线,0不在线,1在线,2获取失败,3未激活 :type Online: int :param LoginTime: 设备最后上线时间 :type LoginTime: int :param DevicePsk: 设备密钥 :type DevicePsk: str :param EnableState: 设备启用状态 0为停用 1为可用 :type EnableState: int :param ExpireTime: 设备过期时间 :type ExpireTime: int
[ "r", ":", "param", "DeviceName", ":", "设备名", ":", "type", "DeviceName", ":", "str", ":", "param", "Online", ":", "设备是否在线,0不在线,1在线,2获取失败,3未激活", ":", "type", "Online", ":", "int", ":", "param", "LoginTime", ":", "设备最后上线时间", ":", "type", "LoginTime", ":", "in...
def __init__(self): r""" :param DeviceName: 设备名 :type DeviceName: str :param Online: 设备是否在线,0不在线,1在线,2获取失败,3未激活 :type Online: int :param LoginTime: 设备最后上线时间 :type LoginTime: int :param DevicePsk: 设备密钥 :type DevicePsk: str :param EnableState: 设备启用状态 0为停用 1为可用 :type EnableState: int :param ExpireTime: 设备过期时间 :type ExpireTime: int """ self.DeviceName = None self.Online = None self.LoginTime = None self.DevicePsk = None self.EnableState = None self.ExpireTime = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "DeviceName", "=", "None", "self", ".", "Online", "=", "None", "self", ".", "LoginTime", "=", "None", "self", ".", "DevicePsk", "=", "None", "self", ".", "EnableState", "=", "None", "self", ".", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/iotvideo/v20201215/models.py#L4075-L4095
wbond/oscrypto
d40c62577706682a0f6da5616ad09964f1c9137d
oscrypto/_mac/tls.py
python
TLSSocket.read
(self, max_length)
return output[0:max_length]
Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read - output may be less than this :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs oscrypto.errors.TLSDisconnectError - when the connection disconnects oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the data read
Reads data from the TLS-wrapped socket
[ "Reads", "data", "from", "the", "TLS", "-", "wrapped", "socket" ]
def read(self, max_length): """ Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read - output may be less than this :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs oscrypto.errors.TLSDisconnectError - when the connection disconnects oscrypto.errors.TLSGracefulDisconnectError - when the remote end gracefully closed the connection ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the data read """ if not isinstance(max_length, int_types): raise TypeError(pretty_message( ''' max_length must be an integer, not %s ''', type_name(max_length) )) if self._session_context is None: # Even if the session is closed, we can use # buffered data to respond to read requests if self._decrypted_bytes != b'': output = self._decrypted_bytes self._decrypted_bytes = b'' return output self._raise_closed() buffered_length = len(self._decrypted_bytes) # If we already have enough buffered data, just use that if buffered_length >= max_length: output = self._decrypted_bytes[0:max_length] self._decrypted_bytes = self._decrypted_bytes[max_length:] return output # Don't block if we have buffered data available, since it is ok to # return less than the max_length if buffered_length > 0 and not self.select_read(0): output = self._decrypted_bytes self._decrypted_bytes = b'' return output # Only read enough to get the requested amount when # combined with buffered data to_read = max_length - len(self._decrypted_bytes) read_buffer = buffer_from_bytes(to_read) processed_pointer = new(Security, 'size_t *') result = Security.SSLRead( self._session_context, read_buffer, to_read, processed_pointer ) if self._exception is not None: exception = self._exception self._exception = None raise exception if result and result not in set([SecurityConst.errSSLWouldBlock, SecurityConst.errSSLClosedGraceful]): handle_sec_error(result, TLSError) if result and result == SecurityConst.errSSLClosedGraceful: self._gracefully_closed = True self._shutdown(False) self._raise_closed() bytes_read = deref(processed_pointer) output = self._decrypted_bytes + bytes_from_buffer(read_buffer, bytes_read) self._decrypted_bytes = output[max_length:] return output[0:max_length]
[ "def", "read", "(", "self", ",", "max_length", ")", ":", "if", "not", "isinstance", "(", "max_length", ",", "int_types", ")", ":", "raise", "TypeError", "(", "pretty_message", "(", "'''\n max_length must be an integer, not %s\n '''", ",", ...
https://github.com/wbond/oscrypto/blob/d40c62577706682a0f6da5616ad09964f1c9137d/oscrypto/_mac/tls.py#L1017-L1098
allegro/ralph
1e4a9e1800d5f664abaef2624b8bf7512df279ce
src/ralph/virtual/management/commands/openstack_sync.py
python
Command._update_projects
(self, client)
Returns a map tenant_id->tenant_name :rtype: dict
Returns a map tenant_id->tenant_name :rtype: dict
[ "Returns", "a", "map", "tenant_id", "-", ">", "tenant_name", ":", "rtype", ":", "dict" ]
def _update_projects(self, client): """ Returns a map tenant_id->tenant_name :rtype: dict """ for project in client.get_keystone_projects(): if project.id not in self.openstack_projects: self.openstack_projects[project.id] = { 'name': project.name, 'servers': {}, 'tags': [] } self.openstack_projects[project.id]['tags'].append( client.site['tag'] )
[ "def", "_update_projects", "(", "self", ",", "client", ")", ":", "for", "project", "in", "client", ".", "get_keystone_projects", "(", ")", ":", "if", "project", ".", "id", "not", "in", "self", ".", "openstack_projects", ":", "self", ".", "openstack_projects"...
https://github.com/allegro/ralph/blob/1e4a9e1800d5f664abaef2624b8bf7512df279ce/src/ralph/virtual/management/commands/openstack_sync.py#L63-L77
CSAILVision/places365
06218620d593de09ac4f9f39b72ea0d175990a24
wideresnet.py
python
resnet34
(pretrained=False, **kwargs)
return model
Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-34 model.
[ "Constructs", "a", "ResNet", "-", "34", "model", "." ]
def resnet34(pretrained=False, **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) return model
[ "def", "resnet34", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "BasicBlock", ",", "[", "3", ",", "4", ",", "6", ",", "3", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ...
https://github.com/CSAILVision/places365/blob/06218620d593de09ac4f9f39b72ea0d175990a24/wideresnet.py#L170-L179
inspurer/WorkAttendanceSystem
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
V1.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/requests/api.py
python
head
(url, **kwargs)
return request('head', url, **kwargs)
Sends a HEAD request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response
Sends a HEAD request.
[ "Sends", "a", "HEAD", "request", "." ]
def head(url, **kwargs): """Sends a HEAD request. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :return: :class:`Response <Response>` object :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return request('head', url, **kwargs)
[ "def", "head", "(", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "False", ")", "return", "request", "(", "'head'", ",", "url", ",", "*", "*", "kwargs", ")" ]
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V1.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/requests/api.py#L86-L96
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
java/java2py/antlr-3.1.3/runtime/Python/antlr3/streams.py
python
CommonTokenStream.setTokenSource
(self, tokenSource)
Reset this token stream by setting its token source.
Reset this token stream by setting its token source.
[ "Reset", "this", "token", "stream", "by", "setting", "its", "token", "source", "." ]
def setTokenSource(self, tokenSource): """Reset this token stream by setting its token source.""" self.tokenSource = tokenSource self.tokens = [] self.p = -1 self.channel = DEFAULT_CHANNEL
[ "def", "setTokenSource", "(", "self", ",", "tokenSource", ")", ":", "self", ".", "tokenSource", "=", "tokenSource", "self", ".", "tokens", "=", "[", "]", "self", ".", "p", "=", "-", "1", "self", ".", "channel", "=", "DEFAULT_CHANNEL" ]
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/java/java2py/antlr-3.1.3/runtime/Python/antlr3/streams.py#L646-L652
rotki/rotki
aafa446815cdd5e9477436d1b02bee7d01b398c8
rotkehlchen/chain/ethereum/modules/aave/graph.py
python
AaveGraphInquirer._process_events
( self, user_address: ChecksumEthAddress, user_result: Dict[str, Any], from_ts: Timestamp, to_ts: Timestamp, deposits: List[AaveDepositWithdrawalEvent], withdrawals: List[AaveDepositWithdrawalEvent], borrows: List[AaveBorrowEvent], repays: List[AaveRepayEvent], liquidations: List[AaveLiquidationEvent], db_events: List[AaveEvent], balances: AaveBalances, )
return AaveEventProcessingResult( interest_events=interest_events, total_earned_interest=total_earned, total_lost=total_lost, total_earned_liquidations=total_earned_liquidations, )
Calculates the interest events and the total earned from all the given events. Also calculates total loss from borrowing and liquidations. Also returns the edited DB events
Calculates the interest events and the total earned from all the given events. Also calculates total loss from borrowing and liquidations.
[ "Calculates", "the", "interest", "events", "and", "the", "total", "earned", "from", "all", "the", "given", "events", ".", "Also", "calculates", "total", "loss", "from", "borrowing", "and", "liquidations", "." ]
def _process_events( self, user_address: ChecksumEthAddress, user_result: Dict[str, Any], from_ts: Timestamp, to_ts: Timestamp, deposits: List[AaveDepositWithdrawalEvent], withdrawals: List[AaveDepositWithdrawalEvent], borrows: List[AaveBorrowEvent], repays: List[AaveRepayEvent], liquidations: List[AaveLiquidationEvent], db_events: List[AaveEvent], balances: AaveBalances, ) -> AaveEventProcessingResult: """Calculates the interest events and the total earned from all the given events. Also calculates total loss from borrowing and liquidations. Also returns the edited DB events """ actions: List[AaveDepositWithdrawalEvent] = [] borrow_actions: List[AaveEvent] = [] db_interest_events: Set[AaveInterestEvent] = set() for db_event in db_events: if db_event.event_type == 'deposit': actions.append(db_event) # type: ignore elif db_event.event_type == 'withdrawal': actions.append(db_event) # type: ignore elif db_event.event_type == 'interest': db_interest_events.add(db_event) # type: ignore elif db_event.event_type == 'borrow': borrow_actions.append(db_event) elif db_event.event_type == 'repay': borrow_actions.append(db_event) elif db_event.event_type == 'liquidation': borrow_actions.append(db_event) interest_events, total_earned = self._calculate_interest_and_profit( user_address=user_address, user_result=user_result, actions=actions + deposits + withdrawals, balances=balances, db_interest_events=db_interest_events, from_ts=from_ts, to_ts=to_ts, ) total_lost, total_earned_liquidations = _calculate_loss( borrow_actions=borrow_actions + borrows + repays + liquidations, # type: ignore balances=balances, ) return AaveEventProcessingResult( interest_events=interest_events, total_earned_interest=total_earned, total_lost=total_lost, total_earned_liquidations=total_earned_liquidations, )
[ "def", "_process_events", "(", "self", ",", "user_address", ":", "ChecksumEthAddress", ",", "user_result", ":", "Dict", "[", "str", ",", "Any", "]", ",", "from_ts", ":", "Timestamp", ",", "to_ts", ":", "Timestamp", ",", "deposits", ":", "List", "[", "AaveD...
https://github.com/rotki/rotki/blob/aafa446815cdd5e9477436d1b02bee7d01b398c8/rotkehlchen/chain/ethereum/modules/aave/graph.py#L607-L661
LinOTP/LinOTP
bb3940bbaccea99550e6c063ff824f258dd6d6d7
linotp/provider/pushprovider/__init__.py
python
IPushProvider.push_notification
(self, challenge, gda, transactionId)
Sends out the push notification message. :param challenge: The push notification message / challenge :param gda: alternative to the token_info, the gda could be provided directly :param transactionId: The push notification transaction reference :return: A tuple of success and result message
Sends out the push notification message.
[ "Sends", "out", "the", "push", "notification", "message", "." ]
def push_notification(self, challenge, gda, transactionId): """ Sends out the push notification message. :param challenge: The push notification message / challenge :param gda: alternative to the token_info, the gda could be provided directly :param transactionId: The push notification transaction reference :return: A tuple of success and result message """ raise NotImplementedError( "Every subclass of IPushProvider has to implement this method." )
[ "def", "push_notification", "(", "self", ",", "challenge", ",", "gda", ",", "transactionId", ")", ":", "raise", "NotImplementedError", "(", "\"Every subclass of IPushProvider has to implement this method.\"", ")" ]
https://github.com/LinOTP/LinOTP/blob/bb3940bbaccea99550e6c063ff824f258dd6d6d7/linotp/provider/pushprovider/__init__.py#L65-L77
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
openedx/core/djangoapps/util/ratelimit.py
python
request_data_email
(group, request)
return email
Return the the email data param if it exists, otherwise return a random id.
Return the the email data param if it exists, otherwise return a random id.
[ "Return", "the", "the", "email", "data", "param", "if", "it", "exists", "otherwise", "return", "a", "random", "id", "." ]
def request_data_email(group, request) -> str: # pylint: disable=unused-argument """ Return the the email data param if it exists, otherwise return a random id. """ email = request.data.get('email') if not email: email = str(uuid4()) return email
[ "def", "request_data_email", "(", "group", ",", "request", ")", "->", "str", ":", "# pylint: disable=unused-argument", "email", "=", "request", ".", "data", ".", "get", "(", "'email'", ")", "if", "not", "email", ":", "email", "=", "str", "(", "uuid4", "(",...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/openedx/core/djangoapps/util/ratelimit.py#L33-L43
sametmax/Django--an-app-at-a-time
99eddf12ead76e6dfbeb09ce0bae61e282e22f8a
ignore_this_directory/django/utils/timezone.py
python
get_default_timezone
()
return pytz.timezone(settings.TIME_ZONE)
Return the default time zone as a tzinfo instance. This is the time zone defined by settings.TIME_ZONE.
Return the default time zone as a tzinfo instance.
[ "Return", "the", "default", "time", "zone", "as", "a", "tzinfo", "instance", "." ]
def get_default_timezone(): """ Return the default time zone as a tzinfo instance. This is the time zone defined by settings.TIME_ZONE. """ return pytz.timezone(settings.TIME_ZONE)
[ "def", "get_default_timezone", "(", ")", ":", "return", "pytz", ".", "timezone", "(", "settings", ".", "TIME_ZONE", ")" ]
https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/utils/timezone.py#L77-L83
houssamzenati/Efficient-GAN-Anomaly-Detection
15568abb57d2965ce70d4fd0dc70f3fe00c68d1b
gan/run_mnist.py
python
train_and_test
(nb_epochs, weight, method, degree, random_seed, label)
Runs the Bigan on the KDD dataset Note: Saves summaries on tensorboard. To display them, please use cmd line tensorboard --logdir=model.training_logdir() --port=number Args: nb_epochs (int): number of epochs weight (float, optional): weight for the anomaly score composition method (str, optional): 'fm' for ``Feature Matching`` or "cross-e" for ``cross entropy``, "efm" etc. anomalous_label (int): int in range 0 to 10, is the class/digit which is considered outlier
Runs the Bigan on the KDD dataset
[ "Runs", "the", "Bigan", "on", "the", "KDD", "dataset" ]
def train_and_test(nb_epochs, weight, method, degree, random_seed, label): """ Runs the Bigan on the KDD dataset Note: Saves summaries on tensorboard. To display them, please use cmd line tensorboard --logdir=model.training_logdir() --port=number Args: nb_epochs (int): number of epochs weight (float, optional): weight for the anomaly score composition method (str, optional): 'fm' for ``Feature Matching`` or "cross-e" for ``cross entropy``, "efm" etc. anomalous_label (int): int in range 0 to 10, is the class/digit which is considered outlier """ logger = logging.getLogger("GAN.train.mnist.{}.{}".format(method,label)) # Placeholders input_pl = tf.placeholder(tf.float32, shape=data.get_shape_input(), name="input") is_training_pl = tf.placeholder(tf.bool, [], name='is_training_pl') learning_rate = tf.placeholder(tf.float32, shape=(), name="lr_pl") # Data trainx, trainy = data.get_train(label, True) trainx_copy = trainx.copy() testx, testy = data.get_test(label, True) # Parameters starting_lr = network.learning_rate batch_size = network.batch_size latent_dim = network.latent_dim ema_decay = 0.999 rng = np.random.RandomState(RANDOM_SEED) nr_batches_train = int(trainx.shape[0] / batch_size) nr_batches_test = int(testx.shape[0] / batch_size) logger.info('Building training graph...') logger.warn("The GAN is training with the following parameters:") display_parameters(batch_size, starting_lr, ema_decay, weight, method, degree, label) gen = network.generator dis = network.discriminator # Sample noise from random normal distribution random_z = tf.random_normal([batch_size, latent_dim], mean=0.0, stddev=1.0, name='random_z') # Generate images with generator generator = gen(random_z, is_training=is_training_pl) # Pass real and fake images into discriminator separately real_d, inter_layer_real = dis(input_pl, is_training=is_training_pl) fake_d, inter_layer_fake = dis(generator, is_training=is_training_pl, reuse=True) with tf.name_scope('loss_functions'): # Calculate seperate losses for discriminator with real and fake images real_discriminator_loss = tf.losses.sigmoid_cross_entropy(tf.constant(1, shape=[batch_size]), real_d, scope='real_discriminator_loss') fake_discriminator_loss = tf.losses.sigmoid_cross_entropy(tf.constant(0, shape=[batch_size]), fake_d, scope='fake_discriminator_loss') # Add discriminator losses discriminator_loss = real_discriminator_loss + fake_discriminator_loss # Calculate loss for generator by flipping label on discriminator output generator_loss = tf.losses.sigmoid_cross_entropy(tf.constant(1, shape=[batch_size]), fake_d, scope='generator_loss') with tf.name_scope('optimizers'): # control op dependencies for batch norm and trainable variables dvars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='discriminator') gvars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='generator') update_ops_gen = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='generator') update_ops_dis = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='discriminator') optimizer_dis = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=0.5, name='dis_optimizer') optimizer_gen = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=0.5, name='gen_optimizer') with tf.control_dependencies(update_ops_gen): # attached op for moving average batch norm gen_op = optimizer_gen.minimize(generator_loss, var_list=gvars) with tf.control_dependencies(update_ops_dis): dis_op = optimizer_dis.minimize(discriminator_loss, var_list=dvars) dis_ema = tf.train.ExponentialMovingAverage(decay=ema_decay) maintain_averages_op_dis = dis_ema.apply(dvars) with tf.control_dependencies([dis_op]): train_dis_op = tf.group(maintain_averages_op_dis) gen_ema = tf.train.ExponentialMovingAverage(decay=ema_decay) maintain_averages_op_gen = gen_ema.apply(gvars) with tf.control_dependencies([gen_op]): train_gen_op = tf.group(maintain_averages_op_gen) with tf.name_scope('training_summary'): with tf.name_scope('dis_summary'): tf.summary.scalar('real_discriminator_loss', real_discriminator_loss, ['dis']) tf.summary.scalar('fake_discriminator_loss', fake_discriminator_loss, ['dis']) tf.summary.scalar('discriminator_loss', discriminator_loss, ['dis']) with tf.name_scope('gen_summary'): tf.summary.scalar('loss_generator', generator_loss, ['gen']) with tf.name_scope('image_summary'): tf.summary.image('reconstruct', generator, 8, ['image']) tf.summary.image('input_images', input_pl, 8, ['image']) sum_op_dis = tf.summary.merge_all('dis') sum_op_gen = tf.summary.merge_all('gen') sum_op_im = tf.summary.merge_all('image') logger.info('Building testing graph...') with tf.variable_scope("latent_variable"): z_optim = tf.get_variable(name='z_optim', shape= [batch_size, latent_dim], initializer=tf.truncated_normal_initializer()) reinit_z = z_optim.initializer # EMA generator_ema = gen(z_optim, is_training=is_training_pl, getter=get_getter(gen_ema), reuse=True) # Pass real and fake images into discriminator separately real_d_ema, inter_layer_real_ema = dis(input_pl, is_training=is_training_pl, getter=get_getter(gen_ema), reuse=True) fake_d_ema, inter_layer_fake_ema = dis(generator_ema, is_training=is_training_pl, getter=get_getter(gen_ema), reuse=True) with tf.name_scope('error_loss'): delta = input_pl - generator_ema delta_flat = tf.contrib.layers.flatten(delta) gen_score = tf.norm(delta_flat, ord=degree, axis=1, keep_dims=False, name='epsilon') with tf.variable_scope('Discriminator_loss'): if method == "cross-e": dis_score = tf.nn.sigmoid_cross_entropy_with_logits( labels=tf.ones_like(fake_d_ema), logits=fake_d_ema) elif method == "fm": fm = inter_layer_real_ema - inter_layer_fake_ema fm = tf.contrib.layers.flatten(fm) dis_score = tf.norm(fm, ord=degree, axis=1, keep_dims=False, name='d_loss') dis_score = tf.squeeze(dis_score) with tf.variable_scope('Total_loss'): loss = (1 - weight) * gen_score + weight * dis_score with tf.variable_scope("Test_learning_rate"): step = tf.Variable(0, trainable=False) boundaries = [200, 300] values = [0.01, 0.001, 0.0005] learning_rate_invert = tf.train.piecewise_constant(step, boundaries, values) reinit_lr = tf.variables_initializer( tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="Test_learning_rate")) with tf.name_scope('Test_optimizer'): optimizer = tf.train.AdamOptimizer(learning_rate_invert).minimize(loss, global_step=step, var_list=[z_optim], name='optimizer') reinit_optim = tf.variables_initializer( tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='Test_optimizer')) reinit_test_graph_op = [reinit_z, reinit_lr, reinit_optim] with tf.name_scope("Scores"): list_scores = loss logdir = create_logdir(method, weight, label, random_seed) sv = tf.train.Supervisor(logdir=logdir, save_summaries_secs=None, save_model_secs=120) logger.info('Start training...') with sv.managed_session() as sess: logger.info('Initialization done') writer = tf.summary.FileWriter(logdir, sess.graph) train_batch = 0 epoch = 0 while not sv.should_stop() and epoch < nb_epochs: lr = starting_lr begin = time.time() trainx = trainx[rng.permutation(trainx.shape[0])] # shuffling unl dataset trainx_copy = trainx_copy[rng.permutation(trainx.shape[0])] train_loss_dis, train_loss_gen = [0, 0] # training for t in range(nr_batches_train): display_progression_epoch(t, nr_batches_train) # construct randomly permuted minibatches ran_from = t * batch_size ran_to = (t + 1) * batch_size # train discriminator feed_dict = {input_pl: trainx[ran_from:ran_to], is_training_pl:True, learning_rate:lr} _, ld, sm = sess.run([train_dis_op, discriminator_loss, sum_op_dis], feed_dict=feed_dict) train_loss_dis += ld writer.add_summary(sm, train_batch) # train generator feed_dict = {input_pl: trainx_copy[ran_from:ran_to], is_training_pl:True, learning_rate:lr} _, lg, sm = sess.run([train_gen_op, generator_loss, sum_op_gen], feed_dict=feed_dict) train_loss_gen += lg writer.add_summary(sm, train_batch) if t % FREQ_PRINT == 0: # inspect reconstruction t= np.random.randint(0,4000) ran_from = t ran_to = t + batch_size sm = sess.run(sum_op_im, feed_dict={input_pl: trainx[ran_from:ran_to],is_training_pl: False}) writer.add_summary(sm, train_batch) train_batch += 1 train_loss_gen /= nr_batches_train train_loss_dis /= nr_batches_train logger.info('Epoch terminated') print("Epoch %d | time = %ds | loss gen = %.4f | loss dis = %.4f " % (epoch, time.time() - begin, train_loss_gen, train_loss_dis)) epoch += 1 logger.warn('Testing evaluation...') inds = rng.permutation(testx.shape[0]) testx = testx[inds] # shuffling unl dataset testy = testy[inds] scores = [] inference_time = [] # testing for t in range(nr_batches_test): # construct randomly permuted minibatches ran_from = t * batch_size ran_to = (t + 1) * batch_size begin_val_batch = time.time() # invert the gan feed_dict = {input_pl: testx[ran_from:ran_to], is_training_pl:False} for step in range(STEPS_NUMBER): _ = sess.run(optimizer, feed_dict=feed_dict) scores += sess.run(list_scores, feed_dict=feed_dict).tolist() inference_time.append(time.time() - begin_val_batch) sess.run(reinit_test_graph_op) logger.info('Testing : mean inference time is %.4f' % ( np.mean(inference_time))) ran_from = nr_batches_test * batch_size ran_to = (nr_batches_test + 1) * batch_size size = testx[ran_from:ran_to].shape[0] fill = np.ones([batch_size - size, 28, 28, 1]) batch = np.concatenate([testx[ran_from:ran_to], fill], axis=0) feed_dict = {input_pl: batch, is_training_pl: False} for step in range(STEPS_NUMBER): _ = sess.run(optimizer, feed_dict=feed_dict) batch_score = sess.run(list_scores, feed_dict=feed_dict).tolist() scores += batch_score[:size] prc_auc = do_prc(scores, testy, file_name=r'gan/mnist/{}/{}/{}'.format(method, weight, label), directory=r'results/gan/mnist/{}/{}/'.format(method, weight)) print("Testing | PRC AUC = {:.4f}".format(prc_auc))
[ "def", "train_and_test", "(", "nb_epochs", ",", "weight", ",", "method", ",", "degree", ",", "random_seed", ",", "label", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"GAN.train.mnist.{}.{}\"", ".", "format", "(", "method", ",", "label", ")",...
https://github.com/houssamzenati/Efficient-GAN-Anomaly-Detection/blob/15568abb57d2965ce70d4fd0dc70f3fe00c68d1b/gan/run_mnist.py#L49-L322
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/widgets.py
python
ToolLineHandles.set_animated
(self, value)
Set the animated state of the handles artist.
Set the animated state of the handles artist.
[ "Set", "the", "animated", "state", "of", "the", "handles", "artist", "." ]
def set_animated(self, value): """Set the animated state of the handles artist.""" for artist in self.artists: artist.set_animated(value)
[ "def", "set_animated", "(", "self", ",", "value", ")", ":", "for", "artist", "in", "self", ".", "artists", ":", "artist", ".", "set_animated", "(", "value", ")" ]
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/widgets.py#L2655-L2658
tensorlayer/RLzoo
8dd3ff1003d1c7a446f45119bbd6b48c048990f4
rlzoo/algorithms/ddpg/ddpg.py
python
DDPG.load_ckpt
(self, env_name)
load trained weights :return: None
load trained weights
[ "load", "trained", "weights" ]
def load_ckpt(self, env_name): """ load trained weights :return: None """ load_model(self.actor, 'model_policy_net', self.name, env_name) load_model(self.actor_target, 'model_target_policy_net', self.name, env_name) load_model(self.critic, 'model_q_net', self.name, env_name) load_model(self.critic_target, 'model_target_q_net', self.name, env_name)
[ "def", "load_ckpt", "(", "self", ",", "env_name", ")", ":", "load_model", "(", "self", ".", "actor", ",", "'model_policy_net'", ",", "self", ".", "name", ",", "env_name", ")", "load_model", "(", "self", ".", "actor_target", ",", "'model_target_policy_net'", ...
https://github.com/tensorlayer/RLzoo/blob/8dd3ff1003d1c7a446f45119bbd6b48c048990f4/rlzoo/algorithms/ddpg/ddpg.py#L169-L178
OpenMined/PySyft
f181ca02d307d57bfff9477610358df1a12e3ac9
packages/syft/src/syft/ast/static_attr.py
python
StaticAttribute.solve_set_value
(self, set_value: Any)
Local execution of setter function is performed. The `solve_set_value` method executes the setter function on the AST. Args: set_value: The value to set to. Raises: ValueError : If `path_and_name` is `None`.
Local execution of setter function is performed.
[ "Local", "execution", "of", "setter", "function", "is", "performed", "." ]
def solve_set_value(self, set_value: Any) -> None: """Local execution of setter function is performed. The `solve_set_value` method executes the setter function on the AST. Args: set_value: The value to set to. Raises: ValueError : If `path_and_name` is `None`. """ self.apply_node_changes() if self.path_and_name is None: raise ValueError("path_and_none should not be None") setattr(self.parent.object_ref, self.path_and_name.rsplit(".")[-1], set_value)
[ "def", "solve_set_value", "(", "self", ",", "set_value", ":", "Any", ")", "->", "None", ":", "self", ".", "apply_node_changes", "(", ")", "if", "self", ".", "path_and_name", "is", "None", ":", "raise", "ValueError", "(", "\"path_and_none should not be None\"", ...
https://github.com/OpenMined/PySyft/blob/f181ca02d307d57bfff9477610358df1a12e3ac9/packages/syft/src/syft/ast/static_attr.py#L105-L122
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/req/__init__.py
python
install_given_reqs
( to_install, # type: List[InstallRequirement] install_options, # type: List[str] global_options=(), # type: Sequence[str] *args, **kwargs )
return to_install
Install everything in the given list. (to be called after having downloaded and unpacked the packages)
Install everything in the given list.
[ "Install", "everything", "in", "the", "given", "list", "." ]
def install_given_reqs( to_install, # type: List[InstallRequirement] install_options, # type: List[str] global_options=(), # type: Sequence[str] *args, **kwargs ): # type: (...) -> List[InstallRequirement] """ Install everything in the given list. (to be called after having downloaded and unpacked the packages) """ if to_install: logger.info( 'Installing collected packages: %s', ', '.join([req.name for req in to_install]), ) with indent_log(): for requirement in to_install: if requirement.conflicts_with: logger.info( 'Found existing installation: %s', requirement.conflicts_with, ) with indent_log(): uninstalled_pathset = requirement.uninstall( auto_confirm=True ) try: requirement.install( install_options, global_options, *args, **kwargs ) except Exception: should_rollback = ( requirement.conflicts_with and not requirement.install_succeeded ) # if install did not succeed, rollback previous uninstall if should_rollback: uninstalled_pathset.rollback() raise else: should_commit = ( requirement.conflicts_with and requirement.install_succeeded ) if should_commit: uninstalled_pathset.commit() requirement.remove_temporary_source() return to_install
[ "def", "install_given_reqs", "(", "to_install", ",", "# type: List[InstallRequirement]", "install_options", ",", "# type: List[str]", "global_options", "=", "(", ")", ",", "# type: Sequence[str]", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (...) -> List[In...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/req/__init__.py#L22-L77
hupili/snsapi
129529b89f38cbee253a23e5ed31dae2a0ea4254
snsapi/third/twitter.py
python
User.SetListedCount
(self, count)
Set the listed count for this user. Args: count: The number of lists this user belongs to.
Set the listed count for this user.
[ "Set", "the", "listed", "count", "for", "this", "user", "." ]
def SetListedCount(self, count): '''Set the listed count for this user. Args: count: The number of lists this user belongs to. ''' self._listed_count = count
[ "def", "SetListedCount", "(", "self", ",", "count", ")", ":", "self", ".", "_listed_count", "=", "count" ]
https://github.com/hupili/snsapi/blob/129529b89f38cbee253a23e5ed31dae2a0ea4254/snsapi/third/twitter.py#L1153-L1160
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/lxml/html/diff.py
python
start_tag
(el)
return '<%s%s>' % ( el.tag, ''.join([' %s="%s"' % (name, html_escape(value, True)) for name, value in el.attrib.items()]))
The text representation of the start tag for a tag.
The text representation of the start tag for a tag.
[ "The", "text", "representation", "of", "the", "start", "tag", "for", "a", "tag", "." ]
def start_tag(el): """ The text representation of the start tag for a tag. """ return '<%s%s>' % ( el.tag, ''.join([' %s="%s"' % (name, html_escape(value, True)) for name, value in el.attrib.items()]))
[ "def", "start_tag", "(", "el", ")", ":", "return", "'<%s%s>'", "%", "(", "el", ".", "tag", ",", "''", ".", "join", "(", "[", "' %s=\"%s\"'", "%", "(", "name", ",", "html_escape", "(", "value", ",", "True", ")", ")", "for", "name", ",", "value", "...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/lxml/html/diff.py#L725-L731
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/transports/plugins/local.py
python
LocalTransport._os_path_split_asunder
(path)
return parts
Used by makedirs, Takes path (a str) and returns a list deconcatenating the path.
Used by makedirs, Takes path (a str) and returns a list deconcatenating the path.
[ "Used", "by", "makedirs", "Takes", "path", "(", "a", "str", ")", "and", "returns", "a", "list", "deconcatenating", "the", "path", "." ]
def _os_path_split_asunder(path): """Used by makedirs, Takes path (a str) and returns a list deconcatenating the path.""" parts = [] while True: newpath, tail = os.path.split(path) if newpath == path: assert not tail if path: parts.append(path) break parts.append(tail) path = newpath parts.reverse() return parts
[ "def", "_os_path_split_asunder", "(", "path", ")", ":", "parts", "=", "[", "]", "while", "True", ":", "newpath", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "newpath", "==", "path", ":", "assert", "not", "tail", "if", ...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/transports/plugins/local.py#L137-L150
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/Phylo/PhyloXMLIO.py
python
_get_children_as
(parent, tag, construct)
return [construct(child) for child in parent.findall(_ns(tag))]
Find child nodes by tag; pass each through a constructor (PRIVATE). Returns an empty list if no matching child is found.
Find child nodes by tag; pass each through a constructor (PRIVATE).
[ "Find", "child", "nodes", "by", "tag", ";", "pass", "each", "through", "a", "constructor", "(", "PRIVATE", ")", "." ]
def _get_children_as(parent, tag, construct): """Find child nodes by tag; pass each through a constructor (PRIVATE). Returns an empty list if no matching child is found. """ return [construct(child) for child in parent.findall(_ns(tag))]
[ "def", "_get_children_as", "(", "parent", ",", "tag", ",", "construct", ")", ":", "return", "[", "construct", "(", "child", ")", "for", "child", "in", "parent", ".", "findall", "(", "_ns", "(", "tag", ")", ")", "]" ]
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/Phylo/PhyloXMLIO.py#L174-L179
ryderling/DEEPSEC
2c67afac0ae966767b6712a51db85f04f4f5c565
Attacks/AttackMethods/DEEPFOOL.py
python
DeepFoolAttack.perturbation
(self, xs, device)
return np.array(adv_samples)
:param xs: batch of samples :param device: :return: batch of adversarial samples
[]
def perturbation(self, xs, device): """ :param xs: batch of samples :param device: :return: batch of adversarial samples """ print('\nThe DeepFool attack perturbs the samples one by one ......\n') adv_samples = [] for i in range(len(xs)): adv_image, _, _ = self.perturbation_single(sample=xs[i: i + 1], device=device) adv_samples.extend(adv_image) return np.array(adv_samples)
[ "def", "perturbation", "(", "self", ",", "xs", ",", "device", ")", ":", "print", "(", "'\\nThe DeepFool attack perturbs the samples one by one ......\\n'", ")", "adv_samples", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "xs", ")", ")", ":", "a...
https://github.com/ryderling/DEEPSEC/blob/2c67afac0ae966767b6712a51db85f04f4f5c565/Attacks/AttackMethods/DEEPFOOL.py#L94-L106
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/index.py
python
HTMLPage.links
(self)
Yields all links in the page
Yields all links in the page
[ "Yields", "all", "links", "in", "the", "page" ]
def links(self): """Yields all links in the page""" for anchor in self.parsed.findall(".//a"): if anchor.get("href"): href = anchor.get("href") url = self.clean_link( urllib_parse.urljoin(self.base_url, href) ) pyrequire = anchor.get('data-requires-python') pyrequire = unescape(pyrequire) if pyrequire else None yield Link(url, self, requires_python=pyrequire)
[ "def", "links", "(", "self", ")", ":", "for", "anchor", "in", "self", ".", "parsed", ".", "findall", "(", "\".//a\"", ")", ":", "if", "anchor", ".", "get", "(", "\"href\"", ")", ":", "href", "=", "anchor", ".", "get", "(", "\"href\"", ")", "url", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/index.py#L858-L868
google/tf-quant-finance
8fd723689ebf27ff4bb2bd2acb5f6091c5e07309
tf_quant_finance/datetime/unbounded_holiday_calendar.py
python
UnboundedHolidayCalendar._apply_roll_biz_space
(self, date_tensor, biz_days, is_bizday, roll_convention)
Applies roll in business day space.
Applies roll in business day space.
[ "Applies", "roll", "in", "business", "day", "space", "." ]
def _apply_roll_biz_space(self, date_tensor, biz_days, is_bizday, roll_convention): """Applies roll in business day space.""" if roll_convention == constants.BusinessDayConvention.NONE: # If no business convention is specified, return the current business # day. return biz_days if roll_convention == constants.BusinessDayConvention.FOLLOWING: return tf.where(is_bizday, biz_days, biz_days + 1) if roll_convention == constants.BusinessDayConvention.PRECEDING: return biz_days if roll_convention == constants.BusinessDayConvention.MODIFIED_FOLLOWING: maybe_prev_biz_day = biz_days maybe_next_biz_day = tf.where(is_bizday, biz_days, biz_days + 1) maybe_next_biz_ordinal = self._from_biz_space(maybe_next_biz_day) take_previous = tf.not_equal( _get_month(maybe_next_biz_ordinal), date_tensor.month()) return tf.where(take_previous, maybe_prev_biz_day, maybe_next_biz_day) if roll_convention == constants.BusinessDayConvention.MODIFIED_PRECEDING: maybe_prev_biz_day = biz_days maybe_next_biz_day = tf.where(is_bizday, biz_days, biz_days + 1) maybe_prev_biz_ordinal = self._from_biz_space(maybe_prev_biz_day) take_next = tf.not_equal( _get_month(maybe_prev_biz_ordinal), date_tensor.month()) return tf.where(take_next, maybe_next_biz_day, maybe_prev_biz_day) raise ValueError('Unsupported roll convention: {}'.format(roll_convention))
[ "def", "_apply_roll_biz_space", "(", "self", ",", "date_tensor", ",", "biz_days", ",", "is_bizday", ",", "roll_convention", ")", ":", "if", "roll_convention", "==", "constants", ".", "BusinessDayConvention", ".", "NONE", ":", "# If no business convention is specified, r...
https://github.com/google/tf-quant-finance/blob/8fd723689ebf27ff4bb2bd2acb5f6091c5e07309/tf_quant_finance/datetime/unbounded_holiday_calendar.py#L80-L110
visionml/pytracking
3e6a8980db7a2275252abcc398ed0c2494f0ceab
ltr/data/processing_utils.py
python
iou
(reference, proposals)
return intersection / union
Compute the IoU between a reference box with multiple proposal boxes. args: reference - Tensor of shape (1, 4). proposals - Tensor of shape (num_proposals, 4) returns: torch.Tensor - Tensor of shape (num_proposals,) containing IoU of reference box with each proposal box.
Compute the IoU between a reference box with multiple proposal boxes.
[ "Compute", "the", "IoU", "between", "a", "reference", "box", "with", "multiple", "proposal", "boxes", "." ]
def iou(reference, proposals): """Compute the IoU between a reference box with multiple proposal boxes. args: reference - Tensor of shape (1, 4). proposals - Tensor of shape (num_proposals, 4) returns: torch.Tensor - Tensor of shape (num_proposals,) containing IoU of reference box with each proposal box. """ # Intersection box tl = torch.max(reference[:, :2], proposals[:, :2]) br = torch.min(reference[:, :2] + reference[:, 2:], proposals[:, :2] + proposals[:, 2:]) sz = (br - tl).clamp(0) # Area intersection = sz.prod(dim=1) union = reference[:, 2:].prod(dim=1) + proposals[:, 2:].prod(dim=1) - intersection return intersection / union
[ "def", "iou", "(", "reference", ",", "proposals", ")", ":", "# Intersection box", "tl", "=", "torch", ".", "max", "(", "reference", "[", ":", ",", ":", "2", "]", ",", "proposals", "[", ":", ",", ":", "2", "]", ")", "br", "=", "torch", ".", "min",...
https://github.com/visionml/pytracking/blob/3e6a8980db7a2275252abcc398ed0c2494f0ceab/ltr/data/processing_utils.py#L410-L430
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/src/class/oc_user.py
python
OCUser.user
(self, data)
setter function for user
setter function for user
[ "setter", "function", "for", "user" ]
def user(self, data): ''' setter function for user ''' self._user = data
[ "def", "user", "(", "self", ",", "data", ")", ":", "self", ".", "_user", "=", "data" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/src/class/oc_user.py#L28-L30
deepfakes/faceswap
09c7d8aca3c608d1afad941ea78e9fd9b64d9219
lib/gui/control_helper.py
python
ControlBuilder.slider_control
(self)
return ctl
A slider control with corresponding Entry box
A slider control with corresponding Entry box
[ "A", "slider", "control", "with", "corresponding", "Entry", "box" ]
def slider_control(self): """ A slider control with corresponding Entry box """ logger.debug("Add slider control to Options Frame: (widget: '%s', dtype: %s, " "rounding: %s, min_max: %s)", self.option.name, self.option.dtype, self.option.rounding, self.option.min_max) validate = self.slider_check_int if self.option.dtype == int else self.slider_check_float vcmd = (self.frame.register(validate)) tbox = tk.Entry(self.frame, width=8, textvariable=self.option.tk_var, justify=tk.RIGHT, font=get_config().default_font, validate="all", validatecommand=(vcmd, "%P"), bg=self._theme["input_color"], fg=self._theme["input_font"], highlightbackground=self._theme["input_font"], highlightthickness=1, bd=0) tbox.pack(padx=(0, 5), side=tk.RIGHT) cmd = partial(set_slider_rounding, var=self.option.tk_var, d_type=self.option.dtype, round_to=self.option.rounding, min_max=self.option.min_max) ctl = ttk.Scale(self.frame, variable=self.option.tk_var, command=cmd, style=f"{self._style}Horizontal.TScale") _add_command(ctl.cget("command"), cmd) rc_menu = _get_contextmenu(tbox) rc_menu.cm_bind() ctl["from_"] = self.option.min_max[0] ctl["to"] = self.option.min_max[1] logger.debug("Added slider control to Options Frame: %s", self.option.name) return ctl
[ "def", "slider_control", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Add slider control to Options Frame: (widget: '%s', dtype: %s, \"", "\"rounding: %s, min_max: %s)\"", ",", "self", ".", "option", ".", "name", ",", "self", ".", "option", ".", "dtype", ","...
https://github.com/deepfakes/faceswap/blob/09c7d8aca3c608d1afad941ea78e9fd9b64d9219/lib/gui/control_helper.py#L1055-L1090
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/keyframeeditor.py
python
KeyFrameEditor._hamburger_pressed
(self, widget, event)
[]
def _hamburger_pressed(self, widget, event): menu = buttons_hamburger_menu guiutils.remove_children(menu) frame, value, kf_type = self.clip_editor.keyframes[self.clip_editor.active_kf_index] active_type_menu_item = Gtk.MenuItem(_("Active Keyframe Type")) type_menu = Gtk.Menu() active_type_menu_item.set_submenu(type_menu) self._create_keyframe_type_submenu(kf_type, type_menu, self._menu_item_activated) active_type_menu_item.show_all() menu.add(active_type_menu_item) item = _get_menu_item("this gets overwritten..twice", self._menu_item_activated, "copy_kf") action = gui.editor_window.ui.get_action_groups()[0].get_action("Copy") item.set_related_action(action) item.set_label(_("Copy Keyframe Value")) menu.add(item) item = _get_menu_item("this gets overwritten..twice", self._menu_item_activated, "paste_kf") action = gui.editor_window.ui.get_action_groups()[0].get_action("Paste") item.set_related_action(action) item.set_label(_("Paste Keyframe Value")) menu.add(item) before_kfs = len(self.clip_editor.get_out_of_range_before_kfs()) after_kfs = len(self.clip_editor.get_out_of_range_after_kfs()) if before_kfs > 0 or after_kfs > 0: _add_separator(menu) if len(self.clip_editor.keyframes) > 1: menu.add(_get_menu_item(_("Set Keyframe at Frame 0 to value of next Keyframe"), self.clip_editor._oor_menu_item_activated, "zero_next" )) if before_kfs > 1: menu.add(_get_menu_item(_("Delete all but first Keyframe before Clip Range"), self.clip_editor._oor_menu_item_activated, "delete_all_before" )) if after_kfs > 0: menu.add(_get_menu_item(_("Delete all Keyframes after Clip Range"), self.clip_editor._oor_menu_item_activated, "delete_all_after" )) if before_kfs > 0 or after_kfs > 0: _add_separator(menu) menu.popup(None, None, None, None, event.button, event.time)
[ "def", "_hamburger_pressed", "(", "self", ",", "widget", ",", "event", ")", ":", "menu", "=", "buttons_hamburger_menu", "guiutils", ".", "remove_children", "(", "menu", ")", "frame", ",", "value", ",", "kf_type", "=", "self", ".", "clip_editor", ".", "keyfra...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/keyframeeditor.py#L1210-L1251
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/reportlab/build/lib.linux-i686-2.7/reportlab/pdfbase/cidfonts.py
python
CIDEncoding.parseCMAPFile
(self, name)
This is a tricky one as CMAP files are Postscript ones. Some refer to others with a 'usecmap' command
This is a tricky one as CMAP files are Postscript ones. Some refer to others with a 'usecmap' command
[ "This", "is", "a", "tricky", "one", "as", "CMAP", "files", "are", "Postscript", "ones", ".", "Some", "refer", "to", "others", "with", "a", "usecmap", "command" ]
def parseCMAPFile(self, name): """This is a tricky one as CMAP files are Postscript ones. Some refer to others with a 'usecmap' command""" #started = time.clock() cmapfile = findCMapFile(name) # this will CRAWL with the unicode encodings... rawdata = open(cmapfile, 'r').read() self._mapFileHash = self._hash(rawdata) #if it contains the token 'usecmap', parse the other #cmap file first.... usecmap_pos = rawdata.find('usecmap') if usecmap_pos > -1: #they tell us to look in another file #for the code space ranges. The one # to use will be the previous word. chunk = rawdata[0:usecmap_pos] words = chunk.split() otherCMAPName = words[-1] #print 'referred to another CMAP %s' % otherCMAPName self.parseCMAPFile(otherCMAPName) # now continue parsing this, as it may # override some settings words = rawdata.split() while words != []: if words[0] == 'begincodespacerange': words = words[1:] while words[0] != 'endcodespacerange': strStart, strEnd, words = words[0], words[1], words[2:] start = int(strStart[1:-1], 16) end = int(strEnd[1:-1], 16) self._codeSpaceRanges.append((start, end),) elif words[0] == 'beginnotdefrange': words = words[1:] while words[0] != 'endnotdefrange': strStart, strEnd, strValue = words[0:3] start = int(strStart[1:-1], 16) end = int(strEnd[1:-1], 16) value = int(strValue) self._notDefRanges.append((start, end, value),) words = words[3:] elif words[0] == 'begincidrange': words = words[1:] while words[0] != 'endcidrange': strStart, strEnd, strValue = words[0:3] start = int(strStart[1:-1], 16) end = int(strEnd[1:-1], 16) value = int(strValue) # this means that 'start' corresponds to 'value', # start+1 corresponds to value+1 and so on up # to end offset = 0 while start + offset <= end: self._cmap[start + offset] = value + offset offset = offset + 1 words = words[3:] else: words = words[1:]
[ "def", "parseCMAPFile", "(", "self", ",", "name", ")", ":", "#started = time.clock()", "cmapfile", "=", "findCMapFile", "(", "name", ")", "# this will CRAWL with the unicode encodings...", "rawdata", "=", "open", "(", "cmapfile", ",", "'r'", ")", ".", "read", "(",...
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/reportlab/build/lib.linux-i686-2.7/reportlab/pdfbase/cidfonts.py#L96-L157
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/names/_rfc1982.py
python
SerialNumber.__lt__
(self, other: object)
return ( self._number < other._number and (other._number - self._number) < self._halfRing ) or ( self._number > other._number and (self._number - other._number) > self._halfRing )
Allow I{less than} comparison with another L{SerialNumber} instance.
Allow I{less than} comparison with another L{SerialNumber} instance.
[ "Allow", "I", "{", "less", "than", "}", "comparison", "with", "another", "L", "{", "SerialNumber", "}", "instance", "." ]
def __lt__(self, other: object) -> bool: """ Allow I{less than} comparison with another L{SerialNumber} instance. """ try: other = self._convertOther(other) except TypeError: return NotImplemented return ( self._number < other._number and (other._number - self._number) < self._halfRing ) or ( self._number > other._number and (self._number - other._number) > self._halfRing )
[ "def", "__lt__", "(", "self", ",", "other", ":", "object", ")", "->", "bool", ":", "try", ":", "other", "=", "self", ".", "_convertOther", "(", "other", ")", "except", "TypeError", ":", "return", "NotImplemented", "return", "(", "self", ".", "_number", ...
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/names/_rfc1982.py#L121-L135
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3/s3navigation.py
python
S3NavigationItem.get_all
(self, **flags)
return items
Get all components with these flags Args: flags: dictionary of flags
Get all components with these flags
[ "Get", "all", "components", "with", "these", "flags" ]
def get_all(self, **flags): """ Get all components with these flags Args: flags: dictionary of flags """ items = [] for item in self.components: if not flags or \ all([getattr(item, f) == flags[f] for f in flags]): items.append(item) return items
[ "def", "get_all", "(", "self", ",", "*", "*", "flags", ")", ":", "items", "=", "[", "]", "for", "item", "in", "self", ".", "components", ":", "if", "not", "flags", "or", "all", "(", "[", "getattr", "(", "item", ",", "f", ")", "==", "flags", "["...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3navigation.py#L1180-L1193
IntelAI/nauta
bbedb114a755cf1f43b834a58fc15fb6e3a4b291
applications/cli/util/github.py
python
Github.__init__
(self, repository_name, token)
[]
def __init__(self, repository_name, token): self.token = token self.repository_name = repository_name
[ "def", "__init__", "(", "self", ",", "repository_name", ",", "token", ")", ":", "self", ".", "token", "=", "token", "self", ".", "repository_name", "=", "repository_name" ]
https://github.com/IntelAI/nauta/blob/bbedb114a755cf1f43b834a58fc15fb6e3a4b291/applications/cli/util/github.py#L48-L50
jansel/opentuner
070c5cef6d933eb760a2f9cd5cd08c95f27aee75
opentuner/search/plugin.py
python
SearchPlugin.set_driver
(self, driver)
called before all other methods
called before all other methods
[ "called", "before", "all", "other", "methods" ]
def set_driver(self, driver): """called before all other methods""" self.driver = driver
[ "def", "set_driver", "(", "self", ",", "driver", ")", ":", "self", ".", "driver", "=", "driver" ]
https://github.com/jansel/opentuner/blob/070c5cef6d933eb760a2f9cd5cd08c95f27aee75/opentuner/search/plugin.py#L34-L36
Yonv1943/Python
ecce2153892093d7a13686e4cbfd6b323cb59de8
ElegantRL/Beta/net.py
python
SharedSPG.get_a_logprob
(self, state)
return a_noise_tanh, logprob
add noise to action, stochastic policy
add noise to action, stochastic policy
[ "add", "noise", "to", "action", "stochastic", "policy" ]
def get_a_logprob(self, state): # actor s_ = self.enc_s(state) a_ = self.net(s_) """add noise to action, stochastic policy""" a_avg = self.dec_a(a_) # NOTICE! it is action without .tanh() a_std_log = self.dec_d(a_).clamp(-20, 2) a_std = a_std_log.exp() noise = torch.randn_like(a_avg, requires_grad=True) a_noise = a_avg + a_std * noise a_noise_tanh = a_noise.tanh() fix_term = (-a_noise_tanh.pow(2) + 1.00001).log() logprob = (noise.pow(2) / 2 + a_std_log + fix_term).sum(1) + self.log_sqrt_2pi_sum return a_noise_tanh, logprob
[ "def", "get_a_logprob", "(", "self", ",", "state", ")", ":", "# actor", "s_", "=", "self", ".", "enc_s", "(", "state", ")", "a_", "=", "self", ".", "net", "(", "s_", ")", "a_avg", "=", "self", ".", "dec_a", "(", "a_", ")", "# NOTICE! it is action wit...
https://github.com/Yonv1943/Python/blob/ecce2153892093d7a13686e4cbfd6b323cb59de8/ElegantRL/Beta/net.py#L509-L524
dragondjf/QMarkdowner
fc79c85ca2949fa9ce3b317606ad7bbcd1299960
markdown/__init__.py
python
Markdown.registerExtension
(self, extension)
return self
This gets called by the extension
This gets called by the extension
[ "This", "gets", "called", "by", "the", "extension" ]
def registerExtension(self, extension): """ This gets called by the extension """ self.registeredExtensions.append(extension) return self
[ "def", "registerExtension", "(", "self", ",", "extension", ")", ":", "self", ".", "registeredExtensions", ".", "append", "(", "extension", ")", "return", "self" ]
https://github.com/dragondjf/QMarkdowner/blob/fc79c85ca2949fa9ce3b317606ad7bbcd1299960/markdown/__init__.py#L299-L302
Azure/azure-cli
6c1b085a0910c6c2139006fcbd8ade44006eb6dd
src/azure-cli/azure/cli/command_modules/batchai/custom.py
python
_get_effective_credentials
(cli_ctx, existing_credentials, account_name)
return models.AzureStorageCredentialsInfo( account_key=_get_storage_account_key(cli_ctx, account_name, account_key=None))
Returns AzureStorageCredentialInfo for the account :param models.AzureStorageCredentialsInfo existing_credentials: known credentials :param str account_name: storage account name :return models.AzureStorageCredentialsInfo: credentials to be used
Returns AzureStorageCredentialInfo for the account
[ "Returns", "AzureStorageCredentialInfo", "for", "the", "account" ]
def _get_effective_credentials(cli_ctx, existing_credentials, account_name): """Returns AzureStorageCredentialInfo for the account :param models.AzureStorageCredentialsInfo existing_credentials: known credentials :param str account_name: storage account name :return models.AzureStorageCredentialsInfo: credentials to be used """ if existing_credentials and (existing_credentials.account_key or existing_credentials.account_key_secret_reference): return existing_credentials return models.AzureStorageCredentialsInfo( account_key=_get_storage_account_key(cli_ctx, account_name, account_key=None))
[ "def", "_get_effective_credentials", "(", "cli_ctx", ",", "existing_credentials", ",", "account_name", ")", ":", "if", "existing_credentials", "and", "(", "existing_credentials", ".", "account_key", "or", "existing_credentials", ".", "account_key_secret_reference", ")", "...
https://github.com/Azure/azure-cli/blob/6c1b085a0910c6c2139006fcbd8ade44006eb6dd/src/azure-cli/azure/cli/command_modules/batchai/custom.py#L196-L206
TheAlgorithms/Python
9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c
matrix/sherman_morrison.py
python
Matrix.validateIndices
(self, loc: tuple)
<method Matrix.validateIndices> Check if given indices are valid to pick element from matrix. Example: >>> a = Matrix(2, 6, 0) >>> a.validateIndices((2, 7)) False >>> a.validateIndices((0, 0)) True
<method Matrix.validateIndices> Check if given indices are valid to pick element from matrix.
[ "<method", "Matrix", ".", "validateIndices", ">", "Check", "if", "given", "indices", "are", "valid", "to", "pick", "element", "from", "matrix", "." ]
def validateIndices(self, loc: tuple): """ <method Matrix.validateIndices> Check if given indices are valid to pick element from matrix. Example: >>> a = Matrix(2, 6, 0) >>> a.validateIndices((2, 7)) False >>> a.validateIndices((0, 0)) True """ if not (isinstance(loc, (list, tuple)) and len(loc) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True
[ "def", "validateIndices", "(", "self", ",", "loc", ":", "tuple", ")", ":", "if", "not", "(", "isinstance", "(", "loc", ",", "(", "list", ",", "tuple", ")", ")", "and", "len", "(", "loc", ")", "==", "2", ")", ":", "return", "False", "elif", "not",...
https://github.com/TheAlgorithms/Python/blob/9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c/matrix/sherman_morrison.py#L53-L70
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/beets/importer.py
python
progress_element
(toppath, path)
return i != len(imported) and imported[i] == path
Return whether `path` has been imported in `toppath`.
Return whether `path` has been imported in `toppath`.
[ "Return", "whether", "path", "has", "been", "imported", "in", "toppath", "." ]
def progress_element(toppath, path): """Return whether `path` has been imported in `toppath`. """ state = progress_read() if toppath not in state: return False imported = state[toppath] i = bisect_left(imported, path) return i != len(imported) and imported[i] == path
[ "def", "progress_element", "(", "toppath", ",", "path", ")", ":", "state", "=", "progress_read", "(", ")", "if", "toppath", "not", "in", "state", ":", "return", "False", "imported", "=", "state", "[", "toppath", "]", "i", "=", "bisect_left", "(", "import...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/beets/importer.py#L124-L132
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/feed_mapping_service/client.py
python
FeedMappingServiceClient.transport
(self)
return self._transport
Return the transport used by the client instance. Returns: FeedMappingServiceTransport: The transport used by the client instance.
Return the transport used by the client instance.
[ "Return", "the", "transport", "used", "by", "the", "client", "instance", "." ]
def transport(self) -> FeedMappingServiceTransport: """Return the transport used by the client instance. Returns: FeedMappingServiceTransport: The transport used by the client instance. """ return self._transport
[ "def", "transport", "(", "self", ")", "->", "FeedMappingServiceTransport", ":", "return", "self", ".", "_transport" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/feed_mapping_service/client.py#L154-L160
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/qbittorrent/sensor.py
python
QBittorrentSensor.__init__
( self, description: SensorEntityDescription, qbittorrent_client, client_name, exception, )
Initialize the qBittorrent sensor.
Initialize the qBittorrent sensor.
[ "Initialize", "the", "qBittorrent", "sensor", "." ]
def __init__( self, description: SensorEntityDescription, qbittorrent_client, client_name, exception, ): """Initialize the qBittorrent sensor.""" self.entity_description = description self.client = qbittorrent_client self._exception = exception self._attr_name = f"{client_name} {description.name}" self._attr_available = False
[ "def", "__init__", "(", "self", ",", "description", ":", "SensorEntityDescription", ",", "qbittorrent_client", ",", "client_name", ",", "exception", ",", ")", ":", "self", ".", "entity_description", "=", "description", "self", ".", "client", "=", "qbittorrent_clie...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/qbittorrent/sensor.py#L101-L114
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/setuptools/msvc.py
python
msvc9_query_vcvarsall
(ver, arch='x86', *args, **kwargs)
Patched "distutils.msvc9compiler.query_vcvarsall" for support extra compilers. Set environment without use of "vcvarsall.bat". Known supported compilers ------------------------- Microsoft Visual C++ 9.0: Microsoft Visual C++ Compiler for Python 2.7 (x86, amd64) Microsoft Windows SDK 6.1 (x86, x64, ia64) Microsoft Windows SDK 7.0 (x86, x64, ia64) Microsoft Visual C++ 10.0: Microsoft Windows SDK 7.1 (x86, x64, ia64) Parameters ---------- ver: float Required Microsoft Visual C++ version. arch: str Target architecture. Return ------ environment: dict
Patched "distutils.msvc9compiler.query_vcvarsall" for support extra compilers.
[ "Patched", "distutils", ".", "msvc9compiler", ".", "query_vcvarsall", "for", "support", "extra", "compilers", "." ]
def msvc9_query_vcvarsall(ver, arch='x86', *args, **kwargs): """ Patched "distutils.msvc9compiler.query_vcvarsall" for support extra compilers. Set environment without use of "vcvarsall.bat". Known supported compilers ------------------------- Microsoft Visual C++ 9.0: Microsoft Visual C++ Compiler for Python 2.7 (x86, amd64) Microsoft Windows SDK 6.1 (x86, x64, ia64) Microsoft Windows SDK 7.0 (x86, x64, ia64) Microsoft Visual C++ 10.0: Microsoft Windows SDK 7.1 (x86, x64, ia64) Parameters ---------- ver: float Required Microsoft Visual C++ version. arch: str Target architecture. Return ------ environment: dict """ # Try to get environement from vcvarsall.bat (Classical way) try: orig = get_unpatched(msvc9_query_vcvarsall) return orig(ver, arch, *args, **kwargs) except distutils.errors.DistutilsPlatformError: # Pass error if Vcvarsall.bat is missing pass except ValueError: # Pass error if environment not set after executing vcvarsall.bat pass # If error, try to set environment directly try: return EnvironmentInfo(arch, ver).return_env() except distutils.errors.DistutilsPlatformError as exc: _augment_exception(exc, ver, arch) raise
[ "def", "msvc9_query_vcvarsall", "(", "ver", ",", "arch", "=", "'x86'", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Try to get environement from vcvarsall.bat (Classical way)", "try", ":", "orig", "=", "get_unpatched", "(", "msvc9_query_vcvarsall", ")", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/setuptools/msvc.py#L106-L150
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
TensorFlow/LanguageModeling/BERT/utils/create_glue_data.py
python
convert_examples_to_features
(examples, label_list, max_seq_length, tokenizer)
return features
Convert a set of `InputExample`s to a list of `InputFeatures`.
Convert a set of `InputExample`s to a list of `InputFeatures`.
[ "Convert", "a", "set", "of", "InputExample", "s", "to", "a", "list", "of", "InputFeatures", "." ]
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """Convert a set of `InputExample`s to a list of `InputFeatures`.""" features = [] for (ex_index, example) in enumerate(examples): if ex_index % 10000 == 0: tf.compat.v1.logging.info("Writing example %d of %d" % (ex_index, len(examples))) feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer, FLAGS.verbose_logging) features.append(feature) return features
[ "def", "convert_examples_to_features", "(", "examples", ",", "label_list", ",", "max_seq_length", ",", "tokenizer", ")", ":", "features", "=", "[", "]", "for", "(", "ex_index", ",", "example", ")", "in", "enumerate", "(", "examples", ")", ":", "if", "ex_inde...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow/LanguageModeling/BERT/utils/create_glue_data.py#L435-L448
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/logging/__init__.py
python
Handler.flush
(self)
Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses.
Ensure all logging output has been flushed.
[ "Ensure", "all", "logging", "output", "has", "been", "flushed", "." ]
def flush(self): """ Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses. """ pass
[ "def", "flush", "(", "self", ")", ":", "pass" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/logging/__init__.py#L755-L762
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v2beta2_horizontal_pod_autoscaler_spec.py
python
V2beta2HorizontalPodAutoscalerSpec.__init__
(self, behavior=None, max_replicas=None, metrics=None, min_replicas=None, scale_target_ref=None, local_vars_configuration=None)
V2beta2HorizontalPodAutoscalerSpec - a model defined in OpenAPI
V2beta2HorizontalPodAutoscalerSpec - a model defined in OpenAPI
[ "V2beta2HorizontalPodAutoscalerSpec", "-", "a", "model", "defined", "in", "OpenAPI" ]
def __init__(self, behavior=None, max_replicas=None, metrics=None, min_replicas=None, scale_target_ref=None, local_vars_configuration=None): # noqa: E501 """V2beta2HorizontalPodAutoscalerSpec - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._behavior = None self._max_replicas = None self._metrics = None self._min_replicas = None self._scale_target_ref = None self.discriminator = None if behavior is not None: self.behavior = behavior self.max_replicas = max_replicas if metrics is not None: self.metrics = metrics if min_replicas is not None: self.min_replicas = min_replicas self.scale_target_ref = scale_target_ref
[ "def", "__init__", "(", "self", ",", "behavior", "=", "None", ",", "max_replicas", "=", "None", ",", "metrics", "=", "None", ",", "min_replicas", "=", "None", ",", "scale_target_ref", "=", "None", ",", "local_vars_configuration", "=", "None", ")", ":", "# ...
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v2beta2_horizontal_pod_autoscaler_spec.py#L51-L71
IntelPython/sdc
1ebf55c00ef38dfbd401a70b3945e352a5a38b87
sdc/str_arr_ext.py
python
copy_str_arr_slice
(typingctx, str_arr_typ, out_str_arr_typ, ind_t=None)
return types.void(string_array_type, string_array_type, ind_t), codegen
[]
def copy_str_arr_slice(typingctx, str_arr_typ, out_str_arr_typ, ind_t=None): def codegen(context, builder, sig, args): out_str_arr, in_str_arr, ind = args in_string_array = context.make_helper(builder, string_array_type, in_str_arr) out_string_array = context.make_helper(builder, string_array_type, out_str_arr) in_offsets = builder.bitcast(in_string_array.offsets, lir.IntType(32).as_pointer()) out_offsets = builder.bitcast(out_string_array.offsets, lir.IntType(32).as_pointer()) ind_p1 = builder.add(ind, context.get_constant(types.intp, 1)) cgutils.memcpy(builder, out_offsets, in_offsets, ind_p1) cgutils.memcpy( builder, out_string_array.data, in_string_array.data, builder.load( builder.gep( in_offsets, [ind]))) # n_bytes = (num_strings+sizeof(uint8_t)-1)/sizeof(uint8_t) ind_p7 = builder.add(ind, lir.Constant(lir.IntType(64), 7)) n_bytes = builder.lshr(ind_p7, lir.Constant(lir.IntType(64), 3)) # assuming rest of last byte is set to all ones (e.g. from prealloc) cgutils.memcpy(builder, out_string_array.null_bitmap, in_string_array.null_bitmap, n_bytes) return context.get_dummy_value() return types.void(string_array_type, string_array_type, ind_t), codegen
[ "def", "copy_str_arr_slice", "(", "typingctx", ",", "str_arr_typ", ",", "out_str_arr_typ", ",", "ind_t", "=", "None", ")", ":", "def", "codegen", "(", "context", ",", "builder", ",", "sig", ",", "args", ")", ":", "out_str_arr", ",", "in_str_arr", ",", "ind...
https://github.com/IntelPython/sdc/blob/1ebf55c00ef38dfbd401a70b3945e352a5a38b87/sdc/str_arr_ext.py#L260-L288
nosmokingbandit/Watcher3
0217e75158b563bdefc8e01c3be7620008cf3977
lib/hachoir/regex/regex.py
python
Regex.__or__
(self, other)
return RegexOr((self, other))
Public method of OR operator: a|b. It call or_() internal method. If or_() returns None: RegexOr object is used (and otherwise, use or_() result).
Public method of OR operator: a|b. It call or_() internal method. If or_() returns None: RegexOr object is used (and otherwise, use or_() result).
[ "Public", "method", "of", "OR", "operator", ":", "a|b", ".", "It", "call", "or_", "()", "internal", "method", ".", "If", "or_", "()", "returns", "None", ":", "RegexOr", "object", "is", "used", "(", "and", "otherwise", "use", "or_", "()", "result", ")",...
def __or__(self, other): """ Public method of OR operator: a|b. It call or_() internal method. If or_() returns None: RegexOr object is used (and otherwise, use or_() result). """ # Try to optimize (a|b) new_regex = self.or_(other) if new_regex: return new_regex # Else use (a|b) return RegexOr((self, other))
[ "def", "__or__", "(", "self", ",", "other", ")", ":", "# Try to optimize (a|b)", "new_regex", "=", "self", ".", "or_", "(", "other", ")", "if", "new_regex", ":", "return", "new_regex", "# Else use (a|b)", "return", "RegexOr", "(", "(", "self", ",", "other", ...
https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/lib/hachoir/regex/regex.py#L233-L245
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/internals/managers.py
python
SingleBlockManager.asobject
(self)
return self._block.get_values(dtype=object)
return a object dtype array. datetime/timedelta like values are boxed to Timestamp/Timedelta instances.
return a object dtype array. datetime/timedelta like values are boxed to Timestamp/Timedelta instances.
[ "return", "a", "object", "dtype", "array", ".", "datetime", "/", "timedelta", "like", "values", "are", "boxed", "to", "Timestamp", "/", "Timedelta", "instances", "." ]
def asobject(self): """ return a object dtype array. datetime/timedelta like values are boxed to Timestamp/Timedelta instances. """ return self._block.get_values(dtype=object)
[ "def", "asobject", "(", "self", ")", ":", "return", "self", ".", "_block", ".", "get_values", "(", "dtype", "=", "object", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/internals/managers.py#L1561-L1566
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/urllib3/contrib/_securetransport/low_level.py
python
_create_cfstring_array
(lst)
return cf_arr
Given a list of Python binary data, create an associated CFMutableArray. The array must be CFReleased by the caller. Raises an ssl.SSLError on failure.
Given a list of Python binary data, create an associated CFMutableArray. The array must be CFReleased by the caller.
[ "Given", "a", "list", "of", "Python", "binary", "data", "create", "an", "associated", "CFMutableArray", ".", "The", "array", "must", "be", "CFReleased", "by", "the", "caller", "." ]
def _create_cfstring_array(lst): """ Given a list of Python binary data, create an associated CFMutableArray. The array must be CFReleased by the caller. Raises an ssl.SSLError on failure. """ cf_arr = None try: cf_arr = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) if not cf_arr: raise MemoryError("Unable to allocate memory!") for item in lst: cf_str = _cfstr(item) if not cf_str: raise MemoryError("Unable to allocate memory!") try: CoreFoundation.CFArrayAppendValue(cf_arr, cf_str) finally: CoreFoundation.CFRelease(cf_str) except BaseException as e: if cf_arr: CoreFoundation.CFRelease(cf_arr) raise ssl.SSLError("Unable to allocate array: %s" % (e,)) return cf_arr
[ "def", "_create_cfstring_array", "(", "lst", ")", ":", "cf_arr", "=", "None", "try", ":", "cf_arr", "=", "CoreFoundation", ".", "CFArrayCreateMutable", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "0", ",", "ctypes", ".", "byref", "(", "CoreFoundation...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/urllib3/contrib/_securetransport/low_level.py#L73-L101
PythonOT/POT
be0ed1dcd0b65ec804e454f1a2d3c0d227c0ddbe
ot/smooth.py
python
solve_semi_dual
(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500, verbose=False)
return res.x, res
Solve the "smoothed" semi-dual objective. Parameters ---------- a: array, shape = (len(a), ) b: array, shape = (len(b), ) Input histograms (should be non-negative and sum to 1). C: array, shape = (len(a), len(b)) Ground cost matrix. regul: Regularization object Should implement a `max_Omega(X)` method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = (len(a), ) Semi-dual potentials.
Solve the "smoothed" semi-dual objective.
[ "Solve", "the", "smoothed", "semi", "-", "dual", "objective", "." ]
def solve_semi_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500, verbose=False): """ Solve the "smoothed" semi-dual objective. Parameters ---------- a: array, shape = (len(a), ) b: array, shape = (len(b), ) Input histograms (should be non-negative and sum to 1). C: array, shape = (len(a), len(b)) Ground cost matrix. regul: Regularization object Should implement a `max_Omega(X)` method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = (len(a), ) Semi-dual potentials. """ def _func(alpha): obj, grad = semi_dual_obj_grad(alpha, a, b, C, regul) # We need to maximize the semi-dual. return -obj, -grad alpha_init = np.zeros(len(a)) res = minimize(_func, alpha_init, method=method, jac=True, tol=tol, options=dict(maxiter=max_iter, disp=verbose)) return res.x, res
[ "def", "solve_semi_dual", "(", "a", ",", "b", ",", "C", ",", "regul", ",", "method", "=", "\"L-BFGS-B\"", ",", "tol", "=", "1e-3", ",", "max_iter", "=", "500", ",", "verbose", "=", "False", ")", ":", "def", "_func", "(", "alpha", ")", ":", "obj", ...
https://github.com/PythonOT/POT/blob/be0ed1dcd0b65ec804e454f1a2d3c0d227c0ddbe/ot/smooth.py#L350-L387
guptarohit/cryptoCMD
87b80b544c31999313692e4adde7d0055de2c08a
setup.py
python
UploadCommand.status
(s)
Prints things in bold.
Prints things in bold.
[ "Prints", "things", "in", "bold", "." ]
def status(s): """Prints things in bold.""" print("\033[1m{0}\033[0m".format(s))
[ "def", "status", "(", "s", ")", ":", "print", "(", "\"\\033[1m{0}\\033[0m\"", ".", "format", "(", "s", ")", ")" ]
https://github.com/guptarohit/cryptoCMD/blob/87b80b544c31999313692e4adde7d0055de2c08a/setup.py#L29-L31
mozilla/addons-server
cbfb29e5be99539c30248d70b93bb15e1c1bc9d7
src/olympia/addons/models.py
python
resolve_webext_translations
(cls, data, upload)
return data
Resolve all possible translations from an add-on. This returns a modified `data` dictionary accordingly with proper translations filled in.
Resolve all possible translations from an add-on.
[ "Resolve", "all", "possible", "translations", "from", "an", "add", "-", "on", "." ]
def resolve_webext_translations(cls, data, upload): """Resolve all possible translations from an add-on. This returns a modified `data` dictionary accordingly with proper translations filled in. """ default_locale = find_language(data.get('default_locale')) if not default_locale: # Don't change anything if we don't meet the requirements return data # find_language might have expanded short to full locale, so update it. data['default_locale'] = default_locale fields = ('name', 'homepage', 'summary') messages = extract_translations(upload) for field in fields: data[field] = { locale: resolve_i18n_message( data[field], locale=locale, default_locale=default_locale, messages=messages, ) for locale in messages } return data
[ "def", "resolve_webext_translations", "(", "cls", ",", "data", ",", "upload", ")", ":", "default_locale", "=", "find_language", "(", "data", ".", "get", "(", "'default_locale'", ")", ")", "if", "not", "default_locale", ":", "# Don't change anything if we don't meet ...
https://github.com/mozilla/addons-server/blob/cbfb29e5be99539c30248d70b93bb15e1c1bc9d7/src/olympia/addons/models.py#L934-L963
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/pip/pip/_vendor/requests/packages/urllib3/util/timeout.py
python
Timeout.get_connect_duration
(self)
return current_time() - self._start_connect
Gets the time elapsed since the call to :meth:`start_connect`. :return: Elapsed time. :rtype: float :raises urllib3.exceptions.TimeoutStateError: if you attempt to get duration for a timer that hasn't been started.
Gets the time elapsed since the call to :meth:`start_connect`.
[ "Gets", "the", "time", "elapsed", "since", "the", "call", "to", ":", "meth", ":", "start_connect", "." ]
def get_connect_duration(self): """ Gets the time elapsed since the call to :meth:`start_connect`. :return: Elapsed time. :rtype: float :raises urllib3.exceptions.TimeoutStateError: if you attempt to get duration for a timer that hasn't been started. """ if self._start_connect is None: raise TimeoutStateError("Can't get connect duration for timer " "that has not started.") return current_time() - self._start_connect
[ "def", "get_connect_duration", "(", "self", ")", ":", "if", "self", ".", "_start_connect", "is", "None", ":", "raise", "TimeoutStateError", "(", "\"Can't get connect duration for timer \"", "\"that has not started.\"", ")", "return", "current_time", "(", ")", "-", "se...
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/pip/_vendor/requests/packages/urllib3/util/timeout.py#L180-L191
gautamkrishnar/socli
4d68e523fa7c70b0b3aabd51b097769f948a3821
socli/socli.py
python
socli_browse_interactive_windows
(query_tag)
Interactive mode for -b browse :param query_tag: :return:
Interactive mode for -b browse :param query_tag: :return:
[ "Interactive", "mode", "for", "-", "b", "browse", ":", "param", "query_tag", ":", ":", "return", ":" ]
def socli_browse_interactive_windows(query_tag): """ Interactive mode for -b browse :param query_tag: :return: """ try: search_res = requests.get(search.so_burl + query_tag) search.captcha_check(search_res.url) soup = BeautifulSoup(search_res.text, 'html.parser') try: soup.find_all("div", class_="question-summary")[0] # For explicitly raising exception tmp = (soup.find_all("div", class_="question-summary")) i = 0 question_local_url = [] print(printer.bold("\nSelect a question below:\n")) while i < len(tmp): if i == 10: break # limiting results question_text = ' '.join((tmp[i].a.get_text()).split()) question_text = question_text.replace("Q: ", "") printer.print_warning(str(i + 1) + ". " + printer.display_str(question_text)) q_tag = (soup.find_all("div", class_="question-summary"))[i] answers = [s.get_text() for s in q_tag.find_all("a", class_="post-tag")][0:] ques_tags = " ".join(str(x) for x in answers) question_local_url.append(tmp[i].a.get("href")) print(" " + printer.display_str(ques_tags) + "\n") i = i + 1 try: op = int(printer.inputs("\nType the option no to continue or any other key to exit:")) while 1: if (op > 0) and (op <= i): display_results(search.so_burl + question_local_url[op - 1]) cnt = 1 # this is because the 1st post is the question itself while 1: global tmpsoup qna = printer.inputs( "Type " + printer.bold("o") + " to open in browser, " + printer.bold( "n") + " to next answer, " + printer.bold( "b") + " for previous answer or any other key to exit:") if qna in ["n", "N"]: try: answer = (tmpsoup.find_all("div", class_="js-post-body")[cnt + 1].get_text()) printer.print_green("\n\nAnswer:\n") print("-------\n" + answer + "\n-------\n") cnt = cnt + 1 except IndexError: printer.print_warning(" No more answers found for this question. Exiting...") sys.exit(0) continue if qna in ["b", "B"]: if cnt == 1: printer.print_warning(" You cant go further back. You are on the first answer!") continue answer = (tmpsoup.find_all("div", class_="js-post-body")[cnt - 1].get_text()) printer.print_green("\n\nAnswer:\n") print("-------\n" + answer + "\n-------\n") cnt = cnt - 1 continue if qna in ["o", "O"]: import webbrowser printer.print_warning("Opening in your browser...") webbrowser.open(search.so_burl + question_local_url[op - 1]) else: break sys.exit(0) else: op = int(input("\n\nWrong option. select the option no to continue:")) except Exception as e: printer.showerror(e) printer.print_warning("\n Exiting...") sys.exit(0) except IndexError: printer.print_warning("No results found...") sys.exit(0) except UnicodeEncodeError: printer.print_warning("\n\nEncoding error: Use \"chcp 65001\" command before using socli...") sys.exit(0) except requests.exceptions.ConnectionError: printer.print_fail("Please check your internet connectivity...") except Exception as e: printer.showerror(e) sys.exit(0)
[ "def", "socli_browse_interactive_windows", "(", "query_tag", ")", ":", "try", ":", "search_res", "=", "requests", ".", "get", "(", "search", ".", "so_burl", "+", "query_tag", ")", "search", ".", "captcha_check", "(", "search_res", ".", "url", ")", "soup", "=...
https://github.com/gautamkrishnar/socli/blob/4d68e523fa7c70b0b3aabd51b097769f948a3821/socli/socli.py#L137-L220
TkTech/notifico
484c411cba3cc00b69dbf462c2f038a2d9a44f84
notifico/bots/bot.py
python
Channel.__init__
(self, client, name, password=None)
[]
def __init__(self, client, name, password=None): self._client = client self._name = name self._password = password self.message_min_delay = 0 self._joined = gevent.event.Event() self._message_queue = gevent.queue.Queue() signals.m.on_JOIN.connect(self.on_join, sender=client) signals.m.on_KICK.connect(self.on_kick, sender=client) # start off the sender greenlet gevent.spawn(self._check_message_queue)
[ "def", "__init__", "(", "self", ",", "client", ",", "name", ",", "password", "=", "None", ")", ":", "self", ".", "_client", "=", "client", "self", ".", "_name", "=", "name", "self", ".", "_password", "=", "password", "self", ".", "message_min_delay", "...
https://github.com/TkTech/notifico/blob/484c411cba3cc00b69dbf462c2f038a2d9a44f84/notifico/bots/bot.py#L86-L100
nucleic/enaml
65c2a2a2d765e88f2e1103046680571894bb41ed
enaml/workbench/plugin_manifest.py
python
PluginManifest.extension_points
(self)
return [c for c in self.children if isinstance(c, ExtensionPoint)]
Get the list of extensions points defined by the manifest.
Get the list of extensions points defined by the manifest.
[ "Get", "the", "list", "of", "extensions", "points", "defined", "by", "the", "manifest", "." ]
def extension_points(self): """ Get the list of extensions points defined by the manifest. """ return [c for c in self.children if isinstance(c, ExtensionPoint)]
[ "def", "extension_points", "(", "self", ")", ":", "return", "[", "c", "for", "c", "in", "self", ".", "children", "if", "isinstance", "(", "c", ",", "ExtensionPoint", ")", "]" ]
https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/workbench/plugin_manifest.py#L62-L66
veegee/guv
d7bac2ca6a73cc2059969af08223b82f3e187922
guv/hubs/hub.py
python
get_default_hub
()
Get default hub implementation
Get default hub implementation
[ "Get", "default", "hub", "implementation" ]
def get_default_hub(): """Get default hub implementation """ names = [hub_name] if hub_name else ['pyuv_cffi', 'pyuv', 'epoll'] for name in names: try: module = importlib.import_module('guv.hubs.{}'.format(name)) log.debug('Hub: use {}'.format(name)) return module except ImportError: # try the next possible hub pass
[ "def", "get_default_hub", "(", ")", ":", "names", "=", "[", "hub_name", "]", "if", "hub_name", "else", "[", "'pyuv_cffi'", ",", "'pyuv'", ",", "'epoll'", "]", "for", "name", "in", "names", ":", "try", ":", "module", "=", "importlib", ".", "import_module"...
https://github.com/veegee/guv/blob/d7bac2ca6a73cc2059969af08223b82f3e187922/guv/hubs/hub.py#L31-L43
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1beta1_custom_resource_subresources.py
python
V1beta1CustomResourceSubresources.status
(self, status)
Sets the status of this V1beta1CustomResourceSubresources. status indicates the custom resource should serve a `/status` subresource. When enabled: 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. # noqa: E501 :param status: The status of this V1beta1CustomResourceSubresources. # noqa: E501 :type: object
Sets the status of this V1beta1CustomResourceSubresources.
[ "Sets", "the", "status", "of", "this", "V1beta1CustomResourceSubresources", "." ]
def status(self, status): """Sets the status of this V1beta1CustomResourceSubresources. status indicates the custom resource should serve a `/status` subresource. When enabled: 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. # noqa: E501 :param status: The status of this V1beta1CustomResourceSubresources. # noqa: E501 :type: object """ self._status = status
[ "def", "status", "(", "self", ",", "status", ")", ":", "self", ".", "_status", "=", "status" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1beta1_custom_resource_subresources.py#L93-L102
huhamhire/huhamhire-hosts
33b9c49e7a4045b00e0c0df06f25e9ce8a037761
util/retrievedata.py
python
RetrieveData.db_exists
(cls, database=DATABASE)
return os.path.isfile(database)
Check whether the :attr:`database` file exists or not. .. note:: This is a `classmethod`. :param database: Path to a SQLite database file. `./hostslist.s3db` by default. :type database: str :return: A flag indicating whether the database file exists or not. :rtype: bool
Check whether the :attr:`database` file exists or not.
[ "Check", "whether", "the", ":", "attr", ":", "database", "file", "exists", "or", "not", "." ]
def db_exists(cls, database=DATABASE): """ Check whether the :attr:`database` file exists or not. .. note:: This is a `classmethod`. :param database: Path to a SQLite database file. `./hostslist.s3db` by default. :type database: str :return: A flag indicating whether the database file exists or not. :rtype: bool """ return os.path.isfile(database)
[ "def", "db_exists", "(", "cls", ",", "database", "=", "DATABASE", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "database", ")" ]
https://github.com/huhamhire/huhamhire-hosts/blob/33b9c49e7a4045b00e0c0df06f25e9ce8a037761/util/retrievedata.py#L46-L58
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/distutils/command/sdist.py
python
sdist.run
(self)
[]
def run(self): # 'filelist' contains the list of files that will make up the # manifest self.filelist = FileList() # Run sub commands for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) # Do whatever it takes to get the list of files to process # (process the manifest template, read an existing manifest, # whatever). File list is accumulated in 'self.filelist'. self.get_file_list() # If user just wanted us to regenerate the manifest, stop now. if self.manifest_only: return # Otherwise, go ahead and create the source distribution tarball, # or zipfile, or whatever. self.make_distribution()
[ "def", "run", "(", "self", ")", ":", "# 'filelist' contains the list of files that will make up the", "# manifest", "self", ".", "filelist", "=", "FileList", "(", ")", "# Run sub commands", "for", "cmd_name", "in", "self", ".", "get_sub_commands", "(", ")", ":", "se...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/distutils/command/sdist.py#L148-L168
sadighian/crypto-rl
078081e5715cadeae9c798a3d759c9d59d2041bc
data_recorder/bitfinex_connector/bitfinex_book.py
python
BitfinexBook.match
(self, msg: dict)
This method is not implemented within Bitmex's API. However, I've implemented it to capture order arrival flows (i.e., incoming market orders.) and to be consistent with the overarching design pattern. Note: this event handler does not impact the LOB in any other way than updating the number of market orders received at a given price level. :param msg: buy or sell transaction message from Bitfinex :return: (void)
This method is not implemented within Bitmex's API.
[ "This", "method", "is", "not", "implemented", "within", "Bitmex", "s", "API", "." ]
def match(self, msg: dict) -> None: """ This method is not implemented within Bitmex's API. However, I've implemented it to capture order arrival flows (i.e., incoming market orders.) and to be consistent with the overarching design pattern. Note: this event handler does not impact the LOB in any other way than updating the number of market orders received at a given price level. :param msg: buy or sell transaction message from Bitfinex :return: (void) """ price = msg.get('price', None) if price in self.price_dict: quantity = abs(msg['size']) self.price_dict[price].add_market(quantity=quantity, price=price)
[ "def", "match", "(", "self", ",", "msg", ":", "dict", ")", "->", "None", ":", "price", "=", "msg", ".", "get", "(", "'price'", ",", "None", ")", "if", "price", "in", "self", ".", "price_dict", ":", "quantity", "=", "abs", "(", "msg", "[", "'size'...
https://github.com/sadighian/crypto-rl/blob/078081e5715cadeae9c798a3d759c9d59d2041bc/data_recorder/bitfinex_connector/bitfinex_book.py#L28-L44
rucio/rucio
6d0d358e04f5431f0b9a98ae40f31af0ddff4833
lib/rucio/db/sqla/session.py
python
get_session
()
return session
Creates a session to a specific database, assumes that schema already in place. :returns: session
Creates a session to a specific database, assumes that schema already in place. :returns: session
[ "Creates", "a", "session", "to", "a", "specific", "database", "assumes", "that", "schema", "already", "in", "place", ".", ":", "returns", ":", "session" ]
def get_session(): """ Creates a session to a specific database, assumes that schema already in place. :returns: session """ global _MAKER, _LOCK if not _MAKER: _LOCK.acquire() try: get_engine() get_maker() finally: _LOCK.release() assert _MAKER session = scoped_session(_MAKER) return session
[ "def", "get_session", "(", ")", ":", "global", "_MAKER", ",", "_LOCK", "if", "not", "_MAKER", ":", "_LOCK", ".", "acquire", "(", ")", "try", ":", "get_engine", "(", ")", "get_maker", "(", ")", "finally", ":", "_LOCK", ".", "release", "(", ")", "asser...
https://github.com/rucio/rucio/blob/6d0d358e04f5431f0b9a98ae40f31af0ddff4833/lib/rucio/db/sqla/session.py#L240-L254
ethereum/trinity
6383280c5044feb06695ac2f7bc1100b7bcf4fe0
trinity/protocol/common/peer_pool_event_bus.py
python
PeerPoolEventServer.handle_get_connected_peers_requests
(self)
[]
async def handle_get_connected_peers_requests(self) -> None: async for req in self.event_bus.stream(GetConnectedPeersRequest): await self.event_bus.broadcast( GetConnectedPeersResponse.from_connected_nodes(self.peer_pool.connected_nodes), req.broadcast_config() )
[ "async", "def", "handle_get_connected_peers_requests", "(", "self", ")", "->", "None", ":", "async", "for", "req", "in", "self", ".", "event_bus", ".", "stream", "(", "GetConnectedPeersRequest", ")", ":", "await", "self", ".", "event_bus", ".", "broadcast", "(...
https://github.com/ethereum/trinity/blob/6383280c5044feb06695ac2f7bc1100b7bcf4fe0/trinity/protocol/common/peer_pool_event_bus.py#L183-L188
sosreport/sos
900e8bea7f3cd36c1dd48f3cbb351ab92f766654
sos/options.py
python
SoSOptions._convert_to_type
(self, key, val, conf)
return val
Ensure that the value read from a config file is the proper type for consumption by the component, as defined by arg_defaults. Params: :param key: The key in arg_defaults we need to match the type of :param val: The value to be converted to a particular type :param conf: File values are being loaded from
Ensure that the value read from a config file is the proper type for consumption by the component, as defined by arg_defaults.
[ "Ensure", "that", "the", "value", "read", "from", "a", "config", "file", "is", "the", "proper", "type", "for", "consumption", "by", "the", "component", "as", "defined", "by", "arg_defaults", "." ]
def _convert_to_type(self, key, val, conf): """Ensure that the value read from a config file is the proper type for consumption by the component, as defined by arg_defaults. Params: :param key: The key in arg_defaults we need to match the type of :param val: The value to be converted to a particular type :param conf: File values are being loaded from """ if isinstance(self.arg_defaults[key], type(val)): return val if isinstance(self.arg_defaults[key], list): return [v for v in val.split(',')] if isinstance(self.arg_defaults[key], bool): _val = val.lower() if _val in ['true', 'on', 'yes']: return True elif _val in ['false', 'off', 'no']: return False else: raise Exception( "Value of '%s' in %s must be True or False or analagous" % (key, conf)) if isinstance(self.arg_defaults[key], int): try: return int(val) except ValueError: raise Exception("Value of '%s' in %s must be integer" % (key, conf)) return val
[ "def", "_convert_to_type", "(", "self", ",", "key", ",", "val", ",", "conf", ")", ":", "if", "isinstance", "(", "self", ".", "arg_defaults", "[", "key", "]", ",", "type", "(", "val", ")", ")", ":", "return", "val", "if", "isinstance", "(", "self", ...
https://github.com/sosreport/sos/blob/900e8bea7f3cd36c1dd48f3cbb351ab92f766654/sos/options.py#L141-L171
rkhleics/wagtailmodeladmin
7fddc853bab2ff3868b8c7a03329308c55f16358
wagtailmodeladmin/views.py
python
InspectView.get_document_field_display
(self, field_name, field)
return self.model_admin.get_empty_value_display()
Render a link to a document
Render a link to a document
[ "Render", "a", "link", "to", "a", "document" ]
def get_document_field_display(self, field_name, field): """ Render a link to a document """ document = getattr(self.instance, field_name) if document: return mark_safe( '<a href="%s">%s <span class="meta">(%s, %s)</span></a>' % ( document.url, document.title, document.file_extension.upper(), filesizeformat(document.file.size), ) ) return self.model_admin.get_empty_value_display()
[ "def", "get_document_field_display", "(", "self", ",", "field_name", ",", "field", ")", ":", "document", "=", "getattr", "(", "self", ".", "instance", ",", "field_name", ")", "if", "document", ":", "return", "mark_safe", "(", "'<a href=\"%s\">%s <span class=\"meta...
https://github.com/rkhleics/wagtailmodeladmin/blob/7fddc853bab2ff3868b8c7a03329308c55f16358/wagtailmodeladmin/views.py#L795-L807
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/dev/bdf_vectorized/cards/optimization.py
python
DDVAL.add_card
(cls, card, comment='')
return DDVAL(oid, ddvals, comment=comment)
Adds a DDVAL card from ``BDF.add_card(...)`` Parameters ---------- card : BDFCard() a BDFCard object comment : str; default='' a comment for the card
Adds a DDVAL card from ``BDF.add_card(...)``
[ "Adds", "a", "DDVAL", "card", "from", "BDF", ".", "add_card", "(", "...", ")" ]
def add_card(cls, card, comment=''): """ Adds a DDVAL card from ``BDF.add_card(...)`` Parameters ---------- card : BDFCard() a BDFCard object comment : str; default='' a comment for the card """ oid = integer(card, 1, 'oid') n = 1 ddvals = [] for i in range(2, len(card)): ddval = double_string_or_blank(card, i, 'DDVAL%s' % n) if ddval is not None: ddvals.append(ddval) return DDVAL(oid, ddvals, comment=comment)
[ "def", "add_card", "(", "cls", ",", "card", ",", "comment", "=", "''", ")", ":", "oid", "=", "integer", "(", "card", ",", "1", ",", "'oid'", ")", "n", "=", "1", "ddvals", "=", "[", "]", "for", "i", "in", "range", "(", "2", ",", "len", "(", ...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/dev/bdf_vectorized/cards/optimization.py#L518-L536
dpp/simply_lift
cf49f7dcce81c7f1557314dd0f0bb08aaedc73da
elyxer.py
python
IncludeInset.__unicode__
(self)
return 'Included "' + self.filename + '"'
Return a printable description.
Return a printable description.
[ "Return", "a", "printable", "description", "." ]
def __unicode__(self): "Return a printable description." if not self.filename: return 'Included unnamed file' return 'Included "' + self.filename + '"'
[ "def", "__unicode__", "(", "self", ")", ":", "if", "not", "self", ".", "filename", ":", "return", "'Included unnamed file'", "return", "'Included \"'", "+", "self", ".", "filename", "+", "'\"'" ]
https://github.com/dpp/simply_lift/blob/cf49f7dcce81c7f1557314dd0f0bb08aaedc73da/elyxer.py#L7142-L7146
dansanderson/picotool
d8c51e58416f8010dc8c0fba3df5f0424b5bb852
pico8/lua/parser.py
python
Parser.process_tokens
(self, tokens)
Process a list of tokens into an AST. This method must be single-threaded. To process multiple tokens in multiple threads, use one Parser instance per thread. Args: tokens: An iterable of lexer.Token objects. All tokens will be loaded into memory for processing. Raises: ParserError: Some pattern of tokens did not match the grammar.
Process a list of tokens into an AST.
[ "Process", "a", "list", "of", "tokens", "into", "an", "AST", "." ]
def process_tokens(self, tokens): """Process a list of tokens into an AST. This method must be single-threaded. To process multiple tokens in multiple threads, use one Parser instance per thread. Args: tokens: An iterable of lexer.Token objects. All tokens will be loaded into memory for processing. Raises: ParserError: Some pattern of tokens did not match the grammar. """ self._tokens = list(tokens) self._pos = 0 self._ast = self._assert(self._chunk(), 'input to be a program') self._ast.store_token_groups(self._tokens)
[ "def", "process_tokens", "(", "self", ",", "tokens", ")", ":", "self", ".", "_tokens", "=", "list", "(", "tokens", ")", "self", ".", "_pos", "=", "0", "self", ".", "_ast", "=", "self", ".", "_assert", "(", "self", ".", "_chunk", "(", ")", ",", "'...
https://github.com/dansanderson/picotool/blob/d8c51e58416f8010dc8c0fba3df5f0424b5bb852/pico8/lua/parser.py#L1061-L1078
indico/indico
1579ea16235bbe5f22a308b79c5902c85374721f
indico/cli/user.py
python
revoke_admin
(user_id)
Revoke administration rights from a given user.
Revoke administration rights from a given user.
[ "Revoke", "administration", "rights", "from", "a", "given", "user", "." ]
def revoke_admin(user_id): """Revoke administration rights from a given user.""" user = User.get(user_id) if user is None: click.secho('This user does not exist', fg='red') return _print_user_info(user) if not user.is_admin: click.secho('This user does not have administration rights', fg='yellow') return if click.confirm(click.style('Revoke administration rights from this user?', fg='yellow')): user.is_admin = False db.session.commit() click.secho('Administration rights revoked successfully', fg='green')
[ "def", "revoke_admin", "(", "user_id", ")", ":", "user", "=", "User", ".", "get", "(", "user_id", ")", "if", "user", "is", "None", ":", "click", ".", "secho", "(", "'This user does not exist'", ",", "fg", "=", "'red'", ")", "return", "_print_user_info", ...
https://github.com/indico/indico/blob/1579ea16235bbe5f22a308b79c5902c85374721f/indico/cli/user.py#L168-L181
Yelp/mrjob
091572e87bc24cc64be40278dd0f5c3617c98d4b
mrjob/spark/harness.py
python
_run_reducer
(make_mrc_job, step_num, rdd, num_reducers=None)
return rdd.mapPartitions( reduce_lines, preservesPartitioning=bool(num_reducers))
Run our job's combiner, and group lines with the same key together. :param reducer_job: an instance of our job, instantiated to be the mapper for the step we wish to run :param rdd: an RDD containing "reducer ready" lines representing encoded key-value pairs, that is, where all lines with the same key are adjacent and in the same partition :param num_reducers: limit the number of paratitions of output rdd, which is similar to mrjob's limit on number of reducers. :return: an RDD containing encoded key-value pairs
Run our job's combiner, and group lines with the same key together.
[ "Run", "our", "job", "s", "combiner", "and", "group", "lines", "with", "the", "same", "key", "together", "." ]
def _run_reducer(make_mrc_job, step_num, rdd, num_reducers=None): """Run our job's combiner, and group lines with the same key together. :param reducer_job: an instance of our job, instantiated to be the mapper for the step we wish to run :param rdd: an RDD containing "reducer ready" lines representing encoded key-value pairs, that is, where all lines with the same key are adjacent and in the same partition :param num_reducers: limit the number of paratitions of output rdd, which is similar to mrjob's limit on number of reducers. :return: an RDD containing encoded key-value pairs """ # initialize job class inside mapPartitions(). this deals with jobs that # can't be initialized in the Spark driver (see #2044) def reduce_lines(lines): job = make_mrc_job('reducer', step_num) read, write = job.pick_protocols(step_num, 'reducer') # decode lines into key-value pairs (as a generator, not a list) # # line -> (k, v) if read: pairs = (read(line) for line in lines) else: pairs = lines # pairs were never encoded # reduce_pairs() runs key-value pairs through reducer # # (k, v), ... -> (k, v), ... for k, v in job.reduce_pairs(pairs, step_num): # encode key-value pairs back into lines # # (k, v) -> line if write: yield write(k, v) else: yield k, v # if *num_reducers* is set, don't re-partition. otherwise, doesn't matter return rdd.mapPartitions( reduce_lines, preservesPartitioning=bool(num_reducers))
[ "def", "_run_reducer", "(", "make_mrc_job", ",", "step_num", ",", "rdd", ",", "num_reducers", "=", "None", ")", ":", "# initialize job class inside mapPartitions(). this deals with jobs that", "# can't be initialized in the Spark driver (see #2044)", "def", "reduce_lines", "(", ...
https://github.com/Yelp/mrjob/blob/091572e87bc24cc64be40278dd0f5c3617c98d4b/mrjob/spark/harness.py#L545-L587
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/distlib/util.py
python
CSVWriter.writerow
(self, row)
[]
def writerow(self, row): if sys.version_info[0] < 3: r = [] for item in row: if isinstance(item, text_type): item = item.encode('utf-8') r.append(item) row = r self.writer.writerow(row)
[ "def", "writerow", "(", "self", ",", "row", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "r", "=", "[", "]", "for", "item", "in", "row", ":", "if", "isinstance", "(", "item", ",", "text_type", ")", ":", "item", "=",...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/distlib/util.py#L1493-L1501
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v5_1/service_hooks/service_hooks_client.py
python
ServiceHooksClient.get_notifications
(self, subscription_id, max_results=None, status=None, result=None)
return self._deserialize('[Notification]', self._unwrap_collection(response))
GetNotifications. Get a list of notifications for a specific subscription. A notification includes details about the event, the request to and the response from the consumer service. :param str subscription_id: ID for a subscription. :param int max_results: Maximum number of notifications to return. Default is **100**. :param str status: Get only notifications with this status. :param str result: Get only notifications with this result type. :rtype: [Notification]
GetNotifications. Get a list of notifications for a specific subscription. A notification includes details about the event, the request to and the response from the consumer service. :param str subscription_id: ID for a subscription. :param int max_results: Maximum number of notifications to return. Default is **100**. :param str status: Get only notifications with this status. :param str result: Get only notifications with this result type. :rtype: [Notification]
[ "GetNotifications", ".", "Get", "a", "list", "of", "notifications", "for", "a", "specific", "subscription", ".", "A", "notification", "includes", "details", "about", "the", "event", "the", "request", "to", "and", "the", "response", "from", "the", "consumer", "...
def get_notifications(self, subscription_id, max_results=None, status=None, result=None): """GetNotifications. Get a list of notifications for a specific subscription. A notification includes details about the event, the request to and the response from the consumer service. :param str subscription_id: ID for a subscription. :param int max_results: Maximum number of notifications to return. Default is **100**. :param str status: Get only notifications with this status. :param str result: Get only notifications with this result type. :rtype: [Notification] """ route_values = {} if subscription_id is not None: route_values['subscriptionId'] = self._serialize.url('subscription_id', subscription_id, 'str') query_parameters = {} if max_results is not None: query_parameters['maxResults'] = self._serialize.query('max_results', max_results, 'int') if status is not None: query_parameters['status'] = self._serialize.query('status', status, 'str') if result is not None: query_parameters['result'] = self._serialize.query('result', result, 'str') response = self._send(http_method='GET', location_id='0c62d343-21b0-4732-997b-017fde84dc28', version='5.1', route_values=route_values, query_parameters=query_parameters) return self._deserialize('[Notification]', self._unwrap_collection(response))
[ "def", "get_notifications", "(", "self", ",", "subscription_id", ",", "max_results", "=", "None", ",", "status", "=", "None", ",", "result", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "subscription_id", "is", "not", "None", ":", "route_val...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v5_1/service_hooks/service_hooks_client.py#L190-L214
awslabs/aws-ec2rescue-linux
8ecf40e7ea0d2563dac057235803fca2221029d2
lib/boto3/s3/transfer.py
python
S3Transfer.upload_file
(self, filename, bucket, key, callback=None, extra_args=None)
Upload a file to an S3 object. Variants have also been injected into S3 client, Bucket and Object. You don't have to use S3Transfer.upload_file() directly. .. seealso:: :py:meth:`S3.Client.upload_file` :py:meth:`S3.Client.upload_fileobj`
Upload a file to an S3 object.
[ "Upload", "a", "file", "to", "an", "S3", "object", "." ]
def upload_file(self, filename, bucket, key, callback=None, extra_args=None): """Upload a file to an S3 object. Variants have also been injected into S3 client, Bucket and Object. You don't have to use S3Transfer.upload_file() directly. .. seealso:: :py:meth:`S3.Client.upload_file` :py:meth:`S3.Client.upload_fileobj` """ if not isinstance(filename, six.string_types): raise ValueError('Filename must be a string') subscribers = self._get_subscribers(callback) future = self._manager.upload( filename, bucket, key, extra_args, subscribers) try: future.result() # If a client error was raised, add the backwards compatibility layer # that raises a S3UploadFailedError. These specific errors were only # ever thrown for upload_parts but now can be thrown for any related # client error. except ClientError as e: raise S3UploadFailedError( "Failed to upload %s to %s: %s" % ( filename, '/'.join([bucket, key]), e))
[ "def", "upload_file", "(", "self", ",", "filename", ",", "bucket", ",", "key", ",", "callback", "=", "None", ",", "extra_args", "=", "None", ")", ":", "if", "not", "isinstance", "(", "filename", ",", "six", ".", "string_types", ")", ":", "raise", "Valu...
https://github.com/awslabs/aws-ec2rescue-linux/blob/8ecf40e7ea0d2563dac057235803fca2221029d2/lib/boto3/s3/transfer.py#L261-L287
ElsevierDev/elsapy
5fda0434f106fdd89fa851144c25d80d7e1100d5
elsapy/elsprofile.py
python
ElsAffil.__init__
(self, uri = '', affil_id = '')
Initializes an affiliation given a Scopus affiliation URI or affiliation ID.
Initializes an affiliation given a Scopus affiliation URI or affiliation ID.
[ "Initializes", "an", "affiliation", "given", "a", "Scopus", "affiliation", "URI", "or", "affiliation", "ID", "." ]
def __init__(self, uri = '', affil_id = ''): """Initializes an affiliation given a Scopus affiliation URI or affiliation ID.""" if uri and not affil_id: super().__init__(uri) elif affil_id and not uri: super().__init__(self._uri_base + str(affil_id)) elif not uri and not affil_id: raise ValueError('No URI or affiliation ID specified') else: raise ValueError('Both URI and affiliation ID specified; just need one.')
[ "def", "__init__", "(", "self", ",", "uri", "=", "''", ",", "affil_id", "=", "''", ")", ":", "if", "uri", "and", "not", "affil_id", ":", "super", "(", ")", ".", "__init__", "(", "uri", ")", "elif", "affil_id", "and", "not", "uri", ":", "super", "...
https://github.com/ElsevierDev/elsapy/blob/5fda0434f106fdd89fa851144c25d80d7e1100d5/elsapy/elsprofile.py#L180-L189
missionpinball/mpf
8e6b74cff4ba06d2fec9445742559c1068b88582
mpf/commands/create_config.py
python
Command.create_show
(self)
Create a show.
Create a show.
[ "Create", "a", "show", "." ]
def create_show(self): """Create a show.""" show_name = input_dialog( title='Mode', text='Cool, got a name for your show?', style=self.example_style).run() # create shows folder show_path = os.path.normpath(os.path.join(self.machine_path, "shows", show_name)) shows_dir = os.path.normpath(os.path.join(self.machine_path, "shows")) if not os.path.exists(show_path): if self.in_machine_folder(): self.create_show_structure(show_name, shows_dir, self.machine_path) message_dialog( title='Shows', text=HTML('<style fg="green">Success:</style> Created show {}.'.format(show_name)), # text='Success: Created machine config {}.'.format(config_name), style=self.example_style ).run() else: self.show_not_in_machine_folder_dialog() else: message_dialog( title='Mode', text=HTML( '<style fg="red">Error:</style> A show with this name already exists\nPlease pick another one!'), style=self.example_style ).run() self.create_machine_config()
[ "def", "create_show", "(", "self", ")", ":", "show_name", "=", "input_dialog", "(", "title", "=", "'Mode'", ",", "text", "=", "'Cool, got a name for your show?'", ",", "style", "=", "self", ".", "example_style", ")", ".", "run", "(", ")", "# create shows folde...
https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/commands/create_config.py#L142-L172
google/clusterfuzz
f358af24f414daa17a3649b143e71ea71871ef59
src/clusterfuzz/_internal/bot/minimizer/utils.py
python
get_size_string
(size)
return '%d GB' % (size >> 30)
Return string representation for size.
Return string representation for size.
[ "Return", "string", "representation", "for", "size", "." ]
def get_size_string(size): """Return string representation for size.""" if size < 1 << 10: return '%d B' % size if size < 1 << 20: return '%d KB' % (size >> 10) if size < 1 << 30: return '%d MB' % (size >> 20) return '%d GB' % (size >> 30)
[ "def", "get_size_string", "(", "size", ")", ":", "if", "size", "<", "1", "<<", "10", ":", "return", "'%d B'", "%", "size", "if", "size", "<", "1", "<<", "20", ":", "return", "'%d KB'", "%", "(", "size", ">>", "10", ")", "if", "size", "<", "1", ...
https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/clusterfuzz/_internal/bot/minimizer/utils.py#L65-L74