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
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/procedures/stubs/syscall_stub.py
python
syscall.run
(self, *args, resolves=None)
return self.state.solver.Unconstrained("syscall_stub_%s" % self.display_name, self.state.arch.bits, key=('syscall', '?', self.display_name))
[]
def run(self, *args, resolves=None): self.resolves = resolves # pylint:disable=attribute-defined-outside-init if self.successors is not None: self.successors.artifacts['resolves'] = resolves return self.state.solver.Unconstrained("syscall_stub_%s" % self.display_name, self.state....
[ "def", "run", "(", "self", ",", "*", "args", ",", "resolves", "=", "None", ")", ":", "self", ".", "resolves", "=", "resolves", "# pylint:disable=attribute-defined-outside-init", "if", "self", ".", "successors", "is", "not", "None", ":", "self", ".", "success...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/procedures/stubs/syscall_stub.py#L10-L17
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/reports/standard/sms.py
python
SMSOptOutReport.shared_pagination_GET_params
(self)
return []
[]
def shared_pagination_GET_params(self): return []
[ "def", "shared_pagination_GET_params", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/reports/standard/sms.py#L1142-L1143
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/clients/client.py
python
BotClient.post_initialise
(self)
[]
def post_initialise(self): bots = self.bot_factory.bots() for bot in bots: bot.post_initialise()
[ "def", "post_initialise", "(", "self", ")", ":", "bots", "=", "self", ".", "bot_factory", ".", "bots", "(", ")", "for", "bot", "in", "bots", ":", "bot", ".", "post_initialise", "(", ")" ]
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/clients/client.py#L88-L91
MalloyDelacroix/DownloaderForReddit
e2547a6d1f119b31642445e64cb21f4568ce4012
DownloaderForReddit/database/models.py
python
RedditObject.set_date_limit
(self, epoch)
Tests the supplied epoch time to see if it is newer than the already established absolute date limit, and if so sets the absolute date limit to the time of the supplied epoch. :param epoch: A datetime in epoch seconds that should be the time of an extracted submission.
Tests the supplied epoch time to see if it is newer than the already established absolute date limit, and if so sets the absolute date limit to the time of the supplied epoch. :param epoch: A datetime in epoch seconds that should be the time of an extracted submission.
[ "Tests", "the", "supplied", "epoch", "time", "to", "see", "if", "it", "is", "newer", "than", "the", "already", "established", "absolute", "date", "limit", "and", "if", "so", "sets", "the", "absolute", "date", "limit", "to", "the", "time", "of", "the", "s...
def set_date_limit(self, epoch): """ Tests the supplied epoch time to see if it is newer than the already established absolute date limit, and if so sets the absolute date limit to the time of the supplied epoch. :param epoch: A datetime in epoch seconds that should be the time of an ext...
[ "def", "set_date_limit", "(", "self", ",", "epoch", ")", ":", "date_limit_epoch", "=", "self", ".", "absolute_date_limit", ".", "timestamp", "(", ")", "if", "epoch", ">", "date_limit_epoch", ":", "self", ".", "absolute_date_limit", "=", "datetime", ".", "fromt...
https://github.com/MalloyDelacroix/DownloaderForReddit/blob/e2547a6d1f119b31642445e64cb21f4568ce4012/DownloaderForReddit/database/models.py#L374-L385
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/cbook/__init__.py
python
_setattr_cm
(obj, **kwargs)
Temporarily set some attributes; restore original state at context exit.
Temporarily set some attributes; restore original state at context exit.
[ "Temporarily", "set", "some", "attributes", ";", "restore", "original", "state", "at", "context", "exit", "." ]
def _setattr_cm(obj, **kwargs): """ Temporarily set some attributes; restore original state at context exit. """ sentinel = object() origs = {} for attr in kwargs: orig = getattr(obj, attr, sentinel) if attr in obj.__dict__ or orig is sentinel: # if we are pulling fro...
[ "def", "_setattr_cm", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "sentinel", "=", "object", "(", ")", "origs", "=", "{", "}", "for", "attr", "in", "kwargs", ":", "orig", "=", "getattr", "(", "obj", ",", "attr", ",", "sentinel", ")", "if", "at...
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/cbook/__init__.py#L2019-L2059
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/iotexplorer/v20190423/iotexplorer_client.py
python
IotexplorerClient.DeleteDevices
(self, request)
批量删除设备 :param request: Request instance for DeleteDevices. :type request: :class:`tencentcloud.iotexplorer.v20190423.models.DeleteDevicesRequest` :rtype: :class:`tencentcloud.iotexplorer.v20190423.models.DeleteDevicesResponse`
批量删除设备
[ "批量删除设备" ]
def DeleteDevices(self, request): """批量删除设备 :param request: Request instance for DeleteDevices. :type request: :class:`tencentcloud.iotexplorer.v20190423.models.DeleteDevicesRequest` :rtype: :class:`tencentcloud.iotexplorer.v20190423.models.DeleteDevicesResponse` """ tr...
[ "def", "DeleteDevices", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DeleteDevices\"", ",", "params", ")", "response", "=", "json", ".", "loads", "("...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/iotexplorer/v20190423/iotexplorer_client.py#L449-L474
gitpython-developers/GitPython
fac603789d66c0fd7c26e75debb41b06136c5026
git/util.py
python
assure_directory_exists
(path: PathLike, is_file: bool = False)
return False
Assure that the directory pointed to by path exists. :param is_file: If True, path is assumed to be a file and handled correctly. Otherwise it must be a directory :return: True if the directory was created, False if it already existed
Assure that the directory pointed to by path exists.
[ "Assure", "that", "the", "directory", "pointed", "to", "by", "path", "exists", "." ]
def assure_directory_exists(path: PathLike, is_file: bool = False) -> bool: """Assure that the directory pointed to by path exists. :param is_file: If True, path is assumed to be a file and handled correctly. Otherwise it must be a directory :return: True if the directory was created, False if it a...
[ "def", "assure_directory_exists", "(", "path", ":", "PathLike", ",", "is_file", ":", "bool", "=", "False", ")", "->", "bool", ":", "if", "is_file", ":", "path", "=", "osp", ".", "dirname", "(", "path", ")", "# END handle file", "if", "not", "osp", ".", ...
https://github.com/gitpython-developers/GitPython/blob/fac603789d66c0fd7c26e75debb41b06136c5026/git/util.py#L208-L220
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/lib/flask_cache/backends.py
python
gaememcached
(app, config, args, kwargs)
return GAEMemcachedCache(*args, **kwargs)
[]
def gaememcached(app, config, args, kwargs): kwargs.update(dict(key_prefix=config['CACHE_KEY_PREFIX'])) return GAEMemcachedCache(*args, **kwargs)
[ "def", "gaememcached", "(", "app", ",", "config", ",", "args", ",", "kwargs", ")", ":", "kwargs", ".", "update", "(", "dict", "(", "key_prefix", "=", "config", "[", "'CACHE_KEY_PREFIX'", "]", ")", ")", "return", "GAEMemcachedCache", "(", "*", "args", ","...
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/flask_cache/backends.py#L44-L46
getnikola/nikola
2da876e9322e42a93f8295f950e336465c6a4ee5
nikola/plugins/task/galleries.py
python
Galleries.create_galleries_paths
(self)
Given a list of galleries, put their paths into self.gallery_links.
Given a list of galleries, put their paths into self.gallery_links.
[ "Given", "a", "list", "of", "galleries", "put", "their", "paths", "into", "self", ".", "gallery_links", "." ]
def create_galleries_paths(self): """Given a list of galleries, put their paths into self.gallery_links.""" # gallery_path is "gallery/foo/name" self.proper_gallery_links = dict() self.improper_gallery_links = dict() for gallery_path, input_folder, output_folder in self.gallery_l...
[ "def", "create_galleries_paths", "(", "self", ")", ":", "# gallery_path is \"gallery/foo/name\"", "self", ".", "proper_gallery_links", "=", "dict", "(", ")", "self", ".", "improper_gallery_links", "=", "dict", "(", ")", "for", "gallery_path", ",", "input_folder", ",...
https://github.com/getnikola/nikola/blob/2da876e9322e42a93f8295f950e336465c6a4ee5/nikola/plugins/task/galleries.py#L387-L415
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/docutils/utils/math/math2html.py
python
ContainerSize.set
(self, width = None, height = None)
return self
Set the proper size with width and height.
Set the proper size with width and height.
[ "Set", "the", "proper", "size", "with", "width", "and", "height", "." ]
def set(self, width = None, height = None): "Set the proper size with width and height." self.setvalue('width', width) self.setvalue('height', height) return self
[ "def", "set", "(", "self", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "self", ".", "setvalue", "(", "'width'", ",", "width", ")", "self", ".", "setvalue", "(", "'height'", ",", "height", ")", "return", "self" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/docutils/utils/math/math2html.py#L3320-L3324
504ensicsLabs/DAMM
60e7ec7dacd6087cd6320b3615becca9b4cf9b24
volatility/plugins/registry/registryapi.py
python
RegistryApi.reset_current
(self)
this is in case we switch to a different hive/user/context
this is in case we switch to a different hive/user/context
[ "this", "is", "in", "case", "we", "switch", "to", "a", "different", "hive", "/", "user", "/", "context" ]
def reset_current(self): ''' this is in case we switch to a different hive/user/context ''' self.current_offsets = {}
[ "def", "reset_current", "(", "self", ")", ":", "self", ".", "current_offsets", "=", "{", "}" ]
https://github.com/504ensicsLabs/DAMM/blob/60e7ec7dacd6087cd6320b3615becca9b4cf9b24/volatility/plugins/registry/registryapi.py#L112-L116
ansible-community/molecule
be98c8db07666fd1125f69020419b67fda48b559
src/molecule/driver/base.py
python
Driver.ansible_connection_options
(self, instance_name)
Ansible specific connection options supplied to inventory and returns a \ dict. :param instance_name: A string containing the instance to login to. :returns: dict
Ansible specific connection options supplied to inventory and returns a \ dict.
[ "Ansible", "specific", "connection", "options", "supplied", "to", "inventory", "and", "returns", "a", "\\", "dict", "." ]
def ansible_connection_options(self, instance_name): # pragma: no cover """ Ansible specific connection options supplied to inventory and returns a \ dict. :param instance_name: A string containing the instance to login to. :returns: dict """
[ "def", "ansible_connection_options", "(", "self", ",", "instance_name", ")", ":", "# pragma: no cover" ]
https://github.com/ansible-community/molecule/blob/be98c8db07666fd1125f69020419b67fda48b559/src/molecule/driver/base.py#L115-L122
PokemonGoF/PokemonGo-Bot
5e80f20760f32478a84a8f0ced7ca24cdf41fe03
pokemongo_bot/cell_workers/recycle_items.py
python
RecycleItems.get_category_items_to_recycle
(self, category_inventory, category_count, category_max)
return items_to_recycle
Returns an array to be recycle within a category of items with the item id and item count. :param category_inventory: :param category_count: :param category_max: :return: array of items to be recycle. :rtype: array
Returns an array to be recycle within a category of items with the item id and item count. :param category_inventory: :param category_count: :param category_max: :return: array of items to be recycle. :rtype: array
[ "Returns", "an", "array", "to", "be", "recycle", "within", "a", "category", "of", "items", "with", "the", "item", "id", "and", "item", "count", ".", ":", "param", "category_inventory", ":", ":", "param", "category_count", ":", ":", "param", "category_max", ...
def get_category_items_to_recycle(self, category_inventory, category_count, category_max): """ Returns an array to be recycle within a category of items with the item id and item count. :param category_inventory: :param category_count: :param category_max: :return: array ...
[ "def", "get_category_items_to_recycle", "(", "self", ",", "category_inventory", ",", "category_count", ",", "category_max", ")", ":", "x", "=", "0", "items_to_recycle", "=", "[", "]", "if", "category_count", ">", "category_max", ":", "items_to_be_recycled", "=", "...
https://github.com/PokemonGoF/PokemonGo-Bot/blob/5e80f20760f32478a84a8f0ced7ca24cdf41fe03/pokemongo_bot/cell_workers/recycle_items.py#L230-L257
mne-tools/mne-python
f90b303ce66a8415e64edd4605b09ac0179c1ebf
mne/viz/_mpl_figure.py
python
MNEBrowseFigure._buttonpress
(self, event)
Handle mouse clicks.
Handle mouse clicks.
[ "Handle", "mouse", "clicks", "." ]
def _buttonpress(self, event): """Handle mouse clicks.""" butterfly = self.mne.butterfly annotating = self.mne.fig_annotation is not None ax_main = self.mne.ax_main inst = self.mne.inst # ignore middle clicks, scroll wheel events, and clicks outside axes if event....
[ "def", "_buttonpress", "(", "self", ",", "event", ")", ":", "butterfly", "=", "self", ".", "mne", ".", "butterfly", "annotating", "=", "self", ".", "mne", ".", "fig_annotation", "is", "not", "None", "ax_main", "=", "self", ".", "mne", ".", "ax_main", "...
https://github.com/mne-tools/mne-python/blob/f90b303ce66a8415e64edd4605b09ac0179c1ebf/mne/viz/_mpl_figure.py#L698-L754
tensorflow/privacy
867f3d4c5566b21433a6a1bed998094d1479b4d5
research/pate_2017/analysis.py
python
logmgf_exact
(q, priv_eps, l)
return min(0.5 * priv_eps * priv_eps * l * (l + 1), log_t, priv_eps * l)
Computes the logmgf value given q and privacy eps. The bound used is the min of three terms. The first term is from https://arxiv.org/pdf/1605.02065.pdf. The second term is based on the fact that when event has probability (1-q) for q close to zero, q can only change by exp(eps), which corresponds to a much ...
Computes the logmgf value given q and privacy eps.
[ "Computes", "the", "logmgf", "value", "given", "q", "and", "privacy", "eps", "." ]
def logmgf_exact(q, priv_eps, l): """Computes the logmgf value given q and privacy eps. The bound used is the min of three terms. The first term is from https://arxiv.org/pdf/1605.02065.pdf. The second term is based on the fact that when event has probability (1-q) for q close to zero, q can only change by e...
[ "def", "logmgf_exact", "(", "q", ",", "priv_eps", ",", "l", ")", ":", "if", "q", "<", "0.5", ":", "t_one", "=", "(", "1", "-", "q", ")", "*", "math", ".", "pow", "(", "(", "1", "-", "q", ")", "/", "(", "1", "-", "math", ".", "exp", "(", ...
https://github.com/tensorflow/privacy/blob/867f3d4c5566b21433a6a1bed998094d1479b4d5/research/pate_2017/analysis.py#L120-L148
odlgroup/odl
0b088df8dc4621c68b9414c3deff9127f4c4f11d
odl/set/space.py
python
LinearSpace.field
(self)
return self.__field
Scalar field of numbers for this vector space.
Scalar field of numbers for this vector space.
[ "Scalar", "field", "of", "numbers", "for", "this", "vector", "space", "." ]
def field(self): """Scalar field of numbers for this vector space.""" return self.__field
[ "def", "field", "(", "self", ")", ":", "return", "self", ".", "__field" ]
https://github.com/odlgroup/odl/blob/0b088df8dc4621c68b9414c3deff9127f4c4f11d/odl/set/space.py#L46-L48
numenta/nupic
b9ebedaf54f49a33de22d8d44dff7c765cdb5548
external/linux32/lib/python2.6/site-packages/pkg_resources.py
python
IMetadataProvider.get_metadata
(name)
The named metadata resource as a string
The named metadata resource as a string
[ "The", "named", "metadata", "resource", "as", "a", "string" ]
def get_metadata(name): """The named metadata resource as a string"""
[ "def", "get_metadata", "(", "name", ")", ":" ]
https://github.com/numenta/nupic/blob/b9ebedaf54f49a33de22d8d44dff7c765cdb5548/external/linux32/lib/python2.6/site-packages/pkg_resources.py#L293-L294
cogitas3d/OrtogOnBlender
881e93f5beb2263e44c270974dd0e81deca44762
OtherOnBlender.py
python
OTHER_PT_Cut_Points.draw
(self, context)
[]
def draw(self, context): layout = self.layout context = bpy.context obj = context.object scn = context.scene # row = layout.row() # row.label(text="Dimensions:") # Add Volume Area row = layout.row() linha=row.operator("wm.tool_set_by_id", text="Cur...
[ "def", "draw", "(", "self", ",", "context", ")", ":", "layout", "=", "self", ".", "layout", "context", "=", "bpy", ".", "context", "obj", "=", "context", ".", "object", "scn", "=", "context", ".", "scene", "# row = layout.row()", "# row.label(t...
https://github.com/cogitas3d/OrtogOnBlender/blob/881e93f5beb2263e44c270974dd0e81deca44762/OtherOnBlender.py#L257-L291
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/tarfile.py
python
TarFile.next
(self)
return tarinfo
Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available.
Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available.
[ "Return", "the", "next", "member", "of", "the", "archive", "as", "a", "TarInfo", "object", "when", "TarFile", "is", "opened", "for", "reading", ".", "Return", "None", "if", "there", "is", "no", "more", "available", "." ]
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firs...
[ "def", "next", "(", "self", ")", ":", "self", ".", "_check", "(", "\"ra\"", ")", "if", "self", ".", "firstmember", "is", "not", "None", ":", "m", "=", "self", ".", "firstmember", "self", ".", "firstmember", "=", "None", "return", "m", "# Advance the fi...
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/tarfile.py#L2262-L2311
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/ipython-4.0.0-py3.3.egg/IPython/core/interactiveshell.py
python
InteractiveShell.init_user_ns
(self)
Initialize all user-visible namespaces to their minimum defaults. Certain history lists are also initialized here, as they effectively act as user namespaces. Notes ----- All data structures here are only filled in, they are NOT reset by this method. If they were not e...
Initialize all user-visible namespaces to their minimum defaults.
[ "Initialize", "all", "user", "-", "visible", "namespaces", "to", "their", "minimum", "defaults", "." ]
def init_user_ns(self): """Initialize all user-visible namespaces to their minimum defaults. Certain history lists are also initialized here, as they effectively act as user namespaces. Notes ----- All data structures here are only filled in, they are NOT reset by this ...
[ "def", "init_user_ns", "(", "self", ")", ":", "# This function works in two parts: first we put a few things in", "# user_ns, and we sync that contents into user_ns_hidden so that these", "# initial variables aren't shown by %who. After the sync, we add the", "# rest of what we *do* want the user...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/ipython-4.0.0-py3.3.egg/IPython/core/interactiveshell.py#L1204-L1262
evhub/coconut
27a4af9dc06667870f736f20c862930001b8cbb2
coconut/convenience.py
python
CoconutStreamReader.decode
(cls, input_bytes, errors="strict")
return cls.compile_coconut(input_str), len_consumed
Decode and compile the given Coconut source bytes.
Decode and compile the given Coconut source bytes.
[ "Decode", "and", "compile", "the", "given", "Coconut", "source", "bytes", "." ]
def decode(cls, input_bytes, errors="strict"): """Decode and compile the given Coconut source bytes.""" input_str, len_consumed = super(CoconutStreamReader, cls).decode(input_bytes, errors) return cls.compile_coconut(input_str), len_consumed
[ "def", "decode", "(", "cls", ",", "input_bytes", ",", "errors", "=", "\"strict\"", ")", ":", "input_str", ",", "len_consumed", "=", "super", "(", "CoconutStreamReader", ",", "cls", ")", ".", "decode", "(", "input_bytes", ",", "errors", ")", "return", "cls"...
https://github.com/evhub/coconut/blob/27a4af9dc06667870f736f20c862930001b8cbb2/coconut/convenience.py#L214-L217
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/tornado/iostream.py
python
_StreamBuffer.__len__
(self)
return self._size
[]
def __len__(self) -> int: return self._size
[ "def", "__len__", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_size" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/tornado/iostream.py#L152-L153
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/dialects/oracle/base.py
python
OracleCompiler.returning_clause
(self, stmt, returning_cols)
return 'RETURNING ' + ', '.join(columns) + " INTO " + ", ".join(binds)
[]
def returning_clause(self, stmt, returning_cols): columns = [] binds = [] for i, column in enumerate( expression._select_iterables(returning_cols)): if column.type._has_column_expression: col_expr = column.type.column_expression(column) el...
[ "def", "returning_clause", "(", "self", ",", "stmt", ",", "returning_cols", ")", ":", "columns", "=", "[", "]", "binds", "=", "[", "]", "for", "i", ",", "column", "in", "enumerate", "(", "expression", ".", "_select_iterables", "(", "returning_cols", ")", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/dialects/oracle/base.py#L779-L805
BigBrotherBot/big-brother-bot
848823c71413c86e7f1ff9584f43e08d40a7f2c0
b3/parsers/ravaged/ravaged_rcon.py
python
RavagedServerPacketHandler.run
(self)
Threaded code.
Threaded code.
[ "Threaded", "code", "." ]
def run(self): """ Threaded code. """ self.log.info('start server packet handler loop') try: while not self.isStopped(): try: packet = self._received_packets.get(timeout=10) if packet is self.__stop_token: ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'start server packet handler loop'", ")", "try", ":", "while", "not", "self", ".", "isStopped", "(", ")", ":", "try", ":", "packet", "=", "self", ".", "_received_packets", ".", ...
https://github.com/BigBrotherBot/big-brother-bot/blob/848823c71413c86e7f1ff9584f43e08d40a7f2c0/b3/parsers/ravaged/ravaged_rcon.py#L245-L262
out0fmemory/GoAgent-Always-Available
c4254984fea633ce3d1893fe5901debd9f22c2a9
server/lib/google/appengine/api/memcache/__init__.py
python
Client.get_multi
(self, keys, key_prefix='', namespace=None, for_cas=False)
return rpc.get_result()
Looks up multiple keys from memcache in one operation. This is the recommended way to do bulk loads. Args: keys: List of keys to look up. Keys may be strings or tuples of (hash_value, string). Google App Engine does the sharding and hashing automatically, though, so the hash va...
Looks up multiple keys from memcache in one operation.
[ "Looks", "up", "multiple", "keys", "from", "memcache", "in", "one", "operation", "." ]
def get_multi(self, keys, key_prefix='', namespace=None, for_cas=False): """Looks up multiple keys from memcache in one operation. This is the recommended way to do bulk loads. Args: keys: List of keys to look up. Keys may be strings or tuples of (hash_value, string). Google App Engine ...
[ "def", "get_multi", "(", "self", ",", "keys", ",", "key_prefix", "=", "''", ",", "namespace", "=", "None", ",", "for_cas", "=", "False", ")", ":", "rpc", "=", "self", ".", "get_multi_async", "(", "keys", ",", "key_prefix", ",", "namespace", ",", "for_c...
https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/api/memcache/__init__.py#L567-L590
textX/Arpeggio
9ec6c7ee402054616b2f81e76557d39d3d376fcd
examples/csv/csv.py
python
CSVVisitor.visit_field
(self, node, children)
[]
def visit_field(self, node, children): value = children[0] try: return float(value) except: pass try: return int(value) except: return value
[ "def", "visit_field", "(", "self", ",", "node", ",", "children", ")", ":", "value", "=", "children", "[", "0", "]", "try", ":", "return", "float", "(", "value", ")", "except", ":", "pass", "try", ":", "return", "int", "(", "value", ")", "except", "...
https://github.com/textX/Arpeggio/blob/9ec6c7ee402054616b2f81e76557d39d3d376fcd/examples/csv/csv.py#L24-L33
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/scipy/integrate/_ode.py
python
_transform_banded_jac
(bjac)
return newjac
Convert a real matrix of the form (for example) [0 0 A B] [0 0 0 B] [0 0 C D] [0 0 A D] [E F G H] to [0 F C H] [I J K L] [E J G L] [I 0 K 0] That is, every other column is shifted up one.
Convert a real matrix of the form (for example)
[ "Convert", "a", "real", "matrix", "of", "the", "form", "(", "for", "example", ")" ]
def _transform_banded_jac(bjac): """ Convert a real matrix of the form (for example) [0 0 A B] [0 0 0 B] [0 0 C D] [0 0 A D] [E F G H] to [0 F C H] [I J K L] [E J G L] [I 0 K 0] That is, every other column is shifted up one....
[ "def", "_transform_banded_jac", "(", "bjac", ")", ":", "# Shift every other column.", "newjac", "=", "zeros", "(", "(", "bjac", ".", "shape", "[", "0", "]", "+", "1", ",", "bjac", ".", "shape", "[", "1", "]", ")", ")", "newjac", "[", "1", ":", ",", ...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/scipy/integrate/_ode.py#L456-L472
nltk/nltk
3f74ac55681667d7ef78b664557487145f51eb02
nltk/lm/counter.py
python
NgramCounter.N
(self)
return sum(val.N() for val in self._counts.values())
Returns grand total number of ngrams stored. This includes ngrams from all orders, so some duplication is expected. :rtype: int >>> from nltk.lm import NgramCounter >>> counts = NgramCounter([[("a", "b"), ("c",), ("d", "e")]]) >>> counts.N() 3
Returns grand total number of ngrams stored.
[ "Returns", "grand", "total", "number", "of", "ngrams", "stored", "." ]
def N(self): """Returns grand total number of ngrams stored. This includes ngrams from all orders, so some duplication is expected. :rtype: int >>> from nltk.lm import NgramCounter >>> counts = NgramCounter([[("a", "b"), ("c",), ("d", "e")]]) >>> counts.N() 3 ...
[ "def", "N", "(", "self", ")", ":", "return", "sum", "(", "val", ".", "N", "(", ")", "for", "val", "in", "self", ".", "_counts", ".", "values", "(", ")", ")" ]
https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/lm/counter.py#L130-L142
tkipf/relational-gcn
4bec1341dd46b72bf482f7ed26c2dca4533577f6
rgcn/utils.py
python
bfs_sample
(adj, roots, max_lvl_size)
BFS with node dropout. Only keeps random subset of nodes per level up to max_lvl_size. 'roots' should be a mini-batch of nodes (set of node indices). NOTE: In this implementation, not every node in the mini-batch is guaranteed to have the same number of neighbors, as we're sampling for the whole batch at t...
BFS with node dropout. Only keeps random subset of nodes per level up to max_lvl_size. 'roots' should be a mini-batch of nodes (set of node indices).
[ "BFS", "with", "node", "dropout", ".", "Only", "keeps", "random", "subset", "of", "nodes", "per", "level", "up", "to", "max_lvl_size", ".", "roots", "should", "be", "a", "mini", "-", "batch", "of", "nodes", "(", "set", "of", "node", "indices", ")", "."...
def bfs_sample(adj, roots, max_lvl_size): """ BFS with node dropout. Only keeps random subset of nodes per level up to max_lvl_size. 'roots' should be a mini-batch of nodes (set of node indices). NOTE: In this implementation, not every node in the mini-batch is guaranteed to have the same number of...
[ "def", "bfs_sample", "(", "adj", ",", "roots", ",", "max_lvl_size", ")", ":", "visited", "=", "set", "(", "roots", ")", "current_lvl", "=", "set", "(", "roots", ")", "while", "current_lvl", ":", "next_lvl", "=", "get_neighbors", "(", "adj", ",", "current...
https://github.com/tkipf/relational-gcn/blob/4bec1341dd46b72bf482f7ed26c2dca4533577f6/rgcn/utils.py#L112-L132
asappresearch/flambe
98f10f859fe9223fd2d1d76d430f77cdbddc0956
flambe/experiment/utils.py
python
extract_dict
(config: Mapping[str, Any])
return helper(config)
Turn the schema into a dictionary, ignoring types. NOTE: We recurse if any value is itself a `Schema`, a `Sequence` of `Schema`s, or a `Mapping` of `Schema`s. Other unconvential collections will not be inspected. Parameters ---------- schema: Schema The object to be converted into a di...
Turn the schema into a dictionary, ignoring types.
[ "Turn", "the", "schema", "into", "a", "dictionary", "ignoring", "types", "." ]
def extract_dict(config: Mapping[str, Any]) -> Dict[str, Any]: """Turn the schema into a dictionary, ignoring types. NOTE: We recurse if any value is itself a `Schema`, a `Sequence` of `Schema`s, or a `Mapping` of `Schema`s. Other unconvential collections will not be inspected. Parameters ----...
[ "def", "extract_dict", "(", "config", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "def", "helper", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "Schema", ")", ":", "out", "=", ...
https://github.com/asappresearch/flambe/blob/98f10f859fe9223fd2d1d76d430f77cdbddc0956/flambe/experiment/utils.py#L336-L374
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/http/server.py
python
BaseHTTPRequestHandler.date_time_string
(self, timestamp=None)
return email.utils.formatdate(timestamp, usegmt=True)
Return the current date and time formatted for a message header.
Return the current date and time formatted for a message header.
[ "Return", "the", "current", "date", "and", "time", "formatted", "for", "a", "message", "header", "." ]
def date_time_string(self, timestamp=None): """Return the current date and time formatted for a message header.""" if timestamp is None: timestamp = time.time() return email.utils.formatdate(timestamp, usegmt=True)
[ "def", "date_time_string", "(", "self", ",", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "time", ".", "time", "(", ")", "return", "email", ".", "utils", ".", "formatdate", "(", "timestamp", ",", "usegmt", ...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/http/server.py#L578-L582
splunk/splunk-sdk-python
ef88e9d3e90ab9d6cf48cf940c7376400ed759b8
examples/twitted/twitted/bin/tophashtags.py
python
output_results
(results, mvdelim = '\n', output = sys.stdout)
Given a list of dictionaries, each representing a single result, and an optional list of fields, output those results to stdout for consumption by the Splunk pipeline
Given a list of dictionaries, each representing a single result, and an optional list of fields, output those results to stdout for consumption by the Splunk pipeline
[ "Given", "a", "list", "of", "dictionaries", "each", "representing", "a", "single", "result", "and", "an", "optional", "list", "of", "fields", "output", "those", "results", "to", "stdout", "for", "consumption", "by", "the", "Splunk", "pipeline" ]
def output_results(results, mvdelim = '\n', output = sys.stdout): """Given a list of dictionaries, each representing a single result, and an optional list of fields, output those results to stdout for consumption by the Splunk pipeline""" # We collect all the unique field names, as well as # c...
[ "def", "output_results", "(", "results", ",", "mvdelim", "=", "'\\n'", ",", "output", "=", "sys", ".", "stdout", ")", ":", "# We collect all the unique field names, as well as ", "# convert all multivalue keys to the right form", "fields", "=", "set", "(", ")", "for", ...
https://github.com/splunk/splunk-sdk-python/blob/ef88e9d3e90ab9d6cf48cf940c7376400ed759b8/examples/twitted/twitted/bin/tophashtags.py#L85-L109
omnilib/aiomultiprocess
3daaa8a22e129dec4298b2d3e4ff6fea742a8f3c
aiomultiprocess/pool.py
python
PoolWorker.run
(self)
Pick up work, execute work, return results, rinse, repeat.
Pick up work, execute work, return results, rinse, repeat.
[ "Pick", "up", "work", "execute", "work", "return", "results", "rinse", "repeat", "." ]
async def run(self) -> None: """Pick up work, execute work, return results, rinse, repeat.""" pending: Dict[asyncio.Future, TaskID] = {} completed = 0 running = True while running or pending: # TTL, Tasks To Live, determines how many tasks to execute before dying ...
[ "async", "def", "run", "(", "self", ")", "->", "None", ":", "pending", ":", "Dict", "[", "asyncio", ".", "Future", ",", "TaskID", "]", "=", "{", "}", "completed", "=", "0", "running", "=", "True", "while", "running", "or", "pending", ":", "# TTL, Tas...
https://github.com/omnilib/aiomultiprocess/blob/3daaa8a22e129dec4298b2d3e4ff6fea742a8f3c/aiomultiprocess/pool.py#L71-L118
lad1337/XDM
0c1b7009fe00f06f102a6f67c793478f515e7efe
site-packages/cherrypy/lib/encoding.py
python
ResponseEncoder.encode_stream
(self, encoding)
return True
Encode a streaming response body. Use a generator wrapper, and just pray it works as the stream is being written out.
Encode a streaming response body. Use a generator wrapper, and just pray it works as the stream is being written out.
[ "Encode", "a", "streaming", "response", "body", ".", "Use", "a", "generator", "wrapper", "and", "just", "pray", "it", "works", "as", "the", "stream", "is", "being", "written", "out", "." ]
def encode_stream(self, encoding): """Encode a streaming response body. Use a generator wrapper, and just pray it works as the stream is being written out. """ if encoding in self.attempted_charsets: return False self.attempted_charsets.add(encoding) ...
[ "def", "encode_stream", "(", "self", ",", "encoding", ")", ":", "if", "encoding", "in", "self", ".", "attempted_charsets", ":", "return", "False", "self", ".", "attempted_charsets", ".", "add", "(", "encoding", ")", "def", "encoder", "(", "body", ")", ":",...
https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/cherrypy/lib/encoding.py#L60-L76
w3h/isf
6faf0a3df185465ec17369c90ccc16e2a03a1870
lib/thirdparty/pyreadline/rlmain.py
python
BaseReadline.read_history_file
(self, filename=None)
Load a readline history file. The default filename is ~/.history.
Load a readline history file. The default filename is ~/.history.
[ "Load", "a", "readline", "history", "file", ".", "The", "default", "filename", "is", "~", "/", ".", "history", "." ]
def read_history_file(self, filename=None): '''Load a readline history file. The default filename is ~/.history.''' if filename is None: filename = self.mode._history.history_filename log("read_history_file from %s"%ensure_unicode(filename)) self.mode._history.read_history_f...
[ "def", "read_history_file", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "mode", ".", "_history", ".", "history_filename", "log", "(", "\"read_history_file from %s\"", "%", "ensure_unic...
https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/pyreadline/rlmain.py#L160-L165
aliyun/aliyun-openapi-python-sdk
bda53176cc9cf07605b1cf769f0df444cca626a0
aliyun-python-sdk-core/aliyunsdkcore/vendored/requests/models.py
python
Response.__bool__
(self)
return self.ok
Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see i...
Returns True if :attr:`status_code` is less than 400.
[ "Returns", "True", "if", ":", "attr", ":", "status_code", "is", "less", "than", "400", "." ]
def __bool__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This ...
[ "def", "__bool__", "(", "self", ")", ":", "return", "self", ".", "ok" ]
https://github.com/aliyun/aliyun-openapi-python-sdk/blob/bda53176cc9cf07605b1cf769f0df444cca626a0/aliyun-python-sdk-core/aliyunsdkcore/vendored/requests/models.py#L663-L671
thaines/helit
04bd36ee0fb6b762c63d746e2cd8813641dceda9
dhdp/params.py
python
Params.__init__
(self, toClone = None)
Sets the parameters to reasonable defaults. Will act as a copy constructor if given an instance of this object.
Sets the parameters to reasonable defaults. Will act as a copy constructor if given an instance of this object.
[ "Sets", "the", "parameters", "to", "reasonable", "defaults", ".", "Will", "act", "as", "a", "copy", "constructor", "if", "given", "an", "instance", "of", "this", "object", "." ]
def __init__(self, toClone = None): """Sets the parameters to reasonable defaults. Will act as a copy constructor if given an instance of this object.""" if toClone!=None: self.__runs = toClone.runs self.__samples = toClone.samples self.__burnIn = toClone.burnIn self.__lag = toClone.lag ...
[ "def", "__init__", "(", "self", ",", "toClone", "=", "None", ")", ":", "if", "toClone", "!=", "None", ":", "self", ".", "__runs", "=", "toClone", ".", "runs", "self", ".", "__samples", "=", "toClone", ".", "samples", "self", ".", "__burnIn", "=", "to...
https://github.com/thaines/helit/blob/04bd36ee0fb6b762c63d746e2cd8813641dceda9/dhdp/params.py#L13-L24
googleapis/google-auth-library-python
87cd2455aca96ac3fbc4a8b2f8e4c0bba568a70b
google/oauth2/credentials.py
python
Credentials.__getstate__
(self)
return state_dict
A __getstate__ method must exist for the __setstate__ to be called This is identical to the default implementation. See https://docs.python.org/3.7/library/pickle.html#object.__setstate__
A __getstate__ method must exist for the __setstate__ to be called This is identical to the default implementation. See https://docs.python.org/3.7/library/pickle.html#object.__setstate__
[ "A", "__getstate__", "method", "must", "exist", "for", "the", "__setstate__", "to", "be", "called", "This", "is", "identical", "to", "the", "default", "implementation", ".", "See", "https", ":", "//", "docs", ".", "python", ".", "org", "/", "3", ".", "7"...
def __getstate__(self): """A __getstate__ method must exist for the __setstate__ to be called This is identical to the default implementation. See https://docs.python.org/3.7/library/pickle.html#object.__setstate__ """ state_dict = self.__dict__.copy() # Remove _refresh_h...
[ "def", "__getstate__", "(", "self", ")", ":", "state_dict", "=", "self", ".", "__dict__", ".", "copy", "(", ")", "# Remove _refresh_handler function as there are limitations pickling and", "# unpickling certain callables (lambda, functools.partial instances)", "# because they need ...
https://github.com/googleapis/google-auth-library-python/blob/87cd2455aca96ac3fbc4a8b2f8e4c0bba568a70b/google/oauth2/credentials.py#L136-L147
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/webapp2-2.5.1/webapp2_extras/i18n.py
python
format_datetime
(datetime=None, format=None, rebase=True)
return get_i18n().format_datetime(datetime, format, rebase)
See :meth:`I18n.format_datetime`.
See :meth:`I18n.format_datetime`.
[ "See", ":", "meth", ":", "I18n", ".", "format_datetime", "." ]
def format_datetime(datetime=None, format=None, rebase=True): """See :meth:`I18n.format_datetime`.""" return get_i18n().format_datetime(datetime, format, rebase)
[ "def", "format_datetime", "(", "datetime", "=", "None", ",", "format", "=", "None", ",", "rebase", "=", "True", ")", ":", "return", "get_i18n", "(", ")", ".", "format_datetime", "(", "datetime", ",", "format", ",", "rebase", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/webapp2-2.5.1/webapp2_extras/i18n.py#L736-L738
urwid/urwid
e2423b5069f51d318ea1ac0f355a0efe5448f7eb
urwid/graphics.py
python
BigText.set_text
(self, markup)
[]
def set_text(self, markup): self.text, self.attrib = decompose_tagmarkup(markup) self._invalidate()
[ "def", "set_text", "(", "self", ",", "markup", ")", ":", "self", ".", "text", ",", "self", ".", "attrib", "=", "decompose_tagmarkup", "(", "markup", ")", "self", ".", "_invalidate", "(", ")" ]
https://github.com/urwid/urwid/blob/e2423b5069f51d318ea1ac0f355a0efe5448f7eb/urwid/graphics.py#L48-L50
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
kube_dns/datadog_checks/kube_dns/kube_dns.py
python
KubeDNSCheck._create_kube_dns_instance
(self, instance)
return kube_dns_instance
Set up kube_dns instance so it can be used in OpenMetricsBaseCheck
Set up kube_dns instance so it can be used in OpenMetricsBaseCheck
[ "Set", "up", "kube_dns", "instance", "so", "it", "can", "be", "used", "in", "OpenMetricsBaseCheck" ]
def _create_kube_dns_instance(self, instance): """ Set up kube_dns instance so it can be used in OpenMetricsBaseCheck """ kube_dns_instance = deepcopy(instance) # kube_dns uses 'prometheus_endpoint' and not 'prometheus_url', so we have to rename the key kube_dns_instance...
[ "def", "_create_kube_dns_instance", "(", "self", ",", "instance", ")", ":", "kube_dns_instance", "=", "deepcopy", "(", "instance", ")", "# kube_dns uses 'prometheus_endpoint' and not 'prometheus_url', so we have to rename the key", "kube_dns_instance", "[", "'prometheus_url'", "]...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/kube_dns/datadog_checks/kube_dns/kube_dns.py#L56-L86
citronneur/rdpy
cef16a9f64d836a3221a344ca7d571644280d829
rdpy/protocol/rdp/rdp.py
python
RDPClientController.addClientObserver
(self, observer)
@summary: Add observer to RDP protocol @param observer: new observer to add
[]
def addClientObserver(self, observer): """ @summary: Add observer to RDP protocol @param observer: new observer to add """ self._clientObserver.append(observer)
[ "def", "addClientObserver", "(", "self", ",", "observer", ")", ":", "self", ".", "_clientObserver", ".", "append", "(", "observer", ")" ]
https://github.com/citronneur/rdpy/blob/cef16a9f64d836a3221a344ca7d571644280d829/rdpy/protocol/rdp/rdp.py#L166-L171
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/email/_header_value_parser.py
python
get_address
(value)
return address, value
address = mailbox / group Note that counter-intuitively, an address can be either a single address or a list of addresses (a group). This is why the returned Address object has a 'mailboxes' attribute which treats a single address as a list of length one. When you need to differentiate between to two...
address = mailbox / group
[ "address", "=", "mailbox", "/", "group" ]
def get_address(value): """ address = mailbox / group Note that counter-intuitively, an address can be either a single address or a list of addresses (a group). This is why the returned Address object has a 'mailboxes' attribute which treats a single address as a list of length one. When you need...
[ "def", "get_address", "(", "value", ")", ":", "# The formal grammar isn't very helpful when parsing an address. mailbox", "# and group, especially when allowing for obsolete forms, start off very", "# similarly. It is only when you reach one of @, <, or : that you know", "# what you've got. So,...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/email/_header_value_parser.py#L1946-L1973
Sujit-O/pykg2vec
492807b627574f95b0db9e7cb9f090c3c45a030a
pykg2vec/models/pairwise.py
python
TransD.forward
(self, h, r, t)
return torch.norm(norm_h_e + norm_r_e - norm_t_e, p=2, dim=-1)
Function to get the embedding value. Args: h (Tensor): Head entities ids. r (Tensor): Relation ids. t (Tensor): Tail entity ids. Returns: Tensors: the scores of evaluationReturns head, relation and tail embedding Tensors.
Function to get the embedding value.
[ "Function", "to", "get", "the", "embedding", "value", "." ]
def forward(self, h, r, t): """Function to get the embedding value. Args: h (Tensor): Head entities ids. r (Tensor): Relation ids. t (Tensor): Tail entity ids. Returns: Tensors: the scores of evaluationReturns head, relation a...
[ "def", "forward", "(", "self", ",", "h", ",", "r", ",", "t", ")", ":", "h_e", ",", "r_e", ",", "t_e", "=", "self", ".", "embed", "(", "h", ",", "r", ",", "t", ")", "norm_h_e", "=", "F", ".", "normalize", "(", "h_e", ",", "p", "=", "2", ",...
https://github.com/Sujit-O/pykg2vec/blob/492807b627574f95b0db9e7cb9f090c3c45a030a/pykg2vec/models/pairwise.py#L253-L273
mitogen-hq/mitogen
5b505f524a7ae170fe68613841ab92b299613d3f
mitogen/master.py
python
Router.get_stats
(self)
return { 'get_module_count': self.responder.get_module_count, 'get_module_secs': self.responder.get_module_secs, 'good_load_module_count': self.responder.good_load_module_count, 'good_load_module_size': self.responder.good_load_module_size, 'bad_load_module_co...
Return performance data for the module responder. :returns: Dict containing keys: * `get_module_count`: Integer count of :data:`mitogen.core.GET_MODULE` messages received. * `get_module_secs`: Floating point total seconds spent servicing :data:`...
Return performance data for the module responder.
[ "Return", "performance", "data", "for", "the", "module", "responder", "." ]
def get_stats(self): """ Return performance data for the module responder. :returns: Dict containing keys: * `get_module_count`: Integer count of :data:`mitogen.core.GET_MODULE` messages received. * `get_module_secs`: Floating point total seco...
[ "def", "get_stats", "(", "self", ")", ":", "return", "{", "'get_module_count'", ":", "self", ".", "responder", ".", "get_module_count", ",", "'get_module_secs'", ":", "self", ".", "responder", ".", "get_module_secs", ",", "'good_load_module_count'", ":", "self", ...
https://github.com/mitogen-hq/mitogen/blob/5b505f524a7ae170fe68613841ab92b299613d3f/mitogen/master.py#L1266-L1294
XiaohangZhan/deocclusion
ac543f9a54f4cb8baf0774bdb5f8638eadf8b57c
demos/GCAMatting/trainer.py
python
Trainer.save_model
(self, checkpoint_name, iter, loss)
Restore the trained generator and discriminator.
Restore the trained generator and discriminator.
[ "Restore", "the", "trained", "generator", "and", "discriminator", "." ]
def save_model(self, checkpoint_name, iter, loss): """Restore the trained generator and discriminator.""" torch.save({ 'iter': iter, 'loss': loss, 'state_dict': self.G.state_dict(), 'opt_state_dict': self.G_optimizer.state_dict(), 'lr_state_dic...
[ "def", "save_model", "(", "self", ",", "checkpoint_name", ",", "iter", ",", "loss", ")", ":", "torch", ".", "save", "(", "{", "'iter'", ":", "iter", ",", "'loss'", ":", "loss", ",", "'state_dict'", ":", "self", ".", "G", ".", "state_dict", "(", ")", ...
https://github.com/XiaohangZhan/deocclusion/blob/ac543f9a54f4cb8baf0774bdb5f8638eadf8b57c/demos/GCAMatting/trainer.py#L375-L383
zjhuang22/maskscoring_rcnn
0e8fae677b8ab987e4cdd3e894f17c25410388d8
maskrcnn_benchmark/modeling/roi_heads/box_head/loss.py
python
FastRCNNLossComputation.subsample
(self, proposals, targets)
return proposals
This method performs the positive/negative sampling, and return the sampled proposals. Note: this function keeps a state. Arguments: proposals (list[BoxList]) targets (list[BoxList])
This method performs the positive/negative sampling, and return the sampled proposals. Note: this function keeps a state.
[ "This", "method", "performs", "the", "positive", "/", "negative", "sampling", "and", "return", "the", "sampled", "proposals", ".", "Note", ":", "this", "function", "keeps", "a", "state", "." ]
def subsample(self, proposals, targets): """ This method performs the positive/negative sampling, and return the sampled proposals. Note: this function keeps a state. Arguments: proposals (list[BoxList]) targets (list[BoxList]) """ labels...
[ "def", "subsample", "(", "self", ",", "proposals", ",", "targets", ")", ":", "labels", ",", "regression_targets", "=", "self", ".", "prepare_targets", "(", "proposals", ",", "targets", ")", "sampled_pos_inds", ",", "sampled_neg_inds", "=", "self", ".", "fg_bg_...
https://github.com/zjhuang22/maskscoring_rcnn/blob/0e8fae677b8ab987e4cdd3e894f17c25410388d8/maskrcnn_benchmark/modeling/roi_heads/box_head/loss.py#L75-L109
google/flax
89e1126cc43588c6946bc85506987dc812909575
flax/linen/pooling.py
python
min_pool
(inputs, window_shape, strides=None, padding="VALID")
return pool(inputs, jnp.inf, lax.min, window_shape, strides, padding)
Pools the input by taking the minimum of a window slice. Args: inputs: Input data with dimensions (batch, window dims..., features). window_shape: A shape tuple defining the window to reduce over. strides: A sequence of `n` integers, representing the inter-window strides (default: `(1, ..., 1)`)....
Pools the input by taking the minimum of a window slice.
[ "Pools", "the", "input", "by", "taking", "the", "minimum", "of", "a", "window", "slice", "." ]
def min_pool(inputs, window_shape, strides=None, padding="VALID"): """Pools the input by taking the minimum of a window slice. Args: inputs: Input data with dimensions (batch, window dims..., features). window_shape: A shape tuple defining the window to reduce over. strides: A sequence of `n` integers,...
[ "def", "min_pool", "(", "inputs", ",", "window_shape", ",", "strides", "=", "None", ",", "padding", "=", "\"VALID\"", ")", ":", "return", "pool", "(", "inputs", ",", "jnp", ".", "inf", ",", "lax", ".", "min", ",", "window_shape", ",", "strides", ",", ...
https://github.com/google/flax/blob/89e1126cc43588c6946bc85506987dc812909575/flax/linen/pooling.py#L109-L124
indico/indico
1579ea16235bbe5f22a308b79c5902c85374721f
indico/modules/events/controllers/display.py
python
RHDisplayEvent._display_conference_page
(self)
return WPPage.render_template('page.html', self.event, page=self.event.default_page)
Display the custom conference home page.
Display the custom conference home page.
[ "Display", "the", "custom", "conference", "home", "page", "." ]
def _display_conference_page(self): """Display the custom conference home page.""" return WPPage.render_template('page.html', self.event, page=self.event.default_page)
[ "def", "_display_conference_page", "(", "self", ")", ":", "return", "WPPage", ".", "render_template", "(", "'page.html'", ",", "self", ".", "event", ",", "page", "=", "self", ".", "event", ".", "default_page", ")" ]
https://github.com/indico/indico/blob/1579ea16235bbe5f22a308b79c5902c85374721f/indico/modules/events/controllers/display.py#L64-L66
petterobam/learn-scrapy
e216ac40ddf5f8c595f170b2f79f7f86b686089c
DBTools/MyES.py
python
MyESClient.indexData
(self, data, id=None)
return res
单条数据添加 :param data: :return:
单条数据添加 :param data: :return:
[ "单条数据添加", ":", "param", "data", ":", ":", "return", ":" ]
def indexData(self, data, id=None): ''' 单条数据添加 :param data: :return: ''' res = self.es.index(index=self.index_name, doc_type=self.index_type, body=data, id=id) if self.show_es_result: print(res) return res
[ "def", "indexData", "(", "self", ",", "data", ",", "id", "=", "None", ")", ":", "res", "=", "self", ".", "es", ".", "index", "(", "index", "=", "self", ".", "index_name", ",", "doc_type", "=", "self", ".", "index_type", ",", "body", "=", "data", ...
https://github.com/petterobam/learn-scrapy/blob/e216ac40ddf5f8c595f170b2f79f7f86b686089c/DBTools/MyES.py#L99-L108
FSecureLABS/drozer
df11e6e63fbaefa9b58ed1e42533ddf76241d7e1
src/drozer/ssl/provider.py
python
Provider.__certificate_path
(self, cn, skip_default=False)
return os.path.join(self.ca_path(skip_default), "%s.crt" % cn)
Get the path to a certificate file.
Get the path to a certificate file.
[ "Get", "the", "path", "to", "a", "certificate", "file", "." ]
def __certificate_path(self, cn, skip_default=False): """ Get the path to a certificate file. """ return os.path.join(self.ca_path(skip_default), "%s.crt" % cn)
[ "def", "__certificate_path", "(", "self", ",", "cn", ",", "skip_default", "=", "False", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "ca_path", "(", "skip_default", ")", ",", "\"%s.crt\"", "%", "cn", ")" ]
https://github.com/FSecureLABS/drozer/blob/df11e6e63fbaefa9b58ed1e42533ddf76241d7e1/src/drozer/ssl/provider.py#L278-L283
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
pyrevitlib/pyrevit/versionmgr/__init__.py
python
_PyRevitVersion.as_int_tuple
(self)
return ver_tuple
Returns version as an int tuple (major, minor, patch)
Returns version as an int tuple (major, minor, patch)
[ "Returns", "version", "as", "an", "int", "tuple", "(", "major", "minor", "patch", ")" ]
def as_int_tuple(self): """Returns version as an int tuple (major, minor, patch)""" try: signature = int(self.patch, 16) except Exception: signature = 0 ver_tuple = (_PyRevitVersion.major, _PyRevitVersion.minor, signature) return ver_tuple
[ "def", "as_int_tuple", "(", "self", ")", ":", "try", ":", "signature", "=", "int", "(", "self", ".", "patch", ",", "16", ")", "except", "Exception", ":", "signature", "=", "0", "ver_tuple", "=", "(", "_PyRevitVersion", ".", "major", ",", "_PyRevitVersion...
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/pyrevitlib/pyrevit/versionmgr/__init__.py#L40-L48
google/timesketch
1ce6b60e125d104e6644947c6f1dbe1b82ac76b6
timesketch/api/v1/resources/__init__.py
python
ResourceMixin.datastore
(self)
return OpenSearchDataStore( host=current_app.config['OPENSEARCH_HOST'], port=current_app.config['OPENSEARCH_PORT'])
Property to get an instance of the datastore backend. Returns: Instance of lib.datastores.opensearch.OpenSearchDatastore
Property to get an instance of the datastore backend.
[ "Property", "to", "get", "an", "instance", "of", "the", "datastore", "backend", "." ]
def datastore(self): """Property to get an instance of the datastore backend. Returns: Instance of lib.datastores.opensearch.OpenSearchDatastore """ return OpenSearchDataStore( host=current_app.config['OPENSEARCH_HOST'], port=current_app.config['OPENS...
[ "def", "datastore", "(", "self", ")", ":", "return", "OpenSearchDataStore", "(", "host", "=", "current_app", ".", "config", "[", "'OPENSEARCH_HOST'", "]", ",", "port", "=", "current_app", ".", "config", "[", "'OPENSEARCH_PORT'", "]", ")" ]
https://github.com/google/timesketch/blob/1ce6b60e125d104e6644947c6f1dbe1b82ac76b6/timesketch/api/v1/resources/__init__.py#L250-L258
jindongwang/transferlearning
74a8914eed52c6f0759f39c0239d7e8b5baa6245
code/feature_extractor/for_image_data/main.py
python
classify_1nn
(data_train, data_test)
return ypred, acc
Classification using 1NN Inputs: data_train, data_test: train and test csv file path Outputs: yprediction and accuracy
Classification using 1NN Inputs: data_train, data_test: train and test csv file path Outputs: yprediction and accuracy
[ "Classification", "using", "1NN", "Inputs", ":", "data_train", "data_test", ":", "train", "and", "test", "csv", "file", "path", "Outputs", ":", "yprediction", "and", "accuracy" ]
def classify_1nn(data_train, data_test): ''' Classification using 1NN Inputs: data_train, data_test: train and test csv file path Outputs: yprediction and accuracy ''' from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score from sklearn.preprocessing...
[ "def", "classify_1nn", "(", "data_train", ",", "data_test", ")", ":", "from", "sklearn", ".", "neighbors", "import", "KNeighborsClassifier", "from", "sklearn", ".", "metrics", "import", "accuracy_score", "from", "sklearn", ".", "preprocessing", "import", "StandardSc...
https://github.com/jindongwang/transferlearning/blob/74a8914eed52c6f0759f39c0239d7e8b5baa6245/code/feature_extractor/for_image_data/main.py#L173-L194
proycon/pynlpl
7707f69a91caaa6cde037f0d0379f1d42500a68b
pynlpl/formats/folia.py
python
makeelement
(E, tagname, **kwargs)
Internal function
Internal function
[ "Internal", "function" ]
def makeelement(E, tagname, **kwargs): """Internal function""" if sys.version < '3': try: kwargs2 = {} for k,v in kwargs.items(): kwargs2[k.encode('utf-8')] = v.encode('utf-8') #return E._makeelement(tagname.encode('utf-8'), **{ k.encode('utf-8'): ...
[ "def", "makeelement", "(", "E", ",", "tagname", ",", "*", "*", "kwargs", ")", ":", "if", "sys", ".", "version", "<", "'3'", ":", "try", ":", "kwargs2", "=", "{", "}", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "kwargs2",...
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L569-L591
TabbycatDebate/tabbycat
7cc3b2fa1cc34569501a4be10fe9234b98c65df3
tabbycat/results/result.py
python
BaseDebateResult.load_from_db
(self)
Populates the buffer from the database. Subclasses should extend this method as necessary.
Populates the buffer from the database. Subclasses should extend this method as necessary.
[ "Populates", "the", "buffer", "from", "the", "database", ".", "Subclasses", "should", "extend", "this", "method", "as", "necessary", "." ]
def load_from_db(self): """Populates the buffer from the database. Subclasses should extend this method as necessary.""" self.load_debateteams() self.load_scoresheets()
[ "def", "load_from_db", "(", "self", ")", ":", "self", ".", "load_debateteams", "(", ")", "self", ".", "load_scoresheets", "(", ")" ]
https://github.com/TabbycatDebate/tabbycat/blob/7cc3b2fa1cc34569501a4be10fe9234b98c65df3/tabbycat/results/result.py#L238-L242
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/core/leoDebugger.py
python
get_gnx_from_file
(file_s, p, path)
return False
Set p's gnx from the @file node in the derived file.
Set p's gnx from the
[ "Set", "p", "s", "gnx", "from", "the" ]
def get_gnx_from_file(file_s, p, path): """Set p's gnx from the @file node in the derived file.""" pat = re.compile(r'^#@\+node:(.*): \*+ @file (.+)$') for line in g.splitLines(file_s): m = pat.match(line) if m: gnx, path2 = m.group(1), m.group(2) path2 = path2.replac...
[ "def", "get_gnx_from_file", "(", "file_s", ",", "p", ",", "path", ")", ":", "pat", "=", "re", ".", "compile", "(", "r'^#@\\+node:(.*): \\*+ @file (.+)$'", ")", "for", "line", "in", "g", ".", "splitLines", "(", "file_s", ")", ":", "m", "=", "pat", ".", ...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/core/leoDebugger.py#L363-L376
Epistimio/orion
732e739d99561020dbe620760acf062ade746006
src/orion/core/cli/serve.py
python
GunicornApp.load
(self)
return self.application
Load the WSGI application
Load the WSGI application
[ "Load", "the", "WSGI", "application" ]
def load(self): """Load the WSGI application""" return self.application
[ "def", "load", "(", "self", ")", ":", "return", "self", ".", "application" ]
https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/core/cli/serve.py#L66-L68
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/urllib3/util/ssltransport.py
python
SSLTransport.unwrap
(self)
[]
def unwrap(self): self._ssl_io_loop(self.sslobj.unwrap)
[ "def", "unwrap", "(", "self", ")", ":", "self", ".", "_ssl_io_loop", "(", "self", ".", "sslobj", ".", "unwrap", ")" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/urllib3/util/ssltransport.py#L150-L151
golemhq/golem
84f51478b169cdeab73fc7e2a22a64d0a2a29263
golem/webdriver/extended_webelement.py
python
ExtendedWebElement.find_all
(self, element=None, id=None, name=None, link_text=None, partial_link_text=None, css=None, xpath=None, tag_name=None)
return _find_all(self, element, id, name, link_text, partial_link_text, css, xpath, tag_name)
Find all WebElements that match the search criteria. Search criteria: The first argument must be: an element tuple, a CSS string, or an XPath string. Keyword search criteria: id, name, link_text, partial_link_text, css, xpath, tag_name. Only one search criteria should be...
Find all WebElements that match the search criteria.
[ "Find", "all", "WebElements", "that", "match", "the", "search", "criteria", "." ]
def find_all(self, element=None, id=None, name=None, link_text=None, partial_link_text=None, css=None, xpath=None, tag_name=None) -> List['ExtendedRemoteWebElement']: """Find all WebElements that match the search criteria. Search criteria: The first argument mu...
[ "def", "find_all", "(", "self", ",", "element", "=", "None", ",", "id", "=", "None", ",", "name", "=", "None", ",", "link_text", "=", "None", ",", "partial_link_text", "=", "None", ",", "css", "=", "None", ",", "xpath", "=", "None", ",", "tag_name", ...
https://github.com/golemhq/golem/blob/84f51478b169cdeab73fc7e2a22a64d0a2a29263/golem/webdriver/extended_webelement.py#L70-L91
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/contrib/pyros/pyros.py
python
PositiveIntOrMinusOne
(obj)
return ans
if obj is a positive int, return the int if obj is -1, return -1 else, error
if obj is a positive int, return the int if obj is -1, return -1 else, error
[ "if", "obj", "is", "a", "positive", "int", "return", "the", "int", "if", "obj", "is", "-", "1", "return", "-", "1", "else", "error" ]
def PositiveIntOrMinusOne(obj): ''' if obj is a positive int, return the int if obj is -1, return -1 else, error ''' ans = int(obj) if ans != float(obj) or (ans <= 0 and ans != -1): raise ValueError( "Expected positive int, but received %s" % (obj,)) return ans
[ "def", "PositiveIntOrMinusOne", "(", "obj", ")", ":", "ans", "=", "int", "(", "obj", ")", "if", "ans", "!=", "float", "(", "obj", ")", "or", "(", "ans", "<=", "0", "and", "ans", "!=", "-", "1", ")", ":", "raise", "ValueError", "(", "\"Expected posi...
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/contrib/pyros/pyros.py#L60-L70
IntelPython/sdc
1ebf55c00ef38dfbd401a70b3945e352a5a38b87
sdc/datatypes/hpat_pandas_stringmethods_functions.py
python
hpat_pandas_stringmethods_lower
(self)
return hpat_pandas_stringmethods_lower_impl
[]
def hpat_pandas_stringmethods_lower(self): ty_checker = TypeChecker('Method lower().') ty_checker.check(self, StringMethodsType) def hpat_pandas_stringmethods_lower_impl(self): mask = get_nan_mask(self._data._data) item_count = len(self._data) res_list = [''] * item_count f...
[ "def", "hpat_pandas_stringmethods_lower", "(", "self", ")", ":", "ty_checker", "=", "TypeChecker", "(", "'Method lower().'", ")", "ty_checker", ".", "check", "(", "self", ",", "StringMethodsType", ")", "def", "hpat_pandas_stringmethods_lower_impl", "(", "self", ")", ...
https://github.com/IntelPython/sdc/blob/1ebf55c00ef38dfbd401a70b3945e352a5a38b87/sdc/datatypes/hpat_pandas_stringmethods_functions.py#L937-L958
pyvista/pyvista
012dbb95a9aae406c3cd4cd94fc8c477f871e426
pyvista/utilities/errors.py
python
GPUInfo.renderer
(self)
return renderer.strip()
GPU renderer name.
GPU renderer name.
[ "GPU", "renderer", "name", "." ]
def renderer(self): """GPU renderer name.""" regex = re.compile("OpenGL renderer string:(.+)\n") try: renderer = regex.findall(self._gpu_info)[0] except IndexError: raise RuntimeError("Unable to parse GPU information for the renderer.") return renderer.str...
[ "def", "renderer", "(", "self", ")", ":", "regex", "=", "re", ".", "compile", "(", "\"OpenGL renderer string:(.+)\\n\"", ")", "try", ":", "renderer", "=", "regex", ".", "findall", "(", "self", ".", "_gpu_info", ")", "[", "0", "]", "except", "IndexError", ...
https://github.com/pyvista/pyvista/blob/012dbb95a9aae406c3cd4cd94fc8c477f871e426/pyvista/utilities/errors.py#L201-L208
vcg-uvic/lf-net-release
54abf68101901bc938325a62d68313e4cff463d4
common/tf_layer_utils.py
python
batch_norm_template
(inputs, is_training, scope, moments_dims, bn_decay=None, affine=True)
Batch normalization on convolutional maps and beyond... Ref.: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow Args: inputs: Tensor, k-D input ... x C could be BC or BHWC or BDHWC is_training: boolean tf.Varialbe, true indicates training phase ...
Batch normalization on convolutional maps and beyond... Ref.: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow
[ "Batch", "normalization", "on", "convolutional", "maps", "and", "beyond", "...", "Ref", ".", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "33949786", "/", "how", "-", "could", "-", "i", "-", "use", "-", "batch", "-", "nor...
def batch_norm_template(inputs, is_training, scope, moments_dims, bn_decay=None, affine=True): """ Batch normalization on convolutional maps and beyond... Ref.: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow Args: inputs: Tensor, k-D input ... x C...
[ "def", "batch_norm_template", "(", "inputs", ",", "is_training", ",", "scope", ",", "moments_dims", ",", "bn_decay", "=", "None", ",", "affine", "=", "True", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ")", "as", "sc", ":", "if", "len", ...
https://github.com/vcg-uvic/lf-net-release/blob/54abf68101901bc938325a62d68313e4cff463d4/common/tf_layer_utils.py#L77-L132
thautwarm/restrain-jit
f76b3e9ae8a34d2eef87a42cc87197153f14634c
restrain_jit/utils.py
python
CodeOut.to_code_lines
(self)
[]
def to_code_lines(self): def key(x): return x[0] for _, v in sorted(self.items(), key=key): yield from v
[ "def", "to_code_lines", "(", "self", ")", ":", "def", "key", "(", "x", ")", ":", "return", "x", "[", "0", "]", "for", "_", ",", "v", "in", "sorted", "(", "self", ".", "items", "(", ")", ",", "key", "=", "key", ")", ":", "yield", "from", "v" ]
https://github.com/thautwarm/restrain-jit/blob/f76b3e9ae8a34d2eef87a42cc87197153f14634c/restrain_jit/utils.py#L26-L32
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/ssl.py
python
cert_time_to_seconds
(cert_time)
Return the time in seconds since the Epoch, given the timestring representing the "notBefore" or "notAfter" date from a certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). "notBefore" or "notAfter" dates must use UTC (RFC 5280). Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oc...
Return the time in seconds since the Epoch, given the timestring representing the "notBefore" or "notAfter" date from a certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
[ "Return", "the", "time", "in", "seconds", "since", "the", "Epoch", "given", "the", "timestring", "representing", "the", "notBefore", "or", "notAfter", "date", "from", "a", "certificate", "in", "%b", "%d", "%H", ":", "%M", ":", "%S", "%Y", "%Z", "strptime",...
def cert_time_to_seconds(cert_time): """Return the time in seconds since the Epoch, given the timestring representing the "notBefore" or "notAfter" date from a certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). "notBefore" or "notAfter" dates must use UTC (RFC 5280). Month is on...
[ "def", "cert_time_to_seconds", "(", "cert_time", ")", ":", "from", "time", "import", "strptime", "from", "calendar", "import", "timegm", "months", "=", "(", "\"Jan\"", ",", "\"Feb\"", ",", "\"Mar\"", ",", "\"Apr\"", ",", "\"May\"", ",", "\"Jun\"", ",", "\"Ju...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/ssl.py#L1449-L1477
RasaHQ/rasa
54823b68c1297849ba7ae841a4246193cd1223a1
rasa/core/featurizers/single_state_featurizer.py
python
IntentTokenizerSingleStateFeaturizer.encode_all_labels
( self, domain: Domain, precomputations: Optional[MessageContainerForCoreFeaturization], )
return [ self._encode_intent(intent, precomputations) for intent in domain.intents ]
Encodes all relevant labels from the domain using the given precomputations. Args: domain: The domain that contains the labels. precomputations: Contains precomputed features and attributes. Returns: A list of encoded labels.
Encodes all relevant labels from the domain using the given precomputations.
[ "Encodes", "all", "relevant", "labels", "from", "the", "domain", "using", "the", "given", "precomputations", "." ]
def encode_all_labels( self, domain: Domain, precomputations: Optional[MessageContainerForCoreFeaturization], ) -> List[Dict[Text, List[Features]]]: """Encodes all relevant labels from the domain using the given precomputations. Args: domain: The domain that cont...
[ "def", "encode_all_labels", "(", "self", ",", "domain", ":", "Domain", ",", "precomputations", ":", "Optional", "[", "MessageContainerForCoreFeaturization", "]", ",", ")", "->", "List", "[", "Dict", "[", "Text", ",", "List", "[", "Features", "]", "]", "]", ...
https://github.com/RasaHQ/rasa/blob/54823b68c1297849ba7ae841a4246193cd1223a1/rasa/core/featurizers/single_state_featurizer.py#L386-L402
Fallen-Breath/MCDReforged
fdb1d2520b35f916123f265dbd94603981bb2b0c
mcdreforged/executor/watchdog.py
python
WatchDog.check_task_executor_state
(self)
[]
def check_task_executor_state(self): task_executor = self.mcdr_server.task_executor if task_executor.get_this_tick_time() > self.TASK_EXECUTOR_NO_RESPOND_THRESHOLD and self.__monitoring: plugin = self.mcdr_server.plugin_manager.get_current_running_plugin(thread=task_executor.get_thread()) self.mcdr_server.log...
[ "def", "check_task_executor_state", "(", "self", ")", ":", "task_executor", "=", "self", ".", "mcdr_server", ".", "task_executor", "if", "task_executor", ".", "get_this_tick_time", "(", ")", ">", "self", ".", "TASK_EXECUTOR_NO_RESPOND_THRESHOLD", "and", "self", ".",...
https://github.com/Fallen-Breath/MCDReforged/blob/fdb1d2520b35f916123f265dbd94603981bb2b0c/mcdreforged/executor/watchdog.py#L36-L49
microsoft/bistring
e23443e495f762967b09670b27bb1ff46ff4fef1
python/bistring/_alignment.py
python
Alignment.modified_range
(self, *args: AnyBounds)
return range(*self.modified_bounds(*args))
Like :meth:`modified_bounds`, but returns a :class:`range`.
Like :meth:`modified_bounds`, but returns a :class:`range`.
[ "Like", ":", "meth", ":", "modified_bounds", "but", "returns", "a", ":", "class", ":", "range", "." ]
def modified_range(self, *args: AnyBounds) -> range: """ Like :meth:`modified_bounds`, but returns a :class:`range`. """ return range(*self.modified_bounds(*args))
[ "def", "modified_range", "(", "self", ",", "*", "args", ":", "AnyBounds", ")", "->", "range", ":", "return", "range", "(", "*", "self", ".", "modified_bounds", "(", "*", "args", ")", ")" ]
https://github.com/microsoft/bistring/blob/e23443e495f762967b09670b27bb1ff46ff4fef1/python/bistring/_alignment.py#L475-L479
ym2011/PenetrationTestingScripts
b620ce6b8569382aef4484444fb3c087da9cfc21
BruteXSS/mechanize/_form.py
python
HTMLForm.click
(self, name=None, type=None, id=None, nr=0, coord=(1,1), request_class=_request.Request, label=None)
return self._click(name, type, id, label, nr, coord, "request", self._request_class)
Return request that would result from clicking on a control. The request object is a mechanize.Request instance, which you can pass to mechanize.urlopen. Only some control types (INPUT/SUBMIT & BUTTON/SUBMIT buttons and IMAGEs) can be clicked. Will click on the first clickable...
Return request that would result from clicking on a control.
[ "Return", "request", "that", "would", "result", "from", "clicking", "on", "a", "control", "." ]
def click(self, name=None, type=None, id=None, nr=0, coord=(1,1), request_class=_request.Request, label=None): """Return request that would result from clicking on a control. The request object is a mechanize.Request instance, which you can pass to mechanize.urlopen....
[ "def", "click", "(", "self", ",", "name", "=", "None", ",", "type", "=", "None", ",", "id", "=", "None", ",", "nr", "=", "0", ",", "coord", "=", "(", "1", ",", "1", ")", ",", "request_class", "=", "_request", ".", "Request", ",", "label", "=", ...
https://github.com/ym2011/PenetrationTestingScripts/blob/b620ce6b8569382aef4484444fb3c087da9cfc21/BruteXSS/mechanize/_form.py#L2974-L2999
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/external/pip/_vendor/pyparsing.py
python
ParserElement.addCondition
(self, *fns, **kwargs)
return self
Add a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the condition. Optional keyword arguments: ...
Add a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the condition.
[ "Add", "a", "boolean", "predicate", "function", "to", "expression", "s", "list", "of", "parse", "actions", ".", "See", "L", "{", "I", "{", "setParseAction", "}", "<setParseAction", ">", "}", "for", "function", "call", "signatures", ".", "Unlike", "C", "{",...
def addCondition(self, *fns, **kwargs): """Add a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the con...
[ "def", "addCondition", "(", "self", ",", "*", "fns", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "kwargs", ".", "get", "(", "\"message\"", ",", "\"failed user-defined condition\"", ")", "exc_type", "=", "ParseFatalException", "if", "kwargs", ".", "get", ...
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/pyparsing.py#L1275-L1300
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-50/fabmetheus_utilities/geometry/geometry_utilities/evaluate.py
python
getEvaluatedValueObliviously
(elementNode, key)
return getEvaluatedLinkValue(elementNode, value)
Get the evaluated value.
Get the evaluated value.
[ "Get", "the", "evaluated", "value", "." ]
def getEvaluatedValueObliviously(elementNode, key): 'Get the evaluated value.' value = str(elementNode.attributes[key]).strip() if key == 'id' or key == 'name' or key == 'tags': return value return getEvaluatedLinkValue(elementNode, value)
[ "def", "getEvaluatedValueObliviously", "(", "elementNode", ",", "key", ")", ":", "value", "=", "str", "(", "elementNode", ".", "attributes", "[", "key", "]", ")", ".", "strip", "(", ")", "if", "key", "==", "'id'", "or", "key", "==", "'name'", "or", "ke...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-50/fabmetheus_utilities/geometry/geometry_utilities/evaluate.py#L393-L398
django/django
0a17666045de6739ae1c2ac695041823d5f827f7
django/utils/termcolors.py
python
make_style
(opts=(), **kwargs)
return lambda text: colorize(text, opts, **kwargs)
Return a function with default parameters for colorize() Example: bold_red = make_style(opts=('bold',), fg='red') print(bold_red('hello')) KEYWORD = make_style(fg='yellow') COMMENT = make_style(fg='blue', opts=('bold',))
Return a function with default parameters for colorize()
[ "Return", "a", "function", "with", "default", "parameters", "for", "colorize", "()" ]
def make_style(opts=(), **kwargs): """ Return a function with default parameters for colorize() Example: bold_red = make_style(opts=('bold',), fg='red') print(bold_red('hello')) KEYWORD = make_style(fg='yellow') COMMENT = make_style(fg='blue', opts=('bold',)) """ ret...
[ "def", "make_style", "(", "opts", "=", "(", ")", ",", "*", "*", "kwargs", ")", ":", "return", "lambda", "text", ":", "colorize", "(", "text", ",", "opts", ",", "*", "*", "kwargs", ")" ]
https://github.com/django/django/blob/0a17666045de6739ae1c2ac695041823d5f827f7/django/utils/termcolors.py#L58-L68
PaddlePaddle/Research
2da0bd6c72d60e9df403aff23a7802779561c4a1
ST_DM/KDD2021-HGAMN/src/tokenization.py
python
CharTokenizer.tokenize
(self, text)
return split_tokens
doc
doc
[ "doc" ]
def tokenize(self, text): """doc""" split_tokens = [] for token in text.lower().split(" "): for sub_token in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) return split_tokens
[ "def", "tokenize", "(", "self", ",", "text", ")", ":", "split_tokens", "=", "[", "]", "for", "token", "in", "text", ".", "lower", "(", ")", ".", "split", "(", "\" \"", ")", ":", "for", "sub_token", "in", "self", ".", "wordpiece_tokenizer", ".", "toke...
https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/ST_DM/KDD2021-HGAMN/src/tokenization.py#L208-L215
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/ldap3/strategy/mockBase.py
python
MockBaseStrategy.mock_add
(self, request_message, controls)
return {'resultCode': result_code, 'matchedDN': '', 'diagnosticMessage': to_unicode(message, SERVER_ENCODING), 'referral': None }
[]
def mock_add(self, request_message, controls): # AddRequest ::= [APPLICATION 8] SEQUENCE { # entry LDAPDN, # attributes AttributeList } # # AddResponse ::= [APPLICATION 9] LDAPResult # # request: entry, attributes # response: LDAPRes...
[ "def", "mock_add", "(", "self", ",", "request_message", ",", "controls", ")", ":", "# AddRequest ::= [APPLICATION 8] SEQUENCE {", "# entry LDAPDN,", "# attributes AttributeList }", "#", "# AddResponse ::= [APPLICATION 9] LDAPResult", "#", "# request: entry, att...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/ldap3/strategy/mockBase.py#L363-L392
KvasirSecurity/Kvasir
a5b3775184a8343240e1154a1f762f75df04dc0a
modules/xlsxwriter/chart.py
python
Chart.set_high_low_lines
(self, options=None)
Set properties for the chart high-low lines. Args: options: A dictionary of options. Returns: Nothing.
Set properties for the chart high-low lines.
[ "Set", "properties", "for", "the", "chart", "high", "-", "low", "lines", "." ]
def set_high_low_lines(self, options=None): """ Set properties for the chart high-low lines. Args: options: A dictionary of options. Returns: Nothing. """ if options is None: options = {} line = self._get_line_properties(opt...
[ "def", "set_high_low_lines", "(", "self", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "line", "=", "self", ".", "_get_line_properties", "(", "options", ".", "get", "(", "'line'", ")", ")", "fill"...
https://github.com/KvasirSecurity/Kvasir/blob/a5b3775184a8343240e1154a1f762f75df04dc0a/modules/xlsxwriter/chart.py#L486-L503
axcore/tartube
36dd493642923fe8b9190a41db596c30c043ae90
tartube/config.py
python
OptionsEditWin.setup_files_tab
(self)
Called by self.setup_tabs(). Sets up the 'Files' tab.
Called by self.setup_tabs().
[ "Called", "by", "self", ".", "setup_tabs", "()", "." ]
def setup_files_tab(self): """Called by self.setup_tabs(). Sets up the 'Files' tab. """ # Add this tab... tab, grid = self.add_notebook_tab(_('_Files'), 0) # ...and an inner notebook... inner_notebook = self.add_inner_notebook(grid) # ...with its own ...
[ "def", "setup_files_tab", "(", "self", ")", ":", "# Add this tab...", "tab", ",", "grid", "=", "self", ".", "add_notebook_tab", "(", "_", "(", "'_Files'", ")", ",", "0", ")", "# ...and an inner notebook...", "inner_notebook", "=", "self", ".", "add_inner_noteboo...
https://github.com/axcore/tartube/blob/36dd493642923fe8b9190a41db596c30c043ae90/tartube/config.py#L4064-L4082
googleads/googleads-python-lib
b3b42a6deedbe6eaa1c9b30183a9eae3f9e9a7ee
examples/ad_manager/v202105/label_service/get_active_labels.py
python
main
(client)
[]
def main(client): # Initialize appropriate service. label_service = client.GetService('LabelService', version='v202105') # Create a statement to select labels. statement = (ad_manager.StatementBuilder(version='v202105') .Where('isActive = :isActive') .WithBindVariable('isActive', T...
[ "def", "main", "(", "client", ")", ":", "# Initialize appropriate service.", "label_service", "=", "client", ".", "GetService", "(", "'LabelService'", ",", "version", "=", "'v202105'", ")", "# Create a statement to select labels.", "statement", "=", "(", "ad_manager", ...
https://github.com/googleads/googleads-python-lib/blob/b3b42a6deedbe6eaa1c9b30183a9eae3f9e9a7ee/examples/ad_manager/v202105/label_service/get_active_labels.py#L23-L44
XuezheMax/flowseq
8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b
flownmt/nnet/attention.py
python
MultiHeadAttention.init
(self, query, key, value, key_mask=None, init_scale=1.0)
[]
def init(self, query, key, value, key_mask=None, init_scale=1.0): with torch.no_grad(): return self(query, key, value, key_mask=key_mask)
[ "def", "init", "(", "self", ",", "query", ",", "key", ",", "value", ",", "key_mask", "=", "None", ",", "init_scale", "=", "1.0", ")", ":", "with", "torch", ".", "no_grad", "(", ")", ":", "return", "self", "(", "query", ",", "key", ",", "value", "...
https://github.com/XuezheMax/flowseq/blob/8cb4ae00c26fbeb3e1459e3b3b90e7e9a84c3d2b/flownmt/nnet/attention.py#L207-L209
sagemath/sagenb
67a73cbade02639bc08265f28f3165442113ad4d
sagenb/notebook/interact.py
python
interact
(f, layout=None, width='800px')
return f
r""" Use interact as a decorator to create interactive Sage notebook cells with sliders, text boxes, radio buttons, check boxes, and color selectors. Simply put ``@interact`` on the line before a function definition in a cell by itself, and choose appropriate defaults for the variable names to dete...
r""" Use interact as a decorator to create interactive Sage notebook cells with sliders, text boxes, radio buttons, check boxes, and color selectors. Simply put ``@interact`` on the line before a function definition in a cell by itself, and choose appropriate defaults for the variable names to dete...
[ "r", "Use", "interact", "as", "a", "decorator", "to", "create", "interactive", "Sage", "notebook", "cells", "with", "sliders", "text", "boxes", "radio", "buttons", "check", "boxes", "and", "color", "selectors", ".", "Simply", "put", "@interact", "on", "the", ...
def interact(f, layout=None, width='800px'): r""" Use interact as a decorator to create interactive Sage notebook cells with sliders, text boxes, radio buttons, check boxes, and color selectors. Simply put ``@interact`` on the line before a function definition in a cell by itself, and choose approp...
[ "def", "interact", "(", "f", ",", "layout", "=", "None", ",", "width", "=", "'800px'", ")", ":", "if", "not", "isinstance", "(", "f", ",", "types", ".", "FunctionType", ")", "and", "callable", "(", "f", ")", ":", "f", "=", "f", ".", "__call__", "...
https://github.com/sagemath/sagenb/blob/67a73cbade02639bc08265f28f3165442113ad4d/sagenb/notebook/interact.py#L2259-L2673
OpenNMT/OpenNMT-py
4815f07fcd482af9a1fe1d3b620d144197178bc5
onmt/decoders/ensemble.py
python
EnsembleEncoder.forward
(self, src, lengths=None)
return enc_hidden, memory_bank, lengths
[]
def forward(self, src, lengths=None): enc_hidden, memory_bank, _ = zip(*[ model_encoder(src, lengths) for model_encoder in self.model_encoders]) return enc_hidden, memory_bank, lengths
[ "def", "forward", "(", "self", ",", "src", ",", "lengths", "=", "None", ")", ":", "enc_hidden", ",", "memory_bank", ",", "_", "=", "zip", "(", "*", "[", "model_encoder", "(", "src", ",", "lengths", ")", "for", "model_encoder", "in", "self", ".", "mod...
https://github.com/OpenNMT/OpenNMT-py/blob/4815f07fcd482af9a1fe1d3b620d144197178bc5/onmt/decoders/ensemble.py#L39-L43
ailabx/ailabx
4a8c701a3604bbc34157167224588041944ac1a2
codes/qlib-main/qlib/model/riskmodel/poet.py
python
POETCovEstimator.__init__
(self, num_factors: int = 0, thresh: float = 1.0, thresh_method: str = "soft", **kwargs)
Args: num_factors (int): number of factors (if set to zero, no factor model will be used). thresh (float): the positive constant for thresholding. thresh_method (str): thresholding method, which can be - 'soft': soft thresholding. - 'hard': hard thresh...
Args: num_factors (int): number of factors (if set to zero, no factor model will be used). thresh (float): the positive constant for thresholding. thresh_method (str): thresholding method, which can be - 'soft': soft thresholding. - 'hard': hard thresh...
[ "Args", ":", "num_factors", "(", "int", ")", ":", "number", "of", "factors", "(", "if", "set", "to", "zero", "no", "factor", "model", "will", "be", "used", ")", ".", "thresh", "(", "float", ")", ":", "the", "positive", "constant", "for", "thresholding"...
def __init__(self, num_factors: int = 0, thresh: float = 1.0, thresh_method: str = "soft", **kwargs): """ Args: num_factors (int): number of factors (if set to zero, no factor model will be used). thresh (float): the positive constant for thresholding. thresh_method (...
[ "def", "__init__", "(", "self", ",", "num_factors", ":", "int", "=", "0", ",", "thresh", ":", "float", "=", "1.0", ",", "thresh_method", ":", "str", "=", "\"soft\"", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", ...
https://github.com/ailabx/ailabx/blob/4a8c701a3604bbc34157167224588041944ac1a2/codes/qlib-main/qlib/model/riskmodel/poet.py#L19-L43
benedekrozemberczki/Splitter
003814d4c42e0b6ecbcea711b4de651eb2b7c5eb
src/splitter.py
python
SplitterTrainer.update_average_loss
(self, loss_score)
Updating the average loss and the description of the time remains bar. :param loss_score: Loss on the sample.
Updating the average loss and the description of the time remains bar. :param loss_score: Loss on the sample.
[ "Updating", "the", "average", "loss", "and", "the", "description", "of", "the", "time", "remains", "bar", ".", ":", "param", "loss_score", ":", "Loss", "on", "the", "sample", "." ]
def update_average_loss(self, loss_score): """ Updating the average loss and the description of the time remains bar. :param loss_score: Loss on the sample. """ self.cummulative_loss = self.cummulative_loss + loss_score self.steps = self.steps + 1 average_loss = s...
[ "def", "update_average_loss", "(", "self", ",", "loss_score", ")", ":", "self", ".", "cummulative_loss", "=", "self", ".", "cummulative_loss", "+", "loss_score", "self", ".", "steps", "=", "self", ".", "steps", "+", "1", "average_loss", "=", "self", ".", "...
https://github.com/benedekrozemberczki/Splitter/blob/003814d4c42e0b6ecbcea711b4de651eb2b7c5eb/src/splitter.py#L204-L212
pretix/pretix
96f694cf61345f54132cd26cdeb07d5d11b34232
src/pretix/base/payment.py
python
BasePaymentProvider.is_allowed
(self, request: HttpRequest, total: Decimal=None)
return timing and pricing
You can use this method to disable this payment provider for certain groups of users, products or other criteria. If this method returns ``False``, the user will not be able to select this payment method. This will only be called during checkout, not on retrying. The default implementat...
You can use this method to disable this payment provider for certain groups of users, products or other criteria. If this method returns ``False``, the user will not be able to select this payment method. This will only be called during checkout, not on retrying.
[ "You", "can", "use", "this", "method", "to", "disable", "this", "payment", "provider", "for", "certain", "groups", "of", "users", "products", "or", "other", "criteria", ".", "If", "this", "method", "returns", "False", "the", "user", "will", "not", "be", "a...
def is_allowed(self, request: HttpRequest, total: Decimal=None) -> bool: """ You can use this method to disable this payment provider for certain groups of users, products or other criteria. If this method returns ``False``, the user will not be able to select this payment method. This w...
[ "def", "is_allowed", "(", "self", ",", "request", ":", "HttpRequest", ",", "total", ":", "Decimal", "=", "None", ")", "->", "bool", ":", "timing", "=", "self", ".", "_is_still_available", "(", "cart_id", "=", "get_or_create_cart_id", "(", "request", ")", "...
https://github.com/pretix/pretix/blob/96f694cf61345f54132cd26cdeb07d5d11b34232/src/pretix/base/payment.py#L499-L558
gammapy/gammapy
735b25cd5bbed35e2004d633621896dcd5295e8b
gammapy/maps/hpx/core.py
python
HpxMap.to_swapped
(self)
Return a new map with the opposite scheme (ring or nested). Returns ------- map : `~HpxMap` Map object.
Return a new map with the opposite scheme (ring or nested).
[ "Return", "a", "new", "map", "with", "the", "opposite", "scheme", "(", "ring", "or", "nested", ")", "." ]
def to_swapped(self): """Return a new map with the opposite scheme (ring or nested). Returns ------- map : `~HpxMap` Map object. """ pass
[ "def", "to_swapped", "(", "self", ")", ":", "pass" ]
https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/gammapy/maps/hpx/core.py#L264-L272
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/markdown/markdown/blockparser.py
python
State.isstate
(self, state)
Test that top (current) level is of given state.
Test that top (current) level is of given state.
[ "Test", "that", "top", "(", "current", ")", "level", "is", "of", "given", "state", "." ]
def isstate(self, state): """ Test that top (current) level is of given state. """ if len(self): return self[-1] == state else: return False
[ "def", "isstate", "(", "self", ",", "state", ")", ":", "if", "len", "(", "self", ")", ":", "return", "self", "[", "-", "1", "]", "==", "state", "else", ":", "return", "False" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/markdown/markdown/blockparser.py#L30-L35
qiyuangong/leetcode
790f9ee86dcc7bf85be1bd9358f4c069b4a4c2f5
python/033_Search_in_Rotated_Sorted_Array.py
python
Solution.search
(self, nums, target)
return get(0, len(nums) - 1)
:type nums: List[int] :type target: int :rtype: int
:type nums: List[int] :type target: int :rtype: int
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "type", "target", ":", "int", ":", "rtype", ":", "int" ]
def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # binary search # if start < mid, then left part is sorted # if mid < end, then right part is sorted def get(start, end): if start > end: ...
[ "def", "search", "(", "self", ",", "nums", ",", "target", ")", ":", "# binary search", "# if start < mid, then left part is sorted", "# if mid < end, then right part is sorted", "def", "get", "(", "start", ",", "end", ")", ":", "if", "start", ">", "end", ":", "ret...
https://github.com/qiyuangong/leetcode/blob/790f9ee86dcc7bf85be1bd9358f4c069b4a4c2f5/python/033_Search_in_Rotated_Sorted_Array.py#L2-L27
eclipse/paho.mqtt.python
9782ab81fe7ee3a05e74c7f3e1d03d5611ea4be4
src/paho/mqtt/client.py
python
Client.enable_bridge_mode
(self)
Sets the client in a bridge mode instead of client mode. Must be called before connect() to have any effect. Requires brokers that support bridge mode. Under bridge mode, the broker will identify the client as a bridge and not send it's own messages back to it. Hence a subsciption of #...
Sets the client in a bridge mode instead of client mode.
[ "Sets", "the", "client", "in", "a", "bridge", "mode", "instead", "of", "client", "mode", "." ]
def enable_bridge_mode(self): """Sets the client in a bridge mode instead of client mode. Must be called before connect() to have any effect. Requires brokers that support bridge mode. Under bridge mode, the broker will identify the client as a bridge and not send it's own mess...
[ "def", "enable_bridge_mode", "(", "self", ")", ":", "self", ".", "_client_mode", "=", "MQTT_BRIDGE" ]
https://github.com/eclipse/paho.mqtt.python/blob/9782ab81fe7ee3a05e74c7f3e1d03d5611ea4be4/src/paho/mqtt/client.py#L1321-L1335
AnasAboureada/Penetration-Testing-Study-Notes
8152fd609cf818dba2f07e060738a24c56221687
scripts/string_decode.py
python
Haval256
()
[]
def Haval256(): hs='7169ecae19a5cd729f6e9574228b8b3c91699175324e6222dec569d4281d4a4a' if len(hash)==len(hs) and hash.isdigit()==False and hash.isalpha()==False and hash.isalnum()==True: jerar.append("115040")
[ "def", "Haval256", "(", ")", ":", "hs", "=", "'7169ecae19a5cd729f6e9574228b8b3c91699175324e6222dec569d4281d4a4a'", "if", "len", "(", "hash", ")", "==", "len", "(", "hs", ")", "and", "hash", ".", "isdigit", "(", ")", "==", "False", "and", "hash", ".", "isalph...
https://github.com/AnasAboureada/Penetration-Testing-Study-Notes/blob/8152fd609cf818dba2f07e060738a24c56221687/scripts/string_decode.py#L439-L442
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/sklearn/utils/__init__.py
python
gen_even_slices
(n, n_packs, n_samples=None)
Generator to create n_packs slices going up to n. Pass n_samples when the slices are to be used for sparse matrix indexing; slicing off-the-end raises an exception, while it works for NumPy arrays. Examples -------- >>> from sklearn.utils import gen_even_slices >>> list(gen_even_slices(10, 1))...
Generator to create n_packs slices going up to n.
[ "Generator", "to", "create", "n_packs", "slices", "going", "up", "to", "n", "." ]
def gen_even_slices(n, n_packs, n_samples=None): """Generator to create n_packs slices going up to n. Pass n_samples when the slices are to be used for sparse matrix indexing; slicing off-the-end raises an exception, while it works for NumPy arrays. Examples -------- >>> from sklearn.utils imp...
[ "def", "gen_even_slices", "(", "n", ",", "n_packs", ",", "n_samples", "=", "None", ")", ":", "start", "=", "0", "if", "n_packs", "<", "1", ":", "raise", "ValueError", "(", "\"gen_even_slices got n_packs=%s, must be >=1\"", "%", "n_packs", ")", "for", "pack_num...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/sklearn/utils/__init__.py#L341-L372
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/craft_plugins/tower.py
python
ThreadLayer.__repr__
(self)
return '%s' % self.islands
Get the string representation of this thread layer.
Get the string representation of this thread layer.
[ "Get", "the", "string", "representation", "of", "this", "thread", "layer", "." ]
def __repr__(self): "Get the string representation of this thread layer." return '%s' % self.islands
[ "def", "__repr__", "(", "self", ")", ":", "return", "'%s'", "%", "self", ".", "islands" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/craft_plugins/tower.py#L136-L138
DSE-MSU/DeepRobust
2bcde200a5969dae32cddece66206a52c87c43e8
deeprobust/image/netmodels/CNN_multilayer.py
python
Net.forward
(self, x)
return F.log_softmax(layers[6], dim=1)
[]
def forward(self, x): self.layers[0] = F.relu(self.conv1(x)) self.layers[1] = F.max_pool2d(x, 2, 2) self.layers[2] = F.relu(self.conv2(x)) self.layers[3] = F.max_pool2d(x, 2, 2) self.layers[4] = x.view(-1, int(self.H/4) * int(self.W/4) * self.out_channel2) self.layers[5] ...
[ "def", "forward", "(", "self", ",", "x", ")", ":", "self", ".", "layers", "[", "0", "]", "=", "F", ".", "relu", "(", "self", ".", "conv1", "(", "x", ")", ")", "self", ".", "layers", "[", "1", "]", "=", "F", ".", "max_pool2d", "(", "x", ",",...
https://github.com/DSE-MSU/DeepRobust/blob/2bcde200a5969dae32cddece66206a52c87c43e8/deeprobust/image/netmodels/CNN_multilayer.py#L38-L46
jiangxinyang227/NLP-Project
b11f67d8962f40e17990b4fc4551b0ea5496881c
few_shot_learning/prototypical_network/metrics.py
python
multi_recall
(pred_y, true_y, labels)
return rec
Calculate the recall of multi classification :param pred_y: predict result :param true_y: true result :param labels: label list :return:
Calculate the recall of multi classification :param pred_y: predict result :param true_y: true result :param labels: label list :return:
[ "Calculate", "the", "recall", "of", "multi", "classification", ":", "param", "pred_y", ":", "predict", "result", ":", "param", "true_y", ":", "true", "result", ":", "param", "labels", ":", "label", "list", ":", "return", ":" ]
def multi_recall(pred_y, true_y, labels): """ Calculate the recall of multi classification :param pred_y: predict result :param true_y: true result :param labels: label list :return: """ if isinstance(pred_y[0], list): pred_y = [item[0] for item in pred_y] recalls = [binary_...
[ "def", "multi_recall", "(", "pred_y", ",", "true_y", ",", "labels", ")", ":", "if", "isinstance", "(", "pred_y", "[", "0", "]", ",", "list", ")", ":", "pred_y", "=", "[", "item", "[", "0", "]", "for", "item", "in", "pred_y", "]", "recalls", "=", ...
https://github.com/jiangxinyang227/NLP-Project/blob/b11f67d8962f40e17990b4fc4551b0ea5496881c/few_shot_learning/prototypical_network/metrics.py#L122-L135
ClusterLabs/pcs
1f225199e02c8d20456bb386f4c913c3ff21ac78
pcs/lib/cib/acl.py
python
provide_role
(acl_section, role_id)
return role if role is not None else create_role(acl_section, role_id)
Returns role with id role_id. If doesn't exist, it will be created. role_id id of desired role
Returns role with id role_id. If doesn't exist, it will be created. role_id id of desired role
[ "Returns", "role", "with", "id", "role_id", ".", "If", "doesn", "t", "exist", "it", "will", "be", "created", ".", "role_id", "id", "of", "desired", "role" ]
def provide_role(acl_section, role_id): """ Returns role with id role_id. If doesn't exist, it will be created. role_id id of desired role """ role = find_role(acl_section, role_id, none_if_id_unused=True) return role if role is not None else create_role(acl_section, role_id)
[ "def", "provide_role", "(", "acl_section", ",", "role_id", ")", ":", "role", "=", "find_role", "(", "acl_section", ",", "role_id", ",", "none_if_id_unused", "=", "True", ")", "return", "role", "if", "role", "is", "not", "None", "else", "create_role", "(", ...
https://github.com/ClusterLabs/pcs/blob/1f225199e02c8d20456bb386f4c913c3ff21ac78/pcs/lib/cib/acl.py#L213-L219
wkeeling/selenium-wire
5a5a83c0189e0a10fbcf100d619148d6c1bc7dad
seleniumwire/server.py
python
MitmProxy.serve_forever
(self)
Run the server.
Run the server.
[ "Run", "the", "server", "." ]
def serve_forever(self): """Run the server.""" asyncio.set_event_loop(self._event_loop) self.master.run_loop(self._event_loop)
[ "def", "serve_forever", "(", "self", ")", ":", "asyncio", ".", "set_event_loop", "(", "self", ".", "_event_loop", ")", "self", ".", "master", ".", "run_loop", "(", "self", ".", "_event_loop", ")" ]
https://github.com/wkeeling/selenium-wire/blob/5a5a83c0189e0a10fbcf100d619148d6c1bc7dad/seleniumwire/server.py#L66-L69
MisaOgura/flashtorch
9422bf9dddfe7c65b13871b1c9f455e0a54f02dc
flashtorch/activmax/gradient_ascent.py
python
GradientAscent.optimize
(self, layer, filter_idx, input_=None, num_iter=30)
return self._ascent(input_, num_iter)
Generates an image that maximally activates the target filter. Args: layer (torch.nn.modules.conv.Conv2d): The target Conv2d layer from which the filter to be chosen, based on `filter_idx`. filter_idx (int): The index of the target filter. num_iter (int, opti...
Generates an image that maximally activates the target filter.
[ "Generates", "an", "image", "that", "maximally", "activates", "the", "target", "filter", "." ]
def optimize(self, layer, filter_idx, input_=None, num_iter=30): """Generates an image that maximally activates the target filter. Args: layer (torch.nn.modules.conv.Conv2d): The target Conv2d layer from which the filter to be chosen, based on `filter_idx`. filte...
[ "def", "optimize", "(", "self", ",", "layer", ",", "filter_idx", ",", "input_", "=", "None", ",", "num_iter", "=", "30", ")", ":", "# Validate the type of the layer", "if", "type", "(", "layer", ")", "!=", "nn", ".", "modules", ".", "conv", ".", "Conv2d"...
https://github.com/MisaOgura/flashtorch/blob/9422bf9dddfe7c65b13871b1c9f455e0a54f02dc/flashtorch/activmax/gradient_ascent.py#L83-L137
broadinstitute/gtex-pipeline
3481dd43b2e8a33cc217155483ce25d5255aafa9
genotype/shapeit2/src/aggregate_pirs.py
python
get_header_size
(pir_file)
return int(line.split(' ')[1])+1
Get size of header (lines)
Get size of header (lines)
[ "Get", "size", "of", "header", "(", "lines", ")" ]
def get_header_size(pir_file): """ Get size of header (lines) """ with open (pir_file, 'r') as f: line = f.readline() return int(line.split(' ')[1])+1
[ "def", "get_header_size", "(", "pir_file", ")", ":", "with", "open", "(", "pir_file", ",", "'r'", ")", "as", "f", ":", "line", "=", "f", ".", "readline", "(", ")", "return", "int", "(", "line", ".", "split", "(", "' '", ")", "[", "1", "]", ")", ...
https://github.com/broadinstitute/gtex-pipeline/blob/3481dd43b2e8a33cc217155483ce25d5255aafa9/genotype/shapeit2/src/aggregate_pirs.py#L8-L14
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
pyrevitlib/rpw/db/curve.py
python
Line.mid_point
(self)
return XYZ(self._revit_object.GetEndPoint(0.5))
Mid Point of line
Mid Point of line
[ "Mid", "Point", "of", "line" ]
def mid_point(self): """ Mid Point of line """ return XYZ(self._revit_object.GetEndPoint(0.5))
[ "def", "mid_point", "(", "self", ")", ":", "return", "XYZ", "(", "self", ".", "_revit_object", ".", "GetEndPoint", "(", "0.5", ")", ")" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/pyrevitlib/rpw/db/curve.py#L74-L76
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
portia_examle/lib/python2.7/site-packages/pip/_vendor/requests/utils.py
python
parse_header_links
(value)
return links
Return a dict of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list
Return a dict of parsed link headers proxies.
[ "Return", "a", "dict", "of", "parsed", "link", "headers", "proxies", "." ]
def parse_header_links(value): """Return a dict of parsed link headers proxies. i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" :rtype: list """ links = [] replace_chars = ' \'"' for val in re.split(', *<', value): ...
[ "def", "parse_header_links", "(", "value", ")", ":", "links", "=", "[", "]", "replace_chars", "=", "' \\'\"'", "for", "val", "in", "re", ".", "split", "(", "', *<'", ",", "value", ")", ":", "try", ":", "url", ",", "params", "=", "val", ".", "split", ...
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/portia_examle/lib/python2.7/site-packages/pip/_vendor/requests/utils.py#L658-L688
hbashton/spotify-ripper
d0464193dead7bd3ac7580e98bde86a0f323acae
spotify_ripper/utils.py
python
escape_filename_part
(part)
return part
escape possible offending characters
escape possible offending characters
[ "escape", "possible", "offending", "characters" ]
def escape_filename_part(part): """escape possible offending characters""" part = re.sub(r"\s*/\s*", r' & ', part) part = re.sub(r"""\s*[\\/:"*?<>|]+\s*""", r' ', part) part = part.strip() part = re.sub(r"(^\.+\s*|(?<=\.)\.+|\s*\.+$)", r'', part) return part
[ "def", "escape_filename_part", "(", "part", ")", ":", "part", "=", "re", ".", "sub", "(", "r\"\\s*/\\s*\"", ",", "r' & '", ",", "part", ")", "part", "=", "re", ".", "sub", "(", "r\"\"\"\\s*[\\\\/:\"*?<>|]+\\s*\"\"\"", ",", "r' '", ",", "part", ")", "part",...
https://github.com/hbashton/spotify-ripper/blob/d0464193dead7bd3ac7580e98bde86a0f323acae/spotify_ripper/utils.py#L58-L64