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
pymc-devs/pymc
pymc/StepMethods.py
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L1204-L1214
def check_type(self): """Make sure each stochastic has a correct type, and identify discrete stochastics.""" self.isdiscrete = {} for stochastic in self.stochastics: if stochastic.dtype in integer_dtypes: self.isdiscrete[stochastic] = True elif stochastic....
[ "def", "check_type", "(", "self", ")", ":", "self", ".", "isdiscrete", "=", "{", "}", "for", "stochastic", "in", "self", ".", "stochastics", ":", "if", "stochastic", ".", "dtype", "in", "integer_dtypes", ":", "self", ".", "isdiscrete", "[", "stochastic", ...
Make sure each stochastic has a correct type, and identify discrete stochastics.
[ "Make", "sure", "each", "stochastic", "has", "a", "correct", "type", "and", "identify", "discrete", "stochastics", "." ]
python
train
GoogleCloudPlatform/appengine-pipelines
python/src/pipeline/models.py
https://github.com/GoogleCloudPlatform/appengine-pipelines/blob/277394648dac3e8214677af898935d07399ac8e1/python/src/pipeline/models.py#L251-L271
def to_barrier_key(cls, barrier_index_key): """Converts a _BarrierIndex key to a _BarrierRecord key. Args: barrier_index_key: db.Key for a _BarrierIndex entity. Returns: db.Key for the corresponding _BarrierRecord entity. """ barrier_index_path = barrier_index_key.to_path() # Pick...
[ "def", "to_barrier_key", "(", "cls", ",", "barrier_index_key", ")", ":", "barrier_index_path", "=", "barrier_index_key", ".", "to_path", "(", ")", "# Pick out the items from the _BarrierIndex key path that we need to", "# construct the _BarrierRecord key path.", "(", "pipeline_ki...
Converts a _BarrierIndex key to a _BarrierRecord key. Args: barrier_index_key: db.Key for a _BarrierIndex entity. Returns: db.Key for the corresponding _BarrierRecord entity.
[ "Converts", "a", "_BarrierIndex", "key", "to", "a", "_BarrierRecord", "key", "." ]
python
train
mila-iqia/fuel
fuel/server.py
https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/server.py#L48-L81
def recv_arrays(socket): """Receive a list of NumPy arrays. Parameters ---------- socket : :class:`zmq.Socket` The socket to receive the arrays on. Returns ------- list A list of :class:`numpy.ndarray` objects. Raises ------ StopIteration If the first J...
[ "def", "recv_arrays", "(", "socket", ")", ":", "headers", "=", "socket", ".", "recv_json", "(", ")", "if", "'stop'", "in", "headers", ":", "raise", "StopIteration", "arrays", "=", "[", "]", "for", "header", "in", "headers", ":", "data", "=", "socket", ...
Receive a list of NumPy arrays. Parameters ---------- socket : :class:`zmq.Socket` The socket to receive the arrays on. Returns ------- list A list of :class:`numpy.ndarray` objects. Raises ------ StopIteration If the first JSON object received contains the...
[ "Receive", "a", "list", "of", "NumPy", "arrays", "." ]
python
train
welbornprod/colr
colr/colr.py
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr.py#L904-L920
def _ext_attr_to_partial(self, name, kwarg_key): """ Convert a string like '233' or 'aliceblue' into partial for self.chained. """ try: intval = int(name) except ValueError: # Try as an extended name_data name. info = name_data.get(name, No...
[ "def", "_ext_attr_to_partial", "(", "self", ",", "name", ",", "kwarg_key", ")", ":", "try", ":", "intval", "=", "int", "(", "name", ")", "except", "ValueError", ":", "# Try as an extended name_data name.", "info", "=", "name_data", ".", "get", "(", "name", "...
Convert a string like '233' or 'aliceblue' into partial for self.chained.
[ "Convert", "a", "string", "like", "233", "or", "aliceblue", "into", "partial", "for", "self", ".", "chained", "." ]
python
train
ampl/amplpy
amplpy/ampl.py
https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L1084-L1090
def _startRecording(self, filename): """ Start recording the session to a file for debug purposes. """ self.setOption('_log_file_name', filename) self.setOption('_log_input_only', True) self.setOption('_log', True)
[ "def", "_startRecording", "(", "self", ",", "filename", ")", ":", "self", ".", "setOption", "(", "'_log_file_name'", ",", "filename", ")", "self", ".", "setOption", "(", "'_log_input_only'", ",", "True", ")", "self", ".", "setOption", "(", "'_log'", ",", "...
Start recording the session to a file for debug purposes.
[ "Start", "recording", "the", "session", "to", "a", "file", "for", "debug", "purposes", "." ]
python
train
gabstopper/smc-python
smc/core/collection.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/collection.py#L903-L919
def add_tunnel_interface(self, interface_id, address, network_value, zone_ref=None, comment=None): """ Creates a tunnel interface for a virtual engine. :param str,int interface_id: the tunnel id for the interface, used as nicid also :param str address: ip ad...
[ "def", "add_tunnel_interface", "(", "self", ",", "interface_id", ",", "address", ",", "network_value", ",", "zone_ref", "=", "None", ",", "comment", "=", "None", ")", ":", "interfaces", "=", "[", "{", "'nodes'", ":", "[", "{", "'address'", ":", "address", ...
Creates a tunnel interface for a virtual engine. :param str,int interface_id: the tunnel id for the interface, used as nicid also :param str address: ip address of interface :param str network_value: network cidr for interface; format: 1.1.1.0/24 :param str zone_ref: zone reference for ...
[ "Creates", "a", "tunnel", "interface", "for", "a", "virtual", "engine", "." ]
python
train
juanifioren/django-oidc-provider
oidc_provider/lib/utils/common.py
https://github.com/juanifioren/django-oidc-provider/blob/f0daed07b2ac7608565b80d4c80ccf04d8c416a8/oidc_provider/lib/utils/common.py#L145-L151
def get_browser_state_or_default(request): """ Determine value to use as session state. """ key = (request.session.session_key or settings.get('OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY')) return sha224(key.encode('utf-8')).hexdigest()
[ "def", "get_browser_state_or_default", "(", "request", ")", ":", "key", "=", "(", "request", ".", "session", ".", "session_key", "or", "settings", ".", "get", "(", "'OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY'", ")", ")", "return", "sha224", "(", "key", ".", "e...
Determine value to use as session state.
[ "Determine", "value", "to", "use", "as", "session", "state", "." ]
python
train
sorgerlab/indra
indra/tools/machine/cli.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/machine/cli.py#L30-L42
def make(directory): """Makes a RAS Machine directory""" if os.path.exists(directory): if os.path.isdir(directory): click.echo('Directory already exists') else: click.echo('Path exists and is not a directory') sys.exit() os.makedirs(directory) os.mkdir(o...
[ "def", "make", "(", "directory", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "click", ".", "echo", "(", "'Directory already exists'", ")", "else", ":...
Makes a RAS Machine directory
[ "Makes", "a", "RAS", "Machine", "directory" ]
python
train
fermiPy/fermipy
fermipy/jobs/scatter_gather.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/scatter_gather.py#L459-L509
def resubmit(self, stream=sys.stdout, fail_running=False, resubmit_failed=False): """Function to resubmit failed jobs and collect results Parameters ----------- stream : `file` Stream that this function will print to, Must have 'write' function. fail_run...
[ "def", "resubmit", "(", "self", ",", "stream", "=", "sys", ".", "stdout", ",", "fail_running", "=", "False", ",", "resubmit_failed", "=", "False", ")", ":", "self", ".", "_build_job_dict", "(", ")", "status_vect", "=", "self", ".", "check_status", "(", "...
Function to resubmit failed jobs and collect results Parameters ----------- stream : `file` Stream that this function will print to, Must have 'write' function. fail_running : `bool` If True, consider running jobs as failed resubmit_failed :...
[ "Function", "to", "resubmit", "failed", "jobs", "and", "collect", "results" ]
python
train
allenai/allennlp
scripts/reformat_text2sql_data.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/reformat_text2sql_data.py#L38-L91
def main(output_directory: int, data: str) -> None: """ Processes the text2sql data into the following directory structure: ``dataset/{query_split, question_split}/{train,dev,test}.json`` for datasets which have train, dev and test splits, or: ``dataset/{query_split, question_split}/{split_{split...
[ "def", "main", "(", "output_directory", ":", "int", ",", "data", ":", "str", ")", "->", "None", ":", "json_files", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "data", ",", "\"*.json\"", ")", ")", "for", "dataset", "in", "jso...
Processes the text2sql data into the following directory structure: ``dataset/{query_split, question_split}/{train,dev,test}.json`` for datasets which have train, dev and test splits, or: ``dataset/{query_split, question_split}/{split_{split_id}}.json`` for datasets which use cross validation. ...
[ "Processes", "the", "text2sql", "data", "into", "the", "following", "directory", "structure", ":" ]
python
train
uw-it-aca/uw-restclients-canvas
uw_canvas/admins.py
https://github.com/uw-it-aca/uw-restclients-canvas/blob/9845faf33d49a8f06908efc22640c001116d6ea2/uw_canvas/admins.py#L9-L20
def get_admins(self, account_id, params={}): """ Return a list of the admins in the account. https://canvas.instructure.com/doc/api/admins.html#method.admins.index """ url = ADMINS_API.format(account_id) admins = [] for data in self._get_paged_resource(url, para...
[ "def", "get_admins", "(", "self", ",", "account_id", ",", "params", "=", "{", "}", ")", ":", "url", "=", "ADMINS_API", ".", "format", "(", "account_id", ")", "admins", "=", "[", "]", "for", "data", "in", "self", ".", "_get_paged_resource", "(", "url", ...
Return a list of the admins in the account. https://canvas.instructure.com/doc/api/admins.html#method.admins.index
[ "Return", "a", "list", "of", "the", "admins", "in", "the", "account", "." ]
python
test
manahl/arctic
arctic/_compression.py
https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/_compression.py#L126-L140
def decompress_array(str_list): """ Decompress a list of strings """ global _compress_thread_pool if not str_list: return str_list if not ENABLE_PARALLEL or len(str_list) <= LZ4_N_PARALLEL: return [lz4_decompress(chunk) for chunk in str_list] if _compress_thread_pool is No...
[ "def", "decompress_array", "(", "str_list", ")", ":", "global", "_compress_thread_pool", "if", "not", "str_list", ":", "return", "str_list", "if", "not", "ENABLE_PARALLEL", "or", "len", "(", "str_list", ")", "<=", "LZ4_N_PARALLEL", ":", "return", "[", "lz4_decom...
Decompress a list of strings
[ "Decompress", "a", "list", "of", "strings" ]
python
train
wavycloud/pyboto3
pyboto3/elasticbeanstalk.py
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/elasticbeanstalk.py#L1672-L1753
def describe_events(ApplicationName=None, VersionLabel=None, TemplateName=None, EnvironmentId=None, EnvironmentName=None, PlatformArn=None, RequestId=None, Severity=None, StartTime=None, EndTime=None, MaxRecords=None, NextToken=None): """ Returns list of event descriptions matching criteria up to the last 6 wee...
[ "def", "describe_events", "(", "ApplicationName", "=", "None", ",", "VersionLabel", "=", "None", ",", "TemplateName", "=", "None", ",", "EnvironmentId", "=", "None", ",", "EnvironmentName", "=", "None", ",", "PlatformArn", "=", "None", ",", "RequestId", "=", ...
Returns list of event descriptions matching criteria up to the last 6 weeks. See also: AWS API Documentation Examples The following operation retrieves events for an environment named my-env: Expected Output: :example: response = client.describe_events( ApplicationName='string', ...
[ "Returns", "list", "of", "event", "descriptions", "matching", "criteria", "up", "to", "the", "last", "6", "weeks", ".", "See", "also", ":", "AWS", "API", "Documentation", "Examples", "The", "following", "operation", "retrieves", "events", "for", "an", "environ...
python
train
cvxopt/chompack
src/python/misc.py
https://github.com/cvxopt/chompack/blob/e07106b58b8055c34f6201e8c954482f86987833/src/python/misc.py#L42-L53
def perm(A, p): """ Symmetric permutation of a symmetric sparse matrix. :param A: :py:class:`spmatrix` :param p: :py:class:`matrix` or :class:`list` of length `A.size[0]` """ assert isinstance(A,spmatrix), "argument must be a sparse matrix" assert A.size[0] == A.size[1], "A must be ...
[ "def", "perm", "(", "A", ",", "p", ")", ":", "assert", "isinstance", "(", "A", ",", "spmatrix", ")", ",", "\"argument must be a sparse matrix\"", "assert", "A", ".", "size", "[", "0", "]", "==", "A", ".", "size", "[", "1", "]", ",", "\"A must be a squa...
Symmetric permutation of a symmetric sparse matrix. :param A: :py:class:`spmatrix` :param p: :py:class:`matrix` or :class:`list` of length `A.size[0]`
[ "Symmetric", "permutation", "of", "a", "symmetric", "sparse", "matrix", "." ]
python
train
django-parler/django-parler-rest
parler_rest/serializers.py
https://github.com/django-parler/django-parler-rest/blob/9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5/parler_rest/serializers.py#L41-L54
def save_translations(self, instance, translated_data): """ Save translation data into translation objects. """ for meta in self.Meta.model._parler_meta: translations = translated_data.get(meta.rel_name, {}) for lang_code, model_fields in translations.items(): ...
[ "def", "save_translations", "(", "self", ",", "instance", ",", "translated_data", ")", ":", "for", "meta", "in", "self", ".", "Meta", ".", "model", ".", "_parler_meta", ":", "translations", "=", "translated_data", ".", "get", "(", "meta", ".", "rel_name", ...
Save translation data into translation objects.
[ "Save", "translation", "data", "into", "translation", "objects", "." ]
python
train
tornadoweb/tornado
tornado/process.py
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/process.py#L319-L340
def initialize(cls) -> None: """Initializes the ``SIGCHLD`` handler. The signal handler is run on an `.IOLoop` to avoid locking issues. Note that the `.IOLoop` used for signal handling need not be the same one used by individual Subprocess objects (as long as the ``IOLoops`` are...
[ "def", "initialize", "(", "cls", ")", "->", "None", ":", "if", "cls", ".", "_initialized", ":", "return", "io_loop", "=", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "cls", ".", "_old_sigchld", "=", "signal", ".", "signal", "(", "signal", ".", ...
Initializes the ``SIGCHLD`` handler. The signal handler is run on an `.IOLoop` to avoid locking issues. Note that the `.IOLoop` used for signal handling need not be the same one used by individual Subprocess objects (as long as the ``IOLoops`` are each running in separate threads). ...
[ "Initializes", "the", "SIGCHLD", "handler", "." ]
python
train
inasafe/inasafe
safe/gis/raster/contour.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/raster/contour.py#L117-L228
def convolve(input, weights, mask=None, slow=False): """2 dimensional convolution. This is a Python implementation of what will be written in Fortran. Borders are handled with reflection. Masking is supported in the following way: * Masked points are skipped. * Parts of the input whic...
[ "def", "convolve", "(", "input", ",", "weights", ",", "mask", "=", "None", ",", "slow", "=", "False", ")", ":", "assert", "(", "len", "(", "input", ".", "shape", ")", "==", "2", ")", "assert", "(", "len", "(", "weights", ".", "shape", ")", "==", ...
2 dimensional convolution. This is a Python implementation of what will be written in Fortran. Borders are handled with reflection. Masking is supported in the following way: * Masked points are skipped. * Parts of the input which are masked have weight 0 in the kernel. * Since th...
[ "2", "dimensional", "convolution", "." ]
python
train
rigetti/grove
grove/pyqaoa/qaoa.py
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/pyqaoa/qaoa.py#L132-L178
def get_parameterized_program(self): """ Return a function that accepts parameters and returns a new Quil program. :returns: a function """ cost_para_programs = [] driver_para_programs = [] for idx in range(self.steps): cost_list = [] dri...
[ "def", "get_parameterized_program", "(", "self", ")", ":", "cost_para_programs", "=", "[", "]", "driver_para_programs", "=", "[", "]", "for", "idx", "in", "range", "(", "self", ".", "steps", ")", ":", "cost_list", "=", "[", "]", "driver_list", "=", "[", ...
Return a function that accepts parameters and returns a new Quil program. :returns: a function
[ "Return", "a", "function", "that", "accepts", "parameters", "and", "returns", "a", "new", "Quil", "program", "." ]
python
train
SAP/PyHDB
pyhdb/protocol/parts.py
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/parts.py#L428-L435
def unpack_data(cls, argument_count, payload): """Unpack payload by splitting up the raw payload into list of locator_ids :param argument_count: number of locator_ids in payload is equal to argument_count :param payload: BytesIO instance with list of concatenated locator_ids, where each locator_...
[ "def", "unpack_data", "(", "cls", ",", "argument_count", ",", "payload", ")", ":", "pl", "=", "payload", ".", "read", "(", ")", "locator_ids", "=", "[", "pl", "[", "start", ":", "start", "+", "8", "]", "for", "start", "in", "range", "(", "0", ",", ...
Unpack payload by splitting up the raw payload into list of locator_ids :param argument_count: number of locator_ids in payload is equal to argument_count :param payload: BytesIO instance with list of concatenated locator_ids, where each locator_id is 8 bytes long
[ "Unpack", "payload", "by", "splitting", "up", "the", "raw", "payload", "into", "list", "of", "locator_ids", ":", "param", "argument_count", ":", "number", "of", "locator_ids", "in", "payload", "is", "equal", "to", "argument_count", ":", "param", "payload", ":"...
python
train
draperjames/qtpandas
qtpandas/ui/fallback/easygui/boxes/base_boxes.py
https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/base_boxes.py#L49-L122
def buttonbox(msg="", title=" ", choices=("Button[1]", "Button[2]", "Button[3]"), image=None, root=None, default_choice=None, cancel_choice=None): """ Display a msg, a title, an image, and a set of buttons. The buttons are defined by the members of the choices list. :param str msg: the msg to be displa...
[ "def", "buttonbox", "(", "msg", "=", "\"\"", ",", "title", "=", "\" \"", ",", "choices", "=", "(", "\"Button[1]\"", ",", "\"Button[2]\"", ",", "\"Button[3]\"", ")", ",", "image", "=", "None", ",", "root", "=", "None", ",", "default_choice", "=", "None", ...
Display a msg, a title, an image, and a set of buttons. The buttons are defined by the members of the choices list. :param str msg: the msg to be displayed :param str title: the window title :param list choices: a list or tuple of the choices to be displayed :param str image: Filename of image to d...
[ "Display", "a", "msg", "a", "title", "an", "image", "and", "a", "set", "of", "buttons", ".", "The", "buttons", "are", "defined", "by", "the", "members", "of", "the", "choices", "list", "." ]
python
train
jsommers/switchyard
switchyard/lib/socket/socketemu.py
https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/socket/socketemu.py#L141-L175
def send_to_app(proto, local_addr, remote_addr, data): ''' Called by a network stack implementer to push application-layer data "up" from the stack. Arguments are protocol number, local_addr (a 2-tuple of IP address and port), remote_addr (a 2-tuple of IP address and port), and ...
[ "def", "send_to_app", "(", "proto", ",", "local_addr", ",", "remote_addr", ",", "data", ")", ":", "proto", "=", "IPProtocol", "(", "proto", ")", "local_addr", "=", "_normalize_addrs", "(", "local_addr", ")", "remote_addr", "=", "_normalize_addrs", "(", "remote...
Called by a network stack implementer to push application-layer data "up" from the stack. Arguments are protocol number, local_addr (a 2-tuple of IP address and port), remote_addr (a 2-tuple of IP address and port), and the message. Returns True if a socket was found to which...
[ "Called", "by", "a", "network", "stack", "implementer", "to", "push", "application", "-", "layer", "data", "up", "from", "the", "stack", "." ]
python
train
nerdvegas/rez
src/rez/suite.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L515-L523
def load_visible_suites(cls, paths=None): """Get a list of suites whos bin paths are visible on $PATH. Returns: List of `Suite` objects. """ suite_paths = cls.visible_suite_paths(paths) suites = [cls.load(x) for x in suite_paths] return suites
[ "def", "load_visible_suites", "(", "cls", ",", "paths", "=", "None", ")", ":", "suite_paths", "=", "cls", ".", "visible_suite_paths", "(", "paths", ")", "suites", "=", "[", "cls", ".", "load", "(", "x", ")", "for", "x", "in", "suite_paths", "]", "retur...
Get a list of suites whos bin paths are visible on $PATH. Returns: List of `Suite` objects.
[ "Get", "a", "list", "of", "suites", "whos", "bin", "paths", "are", "visible", "on", "$PATH", "." ]
python
train
joeyespo/grip
grip/api.py
https://github.com/joeyespo/grip/blob/ce933ccc4ca8e0d3718f271c59bd530a4518bf63/grip/api.py#L13-L46
def create_app(path=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=False, api_url=None, title=None, text=None, autorefresh=None, quiet=None, grip_class=None): """ Creates a Grip application...
[ "def", "create_app", "(", "path", "=", "None", ",", "user_content", "=", "False", ",", "context", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "render_offline", "=", "False", ",", "render_wide", "=", "False", ",", "render...
Creates a Grip application with the specified overrides.
[ "Creates", "a", "Grip", "application", "with", "the", "specified", "overrides", "." ]
python
train
UDST/urbansim
urbansim/utils/misc.py
https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/utils/misc.py#L300-L317
def numpymat2df(mat): """ Sometimes (though not very often) it is useful to convert a numpy matrix which has no column names to a Pandas dataframe for use of the Pandas functions. This method converts a 2D numpy matrix to Pandas dataframe with default column headers. Parameters ---------- ...
[ "def", "numpymat2df", "(", "mat", ")", ":", "return", "pd", ".", "DataFrame", "(", "dict", "(", "(", "'x%d'", "%", "i", ",", "mat", "[", ":", ",", "i", "]", ")", "for", "i", "in", "range", "(", "mat", ".", "shape", "[", "1", "]", ")", ")", ...
Sometimes (though not very often) it is useful to convert a numpy matrix which has no column names to a Pandas dataframe for use of the Pandas functions. This method converts a 2D numpy matrix to Pandas dataframe with default column headers. Parameters ---------- mat : The numpy matrix Re...
[ "Sometimes", "(", "though", "not", "very", "often", ")", "it", "is", "useful", "to", "convert", "a", "numpy", "matrix", "which", "has", "no", "column", "names", "to", "a", "Pandas", "dataframe", "for", "use", "of", "the", "Pandas", "functions", ".", "Thi...
python
train
pyamg/pyamg
pyamg/graph.py
https://github.com/pyamg/pyamg/blob/89dc54aa27e278f65d2f54bdaf16ab97d7768fa6/pyamg/graph.py#L32-L78
def maximal_independent_set(G, algo='serial', k=None): """Compute a maximal independent vertex set for a graph. Parameters ---------- G : sparse matrix Symmetric matrix, preferably in sparse CSR or CSC format The nonzeros of G represent the edges of an undirected graph. algo : {'ser...
[ "def", "maximal_independent_set", "(", "G", ",", "algo", "=", "'serial'", ",", "k", "=", "None", ")", ":", "G", "=", "asgraph", "(", "G", ")", "N", "=", "G", ".", "shape", "[", "0", "]", "mis", "=", "np", ".", "empty", "(", "N", ",", "dtype", ...
Compute a maximal independent vertex set for a graph. Parameters ---------- G : sparse matrix Symmetric matrix, preferably in sparse CSR or CSC format The nonzeros of G represent the edges of an undirected graph. algo : {'serial', 'parallel'} Algorithm used to compute the MIS ...
[ "Compute", "a", "maximal", "independent", "vertex", "set", "for", "a", "graph", "." ]
python
train
mrstephenneal/pdfconduit
pdf/modify/draw/pdf.py
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/modify/draw/pdf.py#L15-L17
def text_width(string, font_name, font_size): """Determine with width in pixels of string.""" return stringWidth(string, fontName=font_name, fontSize=font_size)
[ "def", "text_width", "(", "string", ",", "font_name", ",", "font_size", ")", ":", "return", "stringWidth", "(", "string", ",", "fontName", "=", "font_name", ",", "fontSize", "=", "font_size", ")" ]
Determine with width in pixels of string.
[ "Determine", "with", "width", "in", "pixels", "of", "string", "." ]
python
train
shoeffner/pandoc-source-exec
pandoc_source_exec.py
https://github.com/shoeffner/pandoc-source-exec/blob/9a13b9054d629a60b63196a906fafe2673722d13/pandoc_source_exec.py#L189-L209
def remove_import_statements(code): """Removes lines with import statements from the code. Args: code: The code to be stripped. Returns: The code without import statements. """ new_code = [] for line in code.splitlines(): if not line.lstrip().startswith('import ') and \...
[ "def", "remove_import_statements", "(", "code", ")", ":", "new_code", "=", "[", "]", "for", "line", "in", "code", ".", "splitlines", "(", ")", ":", "if", "not", "line", ".", "lstrip", "(", ")", ".", "startswith", "(", "'import '", ")", "and", "not", ...
Removes lines with import statements from the code. Args: code: The code to be stripped. Returns: The code without import statements.
[ "Removes", "lines", "with", "import", "statements", "from", "the", "code", "." ]
python
train
jjkester/moneybird-python
moneybird/api.py
https://github.com/jjkester/moneybird-python/blob/da5f4c8c7ae6c8ed717dc273514a464bc9c284ed/moneybird/api.py#L138-L190
def _process_response(response: requests.Response, expected: list = []) -> dict: """ Processes an API response. Raises an exception when appropriate. The exception that will be raised is MoneyBird.APIError. This exception is subclassed so implementing programs can easily react appropria...
[ "def", "_process_response", "(", "response", ":", "requests", ".", "Response", ",", "expected", ":", "list", "=", "[", "]", ")", "->", "dict", ":", "responses", "=", "{", "200", ":", "None", ",", "201", ":", "None", ",", "204", ":", "None", ",", "4...
Processes an API response. Raises an exception when appropriate. The exception that will be raised is MoneyBird.APIError. This exception is subclassed so implementing programs can easily react appropriately to different exceptions. The following subclasses of MoneyBird.APIError are likely to b...
[ "Processes", "an", "API", "response", ".", "Raises", "an", "exception", "when", "appropriate", "." ]
python
train
mikemaccana/python-docx
docx.py
https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L644-L661
def clean(document): """ Perform misc cleaning operations on documents. Returns cleaned document. """ newdocument = document # Clean empty text and r tags for t in ('t', 'r'): rmlist = [] for element in newdocument.iter(): if element.tag == '{%s}%s' % (nsprefixe...
[ "def", "clean", "(", "document", ")", ":", "newdocument", "=", "document", "# Clean empty text and r tags", "for", "t", "in", "(", "'t'", ",", "'r'", ")", ":", "rmlist", "=", "[", "]", "for", "element", "in", "newdocument", ".", "iter", "(", ")", ":", ...
Perform misc cleaning operations on documents. Returns cleaned document.
[ "Perform", "misc", "cleaning", "operations", "on", "documents", ".", "Returns", "cleaned", "document", "." ]
python
train
ldomic/lintools
lintools/lintools.py
https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/lintools.py#L87-L97
def analysis_of_prot_lig_interactions(self): """ The classes and function that deal with protein-ligand interaction analysis. """ self.hbonds = HBonds(self.topol_data,self.trajectory,self.start,self.end,self.skip,self.analysis_cutoff,distance=3) self.pistacking = PiStacking(self....
[ "def", "analysis_of_prot_lig_interactions", "(", "self", ")", ":", "self", ".", "hbonds", "=", "HBonds", "(", "self", ".", "topol_data", ",", "self", ".", "trajectory", ",", "self", ".", "start", ",", "self", ".", "end", ",", "self", ".", "skip", ",", ...
The classes and function that deal with protein-ligand interaction analysis.
[ "The", "classes", "and", "function", "that", "deal", "with", "protein", "-", "ligand", "interaction", "analysis", "." ]
python
train
mogproject/mog-commons-python
src/mog_commons/terminal.py
https://github.com/mogproject/mog-commons-python/blob/951cf0fa9a56248b4d45be720be25f1d4b7e1bff/src/mog_commons/terminal.py#L108-L122
def _get_restore_function(self): """ Return the binary function for restoring terminal attributes. :return: function (signal, frame) => None: """ if os.name == 'nt' or not self.getch_enabled: return lambda signal, frame: None try: fd = self.stdin....
[ "def", "_get_restore_function", "(", "self", ")", ":", "if", "os", ".", "name", "==", "'nt'", "or", "not", "self", ".", "getch_enabled", ":", "return", "lambda", "signal", ",", "frame", ":", "None", "try", ":", "fd", "=", "self", ".", "stdin", ".", "...
Return the binary function for restoring terminal attributes. :return: function (signal, frame) => None:
[ "Return", "the", "binary", "function", "for", "restoring", "terminal", "attributes", ".", ":", "return", ":", "function", "(", "signal", "frame", ")", "=", ">", "None", ":" ]
python
train
iotile/coretools
transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/bled112/iotile_transport_bled112/bled112_cmd.py#L290-L298
def _disable_rpcs(self, conn, services, timeout=1.0): """Prevent this device from receiving more RPCs """ success, result = self._set_notification(conn, services[TileBusService]['characteristics'][TileBusReceiveHeaderCharacteristic], False, timeout) if not success: return su...
[ "def", "_disable_rpcs", "(", "self", ",", "conn", ",", "services", ",", "timeout", "=", "1.0", ")", ":", "success", ",", "result", "=", "self", ".", "_set_notification", "(", "conn", ",", "services", "[", "TileBusService", "]", "[", "'characteristics'", "]...
Prevent this device from receiving more RPCs
[ "Prevent", "this", "device", "from", "receiving", "more", "RPCs" ]
python
train
KelSolaar/Umbra
umbra/components/factory/script_editor/models.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/models.py#L723-L737
def delete_authoring_nodes(self, editor): """ Deletes the Model authoring Nodes associated with given editor. :param editor: Editor. :type editor: Editor :return: Method success. :rtype: bool """ editor_node = foundations.common.get_first_item(self.get_e...
[ "def", "delete_authoring_nodes", "(", "self", ",", "editor", ")", ":", "editor_node", "=", "foundations", ".", "common", ".", "get_first_item", "(", "self", ".", "get_editor_nodes", "(", "editor", ")", ")", "file_node", "=", "editor_node", ".", "parent", "self...
Deletes the Model authoring Nodes associated with given editor. :param editor: Editor. :type editor: Editor :return: Method success. :rtype: bool
[ "Deletes", "the", "Model", "authoring", "Nodes", "associated", "with", "given", "editor", "." ]
python
train
hawkular/hawkular-client-python
hawkular/alerts/common.py
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/common.py#L81-L90
def status(self): """ Get the status of Alerting Service :return: Status object """ orig_dict = self._get(self._service_url('status')) orig_dict['implementation_version'] = orig_dict.pop('Implementation-Version') orig_dict['built_from_git_sha1'] = orig_dict.pop('...
[ "def", "status", "(", "self", ")", ":", "orig_dict", "=", "self", ".", "_get", "(", "self", ".", "_service_url", "(", "'status'", ")", ")", "orig_dict", "[", "'implementation_version'", "]", "=", "orig_dict", ".", "pop", "(", "'Implementation-Version'", ")",...
Get the status of Alerting Service :return: Status object
[ "Get", "the", "status", "of", "Alerting", "Service" ]
python
train
rbuffat/pyepw
pyepw/epw.py
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L1034-L1061
def coldestmonth(self, value=None): """Corresponds to IDD Field `coldestmonth` Args: value (int): value for IDD Field `coldestmonth` value >= 1 value <= 12 if `value` is None it will not be checked against the specification and...
[ "def", "coldestmonth", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type int...
Corresponds to IDD Field `coldestmonth` Args: value (int): value for IDD Field `coldestmonth` value >= 1 value <= 12 if `value` is None it will not be checked against the specification and is assumed to be a missing value Rais...
[ "Corresponds", "to", "IDD", "Field", "coldestmonth" ]
python
train
saltstack/salt
salt/modules/ps.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L119-L178
def top(num_processes=5, interval=3): ''' Return a list of top CPU consuming processes during the interval. num_processes = return the top N CPU consuming processes interval = the number of seconds to sample CPU usage over CLI Examples: .. code-block:: bash salt '*' ps.top sa...
[ "def", "top", "(", "num_processes", "=", "5", ",", "interval", "=", "3", ")", ":", "result", "=", "[", "]", "start_usage", "=", "{", "}", "for", "pid", "in", "psutil", ".", "pids", "(", ")", ":", "try", ":", "process", "=", "psutil", ".", "Proces...
Return a list of top CPU consuming processes during the interval. num_processes = return the top N CPU consuming processes interval = the number of seconds to sample CPU usage over CLI Examples: .. code-block:: bash salt '*' ps.top salt '*' ps.top 5 10
[ "Return", "a", "list", "of", "top", "CPU", "consuming", "processes", "during", "the", "interval", ".", "num_processes", "=", "return", "the", "top", "N", "CPU", "consuming", "processes", "interval", "=", "the", "number", "of", "seconds", "to", "sample", "CPU...
python
train
GetmeUK/MongoFrames
snippets/comparable.py
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/snippets/comparable.py#L151-L214
def diff_to_html(cls, details): """Return an entry's details in HTML format""" changes = [] # Check that there are details to convert to HMTL if not details: return '' def _frame(value): """ Handle converted `Frame` references where the human...
[ "def", "diff_to_html", "(", "cls", ",", "details", ")", ":", "changes", "=", "[", "]", "# Check that there are details to convert to HMTL", "if", "not", "details", ":", "return", "''", "def", "_frame", "(", "value", ")", ":", "\"\"\"\n Handle converted `F...
Return an entry's details in HTML format
[ "Return", "an", "entry", "s", "details", "in", "HTML", "format" ]
python
train
jdoda/sdl2hl
sdl2hl/rect.py
https://github.com/jdoda/sdl2hl/blob/3b477e1e01cea5d8e15e9e5ef3a302ea460f5946/sdl2hl/rect.py#L117-L126
def has_intersection(self, other): """Return whether this rectangle intersects with another rectangle. Args: other (Rect): The rectangle to test intersection with. Returns: bool: True if there is an intersection, False otherwise. """ return bool(lib.SDL_...
[ "def", "has_intersection", "(", "self", ",", "other", ")", ":", "return", "bool", "(", "lib", ".", "SDL_HasIntersection", "(", "self", ".", "_ptr", ",", "other", ".", "_ptr", ")", ")" ]
Return whether this rectangle intersects with another rectangle. Args: other (Rect): The rectangle to test intersection with. Returns: bool: True if there is an intersection, False otherwise.
[ "Return", "whether", "this", "rectangle", "intersects", "with", "another", "rectangle", "." ]
python
train
prajwalkr/track-it
trackit/trackers.py
https://github.com/prajwalkr/track-it/blob/01a91dba8e7bc169976e0b13faacf7dd7330237b/trackit/trackers.py#L421-L463
def Extract_Checkpoints(self): ''' Extract the checkpoints and store in self.tracking_data ''' # Make sure page is available if self.page is None: raise Exception("The HTML data was not fetched due to some reasons") soup = BeautifulSoup(self.page,'html.parser') if 'Delivery information not found' i...
[ "def", "Extract_Checkpoints", "(", "self", ")", ":", "# Make sure page is available", "if", "self", ".", "page", "is", "None", ":", "raise", "Exception", "(", "\"The HTML data was not fetched due to some reasons\"", ")", "soup", "=", "BeautifulSoup", "(", "self", ".",...
Extract the checkpoints and store in self.tracking_data
[ "Extract", "the", "checkpoints", "and", "store", "in", "self", ".", "tracking_data" ]
python
train
docker/docker-py
docker/models/plugins.py
https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/models/plugins.py#L100-L122
def upgrade(self, remote=None): """ Upgrade the plugin. Args: remote (string): Remote reference to upgrade to. The ``:latest`` tag is optional and is the default if omitted. Default: this plugin's name. Returns: ...
[ "def", "upgrade", "(", "self", ",", "remote", "=", "None", ")", ":", "if", "self", ".", "enabled", ":", "raise", "errors", ".", "DockerError", "(", "'Plugin must be disabled before upgrading.'", ")", "if", "remote", "is", "None", ":", "remote", "=", "self", ...
Upgrade the plugin. Args: remote (string): Remote reference to upgrade to. The ``:latest`` tag is optional and is the default if omitted. Default: this plugin's name. Returns: A generator streaming the decoded API logs
[ "Upgrade", "the", "plugin", "." ]
python
train
Captricity/captools
captools/api/client.py
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L207-L227
def _put_or_post_json(self, method, url, data): """ urlencodes the data and PUTs it to the url the response is parsed as JSON and the resulting data type is returned """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.net...
[ "def", "_put_or_post_json", "(", "self", ",", "method", ",", "url", ",", "data", ")", ":", "if", "self", ".", "parsed_endpoint", ".", "scheme", "==", "'https'", ":", "conn", "=", "httplib", ".", "HTTPSConnection", "(", "self", ".", "parsed_endpoint", ".", ...
urlencodes the data and PUTs it to the url the response is parsed as JSON and the resulting data type is returned
[ "urlencodes", "the", "data", "and", "PUTs", "it", "to", "the", "url", "the", "response", "is", "parsed", "as", "JSON", "and", "the", "resulting", "data", "type", "is", "returned" ]
python
train
Jajcus/pyxmpp2
pyxmpp2/roster.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/roster.py#L307-L321
def verify_roster_push(self, fix = False): """Check if `self` is valid roster push item. Valid item must have proper `subscription` value other and valid value for 'ask'. :Parameters: - `fix`: if `True` than replace invalid 'subscription' and 'ask' values with...
[ "def", "verify_roster_push", "(", "self", ",", "fix", "=", "False", ")", ":", "self", ".", "_verify", "(", "(", "None", ",", "u\"from\"", ",", "u\"to\"", ",", "u\"both\"", ",", "u\"remove\"", ")", ",", "fix", ")" ]
Check if `self` is valid roster push item. Valid item must have proper `subscription` value other and valid value for 'ask'. :Parameters: - `fix`: if `True` than replace invalid 'subscription' and 'ask' values with the defaults :Types: - `fix`: `bo...
[ "Check", "if", "self", "is", "valid", "roster", "push", "item", "." ]
python
valid
Kortemme-Lab/klab
klab/bio/basics.py
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/basics.py#L283-L290
def pdb_atom_name_to_element(s): '''s should be a string taken from columns 12-15 (zero-indexed) inclusive of a PDB coordinate line.''' assert(len(s) == 4) if len(s.strip()) == 4: assert(s[0] == 'H' or s[0] == 'C' or s[0] == 'O') # "If the name of a hydrogen has four characters, it is left-justified...
[ "def", "pdb_atom_name_to_element", "(", "s", ")", ":", "assert", "(", "len", "(", "s", ")", "==", "4", ")", "if", "len", "(", "s", ".", "strip", "(", ")", ")", "==", "4", ":", "assert", "(", "s", "[", "0", "]", "==", "'H'", "or", "s", "[", ...
s should be a string taken from columns 12-15 (zero-indexed) inclusive of a PDB coordinate line.
[ "s", "should", "be", "a", "string", "taken", "from", "columns", "12", "-", "15", "(", "zero", "-", "indexed", ")", "inclusive", "of", "a", "PDB", "coordinate", "line", "." ]
python
train
AtteqCom/zsl
src/zsl/resource/resource_helper.py
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/resource_helper.py#L173-L184
def flat_model(tree): """Flatten the tree into a list of properties adding parents as prefixes.""" names = [] for columns in viewvalues(tree): for col in columns: if isinstance(col, dict): col_name = list(col)[0] names += [col_name + '__' + c for c in flat...
[ "def", "flat_model", "(", "tree", ")", ":", "names", "=", "[", "]", "for", "columns", "in", "viewvalues", "(", "tree", ")", ":", "for", "col", "in", "columns", ":", "if", "isinstance", "(", "col", ",", "dict", ")", ":", "col_name", "=", "list", "("...
Flatten the tree into a list of properties adding parents as prefixes.
[ "Flatten", "the", "tree", "into", "a", "list", "of", "properties", "adding", "parents", "as", "prefixes", "." ]
python
train
Tanganelli/CoAPthon3
coapthon/layers/requestlayer.py
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/requestlayer.py#L99-L115
def _handle_post(self, transaction): """ Handle POST requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ path = str("/"...
[ "def", "_handle_post", "(", "self", ",", "transaction", ")", ":", "path", "=", "str", "(", "\"/\"", "+", "transaction", ".", "request", ".", "uri_path", ")", "transaction", ".", "response", "=", "Response", "(", ")", "transaction", ".", "response", ".", ...
Handle POST requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request
[ "Handle", "POST", "requests" ]
python
train
gbowerman/azurerm
azurerm/amsrp.py
https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/amsrp.py#L862-L876
def helper_list(access_token, oid, path): '''Helper Function to list a URL path. Args: access_token (str): A valid Azure authentication token. oid (str): An OID. path (str): A URL Path. Returns: HTTP response. JSON body. ''' if oid != "": path = ''.join([pat...
[ "def", "helper_list", "(", "access_token", ",", "oid", ",", "path", ")", ":", "if", "oid", "!=", "\"\"", ":", "path", "=", "''", ".", "join", "(", "[", "path", ",", "\"('\"", ",", "oid", ",", "\"')\"", "]", ")", "endpoint", "=", "''", ".", "join"...
Helper Function to list a URL path. Args: access_token (str): A valid Azure authentication token. oid (str): An OID. path (str): A URL Path. Returns: HTTP response. JSON body.
[ "Helper", "Function", "to", "list", "a", "URL", "path", "." ]
python
train
thomasdelaet/python-velbus
velbus/controller.py
https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/controller.py#L96-L121
def scan(self, callback=None): """ Scan the bus and call the callback when a new module is discovered :return: None """ def scan_finished(): """ Callback when scan is finished """ time.sleep(3) logging.info('Scan finish...
[ "def", "scan", "(", "self", ",", "callback", "=", "None", ")", ":", "def", "scan_finished", "(", ")", ":", "\"\"\"\n Callback when scan is finished\n \"\"\"", "time", ".", "sleep", "(", "3", ")", "logging", ".", "info", "(", "'Scan finished'"...
Scan the bus and call the callback when a new module is discovered :return: None
[ "Scan", "the", "bus", "and", "call", "the", "callback", "when", "a", "new", "module", "is", "discovered" ]
python
train
erikrose/more-itertools
more_itertools/more.py
https://github.com/erikrose/more-itertools/blob/6a91b4e25c8e12fcf9fc2b53cf8ee0fba293e6f9/more_itertools/more.py#L1401-L1451
def always_iterable(obj, base_type=(str, bytes)): """If *obj* is iterable, return an iterator over its items:: >>> obj = (1, 2, 3) >>> list(always_iterable(obj)) [1, 2, 3] If *obj* is not iterable, return a one-item iterable containing *obj*:: >>> obj = 1 >>> list(alwa...
[ "def", "always_iterable", "(", "obj", ",", "base_type", "=", "(", "str", ",", "bytes", ")", ")", ":", "if", "obj", "is", "None", ":", "return", "iter", "(", "(", ")", ")", "if", "(", "base_type", "is", "not", "None", ")", "and", "isinstance", "(", ...
If *obj* is iterable, return an iterator over its items:: >>> obj = (1, 2, 3) >>> list(always_iterable(obj)) [1, 2, 3] If *obj* is not iterable, return a one-item iterable containing *obj*:: >>> obj = 1 >>> list(always_iterable(obj)) [1] If *obj* is ``None``, ...
[ "If", "*", "obj", "*", "is", "iterable", "return", "an", "iterator", "over", "its", "items", "::" ]
python
train
has2k1/plotnine
plotnine/qplot.py
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/qplot.py#L21-L215
def qplot(x=None, y=None, data=None, facets=None, margins=False, geom='auto', xlim=None, ylim=None, log='', main=None, xlab=None, ylab=None, asp=None, **kwargs): """ Quick plot Parameters ---------- x : str | array_like x aesthetic y : str | array_like y aest...
[ "def", "qplot", "(", "x", "=", "None", ",", "y", "=", "None", ",", "data", "=", "None", ",", "facets", "=", "None", ",", "margins", "=", "False", ",", "geom", "=", "'auto'", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "log", "=", ...
Quick plot Parameters ---------- x : str | array_like x aesthetic y : str | array_like y aesthetic data : dataframe Data frame to use (optional). If not specified, will create one, extracting arrays from the current environment. geom : str | list ...
[ "Quick", "plot" ]
python
train
slhck/ffmpeg-normalize
ffmpeg_normalize/_media_file.py
https://github.com/slhck/ffmpeg-normalize/blob/18477a7f2d092777ee238340be40c04ecb45c132/ffmpeg_normalize/_media_file.py#L51-L114
def parse_streams(self): """ Try to parse all input streams from file """ logger.debug("Parsing streams of {}".format(self.input_file)) cmd = [ self.ffmpeg_normalize.ffmpeg_exe, '-i', self.input_file, '-c', 'copy', '-t', '0', '-map', '0', '-f'...
[ "def", "parse_streams", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Parsing streams of {}\"", ".", "format", "(", "self", ".", "input_file", ")", ")", "cmd", "=", "[", "self", ".", "ffmpeg_normalize", ".", "ffmpeg_exe", ",", "'-i'", ",", "self",...
Try to parse all input streams from file
[ "Try", "to", "parse", "all", "input", "streams", "from", "file" ]
python
train
blockstack/blockstack-core
blockstack/lib/storage/crawl.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/storage/crawl.py#L208-L221
def add_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=True): """ Add a zone file to the atlas zonefiles Return True on success Return False on error """ rc = store_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=fsync) if not rc: zonefile_hash = get_zonefile_data_has...
[ "def", "add_atlas_zonefile_data", "(", "zonefile_text", ",", "zonefile_dir", ",", "fsync", "=", "True", ")", ":", "rc", "=", "store_atlas_zonefile_data", "(", "zonefile_text", ",", "zonefile_dir", ",", "fsync", "=", "fsync", ")", "if", "not", "rc", ":", "zonef...
Add a zone file to the atlas zonefiles Return True on success Return False on error
[ "Add", "a", "zone", "file", "to", "the", "atlas", "zonefiles", "Return", "True", "on", "success", "Return", "False", "on", "error" ]
python
train
Kentzo/Power
power/darwin.py
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L209-L215
def stopPowerNotificationsThread(self): """Removes the only source from NSRunLoop and cancels thread.""" assert NSThread.currentThread() == self._thread CFRunLoopSourceInvalidate(self._source) self._source = None NSThread.currentThread().cancel()
[ "def", "stopPowerNotificationsThread", "(", "self", ")", ":", "assert", "NSThread", ".", "currentThread", "(", ")", "==", "self", ".", "_thread", "CFRunLoopSourceInvalidate", "(", "self", ".", "_source", ")", "self", ".", "_source", "=", "None", "NSThread", "....
Removes the only source from NSRunLoop and cancels thread.
[ "Removes", "the", "only", "source", "from", "NSRunLoop", "and", "cancels", "thread", "." ]
python
train
jopohl/urh
src/urh/controller/CompareFrameController.py
https://github.com/jopohl/urh/blob/2eb33b125c8407964cd1092843cde5010eb88aae/src/urh/controller/CompareFrameController.py#L201-L207
def protocols(self): """ :rtype: dict[int, list of ProtocolAnalyzer] """ if self.__protocols is None: self.__protocols = self.proto_tree_model.protocols return self.__protocols
[ "def", "protocols", "(", "self", ")", ":", "if", "self", ".", "__protocols", "is", "None", ":", "self", ".", "__protocols", "=", "self", ".", "proto_tree_model", ".", "protocols", "return", "self", ".", "__protocols" ]
:rtype: dict[int, list of ProtocolAnalyzer]
[ ":", "rtype", ":", "dict", "[", "int", "list", "of", "ProtocolAnalyzer", "]" ]
python
train
guaix-ucm/numina
numina/logger.py
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/logger.py#L30-L54
def log_to_history(logger, name): """Decorate function, adding a logger handler stored in FITS.""" def log_to_history_decorator(method): def l2h_method(self, ri): history_header = fits.Header() fh = FITSHistoryHandler(history_header) fh.setLevel(logging.INFO) ...
[ "def", "log_to_history", "(", "logger", ",", "name", ")", ":", "def", "log_to_history_decorator", "(", "method", ")", ":", "def", "l2h_method", "(", "self", ",", "ri", ")", ":", "history_header", "=", "fits", ".", "Header", "(", ")", "fh", "=", "FITSHist...
Decorate function, adding a logger handler stored in FITS.
[ "Decorate", "function", "adding", "a", "logger", "handler", "stored", "in", "FITS", "." ]
python
train
androguard/androguard
androguard/core/bytecodes/axml/__init__.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/axml/__init__.py#L2383-L2392
def get_language_and_region(self): """ Returns the combined language+region string or \x00\x00 for the default locale :return: """ if self.locale != 0: _language = self._unpack_language_or_region([self.locale & 0xff, (self.locale & 0xff00) >> 8, ], ord('a')) ...
[ "def", "get_language_and_region", "(", "self", ")", ":", "if", "self", ".", "locale", "!=", "0", ":", "_language", "=", "self", ".", "_unpack_language_or_region", "(", "[", "self", ".", "locale", "&", "0xff", ",", "(", "self", ".", "locale", "&", "0xff00...
Returns the combined language+region string or \x00\x00 for the default locale :return:
[ "Returns", "the", "combined", "language", "+", "region", "string", "or", "\\", "x00", "\\", "x00", "for", "the", "default", "locale", ":", "return", ":" ]
python
train
roboogle/gtkmvc3
gtkmvco/examples/undo/undo_manager.py
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/examples/undo/undo_manager.py#L78-L82
def can_undo(self): """ Are there actions to undo? """ return bool(self._undo) or bool(self._open and self._open[0])
[ "def", "can_undo", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "_undo", ")", "or", "bool", "(", "self", ".", "_open", "and", "self", ".", "_open", "[", "0", "]", ")" ]
Are there actions to undo?
[ "Are", "there", "actions", "to", "undo?" ]
python
train
resync/resync
resync/list_base_with_index.py
https://github.com/resync/resync/blob/98292c17b2c00f2d6f5191c6ab51fef8c292a018/resync/list_base_with_index.py#L352-L356
def index_as_xml(self): """XML serialization of this list taken to be sitemapindex entries.""" self.default_capability() s = self.new_sitemap() return s.resources_as_xml(self, sitemapindex=True)
[ "def", "index_as_xml", "(", "self", ")", ":", "self", ".", "default_capability", "(", ")", "s", "=", "self", ".", "new_sitemap", "(", ")", "return", "s", ".", "resources_as_xml", "(", "self", ",", "sitemapindex", "=", "True", ")" ]
XML serialization of this list taken to be sitemapindex entries.
[ "XML", "serialization", "of", "this", "list", "taken", "to", "be", "sitemapindex", "entries", "." ]
python
train
Tanganelli/CoAPthon3
coapthon/client/coap.py
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/coap.py#L309-L321
def _send_rst(self, transaction): # pragma: no cover """ Sends an RST message for the response. :param transaction: transaction that holds the response """ rst = Message() rst.type = defines.Types['RST'] if not transaction.response.acknowledged: rs...
[ "def", "_send_rst", "(", "self", ",", "transaction", ")", ":", "# pragma: no cover", "rst", "=", "Message", "(", ")", "rst", ".", "type", "=", "defines", ".", "Types", "[", "'RST'", "]", "if", "not", "transaction", ".", "response", ".", "acknowledged", "...
Sends an RST message for the response. :param transaction: transaction that holds the response
[ "Sends", "an", "RST", "message", "for", "the", "response", "." ]
python
train
coins13/twins
twins/twins.py
https://github.com/coins13/twins/blob/d66cc850007a25f01812a9d8c7e3efe64a631ca2/twins/twins.py#L274-L306
def get_registered_courses (self): """ 履修登録済み授業を取得 """ kdb = twins.kdb.Kdb() _reged = [] for x in ((1, "A"), (2, "A"), (3, "A"), (4, "B"), (5, "B"), (6, "B")): self.req("RSW0001000-flow") self.get({ "_eventId": "search", ...
[ "def", "get_registered_courses", "(", "self", ")", ":", "kdb", "=", "twins", ".", "kdb", ".", "Kdb", "(", ")", "_reged", "=", "[", "]", "for", "x", "in", "(", "(", "1", ",", "\"A\"", ")", ",", "(", "2", ",", "\"A\"", ")", ",", "(", "3", ",", ...
履修登録済み授業を取得
[ "履修登録済み授業を取得" ]
python
train
vertexproject/synapse
synapse/lib/base.py
https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/base.py#L161-L170
def onfini(self, func): ''' Add a function/coroutine/Base to be called on fini(). ''' if isinstance(func, Base): self.tofini.add(func) return assert self.anitted self._fini_funcs.append(func)
[ "def", "onfini", "(", "self", ",", "func", ")", ":", "if", "isinstance", "(", "func", ",", "Base", ")", ":", "self", ".", "tofini", ".", "add", "(", "func", ")", "return", "assert", "self", ".", "anitted", "self", ".", "_fini_funcs", ".", "append", ...
Add a function/coroutine/Base to be called on fini().
[ "Add", "a", "function", "/", "coroutine", "/", "Base", "to", "be", "called", "on", "fini", "()", "." ]
python
train
croscon/fleaker
fleaker/peewee/mixins/search.py
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/peewee/mixins/search.py#L97-L180
def search(cls, term, fields=()): """Generic SQL search function that uses SQL ``LIKE`` to search the database for matching records. The records are sorted by their relavancey to the search term. The query searches and sorts on the folling criteria, in order, where the target st...
[ "def", "search", "(", "cls", ",", "term", ",", "fields", "=", "(", ")", ")", ":", "if", "not", "any", "(", "(", "cls", ".", "_meta", ".", "search_fields", ",", "fields", ")", ")", ":", "raise", "AttributeError", "(", "\"A list of searchable fields must b...
Generic SQL search function that uses SQL ``LIKE`` to search the database for matching records. The records are sorted by their relavancey to the search term. The query searches and sorts on the folling criteria, in order, where the target string is ``exactly``: 1. Straight equ...
[ "Generic", "SQL", "search", "function", "that", "uses", "SQL", "LIKE", "to", "search", "the", "database", "for", "matching", "records", ".", "The", "records", "are", "sorted", "by", "their", "relavancey", "to", "the", "search", "term", "." ]
python
train
nickmckay/LiPD-utilities
Python/lipd/lpd_noaa.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L806-L823
def __get_filename(table): """ Get filename from a data table :param dict table: :return str: """ try: filename = table['filename'] except KeyError as e: filename = "" logger_lpd_noaa.warning("get_filename: KeyError: Table missi...
[ "def", "__get_filename", "(", "table", ")", ":", "try", ":", "filename", "=", "table", "[", "'filename'", "]", "except", "KeyError", "as", "e", ":", "filename", "=", "\"\"", "logger_lpd_noaa", ".", "warning", "(", "\"get_filename: KeyError: Table missing filename,...
Get filename from a data table :param dict table: :return str:
[ "Get", "filename", "from", "a", "data", "table", ":", "param", "dict", "table", ":", ":", "return", "str", ":" ]
python
train
netpieio/microgear-python
microgear/cache.py
https://github.com/netpieio/microgear-python/blob/ea9bb352c7dd84b92f3462177645eaa4d448d50b/microgear/cache.py#L9-L16
def get_item(key): """Return content in cached file in JSON format""" CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key) try: return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"] except (IOError, ValueError): return None
[ "def", "get_item", "(", "key", ")", ":", "CACHED_KEY_FILE", "=", "os", ".", "path", ".", "join", "(", "CURRENT_DIR", ",", "key", ")", "try", ":", "return", "json", ".", "loads", "(", "open", "(", "CACHED_KEY_FILE", ",", "\"rb\"", ")", ".", "read", "(...
Return content in cached file in JSON format
[ "Return", "content", "in", "cached", "file", "in", "JSON", "format" ]
python
train
ladybug-tools/ladybug
ladybug/_datacollectionbase.py
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/_datacollectionbase.py#L607-L626
def _percentile(self, values, percent, key=lambda x: x): """Find the percentile of a list of values. Args: values: A list of values for which percentiles are desired percent: A float value from 0 to 100 representing the requested percentile. key: optional key functio...
[ "def", "_percentile", "(", "self", ",", "values", ",", "percent", ",", "key", "=", "lambda", "x", ":", "x", ")", ":", "vals", "=", "sorted", "(", "values", ")", "k", "=", "(", "len", "(", "vals", ")", "-", "1", ")", "*", "(", "percent", "/", ...
Find the percentile of a list of values. Args: values: A list of values for which percentiles are desired percent: A float value from 0 to 100 representing the requested percentile. key: optional key function to compute value from each element of N. Return: ...
[ "Find", "the", "percentile", "of", "a", "list", "of", "values", "." ]
python
train
kensho-technologies/graphql-compiler
setup.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/setup.py#L33-L40
def find_name(): """Only define name in one place""" name_file = read_file('__init__.py') name_match = re.search(r'^__package_name__ = ["\']([^"\']*)["\']', name_file, re.M) if name_match: return name_match.group(1) raise RuntimeError('Unable to find name string.')
[ "def", "find_name", "(", ")", ":", "name_file", "=", "read_file", "(", "'__init__.py'", ")", "name_match", "=", "re", ".", "search", "(", "r'^__package_name__ = [\"\\']([^\"\\']*)[\"\\']'", ",", "name_file", ",", "re", ".", "M", ")", "if", "name_match", ":", "...
Only define name in one place
[ "Only", "define", "name", "in", "one", "place" ]
python
train
minhhoit/yacms
yacms/generic/managers.py
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/managers.py#L46-L59
def get_or_create_iexact(self, **kwargs): """ Case insensitive title version of ``get_or_create``. Also allows for multiple existing results. """ lookup = dict(**kwargs) try: lookup["title__iexact"] = lookup.pop("title") except KeyError: pa...
[ "def", "get_or_create_iexact", "(", "self", ",", "*", "*", "kwargs", ")", ":", "lookup", "=", "dict", "(", "*", "*", "kwargs", ")", "try", ":", "lookup", "[", "\"title__iexact\"", "]", "=", "lookup", ".", "pop", "(", "\"title\"", ")", "except", "KeyErr...
Case insensitive title version of ``get_or_create``. Also allows for multiple existing results.
[ "Case", "insensitive", "title", "version", "of", "get_or_create", ".", "Also", "allows", "for", "multiple", "existing", "results", "." ]
python
train
allenai/allennlp
allennlp/modules/token_embedders/embedding.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/token_embedders/embedding.py#L374-L443
def _read_embeddings_from_text_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: """ Read pre-trained word vectors from an eventually compressed t...
[ "def", "_read_embeddings_from_text_file", "(", "file_uri", ":", "str", ",", "embedding_dim", ":", "int", ",", "vocab", ":", "Vocabulary", ",", "namespace", ":", "str", "=", "\"tokens\"", ")", "->", "torch", ".", "FloatTensor", ":", "tokens_to_keep", "=", "set"...
Read pre-trained word vectors from an eventually compressed text file, possibly contained inside an archive with multiple files. The text file is assumed to be utf-8 encoded with space-separated fields: [word] [dim 1] [dim 2] ... Lines that contain more numerical tokens than ``embedding_dim`` raise a warni...
[ "Read", "pre", "-", "trained", "word", "vectors", "from", "an", "eventually", "compressed", "text", "file", "possibly", "contained", "inside", "an", "archive", "with", "multiple", "files", ".", "The", "text", "file", "is", "assumed", "to", "be", "utf", "-", ...
python
train
lsst-sqre/documenteer
documenteer/sphinxext/lssttasks/topiclists.py
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/topiclists.py#L74-L104
def _build_toctree(self): """Create a hidden toctree node with the contents of a directory prefixed by the directory name specified by the `toctree` directive option. """ dirname = posixpath.dirname(self._env.docname) tree_prefix = self.options['toctree'].strip() ...
[ "def", "_build_toctree", "(", "self", ")", ":", "dirname", "=", "posixpath", ".", "dirname", "(", "self", ".", "_env", ".", "docname", ")", "tree_prefix", "=", "self", ".", "options", "[", "'toctree'", "]", ".", "strip", "(", ")", "root", "=", "posixpa...
Create a hidden toctree node with the contents of a directory prefixed by the directory name specified by the `toctree` directive option.
[ "Create", "a", "hidden", "toctree", "node", "with", "the", "contents", "of", "a", "directory", "prefixed", "by", "the", "directory", "name", "specified", "by", "the", "toctree", "directive", "option", "." ]
python
train
mikkeljans/pyconomic
pyconomic/base.py
https://github.com/mikkeljans/pyconomic/blob/845b8148a364cf5be9065f8a70133d4f16ab645d/pyconomic/base.py#L76-L117
def __find_handles(self, model, **spec): """ find model instances based on given filter (spec) The filter is based on available server-calls, so some values might not be available for filtering. Multiple filter-values is going to do multiple server-calls. For complex filters in small dat...
[ "def", "__find_handles", "(", "self", ",", "model", ",", "*", "*", "spec", ")", ":", "server_calls", "=", "[", "]", "filter_names", "=", "dict", "(", "[", "(", "f", "[", "'name'", "]", ",", "f", "[", "'method'", "]", ",", ")", "for", "f", "in", ...
find model instances based on given filter (spec) The filter is based on available server-calls, so some values might not be available for filtering. Multiple filter-values is going to do multiple server-calls. For complex filters in small datasets, it might be faster to fetch all and do your ow...
[ "find", "model", "instances", "based", "on", "given", "filter", "(", "spec", ")", "The", "filter", "is", "based", "on", "available", "server", "-", "calls", "so", "some", "values", "might", "not", "be", "available", "for", "filtering", ".", "Multiple", "fi...
python
train
trailofbits/manticore
manticore/core/manticore.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/manticore.py#L424-L439
def run(self, procs=1, timeout=None, should_profile=False): """ Runs analysis. :param int procs: Number of parallel worker processes :param timeout: Analysis timeout, in seconds """ assert not self.running, "Manticore is already running." self._start_run() ...
[ "def", "run", "(", "self", ",", "procs", "=", "1", ",", "timeout", "=", "None", ",", "should_profile", "=", "False", ")", ":", "assert", "not", "self", ".", "running", ",", "\"Manticore is already running.\"", "self", ".", "_start_run", "(", ")", "self", ...
Runs analysis. :param int procs: Number of parallel worker processes :param timeout: Analysis timeout, in seconds
[ "Runs", "analysis", "." ]
python
valid
TomasTomecek/sen
sen/tui/commands/base.py
https://github.com/TomasTomecek/sen/blob/239b4868125814e8bf5527708119fc08b35f6cc0/sen/tui/commands/base.py#L120-L159
def process(self, argument_list): """ :param argument_list: list of str, input from user :return: dict: {"cleaned_arg_name": "value"} """ arg_index = 0 for a in argument_list: opt_and_val = a.split("=", 1) opt_name = opt_and_val[0] ...
[ "def", "process", "(", "self", ",", "argument_list", ")", ":", "arg_index", "=", "0", "for", "a", "in", "argument_list", ":", "opt_and_val", "=", "a", ".", "split", "(", "\"=\"", ",", "1", ")", "opt_name", "=", "opt_and_val", "[", "0", "]", "try", ":...
:param argument_list: list of str, input from user :return: dict: {"cleaned_arg_name": "value"}
[ ":", "param", "argument_list", ":", "list", "of", "str", "input", "from", "user", ":", "return", ":", "dict", ":", "{", "cleaned_arg_name", ":", "value", "}" ]
python
train
spyder-ide/spyder
spyder/widgets/browser.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/browser.py#L301-L304
def url_combo_activated(self, valid): """Load URL from combo box first item""" text = to_text_string(self.url_combo.currentText()) self.go_to(self.text_to_url(text))
[ "def", "url_combo_activated", "(", "self", ",", "valid", ")", ":", "text", "=", "to_text_string", "(", "self", ".", "url_combo", ".", "currentText", "(", ")", ")", "self", ".", "go_to", "(", "self", ".", "text_to_url", "(", "text", ")", ")" ]
Load URL from combo box first item
[ "Load", "URL", "from", "combo", "box", "first", "item" ]
python
train
owncloud/pyocclient
owncloud/owncloud.py
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1722-L1749
def _make_dav_request(self, method, path, **kwargs): """Makes a WebDAV request :param method: HTTP method :param path: remote path of the targetted file :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns array of :class:`FileInfo` if the res...
[ "def", "_make_dav_request", "(", "self", ",", "method", ",", "path", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_debug", ":", "print", "(", "'DAV request: %s %s'", "%", "(", "method", ",", "path", ")", ")", "if", "kwargs", ".", "get", "("...
Makes a WebDAV request :param method: HTTP method :param path: remote path of the targetted file :param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts :returns array of :class:`FileInfo` if the response contains it, or True if the operation succeded, Fa...
[ "Makes", "a", "WebDAV", "request" ]
python
train
mgoral/subconvert
src/subconvert/utils/SubtitleSearch.py
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/SubtitleSearch.py#L45-L52
def last(self): """Returns the last element accessed via next() or prev(). Returns the first element of range() if neither of these was called.""" if len(self._range) == 0: raise IndexError("range is empty") if self._idx == -1: return self._range[0] return...
[ "def", "last", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_range", ")", "==", "0", ":", "raise", "IndexError", "(", "\"range is empty\"", ")", "if", "self", ".", "_idx", "==", "-", "1", ":", "return", "self", ".", "_range", "[", "0", ...
Returns the last element accessed via next() or prev(). Returns the first element of range() if neither of these was called.
[ "Returns", "the", "last", "element", "accessed", "via", "next", "()", "or", "prev", "()", ".", "Returns", "the", "first", "element", "of", "range", "()", "if", "neither", "of", "these", "was", "called", "." ]
python
train
Unidata/MetPy
metpy/io/_nexrad_msgs/parse_spec.py
https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/io/_nexrad_msgs/parse_spec.py#L138-L146
def fix_desc(desc, units=None): """Clean up description column.""" full_desc = desc.strip() if units and units != 'N/A': if full_desc: full_desc += ' (' + units + ')' else: full_desc = units return full_desc
[ "def", "fix_desc", "(", "desc", ",", "units", "=", "None", ")", ":", "full_desc", "=", "desc", ".", "strip", "(", ")", "if", "units", "and", "units", "!=", "'N/A'", ":", "if", "full_desc", ":", "full_desc", "+=", "' ('", "+", "units", "+", "')'", "...
Clean up description column.
[ "Clean", "up", "description", "column", "." ]
python
train
Apstra/aeon-venos
pylib/aeon/nxos/autoload/guestshell.py
https://github.com/Apstra/aeon-venos/blob/4d4f73d5904831ddc78c30922a8a226c90cf7d90/pylib/aeon/nxos/autoload/guestshell.py#L150-L177
def sudoers(self, enable): """ This method is used to enable/disable bash sudo commands running through the guestshell virtual service. By default sudo access is prevented due to the setting in the 'sudoers' file. Therefore the setting must be disabled in the file to enable sud...
[ "def", "sudoers", "(", "self", ",", "enable", ")", ":", "f_sudoers", "=", "\"/isan/vdc_1/virtual-instance/guestshell+/rootfs/etc/sudoers\"", "if", "enable", "is", "True", ":", "sed_cmd", "=", "r\" 's/\\(^Defaults *requiretty\\)/#\\1/g' \"", "elif", "enable", "is", "False"...
This method is used to enable/disable bash sudo commands running through the guestshell virtual service. By default sudo access is prevented due to the setting in the 'sudoers' file. Therefore the setting must be disabled in the file to enable sudo commands. This method assumes that t...
[ "This", "method", "is", "used", "to", "enable", "/", "disable", "bash", "sudo", "commands", "running", "through", "the", "guestshell", "virtual", "service", ".", "By", "default", "sudo", "access", "is", "prevented", "due", "to", "the", "setting", "in", "the"...
python
train
ARMmbed/icetea
icetea_lib/Plugin/PluginManager.py
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/Plugin/PluginManager.py#L90-L106
def register_run_plugins(self, plugin_name, plugin_class): """ Loads a plugin as a dictionary and attaches needed parts to correct Icetea run global parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing """ if plu...
[ "def", "register_run_plugins", "(", "self", ",", "plugin_name", ",", "plugin_class", ")", ":", "if", "plugin_name", "in", "self", ".", "registered_plugins", ":", "raise", "PluginException", "(", "\"Plugin {} already registered! \"", "\"Duplicate plugins?\"", ".", "forma...
Loads a plugin as a dictionary and attaches needed parts to correct Icetea run global parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing
[ "Loads", "a", "plugin", "as", "a", "dictionary", "and", "attaches", "needed", "parts", "to", "correct", "Icetea", "run", "global", "parts", "." ]
python
train
saltstack/salt
salt/client/ssh/ssh_py_shim.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/ssh_py_shim.py#L143-L156
def get_hash(path, form='sha1', chunk_size=4096): ''' Generate a hash digest string for a file. ''' try: hash_type = getattr(hashlib, form) except AttributeError: raise ValueError('Invalid hash type: {0}'.format(form)) with open(path, 'rb') as ifile: hash_obj = hash_type(...
[ "def", "get_hash", "(", "path", ",", "form", "=", "'sha1'", ",", "chunk_size", "=", "4096", ")", ":", "try", ":", "hash_type", "=", "getattr", "(", "hashlib", ",", "form", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", "'Invalid hash typ...
Generate a hash digest string for a file.
[ "Generate", "a", "hash", "digest", "string", "for", "a", "file", "." ]
python
train
mbakker7/timml
timml/element.py
https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/element.py#L41-L46
def potentiallayers(self, x, y, layers, aq=None): '''Returns array of size len(layers) only used in building equations''' if aq is None: aq = self.model.aq.find_aquifer_data(x, y) pot = np.sum(self.potential(x, y, aq) * aq.eigvec, 1 ) return pot[layers]
[ "def", "potentiallayers", "(", "self", ",", "x", ",", "y", ",", "layers", ",", "aq", "=", "None", ")", ":", "if", "aq", "is", "None", ":", "aq", "=", "self", ".", "model", ".", "aq", ".", "find_aquifer_data", "(", "x", ",", "y", ")", "pot", "="...
Returns array of size len(layers) only used in building equations
[ "Returns", "array", "of", "size", "len", "(", "layers", ")", "only", "used", "in", "building", "equations" ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/mainwindow.py#L121-L132
def create_tab_with_current_kernel(self): """create a new frontend attached to the same kernel as the current tab""" current_widget = self.tab_widget.currentWidget() current_widget_index = self.tab_widget.indexOf(current_widget) current_widget_name = self.tab_widget.tabText(current_widge...
[ "def", "create_tab_with_current_kernel", "(", "self", ")", ":", "current_widget", "=", "self", ".", "tab_widget", ".", "currentWidget", "(", ")", "current_widget_index", "=", "self", ".", "tab_widget", ".", "indexOf", "(", "current_widget", ")", "current_widget_name...
create a new frontend attached to the same kernel as the current tab
[ "create", "a", "new", "frontend", "attached", "to", "the", "same", "kernel", "as", "the", "current", "tab" ]
python
test
Rapptz/discord.py
discord/ext/commands/core.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1039-L1075
def get_command(self, name): """Get a :class:`.Command` or subclasses from the internal list of commands. This could also be used as a way to get aliases. The name could be fully qualified (e.g. ``'foo bar'``) will get the subcommand ``bar`` of the group command ``foo``. If a ...
[ "def", "get_command", "(", "self", ",", "name", ")", ":", "# fast path, no space in name.", "if", "' '", "not", "in", "name", ":", "return", "self", ".", "all_commands", ".", "get", "(", "name", ")", "names", "=", "name", ".", "split", "(", ")", "obj", ...
Get a :class:`.Command` or subclasses from the internal list of commands. This could also be used as a way to get aliases. The name could be fully qualified (e.g. ``'foo bar'``) will get the subcommand ``bar`` of the group command ``foo``. If a subcommand is not found then ``No...
[ "Get", "a", ":", "class", ":", ".", "Command", "or", "subclasses", "from", "the", "internal", "list", "of", "commands", "." ]
python
train
adrianoveiga/django-media-fixtures
django_media_fixtures/finders.py
https://github.com/adrianoveiga/django-media-fixtures/blob/a3f0d9ac84e73d491eeb0c881b23cc47ccca1b54/django_media_fixtures/finders.py#L180-L189
def get_finder(import_path): """ Imports the media fixtures files finder class described by import_path, where import_path is the full Python path to the class. """ Finder = import_string(import_path) if not issubclass(Finder, BaseFinder): raise ImproperlyConfigured('Finder "%s" is not a...
[ "def", "get_finder", "(", "import_path", ")", ":", "Finder", "=", "import_string", "(", "import_path", ")", "if", "not", "issubclass", "(", "Finder", ",", "BaseFinder", ")", ":", "raise", "ImproperlyConfigured", "(", "'Finder \"%s\" is not a subclass of \"%s\"'", "%...
Imports the media fixtures files finder class described by import_path, where import_path is the full Python path to the class.
[ "Imports", "the", "media", "fixtures", "files", "finder", "class", "described", "by", "import_path", "where", "import_path", "is", "the", "full", "Python", "path", "to", "the", "class", "." ]
python
valid
Hackerfleet/hfos
hfos/ui/clientmanager.py
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/ui/clientmanager.py#L825-L834
def getlanguages(self, event): """Compile and return a human readable list of registered translations""" self.log('Client requests all languages.', lvl=verbose) result = { 'component': 'hfos.ui.clientmanager', 'action': 'getlanguages', 'data': language_token_...
[ "def", "getlanguages", "(", "self", ",", "event", ")", ":", "self", ".", "log", "(", "'Client requests all languages.'", ",", "lvl", "=", "verbose", ")", "result", "=", "{", "'component'", ":", "'hfos.ui.clientmanager'", ",", "'action'", ":", "'getlanguages'", ...
Compile and return a human readable list of registered translations
[ "Compile", "and", "return", "a", "human", "readable", "list", "of", "registered", "translations" ]
python
train
tansey/gfl
pygfl/trails.py
https://github.com/tansey/gfl/blob/ae0f078bab57aba9e827ed6162f247ff9dc2aa19/pygfl/trails.py#L50-L79
def calc_euler_tour(g, start, end): '''Calculates an Euler tour over the graph g from vertex start to vertex end. Assumes start and end are odd-degree vertices and that there are no other odd-degree vertices.''' even_g = nx.subgraph(g, g.nodes()).copy() if end in even_g.neighbors(start): # I...
[ "def", "calc_euler_tour", "(", "g", ",", "start", ",", "end", ")", ":", "even_g", "=", "nx", ".", "subgraph", "(", "g", ",", "g", ".", "nodes", "(", ")", ")", ".", "copy", "(", ")", "if", "end", "in", "even_g", ".", "neighbors", "(", "start", "...
Calculates an Euler tour over the graph g from vertex start to vertex end. Assumes start and end are odd-degree vertices and that there are no other odd-degree vertices.
[ "Calculates", "an", "Euler", "tour", "over", "the", "graph", "g", "from", "vertex", "start", "to", "vertex", "end", ".", "Assumes", "start", "and", "end", "are", "odd", "-", "degree", "vertices", "and", "that", "there", "are", "no", "other", "odd", "-", ...
python
train
PatrikValkovic/grammpy
grammpy/transforms/UnitRulesRemove/remove_unit_rules.py
https://github.com/PatrikValkovic/grammpy/blob/879ce0ef794ac2823acc19314fcd7a8aba53e50f/grammpy/transforms/UnitRulesRemove/remove_unit_rules.py#L31-L45
def _create_rule(path, rule): # type: (List[Type[Rule]], Type[Rule]) -> Type[ReducedUnitRule] """ Create ReducedUnitRule based on sequence of unit rules and end, generating rule. :param path: Sequence of unit rules. :param rule: Rule that is attached after sequence of unit rules. :return: Reduce...
[ "def", "_create_rule", "(", "path", ",", "rule", ")", ":", "# type: (List[Type[Rule]], Type[Rule]) -> Type[ReducedUnitRule]", "created", "=", "type", "(", "'Reduced['", "+", "rule", ".", "__name__", "+", "']'", ",", "(", "ReducedUnitRule", ",", ")", ",", "ReducedU...
Create ReducedUnitRule based on sequence of unit rules and end, generating rule. :param path: Sequence of unit rules. :param rule: Rule that is attached after sequence of unit rules. :return: ReducedUnitRule class.
[ "Create", "ReducedUnitRule", "based", "on", "sequence", "of", "unit", "rules", "and", "end", "generating", "rule", ".", ":", "param", "path", ":", "Sequence", "of", "unit", "rules", ".", ":", "param", "rule", ":", "Rule", "that", "is", "attached", "after",...
python
train
trailofbits/manticore
manticore/core/smtlib/solver.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/solver.py#L294-L315
def _is_sat(self) -> bool: """ Check the satisfiability of the current state :return: whether current state is satisfiable or not. """ logger.debug("Solver.check() ") start = time.time() self._send('(check-sat)') status = self._recv() logger.debug...
[ "def", "_is_sat", "(", "self", ")", "->", "bool", ":", "logger", ".", "debug", "(", "\"Solver.check() \"", ")", "start", "=", "time", ".", "time", "(", ")", "self", ".", "_send", "(", "'(check-sat)'", ")", "status", "=", "self", ".", "_recv", "(", ")...
Check the satisfiability of the current state :return: whether current state is satisfiable or not.
[ "Check", "the", "satisfiability", "of", "the", "current", "state" ]
python
valid
readbeyond/aeneas
aeneas/syncmap/fragmentlist.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L212-L221
def nonspeech_fragments(self): """ Iterates through the nonspeech fragments in the list (which are sorted). :rtype: generator of (int, :class:`~aeneas.syncmap.SyncMapFragment`) """ for i, fragment in enumerate(self.__fragments): if fragment.fragment_type == S...
[ "def", "nonspeech_fragments", "(", "self", ")", ":", "for", "i", ",", "fragment", "in", "enumerate", "(", "self", ".", "__fragments", ")", ":", "if", "fragment", ".", "fragment_type", "==", "SyncMapFragment", ".", "NONSPEECH", ":", "yield", "(", "i", ",", ...
Iterates through the nonspeech fragments in the list (which are sorted). :rtype: generator of (int, :class:`~aeneas.syncmap.SyncMapFragment`)
[ "Iterates", "through", "the", "nonspeech", "fragments", "in", "the", "list", "(", "which", "are", "sorted", ")", "." ]
python
train
kxgames/vecrec
vecrec/shapes.py
https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L468-L472
def get_rotated(self, angle): """ Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise. """ result = self.copy() result.rotate(angle) return result
[ "def", "get_rotated", "(", "self", ",", "angle", ")", ":", "result", "=", "self", ".", "copy", "(", ")", "result", ".", "rotate", "(", "angle", ")", "return", "result" ]
Return a vector rotated by angle from the given vector. Angle measured in radians counter-clockwise.
[ "Return", "a", "vector", "rotated", "by", "angle", "from", "the", "given", "vector", ".", "Angle", "measured", "in", "radians", "counter", "-", "clockwise", "." ]
python
train
pycontribs/pyrax
pyrax/cloudmonitoring.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudmonitoring.py#L42-L52
def assure_check(fnc): """ Converts an checkID passed as the check to a CloudMonitorCheck object. """ @wraps(fnc) def _wrapped(self, check, *args, **kwargs): if not isinstance(check, CloudMonitorCheck): # Must be the ID check = self._check_manager.get(check) r...
[ "def", "assure_check", "(", "fnc", ")", ":", "@", "wraps", "(", "fnc", ")", "def", "_wrapped", "(", "self", ",", "check", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "check", ",", "CloudMonitorCheck", ")", "...
Converts an checkID passed as the check to a CloudMonitorCheck object.
[ "Converts", "an", "checkID", "passed", "as", "the", "check", "to", "a", "CloudMonitorCheck", "object", "." ]
python
train
NiklasRosenstein-Python/nr-deprecated
nr/stream.py
https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/stream.py#L136-L141
def of_type(cls, iterable, types): """ Filters using #isinstance(). """ return cls(x for x in iterable if isinstance(x, types))
[ "def", "of_type", "(", "cls", ",", "iterable", ",", "types", ")", ":", "return", "cls", "(", "x", "for", "x", "in", "iterable", "if", "isinstance", "(", "x", ",", "types", ")", ")" ]
Filters using #isinstance().
[ "Filters", "using", "#isinstance", "()", "." ]
python
train
tcpcloud/python-aptly
aptly/publisher/__init__.py
https://github.com/tcpcloud/python-aptly/blob/7eb4ce1c508666bad0e6a0d4c5c561b1485ed558/aptly/publisher/__init__.py#L603-L612
def _find_snapshot(self, name): """ Find snapshot on remote by name or regular expression """ remote_snapshots = self._get_snapshots(self.client) for remote in reversed(remote_snapshots): if remote["Name"] == name or \ re.match(name, remote["Name"]...
[ "def", "_find_snapshot", "(", "self", ",", "name", ")", ":", "remote_snapshots", "=", "self", ".", "_get_snapshots", "(", "self", ".", "client", ")", "for", "remote", "in", "reversed", "(", "remote_snapshots", ")", ":", "if", "remote", "[", "\"Name\"", "]"...
Find snapshot on remote by name or regular expression
[ "Find", "snapshot", "on", "remote", "by", "name", "or", "regular", "expression" ]
python
train
Microsoft/nni
src/sdk/pynni/nni/metis_tuner/metis_tuner.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/metis_tuner.py#L167-L181
def _pack_output(self, init_parameter): """Pack the output Parameters ---------- init_parameter : dict Returns ------- output : dict """ output = {} for i, param in enumerate(init_parameter): output[self.key_order[i]] = param ...
[ "def", "_pack_output", "(", "self", ",", "init_parameter", ")", ":", "output", "=", "{", "}", "for", "i", ",", "param", "in", "enumerate", "(", "init_parameter", ")", ":", "output", "[", "self", ".", "key_order", "[", "i", "]", "]", "=", "param", "re...
Pack the output Parameters ---------- init_parameter : dict Returns ------- output : dict
[ "Pack", "the", "output" ]
python
train
FNNDSC/pfurl
pfurl/pfurl.py
https://github.com/FNNDSC/pfurl/blob/572f634ab582b7b7b7a3fbfd5bf12aadc1ba7958/pfurl/pfurl.py#L1350-L1373
def zipdir(path, ziph, **kwargs): """ Zip up a directory. :param path: :param ziph: :param kwargs: :return: """ str_arcroot = "" for k, v in kwargs.items(): if k == 'arcroot': str_arcroot = v for root, dirs, files in os.walk(path): for file in files: ...
[ "def", "zipdir", "(", "path", ",", "ziph", ",", "*", "*", "kwargs", ")", ":", "str_arcroot", "=", "\"\"", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "==", "'arcroot'", ":", "str_arcroot", "=", "v", "for", "root"...
Zip up a directory. :param path: :param ziph: :param kwargs: :return:
[ "Zip", "up", "a", "directory", "." ]
python
train
jayvdb/flake8-putty
flake8_putty/extension.py
https://github.com/jayvdb/flake8-putty/blob/854b2c6daef409974c2f5e9c5acaf0a069b0ff23/flake8_putty/extension.py#L137-L157
def parse_options(cls, options): """Parse options and activate `ignore_code` handler.""" if (not options.putty_select and not options.putty_ignore and not options.putty_auto_ignore): return options._orig_select = options.select options._orig_ignore = options....
[ "def", "parse_options", "(", "cls", ",", "options", ")", ":", "if", "(", "not", "options", ".", "putty_select", "and", "not", "options", ".", "putty_ignore", "and", "not", "options", ".", "putty_auto_ignore", ")", ":", "return", "options", ".", "_orig_select...
Parse options and activate `ignore_code` handler.
[ "Parse", "options", "and", "activate", "ignore_code", "handler", "." ]
python
train
rootpy/rootpy
rootpy/plotting/contrib/plot_corrcoef_matrix.py
https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/contrib/plot_corrcoef_matrix.py#L13-L133
def plot_corrcoef_matrix(matrix, names=None, cmap=None, cmap_text=None, fontsize=12, grid=False, axes=None): """ This function will draw a lower-triangular correlation matrix Parameters ---------- matrix : 2-dimensional num...
[ "def", "plot_corrcoef_matrix", "(", "matrix", ",", "names", "=", "None", ",", "cmap", "=", "None", ",", "cmap_text", "=", "None", ",", "fontsize", "=", "12", ",", "grid", "=", "False", ",", "axes", "=", "None", ")", ":", "import", "numpy", "as", "np"...
This function will draw a lower-triangular correlation matrix Parameters ---------- matrix : 2-dimensional numpy array/matrix A correlation coefficient matrix names : list of strings, optional (default=None) List of the parameter names corresponding to the rows in ``matrix``. cma...
[ "This", "function", "will", "draw", "a", "lower", "-", "triangular", "correlation", "matrix" ]
python
train
ibis-project/ibis
ibis/sql/sqlite/client.py
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/sql/sqlite/client.py#L113-L129
def _ibis_sqlite_regex_extract(string, pattern, index): """Extract match of regular expression `pattern` from `string` at `index`. Parameters ---------- string : str pattern : str index : int Returns ------- result : str or None """ result = re.search(pattern, string) i...
[ "def", "_ibis_sqlite_regex_extract", "(", "string", ",", "pattern", ",", "index", ")", ":", "result", "=", "re", ".", "search", "(", "pattern", ",", "string", ")", "if", "result", "is", "not", "None", "and", "0", "<=", "index", "<=", "(", "result", "."...
Extract match of regular expression `pattern` from `string` at `index`. Parameters ---------- string : str pattern : str index : int Returns ------- result : str or None
[ "Extract", "match", "of", "regular", "expression", "pattern", "from", "string", "at", "index", "." ]
python
train
osrg/ryu
ryu/services/protocols/bgp/peer.py
https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/services/protocols/bgp/peer.py#L826-L844
def _session_next_hop(self, path): """Returns nexthop address relevant to current session Nexthop used can depend on capabilities of the session. If VPNv6 capability is active and session is on IPv4 connection, we have to use IPv4 mapped IPv6 address. In other cases we can use connectio...
[ "def", "_session_next_hop", "(", "self", ",", "path", ")", ":", "route_family", "=", "path", ".", "route_family", "# By default we use BGPS's interface IP with this peer as next_hop.", "if", "self", ".", "_neigh_conf", ".", "next_hop", ":", "next_hop", "=", "self", "....
Returns nexthop address relevant to current session Nexthop used can depend on capabilities of the session. If VPNv6 capability is active and session is on IPv4 connection, we have to use IPv4 mapped IPv6 address. In other cases we can use connection end point/local ip address.
[ "Returns", "nexthop", "address", "relevant", "to", "current", "session" ]
python
train
owncloud/pyocclient
owncloud/owncloud.py
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1089-L1109
def get_user_groups(self, user_name): """Get a list of groups associated to a user. :param user_name: name of user to list groups :returns: list of groups :raises: HTTPResponseError in case an HTTP error status was returned """ res = self._make_ocs_request( ...
[ "def", "get_user_groups", "(", "self", ",", "user_name", ")", ":", "res", "=", "self", ".", "_make_ocs_request", "(", "'GET'", ",", "self", ".", "OCS_SERVICE_CLOUD", ",", "'users/'", "+", "user_name", "+", "'/groups'", ",", ")", "if", "res", ".", "status_c...
Get a list of groups associated to a user. :param user_name: name of user to list groups :returns: list of groups :raises: HTTPResponseError in case an HTTP error status was returned
[ "Get", "a", "list", "of", "groups", "associated", "to", "a", "user", "." ]
python
train
sourceperl/pyModbusTCP
pyModbusTCP/client.py
https://github.com/sourceperl/pyModbusTCP/blob/993f6e2f5ab52eba164be049e42cea560c3751a5/pyModbusTCP/client.py#L251-L287
def open(self): """Connect to modbus server (open TCP connection) :returns: connect status (True if open) :rtype: bool """ # restart TCP if already open if self.is_open(): self.close() # init socket and connect # list available sockets on the ...
[ "def", "open", "(", "self", ")", ":", "# restart TCP if already open", "if", "self", ".", "is_open", "(", ")", ":", "self", ".", "close", "(", ")", "# init socket and connect", "# list available sockets on the target host/port", "# AF_xxx : AF_INET -> IPv4, AF_INET6 -> IPv6...
Connect to modbus server (open TCP connection) :returns: connect status (True if open) :rtype: bool
[ "Connect", "to", "modbus", "server", "(", "open", "TCP", "connection", ")" ]
python
train
saltstack/salt
salt/utils/stringutils.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L30-L63
def to_bytes(s, encoding=None, errors='strict'): ''' Given bytes, bytearray, str, or unicode (python 2), return bytes (str for python 2) ''' if encoding is None: # Try utf-8 first, and fall back to detected encoding encoding = ('utf-8', __salt_system_encoding__) if not isinstance...
[ "def", "to_bytes", "(", "s", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "if", "encoding", "is", "None", ":", "# Try utf-8 first, and fall back to detected encoding", "encoding", "=", "(", "'utf-8'", ",", "__salt_system_encoding__", ")"...
Given bytes, bytearray, str, or unicode (python 2), return bytes (str for python 2)
[ "Given", "bytes", "bytearray", "str", "or", "unicode", "(", "python", "2", ")", "return", "bytes", "(", "str", "for", "python", "2", ")" ]
python
train