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
avocado-framework/avocado
1f9b3192e8ba47d029c33fe21266bd113d17811f
avocado/utils/script.py
python
make_temp_script
(name, content, prefix='avocado_script', mode=DEFAULT_MODE)
return scpt.path
Creates a new temporary script stored in the file system. :param path: the script file name. :param content: the script content. :param prefix: the directory prefix Default to 'avocado_script'. :param mode: set file mode, default to 0775. :return: the script path.
Creates a new temporary script stored in the file system.
[ "Creates", "a", "new", "temporary", "script", "stored", "in", "the", "file", "system", "." ]
def make_temp_script(name, content, prefix='avocado_script', mode=DEFAULT_MODE): """ Creates a new temporary script stored in the file system. :param path: the script file name. :param content: the script content. :param prefix: the directory prefix Default to 'avocado_script'. :param mode: set file mode, default to 0775. :return: the script path. """ scpt = TemporaryScript(name, content, prefix=prefix, mode=mode) scpt.save() return scpt.path
[ "def", "make_temp_script", "(", "name", ",", "content", ",", "prefix", "=", "'avocado_script'", ",", "mode", "=", "DEFAULT_MODE", ")", ":", "scpt", "=", "TemporaryScript", "(", "name", ",", "content", ",", "prefix", "=", "prefix", ",", "mode", "=", "mode",...
https://github.com/avocado-framework/avocado/blob/1f9b3192e8ba47d029c33fe21266bd113d17811f/avocado/utils/script.py#L149-L161
Cog-Creators/Red-DiscordBot
b05933274a11fb097873ab0d1b246d37b06aa306
redbot/cogs/audio/apis/api_utils.py
python
prepare_config_scope_for_migration23
( # TODO: remove me in a future version ? scope, author: Union[discord.abc.User, int] = None, guild: discord.Guild = None )
return config_scope
Return the scope used by Playlists.
Return the scope used by Playlists.
[ "Return", "the", "scope", "used", "by", "Playlists", "." ]
def prepare_config_scope_for_migration23( # TODO: remove me in a future version ? scope, author: Union[discord.abc.User, int] = None, guild: discord.Guild = None ): """Return the scope used by Playlists.""" scope = standardize_scope(scope) if scope == PlaylistScope.GLOBAL.value: config_scope = [PlaylistScope.GLOBAL.value] elif scope == PlaylistScope.USER.value: if author is None: raise MissingAuthor("Invalid author for user scope.") config_scope = [PlaylistScope.USER.value, str(getattr(author, "id", author))] else: if guild is None: raise MissingGuild("Invalid guild for guild scope.") config_scope = [PlaylistScope.GUILD.value, str(getattr(guild, "id", guild))] return config_scope
[ "def", "prepare_config_scope_for_migration23", "(", "# TODO: remove me in a future version ?", "scope", ",", "author", ":", "Union", "[", "discord", ".", "abc", ".", "User", ",", "int", "]", "=", "None", ",", "guild", ":", "discord", ".", "Guild", "=", "None", ...
https://github.com/Cog-Creators/Red-DiscordBot/blob/b05933274a11fb097873ab0d1b246d37b06aa306/redbot/cogs/audio/apis/api_utils.py#L139-L155
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
example/pyctp/dac.py
python
date2week
(iday)
return (day+2*month+3*(month+1)/5+year+year/4-year/100+year/400)%7 + 1
[]
def date2week(iday): #http://blog.csdn.net/hawkfeifei/article/details/4337181 year = iday/10000 month = iday/100%100 day = iday%100 if month <= 2: month += 12 year -= 1 return (day+2*month+3*(month+1)/5+year+year/4-year/100+year/400)%7 + 1
[ "def", "date2week", "(", "iday", ")", ":", "#http://blog.csdn.net/hawkfeifei/article/details/4337181", "year", "=", "iday", "/", "10000", "month", "=", "iday", "/", "100", "%", "100", "day", "=", "iday", "%", "100", "if", "month", "<=", "2", ":", "month", ...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/pyctp/dac.py#L18-L26
flasgger/flasgger
beb9fa781fc6b063fe3f3081b9677dd70184a2da
examples/marshmallow_apispec.py
python
UserPostView.post
(self)
return jsonify(request.json)
A simple post Do it --- # This value overwrites the attributes above deprecated: true
A simple post Do it --- # This value overwrites the attributes above deprecated: true
[ "A", "simple", "post", "Do", "it", "---", "#", "This", "value", "overwrites", "the", "attributes", "above", "deprecated", ":", "true" ]
def post(self): """ A simple post Do it --- # This value overwrites the attributes above deprecated: true """ return jsonify(request.json)
[ "def", "post", "(", "self", ")", ":", "return", "jsonify", "(", "request", ".", "json", ")" ]
https://github.com/flasgger/flasgger/blob/beb9fa781fc6b063fe3f3081b9677dd70184a2da/examples/marshmallow_apispec.py#L59-L67
uccser/cs-unplugged
f83593f872792e71a9fab3f2d77a0f489205926b
csunplugged/topics/utils/add_lesson_ages_to_objects.py
python
add_lesson_ages_to_objects
(objects)
return objects
Add lesson min and max ages to given list of objects. Args: objects: List of objects of lessons. Returns: Modified list of objects.
Add lesson min and max ages to given list of objects.
[ "Add", "lesson", "min", "and", "max", "ages", "to", "given", "list", "of", "objects", "." ]
def add_lesson_ages_to_objects(objects): """Add lesson min and max ages to given list of objects. Args: objects: List of objects of lessons. Returns: Modified list of objects. """ age_groups = AgeGroup.objects.distinct() for item in objects: item_age_groups = list(age_groups.filter(lessons__id__in=item.lessons.all())) item.min_age = item_age_groups[0].ages.lower item.max_age = item_age_groups[-1].ages.upper return objects
[ "def", "add_lesson_ages_to_objects", "(", "objects", ")", ":", "age_groups", "=", "AgeGroup", ".", "objects", ".", "distinct", "(", ")", "for", "item", "in", "objects", ":", "item_age_groups", "=", "list", "(", "age_groups", ".", "filter", "(", "lessons__id__i...
https://github.com/uccser/cs-unplugged/blob/f83593f872792e71a9fab3f2d77a0f489205926b/csunplugged/topics/utils/add_lesson_ages_to_objects.py#L6-L20
bigmlcom/python
35f69d2f3121f1b3dde43495cf145d4992796ad5
bigml/fields.py
python
get_fields_structure
(resource, errors=False)
return (None, None, None, None, None) if errors else \ (None, None, None, None)
Returns the field structure for a resource, its locale and missing_tokens
Returns the field structure for a resource, its locale and missing_tokens
[ "Returns", "the", "field", "structure", "for", "a", "resource", "its", "locale", "and", "missing_tokens" ]
def get_fields_structure(resource, errors=False): """Returns the field structure for a resource, its locale and missing_tokens """ try: resource_type = get_resource_type(resource) except ValueError: raise ValueError("Unknown resource structure") field_errors = None resource = resource.get('object', resource) # locale and missing tokens if resource_type == SOURCE_PATH: resource_locale = resource['source_parser']['locale'] missing_tokens = resource[ 'source_parser']['missing_tokens'] else: resource_locale = resource.get('locale', DEFAULT_LOCALE) missing_tokens = resource.get('missing_tokens', DEFAULT_MISSING_TOKENS) fields = get_fields(resource) if resource_type in RESOURCES_WITH_FIELDS: # Check whether there's an objective id objective_column = None if resource_type == DATASET_PATH: objective_column = resource.get( \ 'objective_field', {}).get('id') if errors: field_errors = resource.get("status", {}).get("field_errors") elif resource_type in SUPERVISED_PATHS and \ resource_type != FUSION_PATH: objective_id = resource.get( \ 'objective_fields', [None])[0] objective_column = fields.get( \ objective_id, {}).get('column_number') result = fields, resource_locale, missing_tokens, objective_column if errors: result = result + (field_errors,) return result return (None, None, None, None, None) if errors else \ (None, None, None, None)
[ "def", "get_fields_structure", "(", "resource", ",", "errors", "=", "False", ")", ":", "try", ":", "resource_type", "=", "get_resource_type", "(", "resource", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Unknown resource structure\"", ")", "fie...
https://github.com/bigmlcom/python/blob/35f69d2f3121f1b3dde43495cf145d4992796ad5/bigml/fields.py#L72-L113
kupferlauncher/kupfer
1c1e9bcbce05a82f503f68f8b3955c20b02639b3
waflib/Utils.py
python
writef
(fname, data, m='w', encoding='latin-1')
Writes an entire file from a string. See also :py:meth:`waflib.Node.Node.writef`:: def build(ctx): from waflib import Utils txt = Utils.writef(self.path.make_node('i_like_kittens').abspath(), 'some data') self.path.make_node('i_like_kittens').write('some data') :type fname: string :param fname: Path to file :type data: string :param data: The contents to write to the file :type m: string :param m: Open mode :type encoding: string :param encoding: encoding value, only used for python 3
Writes an entire file from a string. See also :py:meth:`waflib.Node.Node.writef`::
[ "Writes", "an", "entire", "file", "from", "a", "string", ".", "See", "also", ":", "py", ":", "meth", ":", "waflib", ".", "Node", ".", "Node", ".", "writef", "::" ]
def writef(fname, data, m='w', encoding='latin-1'): """ Writes an entire file from a string. See also :py:meth:`waflib.Node.Node.writef`:: def build(ctx): from waflib import Utils txt = Utils.writef(self.path.make_node('i_like_kittens').abspath(), 'some data') self.path.make_node('i_like_kittens').write('some data') :type fname: string :param fname: Path to file :type data: string :param data: The contents to write to the file :type m: string :param m: Open mode :type encoding: string :param encoding: encoding value, only used for python 3 """ if sys.hexversion > 0x3000000 and not 'b' in m: data = data.encode(encoding) m += 'b' with open(fname, m) as f: f.write(data)
[ "def", "writef", "(", "fname", ",", "data", ",", "m", "=", "'w'", ",", "encoding", "=", "'latin-1'", ")", ":", "if", "sys", ".", "hexversion", ">", "0x3000000", "and", "not", "'b'", "in", "m", ":", "data", "=", "data", ".", "encode", "(", "encoding...
https://github.com/kupferlauncher/kupfer/blob/1c1e9bcbce05a82f503f68f8b3955c20b02639b3/waflib/Utils.py#L248-L271
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/_vendor/requests/structures.py
python
CaseInsensitiveDict.__setitem__
(self, key, value)
[]
def __setitem__(self, key, value): # Use the lowercased key for lookups, but store the actual # key alongside the value. self._store[key.lower()] = (key, value)
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "# Use the lowercased key for lookups, but store the actual", "# key alongside the value.", "self", ".", "_store", "[", "key", ".", "lower", "(", ")", "]", "=", "(", "key", ",", "value", ")" ...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/_vendor/requests/structures.py#L53-L56
weechat/scripts
99ec0e7eceefabb9efb0f11ec26d45d6e8e84335
python/autosort.py
python
command_helper_set
(buffer, command, args)
return weechat.WEECHAT_RC_OK
Add/update a helper to the helper list.
Add/update a helper to the helper list.
[ "Add", "/", "update", "a", "helper", "to", "the", "helper", "list", "." ]
def command_helper_set(buffer, command, args): ''' Add/update a helper to the helper list. ''' name, expression = split_args(args, 2) config.helpers[name] = expression config.save_helpers() command_helper_list(buffer, command, '') return weechat.WEECHAT_RC_OK
[ "def", "command_helper_set", "(", "buffer", ",", "command", ",", "args", ")", ":", "name", ",", "expression", "=", "split_args", "(", "args", ",", "2", ")", "config", ".", "helpers", "[", "name", "]", "=", "expression", "config", ".", "save_helpers", "("...
https://github.com/weechat/scripts/blob/99ec0e7eceefabb9efb0f11ec26d45d6e8e84335/python/autosort.py#L577-L585
qtile/qtile
803dc06fc1f8b121a1d8fe047f26a43812cd427f
libqtile/widget/base.py
python
_Widget._remove_dead_timers
(self)
Remove completed and cancelled timers from the list.
Remove completed and cancelled timers from the list.
[ "Remove", "completed", "and", "cancelled", "timers", "from", "the", "list", "." ]
def _remove_dead_timers(self): """Remove completed and cancelled timers from the list.""" self._futures = [ timer for timer in self._futures if not (timer.cancelled() or timer.when() < self.qtile._eventloop.time()) ]
[ "def", "_remove_dead_timers", "(", "self", ")", ":", "self", ".", "_futures", "=", "[", "timer", "for", "timer", "in", "self", ".", "_futures", "if", "not", "(", "timer", ".", "cancelled", "(", ")", "or", "timer", ".", "when", "(", ")", "<", "self", ...
https://github.com/qtile/qtile/blob/803dc06fc1f8b121a1d8fe047f26a43812cd427f/libqtile/widget/base.py#L332-L338
riptideio/pymodbus
c5772b35ae3f29d1947f3ab453d8d00df846459f
examples/tools/convert.py
python
ConversionException.__init__
(self, string)
Initialize a ConversionException instance :param string: Additional information to append to exception
Initialize a ConversionException instance
[ "Initialize", "a", "ConversionException", "instance" ]
def __init__(self, string): """ Initialize a ConversionException instance :param string: Additional information to append to exception """ Exception.__init__(self, string) self.string = string
[ "def", "__init__", "(", "self", ",", "string", ")", ":", "Exception", ".", "__init__", "(", "self", ",", "string", ")", "self", ".", "string", "=", "string" ]
https://github.com/riptideio/pymodbus/blob/c5772b35ae3f29d1947f3ab453d8d00df846459f/examples/tools/convert.py#L20-L26
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/np/npyfuncs.py
python
np_int_smax_impl
(context, builder, sig, args)
return builder.select(arg1_sge_arg2, arg1, arg2)
[]
def np_int_smax_impl(context, builder, sig, args): _check_arity_and_homogeneity(sig, args, 2) arg1, arg2 = args arg1_sge_arg2 = builder.icmp(lc.ICMP_SGE, arg1, arg2) return builder.select(arg1_sge_arg2, arg1, arg2)
[ "def", "np_int_smax_impl", "(", "context", ",", "builder", ",", "sig", ",", "args", ")", ":", "_check_arity_and_homogeneity", "(", "sig", ",", "args", ",", "2", ")", "arg1", ",", "arg2", "=", "args", "arg1_sge_arg2", "=", "builder", ".", "icmp", "(", "lc...
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/np/npyfuncs.py#L1327-L1331
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/compiler/transformer.py
python
Transformer.print_stmt
(self, nodelist)
return Printnl(items, dest, lineno=nodelist[0][2])
[]
def print_stmt(self, nodelist): # print ([ test (',' test)* [','] ] | '>>' test [ (',' test)+ [','] ]) items = [] if len(nodelist) == 1: start = 1 dest = None elif nodelist[1][0] == token.RIGHTSHIFT: assert len(nodelist) == 3 \ or nodelist[3][0] == token.COMMA dest = self.com_node(nodelist[2]) start = 4 else: dest = None start = 1 for i in range(start, len(nodelist), 2): items.append(self.com_node(nodelist[i])) if nodelist[-1][0] == token.COMMA: return Print(items, dest, lineno=nodelist[0][2]) return Printnl(items, dest, lineno=nodelist[0][2])
[ "def", "print_stmt", "(", "self", ",", "nodelist", ")", ":", "# print ([ test (',' test)* [','] ] | '>>' test [ (',' test)+ [','] ])", "items", "=", "[", "]", "if", "len", "(", "nodelist", ")", "==", "1", ":", "start", "=", "1", "dest", "=", "None", "elif", "n...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/compiler/transformer.py#L379-L397
pypa/bandersnatch
2e3eb53029ddb8f205f85242d724ae492040c1ce
src/bandersnatch_storage_plugins/filesystem.py
python
FilesystemStorage.mkdir
( self, path: PATH_TYPES, exist_ok: bool = False, parents: bool = False )
return path.mkdir(exist_ok=exist_ok, parents=parents)
Create the provided directory
Create the provided directory
[ "Create", "the", "provided", "directory" ]
def mkdir( self, path: PATH_TYPES, exist_ok: bool = False, parents: bool = False ) -> None: """Create the provided directory""" if not isinstance(path, pathlib.Path): path = pathlib.Path(path) return path.mkdir(exist_ok=exist_ok, parents=parents)
[ "def", "mkdir", "(", "self", ",", "path", ":", "PATH_TYPES", ",", "exist_ok", ":", "bool", "=", "False", ",", "parents", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "not", "isinstance", "(", "path", ",", "pathlib", ".", "Path", ")", ":...
https://github.com/pypa/bandersnatch/blob/2e3eb53029ddb8f205f85242d724ae492040c1ce/src/bandersnatch_storage_plugins/filesystem.py#L191-L197
sripathikrishnan/redis-rdb-tools
548b11ec3c81a603f5b321228d07a61a0b940159
rdbtools/parser.py
python
RdbParser.skip_stream
(self, f)
[]
def skip_stream(self, f): listpacks = self.read_length(f) for _lp in range(listpacks): self.skip_string(f) self.skip_string(f) self.read_length(f) self.read_length(f) self.read_length(f) cgroups = self.read_length(f) for _cg in range(cgroups): self.skip_string(f) self.read_length(f) self.read_length(f) pending = self.read_length(f) for _pel in range(pending): f.read(16) f.read(8) self.read_length(f) consumers = self.read_length(f) for _c in range(consumers): self.skip_string(f) f.read(8) pending = self.read_length(f) f.read(pending*16)
[ "def", "skip_stream", "(", "self", ",", "f", ")", ":", "listpacks", "=", "self", ".", "read_length", "(", "f", ")", "for", "_lp", "in", "range", "(", "listpacks", ")", ":", "self", ".", "skip_string", "(", "f", ")", "self", ".", "skip_string", "(", ...
https://github.com/sripathikrishnan/redis-rdb-tools/blob/548b11ec3c81a603f5b321228d07a61a0b940159/rdbtools/parser.py#L874-L897
microsoft/NimbusML
f6be39ce9359786976429bab0ccd837e849b4ba5
src/python/nimbusml/preprocessing/schema/columnconcatenator.py
python
ColumnConcatenator.get_params
(self, deep=False)
return core.get_params(self)
Get the parameters for this operator.
Get the parameters for this operator.
[ "Get", "the", "parameters", "for", "this", "operator", "." ]
def get_params(self, deep=False): """ Get the parameters for this operator. """ return core.get_params(self)
[ "def", "get_params", "(", "self", ",", "deep", "=", "False", ")", ":", "return", "core", ".", "get_params", "(", "self", ")" ]
https://github.com/microsoft/NimbusML/blob/f6be39ce9359786976429bab0ccd837e849b4ba5/src/python/nimbusml/preprocessing/schema/columnconcatenator.py#L83-L87
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/controllers/plugins/plugin.py
python
Plugin.kb_append
(self, location_a, location_b, info)
kb.kb.append a vulnerability to the KB
kb.kb.append a vulnerability to the KB
[ "kb", ".", "kb", ".", "append", "a", "vulnerability", "to", "the", "KB" ]
def kb_append(self, location_a, location_b, info): """ kb.kb.append a vulnerability to the KB """ kb.kb.append(location_a, location_b, info) om.out.report_finding(info)
[ "def", "kb_append", "(", "self", ",", "location_a", ",", "location_b", ",", "info", ")", ":", "kb", ".", "kb", ".", "append", "(", "location_a", ",", "location_b", ",", "info", ")", "om", ".", "out", ".", "report_finding", "(", "info", ")" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/controllers/plugins/plugin.py#L178-L183
siddharth-agrawal/Convolutional-Neural-Network
b06a04e7c33b8cb40116be0a8498bc59a78848fb
convolutionalNeuralNetwork.py
python
loadTrainingDataset
()
return [train_images, train_labels]
Loads the images and labels as numpy arrays The dataset is originally read as a dictionary
Loads the images and labels as numpy arrays The dataset is originally read as a dictionary
[ "Loads", "the", "images", "and", "labels", "as", "numpy", "arrays", "The", "dataset", "is", "originally", "read", "as", "a", "dictionary" ]
def loadTrainingDataset(): """ Loads the images and labels as numpy arrays The dataset is originally read as a dictionary """ train_data = scipy.io.loadmat('stlTrainSubset.mat') train_images = numpy.array(train_data['trainImages']) train_labels = numpy.array(train_data['trainLabels']) return [train_images, train_labels]
[ "def", "loadTrainingDataset", "(", ")", ":", "train_data", "=", "scipy", ".", "io", ".", "loadmat", "(", "'stlTrainSubset.mat'", ")", "train_images", "=", "numpy", ".", "array", "(", "train_data", "[", "'trainImages'", "]", ")", "train_labels", "=", "numpy", ...
https://github.com/siddharth-agrawal/Convolutional-Neural-Network/blob/b06a04e7c33b8cb40116be0a8498bc59a78848fb/convolutionalNeuralNetwork.py#L233-L242
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/boto/cloudsearch/layer1.py
python
Layer1.update_service_access_policies
(self, domain_name, access_policies)
return self.get_response(doc_path, 'UpdateServiceAccessPolicies', params, verb='POST')
Updates the policies controlling access to the services in this search domain. :type domain_name: string :param domain_name: A string that represents the name of a domain. Domain names must be unique across the domains owned by an account within an AWS region. Domain names must start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase letters and underscores are not allowed. :type access_policies: string :param access_policies: An IAM access policy as described in The Access Policy Language in Using AWS Identity and Access Management. The maximum size of an access policy document is 100KB. :raises: BaseException, InternalException, LimitExceededException, ResourceNotFoundException, InvalidTypeException
Updates the policies controlling access to the services in this search domain.
[ "Updates", "the", "policies", "controlling", "access", "to", "the", "services", "in", "this", "search", "domain", "." ]
def update_service_access_policies(self, domain_name, access_policies): """ Updates the policies controlling access to the services in this search domain. :type domain_name: string :param domain_name: A string that represents the name of a domain. Domain names must be unique across the domains owned by an account within an AWS region. Domain names must start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase letters and underscores are not allowed. :type access_policies: string :param access_policies: An IAM access policy as described in The Access Policy Language in Using AWS Identity and Access Management. The maximum size of an access policy document is 100KB. :raises: BaseException, InternalException, LimitExceededException, ResourceNotFoundException, InvalidTypeException """ doc_path = ('update_service_access_policies_response', 'update_service_access_policies_result', 'access_policies') params = {'AccessPolicies': access_policies, 'DomainName': domain_name} return self.get_response(doc_path, 'UpdateServiceAccessPolicies', params, verb='POST')
[ "def", "update_service_access_policies", "(", "self", ",", "domain_name", ",", "access_policies", ")", ":", "doc_path", "=", "(", "'update_service_access_policies_response'", ",", "'update_service_access_policies_result'", ",", "'access_policies'", ")", "params", "=", "{", ...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/boto/cloudsearch/layer1.py#L625-L654
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/utilities/debug_prefs.py
python
iconset_from_color
(color)
return iconset
Return a QIcon suitable for showing the given color in a menu item or (###k untested, unreviewed) some other widget. The color can be a QColor or any python type we use for colors (out of the few our helper funcs understand).
Return a QIcon suitable for showing the given color in a menu item or (###k untested, unreviewed) some other widget. The color can be a QColor or any python type we use for colors (out of the few our helper funcs understand).
[ "Return", "a", "QIcon", "suitable", "for", "showing", "the", "given", "color", "in", "a", "menu", "item", "or", "(", "###k", "untested", "unreviewed", ")", "some", "other", "widget", ".", "The", "color", "can", "be", "a", "QColor", "or", "any", "python",...
def iconset_from_color(color): """ Return a QIcon suitable for showing the given color in a menu item or (###k untested, unreviewed) some other widget. The color can be a QColor or any python type we use for colors (out of the few our helper funcs understand). """ # figure out desired size of a small icon from PyQt4.Qt import QIcon #size = QIcon.iconSize(QIcon.Small) # a QSize object #w, h = size.width(), size.height() w, h = 16, 16 # hardwire it and be done # get pixmap of that color pixmap = pixmap_from_color_and_size( color, (w,h) ) # for now, let Qt figure out the Active appearance, etc. Later we can draw our own black outline, or so. ##e iconset = QIcon(pixmap) checkmark = ("checkmark" == debug_pref("color checkmark", Choice(["checkmark","box"]))) modify_iconset_On_states( iconset, color = color, checkmark = checkmark ) return iconset
[ "def", "iconset_from_color", "(", "color", ")", ":", "# figure out desired size of a small icon", "from", "PyQt4", ".", "Qt", "import", "QIcon", "#size = QIcon.iconSize(QIcon.Small) # a QSize object", "#w, h = size.width(), size.height()", "w", ",", "h", "=", "16", ",", "16...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/utilities/debug_prefs.py#L526-L543
lilydjwg/winterpy
3864a463386202b9c9c6ce8ba902878e40f3084c
pylib/lilypath.py
python
path.open
(self, mode='r', buffering=2, encoding=None, errors=None, newline=None, closefd=True)
return open(self.value, mode, buffering, encoding, errors, newline, closefd)
打开该文件
打开该文件
[ "打开该文件" ]
def open(self, mode='r', buffering=2, encoding=None, errors=None, newline=None, closefd=True): '''打开该文件''' #XXX 文档说buffering默认值为 None,但事实并非如此。使用full buffering好了 return open(self.value, mode, buffering, encoding, errors, newline, closefd)
[ "def", "open", "(", "self", ",", "mode", "=", "'r'", ",", "buffering", "=", "2", ",", "encoding", "=", "None", ",", "errors", "=", "None", ",", "newline", "=", "None", ",", "closefd", "=", "True", ")", ":", "#XXX 文档说buffering默认值为 None,但事实并非如此。使用full buffer...
https://github.com/lilydjwg/winterpy/blob/3864a463386202b9c9c6ce8ba902878e40f3084c/pylib/lilypath.py#L276-L280
yihui-he/KL-Loss
66c0ed9e886a2218f4cf88c0efd4f40199bff54a
detectron/core/config.py
python
get_output_dir
(datasets, training=True)
return outdir
Get the output directory determined by the current global config.
Get the output directory determined by the current global config.
[ "Get", "the", "output", "directory", "determined", "by", "the", "current", "global", "config", "." ]
def get_output_dir(datasets, training=True): """Get the output directory determined by the current global config.""" assert isinstance(datasets, tuple([tuple, list] + list(six.string_types))), \ 'datasets argument must be of type tuple, list or string' is_string = isinstance(datasets, six.string_types) dataset_name = datasets if is_string else ':'.join(datasets) tag = 'train' if training else 'test' # <output-dir>/<train|test>/<dataset-name>/<model-type>/ outdir = osp.join(__C.OUTPUT_DIR, tag, dataset_name, __C.MODEL.TYPE) if not osp.exists(outdir): os.makedirs(outdir) return outdir
[ "def", "get_output_dir", "(", "datasets", ",", "training", "=", "True", ")", ":", "assert", "isinstance", "(", "datasets", ",", "tuple", "(", "[", "tuple", ",", "list", "]", "+", "list", "(", "six", ".", "string_types", ")", ")", ")", ",", "'datasets a...
https://github.com/yihui-he/KL-Loss/blob/66c0ed9e886a2218f4cf88c0efd4f40199bff54a/detectron/core/config.py#L1113-L1124
seopbo/nlp_classification
21ea6e3f5737e7074bdd8dd190e5f5172f86f6bf
A_Structured_Self-attentive_Sentence_Embedding_ptc/model/utils.py
python
PadSequence.__call__
(self, sample)
[]
def __call__(self, sample): sample_length = len(sample) if sample_length >= self._length: if self._clip and sample_length > self._length: return sample[: self._length] else: return sample else: return sample + [self._pad_val for _ in range(self._length - sample_length)]
[ "def", "__call__", "(", "self", ",", "sample", ")", ":", "sample_length", "=", "len", "(", "sample", ")", "if", "sample_length", ">=", "self", ".", "_length", ":", "if", "self", ".", "_clip", "and", "sample_length", ">", "self", ".", "_length", ":", "r...
https://github.com/seopbo/nlp_classification/blob/21ea6e3f5737e7074bdd8dd190e5f5172f86f6bf/A_Structured_Self-attentive_Sentence_Embedding_ptc/model/utils.py#L218-L226
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idc.py
python
GuessType
(ea)
return idaapi.idc_guess_type(ea)
Guess type of function/variable @param ea: the address of the object, can be the structure member id too @return: type string or None if failed
Guess type of function/variable
[ "Guess", "type", "of", "function", "/", "variable" ]
def GuessType(ea): """ Guess type of function/variable @param ea: the address of the object, can be the structure member id too @return: type string or None if failed """ return idaapi.idc_guess_type(ea)
[ "def", "GuessType", "(", "ea", ")", ":", "return", "idaapi", ".", "idc_guess_type", "(", "ea", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idc.py#L6889-L6897
Altinity/clickhouse-mysql-data-reader
3b1b7088751b05e5bbf45890c5949b58208c2343
clickhouse_mysql/pumper.py
python
Pumper.write_rows_event_each_row
(self, event=None)
WriteRowsEvent.EachRow handler :param event:
WriteRowsEvent.EachRow handler :param event:
[ "WriteRowsEvent", ".", "EachRow", "handler", ":", "param", "event", ":" ]
def write_rows_event_each_row(self, event=None): """ WriteRowsEvent.EachRow handler :param event: """ self.writer.insert(event)
[ "def", "write_rows_event_each_row", "(", "self", ",", "event", "=", "None", ")", ":", "self", ".", "writer", ".", "insert", "(", "event", ")" ]
https://github.com/Altinity/clickhouse-mysql-data-reader/blob/3b1b7088751b05e5bbf45890c5949b58208c2343/clickhouse_mysql/pumper.py#L36-L41
mbj4668/pyang
97523476e7ada8609d27fd47880e1b5061073dc3
pyang/repository.py
python
FileRepository.__init__
(self, path="", use_env=True, no_path_recurse=False, verbose=False)
Create a Repository which searches the filesystem for modules `path` is a `os.pathsep`-separated string of directories
Create a Repository which searches the filesystem for modules
[ "Create", "a", "Repository", "which", "searches", "the", "filesystem", "for", "modules" ]
def __init__(self, path="", use_env=True, no_path_recurse=False, verbose=False): """Create a Repository which searches the filesystem for modules `path` is a `os.pathsep`-separated string of directories """ Repository.__init__(self) self.dirs = [] self.no_path_recurse = no_path_recurse self.modules = None self.verbose = verbose for directory in path.split(os.pathsep): self._add_directory(directory) while use_env: use_env = False modpath = os.getenv('YANG_MODPATH') if modpath is not None: for directory in modpath.split(os.pathsep): self._add_directory(directory) home = os.getenv('HOME') if home is not None: self._add_directory(os.path.join(home, 'yang', 'modules')) inst = os.getenv('YANG_INSTALL') if inst is not None: self._add_directory(os.path.join(inst, 'yang', 'modules')) break # skip search if install location is indicated default_install = os.path.join( sys.prefix, 'share', 'yang', 'modules') if os.path.exists(default_install): self._add_directory(default_install) break # end search if default location exists # for some systems, sys.prefix returns `/usr` # but the real location is `/usr/local` # if the package is installed with pip # this information can be easily retrieved import pkgutil if not pkgutil.find_loader('pip'): break # abort search if pip is not installed # hack below to handle pip 10 internals # if someone knows pip and how to fix this, it would be great! location = None try: import pip.locations as locations location = locations.distutils_scheme('pyang') except: try: import pip._internal.locations as locations location = locations.distutils_scheme('pyang') except: pass if location is not None: self._add_directory( os.path.join(location['data'], 'share', 'yang', 'modules')) if verbose: sys.stderr.write('# module search path: %s\n' % os.pathsep.join(self.dirs))
[ "def", "__init__", "(", "self", ",", "path", "=", "\"\"", ",", "use_env", "=", "True", ",", "no_path_recurse", "=", "False", ",", "verbose", "=", "False", ")", ":", "Repository", ".", "__init__", "(", "self", ")", "self", ".", "dirs", "=", "[", "]", ...
https://github.com/mbj4668/pyang/blob/97523476e7ada8609d27fd47880e1b5061073dc3/pyang/repository.py#L38-L102
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1beta1_endpoint_slice_list.py
python
V1beta1EndpointSliceList.kind
(self, kind)
Sets the kind of this V1beta1EndpointSliceList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1beta1EndpointSliceList. # noqa: E501 :type: str
Sets the kind of this V1beta1EndpointSliceList.
[ "Sets", "the", "kind", "of", "this", "V1beta1EndpointSliceList", "." ]
def kind(self, kind): """Sets the kind of this V1beta1EndpointSliceList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1beta1EndpointSliceList. # noqa: E501 :type: str """ self._kind = kind
[ "def", "kind", "(", "self", ",", "kind", ")", ":", "self", ".", "_kind", "=", "kind" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1beta1_endpoint_slice_list.py#L129-L138
duo-labs/isthislegit
5d51fd2e0fe070cacd1ee169ca8a371a72e005ef
dashboard/lib/flanker/mime/message/fallback/part.py
python
FallbackMimePart.was_changed
(self)
return False
[]
def was_changed(self): return False
[ "def", "was_changed", "(", "self", ")", ":", "return", "False" ]
https://github.com/duo-labs/isthislegit/blob/5d51fd2e0fe070cacd1ee169ca8a371a72e005ef/dashboard/lib/flanker/mime/message/fallback/part.py#L91-L92
deepgully/me
f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0
libs/flask_sqlalchemy.py
python
SQLAlchemy.apply_driver_hacks
(self, app, info, options)
This method is called before engine creation and used to inject driver specific hacks into the options. The `options` parameter is a dictionary of keyword arguments that will then be used to call the :func:`sqlalchemy.create_engine` function. The default implementation provides some saner defaults for things like pool sizes for MySQL and sqlite. Also it injects the setting of `SQLALCHEMY_NATIVE_UNICODE`.
This method is called before engine creation and used to inject driver specific hacks into the options. The `options` parameter is a dictionary of keyword arguments that will then be used to call the :func:`sqlalchemy.create_engine` function.
[ "This", "method", "is", "called", "before", "engine", "creation", "and", "used", "to", "inject", "driver", "specific", "hacks", "into", "the", "options", ".", "The", "options", "parameter", "is", "a", "dictionary", "of", "keyword", "arguments", "that", "will",...
def apply_driver_hacks(self, app, info, options): """This method is called before engine creation and used to inject driver specific hacks into the options. The `options` parameter is a dictionary of keyword arguments that will then be used to call the :func:`sqlalchemy.create_engine` function. The default implementation provides some saner defaults for things like pool sizes for MySQL and sqlite. Also it injects the setting of `SQLALCHEMY_NATIVE_UNICODE`. """ if info.drivername == 'mysql': info.query.setdefault('charset', 'utf8') options.setdefault('pool_size', 10) options.setdefault('pool_recycle', 7200) elif info.drivername == 'sqlite': pool_size = options.get('pool_size') detected_in_memory = False # we go to memory and the pool size was explicitly set to 0 # which is fail. Let the user know that if info.database in (None, '', ':memory:'): detected_in_memory = True if pool_size == 0: raise RuntimeError('SQLite in memory database with an ' 'empty queue not possible due to data ' 'loss.') # if pool size is None or explicitly set to 0 we assume the # user did not want a queue for this sqlite connection and # hook in the null pool. elif not pool_size: from sqlalchemy.pool import NullPool options['poolclass'] = NullPool # if it's not an in memory database we make the path absolute. if not detected_in_memory: info.database = os.path.join(app.root_path, info.database) unu = app.config['SQLALCHEMY_NATIVE_UNICODE'] if unu is None: unu = self.use_native_unicode if not unu: options['use_native_unicode'] = False
[ "def", "apply_driver_hacks", "(", "self", ",", "app", ",", "info", ",", "options", ")", ":", "if", "info", ".", "drivername", "==", "'mysql'", ":", "info", ".", "query", ".", "setdefault", "(", "'charset'", ",", "'utf8'", ")", "options", ".", "setdefault...
https://github.com/deepgully/me/blob/f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0/libs/flask_sqlalchemy.py#L696-L736
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/concurrent/futures/_base.py
python
Executor.submit
(self, fn, *args, **kwargs)
Submits a callable to be executed with the given arguments. Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable. Returns: A Future representing the given call.
Submits a callable to be executed with the given arguments.
[ "Submits", "a", "callable", "to", "be", "executed", "with", "the", "given", "arguments", "." ]
def submit(self, fn, *args, **kwargs): """Submits a callable to be executed with the given arguments. Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable. Returns: A Future representing the given call. """ raise NotImplementedError()
[ "def", "submit", "(", "self", ",", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/concurrent/futures/_base.py#L512-L521
ladybug-tools/honeybee-legacy
bd62af4862fe022801fb87dbc8794fdf1dff73a9
src/Honeybee_Export To OpenStudio.py
python
WriteOPS.updateDXCoolingCoil
(self, model, coolCoil, coolingAvailSched, coolingCOP)
[]
def updateDXCoolingCoil(self, model, coolCoil, coolingAvailSched, coolingCOP): if coolingAvailSched != 'ALWAYS ON': coolAvailSch = self.getOSSchedule(coolingAvailSched, model) coolCoil.setAvailabilitySchedule(coolAvailSch) if coolingCOP != 'Default': coolCoil.setRatedCOP(ops.OptionalDouble(coolingCOP))
[ "def", "updateDXCoolingCoil", "(", "self", ",", "model", ",", "coolCoil", ",", "coolingAvailSched", ",", "coolingCOP", ")", ":", "if", "coolingAvailSched", "!=", "'ALWAYS ON'", ":", "coolAvailSch", "=", "self", ".", "getOSSchedule", "(", "coolingAvailSched", ",", ...
https://github.com/ladybug-tools/honeybee-legacy/blob/bd62af4862fe022801fb87dbc8794fdf1dff73a9/src/Honeybee_Export To OpenStudio.py#L2106-L2111
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/fillet.py
python
getNewRepository
()
return FilletRepository()
Get new repository.
Get new repository.
[ "Get", "new", "repository", "." ]
def getNewRepository(): 'Get new repository.' return FilletRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "FilletRepository", "(", ")" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/fillet.py#L106-L108
Unidata/siphon
d8ede355114801bf7a05db20dfe49ab132723f86
src/siphon/simplewebservice/ndbc.py
python
NDBC.realtime_observations
(cls, buoy, data_type='txt')
return parsers[data_type](raw_data)
Retrieve the realtime buoy data from NDBC. Parameters ---------- buoy : str Name of buoy data_type : str Type of data requested, must be one of 'txt' standard meteorological data 'drift' meteorological data from drifting buoys and limited moored buoy data mainly from international partners 'cwind' continuous winds data (10 minute average) 'spec' spectral wave summaries 'ocean' oceanographic data 'srad' solar radiation data 'dart' water column height 'supl' supplemental measurements data 'rain' hourly rain data Returns ------- Raw data string
Retrieve the realtime buoy data from NDBC.
[ "Retrieve", "the", "realtime", "buoy", "data", "from", "NDBC", "." ]
def realtime_observations(cls, buoy, data_type='txt'): """Retrieve the realtime buoy data from NDBC. Parameters ---------- buoy : str Name of buoy data_type : str Type of data requested, must be one of 'txt' standard meteorological data 'drift' meteorological data from drifting buoys and limited moored buoy data mainly from international partners 'cwind' continuous winds data (10 minute average) 'spec' spectral wave summaries 'ocean' oceanographic data 'srad' solar radiation data 'dart' water column height 'supl' supplemental measurements data 'rain' hourly rain data Returns ------- Raw data string """ endpoint = cls() parsers = {'txt': endpoint._parse_met, 'drift': endpoint._parse_drift, 'cwind': endpoint._parse_cwind, 'spec': endpoint._parse_spec, 'ocean': endpoint._parse_ocean, 'srad': endpoint._parse_srad, 'dart': endpoint._parse_dart, 'supl': endpoint._parse_supl, 'rain': endpoint._parse_rain} if data_type not in parsers: raise KeyError('Data type must be txt, drift, cwind, spec, ocean, srad, dart,' 'supl, or rain for parsed realtime data.') raw_data = endpoint.raw_buoy_data(buoy, data_type=data_type) return parsers[data_type](raw_data)
[ "def", "realtime_observations", "(", "cls", ",", "buoy", ",", "data_type", "=", "'txt'", ")", ":", "endpoint", "=", "cls", "(", ")", "parsers", "=", "{", "'txt'", ":", "endpoint", ".", "_parse_met", ",", "'drift'", ":", "endpoint", ".", "_parse_drift", "...
https://github.com/Unidata/siphon/blob/d8ede355114801bf7a05db20dfe49ab132723f86/src/siphon/simplewebservice/ndbc.py#L26-L67
pytroll/satpy
09e51f932048f98cce7919a4ff8bd2ec01e1ae98
satpy/dataset/data_dict.py
python
DatasetDict.get
(self, key, default=None)
return super(DatasetDict, self).get(key, default)
Get value with optional default.
Get value with optional default.
[ "Get", "value", "with", "optional", "default", "." ]
def get(self, key, default=None): """Get value with optional default.""" try: key = self.get_key(key) except KeyError: return default return super(DatasetDict, self).get(key, default)
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "key", "=", "self", ".", "get_key", "(", "key", ")", "except", "KeyError", ":", "return", "default", "return", "super", "(", "DatasetDict", ",", "self", ")", ...
https://github.com/pytroll/satpy/blob/09e51f932048f98cce7919a4ff8bd2ec01e1ae98/satpy/dataset/data_dict.py#L174-L180
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
docs/refman/main.py
python
main
()
return 0
[]
def main() -> int: parser = argparse.ArgumentParser(description='Meson reference manual generator') parser.add_argument('-l', '--loader', type=str, default='yaml', choices=['yaml', 'pickle'], help='Information loader backend') parser.add_argument('-g', '--generator', type=str, choices=['print', 'pickle', 'md', 'json', 'man'], required=True, help='Generator backend') parser.add_argument('-s', '--sitemap', type=Path, default=meson_root / 'docs' / 'sitemap.txt', help='Path to the input sitemap.txt') parser.add_argument('-o', '--out', type=Path, required=True, help='Output directory for generated files') parser.add_argument('-i', '--input', type=Path, default=meson_root / 'docs' / 'yaml', help='Input path for the selected loader') parser.add_argument('--link-defs', type=Path, help='Output file for the MD generator link definition file') parser.add_argument('--depfile', type=Path, default=None, help='Set to generate a depfile') parser.add_argument('--force-color', action='store_true', help='Force enable colors') parser.add_argument('--no-modules', action='store_true', help='Disable building modules') args = parser.parse_args() if args.force_color: mlog.colorize_console = lambda: True loaders: T.Dict[str, T.Callable[[], LoaderBase]] = { 'yaml': lambda: LoaderYAML(args.input), 'pickle': lambda: LoaderPickle(args.input), } loader = loaders[args.loader]() refMan = loader.load() generators: T.Dict[str, T.Callable[[], GeneratorBase]] = { 'print': lambda: GeneratorPrint(refMan), 'pickle': lambda: GeneratorPickle(refMan, args.out), 'md': lambda: GeneratorMD(refMan, args.out, args.sitemap, args.link_defs, not args.no_modules), 'json': lambda: GeneratorJSON(refMan, args.out, not args.no_modules), 'man': lambda: GeneratorMan(refMan, args.out, not args.no_modules), } generator = generators[args.generator]() # Generate the depfile if required if args.depfile is not None: assert isinstance(args.depfile, Path) assert isinstance(args.out, Path) # Also add all files of this package script_files = list(Path(__file__).resolve().parent.glob('**/*.py')) templates = list(Path(__file__).resolve().parent.glob('**/*.mustache')) out_text = f'{args.out.resolve().as_posix()}: \\\n' for input in loader.input_files + script_files + templates: out_text += f' {input.resolve().as_posix():<93} \\\n' args.depfile.write_text(out_text, encoding='utf-8') generator.generate() return 0
[ "def", "main", "(", ")", "->", "int", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Meson reference manual generator'", ")", "parser", ".", "add_argument", "(", "'-l'", ",", "'--loader'", ",", "type", "=", "str", ",", "def...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/docs/refman/main.py#L34-L83
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/setuptools/_vendor/pyparsing.py
python
pyparsing_common.stripHTMLTags
(s, l, tokens)
return pyparsing_common._html_stripper.transformString(tokens[0])
Parse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>' td,td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page'
Parse action to remove HTML tags from web page HTML source
[ "Parse", "action", "to", "remove", "HTML", "tags", "from", "web", "page", "HTML", "source" ]
def stripHTMLTags(s, l, tokens): """ Parse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>' td,td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page' """ return pyparsing_common._html_stripper.transformString(tokens[0])
[ "def", "stripHTMLTags", "(", "s", ",", "l", ",", "tokens", ")", ":", "return", "pyparsing_common", ".", "_html_stripper", ".", "transformString", "(", "tokens", "[", "0", "]", ")" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/setuptools/_vendor/pyparsing.py#L5647-L5659
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/vsm/vsm/api/v1/agents.py
python
AgentsController._write_zone_info
(self)
return True
Write zone into DB. Zone list: zone_a zone_b zone_c Just write names here.
Write zone into DB.
[ "Write", "zone", "into", "DB", "." ]
def _write_zone_info(self): """Write zone into DB. Zone list: zone_a zone_b zone_c Just write names here. """ #TODO add zone table two variables. cluster_id, storage_group_id. zone_list = self._cluster_info['zone'] for zone_name in zone_list: zone_ref = db.\ zone_get_by_name(self._context, zone_name) if not zone_ref: LOG.info('Have not find zone = %s' % zone_name) db.zone_create(self._context, {'name': zone_name, 'deleted': False}) else: LOG.info('Find zone = %s in zone Table.' % zone_name) return True
[ "def", "_write_zone_info", "(", "self", ")", ":", "#TODO add zone table two variables. cluster_id, storage_group_id.", "zone_list", "=", "self", ".", "_cluster_info", "[", "'zone'", "]", "for", "zone_name", "in", "zone_list", ":", "zone_ref", "=", "db", ".", "zone_get...
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/api/v1/agents.py#L178-L200
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/mako/runtime.py
python
Context.pop_caller
(self)
Pop a ``caller`` callable onto the callstack for this :class:`.Context`.
Pop a ``caller`` callable onto the callstack for this :class:`.Context`.
[ "Pop", "a", "caller", "callable", "onto", "the", "callstack", "for", "this", ":", "class", ":", ".", "Context", "." ]
def pop_caller(self): """Pop a ``caller`` callable onto the callstack for this :class:`.Context`.""" del self.caller_stack[-1]
[ "def", "pop_caller", "(", "self", ")", ":", "del", "self", ".", "caller_stack", "[", "-", "1", "]" ]
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/mako/runtime.py#L86-L90
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
libs/requests/packages/urllib3/__init__.py
python
disable_warnings
(category=exceptions.HTTPWarning)
Helper for quickly disabling all urllib3 warnings.
Helper for quickly disabling all urllib3 warnings.
[ "Helper", "for", "quickly", "disabling", "all", "urllib3", "warnings", "." ]
def disable_warnings(category=exceptions.HTTPWarning): """ Helper for quickly disabling all urllib3 warnings. """ warnings.simplefilter('ignore', category)
[ "def", "disable_warnings", "(", "category", "=", "exceptions", ".", "HTTPWarning", ")", ":", "warnings", ".", "simplefilter", "(", "'ignore'", ",", "category", ")" ]
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/requests/packages/urllib3/__init__.py#L65-L69
onnx/onnx-tensorflow
6194294c9f2f1c9270a614f6ae5078f2095587b7
onnx_tf/handlers/backend/dilated_pooling.py
python
DilatedPooling._calc_argmax_without_padding
(self, ind)
return new_ind
Calculate the original indices as they would be without padding
Calculate the original indices as they would be without padding
[ "Calculate", "the", "original", "indices", "as", "they", "would", "be", "without", "padding" ]
def _calc_argmax_without_padding(self, ind): """ Calculate the original indices as they would be without padding """ in_width = self.orig_input_shape[3] padded_width = self.input_shape[3] num_channels = self.input_shape[1] # mod_floor op is not implemented on GPU # implement it using: a % b = a - (a // b) * b # ind_nhw = ind // num_channels # ind_channel = ind % num_channels ind_nhw = ind // num_channels ind_channel = ind - ind_nhw * num_channels new_ind = (ind_nhw // padded_width) * (self.pads[2] + self.pads[3]) new_ind = ind_nhw - new_ind - self.pads[0] * in_width - self.pads[2] new_ind = num_channels * new_ind + ind_channel return new_ind
[ "def", "_calc_argmax_without_padding", "(", "self", ",", "ind", ")", ":", "in_width", "=", "self", ".", "orig_input_shape", "[", "3", "]", "padded_width", "=", "self", ".", "input_shape", "[", "3", "]", "num_channels", "=", "self", ".", "input_shape", "[", ...
https://github.com/onnx/onnx-tensorflow/blob/6194294c9f2f1c9270a614f6ae5078f2095587b7/onnx_tf/handlers/backend/dilated_pooling.py#L522-L542
PINTO0309/PINTO_model_zoo
2924acda7a7d541d8712efd7cc4fd1c61ef5bddd
024_yolov3-lite/utils/data.py
python
Data.__create_label
(self, bboxes)
return label_sbbox, label_mbbox, label_lbbox, sbboxes, mbboxes, lbboxes
:param bboxes: 一张图对应的所有bbox和每个bbox所属的类别,以及mixup的权重, bbox的坐标为(xmin, ymin, xmax, ymax, class_ind, mixup_weight) :return: label_sbbox: shape为(input_size / 8, input_size / 8, anchor_per_scale, 6 + num_classes) label_mbbox: shape为(input_size / 16, input_size / 16, anchor_per_scale, 6 + num_classes) label_lbbox: shape为(input_size / 32, input_size / 32, anchor_per_scale, 6 + num_classes) 只要某个GT落入grid中,那么这个grid就负责预测它,最多负责预测gt_per_grid个GT, 那么该grid中对应位置的数据为(xmin, ymin, xmax, ymax, 1, classes, mixup_weights), 其他grid对应位置的数据都为(0, 0, 0, 0, 0, 0..., 1) sbboxes:shape为(max_bbox_per_scale, 4) mbboxes:shape为(max_bbox_per_scale, 4) lbboxes:shape为(max_bbox_per_scale, 4) 存储的坐标为(xmin, ymin, xmax, ymax),大小都是bbox纠正后的原始大小
:param bboxes: 一张图对应的所有bbox和每个bbox所属的类别,以及mixup的权重, bbox的坐标为(xmin, ymin, xmax, ymax, class_ind, mixup_weight) :return: label_sbbox: shape为(input_size / 8, input_size / 8, anchor_per_scale, 6 + num_classes) label_mbbox: shape为(input_size / 16, input_size / 16, anchor_per_scale, 6 + num_classes) label_lbbox: shape为(input_size / 32, input_size / 32, anchor_per_scale, 6 + num_classes) 只要某个GT落入grid中,那么这个grid就负责预测它,最多负责预测gt_per_grid个GT, 那么该grid中对应位置的数据为(xmin, ymin, xmax, ymax, 1, classes, mixup_weights), 其他grid对应位置的数据都为(0, 0, 0, 0, 0, 0..., 1) sbboxes:shape为(max_bbox_per_scale, 4) mbboxes:shape为(max_bbox_per_scale, 4) lbboxes:shape为(max_bbox_per_scale, 4) 存储的坐标为(xmin, ymin, xmax, ymax),大小都是bbox纠正后的原始大小
[ ":", "param", "bboxes", ":", "一张图对应的所有bbox和每个bbox所属的类别,以及mixup的权重,", "bbox的坐标为", "(", "xmin", "ymin", "xmax", "ymax", "class_ind", "mixup_weight", ")", ":", "return", ":", "label_sbbox", ":", "shape为", "(", "input_size", "/", "8", "input_size", "/", "8", "anchor...
def __create_label(self, bboxes): """ :param bboxes: 一张图对应的所有bbox和每个bbox所属的类别,以及mixup的权重, bbox的坐标为(xmin, ymin, xmax, ymax, class_ind, mixup_weight) :return: label_sbbox: shape为(input_size / 8, input_size / 8, anchor_per_scale, 6 + num_classes) label_mbbox: shape为(input_size / 16, input_size / 16, anchor_per_scale, 6 + num_classes) label_lbbox: shape为(input_size / 32, input_size / 32, anchor_per_scale, 6 + num_classes) 只要某个GT落入grid中,那么这个grid就负责预测它,最多负责预测gt_per_grid个GT, 那么该grid中对应位置的数据为(xmin, ymin, xmax, ymax, 1, classes, mixup_weights), 其他grid对应位置的数据都为(0, 0, 0, 0, 0, 0..., 1) sbboxes:shape为(max_bbox_per_scale, 4) mbboxes:shape为(max_bbox_per_scale, 4) lbboxes:shape为(max_bbox_per_scale, 4) 存储的坐标为(xmin, ymin, xmax, ymax),大小都是bbox纠正后的原始大小 """ label = [np.zeros((self.__train_output_sizes[i], self.__train_output_sizes[i], self.__gt_per_grid, 6 + self.__num_classes)) for i in range(3)] # mixup weight位默认为1.0 for i in range(3): label[i][:, :, :, -1] = 1.0 bboxes_coor = [[] for _ in range(3)] bboxes_count = [np.zeros((self.__train_output_sizes[i], self.__train_output_sizes[i])) for i in range(3)] for bbox in bboxes: # (1)获取bbox在原图上的顶点坐标、类别索引、mix up权重、中心坐标、高宽、尺度 bbox_coor = bbox[:4] bbox_class_ind = int(bbox[4]) bbox_mixw = bbox[5] bbox_xywh = np.concatenate([(bbox_coor[2:] + bbox_coor[:2]) * 0.5, bbox_coor[2:] - bbox_coor[:2]], axis=-1) bbox_scale = np.sqrt(np.multiply.reduce(bbox_xywh[2:])) # label smooth onehot = np.zeros(self.__num_classes, dtype=np.float) onehot[bbox_class_ind] = 1.0 uniform_distribution = np.full(self.__num_classes, 1.0 / self.__num_classes) deta = 0.01 smooth_onehot = onehot * (1 - deta) + deta * uniform_distribution if bbox_scale <= 30: match_branch = 0 elif (30 < bbox_scale) and (bbox_scale <= 90): match_branch = 1 else: match_branch = 2 xind, yind = np.floor(1.0 * bbox_xywh[:2] / self.__strides[match_branch]).astype(np.int32) gt_count = int(bboxes_count[match_branch][yind, xind]) if gt_count < self.__gt_per_grid: if gt_count == 0: gt_count = slice(None) bbox_label = np.concatenate([bbox_coor, [1.0], smooth_onehot, [bbox_mixw]], axis=-1) label[match_branch][yind, xind, gt_count, :] = 0 label[match_branch][yind, xind, gt_count, :] = bbox_label bboxes_count[match_branch][yind, xind] += 1 bboxes_coor[match_branch].append(bbox_coor) label_sbbox, label_mbbox, label_lbbox = label sbboxes, mbboxes, lbboxes = bboxes_coor return label_sbbox, label_mbbox, label_lbbox, sbboxes, mbboxes, lbboxes
[ "def", "__create_label", "(", "self", ",", "bboxes", ")", ":", "label", "=", "[", "np", ".", "zeros", "(", "(", "self", ".", "__train_output_sizes", "[", "i", "]", ",", "self", ".", "__train_output_sizes", "[", "i", "]", ",", "self", ".", "__gt_per_gri...
https://github.com/PINTO0309/PINTO_model_zoo/blob/2924acda7a7d541d8712efd7cc4fd1c61ef5bddd/024_yolov3-lite/utils/data.py#L192-L251
Hellowlol/bw_plex
86768d6ee89ee1c08d2f6e6468976e4c51135915
bw_plex/audfprint/hash_table.py
python
HashTable.totalhashes
(self)
return np.sum(self.counts)
Return the total count of hashes stored in the table
Return the total count of hashes stored in the table
[ "Return", "the", "total", "count", "of", "hashes", "stored", "in", "the", "table" ]
def totalhashes(self): """ Return the total count of hashes stored in the table """ return np.sum(self.counts)
[ "def", "totalhashes", "(", "self", ")", ":", "return", "np", ".", "sum", "(", "self", ".", "counts", ")" ]
https://github.com/Hellowlol/bw_plex/blob/86768d6ee89ee1c08d2f6e6468976e4c51135915/bw_plex/audfprint/hash_table.py#L296-L298
lsbardel/python-stdnet
78db5320bdedc3f28c5e4f38cda13a4469e35db7
stdnet/odm/query.py
python
get_lookups
(attname, field_lookups)
return lookups
[]
def get_lookups(attname, field_lookups): lookups = field_lookups.get(attname) if lookups is None: lookups = [] field_lookups[attname] = lookups return lookups
[ "def", "get_lookups", "(", "attname", ",", "field_lookups", ")", ":", "lookups", "=", "field_lookups", ".", "get", "(", "attname", ")", "if", "lookups", "is", "None", ":", "lookups", "=", "[", "]", "field_lookups", "[", "attname", "]", "=", "lookups", "r...
https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/odm/query.py#L37-L42
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/weakref.py
python
finalize.__call__
(self, _=None)
If alive then mark as dead and return func(*args, **kwargs); otherwise return None
If alive then mark as dead and return func(*args, **kwargs); otherwise return None
[ "If", "alive", "then", "mark", "as", "dead", "and", "return", "func", "(", "*", "args", "**", "kwargs", ")", ";", "otherwise", "return", "None" ]
def __call__(self, _=None): """If alive then mark as dead and return func(*args, **kwargs); otherwise return None""" info = self._registry.pop(self, None) if info and not self._shutdown: return info.func(*info.args, **(info.kwargs or {}))
[ "def", "__call__", "(", "self", ",", "_", "=", "None", ")", ":", "info", "=", "self", ".", "_registry", ".", "pop", "(", "self", ",", "None", ")", "if", "info", "and", "not", "self", ".", "_shutdown", ":", "return", "info", ".", "func", "(", "*",...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/weakref.py#L514-L519
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_file_types/models/netcdf.py
python
NetCDFFileMetaData.get_variable_formset
(self)
return variable_formset
[]
def get_variable_formset(self): VariableFormSetEdit = formset_factory( wraps(VariableForm)(partial(VariableForm, allow_edit=True)), formset=BaseFormSet, extra=0) variable_formset = VariableFormSetEdit( initial=list(self.variables.all().values()), prefix='Variable') for frm in variable_formset.forms: if len(frm.initial) > 0: frm.action = "/hsapi/_internal/%s/%s/variable/%s/update-file-metadata/" % ( "NetCDFLogicalFile", self.logical_file.id, frm.initial['id']) frm.number = frm.initial['id'] return variable_formset
[ "def", "get_variable_formset", "(", "self", ")", ":", "VariableFormSetEdit", "=", "formset_factory", "(", "wraps", "(", "VariableForm", ")", "(", "partial", "(", "VariableForm", ",", "allow_edit", "=", "True", ")", ")", ",", "formset", "=", "BaseFormSet", ",",...
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_file_types/models/netcdf.py#L205-L218
openstack/barbican
a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce
barbican/api/app.py
python
get_api_wsgi_script
()
return application
[]
def get_api_wsgi_script(): conf = '/etc/barbican/barbican-api-paste.ini' application = deploy.loadapp('config:%s' % conf) return application
[ "def", "get_api_wsgi_script", "(", ")", ":", "conf", "=", "'/etc/barbican/barbican-api-paste.ini'", "application", "=", "deploy", ".", "loadapp", "(", "'config:%s'", "%", "conf", ")", "return", "application" ]
https://github.com/openstack/barbican/blob/a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce/barbican/api/app.py#L116-L119
aouyar/PyMunin
94624d4f56340cb2ed7e96ca3c5d9533a0721306
pysysinfo/lighttpd.py
python
LighttpdInfo.__init__
(self, host=None, port=None, user=None, password=None, statuspath = None, ssl=False, autoInit=True)
Initialize Lighttpd server-status URL access. @param host: Lighttpd Web Server Host. (Default: 127.0.0.1) @param port: Lighttpd Web Server Port. (Default: 80, SSL: 443) @param user: Username. (Not needed unless authentication is required to access server-status page. @param password: Password. (Not needed unless authentication is required to access server-status page. @statuspath: Path of status page. (Default: server-status) @param ssl: Use SSL if True. (Default: False) @param autoInit: If True connect to Lighttpd Web Server on instantiation.
Initialize Lighttpd server-status URL access.
[ "Initialize", "Lighttpd", "server", "-", "status", "URL", "access", "." ]
def __init__(self, host=None, port=None, user=None, password=None, statuspath = None, ssl=False, autoInit=True): """Initialize Lighttpd server-status URL access. @param host: Lighttpd Web Server Host. (Default: 127.0.0.1) @param port: Lighttpd Web Server Port. (Default: 80, SSL: 443) @param user: Username. (Not needed unless authentication is required to access server-status page. @param password: Password. (Not needed unless authentication is required to access server-status page. @statuspath: Path of status page. (Default: server-status) @param ssl: Use SSL if True. (Default: False) @param autoInit: If True connect to Lighttpd Web Server on instantiation. """ if host is not None: self._host = host else: self._host = '127.0.0.1' if port is not None: self._port = int(port) else: if ssl: self._port = defaultHTTPSport else: self._port = defaultHTTPport self._user = user self._password = password if statuspath is not None: self._statuspath = statuspath else: self._statuspath = 'server-status' if ssl: self._proto = 'https' else: self._proto = 'http' self._statusDict = None if autoInit: self.initStats()
[ "def", "__init__", "(", "self", ",", "host", "=", "None", ",", "port", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "statuspath", "=", "None", ",", "ssl", "=", "False", ",", "autoInit", "=", "True", ")", ":", "if", "h...
https://github.com/aouyar/PyMunin/blob/94624d4f56340cb2ed7e96ca3c5d9533a0721306/pysysinfo/lighttpd.py#L28-L66
intrig-unicamp/mininet-wifi
3c8a8f63bd4aa043aa9c1ad16f304dec2916f5ba
mn_wifi/sumo/traci/_vehicletype.py
python
VehicleTypeDomain.setApparentDecel
(self, typeID, decel)
setDecel(string, double) -> None Sets the apparent deceleration in m/s^2 of vehicles of this type.
setDecel(string, double) -> None Sets the apparent deceleration in m/s^2 of vehicles of this type.
[ "setDecel", "(", "string", "double", ")", "-", ">", "None", "Sets", "the", "apparent", "deceleration", "in", "m", "/", "s^2", "of", "vehicles", "of", "this", "type", "." ]
def setApparentDecel(self, typeID, decel): """setDecel(string, double) -> None Sets the apparent deceleration in m/s^2 of vehicles of this type. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_APPARENT_DECEL, typeID, decel)
[ "def", "setApparentDecel", "(", "self", ",", "typeID", ",", "decel", ")", ":", "self", ".", "_connection", ".", "_sendDoubleCmd", "(", "tc", ".", "CMD_SET_VEHICLETYPE_VARIABLE", ",", "tc", ".", "VAR_APPARENT_DECEL", ",", "typeID", ",", "decel", ")" ]
https://github.com/intrig-unicamp/mininet-wifi/blob/3c8a8f63bd4aa043aa9c1ad16f304dec2916f5ba/mn_wifi/sumo/traci/_vehicletype.py#L307-L312
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/django/db/models/sql/query.py
python
Query.add_q
(self, q_object, used_aliases=None, force_having=False)
Adds a Q-object to the current filter. Can also be used to add anything that has an 'add_to_query()' method.
Adds a Q-object to the current filter.
[ "Adds", "a", "Q", "-", "object", "to", "the", "current", "filter", "." ]
def add_q(self, q_object, used_aliases=None, force_having=False): """ Adds a Q-object to the current filter. Can also be used to add anything that has an 'add_to_query()' method. """ if used_aliases is None: used_aliases = self.used_aliases if hasattr(q_object, 'add_to_query'): # Complex custom objects are responsible for adding themselves. q_object.add_to_query(self, used_aliases) else: if self.where and q_object.connector != AND and len(q_object) > 1: self.where.start_subtree(AND) subtree = True else: subtree = False connector = AND if q_object.connector == OR and not force_having: force_having = self.need_force_having(q_object) for child in q_object.children: if connector == OR: refcounts_before = self.alias_refcount.copy() if force_having: self.having.start_subtree(connector) else: self.where.start_subtree(connector) if isinstance(child, Node): self.add_q(child, used_aliases, force_having=force_having) else: self.add_filter(child, connector, q_object.negated, can_reuse=used_aliases, force_having=force_having) if force_having: self.having.end_subtree() else: self.where.end_subtree() if connector == OR: # Aliases that were newly added or not used at all need to # be promoted to outer joins if they are nullable relations. # (they shouldn't turn the whole conditional into the empty # set just because they don't match anything). self.promote_unused_aliases(refcounts_before, used_aliases) connector = q_object.connector if q_object.negated: self.where.negate() if subtree: self.where.end_subtree() if self.filter_is_sticky: self.used_aliases = used_aliases
[ "def", "add_q", "(", "self", ",", "q_object", ",", "used_aliases", "=", "None", ",", "force_having", "=", "False", ")", ":", "if", "used_aliases", "is", "None", ":", "used_aliases", "=", "self", ".", "used_aliases", "if", "hasattr", "(", "q_object", ",", ...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/django/db/models/sql/query.py#L1240-L1289
NVIDIA/DeepLearningExamples
589604d49e016cd9ef4525f7abcc9c7b826cfc5e
TensorFlow/Translation/GNMT/model_helper.py
python
avg_checkpoints
(model_dir, num_last_checkpoints, global_step_name)
return avg_model_dir
Average the last N checkpoints in the model_dir.
Average the last N checkpoints in the model_dir.
[ "Average", "the", "last", "N", "checkpoints", "in", "the", "model_dir", "." ]
def avg_checkpoints(model_dir, num_last_checkpoints, global_step_name): """Average the last N checkpoints in the model_dir.""" checkpoint_state = tf.train.get_checkpoint_state(model_dir) if not checkpoint_state: utils.print_out("# No checkpoint file found in directory: %s" % model_dir) return None # Checkpoints are ordered from oldest to newest. checkpoints = ( checkpoint_state.all_model_checkpoint_paths[-num_last_checkpoints:]) if len(checkpoints) < num_last_checkpoints: utils.print_out( "# Skipping averaging checkpoints because not enough checkpoints is " "available.") return None avg_model_dir = os.path.join(model_dir, "avg_checkpoints") if not tf.gfile.Exists(avg_model_dir): utils.print_out( "# Creating new directory %s for saving averaged checkpoints." % avg_model_dir) tf.gfile.MakeDirs(avg_model_dir) utils.print_out("# Reading and averaging variables in checkpoints:") var_list = tf.contrib.framework.list_variables(checkpoints[0]) var_values, var_dtypes = {}, {} for (name, shape) in var_list: if name != global_step_name: var_values[name] = np.zeros(shape) for checkpoint in checkpoints: utils.print_out(" %s" % checkpoint) reader = tf.contrib.framework.load_checkpoint(checkpoint) for name in var_values: tensor = reader.get_tensor(name) var_dtypes[name] = tensor.dtype var_values[name] += tensor for name in var_values: var_values[name] /= len(checkpoints) # Build a graph with same variables in the checkpoints, and save the averaged # variables into the avg_model_dir. with tf.Graph().as_default(): tf_vars = [ tf.get_variable(v, shape=var_values[v].shape, dtype=var_dtypes[name]) for v in var_values ] placeholders = [tf.placeholder(v.dtype, shape=v.shape) for v in tf_vars] assign_ops = [tf.assign(v, p) for (v, p) in zip(tf_vars, placeholders)] saver = tf.train.Saver(tf.all_variables(), save_relative_paths=True) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) for p, assign_op, (name, value) in zip(placeholders, assign_ops, six.iteritems(var_values)): sess.run(assign_op, {p: value}) # Use the built saver to save the averaged checkpoint. Only keep 1 # checkpoint and the best checkpoint will be moved to avg_best_metric_dir. saver.save( sess, os.path.join(avg_model_dir, "translate.ckpt")) return avg_model_dir
[ "def", "avg_checkpoints", "(", "model_dir", ",", "num_last_checkpoints", ",", "global_step_name", ")", ":", "checkpoint_state", "=", "tf", ".", "train", ".", "get_checkpoint_state", "(", "model_dir", ")", "if", "not", "checkpoint_state", ":", "utils", ".", "print_...
https://github.com/NVIDIA/DeepLearningExamples/blob/589604d49e016cd9ef4525f7abcc9c7b826cfc5e/TensorFlow/Translation/GNMT/model_helper.py#L402-L468
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/partition_algebra.py
python
SetPartitionsBk
(k)
return SetPartitionsBk_k(k)
r""" Return the combinatorial class of set partitions of type `B_k`. These are the set partitions where every block has size 2. EXAMPLES:: sage: B3 = SetPartitionsBk(3); B3 Set partitions of {1, ..., 3, -1, ..., -3} with block size 2 sage: B3.first() #random {{2, -2}, {1, -3}, {3, -1}} sage: B3.last() #random {{1, 2}, {3, -2}, {-3, -1}} sage: B3.random_element() #random {{2, -1}, {1, -3}, {3, -2}} sage: B3.cardinality() 15 sage: B2p5 = SetPartitionsBk(2.5); B2p5 Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2 sage: B2p5.first() #random {{2, -1}, {3, -3}, {1, -2}} sage: B2p5.last() #random {{1, 2}, {3, -3}, {-1, -2}} sage: B2p5.random_element() #random {{2, -2}, {3, -3}, {1, -1}} sage: B2p5.cardinality() 3
r""" Return the combinatorial class of set partitions of type `B_k`.
[ "r", "Return", "the", "combinatorial", "class", "of", "set", "partitions", "of", "type", "B_k", "." ]
def SetPartitionsBk(k): r""" Return the combinatorial class of set partitions of type `B_k`. These are the set partitions where every block has size 2. EXAMPLES:: sage: B3 = SetPartitionsBk(3); B3 Set partitions of {1, ..., 3, -1, ..., -3} with block size 2 sage: B3.first() #random {{2, -2}, {1, -3}, {3, -1}} sage: B3.last() #random {{1, 2}, {3, -2}, {-3, -1}} sage: B3.random_element() #random {{2, -1}, {1, -3}, {3, -2}} sage: B3.cardinality() 15 sage: B2p5 = SetPartitionsBk(2.5); B2p5 Set partitions of {1, ..., 3, -1, ..., -3} with 3 and -3 in the same block and with block size 2 sage: B2p5.first() #random {{2, -1}, {3, -3}, {1, -2}} sage: B2p5.last() #random {{1, 2}, {3, -3}, {-1, -2}} sage: B2p5.random_element() #random {{2, -2}, {3, -3}, {1, -1}} sage: B2p5.cardinality() 3 """ is_int, k = _int_or_half_int(k) if not is_int: return SetPartitionsBkhalf_k(k) return SetPartitionsBk_k(k)
[ "def", "SetPartitionsBk", "(", "k", ")", ":", "is_int", ",", "k", "=", "_int_or_half_int", "(", "k", ")", "if", "not", "is_int", ":", "return", "SetPartitionsBkhalf_k", "(", "k", ")", "return", "SetPartitionsBk_k", "(", "k", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/partition_algebra.py#L609-L646
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/setuptools/command/egg_info.py
python
egg_info.save_version_info
(self, filename)
Materialize the value of date into the build tag. Install build keys in a deterministic order to avoid arbitrary reordering on subsequent builds.
Materialize the value of date into the build tag. Install build keys in a deterministic order to avoid arbitrary reordering on subsequent builds.
[ "Materialize", "the", "value", "of", "date", "into", "the", "build", "tag", ".", "Install", "build", "keys", "in", "a", "deterministic", "order", "to", "avoid", "arbitrary", "reordering", "on", "subsequent", "builds", "." ]
def save_version_info(self, filename): """ Materialize the value of date into the build tag. Install build keys in a deterministic order to avoid arbitrary reordering on subsequent builds. """ egg_info = collections.OrderedDict() # follow the order these keys would have been added # when PYTHONHASHSEED=0 egg_info['tag_build'] = self.tags() egg_info['tag_date'] = 0 edit_config(filename, dict(egg_info=egg_info))
[ "def", "save_version_info", "(", "self", ",", "filename", ")", ":", "egg_info", "=", "collections", ".", "OrderedDict", "(", ")", "# follow the order these keys would have been added", "# when PYTHONHASHSEED=0", "egg_info", "[", "'tag_build'", "]", "=", "self", ".", "...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/setuptools/command/egg_info.py#L180-L191
kLabUM/rrcf
34504c14bba233f86a7dcae35d55fc84cc5b7508
rrcf/rrcf.py
python
RCTree.codisp
(self, leaf)
return co_displacement
Compute collusive displacement at leaf Parameters: ----------- leaf: index of leaf or Leaf instance Returns: -------- codisplacement: float Collusive displacement if leaf is removed. Example: -------- # Create RCTree >>> X = np.random.randn(100, 2) >>> tree = rrcf.RCTree(X) >>> new_point = np.array([4, 4]) >>> tree.insert_point(new_point, index=100) # Compute collusive displacement >>> tree.codisp(100) 31.667
Compute collusive displacement at leaf
[ "Compute", "collusive", "displacement", "at", "leaf" ]
def codisp(self, leaf): """ Compute collusive displacement at leaf Parameters: ----------- leaf: index of leaf or Leaf instance Returns: -------- codisplacement: float Collusive displacement if leaf is removed. Example: -------- # Create RCTree >>> X = np.random.randn(100, 2) >>> tree = rrcf.RCTree(X) >>> new_point = np.array([4, 4]) >>> tree.insert_point(new_point, index=100) # Compute collusive displacement >>> tree.codisp(100) 31.667 """ if not isinstance(leaf, Leaf): try: leaf = self.leaves[leaf] except KeyError: raise KeyError( 'leaf must be a Leaf instance or key to self.leaves') # Handle case where leaf is root if leaf is self.root: return 0 node = leaf results = [] for _ in range(node.d): parent = node.u if parent is None: break if node is parent.l: sibling = parent.r else: sibling = parent.l num_deleted = node.n displacement = sibling.n result = (displacement / num_deleted) results.append(result) node = parent co_displacement = max(results) return co_displacement
[ "def", "codisp", "(", "self", ",", "leaf", ")", ":", "if", "not", "isinstance", "(", "leaf", ",", "Leaf", ")", ":", "try", ":", "leaf", "=", "self", ".", "leaves", "[", "leaf", "]", "except", "KeyError", ":", "raise", "KeyError", "(", "'leaf must be ...
https://github.com/kLabUM/rrcf/blob/34504c14bba233f86a7dcae35d55fc84cc5b7508/rrcf/rrcf.py#L583-L634
cloudtools/stacker
f563a6f5a23550c7a668a1500bcea2b4e94f5bbf
stacker/hooks/iam.py
python
create_ecs_service_role
(provider, context, **kwargs)
return True
Used to create the ecsServieRole, which has to be named exactly that currently, so cannot be created via CloudFormation. See: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html#service_IAM_role Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance Returns: boolean for whether or not the hook succeeded.
Used to create the ecsServieRole, which has to be named exactly that currently, so cannot be created via CloudFormation. See:
[ "Used", "to", "create", "the", "ecsServieRole", "which", "has", "to", "be", "named", "exactly", "that", "currently", "so", "cannot", "be", "created", "via", "CloudFormation", ".", "See", ":" ]
def create_ecs_service_role(provider, context, **kwargs): """Used to create the ecsServieRole, which has to be named exactly that currently, so cannot be created via CloudFormation. See: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/IAM_policies.html#service_IAM_role Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance Returns: boolean for whether or not the hook succeeded. """ role_name = kwargs.get("role_name", "ecsServiceRole") client = get_session(provider.region).client('iam') try: client.create_role( RoleName=role_name, AssumeRolePolicyDocument=get_ecs_assumerole_policy().to_json() ) except ClientError as e: if "already exists" in str(e): pass else: raise policy = Policy( Version='2012-10-17', Statement=[ Statement( Effect=Allow, Resource=["*"], Action=[ecs.CreateCluster, ecs.DeregisterContainerInstance, ecs.DiscoverPollEndpoint, ecs.Poll, ecs.Action("Submit*")] ) ]) client.put_role_policy( RoleName=role_name, PolicyName="AmazonEC2ContainerServiceRolePolicy", PolicyDocument=policy.to_json() ) return True
[ "def", "create_ecs_service_role", "(", "provider", ",", "context", ",", "*", "*", "kwargs", ")", ":", "role_name", "=", "kwargs", ".", "get", "(", "\"role_name\"", ",", "\"ecsServiceRole\"", ")", "client", "=", "get_session", "(", "provider", ".", "region", ...
https://github.com/cloudtools/stacker/blob/f563a6f5a23550c7a668a1500bcea2b4e94f5bbf/stacker/hooks/iam.py#L20-L64
aliyun/aliyun-odps-python-sdk
20b391c8d6eb1a689eedf950c2fc702be5f057c9
odps/ml/algolib/loader.py
python
load_classifiers
(algo_defs, env)
Load an algorithm into a module. The algorithm is an instance of ``AlgorithmDef`` class. :param algo_defs: algorithm definitions :type algo_defs: AlgorithmDef | list[AlgorithmDef] :param env: environment :Example: >>> import sys >>> from odps.ml.algolib.loader import * >>> a = XflowAlgorithmDef('SampleAlgorithm') >>> a.add_param(ParamDef('param1', 'val1')) >>> a.add_port(PortDef('input')) >>> a.add_port(PortDef('output', PortDirection.OUTPUT)) >>> load_classifiers(a, sys.modules[__name__])
Load an algorithm into a module. The algorithm is an instance of ``AlgorithmDef`` class.
[ "Load", "an", "algorithm", "into", "a", "module", ".", "The", "algorithm", "is", "an", "instance", "of", "AlgorithmDef", "class", "." ]
def load_classifiers(algo_defs, env): """ Load an algorithm into a module. The algorithm is an instance of ``AlgorithmDef`` class. :param algo_defs: algorithm definitions :type algo_defs: AlgorithmDef | list[AlgorithmDef] :param env: environment :Example: >>> import sys >>> from odps.ml.algolib.loader import * >>> a = XflowAlgorithmDef('SampleAlgorithm') >>> a.add_param(ParamDef('param1', 'val1')) >>> a.add_port(PortDef('input')) >>> a.add_port(PortDef('output', PortDirection.OUTPUT)) >>> load_classifiers(a, sys.modules[__name__]) """ if not isinstance(algo_defs, Iterable): algo_defs = [algo_defs, ] load_algorithms(algo_defs, 'BaseTrainingAlgorithm', env)
[ "def", "load_classifiers", "(", "algo_defs", ",", "env", ")", ":", "if", "not", "isinstance", "(", "algo_defs", ",", "Iterable", ")", ":", "algo_defs", "=", "[", "algo_defs", ",", "]", "load_algorithms", "(", "algo_defs", ",", "'BaseTrainingAlgorithm'", ",", ...
https://github.com/aliyun/aliyun-odps-python-sdk/blob/20b391c8d6eb1a689eedf950c2fc702be5f057c9/odps/ml/algolib/loader.py#L452-L471
aleju/imgaug
0101108d4fed06bc5056c4a03e2bcb0216dac326
imgaug/random.py
python
_derive_generators_np116_
(random_state, n)
return [_convert_seed_to_generator_np116(seed_ + i) for i in sm.xrange(n)]
[]
def _derive_generators_np116_(random_state, n): seed_ = random_state.randint(SEED_MIN_VALUE, SEED_MAX_VALUE) return [_convert_seed_to_generator_np116(seed_ + i) for i in sm.xrange(n)]
[ "def", "_derive_generators_np116_", "(", "random_state", ",", "n", ")", ":", "seed_", "=", "random_state", ".", "randint", "(", "SEED_MIN_VALUE", ",", "SEED_MAX_VALUE", ")", "return", "[", "_convert_seed_to_generator_np116", "(", "seed_", "+", "i", ")", "for", "...
https://github.com/aleju/imgaug/blob/0101108d4fed06bc5056c4a03e2bcb0216dac326/imgaug/random.py#L1362-L1364
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
libs/codeintel2/pythoncile2.py
python
Scanner._iter_scopes
(self)
[]
def _iter_scopes(self): for item in reversed(self._scope_stack): yield item
[ "def", "_iter_scopes", "(", "self", ")", ":", "for", "item", "in", "reversed", "(", "self", ".", "_scope_stack", ")", ":", "yield", "item" ]
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/codeintel2/pythoncile2.py#L254-L256
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
research/object_detection/tpu_exporters/ssd.py
python
get_prediction_tensor_shapes
(pipeline_config)
return { BOX_ENCODINGS: prediction_dict[BOX_ENCODINGS].shape.as_list(), CLASS_PREDICTIONS_WITH_BACKGROUND: prediction_dict[CLASS_PREDICTIONS_WITH_BACKGROUND].shape.as_list(), ANCHORS: prediction_dict[ANCHORS].shape.as_list(), }
Gets static shapes of tensors by building the graph on CPU. This function builds the graph on CPU and obtain static shapes of output tensors from TPUPartitionedCall. Shapes information are later used for setting shapes of tensors when TPU graphs are built. This is necessary because tensors coming out of TPUPartitionedCall lose their shape information, which are needed for a lot of CPU operations later. Args: pipeline_config: A TrainEvalPipelineConfig proto. Returns: A python dict of tensors' names and their shapes.
Gets static shapes of tensors by building the graph on CPU.
[ "Gets", "static", "shapes", "of", "tensors", "by", "building", "the", "graph", "on", "CPU", "." ]
def get_prediction_tensor_shapes(pipeline_config): """Gets static shapes of tensors by building the graph on CPU. This function builds the graph on CPU and obtain static shapes of output tensors from TPUPartitionedCall. Shapes information are later used for setting shapes of tensors when TPU graphs are built. This is necessary because tensors coming out of TPUPartitionedCall lose their shape information, which are needed for a lot of CPU operations later. Args: pipeline_config: A TrainEvalPipelineConfig proto. Returns: A python dict of tensors' names and their shapes. """ detection_model = model_builder.build( pipeline_config.model, is_training=False) _, input_tensors = exporter.input_placeholder_fn_map['image_tensor']() inputs = tf.cast(input_tensors, dtype=tf.float32) preprocessed_inputs, true_image_shapes = detection_model.preprocess(inputs) prediction_dict = detection_model.predict(preprocessed_inputs, true_image_shapes) return { BOX_ENCODINGS: prediction_dict[BOX_ENCODINGS].shape.as_list(), CLASS_PREDICTIONS_WITH_BACKGROUND: prediction_dict[CLASS_PREDICTIONS_WITH_BACKGROUND].shape.as_list(), ANCHORS: prediction_dict[ANCHORS].shape.as_list(), }
[ "def", "get_prediction_tensor_shapes", "(", "pipeline_config", ")", ":", "detection_model", "=", "model_builder", ".", "build", "(", "pipeline_config", ".", "model", ",", "is_training", "=", "False", ")", "_", ",", "input_tensors", "=", "exporter", ".", "input_pla...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/research/object_detection/tpu_exporters/ssd.py#L45-L74
kuhnertdm/wow-addon-updater
9df13c70873f5e93f30eedb89010d99d42c7baf4
packages/requests/cookies.py
python
cookiejar_from_dict
(cookie_dict, cookiejar=None, overwrite=True)
return cookiejar
Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :param cookiejar: (optional) A cookiejar to add the cookies to. :param overwrite: (optional) If False, will not replace cookies already in the jar with new ones.
Returns a CookieJar from a key/value dictionary.
[ "Returns", "a", "CookieJar", "from", "a", "key", "/", "value", "dictionary", "." ]
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): """Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :param cookiejar: (optional) A cookiejar to add the cookies to. :param overwrite: (optional) If False, will not replace cookies already in the jar with new ones. """ if cookiejar is None: cookiejar = RequestsCookieJar() if cookie_dict is not None: names_from_jar = [cookie.name for cookie in cookiejar] for name in cookie_dict: if overwrite or (name not in names_from_jar): cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) return cookiejar
[ "def", "cookiejar_from_dict", "(", "cookie_dict", ",", "cookiejar", "=", "None", ",", "overwrite", "=", "True", ")", ":", "if", "cookiejar", "is", "None", ":", "cookiejar", "=", "RequestsCookieJar", "(", ")", "if", "cookie_dict", "is", "not", "None", ":", ...
https://github.com/kuhnertdm/wow-addon-updater/blob/9df13c70873f5e93f30eedb89010d99d42c7baf4/packages/requests/cookies.py#L503-L520
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/lib/scons-4.3.0/SCons/Node/Alias.py
python
AliasNodeInfo.__setstate__
(self, state)
Restore the attributes from a pickled state.
Restore the attributes from a pickled state.
[ "Restore", "the", "attributes", "from", "a", "pickled", "state", "." ]
def __setstate__(self, state): """ Restore the attributes from a pickled state. """ # TODO check or discard version del state['_version_id'] for key, value in state.items(): if key not in ('__weakref__',): setattr(self, key, value)
[ "def", "__setstate__", "(", "self", ",", "state", ")", ":", "# TODO check or discard version", "del", "state", "[", "'_version_id'", "]", "for", "key", ",", "value", "in", "state", ".", "items", "(", ")", ":", "if", "key", "not", "in", "(", "'__weakref__'"...
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-4.3.0/SCons/Node/Alias.py#L81-L89
WXinlong/SOLO
95f3732d5fbb0d7c7044c7dd074f439d48a72ce5
mmdet/core/anchor/guided_anchor_target.py
python
ga_shape_target
(approx_list, inside_flag_list, square_list, gt_bboxes_list, img_metas, approxs_per_octave, cfg, gt_bboxes_ignore_list=None, sampling=True, unmap_outputs=True)
return (bbox_anchors_list, bbox_gts_list, bbox_weights_list, num_total_pos, num_total_neg)
Compute guided anchoring targets. Args: approx_list (list[list]): Multi level approxs of each image. inside_flag_list (list[list]): Multi level inside flags of each image. square_list (list[list]): Multi level squares of each image. gt_bboxes_list (list[Tensor]): Ground truth bboxes of each image. img_metas (list[dict]): Meta info of each image. approxs_per_octave (int): number of approxs per octave cfg (dict): RPN train configs. gt_bboxes_ignore_list (list[Tensor]): ignore list of gt bboxes. sampling (bool): sampling or not. unmap_outputs (bool): unmap outputs or not. Returns: tuple
Compute guided anchoring targets.
[ "Compute", "guided", "anchoring", "targets", "." ]
def ga_shape_target(approx_list, inside_flag_list, square_list, gt_bboxes_list, img_metas, approxs_per_octave, cfg, gt_bboxes_ignore_list=None, sampling=True, unmap_outputs=True): """Compute guided anchoring targets. Args: approx_list (list[list]): Multi level approxs of each image. inside_flag_list (list[list]): Multi level inside flags of each image. square_list (list[list]): Multi level squares of each image. gt_bboxes_list (list[Tensor]): Ground truth bboxes of each image. img_metas (list[dict]): Meta info of each image. approxs_per_octave (int): number of approxs per octave cfg (dict): RPN train configs. gt_bboxes_ignore_list (list[Tensor]): ignore list of gt bboxes. sampling (bool): sampling or not. unmap_outputs (bool): unmap outputs or not. Returns: tuple """ num_imgs = len(img_metas) assert len(approx_list) == len(inside_flag_list) == len( square_list) == num_imgs # anchor number of multi levels num_level_squares = [squares.size(0) for squares in square_list[0]] # concat all level anchors and flags to a single tensor inside_flag_flat_list = [] approx_flat_list = [] square_flat_list = [] for i in range(num_imgs): assert len(square_list[i]) == len(inside_flag_list[i]) inside_flag_flat_list.append(torch.cat(inside_flag_list[i])) approx_flat_list.append(torch.cat(approx_list[i])) square_flat_list.append(torch.cat(square_list[i])) # compute targets for each image if gt_bboxes_ignore_list is None: gt_bboxes_ignore_list = [None for _ in range(num_imgs)] (all_bbox_anchors, all_bbox_gts, all_bbox_weights, pos_inds_list, neg_inds_list) = multi_apply( ga_shape_target_single, approx_flat_list, inside_flag_flat_list, square_flat_list, gt_bboxes_list, gt_bboxes_ignore_list, img_metas, approxs_per_octave=approxs_per_octave, cfg=cfg, sampling=sampling, unmap_outputs=unmap_outputs) # no valid anchors if any([bbox_anchors is None for bbox_anchors in all_bbox_anchors]): return None # sampled anchors of all images num_total_pos = sum([max(inds.numel(), 1) for inds in pos_inds_list]) num_total_neg = sum([max(inds.numel(), 1) for inds in neg_inds_list]) # split targets to a list w.r.t. multiple levels bbox_anchors_list = images_to_levels(all_bbox_anchors, num_level_squares) bbox_gts_list = images_to_levels(all_bbox_gts, num_level_squares) bbox_weights_list = images_to_levels(all_bbox_weights, num_level_squares) return (bbox_anchors_list, bbox_gts_list, bbox_weights_list, num_total_pos, num_total_neg)
[ "def", "ga_shape_target", "(", "approx_list", ",", "inside_flag_list", ",", "square_list", ",", "gt_bboxes_list", ",", "img_metas", ",", "approxs_per_octave", ",", "cfg", ",", "gt_bboxes_ignore_list", "=", "None", ",", "sampling", "=", "True", ",", "unmap_outputs", ...
https://github.com/WXinlong/SOLO/blob/95f3732d5fbb0d7c7044c7dd074f439d48a72ce5/mmdet/core/anchor/guided_anchor_target.py#L133-L202
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-graalpython/faulthandler.py
python
enable
(file=None, all_threads=True)
[]
def enable(file=None, all_threads=True): global _enabled _enabled = True
[ "def", "enable", "(", "file", "=", "None", ",", "all_threads", "=", "True", ")", ":", "global", "_enabled", "_enabled", "=", "True" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-graalpython/faulthandler.py#L44-L46
quantumlib/Cirq
89f88b01d69222d3f1ec14d649b7b3a85ed9211f
cirq-core/cirq/sim/simulator.py
python
SimulatesIntermediateState._create_simulator_trial_result
( self, params: 'cirq.ParamResolver', measurements: Dict[str, np.ndarray], final_step_result: TStepResult, )
This method can be implemented to create a trial result. Args: params: The ParamResolver for this trial. measurements: The measurement results for this trial. final_step_result: The final step result of the simulation. Returns: The SimulationTrialResult.
This method can be implemented to create a trial result.
[ "This", "method", "can", "be", "implemented", "to", "create", "a", "trial", "result", "." ]
def _create_simulator_trial_result( self, params: 'cirq.ParamResolver', measurements: Dict[str, np.ndarray], final_step_result: TStepResult, ) -> TSimulationTrialResult: """This method can be implemented to create a trial result. Args: params: The ParamResolver for this trial. measurements: The measurement results for this trial. final_step_result: The final step result of the simulation. Returns: The SimulationTrialResult. """ raise NotImplementedError()
[ "def", "_create_simulator_trial_result", "(", "self", ",", "params", ":", "'cirq.ParamResolver'", ",", "measurements", ":", "Dict", "[", "str", ",", "np", ".", "ndarray", "]", ",", "final_step_result", ":", "TStepResult", ",", ")", "->", "TSimulationTrialResult", ...
https://github.com/quantumlib/Cirq/blob/89f88b01d69222d3f1ec14d649b7b3a85ed9211f/cirq-core/cirq/sim/simulator.py#L667-L683
pgq/skytools-legacy
8b7e6c118572a605d28b7a3403c96aeecfd0d272
scripts/scriptmgr.py
python
launch_cmd
(job, cmd)
return os.system(cmd)
[]
def launch_cmd(job, cmd): if job['user']: cmd = 'sudo -nH -u "%s" %s' % (job['user'], cmd) return os.system(cmd)
[ "def", "launch_cmd", "(", "job", ",", "cmd", ")", ":", "if", "job", "[", "'user'", "]", ":", "cmd", "=", "'sudo -nH -u \"%s\" %s'", "%", "(", "job", "[", "'user'", "]", ",", "cmd", ")", "return", "os", ".", "system", "(", "cmd", ")" ]
https://github.com/pgq/skytools-legacy/blob/8b7e6c118572a605d28b7a3403c96aeecfd0d272/scripts/scriptmgr.py#L75-L78
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/scipy/constants/codata.py
python
value
(key)
return physical_constants[key][0]
Value in physical_constants indexed by key Parameters ---------- key : Python string or unicode Key in dictionary `physical_constants` Returns ------- value : float Value in `physical_constants` corresponding to `key` See Also -------- codata : Contains the description of `physical_constants`, which, as a dictionary literal object, does not itself possess a docstring. Examples -------- >>> from scipy import constants >>> constants.value(u'elementary charge') 1.6021766208e-19
Value in physical_constants indexed by key
[ "Value", "in", "physical_constants", "indexed", "by", "key" ]
def value(key): """ Value in physical_constants indexed by key Parameters ---------- key : Python string or unicode Key in dictionary `physical_constants` Returns ------- value : float Value in `physical_constants` corresponding to `key` See Also -------- codata : Contains the description of `physical_constants`, which, as a dictionary literal object, does not itself possess a docstring. Examples -------- >>> from scipy import constants >>> constants.value(u'elementary charge') 1.6021766208e-19 """ _check_obsolete(key) return physical_constants[key][0]
[ "def", "value", "(", "key", ")", ":", "_check_obsolete", "(", "key", ")", "return", "physical_constants", "[", "key", "]", "[", "0", "]" ]
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/scipy/constants/codata.py#L1200-L1227
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/combined_audience_service/client.py
python
CombinedAudienceServiceClient.common_project_path
(project: str,)
return "projects/{project}".format(project=project,)
Return a fully-qualified project string.
Return a fully-qualified project string.
[ "Return", "a", "fully", "-", "qualified", "project", "string", "." ]
def common_project_path(project: str,) -> str: """Return a fully-qualified project string.""" return "projects/{project}".format(project=project,)
[ "def", "common_project_path", "(", "project", ":", "str", ",", ")", "->", "str", ":", "return", "\"projects/{project}\"", ".", "format", "(", "project", "=", "project", ",", ")" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/combined_audience_service/client.py#L237-L239
openstack/barbican
a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce
barbican/cmd/pkcs11_migrate_kek_signatures.py
python
main
()
[]
def main(): script_desc = ( 'Utility to migrate existing project KEK signatures to include IV.' ) parser = argparse.ArgumentParser(description=script_desc) parser.add_argument( '--dry-run', action='store_true', help='Displays changes that will be made (Non-destructive)' ) args = parser.parse_args() migrator = KekSignatureMigrator( db_connection=CONF.sql_connection, library_path=CONF.p11_crypto_plugin.library_path, login=CONF.p11_crypto_plugin.login, slot_id=CONF.p11_crypto_plugin.slot_id ) migrator.execute(args.dry_run)
[ "def", "main", "(", ")", ":", "script_desc", "=", "(", "'Utility to migrate existing project KEK signatures to include IV.'", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "script_desc", ")", "parser", ".", "add_argument", "(", "'--dr...
https://github.com/openstack/barbican/blob/a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce/barbican/cmd/pkcs11_migrate_kek_signatures.py#L149-L168
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/idlelib/EditorWindow.py
python
EditorWindow.help_dialog
(self, event=None)
Handle Help 'IDLE Help' event.
Handle Help 'IDLE Help' event.
[ "Handle", "Help", "IDLE", "Help", "event", "." ]
def help_dialog(self, event=None): "Handle Help 'IDLE Help' event." # Synchronize with macosxSupport.overrideRootMenu.help_dialog. if self.root: parent = self.root else: parent = self.top help.show_idlehelp(parent)
[ "def", "help_dialog", "(", "self", ",", "event", "=", "None", ")", ":", "# Synchronize with macosxSupport.overrideRootMenu.help_dialog.", "if", "self", ".", "root", ":", "parent", "=", "self", ".", "root", "else", ":", "parent", "=", "self", ".", "top", "help"...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/idlelib/EditorWindow.py#L545-L552
NTMC-Community/MatchZoo-py
0e5c04e1e948aa9277abd5c85ff99d9950d8527f
matchzoo/preprocessors/units/matching_histogram.py
python
MatchingHistogram._normalize_embedding
(self)
Normalize the embedding matrix.
Normalize the embedding matrix.
[ "Normalize", "the", "embedding", "matrix", "." ]
def _normalize_embedding(self): """Normalize the embedding matrix.""" l2_norm = np.sqrt( (self._embedding_matrix * self._embedding_matrix).sum(axis=1) ) self._embedding_matrix = \ self._embedding_matrix / l2_norm[:, np.newaxis]
[ "def", "_normalize_embedding", "(", "self", ")", ":", "l2_norm", "=", "np", ".", "sqrt", "(", "(", "self", ".", "_embedding_matrix", "*", "self", ".", "_embedding_matrix", ")", ".", "sum", "(", "axis", "=", "1", ")", ")", "self", ".", "_embedding_matrix"...
https://github.com/NTMC-Community/MatchZoo-py/blob/0e5c04e1e948aa9277abd5c85ff99d9950d8527f/matchzoo/preprocessors/units/matching_histogram.py#L36-L42
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/asyncio/events.py
python
AbstractEventLoop.is_running
(self)
Return whether the event loop is currently running.
Return whether the event loop is currently running.
[ "Return", "whether", "the", "event", "loop", "is", "currently", "running", "." ]
def is_running(self): """Return whether the event loop is currently running.""" raise NotImplementedError
[ "def", "is_running", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/asyncio/events.py#L234-L236
derv82/wifite2
e190794149f488f9c4a2801962e5165b29e71b5e
wifite/tools/hashcat.py
python
Hashcat.crack_pmkid
(pmkid_file, verbose=False)
Cracks a given pmkid_file using the PMKID/WPA2 attack (-m 16800) Returns: Key (str) if found; `None` if not found.
Cracks a given pmkid_file using the PMKID/WPA2 attack (-m 16800) Returns: Key (str) if found; `None` if not found.
[ "Cracks", "a", "given", "pmkid_file", "using", "the", "PMKID", "/", "WPA2", "attack", "(", "-", "m", "16800", ")", "Returns", ":", "Key", "(", "str", ")", "if", "found", ";", "None", "if", "not", "found", "." ]
def crack_pmkid(pmkid_file, verbose=False): ''' Cracks a given pmkid_file using the PMKID/WPA2 attack (-m 16800) Returns: Key (str) if found; `None` if not found. ''' # Run hashcat once normally, then with --show if it failed # To catch cases where the password is already in the pot file. for additional_arg in ([], ['--show']): command = [ 'hashcat', '--quiet', # Only output the password if found. '-m', '16800', # WPA-PMKID-PBKDF2 '-a', '0', # Wordlist attack-mode pmkid_file, Configuration.wordlist ] if Hashcat.should_use_force(): command.append('--force') command.extend(additional_arg) if verbose and additional_arg == []: Color.pl('{+} {D}Running: {W}{P}%s{W}' % ' '.join(command)) # TODO: Check status of hashcat (%); it's impossible with --quiet hashcat_proc = Process(command) hashcat_proc.wait() stdout = hashcat_proc.stdout() if ':' not in stdout: # Failed continue else: # Cracked key = stdout.strip().split(':', 1)[1] return key
[ "def", "crack_pmkid", "(", "pmkid_file", ",", "verbose", "=", "False", ")", ":", "# Run hashcat once normally, then with --show if it failed", "# To catch cases where the password is already in the pot file.", "for", "additional_arg", "in", "(", "[", "]", ",", "[", "'--show'"...
https://github.com/derv82/wifite2/blob/e190794149f488f9c4a2801962e5165b29e71b5e/wifite/tools/hashcat.py#L59-L95
avirambh/MSDNet-GCN
818246e3e38030e0d97c47f8aa1f39e125a0091c
models/msdnet_layers.py
python
MSDLayer.build_densenet
(self, in_channels, out_channels, bottleneck, bn_width)
return _DynamicInputDenseBlock(nn.ModuleList([conv_module]), self.debug)
Builds a scale sub-network for the first layer :param in_channels: number of input channels :param out_channels: number of output channels :param bottleneck: A flag to perform a channel dimension bottleneck :param bn_width: The width of the bottleneck factor :return: A scale module
Builds a scale sub-network for the first layer
[ "Builds", "a", "scale", "sub", "-", "network", "for", "the", "first", "layer" ]
def build_densenet(self, in_channels, out_channels, bottleneck, bn_width): """ Builds a scale sub-network for the first layer :param in_channels: number of input channels :param out_channels: number of output channels :param bottleneck: A flag to perform a channel dimension bottleneck :param bn_width: The width of the bottleneck factor :return: A scale module """ conv_module = self.convolve(in_channels, out_channels, 'normal', bottleneck, bn_width) return _DynamicInputDenseBlock(nn.ModuleList([conv_module]), self.debug)
[ "def", "build_densenet", "(", "self", ",", "in_channels", ",", "out_channels", ",", "bottleneck", ",", "bn_width", ")", ":", "conv_module", "=", "self", ".", "convolve", "(", "in_channels", ",", "out_channels", ",", "'normal'", ",", "bottleneck", ",", "bn_widt...
https://github.com/avirambh/MSDNet-GCN/blob/818246e3e38030e0d97c47f8aa1f39e125a0091c/models/msdnet_layers.py#L166-L179
lingtengqiu/Deeperlab-pytorch
5c500780a6655ff343d147477402aa20e0ed7a7c
engine/engine.py
python
Engine.__enter__
(self)
return self
[]
def __enter__(self): return self
[ "def", "__enter__", "(", "self", ")", ":", "return", "self" ]
https://github.com/lingtengqiu/Deeperlab-pytorch/blob/5c500780a6655ff343d147477402aa20e0ed7a7c/engine/engine.py#L150-L151
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/linear_model/logistic_regression/hetero_logistic_regression/hetero_lr_host.py
python
HeteroLRHost.fit
(self, data_instances, validate_data=None)
Train lr model of role host Parameters ---------- data_instances: Table of Instance, input data
Train lr model of role host Parameters ---------- data_instances: Table of Instance, input data
[ "Train", "lr", "model", "of", "role", "host", "Parameters", "----------", "data_instances", ":", "Table", "of", "Instance", "input", "data" ]
def fit(self, data_instances, validate_data=None): """ Train lr model of role host Parameters ---------- data_instances: Table of Instance, input data """ LOGGER.info("Enter hetero_logistic_regression host") self.header = self.get_header(data_instances) classes = self.one_vs_rest_obj.get_data_classes(data_instances) if len(classes) > 2: self.need_one_vs_rest = True self.need_call_back_loss = False self.one_vs_rest_fit(train_data=data_instances, validate_data=validate_data) else: self.need_one_vs_rest = False self.fit_binary(data_instances, validate_data)
[ "def", "fit", "(", "self", ",", "data_instances", ",", "validate_data", "=", "None", ")", ":", "LOGGER", ".", "info", "(", "\"Enter hetero_logistic_regression host\"", ")", "self", ".", "header", "=", "self", ".", "get_header", "(", "data_instances", ")", "cla...
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/linear_model/logistic_regression/hetero_logistic_regression/hetero_lr_host.py#L71-L90
pyopenapi/pyswagger
333c4ca08e758cd2194943d9904a3eda3fe43977
pyswagger/scanner/v1_2/validate.py
python
Validate._validate_prop
(self, path, obj, _)
return path, obj.__class__.__name__, errs
validate option combination of Property object
validate option combination of Property object
[ "validate", "option", "combination", "of", "Property", "object" ]
def _validate_prop(self, path, obj, _): """ validate option combination of Property object """ errs = [] if obj.type == 'void': errs.append('void is only allowed in Operation object.') return path, obj.__class__.__name__, errs
[ "def", "_validate_prop", "(", "self", ",", "path", ",", "obj", ",", "_", ")", ":", "errs", "=", "[", "]", "if", "obj", ".", "type", "==", "'void'", ":", "errs", ".", "append", "(", "'void is only allowed in Operation object.'", ")", "return", "path", ","...
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L78-L85
suurjaak/Skyperious
6a4f264dbac8d326c2fa8aeb5483dbca987860bf
skyperious/gui.py
python
MainWindow.on_sys_colour_change
(self, event)
Handler for system colour change, updates filesystem images.
Handler for system colour change, updates filesystem images.
[ "Handler", "for", "system", "colour", "change", "updates", "filesystem", "images", "." ]
def on_sys_colour_change(self, event): """Handler for system colour change, updates filesystem images.""" event.Skip() self.adapt_colours() def after(): self.load_fs_images() for i in range(self.list_db.GetItemCount()): self.list_db.SetItemTextColour(i, self.list_db.ForegroundColour) self.list_db.SetItemBackgroundColour(i, self.list_db.BackgroundColour) wx.CallAfter(after)
[ "def", "on_sys_colour_change", "(", "self", ",", "event", ")", ":", "event", ".", "Skip", "(", ")", "self", ".", "adapt_colours", "(", ")", "def", "after", "(", ")", ":", "self", ".", "load_fs_images", "(", ")", "for", "i", "in", "range", "(", "self"...
https://github.com/suurjaak/Skyperious/blob/6a4f264dbac8d326c2fa8aeb5483dbca987860bf/skyperious/gui.py#L702-L711
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/wallet.py
python
Deterministic_Wallet.get_seed
(self, password)
return self.keystore.get_seed(password)
[]
def get_seed(self, password): return self.keystore.get_seed(password)
[ "def", "get_seed", "(", "self", ",", "password", ")", ":", "return", "self", ".", "keystore", ".", "get_seed", "(", "password", ")" ]
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/wallet.py#L2945-L2946
magenta/magenta
be6558f1a06984faff6d6949234f5fe9ad0ffdb5
magenta/models/image_stylization/model.py
python
upsampling
(input_, kernel_size, stride, num_outputs, scope, activation_fn=tf.nn.relu)
A smooth replacement of a same-padded transposed convolution. This function first computes a nearest-neighbor upsampling of the input by a factor of `stride`, then applies a mirror-padded, same-padded convolution. It expects `kernel_size` to be odd. Args: input_: 4-D Tensor input. kernel_size: int (odd-valued) representing the kernel size. stride: int representing the strides. num_outputs: int. Number of output feature maps. scope: str. Scope under which to operate. activation_fn: activation function. Returns: 4-D Tensor output. Raises: ValueError: if `kernel_size` is even.
A smooth replacement of a same-padded transposed convolution.
[ "A", "smooth", "replacement", "of", "a", "same", "-", "padded", "transposed", "convolution", "." ]
def upsampling(input_, kernel_size, stride, num_outputs, scope, activation_fn=tf.nn.relu): """A smooth replacement of a same-padded transposed convolution. This function first computes a nearest-neighbor upsampling of the input by a factor of `stride`, then applies a mirror-padded, same-padded convolution. It expects `kernel_size` to be odd. Args: input_: 4-D Tensor input. kernel_size: int (odd-valued) representing the kernel size. stride: int representing the strides. num_outputs: int. Number of output feature maps. scope: str. Scope under which to operate. activation_fn: activation function. Returns: 4-D Tensor output. Raises: ValueError: if `kernel_size` is even. """ if kernel_size % 2 == 0: raise ValueError('kernel_size is expected to be odd.') with tf.variable_scope(scope): shape = tf.shape(input_) height = shape[1] width = shape[2] upsampled_input = tf.image.resize_nearest_neighbor( input_, [stride * height, stride * width]) return conv2d( upsampled_input, kernel_size, 1, num_outputs, 'conv', activation_fn=activation_fn)
[ "def", "upsampling", "(", "input_", ",", "kernel_size", ",", "stride", ",", "num_outputs", ",", "scope", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ")", ":", "if", "kernel_size", "%", "2", "==", "0", ":", "raise", "ValueError", "(", "'ker...
https://github.com/magenta/magenta/blob/be6558f1a06984faff6d6949234f5fe9ad0ffdb5/magenta/models/image_stylization/model.py#L108-L149
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/TCLIService/TCLIService.py
python
GetResultSetMetadata_result.__eq__
(self, other)
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
[]
def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", "and", "self", ".", "__dict__", "==", "other", ".", "__dict__" ]
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/TCLIService/TCLIService.py#L3127-L3128
cleverhans-lab/cleverhans
e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d
cleverhans_v3.1.0/cleverhans/confidence_report.py
python
ConfidenceReportEntry.__getitem__
(self, key)
return self.__dict__[key]
[]
def __getitem__(self, key): warnings.warn( "Dictionary confidence report entries are deprecated. " "Switch to accessing the appropriate field of " "ConfidenceReportEntry. " "Dictionary-style access will be removed on or after " "2019-04-24." ) assert key in ["correctness", "confidence"] return self.__dict__[key]
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "warnings", ".", "warn", "(", "\"Dictionary confidence report entries are deprecated. \"", "\"Switch to accessing the appropriate field of \"", "\"ConfidenceReportEntry. \"", "\"Dictionary-style access will be removed on or after...
https://github.com/cleverhans-lab/cleverhans/blob/e5d00e537ce7ad6119ed5a8db1f0e9736d1f6e1d/cleverhans_v3.1.0/cleverhans/confidence_report.py#L112-L121
google-research/exoplanet-ml
3dfe65f7ae44443b124ae87b000c317237c7dc00
exoplanet-ml/experimental/beam/transit_search/bls_scorer.py
python
BlsScorer.ofir
(self, window_size, scatter_after_detrend=False, sqrt_power=False, normalize_by_bls_nbins=False)
return scores
Computes scores using the method of Ofir et al.
Computes scores using the method of Ofir et al.
[ "Computes", "scores", "using", "the", "method", "of", "Ofir", "et", "al", "." ]
def ofir(self, window_size, scatter_after_detrend=False, sqrt_power=False, normalize_by_bls_nbins=False): """Computes scores using the method of Ofir et al.""" powers = self.power(sqrt_power, normalize_by_bls_nbins) trend = scipy.signal.medfilt(powers, window_size) scores = powers - trend if scatter_after_detrend: scatter = np.abs(np.diff(scores)) else: scatter = np.abs(np.diff(powers)) # Diff returns a vector one less than the length of powers. We prepend the # first diff to make the sizes match. scatter = np.concatenate([[scatter[0]], scatter]) scatter_trend = scipy.signal.medfilt(scatter, window_size) scores /= scatter_trend return scores
[ "def", "ofir", "(", "self", ",", "window_size", ",", "scatter_after_detrend", "=", "False", ",", "sqrt_power", "=", "False", ",", "normalize_by_bls_nbins", "=", "False", ")", ":", "powers", "=", "self", ".", "power", "(", "sqrt_power", ",", "normalize_by_bls_n...
https://github.com/google-research/exoplanet-ml/blob/3dfe65f7ae44443b124ae87b000c317237c7dc00/exoplanet-ml/experimental/beam/transit_search/bls_scorer.py#L240-L263
NetManAIOps/OmniAnomaly
7fb0e0acf89ea49908896bcc9f9e80fcfff6baf4
omni_anomaly/spot.py
python
dSPOT._quantile
(self, gamma, sigma)
Compute the quantile at level 1-q Parameters ---------- gamma : float GPD parameter sigma : float GPD parameter Returns ---------- float quantile at level 1-q for the GPD(γ,σ,μ=0)
Compute the quantile at level 1-q Parameters ---------- gamma : float GPD parameter sigma : float GPD parameter
[ "Compute", "the", "quantile", "at", "level", "1", "-", "q", "Parameters", "----------", "gamma", ":", "float", "GPD", "parameter", "sigma", ":", "float", "GPD", "parameter" ]
def _quantile(self, gamma, sigma): """ Compute the quantile at level 1-q Parameters ---------- gamma : float GPD parameter sigma : float GPD parameter Returns ---------- float quantile at level 1-q for the GPD(γ,σ,μ=0) """ r = self.n * self.proba / self.Nt if gamma != 0: return self.init_threshold + (sigma / gamma) * (pow(r, -gamma) - 1) else: return self.init_threshold - sigma * log(r)
[ "def", "_quantile", "(", "self", ",", "gamma", ",", "sigma", ")", ":", "r", "=", "self", ".", "n", "*", "self", ".", "proba", "/", "self", ".", "Nt", "if", "gamma", "!=", "0", ":", "return", "self", ".", "init_threshold", "+", "(", "sigma", "/", ...
https://github.com/NetManAIOps/OmniAnomaly/blob/7fb0e0acf89ea49908896bcc9f9e80fcfff6baf4/omni_anomaly/spot.py#L1367-L1387
leoribeiro/struc2vec
67da70bb75fdf17239e12bf90e1945256270acd8
src/main.py
python
main
(args)
[]
def main(args): G = exec_struc2vec(args) learn_embeddings()
[ "def", "main", "(", "args", ")", ":", "G", "=", "exec_struc2vec", "(", "args", ")", "learn_embeddings", "(", ")" ]
https://github.com/leoribeiro/struc2vec/blob/67da70bb75fdf17239e12bf90e1945256270acd8/src/main.py#L119-L123
HewlettPackard/dlcookbook-dlbs
863ac1d7e72ad2fcafc78d8a13f67d35bc00c235
python/tf_cnn_benchmarks/models/resnet_model.py
python
residual_block
(cnn, depth, stride, pre_activation)
Residual block with identity short-cut. Args: cnn: the network to append residual blocks. depth: the number of output filters for this residual block. stride: Stride used in the first layer of the residual block. pre_activation: use pre_activation structure or not.
Residual block with identity short-cut.
[ "Residual", "block", "with", "identity", "short", "-", "cut", "." ]
def residual_block(cnn, depth, stride, pre_activation): """Residual block with identity short-cut. Args: cnn: the network to append residual blocks. depth: the number of output filters for this residual block. stride: Stride used in the first layer of the residual block. pre_activation: use pre_activation structure or not. """ input_layer = cnn.top_layer in_size = cnn.top_size if in_size != depth: # Plan A of shortcut. shortcut = cnn.apool(1, 1, stride, stride, input_layer=input_layer, num_channels_in=in_size) padding = (depth - in_size) // 2 if cnn.channel_pos == 'channels_last': shortcut = tf.pad( shortcut, [[0, 0], [0, 0], [0, 0], [padding, padding]]) else: shortcut = tf.pad( shortcut, [[0, 0], [padding, padding], [0, 0], [0, 0]]) else: shortcut = input_layer if pre_activation: res = cnn.batch_norm(input_layer) res = tf.nn.relu(res) else: res = input_layer cnn.conv(depth, 3, 3, stride, stride, input_layer=res, num_channels_in=in_size, use_batch_norm=True, bias=None) if pre_activation: res = cnn.conv(depth, 3, 3, 1, 1, activation=None, use_batch_norm=False, bias=None) output = shortcut + res else: res = cnn.conv(depth, 3, 3, 1, 1, activation=None, use_batch_norm=True, bias=None) output = tf.nn.relu(shortcut + res) cnn.top_layer = output cnn.top_size = depth
[ "def", "residual_block", "(", "cnn", ",", "depth", ",", "stride", ",", "pre_activation", ")", ":", "input_layer", "=", "cnn", ".", "top_layer", "in_size", "=", "cnn", ".", "top_size", "if", "in_size", "!=", "depth", ":", "# Plan A of shortcut.", "shortcut", ...
https://github.com/HewlettPackard/dlcookbook-dlbs/blob/863ac1d7e72ad2fcafc78d8a13f67d35bc00c235/python/tf_cnn_benchmarks/models/resnet_model.py#L208-L250
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/base_team.py
python
DropboxTeamBase.team_legal_holds_release_policy
(self, id)
return None
Releases a legal hold by Id. Note: Legal Holds is a paid add-on. Not all teams have the feature. Permission : Team member file access. :param str id: The legal hold Id. :rtype: None :raises: :class:`.exceptions.ApiError` If this raises, ApiError will contain: :class:`dropbox.team.LegalHoldsPolicyReleaseError`
Releases a legal hold by Id. Note: Legal Holds is a paid add-on. Not all teams have the feature. Permission : Team member file access.
[ "Releases", "a", "legal", "hold", "by", "Id", ".", "Note", ":", "Legal", "Holds", "is", "a", "paid", "add", "-", "on", ".", "Not", "all", "teams", "have", "the", "feature", ".", "Permission", ":", "Team", "member", "file", "access", "." ]
def team_legal_holds_release_policy(self, id): """ Releases a legal hold by Id. Note: Legal Holds is a paid add-on. Not all teams have the feature. Permission : Team member file access. :param str id: The legal hold Id. :rtype: None :raises: :class:`.exceptions.ApiError` If this raises, ApiError will contain: :class:`dropbox.team.LegalHoldsPolicyReleaseError` """ arg = team.LegalHoldsPolicyReleaseArg(id) r = self.request( team.legal_holds_release_policy, 'team', arg, None, ) return None
[ "def", "team_legal_holds_release_policy", "(", "self", ",", "id", ")", ":", "arg", "=", "team", ".", "LegalHoldsPolicyReleaseArg", "(", "id", ")", "r", "=", "self", ".", "request", "(", "team", ".", "legal_holds_release_policy", ",", "'team'", ",", "arg", ",...
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/base_team.py#L862-L882
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/miranda/miranda.py
python
upnp.listen
(self,size,socket)
[]
def listen(self,size,socket): if socket == False: socket = self.ssock try: return socket.recv(size) except: return False
[ "def", "listen", "(", "self", ",", "size", ",", "socket", ")", ":", "if", "socket", "==", "False", ":", "socket", "=", "self", ".", "ssock", "try", ":", "return", "socket", ".", "recv", "(", "size", ")", "except", ":", "return", "False" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/miranda/miranda.py#L159-L166
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/tkinter/__init__.py
python
Listbox.scan_dragto
(self, x, y)
Adjust the view of the listbox to 10 times the difference between X and Y and the coordinates given in scan_mark.
Adjust the view of the listbox to 10 times the difference between X and Y and the coordinates given in scan_mark.
[ "Adjust", "the", "view", "of", "the", "listbox", "to", "10", "times", "the", "difference", "between", "X", "and", "Y", "and", "the", "coordinates", "given", "in", "scan_mark", "." ]
def scan_dragto(self, x, y): """Adjust the view of the listbox to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y)
[ "def", "scan_dragto", "(", "self", ",", "x", ",", "y", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'scan'", ",", "'dragto'", ",", "x", ",", "y", ")" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/tkinter/__init__.py#L2657-L2661
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/nltk/collocations.py
python
AbstractCollocationFinder._score_ngrams
(self, score_fn)
Generates of (ngram, score) pairs as determined by the scoring function provided.
Generates of (ngram, score) pairs as determined by the scoring function provided.
[ "Generates", "of", "(", "ngram", "score", ")", "pairs", "as", "determined", "by", "the", "scoring", "function", "provided", "." ]
def _score_ngrams(self, score_fn): """Generates of (ngram, score) pairs as determined by the scoring function provided. """ for tup in self.ngram_fd: score = self.score_ngram(score_fn, *tup) if score is not None: yield tup, score
[ "def", "_score_ngrams", "(", "self", ",", "score_fn", ")", ":", "for", "tup", "in", "self", ".", "ngram_fd", ":", "score", "=", "self", ".", "score_ngram", "(", "score_fn", ",", "*", "tup", ")", "if", "score", "is", "not", "None", ":", "yield", "tup"...
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/collocations.py#L120-L127
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/core/units.py
python
obj_with_unit
(obj, unit)
return ArrayWithUnit(obj, unit=unit, unit_type=unit_type)
Returns a `FloatWithUnit` instance if obj is scalar, a dictionary of objects with units if obj is a dict, else an instance of `ArrayWithFloatWithUnit`. Args: unit: Specific units (eV, Ha, m, ang, etc.).
Returns a `FloatWithUnit` instance if obj is scalar, a dictionary of objects with units if obj is a dict, else an instance of `ArrayWithFloatWithUnit`.
[ "Returns", "a", "FloatWithUnit", "instance", "if", "obj", "is", "scalar", "a", "dictionary", "of", "objects", "with", "units", "if", "obj", "is", "a", "dict", "else", "an", "instance", "of", "ArrayWithFloatWithUnit", "." ]
def obj_with_unit(obj, unit): """ Returns a `FloatWithUnit` instance if obj is scalar, a dictionary of objects with units if obj is a dict, else an instance of `ArrayWithFloatWithUnit`. Args: unit: Specific units (eV, Ha, m, ang, etc.). """ unit_type = _UNAME2UTYPE[unit] if isinstance(obj, numbers.Number): return FloatWithUnit(obj, unit=unit, unit_type=unit_type) if isinstance(obj, collections.Mapping): return {k: obj_with_unit(v, unit) for k, v in obj.items()} return ArrayWithUnit(obj, unit=unit, unit_type=unit_type)
[ "def", "obj_with_unit", "(", "obj", ",", "unit", ")", ":", "unit_type", "=", "_UNAME2UTYPE", "[", "unit", "]", "if", "isinstance", "(", "obj", ",", "numbers", ".", "Number", ")", ":", "return", "FloatWithUnit", "(", "obj", ",", "unit", "=", "unit", ","...
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/core/units.py#L778-L793
googleanalytics/google-analytics-super-proxy
f5bad82eb1375d222638423e6ae302173a9a7948
src/controllers/util/query_helper.py
python
DeleteApiQueryResponses
(api_query)
Deletes an API Query saved response. Args: api_query: The API Query for which to delete the response.
Deletes an API Query saved response.
[ "Deletes", "an", "API", "Query", "saved", "response", "." ]
def DeleteApiQueryResponses(api_query): """Deletes an API Query saved response. Args: api_query: The API Query for which to delete the response. """ if api_query and api_query.api_query_responses: db.delete(api_query.api_query_responses)
[ "def", "DeleteApiQueryResponses", "(", "api_query", ")", ":", "if", "api_query", "and", "api_query", ".", "api_query_responses", ":", "db", ".", "delete", "(", "api_query", ".", "api_query_responses", ")" ]
https://github.com/googleanalytics/google-analytics-super-proxy/blob/f5bad82eb1375d222638423e6ae302173a9a7948/src/controllers/util/query_helper.py#L196-L203
arrayfire/arrayfire-python
96fa9768ee02e5fb5ffcaf3d1f744c898b141637
arrayfire/signal.py
python
ifft
(signal, dim0 = None , scale = None)
return output
Inverse Fast Fourier Transform: 1D Parameters ---------- signal: af.Array A 1 dimensional signal or a batch of 1 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1.0 / (dim0) Returns ------- output: af.Array A complex af.Array containing the full output of the inverse fft. Note ---- The output is always complex.
Inverse Fast Fourier Transform: 1D
[ "Inverse", "Fast", "Fourier", "Transform", ":", "1D" ]
def ifft(signal, dim0 = None , scale = None): """ Inverse Fast Fourier Transform: 1D Parameters ---------- signal: af.Array A 1 dimensional signal or a batch of 1 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1.0 / (dim0) Returns ------- output: af.Array A complex af.Array containing the full output of the inverse fft. Note ---- The output is always complex. """ if dim0 is None: dim0 = signal.dims()[0] if scale is None: scale = 1.0/float(dim0) output = Array() safe_call(backend.get().af_ifft(c_pointer(output.arr), signal.arr, c_double_t(scale), c_dim_t(dim0))) return output
[ "def", "ifft", "(", "signal", ",", "dim0", "=", "None", ",", "scale", "=", "None", ")", ":", "if", "dim0", "is", "None", ":", "dim0", "=", "signal", ".", "dims", "(", ")", "[", "0", "]", "if", "scale", "is", "None", ":", "scale", "=", "1.0", ...
https://github.com/arrayfire/arrayfire-python/blob/96fa9768ee02e5fb5ffcaf3d1f744c898b141637/arrayfire/signal.py#L441-L480
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/sklearn/svm/base.py
python
BaseSVC.predict_proba
(self)
return self._predict_proba
Compute probabilities of possible outcomes for samples in X. The model need to have probability information computed at training time: fit with attribute `probability` set to True. Parameters ---------- X : array-like, shape (n_samples, n_features) For kernel="precomputed", the expected shape of X is [n_samples_test, n_samples_train] Returns ------- T : array-like, shape (n_samples, n_classes) Returns the probability of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute `classes_`. Notes ----- The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets.
Compute probabilities of possible outcomes for samples in X.
[ "Compute", "probabilities", "of", "possible", "outcomes", "for", "samples", "in", "X", "." ]
def predict_proba(self): """Compute probabilities of possible outcomes for samples in X. The model need to have probability information computed at training time: fit with attribute `probability` set to True. Parameters ---------- X : array-like, shape (n_samples, n_features) For kernel="precomputed", the expected shape of X is [n_samples_test, n_samples_train] Returns ------- T : array-like, shape (n_samples, n_classes) Returns the probability of the sample for each class in the model. The columns correspond to the classes in sorted order, as they appear in the attribute `classes_`. Notes ----- The probability model is created using cross validation, so the results can be slightly different than those obtained by predict. Also, it will produce meaningless results on very small datasets. """ self._check_proba() return self._predict_proba
[ "def", "predict_proba", "(", "self", ")", ":", "self", ".", "_check_proba", "(", ")", "return", "self", ".", "_predict_proba" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/svm/base.py#L589-L616
digidotcom/xbee-python
0757f4be0017530c205175fbee8f9f61be9614d1
digi/xbee/models/filesystem.py
python
OpenDirCmdResponse.is_last
(self)
return False
Returns whether there are more elements not included in this response. Returns: Boolean: `True` if there are no more elements to list, `False` otherwise.
Returns whether there are more elements not included in this response.
[ "Returns", "whether", "there", "are", "more", "elements", "not", "included", "in", "this", "response", "." ]
def is_last(self): """ Returns whether there are more elements not included in this response. Returns: Boolean: `True` if there are no more elements to list, `False` otherwise. """ for item in self._fs_entries: if not item: continue if bool(item[0] & DirResponseFlag.IS_LAST): return True return False
[ "def", "is_last", "(", "self", ")", ":", "for", "item", "in", "self", ".", "_fs_entries", ":", "if", "not", "item", ":", "continue", "if", "bool", "(", "item", "[", "0", "]", "&", "DirResponseFlag", ".", "IS_LAST", ")", ":", "return", "True", "return...
https://github.com/digidotcom/xbee-python/blob/0757f4be0017530c205175fbee8f9f61be9614d1/digi/xbee/models/filesystem.py#L1969-L1983
mpenning/ciscoconfparse
a6a176e6ceac7c5f3e974272fa70273476ba84a3
ciscoconfparse/models_nxos.py
python
BaseNXOSIntfLine.has_ip_accessgroup_in
(self)
return bool(self.ipv4_accessgroup_in)
[]
def has_ip_accessgroup_in(self): return bool(self.ipv4_accessgroup_in)
[ "def", "has_ip_accessgroup_in", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "ipv4_accessgroup_in", ")" ]
https://github.com/mpenning/ciscoconfparse/blob/a6a176e6ceac7c5f3e974272fa70273476ba84a3/ciscoconfparse/models_nxos.py#L1637-L1638
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/multiprocessing/util.py
python
debug
(msg, *args)
[]
def debug(msg, *args): if _logger: _logger.log(DEBUG, msg, *args)
[ "def", "debug", "(", "msg", ",", "*", "args", ")", ":", "if", "_logger", ":", "_logger", ".", "log", "(", "DEBUG", ",", "msg", ",", "*", "args", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/multiprocessing/util.py#L72-L74
awslabs/aws-servicebroker
c301912e7df3a2f09a9c34d3ae7ffe67c55aa3a0
sample-apps/rds/sample-app/src/bottle.py
python
redirect
(url, code=None)
Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version.
Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version.
[ "Aborts", "execution", "and", "causes", "a", "303", "or", "302", "redirect", "depending", "on", "the", "HTTP", "protocol", "version", "." ]
def redirect(url, code=None): """ Aborts execution and causes a 303 or 302 redirect, depending on the HTTP protocol version. """ if not code: code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302 res = response.copy(cls=HTTPResponse) res.status = code res.body = "" res.set_header('Location', urljoin(request.url, url)) raise res
[ "def", "redirect", "(", "url", ",", "code", "=", "None", ")", ":", "if", "not", "code", ":", "code", "=", "303", "if", "request", ".", "get", "(", "'SERVER_PROTOCOL'", ")", "==", "\"HTTP/1.1\"", "else", "302", "res", "=", "response", ".", "copy", "("...
https://github.com/awslabs/aws-servicebroker/blob/c301912e7df3a2f09a9c34d3ae7ffe67c55aa3a0/sample-apps/rds/sample-app/src/bottle.py#L2423-L2432
pyqt/examples
843bb982917cecb2350b5f6d7f42c9b7fb142ec1
src/pyqt-official/itemviews/customsortfiltermodel.py
python
MySortFilterProxyModel.setFilterMaximumDate
(self, date)
[]
def setFilterMaximumDate(self, date): self.maxDate = date self.invalidateFilter()
[ "def", "setFilterMaximumDate", "(", "self", ",", "date", ")", ":", "self", ".", "maxDate", "=", "date", "self", ".", "invalidateFilter", "(", ")" ]
https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/itemviews/customsortfiltermodel.py#L68-L70
dr-costas/mad-twinnet
446e49a423a4375e5ceedab5eb51bead1057d06b
helpers/arg_parsing.py
python
get_argument_parser
()
return cmd_arg_parser
Creates and return the CMD argument parser. :return: The CMD argument parser. :rtype: argparse.ArgumentParser
Creates and return the CMD argument parser.
[ "Creates", "and", "return", "the", "CMD", "argument", "parser", "." ]
def get_argument_parser(): """Creates and return the CMD argument parser. :return: The CMD argument parser. :rtype: argparse.ArgumentParser """ cmd_arg_parser = argparse.ArgumentParser( usage='python scripts/use_me [-w the_file.wav]|[-l the_files.txt]', description='Script to use the MaD TwinNet with your own files. Remember to set up properly' 'the PYTHONPATH environmental variable' ) cmd_arg_parser.add_argument( '--input-wav', '-w', action='store', dest='input_wav', default='', help='Specify one wav file to be processed.' ) cmd_arg_parser.add_argument( '--input-list', '-l', action='store', dest='input_list', default=[], help='Specify one txt file with each line to be one path for a wav file.' ) return cmd_arg_parser
[ "def", "get_argument_parser", "(", ")", ":", "cmd_arg_parser", "=", "argparse", ".", "ArgumentParser", "(", "usage", "=", "'python scripts/use_me [-w the_file.wav]|[-l the_files.txt]'", ",", "description", "=", "'Script to use the MaD TwinNet with your own files. Remember to set up...
https://github.com/dr-costas/mad-twinnet/blob/446e49a423a4375e5ceedab5eb51bead1057d06b/helpers/arg_parsing.py#L11-L33
Vector35/debugger
4eb67fa10a8d58704bfbca42d23b5989e0212968
DebugAdapter.py
python
DebugAdapter.breakpoint_list
(self)
return list of addresses
return list of addresses
[ "return", "list", "of", "addresses" ]
def breakpoint_list(self): ''' return list of addresses ''' raise NotImplementedError('')
[ "def", "breakpoint_list", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "''", ")" ]
https://github.com/Vector35/debugger/blob/4eb67fa10a8d58704bfbca42d23b5989e0212968/DebugAdapter.py#L239-L241
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/rapi/client.py
python
GanetiRapiClient.RenameNetwork
(self, network, new_name, reason=None)
return self._SendRequest(HTTP_PUT, ("/%s/networks/%s/rename" % (GANETI_RAPI_VERSION, network)), query, body)
Changes the name of a network. @type network: string @param network: Network name @type new_name: string @param new_name: New network name @type reason: string @param reason: the reason for executing this operation @rtype: string @return: job id
Changes the name of a network.
[ "Changes", "the", "name", "of", "a", "network", "." ]
def RenameNetwork(self, network, new_name, reason=None): """Changes the name of a network. @type network: string @param network: Network name @type new_name: string @param new_name: New network name @type reason: string @param reason: the reason for executing this operation @rtype: string @return: job id """ body = { "new_name": new_name, } query = [] _AppendReason(query, reason) return self._SendRequest(HTTP_PUT, ("/%s/networks/%s/rename" % (GANETI_RAPI_VERSION, network)), query, body)
[ "def", "RenameNetwork", "(", "self", ",", "network", ",", "new_name", ",", "reason", "=", "None", ")", ":", "body", "=", "{", "\"new_name\"", ":", "new_name", ",", "}", "query", "=", "[", "]", "_AppendReason", "(", "query", ",", "reason", ")", "return"...
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/rapi/client.py#L2162-L2185