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
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/contrib/admin/checks.py
python
ModelAdminChecks._check_list_filter_item
(self, obj, model, item, label)
Check one item of `list_filter`, i.e. check if it is one of three options: 1. 'field' -- a basic field filter, possibly w/ relationships (e.g. 'field__rel') 2. ('field', SomeFieldListFilter) - a field-based list filter class 3. SomeListFilter - a non-field list filter class
Check one item of `list_filter`, i.e. check if it is one of three options: 1. 'field' -- a basic field filter, possibly w/ relationships (e.g. 'field__rel') 2. ('field', SomeFieldListFilter) - a field-based list filter class 3. SomeListFilter - a non-field list filter class
[ "Check", "one", "item", "of", "list_filter", "i", ".", "e", ".", "check", "if", "it", "is", "one", "of", "three", "options", ":", "1", ".", "field", "--", "a", "basic", "field", "filter", "possibly", "w", "/", "relationships", "(", "e", ".", "g", "...
def _check_list_filter_item(self, obj, model, item, label): """ Check one item of `list_filter`, i.e. check if it is one of three options: 1. 'field' -- a basic field filter, possibly w/ relationships (e.g. 'field__rel') 2. ('field', SomeFieldListFilter) - a field-based list filter class 3. SomeListFilter - a non-field list filter class """ from django.contrib.admin import ListFilter, FieldListFilter if callable(item) and not isinstance(item, models.Field): # If item is option 3, it should be a ListFilter... if not issubclass(item, ListFilter): return must_inherit_from(parent='ListFilter', option=label, obj=obj, id='admin.E113') # ... but not a FieldListFilter. elif issubclass(item, FieldListFilter): return [ checks.Error( "The value of '%s' must not inherit from 'FieldListFilter'." % label, obj=obj.__class__, id='admin.E114', ) ] else: return [] elif isinstance(item, (tuple, list)): # item is option #2 field, list_filter_class = item if not issubclass(list_filter_class, FieldListFilter): return must_inherit_from(parent='FieldListFilter', option='%s[1]' % label, obj=obj, id='admin.E115') else: return [] else: # item is option #1 field = item # Validate the field string try: get_fields_from_path(model, field) except (NotRelationField, FieldDoesNotExist): return [ checks.Error( "The value of '%s' refers to '%s', which does not refer to a Field." % (label, field), obj=obj.__class__, id='admin.E116', ) ] else: return []
[ "def", "_check_list_filter_item", "(", "self", ",", "obj", ",", "model", ",", "item", ",", "label", ")", ":", "from", "django", ".", "contrib", ".", "admin", "import", "ListFilter", ",", "FieldListFilter", "if", "callable", "(", "item", ")", "and", "not", ...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/admin/checks.py#L700-L750
taokong/FoveaBox
50ce41e5af9cfba562877a318231e53c3b3ce767
mmdet/core/utils/misc.py
python
unmap
(data, count, inds, fill=0)
return ret
Unmap a subset of item (data) back to the original set of items (of size count)
Unmap a subset of item (data) back to the original set of items (of size count)
[ "Unmap", "a", "subset", "of", "item", "(", "data", ")", "back", "to", "the", "original", "set", "of", "items", "(", "of", "size", "count", ")" ]
def unmap(data, count, inds, fill=0): """ Unmap a subset of item (data) back to the original set of items (of size count) """ if data.dim() == 1: ret = data.new_full((count, ), fill) ret[inds] = data else: new_size = (count, ) + data.size()[1:] ret = data.new_full(new_size, fill) ret[inds, :] = data return ret
[ "def", "unmap", "(", "data", ",", "count", ",", "inds", ",", "fill", "=", "0", ")", ":", "if", "data", ".", "dim", "(", ")", "==", "1", ":", "ret", "=", "data", ".", "new_full", "(", "(", "count", ",", ")", ",", "fill", ")", "ret", "[", "in...
https://github.com/taokong/FoveaBox/blob/50ce41e5af9cfba562877a318231e53c3b3ce767/mmdet/core/utils/misc.py#L27-L37
Pagure/pagure
512f23f5cd1f965276969747792edeb1215cba68
pagure/ui/login.py
python
change_password
()
return flask.render_template("login/password_recover.html", form=form)
Method to change the password for local auth users.
Method to change the password for local auth users.
[ "Method", "to", "change", "the", "password", "for", "local", "auth", "users", "." ]
def change_password(): """Method to change the password for local auth users.""" form = forms.ChangePasswordForm() user_obj = pagure.lib.query.search_user( flask.g.session, username=flask.g.fas_user.username ) if not user_obj: flask.abort(404, description="User not found") if form.validate_on_submit(): try: password_checks = check_password( form.old_password.data, user_obj.password, seed=pagure.config.config.get("PASSWORD_SEED", None), ) except pagure.exceptions.PagureException as err: _log.exception(err) flask.flash( "Could not update your password, either user or password " "could not be checked", "error", ) return flask.redirect(flask.url_for("auth_login")) if password_checks: user_obj.password = generate_hashed_value(form.password.data) flask.g.session.add(user_obj) else: flask.flash( "Could not update your password, either user or password " "could not be checked", "error", ) return flask.redirect(flask.url_for("auth_login")) try: flask.g.session.commit() flask.flash("Password changed") except SQLAlchemyError: # pragma: no cover flask.g.session.rollback() flask.flash("Could not set the new password.", "error") _log.exception("Password change - Error setting new password.") return flask.redirect(flask.url_for("auth_login")) return flask.render_template("login/password_recover.html", form=form)
[ "def", "change_password", "(", ")", ":", "form", "=", "forms", ".", "ChangePasswordForm", "(", ")", "user_obj", "=", "pagure", ".", "lib", ".", "query", ".", "search_user", "(", "flask", ".", "g", ".", "session", ",", "username", "=", "flask", ".", "g"...
https://github.com/Pagure/pagure/blob/512f23f5cd1f965276969747792edeb1215cba68/pagure/ui/login.py#L268-L318
honeynet/droidbot
2c7a66bda17c4cc33b4b4d9c98f27f822a81a6bd
droidbot/device.py
python
Device.set_continuous_gps_blocked
(self, center_x, center_y, delta_x, delta_y)
simulate GPS on device via telnet this method is blocked @param center_x: x coordinate of GPS position @param center_y: y coordinate of GPS position @param delta_x: range of x coordinate @param delta_y: range of y coordinate
simulate GPS on device via telnet this method is blocked
[ "simulate", "GPS", "on", "device", "via", "telnet", "this", "method", "is", "blocked" ]
def set_continuous_gps_blocked(self, center_x, center_y, delta_x, delta_y): """ simulate GPS on device via telnet this method is blocked @param center_x: x coordinate of GPS position @param center_y: y coordinate of GPS position @param delta_x: range of x coordinate @param delta_y: range of y coordinate """ import random while self.connected: x = random.random() * delta_x * 2 + center_x - delta_x y = random.random() * delta_y * 2 + center_y - delta_y self.set_gps(x, y) time.sleep(3)
[ "def", "set_continuous_gps_blocked", "(", "self", ",", "center_x", ",", "center_y", ",", "delta_x", ",", "delta_y", ")", ":", "import", "random", "while", "self", ".", "connected", ":", "x", "=", "random", ".", "random", "(", ")", "*", "delta_x", "*", "2...
https://github.com/honeynet/droidbot/blob/2c7a66bda17c4cc33b4b4d9c98f27f822a81a6bd/droidbot/device.py#L404-L418
openbmc/openbmc
5f4109adae05f4d6925bfe960007d52f98c61086
poky/bitbake/lib/bb/pysh/pyshlex.py
python
Lexer.add
(self, data, eof=False)
return ''.join(self._input)
Feed the lexer with data. When eof is set to True, returns unconsumed data or raise if the lexer is in the middle of a delimiting operation. Raise NeedMore otherwise.
Feed the lexer with data. When eof is set to True, returns unconsumed data or raise if the lexer is in the middle of a delimiting operation. Raise NeedMore otherwise.
[ "Feed", "the", "lexer", "with", "data", ".", "When", "eof", "is", "set", "to", "True", "returns", "unconsumed", "data", "or", "raise", "if", "the", "lexer", "is", "in", "the", "middle", "of", "a", "delimiting", "operation", ".", "Raise", "NeedMore", "oth...
def add(self, data, eof=False): """Feed the lexer with data. When eof is set to True, returns unconsumed data or raise if the lexer is in the middle of a delimiting operation. Raise NeedMore otherwise. """ self._input += list(data) self._parse(eof) self._input[:self._pos] = [] return ''.join(self._input)
[ "def", "add", "(", "self", ",", "data", ",", "eof", "=", "False", ")", ":", "self", ".", "_input", "+=", "list", "(", "data", ")", "self", ".", "_parse", "(", "eof", ")", "self", ".", "_input", "[", ":", "self", ".", "_pos", "]", "=", "[", "]...
https://github.com/openbmc/openbmc/blob/5f4109adae05f4d6925bfe960007d52f98c61086/poky/bitbake/lib/bb/pysh/pyshlex.py#L568-L578
google/timesketch
1ce6b60e125d104e6644947c6f1dbe1b82ac76b6
timesketch/models/acl.py
python
AccessControlMixin._get_ace
(self, permission, user=None, group=None, check_group=True)
return ace
Get the specific access control entry for the user and permission. Args: permission: Permission as string (read, write or delete) user: A user (Instance of timesketch.models.user.User) group: A group (Instance of timesketch.models.user.Group) check_group: Check group permission, default is True. Returns: An ACE (instance of timesketch.models.acl.AccessControlEntry) or None if no ACE is found.
Get the specific access control entry for the user and permission.
[ "Get", "the", "specific", "access", "control", "entry", "for", "the", "user", "and", "permission", "." ]
def _get_ace(self, permission, user=None, group=None, check_group=True): """Get the specific access control entry for the user and permission. Args: permission: Permission as string (read, write or delete) user: A user (Instance of timesketch.models.user.User) group: A group (Instance of timesketch.models.user.Group) check_group: Check group permission, default is True. Returns: An ACE (instance of timesketch.models.acl.AccessControlEntry) or None if no ACE is found. """ # If group is specified check if an ACE exist for it and return early. if group: return self.AccessControlEntry.query.filter_by( group=group, permission=permission, parent=self).all() # Check access for user. ace = self.AccessControlEntry.query.filter_by( user=user, group=None, permission=permission, parent=self).all() # If user doesn't have a direct ACE, check group permission. if (user and check_group) and not ace: group_intersection = set(user.groups) & set(self.groups) for _group in group_intersection: # Get group ACE with the requested permission. ace = self.AccessControlEntry.query.filter_by( group=_group, permission=permission, parent=self).all() if ace: return ace return ace
[ "def", "_get_ace", "(", "self", ",", "permission", ",", "user", "=", "None", ",", "group", "=", "None", ",", "check_group", "=", "True", ")", ":", "# If group is specified check if an ACE exist for it and return early.", "if", "group", ":", "return", "self", ".", ...
https://github.com/google/timesketch/blob/1ce6b60e125d104e6644947c6f1dbe1b82ac76b6/timesketch/models/acl.py#L143-L174
jchanvfx/NodeGraphQt
8b810ef469f839176f9c26bdd6496ff34d9b64a2
NodeGraphQt/base/node.py
python
BackdropNode.nodes
(self)
return [self.graph.get_node_by_id(nid) for nid in node_ids]
Returns nodes wrapped within the backdrop node. Returns: list[NodeGraphQt.BaseNode]: list of node under the backdrop.
Returns nodes wrapped within the backdrop node.
[ "Returns", "nodes", "wrapped", "within", "the", "backdrop", "node", "." ]
def nodes(self): """ Returns nodes wrapped within the backdrop node. Returns: list[NodeGraphQt.BaseNode]: list of node under the backdrop. """ node_ids = [n.id for n in self.view.get_nodes()] return [self.graph.get_node_by_id(nid) for nid in node_ids]
[ "def", "nodes", "(", "self", ")", ":", "node_ids", "=", "[", "n", ".", "id", "for", "n", "in", "self", ".", "view", ".", "get_nodes", "(", ")", "]", "return", "[", "self", ".", "graph", ".", "get_node_by_id", "(", "nid", ")", "for", "nid", "in", ...
https://github.com/jchanvfx/NodeGraphQt/blob/8b810ef469f839176f9c26bdd6496ff34d9b64a2/NodeGraphQt/base/node.py#L1276-L1284
chemlab/chemlab
c8730966316d101e24f39ac3b96b51282aba0abe
chemlab/graphics/transformations.py
python
superimposition_matrix
(v0, v1, scale=False, usesvd=True)
return affine_matrix_from_points(v0, v1, shear=False, scale=scale, usesvd=usesvd)
Return matrix to transform given 3D point set into second point set. v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 points. The parameters scale and usesvd are explained in the more general affine_matrix_from_points function. The returned matrix is a similarity or Eucledian transformation matrix. This function has a fast C implementation in transformations.c. >>> v0 = numpy.random.rand(3, 10) >>> M = superimposition_matrix(v0, v0) >>> numpy.allclose(M, numpy.identity(4)) True >>> R = random_rotation_matrix(numpy.random.random(3)) >>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]] >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20 >>> v0[3] = 1 >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> S = scale_matrix(random.random()) >>> T = translation_matrix(numpy.random.random(3)-0.5) >>> M = concatenate_matrices(T, R, S) >>> v1 = numpy.dot(M, v0) >>> v0[:3] += numpy.random.normal(0, 1e-9, 300).reshape(3, -1) >>> M = superimposition_matrix(v0, v1, scale=True) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v = numpy.empty((4, 100, 3)) >>> v[:, :, 0] = v0 >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0])) True
Return matrix to transform given 3D point set into second point set.
[ "Return", "matrix", "to", "transform", "given", "3D", "point", "set", "into", "second", "point", "set", "." ]
def superimposition_matrix(v0, v1, scale=False, usesvd=True): """Return matrix to transform given 3D point set into second point set. v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 points. The parameters scale and usesvd are explained in the more general affine_matrix_from_points function. The returned matrix is a similarity or Eucledian transformation matrix. This function has a fast C implementation in transformations.c. >>> v0 = numpy.random.rand(3, 10) >>> M = superimposition_matrix(v0, v0) >>> numpy.allclose(M, numpy.identity(4)) True >>> R = random_rotation_matrix(numpy.random.random(3)) >>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]] >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20 >>> v0[3] = 1 >>> v1 = numpy.dot(R, v0) >>> M = superimposition_matrix(v0, v1) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> S = scale_matrix(random.random()) >>> T = translation_matrix(numpy.random.random(3)-0.5) >>> M = concatenate_matrices(T, R, S) >>> v1 = numpy.dot(M, v0) >>> v0[:3] += numpy.random.normal(0, 1e-9, 300).reshape(3, -1) >>> M = superimposition_matrix(v0, v1, scale=True) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v0)) True >>> v = numpy.empty((4, 100, 3)) >>> v[:, :, 0] = v0 >>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False) >>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0])) True """ v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3] v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3] return affine_matrix_from_points(v0, v1, shear=False, scale=scale, usesvd=usesvd)
[ "def", "superimposition_matrix", "(", "v0", ",", "v1", ",", "scale", "=", "False", ",", "usesvd", "=", "True", ")", ":", "v0", "=", "numpy", ".", "array", "(", "v0", ",", "dtype", "=", "numpy", ".", "float64", ",", "copy", "=", "False", ")", "[", ...
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/graphics/transformations.py#L1039-L1087
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/core.py
python
ensure_virtualenv
(project, three=None, python=None, site_packages=None, pypi_mirror=None)
Creates a virtualenv, if one doesn't exist.
Creates a virtualenv, if one doesn't exist.
[ "Creates", "a", "virtualenv", "if", "one", "doesn", "t", "exist", "." ]
def ensure_virtualenv(project, three=None, python=None, site_packages=None, pypi_mirror=None): """Creates a virtualenv, if one doesn't exist.""" def abort(): sys.exit(1) if not project.virtualenv_exists: try: # Ensure environment variables are set properly. ensure_environment() # Ensure Python is available. python = ensure_python(project, three=three, python=python) if python is not None and not isinstance(python, str): python = python.path.as_posix() # Create the virtualenv. # Abort if --system (or running in a virtualenv). if project.s.PIPENV_USE_SYSTEM: click.echo( crayons.red( "You are attempting to re–create a virtualenv that " "Pipenv did not create. Aborting." ) ) sys.exit(1) do_create_virtualenv( project, python=python, site_packages=site_packages, pypi_mirror=pypi_mirror ) except KeyboardInterrupt: # If interrupted, cleanup the virtualenv. cleanup_virtualenv(project, bare=False) sys.exit(1) # If --three, --two, or --python were passed... elif (python) or (three is not None) or (site_packages is not None): project.s.USING_DEFAULT_PYTHON = False # Ensure python is installed before deleting existing virtual env python = ensure_python(project, three=three, python=python) if python is not None and not isinstance(python, str): python = python.path.as_posix() click.echo(crayons.red("Virtualenv already exists!"), err=True) # If VIRTUAL_ENV is set, there is a possibility that we are # going to remove the active virtualenv that the user cares # about, so confirm first. if "VIRTUAL_ENV" in os.environ: if not ( project.s.PIPENV_YES or click.confirm("Remove existing virtualenv?", default=True) ): abort() click.echo( crayons.normal(fix_utf8("Removing existing virtualenv..."), bold=True), err=True ) # Remove the virtualenv. cleanup_virtualenv(project, bare=True) # Call this function again. ensure_virtualenv( project, three=three, python=python, site_packages=site_packages, pypi_mirror=pypi_mirror, )
[ "def", "ensure_virtualenv", "(", "project", ",", "three", "=", "None", ",", "python", "=", "None", ",", "site_packages", "=", "None", ",", "pypi_mirror", "=", "None", ")", ":", "def", "abort", "(", ")", ":", "sys", ".", "exit", "(", "1", ")", "if", ...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/core.py#L441-L501
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/customer_negative_criterion_service/client.py
python
CustomerNegativeCriterionServiceClient.from_service_account_file
(cls, filename: str, *args, **kwargs)
return cls(*args, **kwargs)
Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: CustomerNegativeCriterionServiceClient: The constructed client.
Creates an instance of this client using the provided credentials file.
[ "Creates", "an", "instance", "of", "this", "client", "using", "the", "provided", "credentials", "file", "." ]
def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: CustomerNegativeCriterionServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename ) kwargs["credentials"] = credentials return cls(*args, **kwargs)
[ "def", "from_service_account_file", "(", "cls", ",", "filename", ":", "str", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "credentials", "=", "service_account", ".", "Credentials", ".", "from_service_account_file", "(", "filename", ")", "kwargs", "[", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/customer_negative_criterion_service/client.py#L139-L156
chainer/chainercv
7159616642e0be7c5b3ef380b848e16b7e99355b
chainercv/functions/ps_roi_max_pooling_2d.py
python
PSROIMaxPooling2D.backward_gpu
(self, inputs, gy)
return bottom_diff, None, None
[]
def backward_gpu(self, inputs, gy): _, bottom_rois, bottom_roi_indices = inputs channels, height, width = self._bottom_data_shape[1:] out_c, out_h, out_w = gy[0].shape[1:] bottom_diff = cuda.cupy.zeros(self._bottom_data_shape, np.float32) cuda.elementwise( ''' raw T top_diff, raw int32 argmax_data, raw T bottom_rois, raw int32 bottom_roi_indices, T spatial_scale, int32 channels, int32 height, int32 width, int32 pooled_dim, int32 pooled_height, int32 pooled_width, int32 group_size ''', 'raw T bottom_diff', ''' int ph = (i / pooled_width) % pooled_height; int pw = i % pooled_width; int ctop = (i / pooled_width / pooled_height) % pooled_dim; int n = i / pooled_width / pooled_height / pooled_dim; // [start, end) interval for spatial sampling int roi_batch_ind = bottom_roi_indices[n]; T roi_start_h = bottom_rois[n * 4 + 0] * spatial_scale; T roi_start_w = bottom_rois[n * 4 + 1] * spatial_scale; T roi_end_h = bottom_rois[n * 4 + 2] * spatial_scale; T roi_end_w = bottom_rois[n * 4 + 3] * spatial_scale; // Force too small ROIs to be 1x1 T roi_height = max(roi_end_h - roi_start_h, 0.1); T roi_width = max(roi_end_w - roi_start_w, 0.1); // avoid 0 // Compute w and h at bottom T bin_size_h = roi_height / static_cast<T>(pooled_height); T bin_size_w = roi_width / static_cast<T>(pooled_width); int hstart = floor( static_cast<T>(ph) * bin_size_h + roi_start_h); int wstart = floor( static_cast<T>(pw) * bin_size_w + roi_start_w); int hend = ceil( static_cast<T>(ph + 1.0) * bin_size_h + roi_start_h); int wend = ceil( static_cast<T>(pw + 1.0) * bin_size_w + roi_start_w); // Add roi offsets and clip to input boundaries hstart = min(max(hstart, 0), height); wstart = min(max(wstart, 0), width); hend = min(max(hend, 0), height); wend = min(max(wend, 0), width); // Compute c at bottom int gh = floor( static_cast<T>(ph) * group_size / pooled_height); int gw = floor( static_cast<T>(pw) * group_size / pooled_width); gh = min(max(gh, 0), group_size - 1); gw = min(max(gw, 0), group_size - 1); int c = (ctop * group_size + gh) * group_size + gw; int bottom_diff_offset = (roi_batch_ind * channels + c); bottom_diff_offset = bottom_diff_offset * height * width; int top_diff_offset = (n * pooled_dim + ctop) * pooled_height * pooled_width; int maxidx = argmax_data[top_diff_offset + ph * pooled_width + pw]; if (maxidx != -1) { atomicAdd( &bottom_diff[bottom_diff_offset + maxidx], top_diff[top_diff_offset + ph * pooled_width + pw]); } ''', 'ps_roi_max_pooling_2d_bwd' )(gy[0], self.argmax_data, bottom_rois, bottom_roi_indices, self.spatial_scale, channels, height, width, out_c, out_h, out_w, self.group_size, bottom_diff, size=gy[0].size) return bottom_diff, None, None
[ "def", "backward_gpu", "(", "self", ",", "inputs", ",", "gy", ")", ":", "_", ",", "bottom_rois", ",", "bottom_roi_indices", "=", "inputs", "channels", ",", "height", ",", "width", "=", "self", ".", "_bottom_data_shape", "[", "1", ":", "]", "out_c", ",", ...
https://github.com/chainer/chainercv/blob/7159616642e0be7c5b3ef380b848e16b7e99355b/chainercv/functions/ps_roi_max_pooling_2d.py#L315-L392
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/tools/appcfg.py
python
UploadBatcher.SendSingleFile
(self, path, payload, mime_type)
Send a single file on its way.
Send a single file on its way.
[ "Send", "a", "single", "file", "on", "its", "way", "." ]
def SendSingleFile(self, path, payload, mime_type): """Send a single file on its way.""" logging.info('Uploading %s %s (%s bytes, type=%s) to %s.', self.what, path, len(payload), mime_type, self.single_url) self.rpcserver.Send(self.single_url, payload=payload, content_type=mime_type, path=path, **self.params)
[ "def", "SendSingleFile", "(", "self", ",", "path", ",", "payload", ",", "mime_type", ")", ":", "logging", ".", "info", "(", "'Uploading %s %s (%s bytes, type=%s) to %s.'", ",", "self", ".", "what", ",", "path", ",", "len", "(", "payload", ")", ",", "mime_typ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/tools/appcfg.py#L1215-L1223
gdraheim/docker-systemctl-replacement
9cbe1a00eb4bdac6ff05b96ca34ec9ed3d8fc06c
files/docker/systemctl3.py
python
Systemctl.set_default_modules
(self, *modules)
return msg
set current default run-level
set current default run-level
[ "set", "current", "default", "run", "-", "level" ]
def set_default_modules(self, *modules): """ set current default run-level""" if not modules: logg.debug(".. no runlevel given") self.error |= NOT_OK return "Too few arguments" current = self.get_default_target() default_target_file = self.get_default_target_file() msg = "" for module in modules: if module == current: continue targetfile = None for targetname, targetpath in self.each_target_file(): if targetname == module: targetfile = targetpath if not targetfile: self.error |= NOT_OK | NOT_ACTIVE # 3 msg = "No such runlevel %s" % (module) continue # if os.path.islink(default_target_file): os.unlink(default_target_file) if not os.path.isdir(os.path.dirname(default_target_file)): os.makedirs(os.path.dirname(default_target_file)) os.symlink(targetfile, default_target_file) msg = "Created symlink from %s -> %s" % (default_target_file, targetfile) logg.debug("%s", msg) return msg
[ "def", "set_default_modules", "(", "self", ",", "*", "modules", ")", ":", "if", "not", "modules", ":", "logg", ".", "debug", "(", "\".. no runlevel given\"", ")", "self", ".", "error", "|=", "NOT_OK", "return", "\"Too few arguments\"", "current", "=", "self", ...
https://github.com/gdraheim/docker-systemctl-replacement/blob/9cbe1a00eb4bdac6ff05b96ca34ec9ed3d8fc06c/files/docker/systemctl3.py#L5609-L5637
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/dircache.py
python
listdir
(path)
return list
List directory contents, using cache.
List directory contents, using cache.
[ "List", "directory", "contents", "using", "cache", "." ]
def listdir(path): """List directory contents, using cache.""" try: cached_mtime, list = cache[path] del cache[path] except KeyError: cached_mtime, list = -1, [] mtime = os.stat(path).st_mtime if mtime != cached_mtime: list = os.listdir(path) list.sort() cache[path] = mtime, list return list
[ "def", "listdir", "(", "path", ")", ":", "try", ":", "cached_mtime", ",", "list", "=", "cache", "[", "path", "]", "del", "cache", "[", "path", "]", "except", "KeyError", ":", "cached_mtime", ",", "list", "=", "-", "1", ",", "[", "]", "mtime", "=", ...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/dircache.py#L21-L33
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
tokumx/datadog_checks/tokumx/vendor/bson/decimal128.py
python
_decimal_to_128
(value)
return high, low
Converts a decimal.Decimal to BID (high bits, low bits). :Parameters: - `value`: An instance of decimal.Decimal
Converts a decimal.Decimal to BID (high bits, low bits).
[ "Converts", "a", "decimal", ".", "Decimal", "to", "BID", "(", "high", "bits", "low", "bits", ")", "." ]
def _decimal_to_128(value): """Converts a decimal.Decimal to BID (high bits, low bits). :Parameters: - `value`: An instance of decimal.Decimal """ with decimal.localcontext(_DEC128_CTX) as ctx: value = ctx.create_decimal(value) if value.is_infinite(): return _NINF if value.is_signed() else _PINF sign, digits, exponent = value.as_tuple() if value.is_nan(): if digits: raise ValueError("NaN with debug payload is not supported") if value.is_snan(): return _NSNAN if value.is_signed() else _PSNAN return _NNAN if value.is_signed() else _PNAN significand = int("".join([str(digit) for digit in digits])) bit_length = _bit_length(significand) high = 0 low = 0 for i in range(min(64, bit_length)): if significand & (1 << i): low |= 1 << i for i in range(64, bit_length): if significand & (1 << i): high |= 1 << (i - 64) biased_exponent = exponent + _EXPONENT_BIAS if high >> 49 == 1: high = high & 0x7fffffffffff high |= _EXPONENT_MASK high |= (biased_exponent & 0x3fff) << 47 else: high |= biased_exponent << 49 if sign: high |= _SIGN return high, low
[ "def", "_decimal_to_128", "(", "value", ")", ":", "with", "decimal", ".", "localcontext", "(", "_DEC128_CTX", ")", "as", "ctx", ":", "value", "=", "ctx", ".", "create_decimal", "(", "value", ")", "if", "value", ".", "is_infinite", "(", ")", ":", "return"...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/tokumx/datadog_checks/tokumx/vendor/bson/decimal128.py#L107-L153
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/gaap/v20180529/gaap_client.py
python
GaapClient.DescribeListenerStatistics
(self, request)
该接口用于查询监听器统计数据,包括出入带宽,出入包量,并发数据。支持300秒, 3600秒和86400秒的细粒度,取值为细粒度范围内最大值。 :param request: Request instance for DescribeListenerStatistics. :type request: :class:`tencentcloud.gaap.v20180529.models.DescribeListenerStatisticsRequest` :rtype: :class:`tencentcloud.gaap.v20180529.models.DescribeListenerStatisticsResponse`
该接口用于查询监听器统计数据,包括出入带宽,出入包量,并发数据。支持300秒, 3600秒和86400秒的细粒度,取值为细粒度范围内最大值。
[ "该接口用于查询监听器统计数据,包括出入带宽,出入包量,并发数据。支持300秒", "3600秒和86400秒的细粒度,取值为细粒度范围内最大值。" ]
def DescribeListenerStatistics(self, request): """该接口用于查询监听器统计数据,包括出入带宽,出入包量,并发数据。支持300秒, 3600秒和86400秒的细粒度,取值为细粒度范围内最大值。 :param request: Request instance for DescribeListenerStatistics. :type request: :class:`tencentcloud.gaap.v20180529.models.DescribeListenerStatisticsRequest` :rtype: :class:`tencentcloud.gaap.v20180529.models.DescribeListenerStatisticsResponse` """ try: params = request._serialize() body = self.call("DescribeListenerStatistics", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeListenerStatisticsResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DescribeListenerStatistics", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DescribeListenerStatistics\"", ",", "params", ")", "response", "=", "json...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/gaap/v20180529/gaap_client.py#L1263-L1288
apache/bloodhound
c3e31294e68af99d4e040e64fbdf52394344df9e
trac/trac/versioncontrol/api.py
python
IRepositoryConnector.get_repository
(repos_type, repos_dir, params)
Return a Repository instance for the given repository type and dir.
Return a Repository instance for the given repository type and dir.
[ "Return", "a", "Repository", "instance", "for", "the", "given", "repository", "type", "and", "dir", "." ]
def get_repository(repos_type, repos_dir, params): """Return a Repository instance for the given repository type and dir. """
[ "def", "get_repository", "(", "repos_type", ",", "repos_dir", ",", "params", ")", ":" ]
https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/trac/trac/versioncontrol/api.py#L57-L59
pimutils/vdirsyncer
e8b72130c25546141718b8c781e8c7e36d829bba
vdirsyncer/storage/dav.py
python
_normalize_href
(base, href)
return x
Normalize the href to be a path only relative to hostname and schema.
Normalize the href to be a path only relative to hostname and schema.
[ "Normalize", "the", "href", "to", "be", "a", "path", "only", "relative", "to", "hostname", "and", "schema", "." ]
def _normalize_href(base, href): """Normalize the href to be a path only relative to hostname and schema.""" orig_href = href if not href: raise ValueError(href) x = urlparse.urljoin(base, href) x = urlparse.urlsplit(x).path # We unquote and quote again, but want to make sure we # keep around the "@" character. x = urlparse.unquote(x) x = urlparse.quote(x, "/@") if orig_href == x: dav_logger.debug(f"Already normalized: {x!r}") else: dav_logger.debug(f"Normalized URL from {orig_href!r} to {x!r}") return x
[ "def", "_normalize_href", "(", "base", ",", "href", ")", ":", "orig_href", "=", "href", "if", "not", "href", ":", "raise", "ValueError", "(", "href", ")", "x", "=", "urlparse", ".", "urljoin", "(", "base", ",", "href", ")", "x", "=", "urlparse", ".",...
https://github.com/pimutils/vdirsyncer/blob/e8b72130c25546141718b8c781e8c7e36d829bba/vdirsyncer/storage/dav.py#L48-L67
JustinhoCHN/SRGAN_Wasserstein
08cb76028880f95cbeea1353c5bfc5b2b356ae83
tensorlayer/files.py
python
save_npz
(save_list=[], name='model.npz', sess=None)
Input parameters and the file name, save parameters into .npz file. Use tl.utils.load_npz() to restore. Parameters ---------- save_list : a list Parameters want to be saved. name : a string or None The name of the .npz file. sess : None or Session Examples -------- >>> tl.files.save_npz(network.all_params, name='model_test.npz', sess=sess) ... File saved to: model_test.npz >>> load_params = tl.files.load_npz(name='model_test.npz') ... Loading param0, (784, 800) ... Loading param1, (800,) ... Loading param2, (800, 800) ... Loading param3, (800,) ... Loading param4, (800, 10) ... Loading param5, (10,) >>> put parameters into a TensorLayer network, please see assign_params() Notes ----- If you got session issues, you can change the value.eval() to value.eval(session=sess) References ---------- - `Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`_
Input parameters and the file name, save parameters into .npz file. Use tl.utils.load_npz() to restore.
[ "Input", "parameters", "and", "the", "file", "name", "save", "parameters", "into", ".", "npz", "file", ".", "Use", "tl", ".", "utils", ".", "load_npz", "()", "to", "restore", "." ]
def save_npz(save_list=[], name='model.npz', sess=None): """Input parameters and the file name, save parameters into .npz file. Use tl.utils.load_npz() to restore. Parameters ---------- save_list : a list Parameters want to be saved. name : a string or None The name of the .npz file. sess : None or Session Examples -------- >>> tl.files.save_npz(network.all_params, name='model_test.npz', sess=sess) ... File saved to: model_test.npz >>> load_params = tl.files.load_npz(name='model_test.npz') ... Loading param0, (784, 800) ... Loading param1, (800,) ... Loading param2, (800, 800) ... Loading param3, (800,) ... Loading param4, (800, 10) ... Loading param5, (10,) >>> put parameters into a TensorLayer network, please see assign_params() Notes ----- If you got session issues, you can change the value.eval() to value.eval(session=sess) References ---------- - `Saving dictionary using numpy <http://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez>`_ """ ## save params into a list save_list_var = [] if sess: save_list_var = sess.run(save_list) else: try: for k, value in enumerate(save_list): save_list_var.append(value.eval()) except: print(" Fail to save model, Hint: pass the session into this function, save_npz(network.all_params, name='model.npz', sess=sess)") np.savez(name, params=save_list_var) save_list_var = None del save_list_var print("[*] %s saved" % name)
[ "def", "save_npz", "(", "save_list", "=", "[", "]", ",", "name", "=", "'model.npz'", ",", "sess", "=", "None", ")", ":", "## save params into a list", "save_list_var", "=", "[", "]", "if", "sess", ":", "save_list_var", "=", "sess", ".", "run", "(", "save...
https://github.com/JustinhoCHN/SRGAN_Wasserstein/blob/08cb76028880f95cbeea1353c5bfc5b2b356ae83/tensorlayer/files.py#L510-L555
arguman/arguman.org
3242df5c6be8186e245af7e5b378e973ca01f6bc
web/profiles/views.py
python
BaseProfileDetailView.get_context_data
(self, **kwargs)
return super(BaseProfileDetailView, self).get_context_data( can_follow=can_follow, is_followed=is_followed, tab_name=self.tab_name, **kwargs )
Adds extra context to template
Adds extra context to template
[ "Adds", "extra", "context", "to", "template" ]
def get_context_data(self, **kwargs): """ Adds extra context to template """ user = self.get_object() can_follow = self.request.user != user if self.request.user.is_authenticated(): is_followed = self.request.user.following.filter( pk=user.id).exists() else: is_followed = False return super(BaseProfileDetailView, self).get_context_data( can_follow=can_follow, is_followed=is_followed, tab_name=self.tab_name, **kwargs )
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "user", "=", "self", ".", "get_object", "(", ")", "can_follow", "=", "self", ".", "request", ".", "user", "!=", "user", "if", "self", ".", "request", ".", "user", ".", "is_aut...
https://github.com/arguman/arguman.org/blob/3242df5c6be8186e245af7e5b378e973ca01f6bc/web/profiles/views.py#L73-L92
nltk/nltk
3f74ac55681667d7ef78b664557487145f51eb02
nltk/translate/chrf_score.py
python
sentence_chrf
( reference, hypothesis, min_len=1, max_len=6, beta=3.0, ignore_whitespace=True )
return corpus_chrf( [reference], [hypothesis], min_len, max_len, beta=beta, ignore_whitespace=ignore_whitespace, )
Calculates the sentence level CHRF (Character n-gram F-score) described in - Maja Popovic. 2015. CHRF: Character n-gram F-score for Automatic MT Evaluation. In Proceedings of the 10th Workshop on Machine Translation. https://www.statmt.org/wmt15/pdf/WMT49.pdf - Maja Popovic. 2016. CHRF Deconstructed: β Parameters and n-gram Weights. In Proceedings of the 1st Conference on Machine Translation. https://www.statmt.org/wmt16/pdf/W16-2341.pdf This implementation of CHRF only supports a single reference at the moment. For details not reported in the paper, consult Maja Popovic's original implementation: https://github.com/m-popovic/chrF The code should output results equivalent to running CHRF++ with the following options: -nw 0 -b 3 An example from the original BLEU paper https://www.aclweb.org/anthology/P02-1040.pdf >>> ref1 = str('It is a guide to action that ensures that the military ' ... 'will forever heed Party commands').split() >>> hyp1 = str('It is a guide to action which ensures that the military ' ... 'always obeys the commands of the party').split() >>> hyp2 = str('It is to insure the troops forever hearing the activity ' ... 'guidebook that party direct').split() >>> sentence_chrf(ref1, hyp1) # doctest: +ELLIPSIS 0.6349... >>> sentence_chrf(ref1, hyp2) # doctest: +ELLIPSIS 0.3330... The infamous "the the the ... " example >>> ref = 'the cat is on the mat'.split() >>> hyp = 'the the the the the the the'.split() >>> sentence_chrf(ref, hyp) # doctest: +ELLIPSIS 0.1468... An example to show that this function allows users to use strings instead of tokens, i.e. list(str) as inputs. >>> ref1 = str('It is a guide to action that ensures that the military ' ... 'will forever heed Party commands') >>> hyp1 = str('It is a guide to action which ensures that the military ' ... 'always obeys the commands of the party') >>> sentence_chrf(ref1, hyp1) # doctest: +ELLIPSIS 0.6349... >>> type(ref1) == type(hyp1) == str True >>> sentence_chrf(ref1.split(), hyp1.split()) # doctest: +ELLIPSIS 0.6349... To skip the unigrams and only use 2- to 3-grams: >>> sentence_chrf(ref1, hyp1, min_len=2, max_len=3) # doctest: +ELLIPSIS 0.6617... :param references: reference sentence :type references: list(str) / str :param hypothesis: a hypothesis sentence :type hypothesis: list(str) / str :param min_len: The minimum order of n-gram this function should extract. :type min_len: int :param max_len: The maximum order of n-gram this function should extract. :type max_len: int :param beta: the parameter to assign more importance to recall over precision :type beta: float :param ignore_whitespace: ignore whitespace characters in scoring :type ignore_whitespace: bool :return: the sentence level CHRF score. :rtype: float
Calculates the sentence level CHRF (Character n-gram F-score) described in - Maja Popovic. 2015. CHRF: Character n-gram F-score for Automatic MT Evaluation. In Proceedings of the 10th Workshop on Machine Translation. https://www.statmt.org/wmt15/pdf/WMT49.pdf - Maja Popovic. 2016. CHRF Deconstructed: β Parameters and n-gram Weights. In Proceedings of the 1st Conference on Machine Translation. https://www.statmt.org/wmt16/pdf/W16-2341.pdf
[ "Calculates", "the", "sentence", "level", "CHRF", "(", "Character", "n", "-", "gram", "F", "-", "score", ")", "described", "in", "-", "Maja", "Popovic", ".", "2015", ".", "CHRF", ":", "Character", "n", "-", "gram", "F", "-", "score", "for", "Automatic"...
def sentence_chrf( reference, hypothesis, min_len=1, max_len=6, beta=3.0, ignore_whitespace=True ): """ Calculates the sentence level CHRF (Character n-gram F-score) described in - Maja Popovic. 2015. CHRF: Character n-gram F-score for Automatic MT Evaluation. In Proceedings of the 10th Workshop on Machine Translation. https://www.statmt.org/wmt15/pdf/WMT49.pdf - Maja Popovic. 2016. CHRF Deconstructed: β Parameters and n-gram Weights. In Proceedings of the 1st Conference on Machine Translation. https://www.statmt.org/wmt16/pdf/W16-2341.pdf This implementation of CHRF only supports a single reference at the moment. For details not reported in the paper, consult Maja Popovic's original implementation: https://github.com/m-popovic/chrF The code should output results equivalent to running CHRF++ with the following options: -nw 0 -b 3 An example from the original BLEU paper https://www.aclweb.org/anthology/P02-1040.pdf >>> ref1 = str('It is a guide to action that ensures that the military ' ... 'will forever heed Party commands').split() >>> hyp1 = str('It is a guide to action which ensures that the military ' ... 'always obeys the commands of the party').split() >>> hyp2 = str('It is to insure the troops forever hearing the activity ' ... 'guidebook that party direct').split() >>> sentence_chrf(ref1, hyp1) # doctest: +ELLIPSIS 0.6349... >>> sentence_chrf(ref1, hyp2) # doctest: +ELLIPSIS 0.3330... The infamous "the the the ... " example >>> ref = 'the cat is on the mat'.split() >>> hyp = 'the the the the the the the'.split() >>> sentence_chrf(ref, hyp) # doctest: +ELLIPSIS 0.1468... An example to show that this function allows users to use strings instead of tokens, i.e. list(str) as inputs. >>> ref1 = str('It is a guide to action that ensures that the military ' ... 'will forever heed Party commands') >>> hyp1 = str('It is a guide to action which ensures that the military ' ... 'always obeys the commands of the party') >>> sentence_chrf(ref1, hyp1) # doctest: +ELLIPSIS 0.6349... >>> type(ref1) == type(hyp1) == str True >>> sentence_chrf(ref1.split(), hyp1.split()) # doctest: +ELLIPSIS 0.6349... To skip the unigrams and only use 2- to 3-grams: >>> sentence_chrf(ref1, hyp1, min_len=2, max_len=3) # doctest: +ELLIPSIS 0.6617... :param references: reference sentence :type references: list(str) / str :param hypothesis: a hypothesis sentence :type hypothesis: list(str) / str :param min_len: The minimum order of n-gram this function should extract. :type min_len: int :param max_len: The maximum order of n-gram this function should extract. :type max_len: int :param beta: the parameter to assign more importance to recall over precision :type beta: float :param ignore_whitespace: ignore whitespace characters in scoring :type ignore_whitespace: bool :return: the sentence level CHRF score. :rtype: float """ return corpus_chrf( [reference], [hypothesis], min_len, max_len, beta=beta, ignore_whitespace=ignore_whitespace, )
[ "def", "sentence_chrf", "(", "reference", ",", "hypothesis", ",", "min_len", "=", "1", ",", "max_len", "=", "6", ",", "beta", "=", "3.0", ",", "ignore_whitespace", "=", "True", ")", ":", "return", "corpus_chrf", "(", "[", "reference", "]", ",", "[", "h...
https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/translate/chrf_score.py#L16-L98
automl/SMAC3
d4cb7ed76e0fbdd9edf6ab5360ff75de67ac2195
smac/epm/util_funcs.py
python
get_types
( config_space: ConfigurationSpace, instance_features: typing.Optional[np.ndarray] = None, )
return types, bounds
TODO
TODO
[ "TODO" ]
def get_types( config_space: ConfigurationSpace, instance_features: typing.Optional[np.ndarray] = None, ) -> typing.Tuple[typing.List[int], typing.List[typing.Tuple[float, float]]]: """TODO""" # Extract types vector for rf from config space and the bounds types = [0] * len(config_space.get_hyperparameters()) bounds = [(np.nan, np.nan)] * len(types) for i, param in enumerate(config_space.get_hyperparameters()): parents = config_space.get_parents_of(param.name) if len(parents) == 0: can_be_inactive = False else: can_be_inactive = True if isinstance(param, (CategoricalHyperparameter)): n_cats = len(param.choices) if can_be_inactive: n_cats = len(param.choices) + 1 types[i] = n_cats bounds[i] = (int(n_cats), np.nan) elif isinstance(param, (OrdinalHyperparameter)): n_cats = len(param.sequence) types[i] = 0 if can_be_inactive: bounds[i] = (0, int(n_cats)) else: bounds[i] = (0, int(n_cats) - 1) elif isinstance(param, Constant): # for constants we simply set types to 0 which makes it a numerical # parameter if can_be_inactive: bounds[i] = (2, np.nan) types[i] = 2 else: bounds[i] = (0, np.nan) types[i] = 0 # and we leave the bounds to be 0 for now elif isinstance(param, UniformFloatHyperparameter): # Are sampled on the unit hypercube thus the bounds # are always 0.0, 1.0 if can_be_inactive: bounds[i] = (-1.0, 1.0) else: bounds[i] = (0, 1.0) elif isinstance(param, UniformIntegerHyperparameter): if can_be_inactive: bounds[i] = (-1.0, 1.0) else: bounds[i] = (0, 1.0) elif not isinstance(param, (UniformFloatHyperparameter, UniformIntegerHyperparameter, OrdinalHyperparameter, CategoricalHyperparameter)): raise TypeError("Unknown hyperparameter type %s" % type(param)) if instance_features is not None: types = types + [0] * instance_features.shape[1] return types, bounds
[ "def", "get_types", "(", "config_space", ":", "ConfigurationSpace", ",", "instance_features", ":", "typing", ".", "Optional", "[", "np", ".", "ndarray", "]", "=", "None", ",", ")", "->", "typing", ".", "Tuple", "[", "typing", ".", "List", "[", "int", "]"...
https://github.com/automl/SMAC3/blob/d4cb7ed76e0fbdd9edf6ab5360ff75de67ac2195/smac/epm/util_funcs.py#L15-L77
HuobiRDCenter/huobi_Python
c75a7fa8b31e99ffc1c173d74dcfcad83682e943
huobi/client/margin.py
python
MarginClient.get_margin_account_balance
(self, symbol: 'str')
return GetMarginAccountBalanceService(params).request(**self.__kwargs)
Get the Balance of the Margin Loan Account. :param symbol: The currency, like "btc". (mandatory) :return: The margin loan account detail list.
Get the Balance of the Margin Loan Account.
[ "Get", "the", "Balance", "of", "the", "Margin", "Loan", "Account", "." ]
def get_margin_account_balance(self, symbol: 'str') -> list: """ Get the Balance of the Margin Loan Account. :param symbol: The currency, like "btc". (mandatory) :return: The margin loan account detail list. """ check_symbol(symbol) params = { "symbol": symbol } from huobi.service.margin.get_margin_account_balance import GetMarginAccountBalanceService return GetMarginAccountBalanceService(params).request(**self.__kwargs)
[ "def", "get_margin_account_balance", "(", "self", ",", "symbol", ":", "'str'", ")", "->", "list", ":", "check_symbol", "(", "symbol", ")", "params", "=", "{", "\"symbol\"", ":", "symbol", "}", "from", "huobi", ".", "service", ".", "margin", ".", "get_margi...
https://github.com/HuobiRDCenter/huobi_Python/blob/c75a7fa8b31e99ffc1c173d74dcfcad83682e943/huobi/client/margin.py#L61-L75
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/polys/polytools.py
python
primitive
(f, *gens, **args)
Compute content and the primitive form of ``f``. Examples ======== >>> from sympy.polys.polytools import primitive >>> from sympy.abc import x >>> primitive(6*x**2 + 8*x + 12) (2, 3*x**2 + 4*x + 6) >>> eq = (2 + 2*x)*x + 2 Expansion is performed by default: >>> primitive(eq) (2, x**2 + x + 1) Set ``expand`` to False to shut this off. Note that the extraction will not be recursive; use the as_content_primitive method for recursive, non-destructive Rational extraction. >>> primitive(eq, expand=False) (1, x*(2*x + 2) + 2) >>> eq.as_content_primitive() (2, x*(x + 1) + 1)
Compute content and the primitive form of ``f``.
[ "Compute", "content", "and", "the", "primitive", "form", "of", "f", "." ]
def primitive(f, *gens, **args): """ Compute content and the primitive form of ``f``. Examples ======== >>> from sympy.polys.polytools import primitive >>> from sympy.abc import x >>> primitive(6*x**2 + 8*x + 12) (2, 3*x**2 + 4*x + 6) >>> eq = (2 + 2*x)*x + 2 Expansion is performed by default: >>> primitive(eq) (2, x**2 + x + 1) Set ``expand`` to False to shut this off. Note that the extraction will not be recursive; use the as_content_primitive method for recursive, non-destructive Rational extraction. >>> primitive(eq, expand=False) (1, x*(2*x + 2) + 2) >>> eq.as_content_primitive() (2, x*(x + 1) + 1) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('primitive', 1, exc) cont, result = F.primitive() if not opt.polys: return cont, result.as_expr() else: return cont, result
[ "def", "primitive", "(", "f", ",", "*", "gens", ",", "*", "*", "args", ")", ":", "options", ".", "allowed_flags", "(", "args", ",", "[", "'polys'", "]", ")", "try", ":", "F", ",", "opt", "=", "poly_from_expr", "(", "f", ",", "*", "gens", ",", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/polys/polytools.py#L5631-L5673
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/utils/dummy_pt_objects.py
python
RemBertForQuestionAnswering.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): requires_backends(self, ["torch"])
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "requires_backends", "(", "self", ",", "[", "\"torch\"", "]", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/utils/dummy_pt_objects.py#L4093-L4094
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/vsm/vsm/db/api.py
python
quota_class_destroy
(context, class_name, resource)
return IMPL.quota_class_destroy(context, class_name, resource)
Destroy the quota class or raise if it does not exist.
Destroy the quota class or raise if it does not exist.
[ "Destroy", "the", "quota", "class", "or", "raise", "if", "it", "does", "not", "exist", "." ]
def quota_class_destroy(context, class_name, resource): """Destroy the quota class or raise if it does not exist.""" return IMPL.quota_class_destroy(context, class_name, resource)
[ "def", "quota_class_destroy", "(", "context", ",", "class_name", ",", "resource", ")", ":", "return", "IMPL", ".", "quota_class_destroy", "(", "context", ",", "class_name", ",", "resource", ")" ]
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/db/api.py#L520-L522
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/bulk_email/forms.py
python
CourseEmailTemplateForm.clean_plain_template
(self)
return template
Validate the plaintext template.
Validate the plaintext template.
[ "Validate", "the", "plaintext", "template", "." ]
def clean_plain_template(self): """Validate the plaintext template.""" template = self.cleaned_data["plain_template"] self._validate_template(template) return template
[ "def", "clean_plain_template", "(", "self", ")", ":", "template", "=", "self", ".", "cleaned_data", "[", "\"plain_template\"", "]", "self", ".", "_validate_template", "(", "template", ")", "return", "template" ]
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/bulk_email/forms.py#L47-L51
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex_restful/restful/dataset/operate.py
python
get_dataset_details
(dataset_path)
return None
[]
def get_dataset_details(dataset_path): status, message = get_folder_status(dataset_path, True) if status == DatasetStatus.XCOPYDONE or status == DatasetStatus.XSPLITED: with open(osp.join(dataset_path, 'statis.pkl'), 'rb') as f: details = pickle.load(f) return details return None
[ "def", "get_dataset_details", "(", "dataset_path", ")", ":", "status", ",", "message", "=", "get_folder_status", "(", "dataset_path", ",", "True", ")", "if", "status", "==", "DatasetStatus", ".", "XCOPYDONE", "or", "status", "==", "DatasetStatus", ".", "XSPLITED...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex_restful/restful/dataset/operate.py#L149-L155
metamorphose/metamorphose2
d2bdd6a86340b9668e93b35a6a568894c9909d68
src/mutagen/_vorbis.py
python
VCommentDict.as_dict
(self)
return dict([(key, self[key]) for key in self.keys()])
Return a copy of the comment data in a real dict.
Return a copy of the comment data in a real dict.
[ "Return", "a", "copy", "of", "the", "comment", "data", "in", "a", "real", "dict", "." ]
def as_dict(self): """Return a copy of the comment data in a real dict.""" return dict([(key, self[key]) for key in self.keys()])
[ "def", "as_dict", "(", "self", ")", ":", "return", "dict", "(", "[", "(", "key", ",", "self", "[", "key", "]", ")", "for", "key", "in", "self", ".", "keys", "(", ")", "]", ")" ]
https://github.com/metamorphose/metamorphose2/blob/d2bdd6a86340b9668e93b35a6a568894c9909d68/src/mutagen/_vorbis.py#L324-L327
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/plugins/leoflexx.py
python
dump_event
(ev)
Print a description of the event.
Print a description of the event.
[ "Print", "a", "description", "of", "the", "event", "." ]
def dump_event(ev): """Print a description of the event.""" id_ = ev.source.title or ev.source.text kind = '' if ev.new_value else 'un-' s = kind + ev.type message = '%s: %s' % (s.rjust(15), id_) print('dump_event: ' + message)
[ "def", "dump_event", "(", "ev", ")", ":", "id_", "=", "ev", ".", "source", ".", "title", "or", "ev", ".", "source", ".", "text", "kind", "=", "''", "if", "ev", ".", "new_value", "else", "'un-'", "s", "=", "kind", "+", "ev", ".", "type", "message"...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/leoflexx.py#L84-L90
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/httplib.py
python
HTTPConnection.putrequest
(self, method, url, skip_host=0, skip_accept_encoding=0)
Send a request to the server. `method' specifies an HTTP request method, e.g. 'GET'. `url' specifies the object being requested, e.g. '/index.html'. `skip_host' if True does not add automatically a 'Host:' header `skip_accept_encoding' if True does not add automatically an 'Accept-Encoding:' header
Send a request to the server.
[ "Send", "a", "request", "to", "the", "server", "." ]
def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0): """Send a request to the server. `method' specifies an HTTP request method, e.g. 'GET'. `url' specifies the object being requested, e.g. '/index.html'. `skip_host' if True does not add automatically a 'Host:' header `skip_accept_encoding' if True does not add automatically an 'Accept-Encoding:' header """ # if a prior response has been completed, then forget about it. if self.__response and self.__response.isclosed(): self.__response = None # in certain cases, we cannot issue another request on this connection. # this occurs when: # 1) we are in the process of sending a request. (_CS_REQ_STARTED) # 2) a response to a previous request has signalled that it is going # to close the connection upon completion. # 3) the headers for the previous response have not been read, thus # we cannot determine whether point (2) is true. (_CS_REQ_SENT) # # if there is no prior response, then we can request at will. # # if point (2) is true, then we will have passed the socket to the # response (effectively meaning, "there is no prior response"), and # will open a new one when a new request is made. # # Note: if a prior response exists, then we *can* start a new request. # We are not allowed to begin fetching the response to this new # request, however, until that prior response is complete. # if self.__state == _CS_IDLE: self.__state = _CS_REQ_STARTED else: raise CannotSendRequest() # Save the method we use, we need it later in the response phase self._method = method if not url: url = '/' hdr = '%s %s %s' % (method, url, self._http_vsn_str) self._output(hdr) if self._http_vsn == 11: # Issue some standard headers for better HTTP/1.1 compliance if not skip_host: # this header is issued *only* for HTTP/1.1 # connections. more specifically, this means it is # only issued when the client uses the new # HTTPConnection() class. backwards-compat clients # will be using HTTP/1.0 and those clients may be # issuing this header themselves. we should NOT issue # it twice; some web servers (such as Apache) barf # when they see two Host: headers # If we need a non-standard port,include it in the # header. If the request is going through a proxy, # but the host of the actual URL, not the host of the # proxy. netloc = '' if url.startswith('http'): nil, netloc, nil, nil, nil = urlsplit(url) if netloc: try: netloc_enc = netloc.encode("ascii") except UnicodeEncodeError: netloc_enc = netloc.encode("idna") self.putheader('Host', netloc_enc) else: try: host_enc = self.host.encode("ascii") except UnicodeEncodeError: host_enc = self.host.encode("idna") # Wrap the IPv6 Host Header with [] (RFC 2732) if host_enc.find(':') >= 0: host_enc = "[" + host_enc + "]" if self.port == self.default_port: self.putheader('Host', host_enc) else: self.putheader('Host', "%s:%s" % (host_enc, self.port)) # note: we are assuming that clients will not attempt to set these # headers since *this* library must deal with the # consequences. this also means that when the supporting # libraries are updated to recognize other forms, then this # code should be changed (removed or updated). # we only want a Content-Encoding of "identity" since we don't # support encodings such as x-gzip or x-deflate. if not skip_accept_encoding: self.putheader('Accept-Encoding', 'identity') # we can accept "chunked" Transfer-Encodings, but no others # NOTE: no TE header implies *only* "chunked" #self.putheader('TE', 'chunked') # if TE is supplied in the header, then it must appear in a # Connection header. #self.putheader('Connection', 'TE') else: # For HTTP/1.0, the server will assume "not chunked" pass
[ "def", "putrequest", "(", "self", ",", "method", ",", "url", ",", "skip_host", "=", "0", ",", "skip_accept_encoding", "=", "0", ")", ":", "# if a prior response has been completed, then forget about it.", "if", "self", ".", "__response", "and", "self", ".", "__res...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/httplib.py#L835-L943
rferrazz/pyqt4topyqt5
c0630e1a3e1e2884d8c56127812c35854dbdf301
pyqt4topyqt5/__init__.py
python
PyQt4ToPyQt5.fix_qglobal
(self, lines)
Replace calls to qInstallMsgHandler() with calls to qInstallMessageHandler(). Args: code -- the list of source code lines
Replace calls to qInstallMsgHandler() with calls to qInstallMessageHandler().
[ "Replace", "calls", "to", "qInstallMsgHandler", "()", "with", "calls", "to", "qInstallMessageHandler", "()", "." ]
def fix_qglobal(self, lines): """Replace calls to qInstallMsgHandler() with calls to qInstallMessageHandler(). Args: code -- the list of source code lines """ for idx, line in enumerate(lines): if self.is_code_line(line): lines[idx] = line.replace('qInstallMsgHandler(', 'qInstallMessageHandler(')
[ "def", "fix_qglobal", "(", "self", ",", "lines", ")", ":", "for", "idx", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "if", "self", ".", "is_code_line", "(", "line", ")", ":", "lines", "[", "idx", "]", "=", "line", ".", "replace", "(", ...
https://github.com/rferrazz/pyqt4topyqt5/blob/c0630e1a3e1e2884d8c56127812c35854dbdf301/pyqt4topyqt5/__init__.py#L1410-L1418
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/subword.py
python
Subwords_wk.__contains__
(self, w)
return len(w) == self._k and Subwords_w.__contains__(self,w)
TESTS:: sage: [] in Subwords([1, 3, 3, 5, 4, 5, 3, 5],0) True sage: [2,3,3,4] in Subwords([1,2,3,4,3,4,4],4) True sage: [2,3,3,4] in Subwords([1,2,3,4,3,4,4],3) False sage: [5,5,3] in Subwords([1,3,3,5,4,5,3,5],3) True sage: [5,5,3] in Subwords([1,3,3,5,4,5,3,5],4) False
TESTS::
[ "TESTS", "::" ]
def __contains__(self, w): """ TESTS:: sage: [] in Subwords([1, 3, 3, 5, 4, 5, 3, 5],0) True sage: [2,3,3,4] in Subwords([1,2,3,4,3,4,4],4) True sage: [2,3,3,4] in Subwords([1,2,3,4,3,4,4],3) False sage: [5,5,3] in Subwords([1,3,3,5,4,5,3,5],3) True sage: [5,5,3] in Subwords([1,3,3,5,4,5,3,5],4) False """ return len(w) == self._k and Subwords_w.__contains__(self,w)
[ "def", "__contains__", "(", "self", ",", "w", ")", ":", "return", "len", "(", "w", ")", "==", "self", ".", "_k", "and", "Subwords_w", ".", "__contains__", "(", "self", ",", "w", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/subword.py#L370-L385
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
examples/extensions/add_sitelinks.py
python
_create_extension_feed_items
(client, customer_id, campaign_resource_name)
return [result.resource_name for result in feed_response.results]
Helper method that creates extension feed items. Args: client: a GoogleAdsClient instance. customer_id: a str Google Ads customer ID, that the extension feed items will be created for. campaign_resource_name: a str resource name for the campaign that will be tracked by the created extension feed items. Returns: A list containing resource names for the created extension feed items.
Helper method that creates extension feed items.
[ "Helper", "method", "that", "creates", "extension", "feed", "items", "." ]
def _create_extension_feed_items(client, customer_id, campaign_resource_name): """Helper method that creates extension feed items. Args: client: a GoogleAdsClient instance. customer_id: a str Google Ads customer ID, that the extension feed items will be created for. campaign_resource_name: a str resource name for the campaign that will be tracked by the created extension feed items. Returns: A list containing resource names for the created extension feed items. """ extension_feed_item_service = client.get_service("ExtensionFeedItemService") geo_target_constant_service = client.get_service("GeoTargetConstantService") extension_type_enum = client.enums.ExtensionTypeEnum feed_item_target_device_enum = client.enums.FeedItemTargetDeviceEnum day_of_week_enum = client.enums.DayOfWeekEnum minute_of_hour_enum = client.enums.MinuteOfHourEnum extension_feed_item_operation1 = client.get_type( "ExtensionFeedItemOperation" ) extension_feed_item1 = extension_feed_item_operation1.create extension_feed_item1.extension_type = extension_type_enum.SITELINK extension_feed_item1.sitelink_feed_item.link_text = "Store Hours" extension_feed_item1.targeted_campaign = campaign_resource_name extension_feed_item1.sitelink_feed_item.final_urls.append( "http://www.example.com/storehours" ) extension_feed_item_operation2 = client.get_type( "ExtensionFeedItemOperation" ) date_range = _get_thanksgiving_string_date_range() extension_feed_item2 = extension_feed_item_operation2.create extension_feed_item2.extension_type = extension_type_enum.SITELINK extension_feed_item2.sitelink_feed_item.link_text = "Thanksgiving Specials" extension_feed_item2.targeted_campaign = campaign_resource_name extension_feed_item2.start_date_time = date_range.start_datetime extension_feed_item2.end_date_time = date_range.end_datetime # Targets this sitelink for the United States only. # A list of country codes can be referenced here: # https://developers.google.com/google-ads/api/reference/data/geotargets united_states = geo_target_constant_service.geo_target_constant_path(2048) extension_feed_item2.targeted_geo_target_constant = united_states extension_feed_item2.sitelink_feed_item.final_urls.append( "http://www.example.com/thanksgiving" ) extension_feed_item_operation3 = client.get_type( "ExtensionFeedItemOperation" ) extension_feed_item3 = extension_feed_item_operation3.create extension_feed_item3.extension_type = extension_type_enum.SITELINK extension_feed_item3.sitelink_feed_item.link_text = "Wifi available" extension_feed_item3.targeted_campaign = campaign_resource_name extension_feed_item3.device = feed_item_target_device_enum.MOBILE extension_feed_item3.sitelink_feed_item.final_urls.append( "http://www.example.com/mobile/wifi" ) extension_feed_item_operation4 = client.get_type( "ExtensionFeedItemOperation" ) extension_feed_item4 = extension_feed_item_operation4.create extension_feed_item4.extension_type = extension_type_enum.SITELINK extension_feed_item4.sitelink_feed_item.link_text = "Happy hours" extension_feed_item4.targeted_campaign = campaign_resource_name extension_feed_item4.device = feed_item_target_device_enum.MOBILE extension_feed_item4.sitelink_feed_item.final_urls.append( "http://www.example.com/happyhours" ) for day_of_week in [ day_of_week_enum.MONDAY, day_of_week_enum.TUESDAY, day_of_week_enum.WEDNESDAY, day_of_week_enum.THURSDAY, day_of_week_enum.FRIDAY, ]: ad_schedule = client.get_type("AdScheduleInfo") _populate_ad_schedule( ad_schedule, day_of_week, 18, minute_of_hour_enum.ZERO, 21, minute_of_hour_enum.ZERO, ) extension_feed_item4.ad_schedules.append(ad_schedule) # Add extension feed items feed_response = extension_feed_item_service.mutate_extension_feed_items( customer_id=customer_id, operations=[ extension_feed_item_operation1, extension_feed_item_operation2, extension_feed_item_operation3, extension_feed_item_operation4, ], ) print("Created ExtensionFeedItems:") for feed_item in feed_response.results: print(f"\tResource name: {feed_item.resource_name}") return [result.resource_name for result in feed_response.results]
[ "def", "_create_extension_feed_items", "(", "client", ",", "customer_id", ",", "campaign_resource_name", ")", ":", "extension_feed_item_service", "=", "client", ".", "get_service", "(", "\"ExtensionFeedItemService\"", ")", "geo_target_constant_service", "=", "client", ".", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/examples/extensions/add_sitelinks.py#L79-L185
vcheckzen/FODI
3bb23644938a33c3fdfb9611a622e35ed4ce6532
back-end-py/main/3rd/Crypto/Hash/Poly1305.py
python
Poly1305_MAC.digest
(self)
return self._mac_tag
Return the **binary** (non-printable) MAC tag of the message authenticated so far. :return: The MAC tag digest, computed over the data processed so far. Binary form. :rtype: byte string
Return the **binary** (non-printable) MAC tag of the message authenticated so far.
[ "Return", "the", "**", "binary", "**", "(", "non", "-", "printable", ")", "MAC", "tag", "of", "the", "message", "authenticated", "so", "far", "." ]
def digest(self): """Return the **binary** (non-printable) MAC tag of the message authenticated so far. :return: The MAC tag digest, computed over the data processed so far. Binary form. :rtype: byte string """ if self._mac_tag: return self._mac_tag bfr = create_string_buffer(16) result = _raw_poly1305.poly1305_digest(self._state.get(), bfr, c_size_t(len(bfr))) if result: raise ValueError("Error %d while creating Poly1305 digest" % result) self._mac_tag = get_raw_buffer(bfr) return self._mac_tag
[ "def", "digest", "(", "self", ")", ":", "if", "self", ".", "_mac_tag", ":", "return", "self", ".", "_mac_tag", "bfr", "=", "create_string_buffer", "(", "16", ")", "result", "=", "_raw_poly1305", ".", "poly1305_digest", "(", "self", ".", "_state", ".", "g...
https://github.com/vcheckzen/FODI/blob/3bb23644938a33c3fdfb9611a622e35ed4ce6532/back-end-py/main/3rd/Crypto/Hash/Poly1305.py#L106-L126
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/provisioningserver/kernel_opts.py
python
compose_purpose_opts
(params)
return kernel_params
Return the list of the purpose-specific kernel options.
Return the list of the purpose-specific kernel options.
[ "Return", "the", "list", "of", "the", "purpose", "-", "specific", "kernel", "options", "." ]
def compose_purpose_opts(params): """Return the list of the purpose-specific kernel options.""" kernel_params = [ "ro", "root=squash:http://%s:5248/images/%s/%s/%s/%s/%s/squashfs" % ( ( "[%s]" % params.fs_host if IPAddress(params.fs_host).version == 6 else params.fs_host ), params.osystem, params.arch, params.subarch, params.release, params.label, ), # Read by cloud-initramfs-dyn-netconf initramfs-tools networking # configuration in the initramfs. Choose IPv4 or IPv6 based on the # family of fs_host. If BOOTIF is set, IPv6 config uses that # exclusively. ( "ip=::::%s:BOOTIF" % params.hostname if IPAddress(params.fs_host).version == 4 else "ip=off" ), ("ip6=dhcp" if IPAddress(params.fs_host).version == 6 else "ip6=off"), # Read by overlayroot package. "overlayroot=tmpfs", # LP:1533822 - Disable reading overlay data from disk. "overlayroot_cfgdisk=disabled", # Select the MAAS datasource by default. "cc:{'datasource_list': ['MAAS']}end_cc", # Read by cloud-init. "cloud-config-url=%s" % params.preseed_url, # Disable apparmor in the ephemeral environment. This addresses # MAAS bug LP: #1677336 due to LP: #1408106 "apparmor=0", ] return kernel_params
[ "def", "compose_purpose_opts", "(", "params", ")", ":", "kernel_params", "=", "[", "\"ro\"", ",", "\"root=squash:http://%s:5248/images/%s/%s/%s/%s/%s/squashfs\"", "%", "(", "(", "\"[%s]\"", "%", "params", ".", "fs_host", "if", "IPAddress", "(", "params", ".", "fs_ho...
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/provisioningserver/kernel_opts.py#L80-L119
tobegit3hub/deep_image_model
8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e
java_predict_client/src/main/proto/tensorflow/python/ops/math_grad.py
python
_SegmentMeanGrad
(op, grad)
return array_ops.gather(scaled_grad, op.inputs[1]), None
Gradient for SegmentMean.
Gradient for SegmentMean.
[ "Gradient", "for", "SegmentMean", "." ]
def _SegmentMeanGrad(op, grad): """Gradient for SegmentMean.""" input_rank = array_ops.rank(op.inputs[0]) ones_shape = array_ops.concat( 0, [array_ops.shape(op.inputs[1]), array_ops.fill(array_ops.expand_dims(input_rank - 1, 0), 1)]) ones = array_ops.fill(ones_shape, constant_op.constant(1, dtype=grad.dtype)) scaled_grad = math_ops.div(grad, math_ops.segment_sum(ones, op.inputs[1])) return array_ops.gather(scaled_grad, op.inputs[1]), None
[ "def", "_SegmentMeanGrad", "(", "op", ",", "grad", ")", ":", "input_rank", "=", "array_ops", ".", "rank", "(", "op", ".", "inputs", "[", "0", "]", ")", "ones_shape", "=", "array_ops", ".", "concat", "(", "0", ",", "[", "array_ops", ".", "shape", "(",...
https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/python/ops/math_grad.py#L155-L164
boostorg/build
aaa95bba19a7acb07badb1929737c67583b14ba0
src/build/generators.py
python
generators_for_toolset
(toolset)
return __generators_for_toolset.get(toolset, [])
Returns all generators which belong to 'toolset'.
Returns all generators which belong to 'toolset'.
[ "Returns", "all", "generators", "which", "belong", "to", "toolset", "." ]
def generators_for_toolset (toolset): """ Returns all generators which belong to 'toolset'. """ assert isinstance(toolset, basestring) return __generators_for_toolset.get(toolset, [])
[ "def", "generators_for_toolset", "(", "toolset", ")", ":", "assert", "isinstance", "(", "toolset", ",", "basestring", ")", "return", "__generators_for_toolset", ".", "get", "(", "toolset", ",", "[", "]", ")" ]
https://github.com/boostorg/build/blob/aaa95bba19a7acb07badb1929737c67583b14ba0/src/build/generators.py#L741-L745
NervanaSystems/ngraph-python
ac032c83c7152b615a9ad129d54d350f9d6a2986
ngraph/transformers/gpu/gpulayout.py
python
GPUFixedLayoutConstraint.get_layout_transform
(self, arg_layout, op_layout, arg)
Generates either a DimshuffleOp or GPUIndexOp for the argument that produces a view which satisfies contiguous order requirement. Arguments: arg_layout (GPULayoutAssignment): layout of the argument op_layout: (GPULayoutAssignment): layout required by the op arg (TensorOp): Op producing the argument Either a GPUIndexOp if no transform is needed, or a DimshuffleOp which satisfies the requirements of the op_layout
Generates either a DimshuffleOp or GPUIndexOp for the argument that produces a view which satisfies contiguous order requirement.
[ "Generates", "either", "a", "DimshuffleOp", "or", "GPUIndexOp", "for", "the", "argument", "that", "produces", "a", "view", "which", "satisfies", "contiguous", "order", "requirement", "." ]
def get_layout_transform(self, arg_layout, op_layout, arg): """ Generates either a DimshuffleOp or GPUIndexOp for the argument that produces a view which satisfies contiguous order requirement. Arguments: arg_layout (GPULayoutAssignment): layout of the argument op_layout: (GPULayoutAssignment): layout required by the op arg (TensorOp): Op producing the argument Either a GPUIndexOp if no transform is needed, or a DimshuffleOp which satisfies the requirements of the op_layout """ arg_mem_order = flatten(arg_layout.axes) arg_axes = arg_layout.ng_axes if self.needs_transform(arg_layout, op_layout): return self.get_dimshuffle(arg_mem_order, arg_axes, [self.order], arg) else: return self.get_reshape(arg_mem_order, arg_axes, [self.order], arg)
[ "def", "get_layout_transform", "(", "self", ",", "arg_layout", ",", "op_layout", ",", "arg", ")", ":", "arg_mem_order", "=", "flatten", "(", "arg_layout", ".", "axes", ")", "arg_axes", "=", "arg_layout", ".", "ng_axes", "if", "self", ".", "needs_transform", ...
https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/transformers/gpu/gpulayout.py#L637-L656
CGATOxford/cgat
326aad4694bdfae8ddc194171bb5d73911243947
CGAT/Mali.py
python
Mali.recount
(self, reset_first=False)
recount residue in alignments.
recount residue in alignments.
[ "recount", "residue", "in", "alignments", "." ]
def recount(self, reset_first=False): """recount residue in alignments.""" for id, seq in list(self.mMali.items()): if reset_first: seq.mFrom = 0 seq.mTo = seq.mFrom + self.countCharacters(seq.mString)
[ "def", "recount", "(", "self", ",", "reset_first", "=", "False", ")", ":", "for", "id", ",", "seq", "in", "list", "(", "self", ".", "mMali", ".", "items", "(", ")", ")", ":", "if", "reset_first", ":", "seq", ".", "mFrom", "=", "0", "seq", ".", ...
https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/Mali.py#L1071-L1076
SecureAuthCorp/impacket
10e53952e64e290712d49e263420b70b681bbc73
impacket/dot11.py
python
Dot11ControlFrameCTS.set_ra
(self, value)
Set 802.11 CTS control frame 48 bit 'Receiver Address' field as a 6 bytes array
Set 802.11 CTS control frame 48 bit 'Receiver Address' field as a 6 bytes array
[ "Set", "802", ".", "11", "CTS", "control", "frame", "48", "bit", "Receiver", "Address", "field", "as", "a", "6", "bytes", "array" ]
def set_ra(self, value): "Set 802.11 CTS control frame 48 bit 'Receiver Address' field as a 6 bytes array" for i in range(0, 6): self.header.set_byte(2+i, value[i])
[ "def", "set_ra", "(", "self", ",", "value", ")", ":", "for", "i", "in", "range", "(", "0", ",", "6", ")", ":", "self", ".", "header", ".", "set_byte", "(", "2", "+", "i", ",", "value", "[", "i", "]", ")" ]
https://github.com/SecureAuthCorp/impacket/blob/10e53952e64e290712d49e263420b70b681bbc73/impacket/dot11.py#L553-L556
MegviiDetection/video_analyst
f4d1bccb1c698961fed3cb70808f1177fab13bdd
videoanalyst/utils/dist_utils.py
python
all_gather
(data, group=None)
return data_list
Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: list of data gathered from each rank
Run all_gather on arbitrary picklable data (not necessarily tensors).
[ "Run", "all_gather", "on", "arbitrary", "picklable", "data", "(", "not", "necessarily", "tensors", ")", "." ]
def all_gather(data, group=None): """ Run all_gather on arbitrary picklable data (not necessarily tensors). Args: data: any picklable object group: a torch process group. By default, will use a group which contains all ranks on gloo backend. Returns: list[data]: list of data gathered from each rank """ if get_world_size() == 1: return [data] if group is None: group = _get_global_gloo_group() if dist.get_world_size(group) == 1: return [data] tensor = _serialize_to_tensor(data, group) size_list, tensor = _pad_to_largest_tensor(tensor, group) max_size = max(size_list) # receiving Tensor from all ranks tensor_list = [ torch.empty((max_size, ), dtype=torch.uint8, device=tensor.device) for _ in size_list ] dist.all_gather(tensor_list, tensor, group=group) data_list = [] for size, tensor in zip(size_list, tensor_list): buffer = tensor.cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer)) return data_list
[ "def", "all_gather", "(", "data", ",", "group", "=", "None", ")", ":", "if", "get_world_size", "(", ")", "==", "1", ":", "return", "[", "data", "]", "if", "group", "is", "None", ":", "group", "=", "_get_global_gloo_group", "(", ")", "if", "dist", "."...
https://github.com/MegviiDetection/video_analyst/blob/f4d1bccb1c698961fed3cb70808f1177fab13bdd/videoanalyst/utils/dist_utils.py#L144-L180
AIChallenger/AI_Challenger_2017
52014e0defbbdd85bf94ab05d308300d5764022f
Baselines/translation_and_interpretation_baseline/train/prepare_data/jieba/__init__.py
python
Tokenizer.gen_pfdict
(self, f)
return lfreq, ltotal
[]
def gen_pfdict(self, f): lfreq = {} ltotal = 0 f_name = resolve_filename(f) for lineno, line in enumerate(f, 1): try: line = line.strip().decode('utf-8') word, freq = line.split(' ')[:2] freq = int(freq) lfreq[word] = freq ltotal += freq for ch in xrange(len(word)): wfrag = word[:ch + 1] if wfrag not in lfreq: lfreq[wfrag] = 0 except ValueError: raise ValueError( 'invalid dictionary entry in %s at Line %s: %s' % (f_name, lineno, line)) f.close() return lfreq, ltotal
[ "def", "gen_pfdict", "(", "self", ",", "f", ")", ":", "lfreq", "=", "{", "}", "ltotal", "=", "0", "f_name", "=", "resolve_filename", "(", "f", ")", "for", "lineno", ",", "line", "in", "enumerate", "(", "f", ",", "1", ")", ":", "try", ":", "line",...
https://github.com/AIChallenger/AI_Challenger_2017/blob/52014e0defbbdd85bf94ab05d308300d5764022f/Baselines/translation_and_interpretation_baseline/train/prepare_data/jieba/__init__.py#L70-L89
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/classification/softmax_regression.py
python
SoftmaxRegressionLearner.cost_grad
(self, theta_flat, X, Y)
return cost, grad.ravel()
[]
def cost_grad(self, theta_flat, X, Y): theta = theta_flat.reshape((self.num_classes, X.shape[1])) M = X.dot(theta.T) P = np.exp(M - np.max(M, axis=1)[:, None]) P /= np.sum(P, axis=1)[:, None] cost = -np.sum(np.log(P) * Y) cost += self.lambda_ * theta_flat.dot(theta_flat) / 2.0 cost /= X.shape[0] grad = X.T.dot(P - Y).T grad += self.lambda_ * theta grad /= X.shape[0] return cost, grad.ravel()
[ "def", "cost_grad", "(", "self", ",", "theta_flat", ",", "X", ",", "Y", ")", ":", "theta", "=", "theta_flat", ".", "reshape", "(", "(", "self", ".", "num_classes", ",", "X", ".", "shape", "[", "1", "]", ")", ")", "M", "=", "X", ".", "dot", "(",...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/classification/softmax_regression.py#L58-L73
google-research/tapas
a3e069b50c71f50b12a6e5bb3dad10fb51f6fe68
tapas/models/bert/optimization.py
python
AdamWeightDecayOptimizer.apply_gradients
(self, grads_and_vars, global_step=None, name=None)
return tf.group( global_step.assign(global_step + 1), *assignments, name=name)
See base class.
See base class.
[ "See", "base", "class", "." ]
def apply_gradients(self, grads_and_vars, global_step=None, name=None): """See base class.""" assignments = [] for (grad, param) in grads_and_vars: if grad is None or param is None: continue if self.grad_clipping is not None: grad = tf.clip_by_value(grad, -1 * self.grad_clipping, self.grad_clipping) param_name = self._get_variable_name(param.name) m = tf.get_variable( name=param_name + "/adam_m", shape=param.shape.as_list(), dtype=tf.float32, trainable=False, initializer=tf.zeros_initializer()) v = tf.get_variable( name=param_name + "/adam_v", shape=param.shape.as_list(), dtype=tf.float32, trainable=False, initializer=tf.zeros_initializer()) # Standard Adam update. next_m = ( tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad)) next_v = ( tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2, tf.square(grad))) update = next_m / (tf.sqrt(next_v) + self.epsilon) # Just adding the square of the weights to the loss function is *not* # the correct way of using L2 regularization/weight decay with Adam, # since that will interact with the m and v parameters in strange ways. # # Instead we want ot decay the weights in a manner that doesn't interact # with the m/v parameters. This is equivalent to adding the square # of the weights to the loss with plain (non-momentum) SGD. if self._do_use_weight_decay(param_name): update += self.weight_decay_rate * param update_with_lr = self.learning_rate * update next_param = param - update_with_lr assignments.extend( [param.assign(next_param), m.assign(next_m), v.assign(next_v)]) return tf.group( global_step.assign(global_step + 1), *assignments, name=name)
[ "def", "apply_gradients", "(", "self", ",", "grads_and_vars", ",", "global_step", "=", "None", ",", "name", "=", "None", ")", ":", "assignments", "=", "[", "]", "for", "(", "grad", ",", "param", ")", "in", "grads_and_vars", ":", "if", "grad", "is", "No...
https://github.com/google-research/tapas/blob/a3e069b50c71f50b12a6e5bb3dad10fb51f6fe68/tapas/models/bert/optimization.py#L209-L262
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/revision_info.py
python
RevisionInfo.__eq__
(self, other)
return self.__dict__ == other.__dict__
Returns true if both objects are equal
Returns true if both objects are equal
[ "Returns", "true", "if", "both", "objects", "are", "equal" ]
def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, RevisionInfo): return False return self.__dict__ == other.__dict__
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "RevisionInfo", ")", ":", "return", "False", "return", "self", ".", "__dict__", "==", "other", ".", "__dict__" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/revision_info.py#L168-L175
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/metagoofil/hachoir_parser/audio/aiff.py
python
Comment.createFields
(self)
[]
def createFields(self): yield TimestampMac32(self, "timestamp") yield PascalString32(self, "text")
[ "def", "createFields", "(", "self", ")", ":", "yield", "TimestampMac32", "(", "self", ",", "\"timestamp\"", ")", "yield", "PascalString32", "(", "self", ",", "\"text\"", ")" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_parser/audio/aiff.py#L28-L30
mapnik/python-mapnik
a2c2a86eec954b42d7f00093da03807d0834b1b4
mapnik/printing/__init__.py
python
PDFPrinter._draw_line
(self, ctx, start_x, start_y, end_x, end_y, line_width=1, stroke_color=(0.5, 0.5, 0.5))
Draws a line from (start_x, start_y) to (end_x, end_y) on the specified cairo context. By default, the line drawn is 1px wide and gray.
Draws a line from (start_x, start_y) to (end_x, end_y) on the specified cairo context. By default, the line drawn is 1px wide and gray.
[ "Draws", "a", "line", "from", "(", "start_x", "start_y", ")", "to", "(", "end_x", "end_y", ")", "on", "the", "specified", "cairo", "context", ".", "By", "default", "the", "line", "drawn", "is", "1px", "wide", "and", "gray", "." ]
def _draw_line(self, ctx, start_x, start_y, end_x, end_y, line_width=1, stroke_color=(0.5, 0.5, 0.5)): """ Draws a line from (start_x, start_y) to (end_x, end_y) on the specified cairo context. By default, the line drawn is 1px wide and gray. """ ctx.save() ctx.move_to(start_x, start_y) ctx.line_to(end_x, end_y) ctx.set_source_rgb(*stroke_color) ctx.set_line_width(line_width) ctx.stroke() ctx.restore()
[ "def", "_draw_line", "(", "self", ",", "ctx", ",", "start_x", ",", "start_y", ",", "end_x", ",", "end_y", ",", "line_width", "=", "1", ",", "stroke_color", "=", "(", "0.5", ",", "0.5", ",", "0.5", ")", ")", ":", "ctx", ".", "save", "(", ")", "ctx...
https://github.com/mapnik/python-mapnik/blob/a2c2a86eec954b42d7f00093da03807d0834b1b4/mapnik/printing/__init__.py#L453-L466
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/idlelib/EditorWindow.py
python
_sphinx_version
()
return release
Format sys.version_info to produce the Sphinx version string used to install the chm docs
Format sys.version_info to produce the Sphinx version string used to install the chm docs
[ "Format", "sys", ".", "version_info", "to", "produce", "the", "Sphinx", "version", "string", "used", "to", "install", "the", "chm", "docs" ]
def _sphinx_version(): "Format sys.version_info to produce the Sphinx version string used to install the chm docs" major, minor, micro, level, serial = sys.version_info release = '%s%s' % (major, minor) release += '%s' % (micro,) if level == 'candidate': release += 'rc%s' % (serial,) elif level != 'final': release += '%s%s' % (level[0], serial) return release
[ "def", "_sphinx_version", "(", ")", ":", "major", ",", "minor", ",", "micro", ",", "level", ",", "serial", "=", "sys", ".", "version_info", "release", "=", "'%s%s'", "%", "(", "major", ",", "minor", ")", "release", "+=", "'%s'", "%", "(", "micro", ",...
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/idlelib/EditorWindow.py#L31-L40
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/celery/app/control.py
python
Inspect.hello
(self, from_node, revoked=None)
return self._request('hello', from_node=from_node, revoked=revoked)
[]
def hello(self, from_node, revoked=None): return self._request('hello', from_node=from_node, revoked=revoked)
[ "def", "hello", "(", "self", ",", "from_node", ",", "revoked", "=", "None", ")", ":", "return", "self", ".", "_request", "(", "'hello'", ",", "from_node", "=", "from_node", ",", "revoked", "=", "revoked", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/app/control.py#L128-L129
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/sharing.py
python
SharePathError.is_inside_public_folder
(self)
return self._tag == 'inside_public_folder'
Check if the union tag is ``inside_public_folder``. :rtype: bool
Check if the union tag is ``inside_public_folder``.
[ "Check", "if", "the", "union", "tag", "is", "inside_public_folder", "." ]
def is_inside_public_folder(self): """ Check if the union tag is ``inside_public_folder``. :rtype: bool """ return self._tag == 'inside_public_folder'
[ "def", "is_inside_public_folder", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'inside_public_folder'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/sharing.py#L8378-L8384
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/physics/secondquant.py
python
VarBosonicBasis.__init__
(self, n_max)
[]
def __init__(self, n_max): self.n_max = n_max self._build_states()
[ "def", "__init__", "(", "self", ",", "n_max", ")", ":", "self", ".", "n_max", "=", "n_max", "self", ".", "_build_states", "(", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/physics/secondquant.py#L1449-L1451
GoSecure/pyrdp
abd8b8762b6d7fd0e49d4a927b529f892b412743
pyrdp/pdu/player.py
python
PlayerFileDownloadResponsePDU.__init__
(self, timestamp: int, deviceID: int, path: str, offset: int, payload: bytes)
:param timestamp: time stamp for this PDU. :param deviceID: ID of the device used. :param path: path of the directory to list. The path should be a Unix-style path. :param offset: offset at which the data starts in the file. :param payload: file data that was read.
:param timestamp: time stamp for this PDU. :param deviceID: ID of the device used. :param path: path of the directory to list. The path should be a Unix-style path. :param offset: offset at which the data starts in the file. :param payload: file data that was read.
[ ":", "param", "timestamp", ":", "time", "stamp", "for", "this", "PDU", ".", ":", "param", "deviceID", ":", "ID", "of", "the", "device", "used", ".", ":", "param", "path", ":", "path", "of", "the", "directory", "to", "list", ".", "The", "path", "shoul...
def __init__(self, timestamp: int, deviceID: int, path: str, offset: int, payload: bytes): """ :param timestamp: time stamp for this PDU. :param deviceID: ID of the device used. :param path: path of the directory to list. The path should be a Unix-style path. :param offset: offset at which the data starts in the file. :param payload: file data that was read. """ super().__init__(PlayerPDUType.FILE_DOWNLOAD_RESPONSE, timestamp, payload) self.deviceID = deviceID self.path = path self.offset = offset
[ "def", "__init__", "(", "self", ",", "timestamp", ":", "int", ",", "deviceID", ":", "int", ",", "path", ":", "str", ",", "offset", ":", "int", ",", "payload", ":", "bytes", ")", ":", "super", "(", ")", ".", "__init__", "(", "PlayerPDUType", ".", "F...
https://github.com/GoSecure/pyrdp/blob/abd8b8762b6d7fd0e49d4a927b529f892b412743/pyrdp/pdu/player.py#L193-L205
clarkduvall/serpy
0c58fb897e60c572f5d21f93966b3e6d8a91c305
serpy/fields.py
python
Field.as_getter
(self, serializer_field_name, serializer_cls)
return None
Returns a function that fetches an attribute from an object. Return ``None`` to use the default getter for the serializer defined in :attr:`Serializer.default_getter`. When a :class:`Serializer` is defined, each :class:`Field` will be converted into a getter function using this method. During serialization, each getter will be called with the object being serialized, and the return value will be passed through :meth:`Field.to_value`. If a :class:`Field` has ``getter_takes_serializer = True``, then the getter returned from this method will be called with the :class:`Serializer` instance as the first argument, and the object being serialized as the second. :param str serializer_field_name: The name this field was assigned to on the serializer. :param serializer_cls: The :class:`Serializer` this field is a part of.
Returns a function that fetches an attribute from an object.
[ "Returns", "a", "function", "that", "fetches", "an", "attribute", "from", "an", "object", "." ]
def as_getter(self, serializer_field_name, serializer_cls): """Returns a function that fetches an attribute from an object. Return ``None`` to use the default getter for the serializer defined in :attr:`Serializer.default_getter`. When a :class:`Serializer` is defined, each :class:`Field` will be converted into a getter function using this method. During serialization, each getter will be called with the object being serialized, and the return value will be passed through :meth:`Field.to_value`. If a :class:`Field` has ``getter_takes_serializer = True``, then the getter returned from this method will be called with the :class:`Serializer` instance as the first argument, and the object being serialized as the second. :param str serializer_field_name: The name this field was assigned to on the serializer. :param serializer_cls: The :class:`Serializer` this field is a part of. """ return None
[ "def", "as_getter", "(", "self", ",", "serializer_field_name", ",", "serializer_cls", ")", ":", "return", "None" ]
https://github.com/clarkduvall/serpy/blob/0c58fb897e60c572f5d21f93966b3e6d8a91c305/serpy/fields.py#L55-L76
peering-manager/peering-manager
62c870fb9caa6dfc056feb77c595d45bc3c4988a
extras/api/views.py
python
IXAPIViewSet.customers
(self, request, pk=None)
return Response(data=customers)
[]
def customers(self, request, pk=None): # Make sure request is valid serializer = IXAPICustomerSerializer(data=request.query_params) serializer.is_valid(raise_exception=True) # Query IX-API with given parameters c = Client( ixapi_url=serializer.validated_data.get("url"), ixapi_key=serializer.validated_data.get("api_key"), ixapi_secret=serializer.validated_data.get("api_secret"), ) c.auth() _, customers = c.get("customers") return Response(data=customers)
[ "def", "customers", "(", "self", ",", "request", ",", "pk", "=", "None", ")", ":", "# Make sure request is valid", "serializer", "=", "IXAPICustomerSerializer", "(", "data", "=", "request", ".", "query_params", ")", "serializer", ".", "is_valid", "(", "raise_exc...
https://github.com/peering-manager/peering-manager/blob/62c870fb9caa6dfc056feb77c595d45bc3c4988a/extras/api/views.py#L40-L54
iGio90/Dwarf
bb3011cdffd209c7e3f5febe558053bf649ca69c
dwarf_debugger/lib/adb.py
python
Adb.device
(self, value)
set serial and check for root
set serial and check for root
[ "set", "serial", "and", "check", "for", "root" ]
def device(self, value): """ set serial and check for root """ try: if isinstance(value, str): self._device_serial = value self._check_requirements() except ValueError: self._device_serial = None
[ "def", "device", "(", "self", ",", "value", ")", ":", "try", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "self", ".", "_device_serial", "=", "value", "self", ".", "_check_requirements", "(", ")", "except", "ValueError", ":", "self", "....
https://github.com/iGio90/Dwarf/blob/bb3011cdffd209c7e3f5febe558053bf649ca69c/dwarf_debugger/lib/adb.py#L60-L68
allenai/dnw
aa9c4f8e38344a832afd0c30a119d642301b0cc5
genutil/config.py
python
AttrDict.yaml
(self)
return yaml_dict
Convert object to yaml dict and return.
Convert object to yaml dict and return.
[ "Convert", "object", "to", "yaml", "dict", "and", "return", "." ]
def yaml(self): """Convert object to yaml dict and return. """ yaml_dict = {} for key in self.__dict__: value = self.__dict__[key] if isinstance(value, AttrDict): yaml_dict[key] = value.yaml() elif isinstance(value, list): if isinstance(value[0], AttrDict): new_l = [] for item in value: new_l.append(item.yaml()) yaml_dict[key] = new_l else: yaml_dict[key] = value else: yaml_dict[key] = value return yaml_dict
[ "def", "yaml", "(", "self", ")", ":", "yaml_dict", "=", "{", "}", "for", "key", "in", "self", ".", "__dict__", ":", "value", "=", "self", ".", "__dict__", "[", "key", "]", "if", "isinstance", "(", "value", ",", "AttrDict", ")", ":", "yaml_dict", "[...
https://github.com/allenai/dnw/blob/aa9c4f8e38344a832afd0c30a119d642301b0cc5/genutil/config.py#L61-L80
kovidgoyal/calibre
2b41671370f2a9eb1109b9ae901ccf915f1bd0c8
src/calibre/ebooks/rtf2xml/output.py
python
Output.__output_to_standard_func
(self)
Required: nothing Returns: nothing Logic: read one line at a time. Output to standard
Required: nothing Returns: nothing Logic: read one line at a time. Output to standard
[ "Required", ":", "nothing", "Returns", ":", "nothing", "Logic", ":", "read", "one", "line", "at", "a", "time", ".", "Output", "to", "standard" ]
def __output_to_standard_func(self): """ Required: nothing Returns: nothing Logic: read one line at a time. Output to standard """ with open_for_read(self.__file) as read_obj: for line in read_obj: sys.stdout.write(line)
[ "def", "__output_to_standard_func", "(", "self", ")", ":", "with", "open_for_read", "(", "self", ".", "__file", ")", "as", "read_obj", ":", "for", "line", "in", "read_obj", ":", "sys", ".", "stdout", ".", "write", "(", "line", ")" ]
https://github.com/kovidgoyal/calibre/blob/2b41671370f2a9eb1109b9ae901ccf915f1bd0c8/src/calibre/ebooks/rtf2xml/output.py#L108-L119
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/gui/api_value_renderers.py
python
ApiRDFStringRenderer.RenderValue
(self, value)
return self._IncludeTypeInfo(result, value)
[]
def RenderValue(self, value): result = str(value) return self._IncludeTypeInfo(result, value)
[ "def", "RenderValue", "(", "self", ",", "value", ")", ":", "result", "=", "str", "(", "value", ")", "return", "self", ".", "_IncludeTypeInfo", "(", "result", ",", "value", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_value_renderers.py#L333-L335
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
run_statements
(*args)
return _idaapi.run_statements(*args)
run_statements(str, elang=None) -> bool
run_statements(str, elang=None) -> bool
[ "run_statements", "(", "str", "elang", "=", "None", ")", "-", ">", "bool" ]
def run_statements(*args): """ run_statements(str, elang=None) -> bool """ return _idaapi.run_statements(*args)
[ "def", "run_statements", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "run_statements", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L26847-L26851
gwastro/pycbc
1e1c85534b9dba8488ce42df693230317ca63dea
pycbc/waveform/utils.py
python
coalign_waveforms
(h1, h2, psd=None, low_frequency_cutoff=None, high_frequency_cutoff=None, resize=True)
return h1, h2
Return two time series which are aligned in time and phase. The alignment is only to the nearest sample point and all changes to the phase are made to the first input waveform. Waveforms should not be split accross the vector boundary. If it is, please use roll or cyclic time shift to ensure that the entire signal is contiguous in the time series. Parameters ---------- h1: pycbc.types.TimeSeries The first waveform to align. h2: pycbc.types.TimeSeries The second waveform to align. psd: {None, pycbc.types.FrequencySeries} A psd to weight the alignment low_frequency_cutoff: {None, float} The low frequency cutoff to weight the matching in Hz. high_frequency_cutoff: {None, float} The high frequency cutoff to weight the matching in Hz. resize: Optional, {True, boolean} If true, the vectors will be resized to match each other. If false, they must be the same length and even in length Returns ------- h1: pycbc.types.TimeSeries The shifted waveform to align with h2 h2: pycbc.type.TimeSeries The resized (if necessary) waveform to align with h1.
Return two time series which are aligned in time and phase.
[ "Return", "two", "time", "series", "which", "are", "aligned", "in", "time", "and", "phase", "." ]
def coalign_waveforms(h1, h2, psd=None, low_frequency_cutoff=None, high_frequency_cutoff=None, resize=True): """ Return two time series which are aligned in time and phase. The alignment is only to the nearest sample point and all changes to the phase are made to the first input waveform. Waveforms should not be split accross the vector boundary. If it is, please use roll or cyclic time shift to ensure that the entire signal is contiguous in the time series. Parameters ---------- h1: pycbc.types.TimeSeries The first waveform to align. h2: pycbc.types.TimeSeries The second waveform to align. psd: {None, pycbc.types.FrequencySeries} A psd to weight the alignment low_frequency_cutoff: {None, float} The low frequency cutoff to weight the matching in Hz. high_frequency_cutoff: {None, float} The high frequency cutoff to weight the matching in Hz. resize: Optional, {True, boolean} If true, the vectors will be resized to match each other. If false, they must be the same length and even in length Returns ------- h1: pycbc.types.TimeSeries The shifted waveform to align with h2 h2: pycbc.type.TimeSeries The resized (if necessary) waveform to align with h1. """ from pycbc.filter import matched_filter mlen = ceilpow2(max(len(h1), len(h2))) h1 = h1.copy() h2 = h2.copy() if resize: h1.resize(mlen) h2.resize(mlen) elif len(h1) != len(h2) or len(h2) % 2 != 0: raise ValueError("Time series must be the same size and even if you do " "not allow resizing") snr = matched_filter(h1, h2, psd=psd, low_frequency_cutoff=low_frequency_cutoff, high_frequency_cutoff=high_frequency_cutoff) _, l = snr.abs_max_loc() rotation = snr[l] / abs(snr[l]) h1 = (h1.to_frequencyseries() * rotation).to_timeseries() h1.roll(l) h1 = TimeSeries(h1, delta_t=h2.delta_t, epoch=h2.start_time) return h1, h2
[ "def", "coalign_waveforms", "(", "h1", ",", "h2", ",", "psd", "=", "None", ",", "low_frequency_cutoff", "=", "None", ",", "high_frequency_cutoff", "=", "None", ",", "resize", "=", "True", ")", ":", "from", "pycbc", ".", "filter", "import", "matched_filter", ...
https://github.com/gwastro/pycbc/blob/1e1c85534b9dba8488ce42df693230317ca63dea/pycbc/waveform/utils.py#L46-L103
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/site-packages/django/utils/cache.py
python
learn_cache_key
(request, response, cache_timeout=None, key_prefix=None, cache=None)
Learns what headers to take into account for some request path from the response object. It stores those headers in a global path registry so that later access to that path will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation. The list of headers to use for cache key generation is stored in the same cache as the pages themselves. If the cache ages some data out of the cache, this just means that we have to build the response once to get at the Vary header and so at the list of headers to use for the cache key.
Learns what headers to take into account for some request path from the response object. It stores those headers in a global path registry so that later access to that path will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation.
[ "Learns", "what", "headers", "to", "take", "into", "account", "for", "some", "request", "path", "from", "the", "response", "object", ".", "It", "stores", "those", "headers", "in", "a", "global", "path", "registry", "so", "that", "later", "access", "to", "t...
def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None): """ Learns what headers to take into account for some request path from the response object. It stores those headers in a global path registry so that later access to that path will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation. The list of headers to use for cache key generation is stored in the same cache as the pages themselves. If the cache ages some data out of the cache, this just means that we have to build the response once to get at the Vary header and so at the list of headers to use for the cache key. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = get_cache(settings.CACHE_MIDDLEWARE_ALIAS) if response.has_header('Vary'): headerlist = ['HTTP_'+header.upper().replace('-', '_') for header in cc_delim_re.split(response['Vary'])] cache.set(cache_key, headerlist, cache_timeout) return _generate_cache_key(request, request.method, headerlist, key_prefix) else: # if there is no Vary header, we still need a cache key # for the request.get_full_path() cache.set(cache_key, [], cache_timeout) return _generate_cache_key(request, request.method, [], key_prefix)
[ "def", "learn_cache_key", "(", "request", ",", "response", ",", "cache_timeout", "=", "None", ",", "key_prefix", "=", "None", ",", "cache", "=", "None", ")", ":", "if", "key_prefix", "is", "None", ":", "key_prefix", "=", "settings", ".", "CACHE_MIDDLEWARE_KE...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/utils/cache.py#L216-L245
digidotcom/xbee-python
0757f4be0017530c205175fbee8f9f61be9614d1
digi/xbee/util/xmodem.py
python
_XModemReadSession.get_file
(self)
Performs the file read operation. Raises: XModemCancelException: if the transfer is cancelled by the remote end. XModemException: if there is any error during the file read process.
Performs the file read operation.
[ "Performs", "the", "file", "read", "operation", "." ]
def get_file(self): """ Performs the file read operation. Raises: XModemCancelException: if the transfer is cancelled by the remote end. XModemException: if there is any error during the file read process. """ if self._log: self._log.debug("Downloading '%s' file through XModem" % self._dest_path) self._download_file = _DownloadFile(self._dest_path, self._mode) # Notify we are ready to receive data. self._send_verification_char() # Execute special protocol pre-actions. if self._mode == _XModemMode.YMODEM: self._read_block_0() else: self._seq_index = 1 # Perform file download process. data = self._read_packet() previous_percent = None while len(data) > 0: if self._progress_cb is not None and self._download_file.percent != previous_percent: self._progress_cb(self._download_file.percent) previous_percent = self._download_file.percent self._download_file.write_data_chunk(data) data = self._read_packet() self._download_file.close_file() # Execute special protocol post-actions. if self._mode == _XModemMode.YMODEM: self._send_verification_char() self._read_block_0()
[ "def", "get_file", "(", "self", ")", ":", "if", "self", ".", "_log", ":", "self", ".", "_log", ".", "debug", "(", "\"Downloading '%s' file through XModem\"", "%", "self", ".", "_dest_path", ")", "self", ".", "_download_file", "=", "_DownloadFile", "(", "self...
https://github.com/digidotcom/xbee-python/blob/0757f4be0017530c205175fbee8f9f61be9614d1/digi/xbee/util/xmodem.py#L893-L924
cournape/Bento
37de23d784407a7c98a4a15770ffc570d5f32d70
bento/private/_yaku/yaku/context.py
python
_hook_id_to_hook_path
(hook_dict)
return dict([(k.srcpath(), v) for k, v in hook_dict.items()])
[]
def _hook_id_to_hook_path(hook_dict): # convert a hook dict indexed by id to a hook dict indexed by # paths (for storage) return dict([(k.srcpath(), v) for k, v in hook_dict.items()])
[ "def", "_hook_id_to_hook_path", "(", "hook_dict", ")", ":", "# convert a hook dict indexed by id to a hook dict indexed by", "# paths (for storage)", "return", "dict", "(", "[", "(", "k", ".", "srcpath", "(", ")", ",", "v", ")", "for", "k", ",", "v", "in", "hook_d...
https://github.com/cournape/Bento/blob/37de23d784407a7c98a4a15770ffc570d5f32d70/bento/private/_yaku/yaku/context.py#L55-L58
ChineseGLUE/ChineseGLUE
1591b85cf5427c2ff60f718d359ecb71d2b44879
baselines/models/ernie/modeling.py
python
BertConfig.to_json_string
(self)
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
Serializes this instance to a JSON string.
Serializes this instance to a JSON string.
[ "Serializes", "this", "instance", "to", "a", "JSON", "string", "." ]
def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
[ "def", "to_json_string", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "to_dict", "(", ")", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ")", "+", "\"\\n\"" ]
https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models/ernie/modeling.py#L102-L104
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/internals/blocks.py
python
_block_shape
(values, ndim=1, shape=None)
return values
guarantee the shape of the values to be at least 1 d
guarantee the shape of the values to be at least 1 d
[ "guarantee", "the", "shape", "of", "the", "values", "to", "be", "at", "least", "1", "d" ]
def _block_shape(values, ndim=1, shape=None): """ guarantee the shape of the values to be at least 1 d """ if values.ndim < ndim: if shape is None: shape = values.shape if not is_extension_array_dtype(values): # TODO: https://github.com/pandas-dev/pandas/issues/23023 # block.shape is incorrect for "2D" ExtensionArrays # We can't, and don't need to, reshape. values = values.reshape(tuple((1, ) + shape)) return values
[ "def", "_block_shape", "(", "values", ",", "ndim", "=", "1", ",", "shape", "=", "None", ")", ":", "if", "values", ".", "ndim", "<", "ndim", ":", "if", "shape", "is", "None", ":", "shape", "=", "values", ".", "shape", "if", "not", "is_extension_array_...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pandas-0.24.2-py3.7-macosx-10.9-x86_64.egg/pandas/core/internals/blocks.py#L3118-L3128
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/celery-4.2.1/celery/app/utils.py
python
Settings.get_by_parts
(self, *parts)
return self['_'.join(part for part in parts if part)]
Return the current value for setting specified as a path. Example: >>> from proj.celery import app >>> app.conf.get_by_parts('worker', 'disable_rate_limits') False
Return the current value for setting specified as a path.
[ "Return", "the", "current", "value", "for", "setting", "specified", "as", "a", "path", "." ]
def get_by_parts(self, *parts): """Return the current value for setting specified as a path. Example: >>> from proj.celery import app >>> app.conf.get_by_parts('worker', 'disable_rate_limits') False """ return self['_'.join(part for part in parts if part)]
[ "def", "get_by_parts", "(", "self", ",", "*", "parts", ")", ":", "return", "self", "[", "'_'", ".", "join", "(", "part", "for", "part", "in", "parts", "if", "part", ")", "]" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/celery-4.2.1/celery/app/utils.py#L160-L168
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/flows/general/file_finder.py
python
FileFinder.ReceiveFetchedFile
(self, unused_stat_entry, file_hash, request_data=None, is_duplicate=False)
Handle downloaded file from MultiGetFileLogic.
Handle downloaded file from MultiGetFileLogic.
[ "Handle", "downloaded", "file", "from", "MultiGetFileLogic", "." ]
def ReceiveFetchedFile(self, unused_stat_entry, file_hash, request_data=None, is_duplicate=False): """Handle downloaded file from MultiGetFileLogic.""" del is_duplicate # Unused. if "original_result" not in request_data: raise RuntimeError("Got fetched file data, but original result " "is missing") result = request_data["original_result"] result.hash_entry = file_hash self.SendReply(result)
[ "def", "ReceiveFetchedFile", "(", "self", ",", "unused_stat_entry", ",", "file_hash", ",", "request_data", "=", "None", ",", "is_duplicate", "=", "False", ")", ":", "del", "is_duplicate", "# Unused.", "if", "\"original_result\"", "not", "in", "request_data", ":", ...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/flows/general/file_finder.py#L372-L386
vanhuyz/CycleGAN-TensorFlow
befe2f57032ee6c25d0dbd1f497f5b5432375da5
build_data.py
python
data_reader
(input_dir, shuffle=True)
return file_paths
Read images from input_dir then shuffle them Args: input_dir: string, path of input dir, e.g., /path/to/dir Returns: file_paths: list of strings
Read images from input_dir then shuffle them Args: input_dir: string, path of input dir, e.g., /path/to/dir Returns: file_paths: list of strings
[ "Read", "images", "from", "input_dir", "then", "shuffle", "them", "Args", ":", "input_dir", ":", "string", "path", "of", "input", "dir", "e", ".", "g", ".", "/", "path", "/", "to", "/", "dir", "Returns", ":", "file_paths", ":", "list", "of", "strings" ...
def data_reader(input_dir, shuffle=True): """Read images from input_dir then shuffle them Args: input_dir: string, path of input dir, e.g., /path/to/dir Returns: file_paths: list of strings """ file_paths = [] for img_file in scandir(input_dir): if img_file.name.endswith('.jpg') and img_file.is_file(): file_paths.append(img_file.path) if shuffle: # Shuffle the ordering of all image files in order to guarantee # random ordering of the images with respect to label in the # saved TFRecord files. Make the randomization repeatable. shuffled_index = list(range(len(file_paths))) random.seed(12345) random.shuffle(shuffled_index) file_paths = [file_paths[i] for i in shuffled_index] return file_paths
[ "def", "data_reader", "(", "input_dir", ",", "shuffle", "=", "True", ")", ":", "file_paths", "=", "[", "]", "for", "img_file", "in", "scandir", "(", "input_dir", ")", ":", "if", "img_file", ".", "name", ".", "endswith", "(", "'.jpg'", ")", "and", "img_...
https://github.com/vanhuyz/CycleGAN-TensorFlow/blob/befe2f57032ee6c25d0dbd1f497f5b5432375da5/build_data.py#L24-L47
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/teleport/webroot/app/controller/__init__.py
python
fix_controller
()
[]
def fix_controller(): dbg_mode, _ = tp_cfg().get_bool('common::debug-mode', False) if dbg_mode: controllers.append((r'/exit/9E37CBAEE2294D9D9965112025CEE87F', index.ExitHandler))
[ "def", "fix_controller", "(", ")", ":", "dbg_mode", ",", "_", "=", "tp_cfg", "(", ")", ".", "get_bool", "(", "'common::debug-mode'", ",", "False", ")", "if", "dbg_mode", ":", "controllers", ".", "append", "(", "(", "r'/exit/9E37CBAEE2294D9D9965112025CEE87F'", ...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/teleport/webroot/app/controller/__init__.py#L298-L301
ysrc/xunfeng
40d40ecf55910019b8b904ef70ae1eebb6b6d26f
vulscan/vuldb/websphere_CVE_2015_7450.py
python
get_plugin_info
()
return plugin_info
[]
def get_plugin_info(): plugin_info = { "name": "WebSphere反序列化代码执行", "info": "漏洞的成因是Apache Commons Collections (ACC) 3.2.1及4.0版本未能正确验证用户输入,其InvokerTransformer类在反序列化来自可疑域的数据时存在安全漏洞,这可使攻击者在用户输入中附加恶意代码并组合运用不同类的readObject()方法,在最终类型检查之前执行Java函数或字节码(包括调用Runtime.exec()执行本地OS命令)。", "level": "紧急", "type": "代码执行", "author": "Dee Ng<d33.n99@gmail.com>", "url": "https://www-01.ibm.com/support/docview.wss?uid=swg21970575", "keyword": "tag:websphere", "source": 1 } return plugin_info
[ "def", "get_plugin_info", "(", ")", ":", "plugin_info", "=", "{", "\"name\"", ":", "\"WebSphere反序列化代码执行\",", "", "\"info\"", ":", "\"漏洞的成因是Apache Commons Collections (ACC) 3.2.1及4.0版本未能正确验证用户输入,其InvokerTransformer类在反序列化来自可疑域的数据时存在安全漏洞,这可使攻击者在用户输入中附加恶意代码并组合运用不同类的readObject()方法,在最终类型检查之前执行...
https://github.com/ysrc/xunfeng/blob/40d40ecf55910019b8b904ef70ae1eebb6b6d26f/vulscan/vuldb/websphere_CVE_2015_7450.py#L10-L21
gawel/pyquery
0a5f285d8541e24b0aeadc5e928037d748e0327c
pyquery/pyquery.py
python
PyQuery.hide
(self)
return self.css('display', 'none')
Remove display:none to elements style: >>> print(PyQuery('<div style="display:none;"/>').hide()) <div style="display: none"/>
Remove display:none to elements style:
[ "Remove", "display", ":", "none", "to", "elements", "style", ":" ]
def hide(self): """Remove display:none to elements style: >>> print(PyQuery('<div style="display:none;"/>').hide()) <div style="display: none"/> """ return self.css('display', 'none')
[ "def", "hide", "(", "self", ")", ":", "return", "self", ".", "css", "(", "'display'", ",", "'none'", ")" ]
https://github.com/gawel/pyquery/blob/0a5f285d8541e24b0aeadc5e928037d748e0327c/pyquery/pyquery.py#L935-L942
ansible-collections/community.general
3faffe8f47968a2400ba3c896c8901c03001a194
plugins/modules/system/iptables_state.py
python
initialize_from_null_state
(initializer, initcommand, fallbackcmd, table)
return rc, out, err
This ensures iptables-state output is suitable for iptables-restore to roll back to it, i.e. iptables-save output is not empty. This also works for the iptables-nft-save alternative.
This ensures iptables-state output is suitable for iptables-restore to roll back to it, i.e. iptables-save output is not empty. This also works for the iptables-nft-save alternative.
[ "This", "ensures", "iptables", "-", "state", "output", "is", "suitable", "for", "iptables", "-", "restore", "to", "roll", "back", "to", "it", "i", ".", "e", ".", "iptables", "-", "save", "output", "is", "not", "empty", ".", "This", "also", "works", "fo...
def initialize_from_null_state(initializer, initcommand, fallbackcmd, table): ''' This ensures iptables-state output is suitable for iptables-restore to roll back to it, i.e. iptables-save output is not empty. This also works for the iptables-nft-save alternative. ''' if table is None: table = 'filter' commandline = list(initializer) commandline += ['-t', table] dummy = module.run_command(commandline, check_rc=True) (rc, out, err) = module.run_command(initcommand, check_rc=True) if '*%s' % table not in out.splitlines(): # The last resort. iptables_input = '*%s\n:OUTPUT ACCEPT\nCOMMIT\n' % table dummy = module.run_command(fallbackcmd, data=iptables_input, check_rc=True) (rc, out, err) = module.run_command(initcommand, check_rc=True) return rc, out, err
[ "def", "initialize_from_null_state", "(", "initializer", ",", "initcommand", ",", "fallbackcmd", ",", "table", ")", ":", "if", "table", "is", "None", ":", "table", "=", "'filter'", "commandline", "=", "list", "(", "initializer", ")", "commandline", "+=", "[", ...
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/modules/system/iptables_state.py#L307-L326
adamchainz/django-mysql
389594dc078f73c9f204306014332344fe4b6d04
src/django_mysql/cache.py
python
Options.__init__
(self, table: str)
[]
def __init__(self, table: str) -> None: self.db_table = table self.app_label = "django_mysql" self.model_name = "cacheentry" self.verbose_name = "cache entry" self.verbose_name_plural = "cache entries" self.object_name = "CacheEntry" self.abstract = False self.managed = True self.proxy = False self.swapped = False
[ "def", "__init__", "(", "self", ",", "table", ":", "str", ")", "->", "None", ":", "self", ".", "db_table", "=", "table", "self", ".", "app_label", "=", "\"django_mysql\"", "self", ".", "model_name", "=", "\"cacheentry\"", "self", ".", "verbose_name", "=", ...
https://github.com/adamchainz/django-mysql/blob/389594dc078f73c9f204306014332344fe4b6d04/src/django_mysql/cache.py#L54-L64
statsmodels/statsmodels
debbe7ea6ba28fe5bdb78f09f8cac694bef98722
statsmodels/tsa/tsatools.py
python
unintegrate
(x, levels)
return np.cumsum(np.r_[x0, x])
After taking n-differences of a series, return the original series Parameters ---------- x : array_like The n-th differenced series levels : list A list of the first-value in each differenced series, for [first-difference, second-difference, ..., n-th difference] Returns ------- y : array_like The original series de-differenced Examples -------- >>> x = np.array([1, 3, 9., 19, 8.]) >>> levels = unintegrate_levels(x, 2) >>> levels array([ 1., 2.]) >>> unintegrate(np.diff(x, 2), levels) array([ 1., 3., 9., 19., 8.])
After taking n-differences of a series, return the original series
[ "After", "taking", "n", "-", "differences", "of", "a", "series", "return", "the", "original", "series" ]
def unintegrate(x, levels): """ After taking n-differences of a series, return the original series Parameters ---------- x : array_like The n-th differenced series levels : list A list of the first-value in each differenced series, for [first-difference, second-difference, ..., n-th difference] Returns ------- y : array_like The original series de-differenced Examples -------- >>> x = np.array([1, 3, 9., 19, 8.]) >>> levels = unintegrate_levels(x, 2) >>> levels array([ 1., 2.]) >>> unintegrate(np.diff(x, 2), levels) array([ 1., 3., 9., 19., 8.]) """ levels = list(levels)[:] # copy if len(levels) > 1: x0 = levels.pop(-1) return unintegrate(np.cumsum(np.r_[x0, x]), levels) x0 = levels[0] return np.cumsum(np.r_[x0, x])
[ "def", "unintegrate", "(", "x", ",", "levels", ")", ":", "levels", "=", "list", "(", "levels", ")", "[", ":", "]", "# copy", "if", "len", "(", "levels", ")", ">", "1", ":", "x0", "=", "levels", ".", "pop", "(", "-", "1", ")", "return", "uninteg...
https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/tsa/tsatools.py#L742-L773
mandiant/capa
c0851fc643793c012f5dd764482133c25c3216c8
capa/render/default.py
python
render_capabilities
(doc, ostream: StringIO)
example:: +-------------------------------------------------------+-------------------------------------------------+ | CAPABILITY | NAMESPACE | |-------------------------------------------------------+-------------------------------------------------| | check for OutputDebugString error (2 matches) | anti-analysis/anti-debugging/debugger-detection | | read and send data from client to server | c2/file-transfer | | ... | ... | +-------------------------------------------------------+-------------------------------------------------+
example::
[ "example", "::" ]
def render_capabilities(doc, ostream: StringIO): """ example:: +-------------------------------------------------------+-------------------------------------------------+ | CAPABILITY | NAMESPACE | |-------------------------------------------------------+-------------------------------------------------| | check for OutputDebugString error (2 matches) | anti-analysis/anti-debugging/debugger-detection | | read and send data from client to server | c2/file-transfer | | ... | ... | +-------------------------------------------------------+-------------------------------------------------+ """ subrule_matches = find_subrule_matches(doc) rows = [] for rule in rutils.capability_rules(doc): if rule["meta"]["name"] in subrule_matches: # rules that are also matched by other rules should not get rendered by default. # this cuts down on the amount of output while giving approx the same detail. # see #224 continue count = len(rule["matches"]) if count == 1: capability = rutils.bold(rule["meta"]["name"]) else: capability = "%s (%d matches)" % (rutils.bold(rule["meta"]["name"]), count) rows.append((capability, rule["meta"]["namespace"])) if rows: ostream.write( tabulate.tabulate(rows, headers=[width("CAPABILITY", 50), width("NAMESPACE", 50)], tablefmt="psql") ) ostream.write("\n") else: ostream.writeln(rutils.bold("no capabilities found"))
[ "def", "render_capabilities", "(", "doc", ",", "ostream", ":", "StringIO", ")", ":", "subrule_matches", "=", "find_subrule_matches", "(", "doc", ")", "rows", "=", "[", "]", "for", "rule", "in", "rutils", ".", "capability_rules", "(", "doc", ")", ":", "if",...
https://github.com/mandiant/capa/blob/c0851fc643793c012f5dd764482133c25c3216c8/capa/render/default.py#L73-L108
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/core/leoGlobals.py
python
goto_last_exception
(c: Cmdr)
Go to the line given by sys.last_traceback.
Go to the line given by sys.last_traceback.
[ "Go", "to", "the", "line", "given", "by", "sys", ".", "last_traceback", "." ]
def goto_last_exception(c: Cmdr): """Go to the line given by sys.last_traceback.""" typ, val, tb = sys.exc_info() if tb: file_name, line_number = g.getLastTracebackFileAndLineNumber() line_number = max(0, line_number - 1) # Convert to zero-based. if file_name.endswith('scriptFile.py'): # A script. c.goToScriptLineNumber(line_number, c.p) else: for p in c.all_nodes(): if p.isAnyAtFileNode() and p.h.endswith(file_name): c.goToLineNumber(line_number) # 2021/07/28: fixed by mypy. return else: g.trace('No previous exception')
[ "def", "goto_last_exception", "(", "c", ":", "Cmdr", ")", ":", "typ", ",", "val", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "if", "tb", ":", "file_name", ",", "line_number", "=", "g", ".", "getLastTracebackFileAndLineNumber", "(", ")", "line_numb...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/core/leoGlobals.py#L6396-L6412
GiulioRossetti/cdlib
b2c6311b99725bb2b029556f531d244a2af14a2a
cdlib/algorithms/internal/multicom.py
python
MultiCom.__approximate_ppr
(self, adj_matrix, seed_set, alpha=0.85, epsilon=1e-5)
return prob
Compute the approximate Personalized PageRank (PPR) from a set set of seed node. This function implements the push method introduced by Andersen et al. in "Local graph partitioning using pagerank vectors", FOCS 2006. :param adj_matrix: compressed sparse row matrix or numpy array Adjacency matrix of the graph :param seed_set: list or set of int Set of seed nodes. :param alpha: float, default 0.85 1 - alpha corresponds to the probability for the random walk to restarts from the seed set. :param epsilon: float, default 1e-3 Precision parameter for the approximation :return: numpy 1D array Vector containing the approximate PPR for each node of the graph.
Compute the approximate Personalized PageRank (PPR) from a set set of seed node. This function implements the push method introduced by Andersen et al. in "Local graph partitioning using pagerank vectors", FOCS 2006. :param adj_matrix: compressed sparse row matrix or numpy array Adjacency matrix of the graph :param seed_set: list or set of int Set of seed nodes. :param alpha: float, default 0.85 1 - alpha corresponds to the probability for the random walk to restarts from the seed set. :param epsilon: float, default 1e-3 Precision parameter for the approximation :return: numpy 1D array Vector containing the approximate PPR for each node of the graph.
[ "Compute", "the", "approximate", "Personalized", "PageRank", "(", "PPR", ")", "from", "a", "set", "set", "of", "seed", "node", ".", "This", "function", "implements", "the", "push", "method", "introduced", "by", "Andersen", "et", "al", ".", "in", "Local", "...
def __approximate_ppr(self, adj_matrix, seed_set, alpha=0.85, epsilon=1e-5): """ Compute the approximate Personalized PageRank (PPR) from a set set of seed node. This function implements the push method introduced by Andersen et al. in "Local graph partitioning using pagerank vectors", FOCS 2006. :param adj_matrix: compressed sparse row matrix or numpy array Adjacency matrix of the graph :param seed_set: list or set of int Set of seed nodes. :param alpha: float, default 0.85 1 - alpha corresponds to the probability for the random walk to restarts from the seed set. :param epsilon: float, default 1e-3 Precision parameter for the approximation :return: numpy 1D array Vector containing the approximate PPR for each node of the graph. """ adj_matrix = self.__convert_adj_matrix(adj_matrix) degree = np.array(np.sum(adj_matrix, axis=0))[0] n_nodes = adj_matrix.shape[0] prob = np.zeros(n_nodes) res = np.zeros(n_nodes) res[list(seed_set)] = 1.0 / len(seed_set) next_nodes = deque(seed_set) while len(next_nodes) > 0: node = next_nodes.pop() push_val = res[node] - 0.5 * epsilon * degree[node] res[node] = 0.5 * epsilon * degree[node] prob[node] += (1.0 - alpha) * push_val put_val = alpha * push_val for neighbor in adj_matrix[node].indices: old_res = res[neighbor] res[neighbor] += put_val * adj_matrix[node, neighbor] / degree[node] threshold = epsilon * degree[neighbor] if res[neighbor] >= threshold > old_res: next_nodes.appendleft(neighbor) return prob
[ "def", "__approximate_ppr", "(", "self", ",", "adj_matrix", ",", "seed_set", ",", "alpha", "=", "0.85", ",", "epsilon", "=", "1e-5", ")", ":", "adj_matrix", "=", "self", ".", "__convert_adj_matrix", "(", "adj_matrix", ")", "degree", "=", "np", ".", "array"...
https://github.com/GiulioRossetti/cdlib/blob/b2c6311b99725bb2b029556f531d244a2af14a2a/cdlib/algorithms/internal/multicom.py#L57-L95
Dash-Industry-Forum/dash-live-source-simulator
23cb15c35656a731d9f6d78a30f2713eff2ec20d
dashlivesim/dashlib/mp4.py
python
trun_box.sample_count
(self)
return struct.unpack('>I', self.fmap[self.offset + 12: self.offset + 16])[0]
[]
def sample_count(self): return struct.unpack('>I', self.fmap[self.offset + 12: self.offset + 16])[0]
[ "def", "sample_count", "(", "self", ")", ":", "return", "struct", ".", "unpack", "(", "'>I'", ",", "self", ".", "fmap", "[", "self", ".", "offset", "+", "12", ":", "self", ".", "offset", "+", "16", "]", ")", "[", "0", "]" ]
https://github.com/Dash-Industry-Forum/dash-live-source-simulator/blob/23cb15c35656a731d9f6d78a30f2713eff2ec20d/dashlivesim/dashlib/mp4.py#L1363-L1365
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/_pydecimal.py
python
Decimal.__rmod__
(self, other, context=None)
return other.__mod__(self, context=context)
Swaps self/other and returns __mod__.
Swaps self/other and returns __mod__.
[ "Swaps", "self", "/", "other", "and", "returns", "__mod__", "." ]
def __rmod__(self, other, context=None): """Swaps self/other and returns __mod__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__mod__(self, context=context)
[ "def", "__rmod__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "return", "other", ".", "__mod__", "(", "self", ",", ...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/_pydecimal.py#L1530-L1535
nucypher/nucypher
f420caeb1c974f511f689fd1e5a9c6bbdf97f2d7
nucypher/blockchain/eth/agents.py
python
StakingEscrowAgent.deposit_tokens
(self, amount: NuNits, lock_periods: PeriodDelta, transacting_power: TransactingPower, staker_address: Optional[ChecksumAddress] = None, )
return receipt
Send tokens to the escrow from the sender's address to be locked on behalf of the staker address. If the sender address is not provided, the stakers address is used. Note that this resolved to two separate contract function signatures.
Send tokens to the escrow from the sender's address to be locked on behalf of the staker address. If the sender address is not provided, the stakers address is used. Note that this resolved to two separate contract function signatures.
[ "Send", "tokens", "to", "the", "escrow", "from", "the", "sender", "s", "address", "to", "be", "locked", "on", "behalf", "of", "the", "staker", "address", ".", "If", "the", "sender", "address", "is", "not", "provided", "the", "stakers", "address", "is", "...
def deposit_tokens(self, amount: NuNits, lock_periods: PeriodDelta, transacting_power: TransactingPower, staker_address: Optional[ChecksumAddress] = None, ) -> TxReceipt: """ Send tokens to the escrow from the sender's address to be locked on behalf of the staker address. If the sender address is not provided, the stakers address is used. Note that this resolved to two separate contract function signatures. """ if not staker_address: staker_address = transacting_power.account contract_function: ContractFunction = self.contract.functions.deposit(staker_address, amount, lock_periods) receipt: TxReceipt = self.blockchain.send_transaction(contract_function=contract_function, transacting_power=transacting_power) return receipt
[ "def", "deposit_tokens", "(", "self", ",", "amount", ":", "NuNits", ",", "lock_periods", ":", "PeriodDelta", ",", "transacting_power", ":", "TransactingPower", ",", "staker_address", ":", "Optional", "[", "ChecksumAddress", "]", "=", "None", ",", ")", "->", "T...
https://github.com/nucypher/nucypher/blob/f420caeb1c974f511f689fd1e5a9c6bbdf97f2d7/nucypher/blockchain/eth/agents.py#L453-L469
openai/jukebox
08efbbc1d4ed1a3cef96e08a931944c8b4d63bb3
apex/examples/imagenet/main_amp.py
python
accuracy
(output, target, topk=(1,))
return res
Computes the precision@k for the specified values of k
Computes the precision
[ "Computes", "the", "precision" ]
def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res
[ "def", "accuracy", "(", "output", ",", "target", ",", "topk", "=", "(", "1", ",", ")", ")", ":", "maxk", "=", "max", "(", "topk", ")", "batch_size", "=", "target", ".", "size", "(", "0", ")", "_", ",", "pred", "=", "output", ".", "topk", "(", ...
https://github.com/openai/jukebox/blob/08efbbc1d4ed1a3cef96e08a931944c8b4d63bb3/apex/examples/imagenet/main_amp.py#L499-L512
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/parsers/parser.py
python
Parser.parse
(self, **kwargs)
Parse the contents of the output files retrieved in the `FolderData`. This method should be implemented in the sub class. Outputs can be registered through the `out` method. After the `parse` call finishes, the runner will automatically link them up to the underlying `CalcJobNode`. :param kwargs: output nodes attached to the `CalcJobNode` of the parser instance. :return: an instance of ExitCode or None
Parse the contents of the output files retrieved in the `FolderData`.
[ "Parse", "the", "contents", "of", "the", "output", "files", "retrieved", "in", "the", "FolderData", "." ]
def parse(self, **kwargs): """Parse the contents of the output files retrieved in the `FolderData`. This method should be implemented in the sub class. Outputs can be registered through the `out` method. After the `parse` call finishes, the runner will automatically link them up to the underlying `CalcJobNode`. :param kwargs: output nodes attached to the `CalcJobNode` of the parser instance. :return: an instance of ExitCode or None """
[ "def", "parse", "(", "self", ",", "*", "*", "kwargs", ")", ":" ]
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/parsers/parser.py#L163-L171
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/modules/common/structures/subscription.py
python
SubscriptionRequest.server_proxy_password
(self)
return self._server_proxy_password
RHSM HTTP proxy - access password. NOTE: This property is stored in SecretData nested DBus structure to protect its contents. :return: RHSM HTTP proxy password stored in SecretData instance :rtype: SecretData instance
RHSM HTTP proxy - access password.
[ "RHSM", "HTTP", "proxy", "-", "access", "password", "." ]
def server_proxy_password(self) -> SecretData: """RHSM HTTP proxy - access password. NOTE: This property is stored in SecretData nested DBus structure to protect its contents. :return: RHSM HTTP proxy password stored in SecretData instance :rtype: SecretData instance """ return self._server_proxy_password
[ "def", "server_proxy_password", "(", "self", ")", "->", "SecretData", ":", "return", "self", ".", "_server_proxy_password" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/modules/common/structures/subscription.py#L379-L388
mozilla-services/socorro
8bff4a90e9e3320eabe7e067adbe0e89f6a39ba7
socorro/lib/threaded_task_manager.py
python
ThreadedTaskManager._responsive_join
(self, thread, waiting_func=None)
similar to the responsive sleep, a join function blocks a thread until some other thread dies. If that takes a long time, we'd like to have some indicaition as to what the waiting thread is doing. This method will wait for another thread while calling the waiting_func once every second. parameters: thread - an instance of the TaskThread class representing the thread to wait for waiting_func - a function to call every second while waiting for the thread to die
similar to the responsive sleep, a join function blocks a thread until some other thread dies. If that takes a long time, we'd like to have some indicaition as to what the waiting thread is doing. This method will wait for another thread while calling the waiting_func once every second.
[ "similar", "to", "the", "responsive", "sleep", "a", "join", "function", "blocks", "a", "thread", "until", "some", "other", "thread", "dies", ".", "If", "that", "takes", "a", "long", "time", "we", "d", "like", "to", "have", "some", "indicaition", "as", "t...
def _responsive_join(self, thread, waiting_func=None): """similar to the responsive sleep, a join function blocks a thread until some other thread dies. If that takes a long time, we'd like to have some indicaition as to what the waiting thread is doing. This method will wait for another thread while calling the waiting_func once every second. parameters: thread - an instance of the TaskThread class representing the thread to wait for waiting_func - a function to call every second while waiting for the thread to die""" while True: try: thread.join(1.0) if not thread.is_alive(): break if waiting_func: waiting_func() except KeyboardInterrupt: self.logger.debug("quit detected by _responsive_join") self.quit = True
[ "def", "_responsive_join", "(", "self", ",", "thread", ",", "waiting_func", "=", "None", ")", ":", "while", "True", ":", "try", ":", "thread", ".", "join", "(", "1.0", ")", "if", "not", "thread", ".", "is_alive", "(", ")", ":", "break", "if", "waitin...
https://github.com/mozilla-services/socorro/blob/8bff4a90e9e3320eabe7e067adbe0e89f6a39ba7/socorro/lib/threaded_task_manager.py#L157-L178
MushroomRL/mushroom-rl
a0eaa2cf8001e433419234a9fc48b64170e3f61c
mushroom_rl/utils/preprocessors.py
python
StandardizationPreprocessor.get_state
(self)
return self._obs_runstand.get_state()
Returns: A dictionary with the normalization state.
Returns: A dictionary with the normalization state.
[ "Returns", ":", "A", "dictionary", "with", "the", "normalization", "state", "." ]
def get_state(self): """ Returns: A dictionary with the normalization state. """ return self._obs_runstand.get_state()
[ "def", "get_state", "(", "self", ")", ":", "return", "self", ".", "_obs_runstand", ".", "get_state", "(", ")" ]
https://github.com/MushroomRL/mushroom-rl/blob/a0eaa2cf8001e433419234a9fc48b64170e3f61c/mushroom_rl/utils/preprocessors.py#L60-L66
timknip/pyswf
3740cc80d7650156831e728ea0d408819e5671eb
swf/stream.py
python
SWFStream.readSOUNDINFO
(self)
return SWFSoundInfo(self)
Read a SWFSoundInfo
Read a SWFSoundInfo
[ "Read", "a", "SWFSoundInfo" ]
def readSOUNDINFO(self): """ Read a SWFSoundInfo """ return SWFSoundInfo(self)
[ "def", "readSOUNDINFO", "(", "self", ")", ":", "return", "SWFSoundInfo", "(", "self", ")" ]
https://github.com/timknip/pyswf/blob/3740cc80d7650156831e728ea0d408819e5671eb/swf/stream.py#L397-L399
duerrp/pyexperiment
c426565d870d944bd5b9712629d8f1ba2527c67f
pyexperiment/utils/HierarchicalMapping.py
python
HierarchicalMapping._new_section
(cls, parent, level)
Creates a new section Mapping
Creates a new section Mapping
[ "Creates", "a", "new", "section", "Mapping" ]
def _new_section(cls, parent, level): """Creates a new section Mapping """ raise NotImplementedError("Subclass should implement this")
[ "def", "_new_section", "(", "cls", ",", "parent", ",", "level", ")", ":", "raise", "NotImplementedError", "(", "\"Subclass should implement this\"", ")" ]
https://github.com/duerrp/pyexperiment/blob/c426565d870d944bd5b9712629d8f1ba2527c67f/pyexperiment/utils/HierarchicalMapping.py#L39-L42
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/distutils/ccompiler.py
python
new_compiler
(plat=None, compiler=None, verbose=0, dry_run=0, force=0)
return klass(None, dry_run, force)
Generate an instance of some CCompiler subclass for the supplied platform/compiler combination. 'plat' defaults to 'os.name' (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler for that platform. Currently only 'posix' and 'nt' are supported, and the default compilers are "traditional Unix interface" (UnixCCompiler class) and Visual C++ (MSVCCompiler class). Note that it's perfectly possible to ask for a Unix compiler object under Windows, and a Microsoft compiler object under Unix -- if you supply a value for 'compiler', 'plat' is ignored.
Generate an instance of some CCompiler subclass for the supplied platform/compiler combination. 'plat' defaults to 'os.name' (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler for that platform. Currently only 'posix' and 'nt' are supported, and the default compilers are "traditional Unix interface" (UnixCCompiler class) and Visual C++ (MSVCCompiler class). Note that it's perfectly possible to ask for a Unix compiler object under Windows, and a Microsoft compiler object under Unix -- if you supply a value for 'compiler', 'plat' is ignored.
[ "Generate", "an", "instance", "of", "some", "CCompiler", "subclass", "for", "the", "supplied", "platform", "/", "compiler", "combination", ".", "plat", "defaults", "to", "os", ".", "name", "(", "eg", ".", "posix", "nt", ")", "and", "compiler", "defaults", ...
def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0): """Generate an instance of some CCompiler subclass for the supplied platform/compiler combination. 'plat' defaults to 'os.name' (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler for that platform. Currently only 'posix' and 'nt' are supported, and the default compilers are "traditional Unix interface" (UnixCCompiler class) and Visual C++ (MSVCCompiler class). Note that it's perfectly possible to ask for a Unix compiler object under Windows, and a Microsoft compiler object under Unix -- if you supply a value for 'compiler', 'plat' is ignored. """ if plat is None: plat = os.name try: if compiler is None: compiler = get_default_compiler(plat) (module_name, class_name, long_description) = compiler_class[compiler] except KeyError: msg = "don't know how to compile C/C++ code on platform '%s'" % plat if compiler is not None: msg = msg + " with '%s' compiler" % compiler raise DistutilsPlatformError, msg try: module_name = "distutils." + module_name __import__ (module_name) module = sys.modules[module_name] klass = vars(module)[class_name] except ImportError: raise DistutilsModuleError, \ "can't compile C/C++ code: unable to load module '%s'" % \ module_name except KeyError: raise DistutilsModuleError, \ ("can't compile C/C++ code: unable to find class '%s' " + "in module '%s'") % (class_name, module_name) # XXX The None is necessary to preserve backwards compatibility # with classes that expect verbose to be the first positional # argument. return klass(None, dry_run, force)
[ "def", "new_compiler", "(", "plat", "=", "None", ",", "compiler", "=", "None", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "force", "=", "0", ")", ":", "if", "plat", "is", "None", ":", "plat", "=", "os", ".", "name", "try", ":", "i...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/distutils/ccompiler.py#L962-L1004
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/requests/sessions.py
python
Session.post
(self, url, data=None, json=None, **kwargs)
return self.request('POST', url, data=data, json=json, **kwargs)
r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a POST request. Returns :class:`Response` object.
[ "r", "Sends", "a", "POST", "request", ".", "Returns", ":", "class", ":", "Response", "object", "." ]
def post(self, url, data=None, json=None, **kwargs): r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('POST', url, data=data, json=json, **kwargs)
[ "def", "post", "(", "self", ",", "url", ",", "data", "=", "None", ",", "json", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "request", "(", "'POST'", ",", "url", ",", "data", "=", "data", ",", "json", "=", "json", ",",...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/requests/sessions.py#L570-L581
pydicom/pynetdicom
f57d8214c82b63c8e76638af43ce331f584a80fa
pynetdicom/sop_class.py
python
uid_to_service_class
(uid: str)
return ServiceClass
Return the :class:`~pynetdicom.service_class.ServiceClass` object corresponding to `uid`. Parameters ---------- uid : pydicom.uid.UID The SOP or Service Class UID to use to find the corresponding Service Class. Returns ------- subclass of service_class.ServiceClass The Service Class corresponding to the SOP Class UID or the base class if support for the SOP Class isn't implemented.
Return the :class:`~pynetdicom.service_class.ServiceClass` object corresponding to `uid`.
[ "Return", "the", ":", "class", ":", "~pynetdicom", ".", "service_class", ".", "ServiceClass", "object", "corresponding", "to", "uid", "." ]
def uid_to_service_class(uid: str) -> Type[ServiceClass]: """Return the :class:`~pynetdicom.service_class.ServiceClass` object corresponding to `uid`. Parameters ---------- uid : pydicom.uid.UID The SOP or Service Class UID to use to find the corresponding Service Class. Returns ------- subclass of service_class.ServiceClass The Service Class corresponding to the SOP Class UID or the base class if support for the SOP Class isn't implemented. """ if uid in _VERIFICATION_CLASSES.values(): return VerificationServiceClass elif uid in _QR_CLASSES.values(): return QueryRetrieveServiceClass elif uid in _STORAGE_CLASSES.values(): return StorageServiceClass elif uid in _SERVICE_CLASSES: return _SERVICE_CLASSES[uid] elif uid in _APPLICATION_EVENT_CLASSES.values(): return ApplicationEventLoggingServiceClass elif uid in _BASIC_WORKLIST_CLASSES.values(): return BasicWorklistManagementServiceClass elif uid in _COLOR_PALETTE_CLASSES.values(): return ColorPaletteQueryRetrieveServiceClass elif uid in _DEFINED_PROCEDURE_CLASSES.values(): return DefinedProcedureProtocolQueryRetrieveServiceClass elif uid in _DISPLAY_SYSTEM_CLASSES.values(): return DisplaySystemManagementServiceClass elif uid in _HANGING_PROTOCOL_CLASSES.values(): return HangingProtocolQueryRetrieveServiceClass elif uid in _IMPLANT_TEMPLATE_CLASSES.values(): return ImplantTemplateQueryRetrieveServiceClass elif uid in _INSTANCE_AVAILABILITY_CLASSES.values(): return InstanceAvailabilityNotificationServiceClass elif uid in _MEDIA_CREATION_CLASSES.values(): return MediaCreationManagementServiceClass elif uid in _MEDIA_STORAGE_CLASSES.values(): return ServiceClass # Not yet implemented elif uid in _NON_PATIENT_OBJECT_CLASSES.values(): return NonPatientObjectStorageServiceClass elif uid in _PRINT_MANAGEMENT_CLASSES.values(): return PrintManagementServiceClass elif uid in _PROCEDURE_STEP_CLASSES.values(): return ProcedureStepServiceClass elif uid in _PROTOCOL_APPROVAL_CLASSES.values(): return ProtocolApprovalQueryRetrieveServiceClass elif uid in _RELEVANT_PATIENT_QUERY_CLASSES.values(): return RelevantPatientInformationQueryServiceClass elif uid in _RT_MACHINE_VERIFICATION_CLASSES.values(): return RTMachineVerificationServiceClass elif uid in _STORAGE_COMMITMENT_CLASSES.values(): return StorageCommitmentServiceClass elif uid in _SUBSTANCE_ADMINISTRATION_CLASSES.values(): return SubstanceAdministrationQueryServiceClass elif uid in _UNIFIED_PROCEDURE_STEP_CLASSES.values(): return UnifiedProcedureStepServiceClass # No SCP implemented return ServiceClass
[ "def", "uid_to_service_class", "(", "uid", ":", "str", ")", "->", "Type", "[", "ServiceClass", "]", ":", "if", "uid", "in", "_VERIFICATION_CLASSES", ".", "values", "(", ")", ":", "return", "VerificationServiceClass", "elif", "uid", "in", "_QR_CLASSES", ".", ...
https://github.com/pydicom/pynetdicom/blob/f57d8214c82b63c8e76638af43ce331f584a80fa/pynetdicom/sop_class.py#L41-L105
rcorcs/NatI
fdf014f4292afdc95250add7b6658468043228e1
lib/pygrooveshark-master/src/grooveshark/classes/song.py
python
Song.track
(self)
return self._track
track number
track number
[ "track", "number" ]
def track(self): """ track number """ return self._track
[ "def", "track", "(", "self", ")", ":", "return", "self", ".", "_track" ]
https://github.com/rcorcs/NatI/blob/fdf014f4292afdc95250add7b6658468043228e1/lib/pygrooveshark-master/src/grooveshark/classes/song.py#L103-L107
vcheckzen/FODI
3bb23644938a33c3fdfb9611a622e35ed4ce6532
back-end-py/main/3rd/PIL/ImageFile.py
python
Parser.feed
(self, data)
(Consumer) Feed data to the parser. :param data: A string buffer. :exception IOError: If the parser failed to parse the image file.
(Consumer) Feed data to the parser.
[ "(", "Consumer", ")", "Feed", "data", "to", "the", "parser", "." ]
def feed(self, data): """ (Consumer) Feed data to the parser. :param data: A string buffer. :exception IOError: If the parser failed to parse the image file. """ # collect data if self.finished: return if self.data is None: self.data = data else: self.data = self.data + data # parse what we have if self.decoder: if self.offset > 0: # skip header skip = min(len(self.data), self.offset) self.data = self.data[skip:] self.offset = self.offset - skip if self.offset > 0 or not self.data: return n, e = self.decoder.decode(self.data) if n < 0: # end of stream self.data = None self.finished = 1 if e < 0: # decoding error self.image = None raise_ioerror(e) else: # end of image return self.data = self.data[n:] elif self.image: # if we end up here with no decoder, this file cannot # be incrementally parsed. wait until we've gotten all # available data pass else: # attempt to open this file try: with io.BytesIO(self.data) as fp: im = Image.open(fp) except OSError: # traceback.print_exc() pass # not enough data else: flag = hasattr(im, "load_seek") or hasattr(im, "load_read") if flag or len(im.tile) != 1: # custom load code, or multiple tiles self.decode = None else: # initialize decoder im.load_prepare() d, e, o, a = im.tile[0] im.tile = [] self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig) self.decoder.setimage(im.im, e) # calculate decoder offset self.offset = o if self.offset <= len(self.data): self.data = self.data[self.offset :] self.offset = 0 self.image = im
[ "def", "feed", "(", "self", ",", "data", ")", ":", "# collect data", "if", "self", ".", "finished", ":", "return", "if", "self", ".", "data", "is", "None", ":", "self", ".", "data", "=", "data", "else", ":", "self", ".", "data", "=", "self", ".", ...
https://github.com/vcheckzen/FODI/blob/3bb23644938a33c3fdfb9611a622e35ed4ce6532/back-end-py/main/3rd/PIL/ImageFile.py#L356-L434
tensorflow/data-validation
6c68c219c5d78d3736fd011d8a7c53fbcb94379c
tensorflow_data_validation/statistics/generators/mutual_information.py
python
_PartitionFn.process
( self, element: types.SlicedRecordBatch )
Performs row-wise random key assignment and column-wise slicing. Each input RecordBatch is mapped to up to self._column_partitions output RecordBatch, each of which contains a subset of columns. Only the label column is duplicated across RecordBatches, so this is nearly a partitioning of columns. If self._column_partitions == 1, the output RecordBatch is unmodified. The total partition key space is _row_partitions * _column_partitions. Args: element: An input sliced record batch. Yields: A sequence of partitioned RecordBatches.
Performs row-wise random key assignment and column-wise slicing.
[ "Performs", "row", "-", "wise", "random", "key", "assignment", "and", "column", "-", "wise", "slicing", "." ]
def process( self, element: types.SlicedRecordBatch ) -> Iterable[Tuple[Tuple[types.SliceKey, int], pa.RecordBatch]]: """Performs row-wise random key assignment and column-wise slicing. Each input RecordBatch is mapped to up to self._column_partitions output RecordBatch, each of which contains a subset of columns. Only the label column is duplicated across RecordBatches, so this is nearly a partitioning of columns. If self._column_partitions == 1, the output RecordBatch is unmodified. The total partition key space is _row_partitions * _column_partitions. Args: element: An input sliced record batch. Yields: A sequence of partitioned RecordBatches. """ row_partition = self._rng.integers(0, self._row_partitions, dtype=int) if self._partitioner is None: slice_key, record_batch = element yield (slice_key, row_partition), record_batch else: for ((slice_key, column_partition), record_batch) in feature_partition_util.generate_feature_partitions( element, self._partitioner, self._label_column): partition = row_partition * self._column_partitions + column_partition yield (slice_key, partition), record_batch
[ "def", "process", "(", "self", ",", "element", ":", "types", ".", "SlicedRecordBatch", ")", "->", "Iterable", "[", "Tuple", "[", "Tuple", "[", "types", ".", "SliceKey", ",", "int", "]", ",", "pa", ".", "RecordBatch", "]", "]", ":", "row_partition", "="...
https://github.com/tensorflow/data-validation/blob/6c68c219c5d78d3736fd011d8a7c53fbcb94379c/tensorflow_data_validation/statistics/generators/mutual_information.py#L352-L382
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/sqlalchemy/sql/selectable.py
python
SelectBase._generate
(self)
return s
Override the default _generate() method to also clear out exported collections.
Override the default _generate() method to also clear out exported collections.
[ "Override", "the", "default", "_generate", "()", "method", "to", "also", "clear", "out", "exported", "collections", "." ]
def _generate(self): """Override the default _generate() method to also clear out exported collections.""" s = self.__class__.__new__(self.__class__) s.__dict__ = self.__dict__.copy() s._reset_exported() return s
[ "def", "_generate", "(", "self", ")", ":", "s", "=", "self", ".", "__class__", ".", "__new__", "(", "self", ".", "__class__", ")", "s", ".", "__dict__", "=", "self", ".", "__dict__", ".", "copy", "(", ")", "s", ".", "_reset_exported", "(", ")", "re...
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/sqlalchemy/sql/selectable.py#L1912-L1919
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/cache.py
python
Cache.get_path_for_link
(self, link)
Return a directory to store cached items in for link.
Return a directory to store cached items in for link.
[ "Return", "a", "directory", "to", "store", "cached", "items", "in", "for", "link", "." ]
def get_path_for_link(self, link): # type: (Link) -> str """Return a directory to store cached items in for link. """ raise NotImplementedError()
[ "def", "get_path_for_link", "(", "self", ",", "link", ")", ":", "# type: (Link) -> str", "raise", "NotImplementedError", "(", ")" ]
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/cache.py#L97-L101
phyllisstein/alp
cbc9e9fa2de19cfd72bc416b9c879b571dc92972
alp/request/requests/packages/charade/chardistribution.py
python
CharDistributionAnalysis.feed
(self, aBuf, aCharLen)
feed a character with known length
feed a character with known length
[ "feed", "a", "character", "with", "known", "length" ]
def feed(self, aBuf, aCharLen): """feed a character with known length""" if aCharLen == 2: # we only care about 2-bytes character in our distribution analysis order = self.get_order(aBuf) else: order = -1 if order >= 0: self._mTotalChars += 1 # order is valid if order < self._mTableSize: if 512 > self._mCharToFreqOrder[order]: self._mFreqChars += 1
[ "def", "feed", "(", "self", ",", "aBuf", ",", "aCharLen", ")", ":", "if", "aCharLen", "==", "2", ":", "# we only care about 2-bytes character in our distribution analysis", "order", "=", "self", ".", "get_order", "(", "aBuf", ")", "else", ":", "order", "=", "-...
https://github.com/phyllisstein/alp/blob/cbc9e9fa2de19cfd72bc416b9c879b571dc92972/alp/request/requests/packages/charade/chardistribution.py#L68-L80
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txweb2/http_headers.py
python
generatePrefer
(items)
return out
[]
def generatePrefer(items): key, value, args = items if value is None: out = '%s' % (key,) else: out = '%s=%s' % (key, value) if args: out += ';' + generateKeyValues(args) return out
[ "def", "generatePrefer", "(", "items", ")", ":", "key", ",", "value", ",", "args", "=", "items", "if", "value", "is", "None", ":", "out", "=", "'%s'", "%", "(", "key", ",", ")", "else", ":", "out", "=", "'%s=%s'", "%", "(", "key", ",", "value", ...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txweb2/http_headers.py#L983-L991
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/validators/slug.py
python
slug
(value)
return slug_regex.match(value)
Validate whether or not given value is valid slug. Valid slug can contain only alphanumeric characters, hyphens and underscores. Examples:: >>> slug('my.slug') ValidationFailure(func=slug, args={'value': 'my.slug'}) >>> slug('my-slug-2134') True .. versionadded:: 0.6 :param value: value to validate
Validate whether or not given value is valid slug.
[ "Validate", "whether", "or", "not", "given", "value", "is", "valid", "slug", "." ]
def slug(value): """ Validate whether or not given value is valid slug. Valid slug can contain only alphanumeric characters, hyphens and underscores. Examples:: >>> slug('my.slug') ValidationFailure(func=slug, args={'value': 'my.slug'}) >>> slug('my-slug-2134') True .. versionadded:: 0.6 :param value: value to validate """ return slug_regex.match(value)
[ "def", "slug", "(", "value", ")", ":", "return", "slug_regex", ".", "match", "(", "value", ")" ]
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/validators/slug.py#L9-L28
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/compiler/symbols.py
python
SymbolVisitor.visitAssign
(self, node, scope)
Propagate assignment flag down to child nodes. The Assign node doesn't itself contains the variables being assigned to. Instead, the children in node.nodes are visited with the assign flag set to true. When the names occur in those nodes, they are marked as defs. Some names that occur in an assignment target are not bound by the assignment, e.g. a name occurring inside a slice. The visitor handles these nodes specially; they do not propagate the assign flag to their children.
Propagate assignment flag down to child nodes.
[ "Propagate", "assignment", "flag", "down", "to", "child", "nodes", "." ]
def visitAssign(self, node, scope): """Propagate assignment flag down to child nodes. The Assign node doesn't itself contains the variables being assigned to. Instead, the children in node.nodes are visited with the assign flag set to true. When the names occur in those nodes, they are marked as defs. Some names that occur in an assignment target are not bound by the assignment, e.g. a name occurring inside a slice. The visitor handles these nodes specially; they do not propagate the assign flag to their children. """ for n in node.nodes: self.visit(n, scope, 1) self.visit(node.expr, scope)
[ "def", "visitAssign", "(", "self", ",", "node", ",", "scope", ")", ":", "for", "n", "in", "node", ".", "nodes", ":", "self", ".", "visit", "(", "n", ",", "scope", ",", "1", ")", "self", ".", "visit", "(", "node", ".", "expr", ",", "scope", ")" ...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/compiler/symbols.py#L347-L362