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
rmax/scrapydo
scrapydo/api.py
https://github.com/rmax/scrapydo/blob/b0f9e6d50a5ea9d2ba8335bffa877003109c3af5/scrapydo/api.py#L130-L153
def _fetch_in_reactor(url, spider_cls=DefaultSpider, **kwargs): """Fetches an URL and returns the response. Parameters ---------- url : str An URL to fetch. spider_cls : scrapy.Spider (default: DefaultSpider) A spider class to be used in the crawler. kwargs : dict, optional ...
[ "def", "_fetch_in_reactor", "(", "url", ",", "spider_cls", "=", "DefaultSpider", ",", "*", "*", "kwargs", ")", ":", "def", "parse", "(", "self", ",", "response", ")", ":", "self", ".", "response", "=", "response", "req", "=", "Request", "(", "url", ")"...
Fetches an URL and returns the response. Parameters ---------- url : str An URL to fetch. spider_cls : scrapy.Spider (default: DefaultSpider) A spider class to be used in the crawler. kwargs : dict, optional Additional arguments to be passed to ``_run_spider_in_reactor``. ...
[ "Fetches", "an", "URL", "and", "returns", "the", "response", "." ]
python
train
neuropsychology/NeuroKit.py
neurokit/statistics/statistics.py
https://github.com/neuropsychology/NeuroKit.py/blob/c9589348fbbde0fa7e986048c48f38e6b488adfe/neurokit/statistics/statistics.py#L125-L165
def find_outliers(data, treshold=2.58): """ Identify outliers (abnormal values) using the standart deviation. Parameters ---------- data : list or ndarray Data array treshold : float Maximum deviation (in terms of standart deviation). Rule of thumb of a gaussian distribution: 2....
[ "def", "find_outliers", "(", "data", ",", "treshold", "=", "2.58", ")", ":", "outliers", "=", "[", "]", "mean", "=", "np", ".", "mean", "(", "data", ")", "std", "=", "np", ".", "std", "(", "data", ")", "for", "i", "in", "data", ":", "if", "abs"...
Identify outliers (abnormal values) using the standart deviation. Parameters ---------- data : list or ndarray Data array treshold : float Maximum deviation (in terms of standart deviation). Rule of thumb of a gaussian distribution: 2.58 = rejecting 1%, 2.33 = rejecting 2%, 1.96 = 5% an...
[ "Identify", "outliers", "(", "abnormal", "values", ")", "using", "the", "standart", "deviation", "." ]
python
train
chaoss/grimoirelab-perceval-mozilla
perceval/backends/mozilla/crates.py
https://github.com/chaoss/grimoirelab-perceval-mozilla/blob/4514f8d3d609d3cb79d83c72d51fcc4b4a7daeb4/perceval/backends/mozilla/crates.py#L91-L104
def fetch_items(self, category, **kwargs): """Fetch packages and summary from Crates.io :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] if category == CATEGORY_C...
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "if", "category", "==", "CATEGORY_CRATES", ":", "return", "self", ".", "__fetch_crates", "(", "from_date", ")", "els...
Fetch packages and summary from Crates.io :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
[ "Fetch", "packages", "and", "summary", "from", "Crates", ".", "io" ]
python
test
Workiva/furious
furious/extras/appengine/ndb_persistence.py
https://github.com/Workiva/furious/blob/c29823ec8b98549e7439d7273aa064d1e5830632/furious/extras/appengine/ndb_persistence.py#L297-L307
def store_async_result(async_id, async_result): """Persist the Async's result to the datastore.""" logging.debug("Storing result for %s", async_id) key = FuriousAsyncMarker( id=async_id, result=json.dumps(async_result.to_dict()), status=async_result.status).put() logging.debug("Settin...
[ "def", "store_async_result", "(", "async_id", ",", "async_result", ")", ":", "logging", ".", "debug", "(", "\"Storing result for %s\"", ",", "async_id", ")", "key", "=", "FuriousAsyncMarker", "(", "id", "=", "async_id", ",", "result", "=", "json", ".", "dumps"...
Persist the Async's result to the datastore.
[ "Persist", "the", "Async", "s", "result", "to", "the", "datastore", "." ]
python
train
mattja/nsim
nsim/analyses1/freq.py
https://github.com/mattja/nsim/blob/ed62c41cd56b918fd97e09f7ad73c12c76a8c3e0/nsim/analyses1/freq.py#L207-L210
def hilbert_phase(ts): """Phase of the analytic signal, using the Hilbert transform""" output = np.angle(signal.hilbert(signal.detrend(ts, axis=0), axis=0)) return Timeseries(output, ts.tspan, labels=ts.labels)
[ "def", "hilbert_phase", "(", "ts", ")", ":", "output", "=", "np", ".", "angle", "(", "signal", ".", "hilbert", "(", "signal", ".", "detrend", "(", "ts", ",", "axis", "=", "0", ")", ",", "axis", "=", "0", ")", ")", "return", "Timeseries", "(", "ou...
Phase of the analytic signal, using the Hilbert transform
[ "Phase", "of", "the", "analytic", "signal", "using", "the", "Hilbert", "transform" ]
python
train
rbarrois/restricted_pkg
restricted_pkg/base.py
https://github.com/rbarrois/restricted_pkg/blob/abbd3cb33ed85af02fbb531fd85dda9c1b070c85/restricted_pkg/base.py#L78-L91
def full_url(self): """The full URL, including username/password.""" if self.needs_auth: netloc = '%s:%s@%s' % (self.username, self.password, self.netloc) else: netloc = self.netloc return urlunparse(( self.scheme, netloc, self....
[ "def", "full_url", "(", "self", ")", ":", "if", "self", ".", "needs_auth", ":", "netloc", "=", "'%s:%s@%s'", "%", "(", "self", ".", "username", ",", "self", ".", "password", ",", "self", ".", "netloc", ")", "else", ":", "netloc", "=", "self", ".", ...
The full URL, including username/password.
[ "The", "full", "URL", "including", "username", "/", "password", "." ]
python
train
elastic/elasticsearch-py
elasticsearch/client/indices.py
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/indices.py#L988-L1015
def shrink(self, index, target, body=None, params=None): """ The shrink index API allows you to shrink an existing index into a new index with fewer primary shards. The number of primary shards in the target index must be a factor of the shards in the source index. For example an...
[ "def", "shrink", "(", "self", ",", "index", ",", "target", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "for", "param", "in", "(", "index", ",", "target", ")", ":", "if", "param", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", ...
The shrink index API allows you to shrink an existing index into a new index with fewer primary shards. The number of primary shards in the target index must be a factor of the shards in the source index. For example an index with 8 primary shards can be shrunk into 4, 2 or 1 primary sha...
[ "The", "shrink", "index", "API", "allows", "you", "to", "shrink", "an", "existing", "index", "into", "a", "new", "index", "with", "fewer", "primary", "shards", ".", "The", "number", "of", "primary", "shards", "in", "the", "target", "index", "must", "be", ...
python
train
saltstack/salt
salt/modules/inspectlib/query.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/query.py#L195-L211
def _configuration(self, *args, **kwargs): ''' Return configuration files. ''' data = dict() self.db.open() for pkg in self.db.get(Package): configs = list() for pkg_cfg in self.db.get(PackageCfgFile, eq={'pkgid': pkg.id}): configs...
[ "def", "_configuration", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "dict", "(", ")", "self", ".", "db", ".", "open", "(", ")", "for", "pkg", "in", "self", ".", "db", ".", "get", "(", "Package", ")", ":", "...
Return configuration files.
[ "Return", "configuration", "files", "." ]
python
train
pygeobuf/pygeobuf
geobuf/scripts/cli.py
https://github.com/pygeobuf/pygeobuf/blob/c9e055ab47532781626cfe2c931a8444820acf05/geobuf/scripts/cli.py#L65-L78
def decode(): """Given a Geobuf byte string on stdin, write a GeoJSON feature collection to stdout.""" logger = logging.getLogger('geobuf') stdin = click.get_binary_stream('stdin') sink = click.get_text_stream('stdout') try: pbf = stdin.read() data = geobuf.decode(pbf) js...
[ "def", "decode", "(", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "'geobuf'", ")", "stdin", "=", "click", ".", "get_binary_stream", "(", "'stdin'", ")", "sink", "=", "click", ".", "get_text_stream", "(", "'stdout'", ")", "try", ":", "pbf",...
Given a Geobuf byte string on stdin, write a GeoJSON feature collection to stdout.
[ "Given", "a", "Geobuf", "byte", "string", "on", "stdin", "write", "a", "GeoJSON", "feature", "collection", "to", "stdout", "." ]
python
train
HewlettPackard/python-hpOneView
hpOneView/resources/servers/server_profiles.py
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/servers/server_profiles.py#L302-L320
def get_available_targets(self, **kwargs): """ Retrieves a list of the target servers and empty device bays that are available for assignment to the server profile. Args: enclosureGroupUri (str): The URI of the enclosure group associated with the resource. serverHa...
[ "def", "get_available_targets", "(", "self", ",", "*", "*", "kwargs", ")", ":", "uri", "=", "self", ".", "_helper", ".", "build_uri_with_query_string", "(", "kwargs", ",", "'/available-targets'", ")", "return", "self", ".", "_helper", ".", "do_get", "(", "ur...
Retrieves a list of the target servers and empty device bays that are available for assignment to the server profile. Args: enclosureGroupUri (str): The URI of the enclosure group associated with the resource. serverHardwareTypeUri (str): The URI of the server hardware type associ...
[ "Retrieves", "a", "list", "of", "the", "target", "servers", "and", "empty", "device", "bays", "that", "are", "available", "for", "assignment", "to", "the", "server", "profile", "." ]
python
train
kyuupichan/aiorpcX
aiorpcx/jsonrpc.py
https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/jsonrpc.py#L330-L336
def encode_payload(cls, payload): '''Encode a Python object as JSON and convert it to bytes.''' try: return json.dumps(payload).encode() except TypeError: msg = f'JSON payload encoding error: {payload}' raise ProtocolError(cls.INTERNAL_ERROR, msg) from None
[ "def", "encode_payload", "(", "cls", ",", "payload", ")", ":", "try", ":", "return", "json", ".", "dumps", "(", "payload", ")", ".", "encode", "(", ")", "except", "TypeError", ":", "msg", "=", "f'JSON payload encoding error: {payload}'", "raise", "ProtocolErro...
Encode a Python object as JSON and convert it to bytes.
[ "Encode", "a", "Python", "object", "as", "JSON", "and", "convert", "it", "to", "bytes", "." ]
python
train
BlueBrain/nat
nat/zotero_wrap.py
https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/zotero_wrap.py#L70-L79
def create_distant_reference(self, ref_data): """Validate and create the reference in Zotero and return the created item.""" self.validate_reference_data(ref_data) creation_status = self._zotero_lib.create_items([ref_data]) try: created_item = creation_status["successful"]["0...
[ "def", "create_distant_reference", "(", "self", ",", "ref_data", ")", ":", "self", ".", "validate_reference_data", "(", "ref_data", ")", "creation_status", "=", "self", ".", "_zotero_lib", ".", "create_items", "(", "[", "ref_data", "]", ")", "try", ":", "creat...
Validate and create the reference in Zotero and return the created item.
[ "Validate", "and", "create", "the", "reference", "in", "Zotero", "and", "return", "the", "created", "item", "." ]
python
train
pydata/xarray
xarray/core/formatting.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/formatting.py#L139-L150
def format_item(x, timedelta_format=None, quote_strings=True): """Returns a succinct summary of an object as a string""" if isinstance(x, (np.datetime64, datetime)): return format_timestamp(x) if isinstance(x, (np.timedelta64, timedelta)): return format_timedelta(x, timedelta_format=timedelt...
[ "def", "format_item", "(", "x", ",", "timedelta_format", "=", "None", ",", "quote_strings", "=", "True", ")", ":", "if", "isinstance", "(", "x", ",", "(", "np", ".", "datetime64", ",", "datetime", ")", ")", ":", "return", "format_timestamp", "(", "x", ...
Returns a succinct summary of an object as a string
[ "Returns", "a", "succinct", "summary", "of", "an", "object", "as", "a", "string" ]
python
train
bcbio/bcbio-nextgen
bcbio/illumina/demultiplex.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/demultiplex.py#L11-L30
def run_bcl2fastq(run_folder, ss_csv, config): """Run bcl2fastq for de-multiplexing and fastq generation. run_folder -- directory of Illumina outputs ss_csv -- Samplesheet CSV file describing samples. """ bc_dir = os.path.join(run_folder, "Data", "Intensities", "BaseCalls") output_dir = os.path....
[ "def", "run_bcl2fastq", "(", "run_folder", ",", "ss_csv", ",", "config", ")", ":", "bc_dir", "=", "os", ".", "path", ".", "join", "(", "run_folder", ",", "\"Data\"", ",", "\"Intensities\"", ",", "\"BaseCalls\"", ")", "output_dir", "=", "os", ".", "path", ...
Run bcl2fastq for de-multiplexing and fastq generation. run_folder -- directory of Illumina outputs ss_csv -- Samplesheet CSV file describing samples.
[ "Run", "bcl2fastq", "for", "de", "-", "multiplexing", "and", "fastq", "generation", ".", "run_folder", "--", "directory", "of", "Illumina", "outputs", "ss_csv", "--", "Samplesheet", "CSV", "file", "describing", "samples", "." ]
python
train
pmneila/morphsnakes
morphsnakes_v1.py
https://github.com/pmneila/morphsnakes/blob/aab66e70f86308d7b1927d76869a1a562120f849/morphsnakes_v1.py#L74-L91
def operator_si(u): """operator_si operator.""" global _aux if np.ndim(u) == 2: P = _P2 elif np.ndim(u) == 3: P = _P3 else: raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") if u.shape != _aux.shape[1:]: ...
[ "def", "operator_si", "(", "u", ")", ":", "global", "_aux", "if", "np", ".", "ndim", "(", "u", ")", "==", "2", ":", "P", "=", "_P2", "elif", "np", ".", "ndim", "(", "u", ")", "==", "3", ":", "P", "=", "_P3", "else", ":", "raise", "ValueError"...
operator_si operator.
[ "operator_si", "operator", "." ]
python
train
rflamary/POT
ot/dr.py
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/dr.py#L25-L35
def sinkhorn(w1, w2, M, reg, k): """Sinkhorn algorithm with fixed number of iteration (autograd) """ K = np.exp(-M / reg) ui = np.ones((M.shape[0],)) vi = np.ones((M.shape[1],)) for i in range(k): vi = w2 / (np.dot(K.T, ui)) ui = w1 / (np.dot(K, vi)) G = ui.reshape((M.shape[0...
[ "def", "sinkhorn", "(", "w1", ",", "w2", ",", "M", ",", "reg", ",", "k", ")", ":", "K", "=", "np", ".", "exp", "(", "-", "M", "/", "reg", ")", "ui", "=", "np", ".", "ones", "(", "(", "M", ".", "shape", "[", "0", "]", ",", ")", ")", "v...
Sinkhorn algorithm with fixed number of iteration (autograd)
[ "Sinkhorn", "algorithm", "with", "fixed", "number", "of", "iteration", "(", "autograd", ")" ]
python
train
hitchtest/hitchserve
hitchserve/service_bundle.py
https://github.com/hitchtest/hitchserve/blob/a2def19979264186d283e76f7f0c88f3ed97f2e0/hitchserve/service_bundle.py#L261-L285
def time_travel(self, datetime=None, timedelta=None, seconds=0, minutes=0, hours=0, days=0): """Mock moving forward or backward in time by shifting the system clock fed to the services tested. Note that all of these arguments can be used together, individually or not at all. The time traveled t...
[ "def", "time_travel", "(", "self", ",", "datetime", "=", "None", ",", "timedelta", "=", "None", ",", "seconds", "=", "0", ",", "minutes", "=", "0", ",", "hours", "=", "0", ",", "days", "=", "0", ")", ":", "if", "datetime", "is", "not", "None", ":...
Mock moving forward or backward in time by shifting the system clock fed to the services tested. Note that all of these arguments can be used together, individually or not at all. The time traveled to will be the sum of all specified time deltas from datetime. If no datetime is specified, the d...
[ "Mock", "moving", "forward", "or", "backward", "in", "time", "by", "shifting", "the", "system", "clock", "fed", "to", "the", "services", "tested", "." ]
python
train
CTPUG/wafer
wafer/registration/sso.py
https://github.com/CTPUG/wafer/blob/a20af3c399267f76373dc342f4d542a9bc457c35/wafer/registration/sso.py#L24-L41
def sso(user, desired_username, name, email, profile_fields=None): """ Create a user, if the provided `user` is None, from the parameters. Then log the user in, and return it. """ if not user: if not settings.REGISTRATION_OPEN: raise SSOError('Account registration is closed') ...
[ "def", "sso", "(", "user", ",", "desired_username", ",", "name", ",", "email", ",", "profile_fields", "=", "None", ")", ":", "if", "not", "user", ":", "if", "not", "settings", ".", "REGISTRATION_OPEN", ":", "raise", "SSOError", "(", "'Account registration is...
Create a user, if the provided `user` is None, from the parameters. Then log the user in, and return it.
[ "Create", "a", "user", "if", "the", "provided", "user", "is", "None", "from", "the", "parameters", ".", "Then", "log", "the", "user", "in", "and", "return", "it", "." ]
python
train
dh1tw/pyhamtools
pyhamtools/locator.py
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/locator.py#L128-L167
def calculate_distance(locator1, locator2): """calculates the (shortpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in km ...
[ "def", "calculate_distance", "(", "locator1", ",", "locator2", ")", ":", "R", "=", "6371", "#earh radius", "lat1", ",", "long1", "=", "locator_to_latlong", "(", "locator1", ")", "lat2", ",", "long2", "=", "locator_to_latlong", "(", "locator2", ")", "d_lat", ...
calculates the (shortpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in km Raises: ValueError: When called wi...
[ "calculates", "the", "(", "shortpath", ")", "distance", "between", "two", "Maidenhead", "locators" ]
python
train
Cue/scales
src/greplin/scales/__init__.py
https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L415-L418
def update(self, instance, oldValue, newValue): """Updates the aggregate based on a change in the child value.""" self.__set__(instance, self.__get__(instance, None) + newValue - (oldValue or 0))
[ "def", "update", "(", "self", ",", "instance", ",", "oldValue", ",", "newValue", ")", ":", "self", ".", "__set__", "(", "instance", ",", "self", ".", "__get__", "(", "instance", ",", "None", ")", "+", "newValue", "-", "(", "oldValue", "or", "0", ")",...
Updates the aggregate based on a change in the child value.
[ "Updates", "the", "aggregate", "based", "on", "a", "change", "in", "the", "child", "value", "." ]
python
train
inspirehep/inspire-dojson
inspire_dojson/cds/rules.py
https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/cds/rules.py#L400-L453
def urls(self, key, value): """Populate the ``8564`` MARC field. Also populate the ``FFT`` field through side effects. """ def _is_preprint(value): return value.get('y', '').lower() == 'preprint' def _is_fulltext(value): return value['u'].endswith('.pdf') and value['u'].startswith(...
[ "def", "urls", "(", "self", ",", "key", ",", "value", ")", ":", "def", "_is_preprint", "(", "value", ")", ":", "return", "value", ".", "get", "(", "'y'", ",", "''", ")", ".", "lower", "(", ")", "==", "'preprint'", "def", "_is_fulltext", "(", "value...
Populate the ``8564`` MARC field. Also populate the ``FFT`` field through side effects.
[ "Populate", "the", "8564", "MARC", "field", "." ]
python
train
coderholic/pyradio
pyradio/player.py
https://github.com/coderholic/pyradio/blob/c5219d350bccbccd49dbd627c1f886a952ea1963/pyradio/player.py#L285-L319
def play(self, name, streamUrl, encoding = ''): """ use a multimedia player to play a stream """ self.close() self.name = name self.oldUserInput = {'Input': '', 'Volume': '', 'Title': ''} self.muted = False self.show_volume = True self.title_prefix = '' se...
[ "def", "play", "(", "self", ",", "name", ",", "streamUrl", ",", "encoding", "=", "''", ")", ":", "self", ".", "close", "(", ")", "self", ".", "name", "=", "name", "self", ".", "oldUserInput", "=", "{", "'Input'", ":", "''", ",", "'Volume'", ":", ...
use a multimedia player to play a stream
[ "use", "a", "multimedia", "player", "to", "play", "a", "stream" ]
python
train
the01/python-paps
paps/si/app/message.py
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L362-L401
def unpack(cls, data): """ Unpack packed data into an instance :param data: Packed data :type data: str :return: Object instance and remaining data :rtype: (APPHeader, str) """ size = struct.calcsize(APPHeader.fmt_header) ( version, ms...
[ "def", "unpack", "(", "cls", ",", "data", ")", ":", "size", "=", "struct", ".", "calcsize", "(", "APPHeader", ".", "fmt_header", ")", "(", "version", ",", "msg_type", ",", "payload_len", ",", "timestamp", ",", "device_id", ",", "flags", ",", ")", ",", ...
Unpack packed data into an instance :param data: Packed data :type data: str :return: Object instance and remaining data :rtype: (APPHeader, str)
[ "Unpack", "packed", "data", "into", "an", "instance" ]
python
train
greyli/flask-dropzone
flask_dropzone/__init__.py
https://github.com/greyli/flask-dropzone/blob/eb1d5ef16d8f83a12e6fed1bb9412a0c12c6d584/flask_dropzone/__init__.py#L29-L134
def load(js_url='', css_url='', version='5.2.0'): """Load Dropzone resources with given version and init dropzone configuration. .. versionchanged:: 1.4.3 Added ``js_url`` and ``css_url`` parameters to pass custom resource URL. .. versionchanged:: 1.4.4 This method was ...
[ "def", "load", "(", "js_url", "=", "''", ",", "css_url", "=", "''", ",", "version", "=", "'5.2.0'", ")", ":", "warnings", ".", "warn", "(", "'The method will be removed in 2.0, see docs for more details.'", ")", "js_filename", "=", "'dropzone.min.js'", "css_filename...
Load Dropzone resources with given version and init dropzone configuration. .. versionchanged:: 1.4.3 Added ``js_url`` and ``css_url`` parameters to pass custom resource URL. .. versionchanged:: 1.4.4 This method was deprecated due to inflexible. Now it's divided into three met...
[ "Load", "Dropzone", "resources", "with", "given", "version", "and", "init", "dropzone", "configuration", "." ]
python
train
CivicSpleen/ambry
ambry/orm/column.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L444-L457
def mangle_name(name): """Mangles a column name to a standard form, remoing illegal characters. :param name: :return: """ import re try: return re.sub('_+', '_', re.sub('[^\w_]', '_', name).lower()).rstrip('_') except TypeError: r...
[ "def", "mangle_name", "(", "name", ")", ":", "import", "re", "try", ":", "return", "re", ".", "sub", "(", "'_+'", ",", "'_'", ",", "re", ".", "sub", "(", "'[^\\w_]'", ",", "'_'", ",", "name", ")", ".", "lower", "(", ")", ")", ".", "rstrip", "("...
Mangles a column name to a standard form, remoing illegal characters. :param name: :return:
[ "Mangles", "a", "column", "name", "to", "a", "standard", "form", "remoing", "illegal", "characters", "." ]
python
train
lawsie/guizero
guizero/tkmixins.py
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/tkmixins.py#L8-L11
def after(self, time, function, args = []): """Call `function` after `time` milliseconds.""" callback_id = self.tk.after(time, self._call_wrapper, time, function, *args) self._callback[function] = [callback_id, False]
[ "def", "after", "(", "self", ",", "time", ",", "function", ",", "args", "=", "[", "]", ")", ":", "callback_id", "=", "self", ".", "tk", ".", "after", "(", "time", ",", "self", ".", "_call_wrapper", ",", "time", ",", "function", ",", "*", "args", ...
Call `function` after `time` milliseconds.
[ "Call", "function", "after", "time", "milliseconds", "." ]
python
train
Loudr/pale
pale/doc.py
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/doc.py#L818-L833
def document_endpoint(endpoint): """Extract the full documentation dictionary from the endpoint.""" descr = clean_description(py_doc_trim(endpoint.__doc__)) docs = { 'name': endpoint._route_name, 'http_method': endpoint._http_method, 'uri': endpoint._uri, 'description': descr...
[ "def", "document_endpoint", "(", "endpoint", ")", ":", "descr", "=", "clean_description", "(", "py_doc_trim", "(", "endpoint", ".", "__doc__", ")", ")", "docs", "=", "{", "'name'", ":", "endpoint", ".", "_route_name", ",", "'http_method'", ":", "endpoint", "...
Extract the full documentation dictionary from the endpoint.
[ "Extract", "the", "full", "documentation", "dictionary", "from", "the", "endpoint", "." ]
python
train
VingtCinq/python-mailchimp
mailchimp3/entities/reportunsubscribes.py
https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/reportunsubscribes.py#L25-L45
def all(self, campaign_id, get_all=False, **queryparams): """ Get information about members who have unsubscribed from a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param get_all: Should the query get all res...
[ "def", "all", "(", "self", ",", "campaign_id", ",", "get_all", "=", "False", ",", "*", "*", "queryparams", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "self", ".", "subscriber_hash", "=", "None", "if", "get_all", ":", "return", "self", ".",...
Get information about members who have unsubscribed from a specific campaign. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` :param get_all: Should the query get all results :type get_all: :py:class:`bool` :param queryparams: The q...
[ "Get", "information", "about", "members", "who", "have", "unsubscribed", "from", "a", "specific", "campaign", "." ]
python
valid
FNNDSC/med2image
med2image/systemMisc.py
https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L183-L215
def com_find2D(ar_grid, **kwargs): """ ARGS **kwargs ordering = 'rc' or 'xy' order the return either in (x,y) or (row, col) order. indexing = 'zero' or 'one' return positions relative to zero (i.e. pytho...
[ "def", "com_find2D", "(", "ar_grid", ",", "*", "*", "kwargs", ")", ":", "b_reorder", "=", "True", "b_oneOffset", "=", "True", "for", "key", ",", "value", "in", "kwargs", ".", "iteritems", "(", ")", ":", "if", "key", "==", "'ordering'", "and", "value", ...
ARGS **kwargs ordering = 'rc' or 'xy' order the return either in (x,y) or (row, col) order. indexing = 'zero' or 'one' return positions relative to zero (i.e. python addressing) or one (i.e. MatLAB ...
[ "ARGS", "**", "kwargs", "ordering", "=", "rc", "or", "xy", "order", "the", "return", "either", "in", "(", "x", "y", ")", "or", "(", "row", "col", ")", "order", ".", "indexing", "=", "zero", "or", "one", "return", "positions", "relative", "to", "zero"...
python
train
bcbio/bcbio-nextgen
bcbio/variation/vcfutils.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/vcfutils.py#L383-L400
def _run_concat_variant_files_gatk4(input_file_list, out_file, config): """Use GATK4 GatherVcfs for concatenation of scattered VCFs. """ if not utils.file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: params = ["-T", "GatherVcfs", "-I", input_file_list, "-O", ...
[ "def", "_run_concat_variant_files_gatk4", "(", "input_file_list", ",", "out_file", ",", "config", ")", ":", "if", "not", "utils", ".", "file_exists", "(", "out_file", ")", ":", "with", "file_transaction", "(", "config", ",", "out_file", ")", "as", "tx_out_file",...
Use GATK4 GatherVcfs for concatenation of scattered VCFs.
[ "Use", "GATK4", "GatherVcfs", "for", "concatenation", "of", "scattered", "VCFs", "." ]
python
train
saltstack/salt
salt/modules/boto_kinesis.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_kinesis.py#L124-L153
def get_stream_when_active(stream_name, region=None, key=None, keyid=None, profile=None): ''' Get complete stream info from AWS, returning only when the stream is in the ACTIVE state. Continues to retry when stream is updating or creating. If the stream is deleted during retries, the loop will catch the...
[ "def", "get_stream_when_active", "(", "stream_name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ...
Get complete stream info from AWS, returning only when the stream is in the ACTIVE state. Continues to retry when stream is updating or creating. If the stream is deleted during retries, the loop will catch the error and break. CLI example:: salt myminion boto_kinesis.get_stream_when_active my_str...
[ "Get", "complete", "stream", "info", "from", "AWS", "returning", "only", "when", "the", "stream", "is", "in", "the", "ACTIVE", "state", ".", "Continues", "to", "retry", "when", "stream", "is", "updating", "or", "creating", ".", "If", "the", "stream", "is",...
python
train
litl/rauth
rauth/oauth.py
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/oauth.py#L115-L155
def sign(self, consumer_secret, access_token_secret, method, url, oauth_params, req_kwargs): '''Sign request parameters. :param consumer_secret: Consumer secret. :type consumer_secret: str :param access_token_...
[ "def", "sign", "(", "self", ",", "consumer_secret", ",", "access_token_secret", ",", "method", ",", "url", ",", "oauth_params", ",", "req_kwargs", ")", ":", "url", "=", "self", ".", "_remove_qs", "(", "url", ")", "oauth_params", "=", "self", ".", "_normali...
Sign request parameters. :param consumer_secret: Consumer secret. :type consumer_secret: str :param access_token_secret: Access token secret. :type access_token_secret: str :param method: The method of this particular request. :type method: str :param url: The UR...
[ "Sign", "request", "parameters", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/__init__.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/__init__.py#L182-L189
def remove_rally(self, key): '''remove a rally point''' a = key.split(' ') if a[0] != 'Rally' or len(a) != 2: print("Bad rally object %s" % key) return i = int(a[1]) self.mpstate.functions.process_stdin('rally remove %u' % i)
[ "def", "remove_rally", "(", "self", ",", "key", ")", ":", "a", "=", "key", ".", "split", "(", "' '", ")", "if", "a", "[", "0", "]", "!=", "'Rally'", "or", "len", "(", "a", ")", "!=", "2", ":", "print", "(", "\"Bad rally object %s\"", "%", "key", ...
remove a rally point
[ "remove", "a", "rally", "point" ]
python
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L367-L445
def get_estimator(output_dir, train_config, args): """Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config ...
[ "def", "get_estimator", "(", "output_dir", ",", "train_config", ",", "args", ")", ":", "# Check the requested mode fits the preprocessed data.", "target_name", "=", "train_config", "[", "'target_column'", "]", "if", "is_classification_model", "(", "args", ".", "model_type...
Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config args: command line parameters Returns: TF lean...
[ "Returns", "a", "tf", "learn", "estimator", "." ]
python
train
DataBiosphere/toil
src/toil/jobStores/aws/jobStore.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/jobStores/aws/jobStore.py#L1226-L1241
def __getBucketVersioning(self, bucket): """ For newly created buckets get_versioning_status returns an empty dict. In the past we've seen None in this case. We map both to a return value of False. Otherwise, the 'Versioning' entry in the dictionary returned by get_versioning_status can...
[ "def", "__getBucketVersioning", "(", "self", ",", "bucket", ")", ":", "for", "attempt", "in", "retry_s3", "(", ")", ":", "with", "attempt", ":", "status", "=", "bucket", ".", "get_versioning_status", "(", ")", "return", "self", ".", "versionings", "[", "st...
For newly created buckets get_versioning_status returns an empty dict. In the past we've seen None in this case. We map both to a return value of False. Otherwise, the 'Versioning' entry in the dictionary returned by get_versioning_status can be 'Enabled', 'Suspended' or 'Disabled' which we map...
[ "For", "newly", "created", "buckets", "get_versioning_status", "returns", "an", "empty", "dict", ".", "In", "the", "past", "we", "ve", "seen", "None", "in", "this", "case", ".", "We", "map", "both", "to", "a", "return", "value", "of", "False", "." ]
python
train
jbloomlab/phydms
phydmslib/models.py
https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L2226-L2229
def branchScale(self): """See docs for `Model` abstract base class.""" bscales = [m.branchScale for m in self._models] return (self.catweights * bscales).sum()
[ "def", "branchScale", "(", "self", ")", ":", "bscales", "=", "[", "m", ".", "branchScale", "for", "m", "in", "self", ".", "_models", "]", "return", "(", "self", ".", "catweights", "*", "bscales", ")", ".", "sum", "(", ")" ]
See docs for `Model` abstract base class.
[ "See", "docs", "for", "Model", "abstract", "base", "class", "." ]
python
train
tjguk/networkzero
networkzero/messenger.py
https://github.com/tjguk/networkzero/blob/0e3e81d2e9200b25a83ac07741612283599486d7/networkzero/messenger.py#L59-L69
def wait_for_news_from(address, prefix=config.EVERYTHING, wait_for_s=config.FOREVER, is_raw=False): """Wait for news whose topic starts with `prefix`. :param address: a nw0 address, eg from `nw0.discover` :param prefix: any text object [default: all messages] :param wait_for_s: how many seconds to ...
[ "def", "wait_for_news_from", "(", "address", ",", "prefix", "=", "config", ".", "EVERYTHING", ",", "wait_for_s", "=", "config", ".", "FOREVER", ",", "is_raw", "=", "False", ")", ":", "_logger", ".", "info", "(", "\"Listen on %s for news matching %s waiting for %s ...
Wait for news whose topic starts with `prefix`. :param address: a nw0 address, eg from `nw0.discover` :param prefix: any text object [default: all messages] :param wait_for_s: how many seconds to wait before giving up [default: forever] :returns: a 2-tuple of (topic, data) or (None, None) if o...
[ "Wait", "for", "news", "whose", "topic", "starts", "with", "prefix", ".", ":", "param", "address", ":", "a", "nw0", "address", "eg", "from", "nw0", ".", "discover", ":", "param", "prefix", ":", "any", "text", "object", "[", "default", ":", "all", "mess...
python
train
RJT1990/pyflux
pyflux/ssm/nllm.py
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/nllm.py#L628-L678
def plot_fit(self,intervals=True,**kwargs): """ Plots the fit of the model Returns ---------- None (plots data and the fit) """ import matplotlib.pyplot as plt import seaborn as sns figsize = kwargs.get('figsize',(10,7)) if self.latent_variables...
[ "def", "plot_fit", "(", "self", ",", "intervals", "=", "True", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "seaborn", "as", "sns", "figsize", "=", "kwargs", ".", "get", "(", "'figsize'", ",", "(", ...
Plots the fit of the model Returns ---------- None (plots data and the fit)
[ "Plots", "the", "fit", "of", "the", "model" ]
python
train
mezz64/pyHik
pyhik/hikvision.py
https://github.com/mezz64/pyHik/blob/1e7afca926e2b045257a43cbf8b1236a435493c2/pyhik/hikvision.py#L225-L231
def _do_update_callback(self, msg): """Call registered callback functions.""" for callback, sensor in self._updateCallbacks: if sensor == msg: _LOGGING.debug('Update callback %s for sensor %s', callback, sensor) callback(msg)
[ "def", "_do_update_callback", "(", "self", ",", "msg", ")", ":", "for", "callback", ",", "sensor", "in", "self", ".", "_updateCallbacks", ":", "if", "sensor", "==", "msg", ":", "_LOGGING", ".", "debug", "(", "'Update callback %s for sensor %s'", ",", "callback...
Call registered callback functions.
[ "Call", "registered", "callback", "functions", "." ]
python
train
ktbyers/netmiko
netmiko/_textfsm/_texttable.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/_textfsm/_texttable.py#L1036-L1103
def CsvToTable(self, buf, header=True, separator=","): """Parses buffer into tabular format. Strips off comments (preceded by '#'). Optionally parses and indexes by first line (header). Args: buf: String file buffer containing CSV data. header: Is the first line of buffer a header. ...
[ "def", "CsvToTable", "(", "self", ",", "buf", ",", "header", "=", "True", ",", "separator", "=", "\",\"", ")", ":", "self", ".", "Reset", "(", ")", "header_row", "=", "self", ".", "row_class", "(", ")", "if", "header", ":", "line", "=", "buf", ".",...
Parses buffer into tabular format. Strips off comments (preceded by '#'). Optionally parses and indexes by first line (header). Args: buf: String file buffer containing CSV data. header: Is the first line of buffer a header. separator: String that CSV is separated by. Returns: ...
[ "Parses", "buffer", "into", "tabular", "format", "." ]
python
train
Gbps/fastlog
fastlog/log.py
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/log.py#L67-L78
def _log(self, lvl, msg, type, args, kwargs): """ Internal method to filter into the formatter before being passed to the main Python logger """ extra = kwargs.get('extra', {}) extra.setdefault("fastlog-type", type) extra.setdefault("fastlog-indent", self._indent) ...
[ "def", "_log", "(", "self", ",", "lvl", ",", "msg", ",", "type", ",", "args", ",", "kwargs", ")", ":", "extra", "=", "kwargs", ".", "get", "(", "'extra'", ",", "{", "}", ")", "extra", ".", "setdefault", "(", "\"fastlog-type\"", ",", "type", ")", ...
Internal method to filter into the formatter before being passed to the main Python logger
[ "Internal", "method", "to", "filter", "into", "the", "formatter", "before", "being", "passed", "to", "the", "main", "Python", "logger" ]
python
train
phoikoi/sisy
src/sisy/models.py
https://github.com/phoikoi/sisy/blob/840c5463ab65488d34e99531f230e61f755d2d69/src/sisy/models.py#L359-L364
def taskinfo_with_label(label): """Return task info dictionary from task label. Internal function, pretty much only used in migrations since the model methods aren't there.""" task = Task.objects.get(label=label) info = json.loads(task._func_info) return info
[ "def", "taskinfo_with_label", "(", "label", ")", ":", "task", "=", "Task", ".", "objects", ".", "get", "(", "label", "=", "label", ")", "info", "=", "json", ".", "loads", "(", "task", ".", "_func_info", ")", "return", "info" ]
Return task info dictionary from task label. Internal function, pretty much only used in migrations since the model methods aren't there.
[ "Return", "task", "info", "dictionary", "from", "task", "label", ".", "Internal", "function", "pretty", "much", "only", "used", "in", "migrations", "since", "the", "model", "methods", "aren", "t", "there", "." ]
python
test
icometrix/dicom2nifti
dicom2nifti/convert_dicom.py
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/convert_dicom.py#L54-L96
def dicom_series_to_nifti(original_dicom_directory, output_file=None, reorient_nifti=True): """ Converts dicom single series (see pydicom) to nifty, mimicking SPM Examples: See unit test will return a dictionary containing - the NIFTI under key 'NIFTI' - the NIFTI file path under 'NII_FILE' -...
[ "def", "dicom_series_to_nifti", "(", "original_dicom_directory", ",", "output_file", "=", "None", ",", "reorient_nifti", "=", "True", ")", ":", "# copy files so we can can modify without altering the original", "temp_directory", "=", "tempfile", ".", "mkdtemp", "(", ")", ...
Converts dicom single series (see pydicom) to nifty, mimicking SPM Examples: See unit test will return a dictionary containing - the NIFTI under key 'NIFTI' - the NIFTI file path under 'NII_FILE' - the BVAL file path under 'BVAL_FILE' (only for dti) - the BVEC file path under 'BVEC_FILE' (onl...
[ "Converts", "dicom", "single", "series", "(", "see", "pydicom", ")", "to", "nifty", "mimicking", "SPM" ]
python
train
explosion/spaCy
spacy/pipeline/functions.py
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/functions.py#L39-L55
def merge_subtokens(doc, label="subtok"): """Merge subtokens into a single token. doc (Doc): The Doc object. label (unicode): The subtoken dependency label. RETURNS (Doc): The Doc object with merged subtokens. DOCS: https://spacy.io/api/pipeline-functions#merge_subtokens """ merger = Match...
[ "def", "merge_subtokens", "(", "doc", ",", "label", "=", "\"subtok\"", ")", ":", "merger", "=", "Matcher", "(", "doc", ".", "vocab", ")", "merger", ".", "add", "(", "\"SUBTOK\"", ",", "None", ",", "[", "{", "\"DEP\"", ":", "label", ",", "\"op\"", ":"...
Merge subtokens into a single token. doc (Doc): The Doc object. label (unicode): The subtoken dependency label. RETURNS (Doc): The Doc object with merged subtokens. DOCS: https://spacy.io/api/pipeline-functions#merge_subtokens
[ "Merge", "subtokens", "into", "a", "single", "token", "." ]
python
train
googleapis/google-cloud-python
logging/google/cloud/logging/client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/client.py#L294-L318
def list_metrics(self, page_size=None, page_token=None): """List metrics for the project associated with this client. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list :type page_size: int :param page_size: Optional. The maximum nu...
[ "def", "list_metrics", "(", "self", ",", "page_size", "=", "None", ",", "page_token", "=", "None", ")", ":", "return", "self", ".", "metrics_api", ".", "list_metrics", "(", "self", ".", "project", ",", "page_size", ",", "page_token", ")" ]
List metrics for the project associated with this client. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/list :type page_size: int :param page_size: Optional. The maximum number of metrics in each page of results from this reques...
[ "List", "metrics", "for", "the", "project", "associated", "with", "this", "client", "." ]
python
train
openstack/horizon
openstack_dashboard/api/neutron.py
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/neutron.py#L361-L371
def list(self, **params): """Fetches a list all security groups. :returns: List of SecurityGroup objects """ # This is to ensure tenant_id key is not populated # if tenant_id=None is specified. tenant_id = params.pop('tenant_id', self.request.user.tenant_id) if t...
[ "def", "list", "(", "self", ",", "*", "*", "params", ")", ":", "# This is to ensure tenant_id key is not populated", "# if tenant_id=None is specified.", "tenant_id", "=", "params", ".", "pop", "(", "'tenant_id'", ",", "self", ".", "request", ".", "user", ".", "te...
Fetches a list all security groups. :returns: List of SecurityGroup objects
[ "Fetches", "a", "list", "all", "security", "groups", "." ]
python
train
CalebBell/fluids
fluids/fittings.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/fittings.py#L3693-L3758
def K_angle_stop_check_valve_Crane(D1, D2, fd=None, style=0): r'''Returns the loss coefficient for a angle stop check valve as shown in [1]_. If β = 1: .. math:: K = K_1 = K_2 = N\cdot f_d Otherwise: .. math:: K_2 = \frac{K + \left[0.5(1-\beta^2) ...
[ "def", "K_angle_stop_check_valve_Crane", "(", "D1", ",", "D2", ",", "fd", "=", "None", ",", "style", "=", "0", ")", ":", "if", "fd", "is", "None", ":", "fd", "=", "ft_Crane", "(", "D2", ")", "try", ":", "K", "=", "angle_stop_check_valve_Crane_coeffs", ...
r'''Returns the loss coefficient for a angle stop check valve as shown in [1]_. If β = 1: .. math:: K = K_1 = K_2 = N\cdot f_d Otherwise: .. math:: K_2 = \frac{K + \left[0.5(1-\beta^2) + (1-\beta^2)^2\right]}{\beta^4} Style 0 is the stand...
[ "r", "Returns", "the", "loss", "coefficient", "for", "a", "angle", "stop", "check", "valve", "as", "shown", "in", "[", "1", "]", "_", ".", "If", "β", "=", "1", ":", "..", "math", "::", "K", "=", "K_1", "=", "K_2", "=", "N", "\\", "cdot", "f_d",...
python
train
pybel/pybel-tools
src/pybel_tools/analysis/neurommsig/algorithm.py
https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/algorithm.py#L166-L172
def neurommsig_gene_ora(graph: BELGraph, genes: List[Gene]) -> float: """Calculate the percentage of target genes mappable to the graph. Assume: graph central dogma inferred, collapsed to genes, collapsed variants """ graph_genes = set(get_nodes_by_function(graph, GENE)) return len(graph_genes...
[ "def", "neurommsig_gene_ora", "(", "graph", ":", "BELGraph", ",", "genes", ":", "List", "[", "Gene", "]", ")", "->", "float", ":", "graph_genes", "=", "set", "(", "get_nodes_by_function", "(", "graph", ",", "GENE", ")", ")", "return", "len", "(", "graph_...
Calculate the percentage of target genes mappable to the graph. Assume: graph central dogma inferred, collapsed to genes, collapsed variants
[ "Calculate", "the", "percentage", "of", "target", "genes", "mappable", "to", "the", "graph", ".", "Assume", ":", "graph", "central", "dogma", "inferred", "collapsed", "to", "genes", "collapsed", "variants" ]
python
valid
Stewori/pytypes
pytypes/type_util.py
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L125-L170
def get_iterable_itemtype(obj): """Attempts to get an iterable's itemtype without iterating over it, not even partly. Note that iterating over an iterable might modify its inner state, e.g. if it is an iterator. Note that obj is expected to be an iterable, not a typing.Iterable. This function levera...
[ "def", "get_iterable_itemtype", "(", "obj", ")", ":", "# support further specific iterables on demand", "try", ":", "if", "isinstance", "(", "obj", ",", "range", ")", ":", "tpl", "=", "tuple", "(", "deep_type", "(", "obj", ".", "start", ")", ",", "deep_type", ...
Attempts to get an iterable's itemtype without iterating over it, not even partly. Note that iterating over an iterable might modify its inner state, e.g. if it is an iterator. Note that obj is expected to be an iterable, not a typing.Iterable. This function leverages various alternative ways to obtain ...
[ "Attempts", "to", "get", "an", "iterable", "s", "itemtype", "without", "iterating", "over", "it", "not", "even", "partly", ".", "Note", "that", "iterating", "over", "an", "iterable", "might", "modify", "its", "inner", "state", "e", ".", "g", ".", "if", "...
python
train
kensho-technologies/graphql-compiler
graphql_compiler/compiler/emit_sql.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/compiler/emit_sql.py#L273-L286
def _transform_local_field_to_expression(expression, node, context): """Transform a LocalField compiler expression into its SQLAlchemy expression representation. Args: expression: expression, LocalField compiler expression. node: SqlNode, the SqlNode the expression applies to. context: ...
[ "def", "_transform_local_field_to_expression", "(", "expression", ",", "node", ",", "context", ")", ":", "column_name", "=", "expression", ".", "field_name", "column", "=", "sql_context_helpers", ".", "get_column", "(", "column_name", ",", "node", ",", "context", ...
Transform a LocalField compiler expression into its SQLAlchemy expression representation. Args: expression: expression, LocalField compiler expression. node: SqlNode, the SqlNode the expression applies to. context: CompilationContext, global compilation state and metadata. Returns: ...
[ "Transform", "a", "LocalField", "compiler", "expression", "into", "its", "SQLAlchemy", "expression", "representation", "." ]
python
train
dpkp/kafka-python
kafka/client_async.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/client_async.py#L704-L738
def least_loaded_node(self): """Choose the node with fewest outstanding requests, with fallbacks. This method will prefer a node with an existing connection and no in-flight-requests. If no such node is found, a node will be chosen randomly from disconnected nodes that are not "blacked ...
[ "def", "least_loaded_node", "(", "self", ")", ":", "nodes", "=", "[", "broker", ".", "nodeId", "for", "broker", "in", "self", ".", "cluster", ".", "brokers", "(", ")", "]", "random", ".", "shuffle", "(", "nodes", ")", "inflight", "=", "float", "(", "...
Choose the node with fewest outstanding requests, with fallbacks. This method will prefer a node with an existing connection and no in-flight-requests. If no such node is found, a node will be chosen randomly from disconnected nodes that are not "blacked out" (i.e., are not subject to a...
[ "Choose", "the", "node", "with", "fewest", "outstanding", "requests", "with", "fallbacks", "." ]
python
train
DataDog/integrations-core
tokumx/datadog_checks/tokumx/vendor/pymongo/common.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/common.py#L178-L187
def validate_readable(option, value): """Validates that 'value' is file-like and readable. """ if value is None: return value # First make sure its a string py3.3 open(True, 'r') succeeds # Used in ssl cert checking due to poor ssl module error reporting value = validate_string(option, v...
[ "def", "validate_readable", "(", "option", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "value", "# First make sure its a string py3.3 open(True, 'r') succeeds", "# Used in ssl cert checking due to poor ssl module error reporting", "value", "=", "validate...
Validates that 'value' is file-like and readable.
[ "Validates", "that", "value", "is", "file", "-", "like", "and", "readable", "." ]
python
train
cisco-sas/kitty
kitty/model/low_level/field.py
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/model/low_level/field.py#L938-L944
def hash(self): ''' :rtype: int :return: hash of the field ''' hashed = super(_LibraryBitField, self).hash() return khash(hashed, self._length, self._signed, self._min_value, self._max_value)
[ "def", "hash", "(", "self", ")", ":", "hashed", "=", "super", "(", "_LibraryBitField", ",", "self", ")", ".", "hash", "(", ")", "return", "khash", "(", "hashed", ",", "self", ".", "_length", ",", "self", ".", "_signed", ",", "self", ".", "_min_value"...
:rtype: int :return: hash of the field
[ ":", "rtype", ":", "int", ":", "return", ":", "hash", "of", "the", "field" ]
python
train
gem/oq-engine
openquake/hazardlib/gsim/nga_east.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/nga_east.py#L530-L534
def _get_tau(self, imt, mag): """ Returns the inter-event standard deviation (tau) """ return TAU_EXECUTION[self.tau_model](imt, mag, self.TAU)
[ "def", "_get_tau", "(", "self", ",", "imt", ",", "mag", ")", ":", "return", "TAU_EXECUTION", "[", "self", ".", "tau_model", "]", "(", "imt", ",", "mag", ",", "self", ".", "TAU", ")" ]
Returns the inter-event standard deviation (tau)
[ "Returns", "the", "inter", "-", "event", "standard", "deviation", "(", "tau", ")" ]
python
train
pyQode/pyqode.core
pyqode/core/widgets/splittable_tab_widget.py
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/widgets/splittable_tab_widget.py#L971-L979
def count(self): """ Returns the number of widgets currently displayed (takes child splits into account). """ c = self.main_tab_widget.count() for child in self.child_splitters: c += child.count() return c
[ "def", "count", "(", "self", ")", ":", "c", "=", "self", ".", "main_tab_widget", ".", "count", "(", ")", "for", "child", "in", "self", ".", "child_splitters", ":", "c", "+=", "child", ".", "count", "(", ")", "return", "c" ]
Returns the number of widgets currently displayed (takes child splits into account).
[ "Returns", "the", "number", "of", "widgets", "currently", "displayed", "(", "takes", "child", "splits", "into", "account", ")", "." ]
python
train
JarryShaw/PyPCAPKit
src/const/ipv6/routing.py
https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv6/routing.py#L21-L27
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Routing(key) if key not in Routing._member_map_: extend_enum(Routing, key, default) return Routing[key]
[ "def", "get", "(", "key", ",", "default", "=", "-", "1", ")", ":", "if", "isinstance", "(", "key", ",", "int", ")", ":", "return", "Routing", "(", "key", ")", "if", "key", "not", "in", "Routing", ".", "_member_map_", ":", "extend_enum", "(", "Routi...
Backport support for original codes.
[ "Backport", "support", "for", "original", "codes", "." ]
python
train
improbable-research/keanu
keanu-python/keanu/vertex/generated.py
https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/keanu-python/keanu/vertex/generated.py#L523-L529
def Sum(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Performs a sum across all dimensions :param input_vertex: the vertex to have its values summed """ return Double(context.jvm_view().SumVertex, label, cast_to_double_vertex(input_vertex))
[ "def", "Sum", "(", "input_vertex", ":", "vertex_constructor_param_types", ",", "label", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Vertex", ":", "return", "Double", "(", "context", ".", "jvm_view", "(", ")", ".", "SumVertex", ",", "label", ...
Performs a sum across all dimensions :param input_vertex: the vertex to have its values summed
[ "Performs", "a", "sum", "across", "all", "dimensions", ":", "param", "input_vertex", ":", "the", "vertex", "to", "have", "its", "values", "summed" ]
python
train
f3at/feat
src/feat/simulation/driver.py
https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/simulation/driver.py#L288-L297
def freeze_all(self): ''' Stop all activity of the agents running. ''' d = defer.succeed(None) for x in self.iter_agents(): d.addCallback(defer.drop_param, x._cancel_long_running_protocols) d.addCallback(defer.drop_param, x._cancel_all_delayed_calls) ...
[ "def", "freeze_all", "(", "self", ")", ":", "d", "=", "defer", ".", "succeed", "(", "None", ")", "for", "x", "in", "self", ".", "iter_agents", "(", ")", ":", "d", ".", "addCallback", "(", "defer", ".", "drop_param", ",", "x", ".", "_cancel_long_runni...
Stop all activity of the agents running.
[ "Stop", "all", "activity", "of", "the", "agents", "running", "." ]
python
train
Skype4Py/Skype4Py
Skype4Py/skype.py
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L555-L567
def CreateChatWith(self, *Usernames): """Creates a chat with one or more users. :Parameters: Usernames : str One or more Skypenames of the users. :return: A chat object :rtype: `Chat` :see: `Chat.AddMembers` """ return Chat(self, chop(self...
[ "def", "CreateChatWith", "(", "self", ",", "*", "Usernames", ")", ":", "return", "Chat", "(", "self", ",", "chop", "(", "self", ".", "_DoCommand", "(", "'CHAT CREATE %s'", "%", "', '", ".", "join", "(", "Usernames", ")", ")", ",", "2", ")", "[", "1",...
Creates a chat with one or more users. :Parameters: Usernames : str One or more Skypenames of the users. :return: A chat object :rtype: `Chat` :see: `Chat.AddMembers`
[ "Creates", "a", "chat", "with", "one", "or", "more", "users", "." ]
python
train
peterldowns/lggr
lggr/__init__.py
https://github.com/peterldowns/lggr/blob/622968f17133e02d9a46a4900dd20fb3b19fe961/lggr/__init__.py#L322-L332
def Printer(open_file=sys.stdout, closing=False): """ Prints items with a timestamp. """ try: while True: logstr = (yield) open_file.write(logstr) open_file.write('\n') # new line except GeneratorExit: if closing: try: open_file.close() ...
[ "def", "Printer", "(", "open_file", "=", "sys", ".", "stdout", ",", "closing", "=", "False", ")", ":", "try", ":", "while", "True", ":", "logstr", "=", "(", "yield", ")", "open_file", ".", "write", "(", "logstr", ")", "open_file", ".", "write", "(", ...
Prints items with a timestamp.
[ "Prints", "items", "with", "a", "timestamp", "." ]
python
train
gunthercox/ChatterBot
chatterbot/storage/sql_storage.py
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/chatterbot/storage/sql_storage.py#L176-L217
def create(self, **kwargs): """ Creates a new statement matching the keyword arguments specified. Returns the created statement. """ Statement = self.get_model('statement') Tag = self.get_model('tag') session = self.Session() tags = set(kwargs.pop('tags'...
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "Tag", "=", "self", ".", "get_model", "(", "'tag'", ")", "session", "=", "self", ".", "Session", "(", ")", "tags", ...
Creates a new statement matching the keyword arguments specified. Returns the created statement.
[ "Creates", "a", "new", "statement", "matching", "the", "keyword", "arguments", "specified", ".", "Returns", "the", "created", "statement", "." ]
python
train
danilobellini/audiolazy
audiolazy/lazy_auditory.py
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_auditory.py#L225-L290
def phon2dB(loudness=None): """ Loudness in phons to Sound Pressure Level (SPL) in dB using the ISO/FDIS 226:2003 model. This function needs Scipy, as ``scipy.interpolate.UnivariateSpline`` objects are used as interpolators. Parameters ---------- loudness : The loudness value in phons to be conver...
[ "def", "phon2dB", "(", "loudness", "=", "None", ")", ":", "from", "scipy", ".", "interpolate", "import", "UnivariateSpline", "table", "=", "phon2dB", ".", "iso226", ".", "table", "schema", "=", "phon2dB", ".", "iso226", ".", "schema", "freqs", "=", "[", ...
Loudness in phons to Sound Pressure Level (SPL) in dB using the ISO/FDIS 226:2003 model. This function needs Scipy, as ``scipy.interpolate.UnivariateSpline`` objects are used as interpolators. Parameters ---------- loudness : The loudness value in phons to be converted, or None (default) to get th...
[ "Loudness", "in", "phons", "to", "Sound", "Pressure", "Level", "(", "SPL", ")", "in", "dB", "using", "the", "ISO", "/", "FDIS", "226", ":", "2003", "model", "." ]
python
train
diffeo/rejester
rejester/_registry.py
https://github.com/diffeo/rejester/blob/5438a4a18be2801d7826c46e2079ba9639d2ecb4/rejester/_registry.py#L953-L979
def delete(self, dict_name): '''Delete an entire dictionary. This operation on its own is atomic and does not require a session lock, but a session lock is honored. :param str dict_name: name of the dictionary to delete :raises rejester.exceptions.LockError: if called with a se...
[ "def", "delete", "(", "self", ",", "dict_name", ")", ":", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "script", "=", "conn", ".", "register_script", "(", "'''\n if redis.call(\"get\", KEYS[1]) == ARGV[1]\n ...
Delete an entire dictionary. This operation on its own is atomic and does not require a session lock, but a session lock is honored. :param str dict_name: name of the dictionary to delete :raises rejester.exceptions.LockError: if called with a session lock, but the system doe...
[ "Delete", "an", "entire", "dictionary", "." ]
python
train
fermiPy/fermipy
fermipy/jobs/file_archive.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L632-L678
def register_file(self, filepath, creator, status=FileStatus.no_file, flags=FileFlags.no_flags): """Register a file in the archive. If the file already exists, this raises a `KeyError` Parameters ---------- filepath : str The path to the file creatror : int...
[ "def", "register_file", "(", "self", ",", "filepath", ",", "creator", ",", "status", "=", "FileStatus", ".", "no_file", ",", "flags", "=", "FileFlags", ".", "no_flags", ")", ":", "# check to see if the file already exists", "try", ":", "file_handle", "=", "self"...
Register a file in the archive. If the file already exists, this raises a `KeyError` Parameters ---------- filepath : str The path to the file creatror : int A unique key for the job that created this file status : `FileStatus` Enu...
[ "Register", "a", "file", "in", "the", "archive", "." ]
python
train
HDI-Project/ballet
ballet/util/fs.py
https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L51-L62
def splitext2(filepath): """Split filepath into root, filename, ext Args: filepath (str, path): file path Returns: str """ root, filename = os.path.split(safepath(filepath)) filename, ext = os.path.splitext(safepath(filename)) return root, filename, ext
[ "def", "splitext2", "(", "filepath", ")", ":", "root", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "safepath", "(", "filepath", ")", ")", "filename", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "safepath", "(", "filename...
Split filepath into root, filename, ext Args: filepath (str, path): file path Returns: str
[ "Split", "filepath", "into", "root", "filename", "ext" ]
python
train
saltstack/salt
salt/modules/snapper.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/snapper.py#L607-L643
def status(config='root', num_pre=None, num_post=None): ''' Returns a comparison between two snapshots config Configuration name. num_pre first snapshot ID to compare. Default is last snapshot num_post last snapshot ID to compare. Default is 0 (current state) CLI exam...
[ "def", "status", "(", "config", "=", "'root'", ",", "num_pre", "=", "None", ",", "num_post", "=", "None", ")", ":", "try", ":", "pre", ",", "post", "=", "_get_num_interval", "(", "config", ",", "num_pre", ",", "num_post", ")", "snapper", ".", "CreateCo...
Returns a comparison between two snapshots config Configuration name. num_pre first snapshot ID to compare. Default is last snapshot num_post last snapshot ID to compare. Default is 0 (current state) CLI example: .. code-block:: bash salt '*' snapper.status ...
[ "Returns", "a", "comparison", "between", "two", "snapshots" ]
python
train
skorch-dev/skorch
skorch/cli.py
https://github.com/skorch-dev/skorch/blob/5b9b8b7b7712cb6e5aaa759d9608ea6269d5bcd3/skorch/cli.py#L138-L157
def parse_net_kwargs(kwargs): """Parse arguments for the estimator. Resolves dotted names and instantiated classes. Examples -------- >>> kwargs = {'lr': 0.1, 'module__nonlin': 'torch.nn.Hardtanh(-2, max_val=3)'} >>> parse_net_kwargs(kwargs) {'lr': 0.1, 'module__nonlin': Hardtanh(min_val=-...
[ "def", "parse_net_kwargs", "(", "kwargs", ")", ":", "if", "not", "kwargs", ":", "return", "kwargs", "resolved", "=", "{", "}", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "resolved", "[", "k", "]", "=", "_resolve_dotted_name", ...
Parse arguments for the estimator. Resolves dotted names and instantiated classes. Examples -------- >>> kwargs = {'lr': 0.1, 'module__nonlin': 'torch.nn.Hardtanh(-2, max_val=3)'} >>> parse_net_kwargs(kwargs) {'lr': 0.1, 'module__nonlin': Hardtanh(min_val=-2, max_val=3)}
[ "Parse", "arguments", "for", "the", "estimator", "." ]
python
train
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/build/engine.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/engine.py#L76-L91
def add_dependency (self, targets, sources): """Adds a dependency from 'targets' to 'sources' Both 'targets' and 'sources' can be either list of target names, or a single target name. """ if isinstance (targets, str): targets = [targets] if isinstance (source...
[ "def", "add_dependency", "(", "self", ",", "targets", ",", "sources", ")", ":", "if", "isinstance", "(", "targets", ",", "str", ")", ":", "targets", "=", "[", "targets", "]", "if", "isinstance", "(", "sources", ",", "str", ")", ":", "sources", "=", "...
Adds a dependency from 'targets' to 'sources' Both 'targets' and 'sources' can be either list of target names, or a single target name.
[ "Adds", "a", "dependency", "from", "targets", "to", "sources" ]
python
train
open511/open511
open511/converter/tmdd.py
https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/converter/tmdd.py#L64-L75
def _generate_automatic_headline(c): """The only field that maps closely to Open511 <headline>, a required field, is optional in TMDD. So we sometimes need to generate our own.""" # Start with the event type, e.g. "Incident" headline = c.data['event_type'].replace('_', ' ').title() if c.data['roads'...
[ "def", "_generate_automatic_headline", "(", "c", ")", ":", "# Start with the event type, e.g. \"Incident\"", "headline", "=", "c", ".", "data", "[", "'event_type'", "]", ".", "replace", "(", "'_'", ",", "' '", ")", ".", "title", "(", ")", "if", "c", ".", "da...
The only field that maps closely to Open511 <headline>, a required field, is optional in TMDD. So we sometimes need to generate our own.
[ "The", "only", "field", "that", "maps", "closely", "to", "Open511", "<headline", ">", "a", "required", "field", "is", "optional", "in", "TMDD", ".", "So", "we", "sometimes", "need", "to", "generate", "our", "own", "." ]
python
valid
lemieuxl/pyGenClean
pyGenClean/run_data_clean_up.py
https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/run_data_clean_up.py#L3162-L3277
def check_input_files(prefix, the_type, required_type): """Check that the file is of a certain file type. :param prefix: the prefix of the input files. :param the_type: the type of the input files (bfile, tfile or file). :param required_type: the required type of the input files (bfile, tfile or ...
[ "def", "check_input_files", "(", "prefix", ",", "the_type", ",", "required_type", ")", ":", "# The files required for each type", "bfile_type", "=", "{", "\".bed\"", ",", "\".bim\"", ",", "\".fam\"", "}", "tfile_type", "=", "{", "\".tped\"", ",", "\".tfam\"", "}",...
Check that the file is of a certain file type. :param prefix: the prefix of the input files. :param the_type: the type of the input files (bfile, tfile or file). :param required_type: the required type of the input files (bfile, tfile or file). :type prefix: str :type the...
[ "Check", "that", "the", "file", "is", "of", "a", "certain", "file", "type", "." ]
python
train
elifesciences/elife-tools
elifetools/utils.py
https://github.com/elifesciences/elife-tools/blob/4b9e38cbe485c61a4ed7cbd8970c6b318334fd86/elifetools/utils.py#L78-L85
def coerce_to_int(val, default=0xDEADBEEF): """Attempts to cast given value to an integer, return the original value if failed or the default if one provided.""" try: return int(val) except (TypeError, ValueError): if default != 0xDEADBEEF: return default return val
[ "def", "coerce_to_int", "(", "val", ",", "default", "=", "0xDEADBEEF", ")", ":", "try", ":", "return", "int", "(", "val", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "if", "default", "!=", "0xDEADBEEF", ":", "return", "default", "return...
Attempts to cast given value to an integer, return the original value if failed or the default if one provided.
[ "Attempts", "to", "cast", "given", "value", "to", "an", "integer", "return", "the", "original", "value", "if", "failed", "or", "the", "default", "if", "one", "provided", "." ]
python
train
lrq3000/pyFileFixity
pyFileFixity/lib/reedsolomon/reedsolo.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/reedsolomon/reedsolo.py#L126-L178
def find_prime_polys(generator=2, c_exp=8, fast_primes=False, single=False): '''Compute the list of prime polynomials for the given generator and galois field characteristic exponent.''' # fast_primes will output less results but will be significantly faster. # single will output the first prime polynomial ...
[ "def", "find_prime_polys", "(", "generator", "=", "2", ",", "c_exp", "=", "8", ",", "fast_primes", "=", "False", ",", "single", "=", "False", ")", ":", "# fast_primes will output less results but will be significantly faster.", "# single will output the first prime polynomi...
Compute the list of prime polynomials for the given generator and galois field characteristic exponent.
[ "Compute", "the", "list", "of", "prime", "polynomials", "for", "the", "given", "generator", "and", "galois", "field", "characteristic", "exponent", "." ]
python
train
nion-software/nionswift
nion/typeshed/API_1_0.py
https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/typeshed/API_1_0.py#L1110-L1119
def create_data_and_metadata_from_data(self, data: numpy.ndarray, intensity_calibration: Calibration.Calibration=None, dimensional_calibrations: typing.List[Calibration.Calibration]=None, metadata: dict=None, timestamp: str=None) -> DataAndMetadata.DataAndMetadata: """Create a data_and_metadata object from data...
[ "def", "create_data_and_metadata_from_data", "(", "self", ",", "data", ":", "numpy", ".", "ndarray", ",", "intensity_calibration", ":", "Calibration", ".", "Calibration", "=", "None", ",", "dimensional_calibrations", ":", "typing", ".", "List", "[", "Calibration", ...
Create a data_and_metadata object from data. .. versionadded:: 1.0 .. deprecated:: 1.1 Use :py:meth:`~nion.swift.Facade.DataItem.create_data_and_metadata` instead. Scriptable: No
[ "Create", "a", "data_and_metadata", "object", "from", "data", "." ]
python
train
Esri/ArcREST
src/arcrest/agol/services.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/agol/services.py#L796-L825
def synchronizeReplica(self, replicaID, transportType="esriTransportTypeUrl", replicaServerGen=None, returnIdsForAdds=False, edits=None, returnAttachmentDatab...
[ "def", "synchronizeReplica", "(", "self", ",", "replicaID", ",", "transportType", "=", "\"esriTransportTypeUrl\"", ",", "replicaServerGen", "=", "None", ",", "returnIdsForAdds", "=", "False", ",", "edits", "=", "None", ",", "returnAttachmentDatabyURL", "=", "False",...
TODO: implement synchronize replica http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r3000000vv000000
[ "TODO", ":", "implement", "synchronize", "replica", "http", ":", "//", "resources", ".", "arcgis", ".", "com", "/", "en", "/", "help", "/", "arcgis", "-", "rest", "-", "api", "/", "index", ".", "html#", "//", "02r3000000vv000000" ]
python
train
OCA/openupgradelib
openupgradelib/openupgrade.py
https://github.com/OCA/openupgradelib/blob/b220b6498075d62c1b64073cc934513a465cfd85/openupgradelib/openupgrade.py#L1193-L1268
def map_values( cr, source_column, target_column, mapping, model=None, table=None, write='sql'): """ Map old values to new values within the same model or table. Old values presumably come from a legacy column. You will typically want to use it in post-migration scripts. :param cr: ...
[ "def", "map_values", "(", "cr", ",", "source_column", ",", "target_column", ",", "mapping", ",", "model", "=", "None", ",", "table", "=", "None", ",", "write", "=", "'sql'", ")", ":", "if", "write", "not", "in", "(", "'sql'", ",", "'orm'", ")", ":", ...
Map old values to new values within the same model or table. Old values presumably come from a legacy column. You will typically want to use it in post-migration scripts. :param cr: The database cursor :param source_column: the database column that contains old values to be \ mapped :param targ...
[ "Map", "old", "values", "to", "new", "values", "within", "the", "same", "model", "or", "table", ".", "Old", "values", "presumably", "come", "from", "a", "legacy", "column", ".", "You", "will", "typically", "want", "to", "use", "it", "in", "post", "-", ...
python
train
bcbio/bcbio-nextgen
bcbio/upload/irods.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/irods.py#L33-L47
def _upload_dir_icommands_cli(local_dir, irods_dir, config=None, metadata=None): """ Upload directory recursively via the standard icommands CLI. example: irsync -Kvar -R $resource $local_dir i:$irods_dir go to https://docs.irods.org/4.2.0/icommands/user/#irsync for more info """ args = ["-K","...
[ "def", "_upload_dir_icommands_cli", "(", "local_dir", ",", "irods_dir", ",", "config", "=", "None", ",", "metadata", "=", "None", ")", ":", "args", "=", "[", "\"-K\"", ",", "\"-v\"", ",", "\"-a\"", ",", "\"-r\"", "]", "if", "config", ":", "if", "config",...
Upload directory recursively via the standard icommands CLI. example: irsync -Kvar -R $resource $local_dir i:$irods_dir go to https://docs.irods.org/4.2.0/icommands/user/#irsync for more info
[ "Upload", "directory", "recursively", "via", "the", "standard", "icommands", "CLI", ".", "example", ":", "irsync", "-", "Kvar", "-", "R", "$resource", "$local_dir", "i", ":", "$irods_dir", "go", "to", "https", ":", "//", "docs", ".", "irods", ".", "org", ...
python
train
ska-sa/katcp-python
katcp/resource_client.py
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1408-L1411
def until_not_synced(self, timeout=None): """Return a tornado Future; resolves when any subordinate client is not synced""" yield until_any(*[r.until_not_synced() for r in dict.values(self.children)], timeout=timeout)
[ "def", "until_not_synced", "(", "self", ",", "timeout", "=", "None", ")", ":", "yield", "until_any", "(", "*", "[", "r", ".", "until_not_synced", "(", ")", "for", "r", "in", "dict", ".", "values", "(", "self", ".", "children", ")", "]", ",", "timeout...
Return a tornado Future; resolves when any subordinate client is not synced
[ "Return", "a", "tornado", "Future", ";", "resolves", "when", "any", "subordinate", "client", "is", "not", "synced" ]
python
train
marcelcaraciolo/foursquare
examples/django/example/djfoursquare/views.py
https://github.com/marcelcaraciolo/foursquare/blob/a8bda33cc2d61e25aa8df72011246269fd98aa13/examples/django/example/djfoursquare/views.py#L22-L30
def unauth(request): """ logout and remove all session data """ if check_key(request): api = get_api(request) request.session.clear() logout(request) return HttpResponseRedirect(reverse('main'))
[ "def", "unauth", "(", "request", ")", ":", "if", "check_key", "(", "request", ")", ":", "api", "=", "get_api", "(", "request", ")", "request", ".", "session", ".", "clear", "(", ")", "logout", "(", "request", ")", "return", "HttpResponseRedirect", "(", ...
logout and remove all session data
[ "logout", "and", "remove", "all", "session", "data" ]
python
train
dwavesystems/dimod
dimod/reference/composites/higherordercomposites.py
https://github.com/dwavesystems/dimod/blob/beff1b7f86b559d923ac653c1de6d593876d6d38/dimod/reference/composites/higherordercomposites.py#L132-L161
def penalty_satisfaction(response, bqm): """ Creates a penalty satisfaction list Given a sampleSet and a bqm object, will create a binary list informing whether the penalties introduced during degree reduction are satisfied for each sample in sampleSet Args: response (:obj:`.SampleSet`): S...
[ "def", "penalty_satisfaction", "(", "response", ",", "bqm", ")", ":", "record", "=", "response", ".", "record", "label_dict", "=", "response", ".", "variables", ".", "index", "if", "len", "(", "bqm", ".", "info", "[", "'reduction'", "]", ")", "==", "0", ...
Creates a penalty satisfaction list Given a sampleSet and a bqm object, will create a binary list informing whether the penalties introduced during degree reduction are satisfied for each sample in sampleSet Args: response (:obj:`.SampleSet`): Samples corresponding to provided bqm bqm...
[ "Creates", "a", "penalty", "satisfaction", "list" ]
python
train
pycontribs/pyrax
pyrax/clouddns.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/clouddns.py#L676-L698
def update_domain(self, domain, emailAddress=None, ttl=None, comment=None): """ Provides a way to modify the following attributes of a domain record: - email address - ttl setting - comment """ if not any((emailAddress, ttl, comment)): ...
[ "def", "update_domain", "(", "self", ",", "domain", ",", "emailAddress", "=", "None", ",", "ttl", "=", "None", ",", "comment", "=", "None", ")", ":", "if", "not", "any", "(", "(", "emailAddress", ",", "ttl", ",", "comment", ")", ")", ":", "raise", ...
Provides a way to modify the following attributes of a domain record: - email address - ttl setting - comment
[ "Provides", "a", "way", "to", "modify", "the", "following", "attributes", "of", "a", "domain", "record", ":", "-", "email", "address", "-", "ttl", "setting", "-", "comment" ]
python
train
fracpete/python-weka-wrapper3
python/weka/core/stemmers.py
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/stemmers.py#L43-L52
def stem(self, s): """ Performs stemming on the string. :param s: the string to stem :type s: str :return: the stemmed string :rtype: str """ return javabridge.get_env().get_string(self.__stem(javabridge.get_env().new_string_utf(s)))
[ "def", "stem", "(", "self", ",", "s", ")", ":", "return", "javabridge", ".", "get_env", "(", ")", ".", "get_string", "(", "self", ".", "__stem", "(", "javabridge", ".", "get_env", "(", ")", ".", "new_string_utf", "(", "s", ")", ")", ")" ]
Performs stemming on the string. :param s: the string to stem :type s: str :return: the stemmed string :rtype: str
[ "Performs", "stemming", "on", "the", "string", "." ]
python
train
yougov/mongo-connector
mongo_connector/namespace_config.py
https://github.com/yougov/mongo-connector/blob/557cafd4b54c848cd54ef28a258391a154650cb4/mongo_connector/namespace_config.py#L560-L567
def namespace_to_regex(namespace): """Create a RegexObject from a wildcard namespace.""" db_name, coll_name = namespace.split(".", 1) # A database name cannot contain a '.' character db_regex = re.escape(db_name).replace(r"\*", "([^.]*)") # But a collection name can. coll_regex = re.escape(coll_...
[ "def", "namespace_to_regex", "(", "namespace", ")", ":", "db_name", ",", "coll_name", "=", "namespace", ".", "split", "(", "\".\"", ",", "1", ")", "# A database name cannot contain a '.' character", "db_regex", "=", "re", ".", "escape", "(", "db_name", ")", ".",...
Create a RegexObject from a wildcard namespace.
[ "Create", "a", "RegexObject", "from", "a", "wildcard", "namespace", "." ]
python
train
pvlib/pvlib-python
pvlib/iotools/crn.py
https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/iotools/crn.py#L43-L106
def read_crn(filename): """ Read NOAA USCRN [1]_ [2]_ fixed-width file into pandas dataframe. Parameters ---------- filename: str filepath or url to read for the fixed-width file. Returns ------- data: Dataframe A dataframe with DatetimeIndex and all of the variables in...
[ "def", "read_crn", "(", "filename", ")", ":", "# read in data", "data", "=", "pd", ".", "read_fwf", "(", "filename", ",", "header", "=", "None", ",", "names", "=", "HEADERS", ".", "split", "(", "' '", ")", ",", "widths", "=", "WIDTHS", ")", "# loop her...
Read NOAA USCRN [1]_ [2]_ fixed-width file into pandas dataframe. Parameters ---------- filename: str filepath or url to read for the fixed-width file. Returns ------- data: Dataframe A dataframe with DatetimeIndex and all of the variables in the file. Notes --...
[ "Read", "NOAA", "USCRN", "[", "1", "]", "_", "[", "2", "]", "_", "fixed", "-", "width", "file", "into", "pandas", "dataframe", "." ]
python
train
Koed00/django-q
django_q/tasks.py
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L532-L540
def run(self): """ Start queueing the chain to the worker cluster :return: the chain's group id """ self.group = async_chain(chain=self.chain[:], group=self.group, cached=self.cached, sync=self.sync, broker=self.broker) self.started = True...
[ "def", "run", "(", "self", ")", ":", "self", ".", "group", "=", "async_chain", "(", "chain", "=", "self", ".", "chain", "[", ":", "]", ",", "group", "=", "self", ".", "group", ",", "cached", "=", "self", ".", "cached", ",", "sync", "=", "self", ...
Start queueing the chain to the worker cluster :return: the chain's group id
[ "Start", "queueing", "the", "chain", "to", "the", "worker", "cluster", ":", "return", ":", "the", "chain", "s", "group", "id" ]
python
train
codelv/enaml-native
src/enamlnative/android/android_coordinator_layout.py
https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_coordinator_layout.py#L35-L40
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = CoordinatorLayout(self.get_context(), None, d.style)
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "widget", "=", "CoordinatorLayout", "(", "self", ".", "get_context", "(", ")", ",", "None", ",", "d", ".", "style", ")" ]
Create the underlying widget.
[ "Create", "the", "underlying", "widget", "." ]
python
train
googlefonts/glyphsLib
Lib/glyphsLib/affine/__init__.py
https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/affine/__init__.py#L214-L243
def rotation(cls, angle, pivot=None): """Create a rotation transform at the specified angle, optionally about the specified pivot point. :param angle: Rotation angle in degrees :type angle: float :param pivot: Point to rotate about, if omitted the rotation is about t...
[ "def", "rotation", "(", "cls", ",", "angle", ",", "pivot", "=", "None", ")", ":", "ca", ",", "sa", "=", "cos_sin_deg", "(", "angle", ")", "if", "pivot", "is", "None", ":", "return", "tuple", ".", "__new__", "(", "cls", ",", "(", "ca", ",", "sa", ...
Create a rotation transform at the specified angle, optionally about the specified pivot point. :param angle: Rotation angle in degrees :type angle: float :param pivot: Point to rotate about, if omitted the rotation is about the origin. :type pivot: sequence ...
[ "Create", "a", "rotation", "transform", "at", "the", "specified", "angle", "optionally", "about", "the", "specified", "pivot", "point", "." ]
python
train
saltstack/salt
salt/modules/macdefaults.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/macdefaults.py#L93-L116
def delete(domain, key, user=None): ''' Delete a default from the system CLI Example: .. code-block:: bash salt '*' macdefaults.delete com.apple.CrashReporter DialogType salt '*' macdefaults.delete NSGlobalDomain ApplePersistence domain The name of the domain to delete f...
[ "def", "delete", "(", "domain", ",", "key", ",", "user", "=", "None", ")", ":", "cmd", "=", "'defaults delete \"{0}\" \"{1}\"'", ".", "format", "(", "domain", ",", "key", ")", "return", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "runas", "="...
Delete a default from the system CLI Example: .. code-block:: bash salt '*' macdefaults.delete com.apple.CrashReporter DialogType salt '*' macdefaults.delete NSGlobalDomain ApplePersistence domain The name of the domain to delete from key The key of the given domain...
[ "Delete", "a", "default", "from", "the", "system" ]
python
train
tell-k/django-modelsdoc
modelsdoc/templatetags/modelsdoc_tags.py
https://github.com/tell-k/django-modelsdoc/blob/c9d336e76251feb142347b3a41365430d3365436/modelsdoc/templatetags/modelsdoc_tags.py#L31-L54
def emptylineless(parser, token): """ Removes empty line. Example usage:: {% emptylineless %} test1 test2 test3 {% endemptylineless %} This example would return this HTML:: test1 test2 test3 """ nodeli...
[ "def", "emptylineless", "(", "parser", ",", "token", ")", ":", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endemptylineless'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "EmptylinelessNode", "(", "nodelist", ")" ]
Removes empty line. Example usage:: {% emptylineless %} test1 test2 test3 {% endemptylineless %} This example would return this HTML:: test1 test2 test3
[ "Removes", "empty", "line", "." ]
python
train
luckydonald/pytgbot
pytgbot/api_types/sendable/passport.py
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/passport.py#L91-L104
def to_array(self): """ Serializes this PassportElementErrorDataField to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(PassportElementErrorDataField, self).to_array() array['source'] = u(self.source) # py2: type ...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "PassportElementErrorDataField", ",", "self", ")", ".", "to_array", "(", ")", "array", "[", "'source'", "]", "=", "u", "(", "self", ".", "source", ")", "# py2: type unicode, py3: type str"...
Serializes this PassportElementErrorDataField to a dictionary. :return: dictionary representation of this object. :rtype: dict
[ "Serializes", "this", "PassportElementErrorDataField", "to", "a", "dictionary", "." ]
python
train
fhcrc/seqmagick
seqmagick/transform.py
https://github.com/fhcrc/seqmagick/blob/1642bb87ba5c171fbd307f9da0f8a0ee1d69d5ed/seqmagick/transform.py#L380-L389
def _update_id(record, new_id): """ Update a record id to new_id, also modifying the ID in record.description """ old_id = record.id record.id = new_id # At least for FASTA, record ID starts the description record.description = re.sub('^' + re.escape(old_id), new_id, record.description) ...
[ "def", "_update_id", "(", "record", ",", "new_id", ")", ":", "old_id", "=", "record", ".", "id", "record", ".", "id", "=", "new_id", "# At least for FASTA, record ID starts the description", "record", ".", "description", "=", "re", ".", "sub", "(", "'^'", "+",...
Update a record id to new_id, also modifying the ID in record.description
[ "Update", "a", "record", "id", "to", "new_id", "also", "modifying", "the", "ID", "in", "record", ".", "description" ]
python
train
spacetelescope/drizzlepac
drizzlepac/wcs_functions.py
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L580-L708
def mergeWCS(default_wcs, user_pars): """ Merges the user specified WCS values given as dictionary derived from the input configObj object with the output PyWCS object computed using distortion.output_wcs(). The user_pars dictionary needs to have the following set of keys:: use...
[ "def", "mergeWCS", "(", "default_wcs", ",", "user_pars", ")", ":", "#", "# Start by making a copy of the input WCS...", "#", "outwcs", "=", "default_wcs", ".", "deepcopy", "(", ")", "# If there are no user set parameters, just return a copy of", "# the original WCS:", "if", ...
Merges the user specified WCS values given as dictionary derived from the input configObj object with the output PyWCS object computed using distortion.output_wcs(). The user_pars dictionary needs to have the following set of keys:: user_pars = {'ra':None,'dec':None,'scale':None,'r...
[ "Merges", "the", "user", "specified", "WCS", "values", "given", "as", "dictionary", "derived", "from", "the", "input", "configObj", "object", "with", "the", "output", "PyWCS", "object", "computed", "using", "distortion", ".", "output_wcs", "()", "." ]
python
train
siznax/wptools
wptools/core.py
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/core.py#L107-L118
def _continue_params(self): """ Returns query string fragment continue parameters """ if not self.data.get('continue'): return params = [] for item in self.data['continue']: params.append("&%s=%s" % (item, self.data['continue'][item])) re...
[ "def", "_continue_params", "(", "self", ")", ":", "if", "not", "self", ".", "data", ".", "get", "(", "'continue'", ")", ":", "return", "params", "=", "[", "]", "for", "item", "in", "self", ".", "data", "[", "'continue'", "]", ":", "params", ".", "a...
Returns query string fragment continue parameters
[ "Returns", "query", "string", "fragment", "continue", "parameters" ]
python
train
LogicalDash/LiSE
allegedb/allegedb/query.py
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/query.py#L599-L605
def commit(self): """Commit the transaction""" self.flush() if hasattr(self, 'transaction') and self.transaction.is_active: self.transaction.commit() elif hasattr(self, 'connection'): self.connection.commit()
[ "def", "commit", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "if", "hasattr", "(", "self", ",", "'transaction'", ")", "and", "self", ".", "transaction", ".", "is_active", ":", "self", ".", "transaction", ".", "commit", "(", ")", "elif", "h...
Commit the transaction
[ "Commit", "the", "transaction" ]
python
train
anti1869/sunhead
src/sunhead/conf.py
https://github.com/anti1869/sunhead/blob/5117ec797a38eb82d955241d20547d125efe80f3/src/sunhead/conf.py#L120-L137
def discover_config_path(self, config_filename: str) -> str: """ Search for config file in a number of places. If there is no config file found, will return None. :param config_filename: Config file name or custom path to filename with config. :return: Path to the discovered con...
[ "def", "discover_config_path", "(", "self", ",", "config_filename", ":", "str", ")", "->", "str", ":", "if", "config_filename", "and", "os", ".", "path", ".", "isfile", "(", "config_filename", ")", ":", "return", "config_filename", "for", "place", "in", "_co...
Search for config file in a number of places. If there is no config file found, will return None. :param config_filename: Config file name or custom path to filename with config. :return: Path to the discovered config file or None.
[ "Search", "for", "config", "file", "in", "a", "number", "of", "places", ".", "If", "there", "is", "no", "config", "file", "found", "will", "return", "None", "." ]
python
train
jason-weirather/py-seq-tools
seqtools/format/sam/__init__.py
https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/format/sam/__init__.py#L145-L163
def target_sequence_length(self): """ Get the length of the target sequence. length of the entire chromosome throws an error if there is no information available :return: length :rtype: int """ if not self.is_aligned(): raise ValueError("no length for reference when read is not not alig...
[ "def", "target_sequence_length", "(", "self", ")", ":", "if", "not", "self", ".", "is_aligned", "(", ")", ":", "raise", "ValueError", "(", "\"no length for reference when read is not not aligned\"", ")", "if", "self", ".", "entries", ".", "tlen", ":", "return", ...
Get the length of the target sequence. length of the entire chromosome throws an error if there is no information available :return: length :rtype: int
[ "Get", "the", "length", "of", "the", "target", "sequence", ".", "length", "of", "the", "entire", "chromosome" ]
python
train
StanfordVL/robosuite
robosuite/utils/mjcf_utils.py
https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/utils/mjcf_utils.py#L82-L97
def new_site(name, rgba=RED, pos=(0, 0, 0), size=(0.005,), **kwargs): """ Creates a site element with attributes specified by @**kwargs. Args: name (str): site name. rgba: color and transparency. Defaults to solid red. pos: 3d position of the site. size ([float]): site size ...
[ "def", "new_site", "(", "name", ",", "rgba", "=", "RED", ",", "pos", "=", "(", "0", ",", "0", ",", "0", ")", ",", "size", "=", "(", "0.005", ",", ")", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"rgba\"", "]", "=", "array_to_string", ...
Creates a site element with attributes specified by @**kwargs. Args: name (str): site name. rgba: color and transparency. Defaults to solid red. pos: 3d position of the site. size ([float]): site size (sites are spherical by default).
[ "Creates", "a", "site", "element", "with", "attributes", "specified", "by", "@", "**", "kwargs", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_ntp.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ntp.py#L12-L23
def show_ntp_input_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_ntp = ET.Element("show_ntp") config = show_ntp input = ET.SubElement(show_ntp, "input") rbridge_id = ET.SubElement(input, "rbridge-id") rbridge_id....
[ "def", "show_ntp_input_rbridge_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_ntp", "=", "ET", ".", "Element", "(", "\"show_ntp\"", ")", "config", "=", "show_ntp", "input", "=", "ET...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
Yubico/yubikey-manager
ykman/cli/oath.py
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L403-L429
def delete(ctx, query, force): """ Delete a credential. Delete a credential from your YubiKey. Provide a query string to match the credential to delete. """ ensure_validated(ctx) controller = ctx.obj['controller'] creds = controller.list() hits = _search(creds, query) if len(hi...
[ "def", "delete", "(", "ctx", ",", "query", ",", "force", ")", ":", "ensure_validated", "(", "ctx", ")", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "creds", "=", "controller", ".", "list", "(", ")", "hits", "=", "_search", "(", "c...
Delete a credential. Delete a credential from your YubiKey. Provide a query string to match the credential to delete.
[ "Delete", "a", "credential", "." ]
python
train
tamasgal/km3pipe
km3pipe/utils/streamds.py
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/streamds.py#L56-L80
def get_data(stream, parameters, fmt): """Retrieve data for given stream and parameters, or None if not found""" sds = kp.db.StreamDS() if stream not in sds.streams: log.error("Stream '{}' not found in the database.".format(stream)) return params = {} if parameters: for param...
[ "def", "get_data", "(", "stream", ",", "parameters", ",", "fmt", ")", ":", "sds", "=", "kp", ".", "db", ".", "StreamDS", "(", ")", "if", "stream", "not", "in", "sds", ".", "streams", ":", "log", ".", "error", "(", "\"Stream '{}' not found in the database...
Retrieve data for given stream and parameters, or None if not found
[ "Retrieve", "data", "for", "given", "stream", "and", "parameters", "or", "None", "if", "not", "found" ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor_ext.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor_ext.py#L154-L167
def show_system_monitor_output_switch_status_port_status_port_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_system_monitor = ET.Element("show_system_monitor") config = show_system_monitor output = ET.SubElement(show_system_monitor, "o...
[ "def", "show_system_monitor_output_switch_status_port_status_port_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_system_monitor", "=", "ET", ".", "Element", "(", "\"show_system_monitor\"", ")...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train