repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
aio-libs/aiodocker
aiodocker/events.py
https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/events.py#L24-L33
def subscribe(self, *, create_task=True, **params): """Subscribes to the Docker events channel. Use the keyword argument create_task=False to prevent automatically spawning the background tasks that listen to the events. This function returns a ChannelSubscriber object. """ ...
[ "def", "subscribe", "(", "self", ",", "*", ",", "create_task", "=", "True", ",", "*", "*", "params", ")", ":", "if", "create_task", "and", "not", "self", ".", "task", ":", "self", ".", "task", "=", "asyncio", ".", "ensure_future", "(", "self", ".", ...
Subscribes to the Docker events channel. Use the keyword argument create_task=False to prevent automatically spawning the background tasks that listen to the events. This function returns a ChannelSubscriber object.
[ "Subscribes", "to", "the", "Docker", "events", "channel", ".", "Use", "the", "keyword", "argument", "create_task", "=", "False", "to", "prevent", "automatically", "spawning", "the", "background", "tasks", "that", "listen", "to", "the", "events", "." ]
python
train
tanghaibao/jcvi
jcvi/projects/synfind.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/synfind.py#L276-L351
def benchmark(args): """ %prog benchmark at bedfile Compare SynFind, MCScanx, iADHoRe and OrthoFinder against the truth. """ p = OptionParser(benchmark.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) pf, bedfile = args truth = pf + ...
[ "def", "benchmark", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "benchmark", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "2", ":", "sys", ".", "exit", "("...
%prog benchmark at bedfile Compare SynFind, MCScanx, iADHoRe and OrthoFinder against the truth.
[ "%prog", "benchmark", "at", "bedfile" ]
python
train
trevisanj/a99
a99/gui/xmisc.py
https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/xmisc.py#L432-L444
def connect_all(self): """[Re-]connects all signals and slots. If already in "connected" state, ignores the call. """ if self.__connected: return # assert not self.__connected, "connect_all() already in \"connected\" state" with self.__lock: for ...
[ "def", "connect_all", "(", "self", ")", ":", "if", "self", ".", "__connected", ":", "return", "# assert not self.__connected, \"connect_all() already in \\\"connected\\\" state\"\r", "with", "self", ".", "__lock", ":", "for", "signal", "in", "self", ".", "__signals", ...
[Re-]connects all signals and slots. If already in "connected" state, ignores the call.
[ "[", "Re", "-", "]", "connects", "all", "signals", "and", "slots", ".", "If", "already", "in", "connected", "state", "ignores", "the", "call", "." ]
python
train
persephone-tools/persephone
persephone/__init__.py
https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/__init__.py#L6-L13
def handle_unhandled_exception(exc_type, exc_value, exc_traceback): """Handler for unhandled exceptions that will write to the logs""" if issubclass(exc_type, KeyboardInterrupt): # call the default excepthook saved at __excepthook__ sys.__excepthook__(exc_type, exc_value, exc_traceback) ...
[ "def", "handle_unhandled_exception", "(", "exc_type", ",", "exc_value", ",", "exc_traceback", ")", ":", "if", "issubclass", "(", "exc_type", ",", "KeyboardInterrupt", ")", ":", "# call the default excepthook saved at __excepthook__", "sys", ".", "__excepthook__", "(", "...
Handler for unhandled exceptions that will write to the logs
[ "Handler", "for", "unhandled", "exceptions", "that", "will", "write", "to", "the", "logs" ]
python
train
Karaage-Cluster/karaage
karaage/plugins/kgapplications/views/base.py
https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/plugins/kgapplications/views/base.py#L158-L171
def start(self, request, application, extra_roles=None): """ Continue the state machine at first state. """ # Get the authentication of the current user roles = self._get_roles_for_request(request, application) if extra_roles is not None: roles.update(extra_roles) # ...
[ "def", "start", "(", "self", ",", "request", ",", "application", ",", "extra_roles", "=", "None", ")", ":", "# Get the authentication of the current user", "roles", "=", "self", ".", "_get_roles_for_request", "(", "request", ",", "application", ")", "if", "extra_r...
Continue the state machine at first state.
[ "Continue", "the", "state", "machine", "at", "first", "state", "." ]
python
train
mikeboers/Flask-ACL
flask_acl/extension.py
https://github.com/mikeboers/Flask-ACL/blob/7339b89f96ad8686d1526e25c138244ad912e12d/flask_acl/extension.py#L116-L144
def route_acl(self, *acl, **options): """Decorator to attach an ACL to a route. E.g:: @app.route('/url/to/view') @authz.route_acl(''' ALLOW WHEEL ALL DENY ANY ALL ''') def my_admin_function(): pa...
[ "def", "route_acl", "(", "self", ",", "*", "acl", ",", "*", "*", "options", ")", ":", "def", "_route_acl", "(", "func", ")", ":", "func", ".", "__acl__", "=", "acl", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "a...
Decorator to attach an ACL to a route. E.g:: @app.route('/url/to/view') @authz.route_acl(''' ALLOW WHEEL ALL DENY ANY ALL ''') def my_admin_function(): pass
[ "Decorator", "to", "attach", "an", "ACL", "to", "a", "route", "." ]
python
train
cdumay/kser
src/kser/controller.py
https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/controller.py#L146-L186
def run(cls, raw_data): """description of run""" logger.debug("{}.ReceivedFromKafka: {}".format( cls.__name__, raw_data )) try: kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data)) except Exception as exc: logger.error( "{}.Impo...
[ "def", "run", "(", "cls", ",", "raw_data", ")", ":", "logger", ".", "debug", "(", "\"{}.ReceivedFromKafka: {}\"", ".", "format", "(", "cls", ".", "__name__", ",", "raw_data", ")", ")", "try", ":", "kmsg", "=", "cls", ".", "_onmessage", "(", "cls", ".",...
description of run
[ "description", "of", "run" ]
python
train
hollenstein/maspy
maspy/xml.py
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/xml.py#L469-L480
def next(self): """ #TODO: docstring :returns: #TODO: docstring """ try: self.event, self.element = next(self.iterator) self.elementTag = clearTag(self.element.tag) except StopIteration: clearParsedElements(self.element) raise Stop...
[ "def", "next", "(", "self", ")", ":", "try", ":", "self", ".", "event", ",", "self", ".", "element", "=", "next", "(", "self", ".", "iterator", ")", "self", ".", "elementTag", "=", "clearTag", "(", "self", ".", "element", ".", "tag", ")", "except",...
#TODO: docstring :returns: #TODO: docstring
[ "#TODO", ":", "docstring" ]
python
train
apple/turicreate
src/unity/python/turicreate/util/__init__.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/util/__init__.py#L367-L380
def _get_temp_file_location(): ''' Returns user specified temporary file location. The temporary location is specified through: >>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...) ''' from .._connect import main as _glconnect unity = _glconnect.get_unity() cache_...
[ "def", "_get_temp_file_location", "(", ")", ":", "from", ".", ".", "_connect", "import", "main", "as", "_glconnect", "unity", "=", "_glconnect", ".", "get_unity", "(", ")", "cache_dir", "=", "_convert_slashes", "(", "unity", ".", "get_current_cache_file_location",...
Returns user specified temporary file location. The temporary location is specified through: >>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...)
[ "Returns", "user", "specified", "temporary", "file", "location", ".", "The", "temporary", "location", "is", "specified", "through", ":" ]
python
train
googledatalab/pydatalab
google/datalab/utils/commands/_commands.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_commands.py#L157-L257
def parse(self, line, cell, namespace=None): """Parses a line and cell into a dictionary of arguments, expanding variables from a namespace. For each line parameters beginning with --, it also checks the cell content and see if it exists there. For example, if "--config1" is a line parameter, it checks to ...
[ "def", "parse", "(", "self", ",", "line", ",", "cell", ",", "namespace", "=", "None", ")", ":", "if", "namespace", "is", "None", ":", "ipy", "=", "IPython", ".", "get_ipython", "(", ")", "namespace", "=", "ipy", ".", "user_ns", "# Find which subcommand i...
Parses a line and cell into a dictionary of arguments, expanding variables from a namespace. For each line parameters beginning with --, it also checks the cell content and see if it exists there. For example, if "--config1" is a line parameter, it checks to see if cell dict contains "config1" item, and if...
[ "Parses", "a", "line", "and", "cell", "into", "a", "dictionary", "of", "arguments", "expanding", "variables", "from", "a", "namespace", "." ]
python
train
dixudx/rtcclient
rtcclient/workitem.py
https://github.com/dixudx/rtcclient/blob/1721dd0b047478f5bdd6359b07a2c503cfafd86f/rtcclient/workitem.py#L419-L433
def getStates(self): """Get all :class:`rtcclient.models.State` objects of this workitem :return: a :class:`list` contains all the :class:`rtcclient.models.State` objects :rtype: list """ cust_attr = (self.raw_data.get("rtc_cm:state") .get("...
[ "def", "getStates", "(", "self", ")", ":", "cust_attr", "=", "(", "self", ".", "raw_data", ".", "get", "(", "\"rtc_cm:state\"", ")", ".", "get", "(", "\"@rdf:resource\"", ")", ".", "split", "(", "\"/\"", ")", "[", "-", "2", "]", ")", "return", "self"...
Get all :class:`rtcclient.models.State` objects of this workitem :return: a :class:`list` contains all the :class:`rtcclient.models.State` objects :rtype: list
[ "Get", "all", ":", "class", ":", "rtcclient", ".", "models", ".", "State", "objects", "of", "this", "workitem" ]
python
train
tanghaibao/jcvi
jcvi/compara/fractionation.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/compara/fractionation.py#L420-L523
def summary(args): """ %prog summary diploid.napus.fractionation gmap.status Provide summary of fractionation. `fractionation` file is generated with loss(). `gmap.status` is generated with genestatus(). """ from jcvi.formats.base import DictFile from jcvi.utils.cbook import percentage, Reg...
[ "def", "summary", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "base", "import", "DictFile", "from", "jcvi", ".", "utils", ".", "cbook", "import", "percentage", ",", "Registry", "p", "=", "OptionParser", "(", "summary", ".", "__doc__", ")"...
%prog summary diploid.napus.fractionation gmap.status Provide summary of fractionation. `fractionation` file is generated with loss(). `gmap.status` is generated with genestatus().
[ "%prog", "summary", "diploid", ".", "napus", ".", "fractionation", "gmap", ".", "status" ]
python
train
frawau/aiolifx
aiolifx/aiolifx.py
https://github.com/frawau/aiolifx/blob/9bd8c5e6d291f4c79314989402f7e2c6476d5851/aiolifx/aiolifx.py#L182-L188
def register(self): """Proxy method to register the device with the parent. """ if not self.registered: self.registered = True if self.parent: self.parent.register(self)
[ "def", "register", "(", "self", ")", ":", "if", "not", "self", ".", "registered", ":", "self", ".", "registered", "=", "True", "if", "self", ".", "parent", ":", "self", ".", "parent", ".", "register", "(", "self", ")" ]
Proxy method to register the device with the parent.
[ "Proxy", "method", "to", "register", "the", "device", "with", "the", "parent", "." ]
python
train
KelSolaar/Umbra
umbra/ui/views.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/views.py#L246-L256
def read_only(self, value): """ Setter for **self.__read_only** attribute. :param value: Attribute value. :type value: bool """ if value is not None: assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("read_only", value) ...
[ "def", "read_only", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "bool", ",", "\"'{0}' attribute: '{1}' type is not 'bool'!\"", ".", "format", "(", "\"read_only\"", ",", "value", ")"...
Setter for **self.__read_only** attribute. :param value: Attribute value. :type value: bool
[ "Setter", "for", "**", "self", ".", "__read_only", "**", "attribute", "." ]
python
train
cmap/cmapPy
cmapPy/math/agg_wt_avg.py
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/agg_wt_avg.py#L17-L41
def get_upper_triangle(correlation_matrix): ''' Extract upper triangle from a square matrix. Negative values are set to 0. Args: correlation_matrix (pandas df): Correlations between all replicates Returns: upper_tri_df (pandas df): Upper triangle extracted from correlation_matrix; rid ...
[ "def", "get_upper_triangle", "(", "correlation_matrix", ")", ":", "upper_triangle", "=", "correlation_matrix", ".", "where", "(", "np", ".", "triu", "(", "np", ".", "ones", "(", "correlation_matrix", ".", "shape", ")", ",", "k", "=", "1", ")", ".", "astype...
Extract upper triangle from a square matrix. Negative values are set to 0. Args: correlation_matrix (pandas df): Correlations between all replicates Returns: upper_tri_df (pandas df): Upper triangle extracted from correlation_matrix; rid is the row index, cid is the column index, c...
[ "Extract", "upper", "triangle", "from", "a", "square", "matrix", ".", "Negative", "values", "are", "set", "to", "0", "." ]
python
train
saltstack/salt
salt/modules/rabbitmq.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rabbitmq.py#L193-L199
def _output_to_list(cmdoutput): ''' Convert rabbitmqctl output to a list of strings (assuming whitespace-delimited output). Ignores output lines that shouldn't be parsed, like warnings. cmdoutput: string output of rabbitmqctl commands ''' return [item for line in cmdoutput.splitlines() if _safe_...
[ "def", "_output_to_list", "(", "cmdoutput", ")", ":", "return", "[", "item", "for", "line", "in", "cmdoutput", ".", "splitlines", "(", ")", "if", "_safe_output", "(", "line", ")", "for", "item", "in", "line", ".", "split", "(", ")", "]" ]
Convert rabbitmqctl output to a list of strings (assuming whitespace-delimited output). Ignores output lines that shouldn't be parsed, like warnings. cmdoutput: string output of rabbitmqctl commands
[ "Convert", "rabbitmqctl", "output", "to", "a", "list", "of", "strings", "(", "assuming", "whitespace", "-", "delimited", "output", ")", ".", "Ignores", "output", "lines", "that", "shouldn", "t", "be", "parsed", "like", "warnings", ".", "cmdoutput", ":", "str...
python
train
aleju/imgaug
imgaug/augmentables/heatmaps.py
https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/heatmaps.py#L240-L272
def pad(self, top=0, right=0, bottom=0, left=0, mode="constant", cval=0.0): """ Pad the heatmaps on their top/right/bottom/left side. Parameters ---------- top : int, optional Amount of pixels to add at the top side of the heatmaps. Must be 0 or greater. rig...
[ "def", "pad", "(", "self", ",", "top", "=", "0", ",", "right", "=", "0", ",", "bottom", "=", "0", ",", "left", "=", "0", ",", "mode", "=", "\"constant\"", ",", "cval", "=", "0.0", ")", ":", "arr_0to1_padded", "=", "ia", ".", "pad", "(", "self",...
Pad the heatmaps on their top/right/bottom/left side. Parameters ---------- top : int, optional Amount of pixels to add at the top side of the heatmaps. Must be 0 or greater. right : int, optional Amount of pixels to add at the right side of the heatmaps. Must b...
[ "Pad", "the", "heatmaps", "on", "their", "top", "/", "right", "/", "bottom", "/", "left", "side", "." ]
python
valid
quintusdias/glymur
glymur/config.py
https://github.com/quintusdias/glymur/blob/8b8fb091130fff00f1028dc82219e69e3f9baf6d/glymur/config.py#L110-L136
def read_config_file(libname): """ Extract library locations from a configuration file. Parameters ---------- libname : str One of either 'openjp2' or 'openjpeg' Returns ------- path : None or str None if no location is specified, otherwise a path to the library """...
[ "def", "read_config_file", "(", "libname", ")", ":", "filename", "=", "glymurrc_fname", "(", ")", "if", "filename", "is", "None", ":", "# There's no library file path to return in this case.", "return", "None", "# Read the configuration file for the library location.", "parse...
Extract library locations from a configuration file. Parameters ---------- libname : str One of either 'openjp2' or 'openjpeg' Returns ------- path : None or str None if no location is specified, otherwise a path to the library
[ "Extract", "library", "locations", "from", "a", "configuration", "file", "." ]
python
train
Kronuz/pyScss
scss/compiler.py
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/compiler.py#L873-L894
def _at_if(self, calculator, rule, scope, block): """ Implements @if and @else if """ # "@if" indicates whether any kind of `if` since the last `@else` has # succeeded, in which case `@else if` should be skipped if block.directive != '@if': if '@if' not in rul...
[ "def", "_at_if", "(", "self", ",", "calculator", ",", "rule", ",", "scope", ",", "block", ")", ":", "# \"@if\" indicates whether any kind of `if` since the last `@else` has", "# succeeded, in which case `@else if` should be skipped", "if", "block", ".", "directive", "!=", "...
Implements @if and @else if
[ "Implements" ]
python
train
niklasf/python-chess
chess/__init__.py
https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L2698-L2762
def parse_san(self, san: str) -> Move: """ Uses the current position as the context to parse a move in standard algebraic notation and returns the corresponding move object. The returned move is guaranteed to be either legal or a null move. :raises: :exc:`ValueError` if the SAN...
[ "def", "parse_san", "(", "self", ",", "san", ":", "str", ")", "->", "Move", ":", "# Castling.", "try", ":", "if", "san", "in", "[", "\"O-O\"", ",", "\"O-O+\"", ",", "\"O-O#\"", "]", ":", "return", "next", "(", "move", "for", "move", "in", "self", "...
Uses the current position as the context to parse a move in standard algebraic notation and returns the corresponding move object. The returned move is guaranteed to be either legal or a null move. :raises: :exc:`ValueError` if the SAN is invalid or ambiguous.
[ "Uses", "the", "current", "position", "as", "the", "context", "to", "parse", "a", "move", "in", "standard", "algebraic", "notation", "and", "returns", "the", "corresponding", "move", "object", "." ]
python
train
deschler/django-modeltranslation
modeltranslation/translator.py
https://github.com/deschler/django-modeltranslation/blob/18fec04a5105cbd83fc3759f4fda20135b3a848c/modeltranslation/translator.py#L566-L575
def get_options_for_model(self, model): """ Thin wrapper around ``_get_options_for_model`` to preserve the semantic of throwing exception for models not directly registered. """ opts = self._get_options_for_model(model) if not opts.registered and not opts.related: ...
[ "def", "get_options_for_model", "(", "self", ",", "model", ")", ":", "opts", "=", "self", ".", "_get_options_for_model", "(", "model", ")", "if", "not", "opts", ".", "registered", "and", "not", "opts", ".", "related", ":", "raise", "NotRegistered", "(", "'...
Thin wrapper around ``_get_options_for_model`` to preserve the semantic of throwing exception for models not directly registered.
[ "Thin", "wrapper", "around", "_get_options_for_model", "to", "preserve", "the", "semantic", "of", "throwing", "exception", "for", "models", "not", "directly", "registered", "." ]
python
train
summa-tx/riemann
riemann/encoding/addresses.py
https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/encoding/addresses.py#L28-L39
def _ser_script_to_sh_address(script_bytes, witness=False, cashaddr=True): ''' makes an p2sh address from a serialized script ''' if witness: script_hash = utils.sha256(script_bytes) else: script_hash = utils.hash160(script_bytes) return _hash_to_sh_address( script_hash=s...
[ "def", "_ser_script_to_sh_address", "(", "script_bytes", ",", "witness", "=", "False", ",", "cashaddr", "=", "True", ")", ":", "if", "witness", ":", "script_hash", "=", "utils", ".", "sha256", "(", "script_bytes", ")", "else", ":", "script_hash", "=", "utils...
makes an p2sh address from a serialized script
[ "makes", "an", "p2sh", "address", "from", "a", "serialized", "script" ]
python
train
ff0000/scarlet
scarlet/cms/renders.py
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/renders.py#L47-L68
def render(self, request, redirect_url=None, **kwargs): """ Uses `self.template` to render a response. :param request: The current request object. :param redirect_url: If given this will return the \ redirect method instead of rendering the normal template. \ Renders pro...
[ "def", "render", "(", "self", ",", "request", ",", "redirect_url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "redirect_url", ":", "# Redirection is used when we click on `Save` for ordering", "# items on `ListView`. `kwargs` contains `message` but that", "# one ...
Uses `self.template` to render a response. :param request: The current request object. :param redirect_url: If given this will return the \ redirect method instead of rendering the normal template. \ Renders providing this argument are referred to as a \ 'render redirect' in thi...
[ "Uses", "self", ".", "template", "to", "render", "a", "response", "." ]
python
train
choderalab/pymbar
pymbar/utils.py
https://github.com/choderalab/pymbar/blob/69d1f0ff680e9ac1c6a51a5a207ea28f3ed86740/pymbar/utils.py#L128-L226
def ensure_type(val, dtype, ndim, name, length=None, can_be_none=False, shape=None, warn_on_cast=True, add_newaxis_on_deficient_ndim=False): """Typecheck the size, shape and dtype of a numpy array, with optional casting. Parameters ---------- val : {np.ndaraay, None} The arr...
[ "def", "ensure_type", "(", "val", ",", "dtype", ",", "ndim", ",", "name", ",", "length", "=", "None", ",", "can_be_none", "=", "False", ",", "shape", "=", "None", ",", "warn_on_cast", "=", "True", ",", "add_newaxis_on_deficient_ndim", "=", "False", ")", ...
Typecheck the size, shape and dtype of a numpy array, with optional casting. Parameters ---------- val : {np.ndaraay, None} The array to check dtype : {nd.dtype, str} The dtype you'd like the array to have ndim : int The number of dimensions you'd like the array to have ...
[ "Typecheck", "the", "size", "shape", "and", "dtype", "of", "a", "numpy", "array", "with", "optional", "casting", "." ]
python
train
OCR-D/core
ocrd_utils/ocrd_utils/logging.py
https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/logging.py#L43-L65
def setOverrideLogLevel(lvl): """ Override all logger filter levels to include lvl and above. - Set root logger level - iterates all existing loggers and sets their log level to ``NOTSET``. Args: lvl (string): Log level name. """ if lvl is None: return logging.info('Ov...
[ "def", "setOverrideLogLevel", "(", "lvl", ")", ":", "if", "lvl", "is", "None", ":", "return", "logging", ".", "info", "(", "'Overriding log level globally to %s'", ",", "lvl", ")", "lvl", "=", "getLevelName", "(", "lvl", ")", "global", "_overrideLogLevel", "# ...
Override all logger filter levels to include lvl and above. - Set root logger level - iterates all existing loggers and sets their log level to ``NOTSET``. Args: lvl (string): Log level name.
[ "Override", "all", "logger", "filter", "levels", "to", "include", "lvl", "and", "above", "." ]
python
train
SystemRDL/systemrdl-compiler
systemrdl/rdltypes.py
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L147-L174
def get_html_desc(self, markdown_inst=None): """ Translates the enum's 'desc' property into HTML. Any RDLFormatCode tags used in the description are converted to HTML. The text is also fed through a Markdown processor. The additional Markdown processing allows designers the cho...
[ "def", "get_html_desc", "(", "self", ",", "markdown_inst", "=", "None", ")", ":", "desc_str", "=", "self", ".", "_rdl_desc_", "if", "desc_str", "is", "None", ":", "return", "None", "return", "rdlformatcode", ".", "rdlfc_to_html", "(", "desc_str", ",", "md", ...
Translates the enum's 'desc' property into HTML. Any RDLFormatCode tags used in the description are converted to HTML. The text is also fed through a Markdown processor. The additional Markdown processing allows designers the choice to use a more modern lightweight markup language as a...
[ "Translates", "the", "enum", "s", "desc", "property", "into", "HTML", "." ]
python
train
pricingassistant/mrq
mrq/job.py
https://github.com/pricingassistant/mrq/blob/d0a5a34de9cba38afa94fb7c9e17f9b570b79a50/mrq/job.py#L614-L654
def trace_memory_stop(self): """ Stops measuring memory consumption """ self.trace_memory_clean_caches() objgraph.show_growth(limit=30) trace_type = context.get_current_config()["trace_memory_type"] if trace_type: filename = '%s/%s-%s.png' % ( cont...
[ "def", "trace_memory_stop", "(", "self", ")", ":", "self", ".", "trace_memory_clean_caches", "(", ")", "objgraph", ".", "show_growth", "(", "limit", "=", "30", ")", "trace_type", "=", "context", ".", "get_current_config", "(", ")", "[", "\"trace_memory_type\"", ...
Stops measuring memory consumption
[ "Stops", "measuring", "memory", "consumption" ]
python
train
AaronWatters/jp_proxy_widget
jp_proxy_widget/watcher.py
https://github.com/AaronWatters/jp_proxy_widget/blob/e53789c9b8a587e2f6e768d16b68e0ae5b3790d9/jp_proxy_widget/watcher.py#L124-L144
def changed_path(self): "Find any changed path and update all changed modification times." result = None # default for path in self.paths_to_modification_times: lastmod = self.paths_to_modification_times[path] mod = os.path.getmtime(path) if mod > lastmod: ...
[ "def", "changed_path", "(", "self", ")", ":", "result", "=", "None", "# default", "for", "path", "in", "self", ".", "paths_to_modification_times", ":", "lastmod", "=", "self", ".", "paths_to_modification_times", "[", "path", "]", "mod", "=", "os", ".", "path...
Find any changed path and update all changed modification times.
[ "Find", "any", "changed", "path", "and", "update", "all", "changed", "modification", "times", "." ]
python
train
penguinmenac3/starttf
starttf/utils/model_io.py
https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/utils/model_io.py#L75-L94
def load_graph(frozen_graph_filename, namespace_prefix="", placeholders=None): """ Loads a frozen graph from a *.pb file. :param frozen_graph_filename: The file which graph to load. :param namespace_prefix: A namespace for your graph to live in. This is useful when having multiple models. :param pla...
[ "def", "load_graph", "(", "frozen_graph_filename", ",", "namespace_prefix", "=", "\"\"", ",", "placeholders", "=", "None", ")", ":", "# Load graph def from protobuff and import the definition", "with", "tf", ".", "gfile", ".", "GFile", "(", "frozen_graph_filename", ",",...
Loads a frozen graph from a *.pb file. :param frozen_graph_filename: The file which graph to load. :param namespace_prefix: A namespace for your graph to live in. This is useful when having multiple models. :param placeholders: A dict containing the new placeholders that replace the old inputs. :return:...
[ "Loads", "a", "frozen", "graph", "from", "a", "*", ".", "pb", "file", ".", ":", "param", "frozen_graph_filename", ":", "The", "file", "which", "graph", "to", "load", ".", ":", "param", "namespace_prefix", ":", "A", "namespace", "for", "your", "graph", "t...
python
train
dankelley/nota
nota/notaclass.py
https://github.com/dankelley/nota/blob/245cd575db60daaea6eebd5edc1d048c5fe23c9b/nota/notaclass.py#L280-L286
def book_number(self, name): '''Return number of book with given name.''' try: number = self.cur.execute("SELECT number FROM book WHERE name= ?;", [name]).fetchone() except: self.error("cannot look up number of book with name %s" % name) return(number)
[ "def", "book_number", "(", "self", ",", "name", ")", ":", "try", ":", "number", "=", "self", ".", "cur", ".", "execute", "(", "\"SELECT number FROM book WHERE name= ?;\"", ",", "[", "name", "]", ")", ".", "fetchone", "(", ")", "except", ":", "self", ".",...
Return number of book with given name.
[ "Return", "number", "of", "book", "with", "given", "name", "." ]
python
train
DerwenAI/pytextrank
pytextrank/pytextrank.py
https://github.com/DerwenAI/pytextrank/blob/181ea41375d29922eb96768cf6550e57a77a0c95/pytextrank/pytextrank.py#L432-L443
def collect_keyword (sent, ranks, stopwords): """ iterator for collecting the single-word keyphrases """ for w in sent: if (w.word_id > 0) and (w.root in ranks) and (w.pos[0] in "NV") and (w.root not in stopwords): rl = RankedLexeme(text=w.raw.lower(), rank=ranks[w.root]/2.0, ids=[w....
[ "def", "collect_keyword", "(", "sent", ",", "ranks", ",", "stopwords", ")", ":", "for", "w", "in", "sent", ":", "if", "(", "w", ".", "word_id", ">", "0", ")", "and", "(", "w", ".", "root", "in", "ranks", ")", "and", "(", "w", ".", "pos", "[", ...
iterator for collecting the single-word keyphrases
[ "iterator", "for", "collecting", "the", "single", "-", "word", "keyphrases" ]
python
valid
captin411/ofxclient
ofxclient/config.py
https://github.com/captin411/ofxclient/blob/4da2719f0ecbbf5eee62fb82c1b3b34ec955ee5e/ofxclient/config.py#L279-L283
def save(self): """Save changes to config file""" with open(self.file_name, 'w') as fp: self.parser.write(fp) return self
[ "def", "save", "(", "self", ")", ":", "with", "open", "(", "self", ".", "file_name", ",", "'w'", ")", "as", "fp", ":", "self", ".", "parser", ".", "write", "(", "fp", ")", "return", "self" ]
Save changes to config file
[ "Save", "changes", "to", "config", "file" ]
python
train
bwohlberg/sporco
sporco/prox/_lp.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/prox/_lp.py#L29-L64
def norm_l0(x, axis=None, eps=0.0): r"""Compute the :math:`\ell_0` "norm" (it is not really a norm) .. math:: \| \mathbf{x} \|_0 = \sum_i \left\{ \begin{array}{ccc} 0 & \text{if} & x_i = 0 \\ 1 &\text{if} & x_i \neq 0 \end{array} \right. where :math:`x_i` is element :math:`i` of vector :ma...
[ "def", "norm_l0", "(", "x", ",", "axis", "=", "None", ",", "eps", "=", "0.0", ")", ":", "nl0", "=", "np", ".", "sum", "(", "np", ".", "abs", "(", "x", ")", ">", "eps", ",", "axis", "=", "axis", ",", "keepdims", "=", "True", ")", "# If the res...
r"""Compute the :math:`\ell_0` "norm" (it is not really a norm) .. math:: \| \mathbf{x} \|_0 = \sum_i \left\{ \begin{array}{ccc} 0 & \text{if} & x_i = 0 \\ 1 &\text{if} & x_i \neq 0 \end{array} \right. where :math:`x_i` is element :math:`i` of vector :math:`\mathbf{x}`. Parameters --...
[ "r", "Compute", "the", ":", "math", ":", "\\", "ell_0", "norm", "(", "it", "is", "not", "really", "a", "norm", ")" ]
python
train
TUT-ARG/sed_eval
sed_eval/sound_event.py
https://github.com/TUT-ARG/sed_eval/blob/0cb1b6d11ceec4fe500cc9b31079c9d8666ed6eb/sed_eval/sound_event.py#L1233-L1575
def evaluate(self, reference_event_list, estimated_event_list): """Evaluate file pair (reference and estimated) Parameters ---------- reference_event_list : event list Reference event list estimated_event_list : event list Estimated event list ...
[ "def", "evaluate", "(", "self", ",", "reference_event_list", ",", "estimated_event_list", ")", ":", "# Make sure input is dcase_util.containers.MetaDataContainer", "if", "not", "isinstance", "(", "reference_event_list", ",", "dcase_util", ".", "containers", ".", "MetaDataCo...
Evaluate file pair (reference and estimated) Parameters ---------- reference_event_list : event list Reference event list estimated_event_list : event list Estimated event list Returns ------- self
[ "Evaluate", "file", "pair", "(", "reference", "and", "estimated", ")" ]
python
train
Esri/ArcREST
src/arcrest/ags/_geoprocessing.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_geoprocessing.py#L289-L342
def submitJob(self, inputs, method="POST", outSR=None, processSR=None, returnZ=False, returnM=False): """ submits a job to the current task, and returns a job ID Inputs: inputs - list of GP object values method - string - eith...
[ "def", "submitJob", "(", "self", ",", "inputs", ",", "method", "=", "\"POST\"", ",", "outSR", "=", "None", ",", "processSR", "=", "None", ",", "returnZ", "=", "False", ",", "returnM", "=", "False", ")", ":", "url", "=", "self", ".", "_url", "+", "\...
submits a job to the current task, and returns a job ID Inputs: inputs - list of GP object values method - string - either GET or POST. The way the service is submitted. outSR - spatial reference of output geometries processSR - ...
[ "submits", "a", "job", "to", "the", "current", "task", "and", "returns", "a", "job", "ID", "Inputs", ":", "inputs", "-", "list", "of", "GP", "object", "values", "method", "-", "string", "-", "either", "GET", "or", "POST", ".", "The", "way", "the", "s...
python
train
tensorflow/tensor2tensor
tensor2tensor/insights/graph.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/insights/graph.py#L102-L110
def new_vertex(self): """Creates and returns a new vertex. Returns: A new Vertex instance with a unique index. """ vertex = Vertex(len(self.vertices)) self.vertices.append(vertex) return vertex
[ "def", "new_vertex", "(", "self", ")", ":", "vertex", "=", "Vertex", "(", "len", "(", "self", ".", "vertices", ")", ")", "self", ".", "vertices", ".", "append", "(", "vertex", ")", "return", "vertex" ]
Creates and returns a new vertex. Returns: A new Vertex instance with a unique index.
[ "Creates", "and", "returns", "a", "new", "vertex", "." ]
python
train
google/brotli
research/brotlidump.py
https://github.com/google/brotli/blob/4b2b2d4f83ffeaac7708e44409fe34896a01a278/research/brotlidump.py#L1269-L1279
def word(self, size, dist): """Get word """ #split dist in index and action ndbits = self.NDBITS[size] index = dist&(1<<ndbits)-1 action = dist>>ndbits #compute position in file position = sum(n<<self.NDBITS[n] for n in range(4,size))+size*index se...
[ "def", "word", "(", "self", ",", "size", ",", "dist", ")", ":", "#split dist in index and action", "ndbits", "=", "self", ".", "NDBITS", "[", "size", "]", "index", "=", "dist", "&", "(", "1", "<<", "ndbits", ")", "-", "1", "action", "=", "dist", ">>"...
Get word
[ "Get", "word" ]
python
test
martinpitt/python-dbusmock
dbusmock/mockobject.py
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L581-L618
def format_args(self, args): '''Format a D-Bus argument tuple into an appropriate logging string.''' def format_arg(a): if isinstance(a, dbus.Boolean): return str(bool(a)) if isinstance(a, dbus.Byte): return str(int(a)) if isinstance(a...
[ "def", "format_args", "(", "self", ",", "args", ")", ":", "def", "format_arg", "(", "a", ")", ":", "if", "isinstance", "(", "a", ",", "dbus", ".", "Boolean", ")", ":", "return", "str", "(", "bool", "(", "a", ")", ")", "if", "isinstance", "(", "a"...
Format a D-Bus argument tuple into an appropriate logging string.
[ "Format", "a", "D", "-", "Bus", "argument", "tuple", "into", "an", "appropriate", "logging", "string", "." ]
python
train
edeposit/edeposit.amqp
bin/edeposit_amqp_storaged.py
https://github.com/edeposit/edeposit.amqp/blob/7804b52028b90ab96302d54bc2430f88dc2ebf64/bin/edeposit_amqp_storaged.py#L36-L54
def main(args, stop=False): """ Arguments parsing, etc.. """ daemon = AMQPDaemon( con_param=getConParams( settings.RABBITMQ_STORAGE_VIRTUALHOST ), queue=settings.RABBITMQ_STORAGE_INPUT_QUEUE, out_exch=settings.RABBITMQ_STORAGE_EXCHANGE, out_key=setting...
[ "def", "main", "(", "args", ",", "stop", "=", "False", ")", ":", "daemon", "=", "AMQPDaemon", "(", "con_param", "=", "getConParams", "(", "settings", ".", "RABBITMQ_STORAGE_VIRTUALHOST", ")", ",", "queue", "=", "settings", ".", "RABBITMQ_STORAGE_INPUT_QUEUE", ...
Arguments parsing, etc..
[ "Arguments", "parsing", "etc", ".." ]
python
train
Toilal/rebulk
rebulk/utils.py
https://github.com/Toilal/rebulk/blob/7511a4671f2fd9493e3df1e5177b7656789069e8/rebulk/utils.py#L14-L56
def find_all(string, sub, start=None, end=None, ignore_case=False, **kwargs): """ Return all indices in string s where substring sub is found, such that sub is contained in the slice s[start:end]. >>> list(find_all('The quick brown fox jumps over the lazy dog', 'fox')) [16] >>> list(find_all('...
[ "def", "find_all", "(", "string", ",", "sub", ",", "start", "=", "None", ",", "end", "=", "None", ",", "ignore_case", "=", "False", ",", "*", "*", "kwargs", ")", ":", "#pylint: disable=unused-argument", "if", "ignore_case", ":", "sub", "=", "sub", ".", ...
Return all indices in string s where substring sub is found, such that sub is contained in the slice s[start:end]. >>> list(find_all('The quick brown fox jumps over the lazy dog', 'fox')) [16] >>> list(find_all('The quick brown fox jumps over the lazy dog', 'mountain')) [] >>> list(find_all('...
[ "Return", "all", "indices", "in", "string", "s", "where", "substring", "sub", "is", "found", "such", "that", "sub", "is", "contained", "in", "the", "slice", "s", "[", "start", ":", "end", "]", "." ]
python
train
PmagPy/PmagPy
pmagpy/command_line_extractor.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/command_line_extractor.py#L50-L83
def check_args(arguments, data_frame): """ check arguments against a command_line_dataframe. checks that: all arguments are valid all required arguments are present default values are used where needed """ stripped_args = [a[0] for a in arguments] df = data_frame.df # first make ...
[ "def", "check_args", "(", "arguments", ",", "data_frame", ")", ":", "stripped_args", "=", "[", "a", "[", "0", "]", "for", "a", "in", "arguments", "]", "df", "=", "data_frame", ".", "df", "# first make sure all args are valid", "for", "a", "in", "arguments", ...
check arguments against a command_line_dataframe. checks that: all arguments are valid all required arguments are present default values are used where needed
[ "check", "arguments", "against", "a", "command_line_dataframe", ".", "checks", "that", ":", "all", "arguments", "are", "valid", "all", "required", "arguments", "are", "present", "default", "values", "are", "used", "where", "needed" ]
python
train
apple/turicreate
src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py#L341-L362
def _load_version(cls, state, version): """ A function to load a previously saved ImageClassifier instance. """ _tkutl._model_version_check(version, cls._PYTHON_IMAGE_CLASSIFIER_VERSION) from turicreate.toolkits.classifier.logistic_classifier import LogisticClassifier ...
[ "def", "_load_version", "(", "cls", ",", "state", ",", "version", ")", ":", "_tkutl", ".", "_model_version_check", "(", "version", ",", "cls", ".", "_PYTHON_IMAGE_CLASSIFIER_VERSION", ")", "from", "turicreate", ".", "toolkits", ".", "classifier", ".", "logistic_...
A function to load a previously saved ImageClassifier instance.
[ "A", "function", "to", "load", "a", "previously", "saved", "ImageClassifier", "instance", "." ]
python
train
acorg/dark-matter
dark/reads.py
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/reads.py#L1374-L1394
def summarizePosition(self, index): """ Compute residue counts at a specific sequence index. @param index: an C{int} index into the sequence. @return: A C{dict} with the count of too-short (excluded) sequences, and a Counter instance giving the residue counts. """ ...
[ "def", "summarizePosition", "(", "self", ",", "index", ")", ":", "countAtPosition", "=", "Counter", "(", ")", "excludedCount", "=", "0", "for", "read", "in", "self", ":", "try", ":", "countAtPosition", "[", "read", ".", "sequence", "[", "index", "]", "]"...
Compute residue counts at a specific sequence index. @param index: an C{int} index into the sequence. @return: A C{dict} with the count of too-short (excluded) sequences, and a Counter instance giving the residue counts.
[ "Compute", "residue", "counts", "at", "a", "specific", "sequence", "index", "." ]
python
train
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/api/apiregistration_v1beta1_api.py
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/apiregistration_v1beta1_api.py#L35-L58
def create_api_service(self, body, **kwargs): # noqa: E501 """create_api_service # noqa: E501 create an APIService # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_ap...
[ "def", "create_api_service", "(", "self", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "create_...
create_api_service # noqa: E501 create an APIService # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_api_service(body, async_req=True) >>> result = thread.get() ...
[ "create_api_service", "#", "noqa", ":", "E501" ]
python
train
danilobellini/audiolazy
setup.py
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/setup.py#L55-L67
def read_rst_and_process(fname, line_process=lambda line: line): """ The reStructuredText string in file ``fname``, without the starting ``..`` comment and with ``line_process`` function applied to every line. """ with open(fname, "r") as f: data = f.read().splitlines() first_idx = next(idx for idx, lin...
[ "def", "read_rst_and_process", "(", "fname", ",", "line_process", "=", "lambda", "line", ":", "line", ")", ":", "with", "open", "(", "fname", ",", "\"r\"", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", ".", "splitlines", "(", ")", "...
The reStructuredText string in file ``fname``, without the starting ``..`` comment and with ``line_process`` function applied to every line.
[ "The", "reStructuredText", "string", "in", "file", "fname", "without", "the", "starting", "..", "comment", "and", "with", "line_process", "function", "applied", "to", "every", "line", "." ]
python
train
spyder-ide/spyder
spyder/utils/external/github.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/external/github.py#L184-L200
def authorize_url(self, state=None): ''' Generate authorize_url. >>> GitHub(client_id='3ebf94c5776d565bcf75').authorize_url() 'https://github.com/login/oauth/authorize?client_id=3ebf94c5776d565bcf75' ''' if not self._client_id: raise ApiAuthError('No client i...
[ "def", "authorize_url", "(", "self", ",", "state", "=", "None", ")", ":", "if", "not", "self", ".", "_client_id", ":", "raise", "ApiAuthError", "(", "'No client id.'", ")", "kw", "=", "dict", "(", "client_id", "=", "self", ".", "_client_id", ")", "if", ...
Generate authorize_url. >>> GitHub(client_id='3ebf94c5776d565bcf75').authorize_url() 'https://github.com/login/oauth/authorize?client_id=3ebf94c5776d565bcf75'
[ "Generate", "authorize_url", "." ]
python
train
pyapi-gitlab/pyapi-gitlab
gitlab/__init__.py
https://github.com/pyapi-gitlab/pyapi-gitlab/blob/f74b6fb5c13cecae9524997847e928905cc60acf/gitlab/__init__.py#L221-L252
def createprojectuser(self, user_id, name, **kwargs): """ Creates a new project owned by the specified user. Available only for admins. :param user_id: user_id of owner :param name: new project name :param description: short project description :param default_branch: 'ma...
[ "def", "createprojectuser", "(", "self", ",", "user_id", ",", "name", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "'name'", ":", "name", "}", "if", "kwargs", ":", "data", ".", "update", "(", "kwargs", ")", "request", "=", "requests", ".", ...
Creates a new project owned by the specified user. Available only for admins. :param user_id: user_id of owner :param name: new project name :param description: short project description :param default_branch: 'master' by default :param issues_enabled: :param merge_reque...
[ "Creates", "a", "new", "project", "owned", "by", "the", "specified", "user", ".", "Available", "only", "for", "admins", "." ]
python
train
mistio/mist.client
src/mistclient/model.py
https://github.com/mistio/mist.client/blob/bc190af2cba358fa556a69b205c12a77a34eb2a8/src/mistclient/model.py#L90-L103
def disable(self): """ Disable the Cloud. :returns: A list of mist.clients' updated clouds. """ payload = { "new_state": "0" } data = json.dumps(payload) req = self.request(self.mist_client.uri+'/clouds/'+self.id, data=data) req.post(...
[ "def", "disable", "(", "self", ")", ":", "payload", "=", "{", "\"new_state\"", ":", "\"0\"", "}", "data", "=", "json", ".", "dumps", "(", "payload", ")", "req", "=", "self", ".", "request", "(", "self", ".", "mist_client", ".", "uri", "+", "'/clouds/...
Disable the Cloud. :returns: A list of mist.clients' updated clouds.
[ "Disable", "the", "Cloud", "." ]
python
train
wcember/pypub
pypub/clean.py
https://github.com/wcember/pypub/blob/88a1adc2ccf6f02c33adea1d2d52c729128216fb/pypub/clean.py#L99-L118
def condense(input_string): """ Trims leadings and trailing whitespace between tags in an html document Args: input_string: A (possible unicode) string representing HTML. Returns: A (possibly unicode) string representing HTML. Raises: TypeError: Raised if input_string isn'...
[ "def", "condense", "(", "input_string", ")", ":", "try", ":", "assert", "isinstance", "(", "input_string", ",", "basestring", ")", "except", "AssertionError", ":", "raise", "TypeError", "removed_leading_whitespace", "=", "re", ".", "sub", "(", "'>\\s+'", ",", ...
Trims leadings and trailing whitespace between tags in an html document Args: input_string: A (possible unicode) string representing HTML. Returns: A (possibly unicode) string representing HTML. Raises: TypeError: Raised if input_string isn't a unicode string or string.
[ "Trims", "leadings", "and", "trailing", "whitespace", "between", "tags", "in", "an", "html", "document" ]
python
train
slackapi/python-slackclient
slack/web/client.py
https://github.com/slackapi/python-slackclient/blob/901341c0284fd81e6d2719d6a0502308760d83e4/slack/web/client.py#L879-L886
def mpim_history(self, *, channel: str, **kwargs) -> SlackResponse: """Fetches history of messages and events from a multiparty direct message. Args: channel (str): Multiparty direct message to fetch history for. e.g. 'G1234567890' """ kwargs.update({"channel": channel}) ...
[ "def", "mpim_history", "(", "self", ",", "*", ",", "channel", ":", "str", ",", "*", "*", "kwargs", ")", "->", "SlackResponse", ":", "kwargs", ".", "update", "(", "{", "\"channel\"", ":", "channel", "}", ")", "return", "self", ".", "api_call", "(", "\...
Fetches history of messages and events from a multiparty direct message. Args: channel (str): Multiparty direct message to fetch history for. e.g. 'G1234567890'
[ "Fetches", "history", "of", "messages", "and", "events", "from", "a", "multiparty", "direct", "message", "." ]
python
train
tensorflow/tensorboard
tensorboard/plugins/graph/keras_util.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/graph/keras_util.py#L48-L65
def _walk_layers(keras_layer): """Walks the nested keras layer configuration in preorder. Args: keras_layer: Keras configuration from model.to_json. Yields: A tuple of (name_scope, layer_config). name_scope: a string representing a scope name, similar to that of tf.name_scope. layer_config: a dic...
[ "def", "_walk_layers", "(", "keras_layer", ")", ":", "yield", "(", "''", ",", "keras_layer", ")", "if", "keras_layer", ".", "get", "(", "'config'", ")", ".", "get", "(", "'layers'", ")", ":", "name_scope", "=", "keras_layer", ".", "get", "(", "'config'",...
Walks the nested keras layer configuration in preorder. Args: keras_layer: Keras configuration from model.to_json. Yields: A tuple of (name_scope, layer_config). name_scope: a string representing a scope name, similar to that of tf.name_scope. layer_config: a dict representing a Keras layer configu...
[ "Walks", "the", "nested", "keras", "layer", "configuration", "in", "preorder", ".", "Args", ":", "keras_layer", ":", "Keras", "configuration", "from", "model", ".", "to_json", "." ]
python
train
Capitains/flask-capitains-nemo
flask_nemo/__init__.py
https://github.com/Capitains/flask-capitains-nemo/blob/8d91f2c05b925a6c8ea8c997baf698c87257bc58/flask_nemo/__init__.py#L570-L593
def r_collection(self, objectId, lang=None): """ Collection content browsing route function :param objectId: Collection identifier :type objectId: str :param lang: Lang in which to express main data :type lang: str :return: Template and collections contained in given col...
[ "def", "r_collection", "(", "self", ",", "objectId", ",", "lang", "=", "None", ")", ":", "collection", "=", "self", ".", "resolver", ".", "getMetadata", "(", "objectId", ")", "return", "{", "\"template\"", ":", "\"main::collection.html\"", ",", "\"collections\...
Collection content browsing route function :param objectId: Collection identifier :type objectId: str :param lang: Lang in which to express main data :type lang: str :return: Template and collections contained in given collection :rtype: {str: Any}
[ "Collection", "content", "browsing", "route", "function" ]
python
valid
proycon/pynlpl
pynlpl/formats/folia.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L3015-L3044
def annotations(self,Class,set=None): """Obtain child elements (annotations) of the specified class. A further restriction can be made based on set. Arguments: Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement` Se...
[ "def", "annotations", "(", "self", ",", "Class", ",", "set", "=", "None", ")", ":", "found", "=", "False", "for", "e", "in", "self", ".", "select", "(", "Class", ",", "set", ",", "True", ",", "default_ignore_annotations", ")", ":", "found", "=", "Tru...
Obtain child elements (annotations) of the specified class. A further restriction can be made based on set. Arguments: Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement` Set (str): The set to match against, only elements ...
[ "Obtain", "child", "elements", "(", "annotations", ")", "of", "the", "specified", "class", "." ]
python
train
seung-lab/cloud-volume
cloudvolume/cloudvolume.py
https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L743-L770
def bbox_to_mip(self, bbox, mip, to_mip): """Convert bbox or slices from one mip level to another.""" if not type(bbox) is Bbox: bbox = lib.generate_slices( bbox, self.mip_bounds(mip).minpt, self.mip_bounds(mip).maxpt, bounded=False ) bbox = Bbox.from_slices(...
[ "def", "bbox_to_mip", "(", "self", ",", "bbox", ",", "mip", ",", "to_mip", ")", ":", "if", "not", "type", "(", "bbox", ")", "is", "Bbox", ":", "bbox", "=", "lib", ".", "generate_slices", "(", "bbox", ",", "self", ".", "mip_bounds", "(", "mip", ")",...
Convert bbox or slices from one mip level to another.
[ "Convert", "bbox", "or", "slices", "from", "one", "mip", "level", "to", "another", "." ]
python
train
newville/wxmplot
examples/tifffile.py
https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L2665-L2807
def main(argv=None): """Command line usage main function.""" if float(sys.version[0:3]) < 2.6: print("This script requires Python version 2.6 or better.") print("This is Python version %s" % sys.version) return 0 if argv is None: argv = sys.argv import re import optp...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "float", "(", "sys", ".", "version", "[", "0", ":", "3", "]", ")", "<", "2.6", ":", "print", "(", "\"This script requires Python version 2.6 or better.\"", ")", "print", "(", "\"This is Python version ...
Command line usage main function.
[ "Command", "line", "usage", "main", "function", "." ]
python
train
crackinglandia/pype32
pype32/pype32.py
https://github.com/crackinglandia/pype32/blob/192fd14dfc0dd36d953739a81c17fbaf5e3d6076/pype32/pype32.py#L534-L616
def extendSection(self, sectionIndex, data): """ Extends an existing section in the L{PE} instance. @type sectionIndex: int @param sectionIndex: The index for the section to be extended. @type data: str @param data: The data to include in the section. ...
[ "def", "extendSection", "(", "self", ",", "sectionIndex", ",", "data", ")", ":", "fa", "=", "self", ".", "ntHeaders", ".", "optionalHeader", ".", "fileAlignment", ".", "value", "sa", "=", "self", ".", "ntHeaders", ".", "optionalHeader", ".", "sectionAlignmen...
Extends an existing section in the L{PE} instance. @type sectionIndex: int @param sectionIndex: The index for the section to be extended. @type data: str @param data: The data to include in the section. @raise IndexError: If an invalid C{sectionIndex} w...
[ "Extends", "an", "existing", "section", "in", "the", "L", "{", "PE", "}", "instance", "." ]
python
train
openstack/proliantutils
proliantutils/ilo/ris.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ris.py#L387-L425
def _get_drive_resource(self, drive_name): """Gets the DiskDrive resource if exists. :param drive_name: can be either "PhysicalDrives" or "LogicalDrives". :returns the list of drives. :raises: IloCommandNotSupportedError if the given drive resource doesn't exist...
[ "def", "_get_drive_resource", "(", "self", ",", "drive_name", ")", ":", "disk_details_list", "=", "[", "]", "array_uri_links", "=", "self", ".", "_create_list_of_array_controllers", "(", ")", "for", "array_link", "in", "array_uri_links", ":", "_", ",", "_", ",",...
Gets the DiskDrive resource if exists. :param drive_name: can be either "PhysicalDrives" or "LogicalDrives". :returns the list of drives. :raises: IloCommandNotSupportedError if the given drive resource doesn't exist. :raises: IloError, on an error from iLO.
[ "Gets", "the", "DiskDrive", "resource", "if", "exists", "." ]
python
train
fmfn/BayesianOptimization
examples/async_optimization.py
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/examples/async_optimization.py#L42-L57
def post(self): """Deal with incoming requests.""" body = tornado.escape.json_decode(self.request.body) try: self._bo.register( params=body["params"], target=body["target"], ) print("BO has registered: {} points.".format(len(se...
[ "def", "post", "(", "self", ")", ":", "body", "=", "tornado", ".", "escape", ".", "json_decode", "(", "self", ".", "request", ".", "body", ")", "try", ":", "self", ".", "_bo", ".", "register", "(", "params", "=", "body", "[", "\"params\"", "]", ","...
Deal with incoming requests.
[ "Deal", "with", "incoming", "requests", "." ]
python
train
Titan-C/slaveparticles
slaveparticles/spins.py
https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/spins.py#L42-L58
def spinflipandhop(slaves): """Calculates the interaction term of a spin flip and pair hopping""" Sdw = [csr_matrix(spin_gen(slaves, i, 0)) for i in range(slaves)] Sup = [mat.T for mat in Sdw] sfh = np.zeros_like(Sup[0]) orbitals = slaves//2 for n in range(orbitals): for m in range(n+1...
[ "def", "spinflipandhop", "(", "slaves", ")", ":", "Sdw", "=", "[", "csr_matrix", "(", "spin_gen", "(", "slaves", ",", "i", ",", "0", ")", ")", "for", "i", "in", "range", "(", "slaves", ")", "]", "Sup", "=", "[", "mat", ".", "T", "for", "mat", "...
Calculates the interaction term of a spin flip and pair hopping
[ "Calculates", "the", "interaction", "term", "of", "a", "spin", "flip", "and", "pair", "hopping" ]
python
train
evandempsey/fp-growth
pyfpgrowth/pyfpgrowth.py
https://github.com/evandempsey/fp-growth/blob/6bf4503024e86c5bbea8a05560594f2f7f061c15/pyfpgrowth/pyfpgrowth.py#L256-L278
def generate_association_rules(patterns, confidence_threshold): """ Given a set of frequent itemsets, return a dict of association rules in the form {(left): ((right), confidence)} """ rules = {} for itemset in patterns.keys(): upper_support = patterns[itemset] for i in rang...
[ "def", "generate_association_rules", "(", "patterns", ",", "confidence_threshold", ")", ":", "rules", "=", "{", "}", "for", "itemset", "in", "patterns", ".", "keys", "(", ")", ":", "upper_support", "=", "patterns", "[", "itemset", "]", "for", "i", "in", "r...
Given a set of frequent itemsets, return a dict of association rules in the form {(left): ((right), confidence)}
[ "Given", "a", "set", "of", "frequent", "itemsets", "return", "a", "dict", "of", "association", "rules", "in", "the", "form", "{", "(", "left", ")", ":", "((", "right", ")", "confidence", ")", "}" ]
python
train
pypa/pipenv
pipenv/patched/notpip/_internal/wheel.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/wheel.py#L727-L733
def _contains_egg_info( s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s))
[ "def", "_contains_egg_info", "(", "s", ",", "_egg_info_re", "=", "re", ".", "compile", "(", "r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)'", ",", "re", ".", "I", ")", ")", ":", "return", "bool", "(", "_egg_info_re", ".", "search", "(", "s", ")", ")" ]
Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1
[ "Determine", "whether", "the", "string", "looks", "like", "an", "egg_info", "." ]
python
train
markuskiller/textblob-de
textblob_de/blob.py
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/blob.py#L748-L779
def _create_sentence_objects(self): """Returns a list of Sentence objects from the raw text.""" sentence_objects = [] sentences = sent_tokenize(self.raw, tokenizer=self.tokenizer) char_index = 0 # Keeps track of character index within the blob for sent in sentences: ...
[ "def", "_create_sentence_objects", "(", "self", ")", ":", "sentence_objects", "=", "[", "]", "sentences", "=", "sent_tokenize", "(", "self", ".", "raw", ",", "tokenizer", "=", "self", ".", "tokenizer", ")", "char_index", "=", "0", "# Keeps track of character ind...
Returns a list of Sentence objects from the raw text.
[ "Returns", "a", "list", "of", "Sentence", "objects", "from", "the", "raw", "text", "." ]
python
train
wonambi-python/wonambi
wonambi/viz/base.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/viz/base.py#L30-L37
def _repr_png_(self): """This is used by ipython to plot inline. """ app.process_events() QApplication.processEvents() img = read_pixels() return bytes(_make_png(img))
[ "def", "_repr_png_", "(", "self", ")", ":", "app", ".", "process_events", "(", ")", "QApplication", ".", "processEvents", "(", ")", "img", "=", "read_pixels", "(", ")", "return", "bytes", "(", "_make_png", "(", "img", ")", ")" ]
This is used by ipython to plot inline.
[ "This", "is", "used", "by", "ipython", "to", "plot", "inline", "." ]
python
train
miquelo/resort
packages/resort/component/glassfish.py
https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/component/glassfish.py#L680-L699
def available(self, context): """ Resource availability. :param resort.engine.execution.Context context: Current execution context. """ try: if self.__available is None: encoded_name = urllib.parse.quote_plus(self.__name) status_code, msg = self.__endpoint.get( "/resources/custom-...
[ "def", "available", "(", "self", ",", "context", ")", ":", "try", ":", "if", "self", ".", "__available", "is", "None", ":", "encoded_name", "=", "urllib", ".", "parse", ".", "quote_plus", "(", "self", ".", "__name", ")", "status_code", ",", "msg", "=",...
Resource availability. :param resort.engine.execution.Context context: Current execution context.
[ "Resource", "availability", ".", ":", "param", "resort", ".", "engine", ".", "execution", ".", "Context", "context", ":", "Current", "execution", "context", "." ]
python
train
alberanid/python-iplib
iplib.py
https://github.com/alberanid/python-iplib/blob/488b56fe57ad836b27feec9e76f51883db28faa6/iplib.py#L808-L833
def is_valid_ip(self, ip): """Return true if the given address in amongst the usable addresses, or if the given CIDR is contained in this one.""" if not isinstance(ip, (IPv4Address, CIDR)): if str(ip).find('/') == -1: ip = IPv4Address(ip) else: ...
[ "def", "is_valid_ip", "(", "self", ",", "ip", ")", ":", "if", "not", "isinstance", "(", "ip", ",", "(", "IPv4Address", ",", "CIDR", ")", ")", ":", "if", "str", "(", "ip", ")", ".", "find", "(", "'/'", ")", "==", "-", "1", ":", "ip", "=", "IPv...
Return true if the given address in amongst the usable addresses, or if the given CIDR is contained in this one.
[ "Return", "true", "if", "the", "given", "address", "in", "amongst", "the", "usable", "addresses", "or", "if", "the", "given", "CIDR", "is", "contained", "in", "this", "one", "." ]
python
valid
brenns10/tswift
tswift.py
https://github.com/brenns10/tswift/blob/f4a8f3127e088d6b3a9669496f107c2704f4d1a3/tswift.py#L156-L198
def main(): """ Run the CLI. """ parser = argparse.ArgumentParser( description='Search artists, lyrics, and songs!' ) parser.add_argument( 'artist', help='Specify an artist name (Default: Taylor Swift)', default='Taylor Swift', nargs='?', ) parser....
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Search artists, lyrics, and songs!'", ")", "parser", ".", "add_argument", "(", "'artist'", ",", "help", "=", "'Specify an artist name (Default: Taylor Swift)'", ...
Run the CLI.
[ "Run", "the", "CLI", "." ]
python
train
pyca/pynacl
src/nacl/bindings/crypto_aead.py
https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_aead.py#L70-L136
def crypto_aead_chacha20poly1305_ietf_encrypt(message, aad, nonce, key): """ Encrypt the given ``message`` using the IETF ratified chacha20poly1305 construction described in RFC7539. :param message: :type message: bytes :param aad: :type aad: bytes :param nonce: :type nonce: bytes ...
[ "def", "crypto_aead_chacha20poly1305_ietf_encrypt", "(", "message", ",", "aad", ",", "nonce", ",", "key", ")", ":", "ensure", "(", "isinstance", "(", "message", ",", "bytes", ")", ",", "'Input message type must be bytes'", ",", "raising", "=", "exc", ".", "TypeE...
Encrypt the given ``message`` using the IETF ratified chacha20poly1305 construction described in RFC7539. :param message: :type message: bytes :param aad: :type aad: bytes :param nonce: :type nonce: bytes :param key: :type key: bytes :return: authenticated ciphertext :rtype:...
[ "Encrypt", "the", "given", "message", "using", "the", "IETF", "ratified", "chacha20poly1305", "construction", "described", "in", "RFC7539", "." ]
python
train
StagPython/StagPy
stagpy/field.py
https://github.com/StagPython/StagPy/blob/18c4416cc4a1011db2fd736ee8b0ec29aa6e4fd4/stagpy/field.py#L242-L283
def cmd(): """Implementation of field subcommand. Other Parameters: conf.field conf.core """ sdat = StagyyData(conf.core.path) sovs = set_of_vars(conf.field.plot) minmax = {} if conf.plot.cminmax: conf.plot.vmin = None conf.plot.vmax = None for step i...
[ "def", "cmd", "(", ")", ":", "sdat", "=", "StagyyData", "(", "conf", ".", "core", ".", "path", ")", "sovs", "=", "set_of_vars", "(", "conf", ".", "field", ".", "plot", ")", "minmax", "=", "{", "}", "if", "conf", ".", "plot", ".", "cminmax", ":", ...
Implementation of field subcommand. Other Parameters: conf.field conf.core
[ "Implementation", "of", "field", "subcommand", "." ]
python
train
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/djitemdata.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/djitemdata.py#L1015-L1028
def data(self, column, role): """Return the data for the specified column and role The column addresses one attribute of the data. :param column: the data column :type column: int :param role: the data role :type role: QtCore.Qt.ItemDataRole :returns: data depen...
[ "def", "data", "(", "self", ",", "column", ",", "role", ")", ":", "return", "self", ".", "columns", "[", "column", "]", "(", "self", ".", "_user", ",", "role", ")" ]
Return the data for the specified column and role The column addresses one attribute of the data. :param column: the data column :type column: int :param role: the data role :type role: QtCore.Qt.ItemDataRole :returns: data depending on the role :rtype: ...
[ "Return", "the", "data", "for", "the", "specified", "column", "and", "role" ]
python
train
wummel/linkchecker
third_party/dnspython/dns/message.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/message.py#L555-L561
def set_opcode(self, opcode): """Set the opcode. @param opcode: the opcode @type opcode: int """ self.flags &= 0x87FF self.flags |= dns.opcode.to_flags(opcode)
[ "def", "set_opcode", "(", "self", ",", "opcode", ")", ":", "self", ".", "flags", "&=", "0x87FF", "self", ".", "flags", "|=", "dns", ".", "opcode", ".", "to_flags", "(", "opcode", ")" ]
Set the opcode. @param opcode: the opcode @type opcode: int
[ "Set", "the", "opcode", "." ]
python
train
PMBio/limix-backup
limix/mtSet/core/preprocessCore.py
https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/preprocessCore.py#L56-L69
def computePCsPlink(plink_path,k,out_dir,bfile,ffile): """ computing the covariance matrix via plink """ print("Using plink to compute principal components") cmd = '%s --bfile %s --pca %d '%(plink_path,bfile,k) cmd+= '--out %s'%(os.path.join(out_dir,'plink')) subprocess.call(cmd,shell=True) ...
[ "def", "computePCsPlink", "(", "plink_path", ",", "k", ",", "out_dir", ",", "bfile", ",", "ffile", ")", ":", "print", "(", "\"Using plink to compute principal components\"", ")", "cmd", "=", "'%s --bfile %s --pca %d '", "%", "(", "plink_path", ",", "bfile", ",", ...
computing the covariance matrix via plink
[ "computing", "the", "covariance", "matrix", "via", "plink" ]
python
train
datastore/datastore
datastore/core/query.py
https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/query.py#L552-L557
def apply_limit(self): '''Naively apply query limit.''' self._ensure_modification_is_safe() if self.query.limit is not None: self._iterable = limit_gen(self.query.limit, self._iterable)
[ "def", "apply_limit", "(", "self", ")", ":", "self", ".", "_ensure_modification_is_safe", "(", ")", "if", "self", ".", "query", ".", "limit", "is", "not", "None", ":", "self", ".", "_iterable", "=", "limit_gen", "(", "self", ".", "query", ".", "limit", ...
Naively apply query limit.
[ "Naively", "apply", "query", "limit", "." ]
python
train
materialsproject/pymatgen
pymatgen/io/vasp/sets.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/sets.py#L151-L170
def write_input(self, output_dir, make_dir_if_not_present=True, include_cif=False): """ Writes a set of VASP input to a directory. Args: output_dir (str): Directory to output the VASP input files make_dir_if_not_present (bool): Set to True if you want...
[ "def", "write_input", "(", "self", ",", "output_dir", ",", "make_dir_if_not_present", "=", "True", ",", "include_cif", "=", "False", ")", ":", "vinput", "=", "self", ".", "get_vasp_input", "(", ")", "vinput", ".", "write_input", "(", "output_dir", ",", "make...
Writes a set of VASP input to a directory. Args: output_dir (str): Directory to output the VASP input files make_dir_if_not_present (bool): Set to True if you want the directory (and the whole path) to be created if it is not present. include_...
[ "Writes", "a", "set", "of", "VASP", "input", "to", "a", "directory", "." ]
python
train
saltstack/salt
salt/modules/cpan.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cpan.py#L35-L63
def install(module): ''' Install a Perl module from CPAN CLI Example: .. code-block:: bash salt '*' cpan.install Template::Alloy ''' ret = { 'old': None, 'new': None, } old_info = show(module) cmd = 'cpan -i {0}'.format(module) out = __salt__['cmd.run...
[ "def", "install", "(", "module", ")", ":", "ret", "=", "{", "'old'", ":", "None", ",", "'new'", ":", "None", ",", "}", "old_info", "=", "show", "(", "module", ")", "cmd", "=", "'cpan -i {0}'", ".", "format", "(", "module", ")", "out", "=", "__salt_...
Install a Perl module from CPAN CLI Example: .. code-block:: bash salt '*' cpan.install Template::Alloy
[ "Install", "a", "Perl", "module", "from", "CPAN" ]
python
train
MahjongRepository/mahjong
mahjong/utils.py
https://github.com/MahjongRepository/mahjong/blob/a269cc4649b545f965a2bb0c2a6e704492567f13/mahjong/utils.py#L193-L228
def is_tile_strictly_isolated(hand_34, tile_34): """ Tile is strictly isolated if it doesn't have -2, -1, 0, +1, +2 neighbors :param hand_34: array of tiles in 34 tile format :param tile_34: int :return: bool """ hand_34 = copy.copy(hand_34) # we don't need to count target tile in the ha...
[ "def", "is_tile_strictly_isolated", "(", "hand_34", ",", "tile_34", ")", ":", "hand_34", "=", "copy", ".", "copy", "(", "hand_34", ")", "# we don't need to count target tile in the hand", "hand_34", "[", "tile_34", "]", "-=", "1", "if", "hand_34", "[", "tile_34", ...
Tile is strictly isolated if it doesn't have -2, -1, 0, +1, +2 neighbors :param hand_34: array of tiles in 34 tile format :param tile_34: int :return: bool
[ "Tile", "is", "strictly", "isolated", "if", "it", "doesn", "t", "have", "-", "2", "-", "1", "0", "+", "1", "+", "2", "neighbors", ":", "param", "hand_34", ":", "array", "of", "tiles", "in", "34", "tile", "format", ":", "param", "tile_34", ":", "int...
python
train
thespacedoctor/neddy
neddy/namesearch.py
https://github.com/thespacedoctor/neddy/blob/f32653b7d6a39a2c46c5845f83b3a29056311e5e/neddy/namesearch.py#L182-L244
def _output_results( self): """ *output results* **Key Arguments:** # - **Return:** - None .. todo:: - @review: when complete, clean _output_results method - @review: when complete add logging """ sel...
[ "def", "_output_results", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_output_results`` method'", ")", "content", "=", "\"\"", "maxNameLen", "=", "0", "for", "r", "in", "self", ".", "results", ":", "if", "maxNameLen", "<", ...
*output results* **Key Arguments:** # - **Return:** - None .. todo:: - @review: when complete, clean _output_results method - @review: when complete add logging
[ "*", "output", "results", "*" ]
python
train
wmayner/pyphi
profiling/code_to_profile.py
https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/profiling/code_to_profile.py#L42-L56
def all_network_files(): """All network files""" # TODO: list explicitly since some are missing? network_types = [ 'AND-circle', 'MAJ-specialized', 'MAJ-complete', 'iit-3.0-modular' ] network_sizes = range(5, 8) network_files = [] for n in network_sizes: ...
[ "def", "all_network_files", "(", ")", ":", "# TODO: list explicitly since some are missing?", "network_types", "=", "[", "'AND-circle'", ",", "'MAJ-specialized'", ",", "'MAJ-complete'", ",", "'iit-3.0-modular'", "]", "network_sizes", "=", "range", "(", "5", ",", "8", ...
All network files
[ "All", "network", "files" ]
python
train
data61/clkhash
clkhash/rest_client.py
https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/rest_client.py#L135-L176
def watch_run_status(server, project, run, apikey, timeout=None, update_period=1): """ Monitor a linkage run and yield status updates. Will immediately yield an update and then only yield further updates when the status object changes. If a timeout is provided and the run hasn't entered a terminal state...
[ "def", "watch_run_status", "(", "server", ",", "project", ",", "run", ",", "apikey", ",", "timeout", "=", "None", ",", "update_period", "=", "1", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "status", "=", "old_status", "=", "run_get_statu...
Monitor a linkage run and yield status updates. Will immediately yield an update and then only yield further updates when the status object changes. If a timeout is provided and the run hasn't entered a terminal state (error or completed) when the timeout is reached, updates will cease and a TimeoutError wi...
[ "Monitor", "a", "linkage", "run", "and", "yield", "status", "updates", ".", "Will", "immediately", "yield", "an", "update", "and", "then", "only", "yield", "further", "updates", "when", "the", "status", "object", "changes", ".", "If", "a", "timeout", "is", ...
python
train
mbr/data
data/__init__.py
https://github.com/mbr/data/blob/f326938502defb4af93e97ed1212a71575641e77/data/__init__.py#L166-L181
def stream(self): """Returns a stream object (:func:`file`, :class:`~io.BytesIO` or :class:`~StringIO.StringIO`) on the data.""" if not hasattr(self, '_stream'): if self.file is not None: self._stream = self.file elif self.filename is not None: ...
[ "def", "stream", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_stream'", ")", ":", "if", "self", ".", "file", "is", "not", "None", ":", "self", ".", "_stream", "=", "self", ".", "file", "elif", "self", ".", "filename", "is", ...
Returns a stream object (:func:`file`, :class:`~io.BytesIO` or :class:`~StringIO.StringIO`) on the data.
[ "Returns", "a", "stream", "object", "(", ":", "func", ":", "file", ":", "class", ":", "~io", ".", "BytesIO", "or", ":", "class", ":", "~StringIO", ".", "StringIO", ")", "on", "the", "data", "." ]
python
train
echinopsii/net.echinopsii.ariane.community.cli.python3
ariane_clip3/directory.py
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L944-L961
def subnet_2_json(self): """ transform ariane_clip3 subnet object to Ariane server JSON obj :return: Ariane JSON obj """ LOGGER.debug("Subnet.subnet_2_json") json_obj = { 'subnetID': self.id, 'subnetName': self.name, 'subnetDescription'...
[ "def", "subnet_2_json", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"Subnet.subnet_2_json\"", ")", "json_obj", "=", "{", "'subnetID'", ":", "self", ".", "id", ",", "'subnetName'", ":", "self", ".", "name", ",", "'subnetDescription'", ":", "self", ...
transform ariane_clip3 subnet object to Ariane server JSON obj :return: Ariane JSON obj
[ "transform", "ariane_clip3", "subnet", "object", "to", "Ariane", "server", "JSON", "obj", ":", "return", ":", "Ariane", "JSON", "obj" ]
python
train
bcbio/bcbio-nextgen
bcbio/structural/seq2c.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/seq2c.py#L124-L138
def _get_seq2c_options(data): """Get adjustable, through resources, or default options for seq2c. """ cov2lr_possible_opts = ["-F"] defaults = {} ropts = config_utils.get_resources("seq2c", data["config"]).get("options", []) assert len(ropts) % 2 == 0, "Expect even number of options for seq2c" %...
[ "def", "_get_seq2c_options", "(", "data", ")", ":", "cov2lr_possible_opts", "=", "[", "\"-F\"", "]", "defaults", "=", "{", "}", "ropts", "=", "config_utils", ".", "get_resources", "(", "\"seq2c\"", ",", "data", "[", "\"config\"", "]", ")", ".", "get", "(",...
Get adjustable, through resources, or default options for seq2c.
[ "Get", "adjustable", "through", "resources", "or", "default", "options", "for", "seq2c", "." ]
python
train
annoviko/pyclustering
pyclustering/container/kdtree.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/container/kdtree.py#L407-L438
def __find_node_by_rule(self, point, search_rule, cur_node): """! @brief Search node that satisfy to parameters in search rule. @details If node with specified parameters does not exist then None will be returned, otherwise required node will be returned. ...
[ "def", "__find_node_by_rule", "(", "self", ",", "point", ",", "search_rule", ",", "cur_node", ")", ":", "req_node", "=", "None", "if", "cur_node", "is", "None", ":", "cur_node", "=", "self", ".", "__root", "while", "cur_node", ":", "if", "cur_node", ".", ...
! @brief Search node that satisfy to parameters in search rule. @details If node with specified parameters does not exist then None will be returned, otherwise required node will be returned. @param[in] point (list): Coordinates of the point whose node should be ...
[ "!" ]
python
valid
gwastro/pycbc
pycbc/fft/fftw.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/fft/fftw.py#L494-L516
def verify_fft_options(opt,parser): """Parses the FFT options and verifies that they are reasonable. Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes. parser : object OptionParser instance. ...
[ "def", "verify_fft_options", "(", "opt", ",", "parser", ")", ":", "if", "opt", ".", "fftw_measure_level", "not", "in", "[", "0", ",", "1", ",", "2", ",", "3", "]", ":", "parser", ".", "error", "(", "\"{0} is not a valid FFTW measure level.\"", ".", "format...
Parses the FFT options and verifies that they are reasonable. Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object with the required attributes. parser : object OptionParser instance.
[ "Parses", "the", "FFT", "options", "and", "verifies", "that", "they", "are", "reasonable", "." ]
python
train
belbio/bel
bel/lang/completion.py
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/completion.py#L44-L175
def cursor( belstr: str, ast: AST, cursor_loc: int, result: Mapping[str, Any] = None ) -> Mapping[str, Any]: """Find BEL function or argument at cursor location Args: belstr: BEL String used to create the completion_text ast (Mapping[str, Any]): AST (dict) of BEL String cursor_loc (...
[ "def", "cursor", "(", "belstr", ":", "str", ",", "ast", ":", "AST", ",", "cursor_loc", ":", "int", ",", "result", ":", "Mapping", "[", "str", ",", "Any", "]", "=", "None", ")", "->", "Mapping", "[", "str", ",", "Any", "]", ":", "log", ".", "deb...
Find BEL function or argument at cursor location Args: belstr: BEL String used to create the completion_text ast (Mapping[str, Any]): AST (dict) of BEL String cursor_loc (int): given cursor location from input field cursor_loc starts at 0, think of it like a block cursor coverin...
[ "Find", "BEL", "function", "or", "argument", "at", "cursor", "location" ]
python
train
blockstack/blockstack-core
blockstack/blockstackd.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L734-L750
def rpc_get_name_DID(self, name, **con_info): """ Given a name or subdomain, return its DID. """ did_info = None if check_name(name): did_info = self.get_name_DID_info(name) elif check_subdomain(name): did_info = self.get_subdomain_DID_info(name) ...
[ "def", "rpc_get_name_DID", "(", "self", ",", "name", ",", "*", "*", "con_info", ")", ":", "did_info", "=", "None", "if", "check_name", "(", "name", ")", ":", "did_info", "=", "self", ".", "get_name_DID_info", "(", "name", ")", "elif", "check_subdomain", ...
Given a name or subdomain, return its DID.
[ "Given", "a", "name", "or", "subdomain", "return", "its", "DID", "." ]
python
train
ekmmetering/ekmmeters
ekmmeters.py
https://github.com/ekmmetering/ekmmeters/blob/b3748bdf30263bfa46ea40157bdf8df2522e1904/ekmmeters.py#L1159-L1198
def sqlInsert(def_buf, raw_a, raw_b): """ Reasonably portable SQL INSERT for from combined read buffer. Args: def_buf (SerialBlock): Database only serial block of all fields. raw_a (str): Raw A read as hex string. raw_b (str): Raw B read (if exists, otherwise empty) a...
[ "def", "sqlInsert", "(", "def_buf", ",", "raw_a", ",", "raw_b", ")", ":", "count", "=", "0", "qry_str", "=", "\"INSERT INTO Meter_Reads ( \\n\\t\"", "for", "fld", "in", "def_buf", ":", "if", "count", ">", "0", ":", "qry_str", "+=", "\", \\n\\t\"", "qry_str"...
Reasonably portable SQL INSERT for from combined read buffer. Args: def_buf (SerialBlock): Database only serial block of all fields. raw_a (str): Raw A read as hex string. raw_b (str): Raw B read (if exists, otherwise empty) as hex string. Returns: str: S...
[ "Reasonably", "portable", "SQL", "INSERT", "for", "from", "combined", "read", "buffer", ".", "Args", ":", "def_buf", "(", "SerialBlock", ")", ":", "Database", "only", "serial", "block", "of", "all", "fields", ".", "raw_a", "(", "str", ")", ":", "Raw", "A...
python
test
Jammy2211/PyAutoLens
autolens/model/galaxy/util/galaxy_util.py
https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/util/galaxy_util.py#L107-L127
def deflections_of_galaxies_from_sub_grid(sub_grid, galaxies): """Compute the deflections of a list of galaxies from an input sub-grid, by summing the individual deflections \ of each galaxy's mass profile. The deflections are calculated on the sub-grid and binned-up to the original regular grid by taking ...
[ "def", "deflections_of_galaxies_from_sub_grid", "(", "sub_grid", ",", "galaxies", ")", ":", "if", "galaxies", ":", "return", "sum", "(", "map", "(", "lambda", "galaxy", ":", "galaxy", ".", "deflections_from_grid", "(", "sub_grid", ")", ",", "galaxies", ")", ")...
Compute the deflections of a list of galaxies from an input sub-grid, by summing the individual deflections \ of each galaxy's mass profile. The deflections are calculated on the sub-grid and binned-up to the original regular grid by taking the mean value \ of every set of sub-pixels. If no galaxies a...
[ "Compute", "the", "deflections", "of", "a", "list", "of", "galaxies", "from", "an", "input", "sub", "-", "grid", "by", "summing", "the", "individual", "deflections", "\\", "of", "each", "galaxy", "s", "mass", "profile", "." ]
python
valid
devassistant/devassistant
devassistant/dapi/dapicli.py
https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/dapi/dapicli.py#L167-L179
def format_users(): '''Formats a list of users available on Dapi''' lines = [] u = users() count = u['count'] if not count: raise DapiCommError('Could not find any users on DAPI.') for user in u['results']: line = user['username'] if user['full_name']: line +=...
[ "def", "format_users", "(", ")", ":", "lines", "=", "[", "]", "u", "=", "users", "(", ")", "count", "=", "u", "[", "'count'", "]", "if", "not", "count", ":", "raise", "DapiCommError", "(", "'Could not find any users on DAPI.'", ")", "for", "user", "in", ...
Formats a list of users available on Dapi
[ "Formats", "a", "list", "of", "users", "available", "on", "Dapi" ]
python
train
koszullab/metaTOR
metator/scripts/hicstuff.py
https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/hicstuff.py#L32-L70
def despeckle_simple(B, th2=2): """Single-chromosome despeckling Simple speckle removing function on a single chromomsome. It also works for multiple chromosomes but trends may be disrupted. Parameters ---------- B : array_like The input matrix to despeckle th2 : float The ...
[ "def", "despeckle_simple", "(", "B", ",", "th2", "=", "2", ")", ":", "A", "=", "np", ".", "copy", "(", "B", ")", "n1", "=", "A", ".", "shape", "[", "0", "]", "dist", "=", "{", "u", ":", "np", ".", "diag", "(", "A", ",", "u", ")", "for", ...
Single-chromosome despeckling Simple speckle removing function on a single chromomsome. It also works for multiple chromosomes but trends may be disrupted. Parameters ---------- B : array_like The input matrix to despeckle th2 : float The number of standard deviations above the...
[ "Single", "-", "chromosome", "despeckling" ]
python
train
oseledets/ttpy
tt/riemannian/riemannian.py
https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L110-L356
def project(X, Z, use_jit=False, debug=False): """ Project tensor Z on the tangent space of tensor X. X is a tensor in the TT format. Z can be a tensor in the TT format or a list of tensors (in this case the function computes projection of the sum off all tensors in the list: project(X, Z) = P_...
[ "def", "project", "(", "X", ",", "Z", ",", "use_jit", "=", "False", ",", "debug", "=", "False", ")", ":", "zArr", "=", "None", "if", "isinstance", "(", "Z", ",", "tt", ".", "vector", ")", ":", "zArr", "=", "[", "Z", "]", "else", ":", "zArr", ...
Project tensor Z on the tangent space of tensor X. X is a tensor in the TT format. Z can be a tensor in the TT format or a list of tensors (in this case the function computes projection of the sum off all tensors in the list: project(X, Z) = P_X(\sum_i Z_i) ). This function implements an al...
[ "Project", "tensor", "Z", "on", "the", "tangent", "space", "of", "tensor", "X", "." ]
python
train
tradenity/python-sdk
tradenity/resources/tax_class.py
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/tax_class.py#L676-L697
def replace_tax_class_by_id(cls, tax_class_id, tax_class, **kwargs): """Replace TaxClass Replace all attributes of TaxClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_tax_class_by...
[ "def", "replace_tax_class_by_id", "(", "cls", ",", "tax_class_id", ",", "tax_class", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".",...
Replace TaxClass Replace all attributes of TaxClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_tax_class_by_id(tax_class_id, tax_class, async=True) >>> result = thread.get() ...
[ "Replace", "TaxClass" ]
python
train
webadmin87/midnight
midnight_main/templatetags/midnight_main.py
https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/templatetags/midnight_main.py#L38-L58
def show_gallery(slug, size="100x100", crop="center", **kwargs): """ Тег отображения фотогалереи Пример использования:: {% show_gallery "gallery-slug" "150x110" "center" class='gallery-class' %} :param slug: символьный код фотогалереи :param size: размер :param crop: параметры кропа ...
[ "def", "show_gallery", "(", "slug", ",", "size", "=", "\"100x100\"", ",", "crop", "=", "\"center\"", ",", "*", "*", "kwargs", ")", ":", "try", ":", "album", "=", "PhotoAlbum", ".", "objects", ".", "published", "(", ")", ".", "get", "(", "slug", "=", ...
Тег отображения фотогалереи Пример использования:: {% show_gallery "gallery-slug" "150x110" "center" class='gallery-class' %} :param slug: символьный код фотогалереи :param size: размер :param crop: параметры кропа :param kwargs: html атрибуты оборачивающего тега :return:
[ "Тег", "отображения", "фотогалереи" ]
python
train
andersinno/python-database-sanitizer
database_sanitizer/sanitizers/string.py
https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/sanitizers/string.py#L25-L31
def sanitize_random(value): """ Random string of same length as the given value. """ if not value: return value return ''.join(random.choice(CHARACTERS) for _ in range(len(value)))
[ "def", "sanitize_random", "(", "value", ")", ":", "if", "not", "value", ":", "return", "value", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "CHARACTERS", ")", "for", "_", "in", "range", "(", "len", "(", "value", ")", ")", ")" ]
Random string of same length as the given value.
[ "Random", "string", "of", "same", "length", "as", "the", "given", "value", "." ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/history_console_widget.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/history_console_widget.py#L66-L101
def _up_pressed(self, shift_modifier): """ Called when the up key is pressed. Returns whether to continue processing the event. """ prompt_cursor = self._get_prompt_cursor() if self._get_cursor().blockNumber() == prompt_cursor.blockNumber(): # Bail out if we're lo...
[ "def", "_up_pressed", "(", "self", ",", "shift_modifier", ")", ":", "prompt_cursor", "=", "self", ".", "_get_prompt_cursor", "(", ")", "if", "self", ".", "_get_cursor", "(", ")", ".", "blockNumber", "(", ")", "==", "prompt_cursor", ".", "blockNumber", "(", ...
Called when the up key is pressed. Returns whether to continue processing the event.
[ "Called", "when", "the", "up", "key", "is", "pressed", ".", "Returns", "whether", "to", "continue", "processing", "the", "event", "." ]
python
test
materialsproject/pymatgen
pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py#L1011-L1066
def is_a_valid_coordination_geometry(self, mp_symbol=None, IUPAC_symbol=None, IUCr_symbol=None, name=None, cn=None): """ Checks whether a given coordination geometry is valid (exists) and whether the parameters are coheren...
[ "def", "is_a_valid_coordination_geometry", "(", "self", ",", "mp_symbol", "=", "None", ",", "IUPAC_symbol", "=", "None", ",", "IUCr_symbol", "=", "None", ",", "name", "=", "None", ",", "cn", "=", "None", ")", ":", "if", "name", "is", "not", "None", ":", ...
Checks whether a given coordination geometry is valid (exists) and whether the parameters are coherent with each other. :param IUPAC_symbol: :param IUCr_symbol: :param name: :param cn: :param mp_symbol: The mp_symbol of the coordination geometry.
[ "Checks", "whether", "a", "given", "coordination", "geometry", "is", "valid", "(", "exists", ")", "and", "whether", "the", "parameters", "are", "coherent", "with", "each", "other", ".", ":", "param", "IUPAC_symbol", ":", ":", "param", "IUCr_symbol", ":", ":"...
python
train
pgmpy/pgmpy
pgmpy/readwrite/PomdpX.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/PomdpX.py#L314-L328
def get_parameter_tbl(self, parameter): """ This method returns parameters as list of dict in case of table type parameter """ par = [] for entry in parameter.findall('Entry'): instance = defaultdict(list) instance['Instance'] = entry.find('Instanc...
[ "def", "get_parameter_tbl", "(", "self", ",", "parameter", ")", ":", "par", "=", "[", "]", "for", "entry", "in", "parameter", ".", "findall", "(", "'Entry'", ")", ":", "instance", "=", "defaultdict", "(", "list", ")", "instance", "[", "'Instance'", "]", ...
This method returns parameters as list of dict in case of table type parameter
[ "This", "method", "returns", "parameters", "as", "list", "of", "dict", "in", "case", "of", "table", "type", "parameter" ]
python
train
alan-turing-institute/topic-modelling-tools
topicmodels/preprocess.py
https://github.com/alan-turing-institute/topic-modelling-tools/blob/f0cf90cdd06f1072e824b446f201c7469b9de5df/topicmodels/preprocess.py#L152-L195
def term_rank(self, items, print_output=True): """ Calculate corpus-level df and tf-idf scores on either tokens (items = "tokens") bigrams (items = 'bigrams') or stems (items = "stems"). Print to file if print_output = True. """ if items == 'stems': v = self...
[ "def", "term_rank", "(", "self", ",", "items", ",", "print_output", "=", "True", ")", ":", "if", "items", "==", "'stems'", ":", "v", "=", "self", ".", "stems", "elif", "items", "==", "'tokens'", ":", "v", "=", "self", ".", "tokens", "elif", "items", ...
Calculate corpus-level df and tf-idf scores on either tokens (items = "tokens") bigrams (items = 'bigrams') or stems (items = "stems"). Print to file if print_output = True.
[ "Calculate", "corpus", "-", "level", "df", "and", "tf", "-", "idf", "scores", "on", "either", "tokens", "(", "items", "=", "tokens", ")", "bigrams", "(", "items", "=", "bigrams", ")", "or", "stems", "(", "items", "=", "stems", ")", ".", "Print", "to"...
python
train
lcgong/redbean
redbean/secure/secure.py
https://github.com/lcgong/redbean/blob/45df9ff1e807e742771c752808d7fdac4007c919/redbean/secure/secure.py#L105-L122
async def encode_jwt(self, identity: SessionIdentity) -> str: """ 将identity编码为JWT """ assert identity payload = { "sub": identity.identity, "user_id": identity.user_id, "exp": int(time.time() + self._max_age) # seconds from 1970-1-1 UTC } ...
[ "async", "def", "encode_jwt", "(", "self", ",", "identity", ":", "SessionIdentity", ")", "->", "str", ":", "assert", "identity", "payload", "=", "{", "\"sub\"", ":", "identity", ".", "identity", ",", "\"user_id\"", ":", "identity", ".", "user_id", ",", "\"...
将identity编码为JWT
[ "将identity编码为JWT" ]
python
train
szastupov/aiotg
aiotg/bot.py
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/bot.py#L526-L534
def get_user_profile_photos(self, user_id, **options): """ Get a list of profile pictures for a user :param int user_id: Unique identifier of the target user :param options: Additional getUserProfilePhotos options (see https://core.telegram.org/bots/api#getuserprofilephotos)...
[ "def", "get_user_profile_photos", "(", "self", ",", "user_id", ",", "*", "*", "options", ")", ":", "return", "self", ".", "api_call", "(", "\"getUserProfilePhotos\"", ",", "user_id", "=", "str", "(", "user_id", ")", ",", "*", "*", "options", ")" ]
Get a list of profile pictures for a user :param int user_id: Unique identifier of the target user :param options: Additional getUserProfilePhotos options (see https://core.telegram.org/bots/api#getuserprofilephotos)
[ "Get", "a", "list", "of", "profile", "pictures", "for", "a", "user" ]
python
train
srittau/python-asserts
asserts/__init__.py
https://github.com/srittau/python-asserts/blob/1d5c797031c68ee27552d1c94e7f918c3d3d0453/asserts/__init__.py#L790-L813
def assert_datetime_about_now(actual, msg_fmt="{msg}"): """Fail if a datetime object is not within 5 seconds of the local time. >>> assert_datetime_about_now(datetime.now()) >>> assert_datetime_about_now(datetime(1900, 1, 1, 12, 0, 0)) Traceback (most recent call last): ... AssertionError: ...
[ "def", "assert_datetime_about_now", "(", "actual", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "now", "=", "datetime", ".", "now", "(", ")", "if", "actual", "is", "None", ":", "msg", "=", "\"None is not a valid date/time\"", "fail", "(", "msg_fmt", ".", "for...
Fail if a datetime object is not within 5 seconds of the local time. >>> assert_datetime_about_now(datetime.now()) >>> assert_datetime_about_now(datetime(1900, 1, 1, 12, 0, 0)) Traceback (most recent call last): ... AssertionError: datetime.datetime(1900, 1, 1, 12, 0) is not close to current da...
[ "Fail", "if", "a", "datetime", "object", "is", "not", "within", "5", "seconds", "of", "the", "local", "time", "." ]
python
train