repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
federico123579/Trading212-API
tradingAPI/low_level.py
https://github.com/federico123579/Trading212-API/blob/0fab20b71a2348e72bbe76071b81f3692128851f/tradingAPI/low_level.py#L125-L129
def elXpath(self, xpath, dom=None): """check if element is present by css""" if dom is None: dom = self.browser return expect(dom.is_element_present_by_xpath, args=[xpath])
[ "def", "elXpath", "(", "self", ",", "xpath", ",", "dom", "=", "None", ")", ":", "if", "dom", "is", "None", ":", "dom", "=", "self", ".", "browser", "return", "expect", "(", "dom", ".", "is_element_present_by_xpath", ",", "args", "=", "[", "xpath", "]...
check if element is present by css
[ "check", "if", "element", "is", "present", "by", "css" ]
python
train
40.8
rupertford/melody
src/melody/search.py
https://github.com/rupertford/melody/blob/d50459880a87fdd1802c6893f6e12b52d51b3b91/src/melody/search.py#L65-L79
def _check_function(self): ''' make some basic checks on the function to make sure it is valid''' # note, callable is valid for Python 2 and Python 3.2 onwards but # not inbetween if not callable(self._function): raise RuntimeError( "provided function '{0}' is...
[ "def", "_check_function", "(", "self", ")", ":", "# note, callable is valid for Python 2 and Python 3.2 onwards but", "# not inbetween", "if", "not", "callable", "(", "self", ".", "_function", ")", ":", "raise", "RuntimeError", "(", "\"provided function '{0}' is not callable\...
make some basic checks on the function to make sure it is valid
[ "make", "some", "basic", "checks", "on", "the", "function", "to", "make", "sure", "it", "is", "valid" ]
python
test
44.866667
costastf/locationsharinglib
_CI/library/patch.py
https://github.com/costastf/locationsharinglib/blob/dcd74b0cdb59b951345df84987238763e50ef282/_CI/library/patch.py#L964-L976
def _reverse(self): """ reverse patch direction (this doesn't touch filenames) """ for p in self.items: for h in p.hunks: h.startsrc, h.starttgt = h.starttgt, h.startsrc h.linessrc, h.linestgt = h.linestgt, h.linessrc for i,line in enumerate(h.text): # need to use line[0:...
[ "def", "_reverse", "(", "self", ")", ":", "for", "p", "in", "self", ".", "items", ":", "for", "h", "in", "p", ".", "hunks", ":", "h", ".", "startsrc", ",", "h", ".", "starttgt", "=", "h", ".", "starttgt", ",", "h", ".", "startsrc", "h", ".", ...
reverse patch direction (this doesn't touch filenames)
[ "reverse", "patch", "direction", "(", "this", "doesn", "t", "touch", "filenames", ")" ]
python
train
40.769231
nir0s/ghost
ghost.py
https://github.com/nir0s/ghost/blob/77da967a4577ca4cf100cfe34e87b39ad88bf21c/ghost.py#L1628-L1638
def export_keys(output_path, stash, passphrase, backend): """Export all keys to a file """ stash = _get_stash(backend, stash, passphrase) try: click.echo('Exporting stash to {0}...'.format(output_path)) stash.export(output_path=output_path) click.echo('Export complete!') exc...
[ "def", "export_keys", "(", "output_path", ",", "stash", ",", "passphrase", ",", "backend", ")", ":", "stash", "=", "_get_stash", "(", "backend", ",", "stash", ",", "passphrase", ")", "try", ":", "click", ".", "echo", "(", "'Exporting stash to {0}...'", ".", ...
Export all keys to a file
[ "Export", "all", "keys", "to", "a", "file" ]
python
valid
32
saltstack/salt
salt/utils/schema.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schema.py#L1481-L1493
def _add_missing_schema_attributes(self): ''' Adds any missed schema attributes to the _attributes list The attributes can be class attributes and they won't be included in the _attributes list automatically ''' for attr in [attr for attr in dir(self) if not attr.startsw...
[ "def", "_add_missing_schema_attributes", "(", "self", ")", ":", "for", "attr", "in", "[", "attr", "for", "attr", "in", "dir", "(", "self", ")", "if", "not", "attr", ".", "startswith", "(", "'__'", ")", "]", ":", "attr_val", "=", "getattr", "(", "self",...
Adds any missed schema attributes to the _attributes list The attributes can be class attributes and they won't be included in the _attributes list automatically
[ "Adds", "any", "missed", "schema", "attributes", "to", "the", "_attributes", "list" ]
python
train
39.923077
tcalmant/ipopo
pelix/internals/registry.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L1016-L1027
def clear(self): """ Clears the registry """ with self.__svc_lock: self.__svc_registry.clear() self.__svc_factories.clear() self.__svc_specs.clear() self.__bundle_svc.clear() self.__bundle_imports.clear() self.__fact...
[ "def", "clear", "(", "self", ")", ":", "with", "self", ".", "__svc_lock", ":", "self", ".", "__svc_registry", ".", "clear", "(", ")", "self", ".", "__svc_factories", ".", "clear", "(", ")", "self", ".", "__svc_specs", ".", "clear", "(", ")", "self", ...
Clears the registry
[ "Clears", "the", "registry" ]
python
train
30.833333
mar10/pyftpsync
ftpsync/ftp_target.py
https://github.com/mar10/pyftpsync/blob/bbdc94186975cdc1cc4f678474bdce08bce7bb76/ftpsync/ftp_target.py#L677-L688
def _ftp_nlst(self, dir_name): """Variant of `self.ftp.nlst()` that supports encoding-fallback.""" assert compat.is_native(dir_name) lines = [] def _add_line(status, line): lines.append(line) cmd = "NLST " + dir_name self._ftp_retrlines_native(cmd, ...
[ "def", "_ftp_nlst", "(", "self", ",", "dir_name", ")", ":", "assert", "compat", ".", "is_native", "(", "dir_name", ")", "lines", "=", "[", "]", "def", "_add_line", "(", "status", ",", "line", ")", ":", "lines", ".", "append", "(", "line", ")", "cmd",...
Variant of `self.ftp.nlst()` that supports encoding-fallback.
[ "Variant", "of", "self", ".", "ftp", ".", "nlst", "()", "that", "supports", "encoding", "-", "fallback", "." ]
python
train
32.083333
gem/oq-engine
openquake/commonlib/shapefileparser.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L120-L143
def extract_source_params(src): """ Extract params from source object. """ tags = get_taglist(src) data = [] for key, param, vtype in BASE_PARAMS: if key in src.attrib: if vtype == "c": data.append((param, src.attrib[key])) elif vtype == "f": ...
[ "def", "extract_source_params", "(", "src", ")", ":", "tags", "=", "get_taglist", "(", "src", ")", "data", "=", "[", "]", "for", "key", ",", "param", ",", "vtype", "in", "BASE_PARAMS", ":", "if", "key", "in", "src", ".", "attrib", ":", "if", "vtype",...
Extract params from source object.
[ "Extract", "params", "from", "source", "object", "." ]
python
train
32.583333
python-openxml/python-docx
docx/oxml/xmlchemy.py
https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/oxml/xmlchemy.py#L664-L675
def _choice_getter(self): """ Return a function object suitable for the "get" side of the property descriptor. """ def get_group_member_element(obj): return obj.first_child_found_in(*self._member_nsptagnames) get_group_member_element.__doc__ = ( 'R...
[ "def", "_choice_getter", "(", "self", ")", ":", "def", "get_group_member_element", "(", "obj", ")", ":", "return", "obj", ".", "first_child_found_in", "(", "*", "self", ".", "_member_nsptagnames", ")", "get_group_member_element", ".", "__doc__", "=", "(", "'Retu...
Return a function object suitable for the "get" side of the property descriptor.
[ "Return", "a", "function", "object", "suitable", "for", "the", "get", "side", "of", "the", "property", "descriptor", "." ]
python
train
39.333333
newville/wxmplot
wxmplot/stackedplotframe.py
https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/stackedplotframe.py#L99-L102
def save_figure(self, event=None, panel='top'): """ save figure image to file""" panel = self.get_panel(panel) panel.save_figure(event=event)
[ "def", "save_figure", "(", "self", ",", "event", "=", "None", ",", "panel", "=", "'top'", ")", ":", "panel", "=", "self", ".", "get_panel", "(", "panel", ")", "panel", ".", "save_figure", "(", "event", "=", "event", ")" ]
save figure image to file
[ "save", "figure", "image", "to", "file" ]
python
train
40.5
MillionIntegrals/vel
vel/internals/model_config.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L18-L30
def find_project_directory(start_path) -> str: """ Locate top-level project directory """ start_path = os.path.realpath(start_path) possible_name = os.path.join(start_path, ModelConfig.PROJECT_FILE_NAME) if os.path.exists(possible_name): return start_path else: ...
[ "def", "find_project_directory", "(", "start_path", ")", "->", "str", ":", "start_path", "=", "os", ".", "path", ".", "realpath", "(", "start_path", ")", "possible_name", "=", "os", ".", "path", ".", "join", "(", "start_path", ",", "ModelConfig", ".", "PRO...
Locate top-level project directory
[ "Locate", "top", "-", "level", "project", "directory" ]
python
train
46.769231
google/neuroglancer
python/neuroglancer/downsample_scales.py
https://github.com/google/neuroglancer/blob/9efd12741013f464286f0bf3fa0b667f75a66658/python/neuroglancer/downsample_scales.py#L53-L88
def compute_two_dimensional_near_isotropic_downsampling_scales( size, voxel_size, max_scales=float('inf'), max_downsampling=DEFAULT_MAX_DOWNSAMPLING, max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE): """Compute a list of successive downsampling factors for 2-d tiles.""" ...
[ "def", "compute_two_dimensional_near_isotropic_downsampling_scales", "(", "size", ",", "voxel_size", ",", "max_scales", "=", "float", "(", "'inf'", ")", ",", "max_downsampling", "=", "DEFAULT_MAX_DOWNSAMPLING", ",", "max_downsampled_size", "=", "DEFAULT_MAX_DOWNSAMPLED_SIZE",...
Compute a list of successive downsampling factors for 2-d tiles.
[ "Compute", "a", "list", "of", "successive", "downsampling", "factors", "for", "2", "-", "d", "tiles", "." ]
python
train
39.583333
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L288-L335
def revnet(inputs, hparams, reuse=None): """Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained in the basic_params1() o...
[ "def", "revnet", "(", "inputs", ",", "hparams", ",", "reuse", "=", "None", ")", ":", "training", "=", "hparams", ".", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "with", "tf", ".", "variable_scope", "(", "'RevNet'", ",", "reuse...
Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained in the basic_params1() object in the common_hparams module: ...
[ "Uses", "Tensor2Tensor", "memory", "optimized", "RevNet", "block", "to", "build", "a", "RevNet", "." ]
python
train
51.791667
project-rig/rig
rig/machine_control/bmp_controller.py
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/bmp_controller.py#L254-L292
def set_led(self, led, action=None, cabinet=Required, frame=Required, board=Required): """Set or toggle the state of an LED. .. note:: At the time of writing, LED 7 is only set by the BMP on start-up to indicate that the watchdog timer reset the board. After this...
[ "def", "set_led", "(", "self", ",", "led", ",", "action", "=", "None", ",", "cabinet", "=", "Required", ",", "frame", "=", "Required", ",", "board", "=", "Required", ")", ":", "if", "isinstance", "(", "led", ",", "int", ")", ":", "leds", "=", "[", ...
Set or toggle the state of an LED. .. note:: At the time of writing, LED 7 is only set by the BMP on start-up to indicate that the watchdog timer reset the board. After this point, the LED is available for use by applications. Parameters ---------- l...
[ "Set", "or", "toggle", "the", "state", "of", "an", "LED", "." ]
python
train
37.025641
mattharrison/rst2odp
odplib/zipwrap.py
https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/zipwrap.py#L223-L229
def unzip(self, directory): """ Write contents of zipfile to directory """ if not os.path.exists(directory): os.makedirs(directory) shutil.copytree(self.src_dir, directory)
[ "def", "unzip", "(", "self", ",", "directory", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ")", "shutil", ".", "copytree", "(", "self", ".", "src_dir", ",", "directory"...
Write contents of zipfile to directory
[ "Write", "contents", "of", "zipfile", "to", "directory" ]
python
train
31.142857
fastai/fastai
courses/dl2/imdb_scripts/predict_with_classifier.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/courses/dl2/imdb_scripts/predict_with_classifier.py#L6-L38
def load_model(itos_filename, classifier_filename, num_classes): """Load the classifier and int to string mapping Args: itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl) classifier_filename (str): The filename of the trained classifier Returns: ...
[ "def", "load_model", "(", "itos_filename", ",", "classifier_filename", ",", "num_classes", ")", ":", "# load the int to string mapping file", "itos", "=", "pickle", ".", "load", "(", "Path", "(", "itos_filename", ")", ".", "open", "(", "'rb'", ")", ")", "# turn ...
Load the classifier and int to string mapping Args: itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl) classifier_filename (str): The filename of the trained classifier Returns: string to int mapping, trained classifer model
[ "Load", "the", "classifier", "and", "int", "to", "string", "mapping" ]
python
train
38.939394
lambdamusic/Ontospy
ontospy/extras/hacks/turtle-cli.py
https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/extras/hacks/turtle-cli.py#L42-L48
def get_default_preds(): """dynamically build autocomplete options based on an external file""" g = ontospy.Ontospy(rdfsschema, text=True, verbose=False, hide_base_schemas=False) classes = [(x.qname, x.bestDescription()) for x in g.all_classes] properties = [(x.qname, x.bestDescription()) for x in g.all...
[ "def", "get_default_preds", "(", ")", ":", "g", "=", "ontospy", ".", "Ontospy", "(", "rdfsschema", ",", "text", "=", "True", ",", "verbose", "=", "False", ",", "hide_base_schemas", "=", "False", ")", "classes", "=", "[", "(", "x", ".", "qname", ",", ...
dynamically build autocomplete options based on an external file
[ "dynamically", "build", "autocomplete", "options", "based", "on", "an", "external", "file" ]
python
train
67.714286
apache/spark
python/pyspark/ml/image.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/image.py#L87-L101
def columnSchema(self): """ Returns the schema for the image column. :return: a :class:`StructType` for image column, ``struct<origin:string, height:int, width:int, nChannels:int, mode:int, data:binary>``. .. versionadded:: 2.4.0 """ if self._columnSchema i...
[ "def", "columnSchema", "(", "self", ")", ":", "if", "self", ".", "_columnSchema", "is", "None", ":", "ctx", "=", "SparkContext", ".", "_active_spark_context", "jschema", "=", "ctx", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "ml", ".", ...
Returns the schema for the image column. :return: a :class:`StructType` for image column, ``struct<origin:string, height:int, width:int, nChannels:int, mode:int, data:binary>``. .. versionadded:: 2.4.0
[ "Returns", "the", "schema", "for", "the", "image", "column", "." ]
python
train
37.4
wgnet/webium
webium/cookie.py
https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/cookie.py#L41-L47
def add_cookies_to_web_driver(driver, cookies): """ Sets cookies in an existing WebDriver session. """ for cookie in cookies: driver.add_cookie(convert_cookie_to_dict(cookie)) return driver
[ "def", "add_cookies_to_web_driver", "(", "driver", ",", "cookies", ")", ":", "for", "cookie", "in", "cookies", ":", "driver", ".", "add_cookie", "(", "convert_cookie_to_dict", "(", "cookie", ")", ")", "return", "driver" ]
Sets cookies in an existing WebDriver session.
[ "Sets", "cookies", "in", "an", "existing", "WebDriver", "session", "." ]
python
train
30.142857
Azure/azure-sdk-for-python
azure-servicemanagement-legacy/azure/servicemanagement/_http/winhttp.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/_http/winhttp.py#L442-L447
def send(self, request_body): ''' Sends request body. ''' if not request_body: self._httprequest.send() else: self._httprequest.send(request_body)
[ "def", "send", "(", "self", ",", "request_body", ")", ":", "if", "not", "request_body", ":", "self", ".", "_httprequest", ".", "send", "(", ")", "else", ":", "self", ".", "_httprequest", ".", "send", "(", "request_body", ")" ]
Sends request body.
[ "Sends", "request", "body", "." ]
python
test
31.5
tensorflow/tensor2tensor
tensor2tensor/utils/registry.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L306-L334
def parse_problem_name(name): """Determines if problem_name specifies a copy and/or reversal. Args: name: str, problem name, possibly with suffixes. Returns: ProblemSpec: namedtuple with ["base_name", "was_reversed", "was_copy"] Raises: ValueError if name contains multiple suffixes of the same ty...
[ "def", "parse_problem_name", "(", "name", ")", ":", "# Recursively strip tags until we reach a base name.", "if", "name", ".", "endswith", "(", "\"_rev\"", ")", ":", "base", ",", "was_reversed", ",", "was_copy", "=", "parse_problem_name", "(", "name", "[", ":", "-...
Determines if problem_name specifies a copy and/or reversal. Args: name: str, problem name, possibly with suffixes. Returns: ProblemSpec: namedtuple with ["base_name", "was_reversed", "was_copy"] Raises: ValueError if name contains multiple suffixes of the same type ('_rev' or '_copy'). One o...
[ "Determines", "if", "problem_name", "specifies", "a", "copy", "and", "/", "or", "reversal", "." ]
python
train
34
jlesquembre/jlle
jlle/releaser/utils.py
https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/utils.py#L90-L105
def system(command, answer=''): """commands.getoutput() replacement that also works on windows""" p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ...
[ "def", "system", "(", "command", ",", "answer", "=", "''", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "command", ",", "shell", "=", "True", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", ...
commands.getoutput() replacement that also works on windows
[ "commands", ".", "getoutput", "()", "replacement", "that", "also", "works", "on", "windows" ]
python
train
34.0625
mlavin/django-hilbert
hilbert/decorators.py
https://github.com/mlavin/django-hilbert/blob/e77b685f4afc6e1224dc7e616e9ee9f7c2bc55b6/hilbert/decorators.py#L50-L67
def anonymous_required(func=None, url=None): """Required that the user is not logged in.""" url = url or "/" def _dec(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): ...
[ "def", "anonymous_required", "(", "func", "=", "None", ",", "url", "=", "None", ")", ":", "url", "=", "url", "or", "\"/\"", "def", "_dec", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_f...
Required that the user is not logged in.
[ "Required", "that", "the", "user", "is", "not", "logged", "in", "." ]
python
train
28.388889
campaignmonitor/createsend-python
lib/createsend/transactional.py
https://github.com/campaignmonitor/createsend-python/blob/4bfe2fd5cb2fc9d8f12280b23569eea0a6c66426/lib/createsend/transactional.py#L16-L24
def smart_email_list(self, status="all", client_id=None): """Gets the smart email list.""" if client_id is None: response = self._get( "/transactional/smartEmail?status=%s" % status) else: response = self._get( "/transactional/smartEmail?st...
[ "def", "smart_email_list", "(", "self", ",", "status", "=", "\"all\"", ",", "client_id", "=", "None", ")", ":", "if", "client_id", "is", "None", ":", "response", "=", "self", ".", "_get", "(", "\"/transactional/smartEmail?status=%s\"", "%", "status", ")", "e...
Gets the smart email list.
[ "Gets", "the", "smart", "email", "list", "." ]
python
train
43.444444
saltstack/salt
salt/modules/saltutil.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L126-L189
def update(version=None): ''' Update the salt minion from the URL defined in opts['update_url'] SaltStack, Inc provides the latest builds here: update_url: https://repo.saltstack.com/windows/ Be aware that as of 2014-8-11 there's a bug in esky such that only the latest version available in the ...
[ "def", "update", "(", "version", "=", "None", ")", ":", "ret", "=", "{", "}", "if", "not", "HAS_ESKY", ":", "ret", "[", "'_error'", "]", "=", "'Esky not available as import'", "return", "ret", "if", "not", "getattr", "(", "sys", ",", "'frozen'", ",", "...
Update the salt minion from the URL defined in opts['update_url'] SaltStack, Inc provides the latest builds here: update_url: https://repo.saltstack.com/windows/ Be aware that as of 2014-8-11 there's a bug in esky such that only the latest version available in the update_url can be downloaded and insta...
[ "Update", "the", "salt", "minion", "from", "the", "URL", "defined", "in", "opts", "[", "update_url", "]", "SaltStack", "Inc", "provides", "the", "latest", "builds", "here", ":", "update_url", ":", "https", ":", "//", "repo", ".", "saltstack", ".", "com", ...
python
train
34.65625
zebpalmer/WeatherAlerts
weatheralerts/weather_alerts.py
https://github.com/zebpalmer/WeatherAlerts/blob/b99513571571fa0d65b90be883bb3bc000994027/weatheralerts/weather_alerts.py#L48-L56
def load_alerts(self): """ NOTE: use refresh() instead of this, if you are just needing to refresh the alerts list Gets raw xml (cap) from the Alerts feed, throws it into the parser and ends up with a list of alerts object, which it stores to self._alerts """ self._feed =...
[ "def", "load_alerts", "(", "self", ")", ":", "self", ".", "_feed", "=", "AlertsFeed", "(", "state", "=", "self", ".", "scope", ",", "maxage", "=", "self", ".", "cachetime", ")", "parser", "=", "CapParser", "(", "self", ".", "_feed", ".", "raw_cap", "...
NOTE: use refresh() instead of this, if you are just needing to refresh the alerts list Gets raw xml (cap) from the Alerts feed, throws it into the parser and ends up with a list of alerts object, which it stores to self._alerts
[ "NOTE", ":", "use", "refresh", "()", "instead", "of", "this", "if", "you", "are", "just", "needing", "to", "refresh", "the", "alerts", "list", "Gets", "raw", "xml", "(", "cap", ")", "from", "the", "Alerts", "feed", "throws", "it", "into", "the", "parse...
python
train
52.222222
fbngrm/babelpy
babelpy/babelfy.py
https://github.com/fbngrm/babelpy/blob/ff305abecddd66aed40c32f0010485cf192e5f17/babelpy/babelfy.py#L196-L201
def _parse_merged_entities(self): """set self._merged_entities to the longest possible(wrapping) tokens """ self._merged_entities = list(filterfalse( lambda token: self._is_wrapped(token, self.entities), self.entities))
[ "def", "_parse_merged_entities", "(", "self", ")", ":", "self", ".", "_merged_entities", "=", "list", "(", "filterfalse", "(", "lambda", "token", ":", "self", ".", "_is_wrapped", "(", "token", ",", "self", ".", "entities", ")", ",", "self", ".", "entities"...
set self._merged_entities to the longest possible(wrapping) tokens
[ "set", "self", ".", "_merged_entities", "to", "the", "longest", "possible", "(", "wrapping", ")", "tokens" ]
python
train
43.666667
saltstack/salt
salt/modules/saltutil.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L1447-L1483
def revoke_auth(preserve_minion_cache=False): ''' The minion sends a request to the master to revoke its own key. Note that the minion session will be revoked and the minion may not be able to return the result of this command back to the master. If the 'preserve_minion_cache' flag is set to True, ...
[ "def", "revoke_auth", "(", "preserve_minion_cache", "=", "False", ")", ":", "masters", "=", "list", "(", ")", "ret", "=", "True", "if", "'master_uri_list'", "in", "__opts__", ":", "for", "master_uri", "in", "__opts__", "[", "'master_uri_list'", "]", ":", "ma...
The minion sends a request to the master to revoke its own key. Note that the minion session will be revoked and the minion may not be able to return the result of this command back to the master. If the 'preserve_minion_cache' flag is set to True, the master cache for this minion will not be removed. ...
[ "The", "minion", "sends", "a", "request", "to", "the", "master", "to", "revoke", "its", "own", "key", ".", "Note", "that", "the", "minion", "session", "will", "be", "revoked", "and", "the", "minion", "may", "not", "be", "able", "to", "return", "the", "...
python
train
31.108108
singularityhub/sregistry-cli
sregistry/auth/secrets.py
https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/auth/secrets.py#L77-L96
def read_client_secrets(): '''for private or protected registries, a client secrets file is required to be located at .sregistry. If no secrets are found, we use default of Singularity Hub, and return a dummy secrets. ''' client_secrets = _default_client_secrets() # If token file not prov...
[ "def", "read_client_secrets", "(", ")", ":", "client_secrets", "=", "_default_client_secrets", "(", ")", "# If token file not provided, check environment", "secrets", "=", "get_secrets_file", "(", ")", "# If exists, load", "if", "secrets", "is", "not", "None", ":", "cli...
for private or protected registries, a client secrets file is required to be located at .sregistry. If no secrets are found, we use default of Singularity Hub, and return a dummy secrets.
[ "for", "private", "or", "protected", "registries", "a", "client", "secrets", "file", "is", "required", "to", "be", "located", "at", ".", "sregistry", ".", "If", "no", "secrets", "are", "found", "we", "use", "default", "of", "Singularity", "Hub", "and", "re...
python
test
32.15
joke2k/faker
faker/providers/ssn/hr_HR/__init__.py
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/ssn/hr_HR/__init__.py#L7-L22
def checksum(digits): """ Calculate and return control digit for given list of digits based on ISO7064, MOD 11,10 standard. """ remainder = 10 for digit in digits: remainder = (remainder + digit) % 10 if remainder == 0: remainder = 10 remainder = (remainder * ...
[ "def", "checksum", "(", "digits", ")", ":", "remainder", "=", "10", "for", "digit", "in", "digits", ":", "remainder", "=", "(", "remainder", "+", "digit", ")", "%", "10", "if", "remainder", "==", "0", ":", "remainder", "=", "10", "remainder", "=", "(...
Calculate and return control digit for given list of digits based on ISO7064, MOD 11,10 standard.
[ "Calculate", "and", "return", "control", "digit", "for", "given", "list", "of", "digits", "based", "on", "ISO7064", "MOD", "11", "10", "standard", "." ]
python
train
26.6875
Netflix-Skunkworks/historical
historical/security_group/collector.py
https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/security_group/collector.py#L47-L92
def describe_group(record, region): """Attempts to describe group ids.""" account_id = record['account'] group_name = cloudwatch.filter_request_parameters('groupName', record) vpc_id = cloudwatch.filter_request_parameters('vpcId', record) group_id = cloudwatch.filter_request_parameters('groupId', r...
[ "def", "describe_group", "(", "record", ",", "region", ")", ":", "account_id", "=", "record", "[", "'account'", "]", "group_name", "=", "cloudwatch", ".", "filter_request_parameters", "(", "'groupName'", ",", "record", ")", "vpc_id", "=", "cloudwatch", ".", "f...
Attempts to describe group ids.
[ "Attempts", "to", "describe", "group", "ids", "." ]
python
train
38.347826
SpriteLink/NIPAP
nipap/nipap/xmlrpc.py
https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap/nipap/xmlrpc.py#L37-L53
def _mangle_prefix(res): """ Mangle prefix result """ # fugly cast from large numbers to string to deal with XML-RPC res['total_addresses'] = unicode(res['total_addresses']) res['used_addresses'] = unicode(res['used_addresses']) res['free_addresses'] = unicode(res['free_addresses']) # postg...
[ "def", "_mangle_prefix", "(", "res", ")", ":", "# fugly cast from large numbers to string to deal with XML-RPC", "res", "[", "'total_addresses'", "]", "=", "unicode", "(", "res", "[", "'total_addresses'", "]", ")", "res", "[", "'used_addresses'", "]", "=", "unicode", ...
Mangle prefix result
[ "Mangle", "prefix", "result" ]
python
train
39.705882
wharris/dougrain
dougrain/link.py
https://github.com/wharris/dougrain/blob/45062a1562fc34793e40c6253a93aa91eb4cf855/dougrain/link.py#L13-L24
def extract_variables(href): """Return a list of variable names used in a URI template.""" patterns = [re.sub(r'\*|:\d+', '', pattern) for pattern in re.findall(r'{[\+#\./;\?&]?([^}]+)*}', href)] variables = [] for pattern in patterns: for part in pattern.split(","): ...
[ "def", "extract_variables", "(", "href", ")", ":", "patterns", "=", "[", "re", ".", "sub", "(", "r'\\*|:\\d+'", ",", "''", ",", "pattern", ")", "for", "pattern", "in", "re", ".", "findall", "(", "r'{[\\+#\\./;\\?&]?([^}]+)*}'", ",", "href", ")", "]", "va...
Return a list of variable names used in a URI template.
[ "Return", "a", "list", "of", "variable", "names", "used", "in", "a", "URI", "template", "." ]
python
train
33
hollenstein/maspy
maspy/_proteindb_refactoring.py
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/_proteindb_refactoring.py#L104-L111
def _addProtein(self, proteinId, proteinName, sequence, fastaHeader, headerInfo, isDecoy=False, isContaminant=False): """#TODO""" proteinEntry = ProteinEntry( proteinId, proteinName, sequence, fastaHeader, headerInfo, isDecoy=isDecoy, isContaminant=isContamina...
[ "def", "_addProtein", "(", "self", ",", "proteinId", ",", "proteinName", ",", "sequence", ",", "fastaHeader", ",", "headerInfo", ",", "isDecoy", "=", "False", ",", "isContaminant", "=", "False", ")", ":", "proteinEntry", "=", "ProteinEntry", "(", "proteinId", ...
#TODO
[ "#TODO" ]
python
train
47.375
PythonSanSebastian/docstamp
docstamp/template.py
https://github.com/PythonSanSebastian/docstamp/blob/b43808f2e15351b0b2f0b7eade9c7ef319c9e646/docstamp/template.py#L272-L287
def render(self, file_path, **kwargs): """ Save the content of the .text file in the PDF. Parameters ---------- file_path: str Path to the output file. """ temp = get_tempfile(suffix='.tex') self.save_content(temp.name) try: self....
[ "def", "render", "(", "self", ",", "file_path", ",", "*", "*", "kwargs", ")", ":", "temp", "=", "get_tempfile", "(", "suffix", "=", "'.tex'", ")", "self", ".", "save_content", "(", "temp", ".", "name", ")", "try", ":", "self", ".", "_render_function", ...
Save the content of the .text file in the PDF. Parameters ---------- file_path: str Path to the output file.
[ "Save", "the", "content", "of", "the", ".", "text", "file", "in", "the", "PDF", "." ]
python
test
29.8125
limix/numpy-sugar
numpy_sugar/linalg/lu.py
https://github.com/limix/numpy-sugar/blob/4bdfa26913135c76ef3cd542a332f4e5861e948b/numpy_sugar/linalg/lu.py#L29-L52
def lu_solve(LU, b): r"""Solve for LU decomposition. Solve the linear equations :math:`\mathrm A \mathbf x = \mathbf b`, given the LU factorization of :math:`\mathrm A`. Args: LU (array_like): LU decomposition. b (array_like): Right-hand side. Returns: :class:`numpy.ndarra...
[ "def", "lu_solve", "(", "LU", ",", "b", ")", ":", "from", "scipy", ".", "linalg", "import", "lu_solve", "as", "sp_lu_solve", "LU", "=", "(", "asarray", "(", "LU", "[", "0", "]", ",", "float", ")", ",", "asarray", "(", "LU", "[", "1", "]", ",", ...
r"""Solve for LU decomposition. Solve the linear equations :math:`\mathrm A \mathbf x = \mathbf b`, given the LU factorization of :math:`\mathrm A`. Args: LU (array_like): LU decomposition. b (array_like): Right-hand side. Returns: :class:`numpy.ndarray`: The solution to the s...
[ "r", "Solve", "for", "LU", "decomposition", "." ]
python
train
29.958333
SoCo/SoCo
dev_tools/analyse_ws.py
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L86-L125
def set_file(self, filename): """ Analyse the file with the captured content """ # Use the file name as prefix if none is given if self.output_prefix is None: _, self.output_prefix = os.path.split(filename) # Check if the file is present, since rdpcap will not do that ...
[ "def", "set_file", "(", "self", ",", "filename", ")", ":", "# Use the file name as prefix if none is given", "if", "self", ".", "output_prefix", "is", "None", ":", "_", ",", "self", ".", "output_prefix", "=", "os", ".", "path", ".", "split", "(", "filename", ...
Analyse the file with the captured content
[ "Analyse", "the", "file", "with", "the", "captured", "content" ]
python
train
44.525
markovmodel/msmtools
msmtools/analysis/dense/expectations.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/analysis/dense/expectations.py#L200-L247
def ec_geometric_series(p0, T, n): r"""Compute expected transition counts for Markov chain after n steps. Expected counts are computed according to ..math:: E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^t T^{k})_{i} p_{ij} The sum is computed using the eigenvalue decomposition of T and applying the e...
[ "def", "ec_geometric_series", "(", "p0", ",", "T", ",", "n", ")", ":", "if", "(", "n", "<=", "0", ")", ":", "EC", "=", "np", ".", "zeros", "(", "T", ".", "shape", ")", "return", "EC", "else", ":", "R", ",", "D", ",", "L", "=", "rdl_decomposit...
r"""Compute expected transition counts for Markov chain after n steps. Expected counts are computed according to ..math:: E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^t T^{k})_{i} p_{ij} The sum is computed using the eigenvalue decomposition of T and applying the expression for a finite geometric series...
[ "r", "Compute", "expected", "transition", "counts", "for", "Markov", "chain", "after", "n", "steps", "." ]
python
train
30.645833
mdickinson/bigfloat
bigfloat/core.py
https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L1857-L1867
def csch(x, context=None): """ Return the hyperbolic cosecant of x. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_csch, (BigFloat._implicit_convert(x),), context, )
[ "def", "csch", "(", "x", ",", "context", "=", "None", ")", ":", "return", "_apply_function_in_current_context", "(", "BigFloat", ",", "mpfr", ".", "mpfr_csch", ",", "(", "BigFloat", ".", "_implicit_convert", "(", "x", ")", ",", ")", ",", "context", ",", ...
Return the hyperbolic cosecant of x.
[ "Return", "the", "hyperbolic", "cosecant", "of", "x", "." ]
python
train
20.727273
dmlc/gluon-nlp
src/gluonnlp/embedding/token_embedding.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/embedding/token_embedding.py#L69-L97
def create(embedding_name, **kwargs): """Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `source`, use :fun...
[ "def", "create", "(", "embedding_name", ",", "*", "*", "kwargs", ")", ":", "create_text_embedding", "=", "registry", ".", "get_create_func", "(", "TokenEmbedding", ",", "'token embedding'", ")", "return", "create_text_embedding", "(", "embedding_name", ",", "*", "...
Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `source`, use :func:`gluonnlp.embedding.list_sources`. Pa...
[ "Creates", "an", "instance", "of", "token", "embedding", "." ]
python
train
37.965517
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L954-L965
def has_bounds(self): """return True, if any variable is bounded""" bounds = self.bounds if bounds in (None, [None, None]): return False for ib, bound in enumerate(bounds): if bound is not None: sign_ = 2 * ib - 1 for bound_i in bou...
[ "def", "has_bounds", "(", "self", ")", ":", "bounds", "=", "self", ".", "bounds", "if", "bounds", "in", "(", "None", ",", "[", "None", ",", "None", "]", ")", ":", "return", "False", "for", "ib", ",", "bound", "in", "enumerate", "(", "bounds", ")", ...
return True, if any variable is bounded
[ "return", "True", "if", "any", "variable", "is", "bounded" ]
python
train
36.833333
ValvePython/steam
steam/util/binary.py
https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/util/binary.py#L27-L36
def read(self, n=1): """Return n bytes :param n: number of bytes to return :type n: :class:`int` :return: bytes :rtype: :class:`bytes` """ self.offset += n return self.data[self.offset - n:self.offset]
[ "def", "read", "(", "self", ",", "n", "=", "1", ")", ":", "self", ".", "offset", "+=", "n", "return", "self", ".", "data", "[", "self", ".", "offset", "-", "n", ":", "self", ".", "offset", "]" ]
Return n bytes :param n: number of bytes to return :type n: :class:`int` :return: bytes :rtype: :class:`bytes`
[ "Return", "n", "bytes" ]
python
train
25.8
pyparsing/pyparsing
examples/sparser.py
https://github.com/pyparsing/pyparsing/blob/f0264bd8d1a548a50b3e5f7d99cfefd577942d14/examples/sparser.py#L77-L81
def debug(ftn, txt): """Used for debugging.""" if debug_p: sys.stdout.write("{0}.{1}:{2}\n".format(modname, ftn, txt)) sys.stdout.flush()
[ "def", "debug", "(", "ftn", ",", "txt", ")", ":", "if", "debug_p", ":", "sys", ".", "stdout", ".", "write", "(", "\"{0}.{1}:{2}\\n\"", ".", "format", "(", "modname", ",", "ftn", ",", "txt", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Used for debugging.
[ "Used", "for", "debugging", "." ]
python
train
32.2
bokeh/bokeh
bokeh/core/property/descriptors.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L842-L875
def _notify_mutated(self, obj, old, hint=None): ''' A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (object) : ...
[ "def", "_notify_mutated", "(", "self", ",", "obj", ",", "old", ",", "hint", "=", "None", ")", ":", "value", "=", "self", ".", "__get__", "(", "obj", ",", "obj", ".", "__class__", ")", "# re-validate because the contents of 'old' have changed,", "# in some cases ...
A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (object) : The "old" value of the container ...
[ "A", "method", "to", "call", "when", "a", "container", "is", "mutated", "behind", "our", "back", "and", "we", "detect", "it", "with", "our", "|PropertyContainer|", "wrappers", "." ]
python
train
36.558824
vtkiorg/vtki
vtki/grid.py
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L108-L133
def _from_arrays(self, x, y, z): """ Create VTK rectilinear grid directly from numpy arrays. Each array gives the uniques coordinates of the mesh along each axial direction. To help ensure you are using this correctly, we take the unique values of each argument. Paramete...
[ "def", "_from_arrays", "(", "self", ",", "x", ",", "y", ",", "z", ")", ":", "x", "=", "np", ".", "unique", "(", "x", ".", "ravel", "(", ")", ")", "y", "=", "np", ".", "unique", "(", "y", ".", "ravel", "(", ")", ")", "z", "=", "np", ".", ...
Create VTK rectilinear grid directly from numpy arrays. Each array gives the uniques coordinates of the mesh along each axial direction. To help ensure you are using this correctly, we take the unique values of each argument. Parameters ---------- x : np.ndarray ...
[ "Create", "VTK", "rectilinear", "grid", "directly", "from", "numpy", "arrays", ".", "Each", "array", "gives", "the", "uniques", "coordinates", "of", "the", "mesh", "along", "each", "axial", "direction", ".", "To", "help", "ensure", "you", "are", "using", "th...
python
train
34.807692
wesm/feather
cpp/build-support/cpplint.py
https://github.com/wesm/feather/blob/99267b30461c46b9e437f95e1d9338a92a854270/cpp/build-support/cpplint.py#L3890-L4003
def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any er...
[ "def", "CheckBraces", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# get rid of comments and strings", "if", "Match", "(", "r'\\s*{\\s*$'", ",", "line", ")", ":", ...
Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
[ "Looks", "for", "misplaced", "braces", "(", "e", ".", "g", ".", "at", "the", "end", "of", "line", ")", "." ]
python
train
52.833333
weld-project/weld
python/pyweld/weld/types.py
https://github.com/weld-project/weld/blob/8ddd6db6b28878bef0892da44b1d2002b564389c/python/pyweld/weld/types.py#L242-L268
def ctype_class(self): """Summary Returns: TYPE: Description """ def vec_factory(elemType): """Summary Args: elemType (TYPE): Description Returns: TYPE: Description """ class Vec(St...
[ "def", "ctype_class", "(", "self", ")", ":", "def", "vec_factory", "(", "elemType", ")", ":", "\"\"\"Summary\n\n Args:\n elemType (TYPE): Description\n\n Returns:\n TYPE: Description\n \"\"\"", "class", "Vec", "(", "Struc...
Summary Returns: TYPE: Description
[ "Summary" ]
python
train
25.851852
prthkms/alex
alex/preprocess.py
https://github.com/prthkms/alex/blob/79d3167c877e94cc07db0aab55a35857fac67ef7/alex/preprocess.py#L125-L136
def process_corpus(self): """Q.process_corpus() -- processes the queries defined by us, by tokenizing, stemming, and removing stop words. """ for doc in self.corpus_list: doc = wt(doc) sentence = [] for word in doc: if word not in self.stop_words and word not in self.punctuation: word = self....
[ "def", "process_corpus", "(", "self", ")", ":", "for", "doc", "in", "self", ".", "corpus_list", ":", "doc", "=", "wt", "(", "doc", ")", "sentence", "=", "[", "]", "for", "word", "in", "doc", ":", "if", "word", "not", "in", "self", ".", "stop_words"...
Q.process_corpus() -- processes the queries defined by us, by tokenizing, stemming, and removing stop words.
[ "Q", ".", "process_corpus", "()", "--", "processes", "the", "queries", "defined", "by", "us", "by", "tokenizing", "stemming", "and", "removing", "stop", "words", "." ]
python
train
33
apache/incubator-heron
heron/tools/tracker/src/python/tracker.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/tracker/src/python/tracker.py#L647-L670
def getTopologyInfo(self, topologyName, cluster, role, environ): """ Returns the JSON representation of a topology by its name, cluster, environ, and an optional role parameter. Raises exception if no such topology is found. """ # Iterate over the values to filter the desired topology. for (...
[ "def", "getTopologyInfo", "(", "self", ",", "topologyName", ",", "cluster", ",", "role", ",", "environ", ")", ":", "# Iterate over the values to filter the desired topology.", "for", "(", "topology_name", ",", "_", ")", ",", "topologyInfo", "in", "self", ".", "top...
Returns the JSON representation of a topology by its name, cluster, environ, and an optional role parameter. Raises exception if no such topology is found.
[ "Returns", "the", "JSON", "representation", "of", "a", "topology", "by", "its", "name", "cluster", "environ", "and", "an", "optional", "role", "parameter", ".", "Raises", "exception", "if", "no", "such", "topology", "is", "found", "." ]
python
valid
49.5
sibirrer/lenstronomy
lenstronomy/Workflow/update_manager.py
https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Workflow/update_manager.py#L136-L171
def update_fixed(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo, lens_add_fixed=[], source_add_fixed=[], lens_light_add_fixed=[], ps_add_fixed=[], cosmo_add_fixed=[], lens_remove_fixed=[], source_remove_fixed=[], lens_light_remove_fixed=[], ps_remo...
[ "def", "update_fixed", "(", "self", ",", "kwargs_lens", ",", "kwargs_source", ",", "kwargs_lens_light", ",", "kwargs_ps", ",", "kwargs_cosmo", ",", "lens_add_fixed", "=", "[", "]", ",", "source_add_fixed", "=", "[", "]", ",", "lens_light_add_fixed", "=", "[", ...
adds the values of the keyword arguments that are stated in the _add_fixed to the existing fixed arguments. :param kwargs_lens: :param kwargs_source: :param kwargs_lens_light: :param kwargs_ps: :param kwargs_cosmo: :param lens_add_fixed: :param source_add_fixed: ...
[ "adds", "the", "values", "of", "the", "keyword", "arguments", "that", "are", "stated", "in", "the", "_add_fixed", "to", "the", "existing", "fixed", "arguments", "." ]
python
train
56.361111
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/fixer_util.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L61-L66
def Call(func_name, args=None, prefix=None): """A function call""" node = Node(syms.power, [func_name, ArgList(args)]) if prefix is not None: node.prefix = prefix return node
[ "def", "Call", "(", "func_name", ",", "args", "=", "None", ",", "prefix", "=", "None", ")", ":", "node", "=", "Node", "(", "syms", ".", "power", ",", "[", "func_name", ",", "ArgList", "(", "args", ")", "]", ")", "if", "prefix", "is", "not", "None...
A function call
[ "A", "function", "call" ]
python
train
32.166667
StackStorm/pybind
pybind/slxos/v17r_2_00/ntp/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_2_00/ntp/__init__.py#L168-L189
def _set_peer(self, v, load=False): """ Setter method for peer, mapped from YANG variable /ntp/peer (list) If this variable is read-only (config: false) in the source YANG file, then _set_peer is considered as a private method. Backends looking to populate this variable should do so via calling ...
[ "def", "_set_peer", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
Setter method for peer, mapped from YANG variable /ntp/peer (list) If this variable is read-only (config: false) in the source YANG file, then _set_peer is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_peer() directly.
[ "Setter", "method", "for", "peer", "mapped", "from", "YANG", "variable", "/", "ntp", "/", "peer", "(", "list", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", "file", "then", ...
python
train
133.136364
saltstack/salt
salt/sdb/rest.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/rest.py#L83-L87
def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the REST interface ''' return query(key, value, service, profile)
[ "def", "set_", "(", "key", ",", "value", ",", "service", "=", "None", ",", "profile", "=", "None", ")", ":", "# pylint: disable=W0613", "return", "query", "(", "key", ",", "value", ",", "service", ",", "profile", ")" ]
Set a key/value pair in the REST interface
[ "Set", "a", "key", "/", "value", "pair", "in", "the", "REST", "interface" ]
python
train
36
aetros/aetros-cli
aetros/starter.py
https://github.com/aetros/aetros-cli/blob/a2a1f38d6af1660e1e2680c7d413ec2aef45faab/aetros/starter.py#L27-L61
def start(logger, full_id, fetch=True, env=None, volumes=None, cpus=None, memory=None, gpu_devices=None, offline=False): """ Starts the job with all logging of a job_id """ owner, name, id = unpack_full_job_id(full_id) if isinstance(sys.stdout, GeneralLogger): # we don't want to have stuff...
[ "def", "start", "(", "logger", ",", "full_id", ",", "fetch", "=", "True", ",", "env", "=", "None", ",", "volumes", "=", "None", ",", "cpus", "=", "None", ",", "memory", "=", "None", ",", "gpu_devices", "=", "None", ",", "offline", "=", "False", ")"...
Starts the job with all logging of a job_id
[ "Starts", "the", "job", "with", "all", "logging", "of", "a", "job_id" ]
python
train
31.542857
ianlini/flatten-dict
flatten_dict/flatten_dict.py
https://github.com/ianlini/flatten-dict/blob/77a2bf669ea6dc7446b8ad1596dc2a41d4c5a7fa/flatten_dict/flatten_dict.py#L79-L108
def unflatten(d, splitter='tuple', inverse=False): """Unflatten dict-like object. Parameters ---------- d: dict-like object The dict that will be unflattened. splitter: {'tuple', 'path', function} (default: 'tuple') The key splitting method. If a function is given, the function will...
[ "def", "unflatten", "(", "d", ",", "splitter", "=", "'tuple'", ",", "inverse", "=", "False", ")", ":", "if", "isinstance", "(", "splitter", ",", "str", ")", ":", "splitter", "=", "SPLITTER_DICT", "[", "splitter", "]", "unflattened_dict", "=", "{", "}", ...
Unflatten dict-like object. Parameters ---------- d: dict-like object The dict that will be unflattened. splitter: {'tuple', 'path', function} (default: 'tuple') The key splitting method. If a function is given, the function will be used to split. 'tuple': Use each eleme...
[ "Unflatten", "dict", "-", "like", "object", "." ]
python
train
32.4
Stewori/pytypes
pytypes/type_util.py
https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L664-L777
def type_str(tp, assumed_globals=None, update_assumed_globals=None, implicit_globals=None, bound_Generic=None, bound_typevars=None): """Generates a nicely readable string representation of the given type. The returned representation is workable as a source code string and would reconstruct the g...
[ "def", "type_str", "(", "tp", ",", "assumed_globals", "=", "None", ",", "update_assumed_globals", "=", "None", ",", "implicit_globals", "=", "None", ",", "bound_Generic", "=", "None", ",", "bound_typevars", "=", "None", ")", ":", "if", "assumed_globals", "is",...
Generates a nicely readable string representation of the given type. The returned representation is workable as a source code string and would reconstruct the given type if handed to eval, provided that globals/locals are configured appropriately (e.g. assumes that various types from typing have been im...
[ "Generates", "a", "nicely", "readable", "string", "representation", "of", "the", "given", "type", ".", "The", "returned", "representation", "is", "workable", "as", "a", "source", "code", "string", "and", "would", "reconstruct", "the", "given", "type", "if", "h...
python
train
48.991228
bcbio/bcbio-nextgen
bcbio/broad/metrics.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/broad/metrics.py#L440-L465
def bed_to_interval(orig_bed, bam_file): """Add header and format BED bait and target files for Picard if necessary. """ with open(orig_bed) as in_handle: line = in_handle.readline() if line.startswith("@"): yield orig_bed else: with pysam.Samfile(bam_file, "rb") as bam_handl...
[ "def", "bed_to_interval", "(", "orig_bed", ",", "bam_file", ")", ":", "with", "open", "(", "orig_bed", ")", "as", "in_handle", ":", "line", "=", "in_handle", ".", "readline", "(", ")", "if", "line", ".", "startswith", "(", "\"@\"", ")", ":", "yield", "...
Add header and format BED bait and target files for Picard if necessary.
[ "Add", "header", "and", "format", "BED", "bait", "and", "target", "files", "for", "Picard", "if", "necessary", "." ]
python
train
44.769231
aewallin/allantools
allantools/ci.py
https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/ci.py#L434-L575
def edf_greenhall(alpha, d, m, N, overlapping=False, modified=False, verbose=False): """ returns Equivalent degrees of freedom Parameters ---------- alpha: int noise type, +2...-4 d: int 1 first-difference variance 2 Allan variance ...
[ "def", "edf_greenhall", "(", "alpha", ",", "d", ",", "m", ",", "N", ",", "overlapping", "=", "False", ",", "modified", "=", "False", ",", "verbose", "=", "False", ")", ":", "if", "modified", ":", "F", "=", "1", "# F filter factor, 1 modified variance, m un...
returns Equivalent degrees of freedom Parameters ---------- alpha: int noise type, +2...-4 d: int 1 first-difference variance 2 Allan variance 3 Hadamard variance require alpha+2*d>1 m: int averaging...
[ "returns", "Equivalent", "degrees", "of", "freedom", "Parameters", "----------", "alpha", ":", "int", "noise", "type", "+", "2", "...", "-", "4", "d", ":", "int", "1", "first", "-", "difference", "variance", "2", "Allan", "variance", "3", "Hadamard", "vari...
python
train
36.774648
MDAnalysis/GridDataFormats
gridData/core.py
https://github.com/MDAnalysis/GridDataFormats/blob/3eeb0432f8cf856912436e4f3e7aba99d3c916be/gridData/core.py#L694-L726
def ndmeshgrid(*arrs): """Return a mesh grid for N dimensions. The input are N arrays, each of which contains the values along one axis of the coordinate system. The arrays do not have to have the same number of entries. The function returns arrays that can be fed into numpy functions so that they ...
[ "def", "ndmeshgrid", "(", "*", "arrs", ")", ":", "#arrs = tuple(reversed(arrs)) <-- wrong on stackoverflow.com", "arrs", "=", "tuple", "(", "arrs", ")", "lens", "=", "list", "(", "map", "(", "len", ",", "arrs", ")", ")", "dim", "=", "len", "(", "arrs", ")"...
Return a mesh grid for N dimensions. The input are N arrays, each of which contains the values along one axis of the coordinate system. The arrays do not have to have the same number of entries. The function returns arrays that can be fed into numpy functions so that they produce values for *all* point...
[ "Return", "a", "mesh", "grid", "for", "N", "dimensions", "." ]
python
valid
30.333333
IdentityPython/pysaml2
src/saml2/attribute_converter.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/attribute_converter.py#L176-L187
def to_local_name(acs, attr): """ :param acs: List of AttributeConverter instances :param attr: an Attribute instance :return: The local attribute name """ for aconv in acs: lattr = aconv.from_format(attr) if lattr: return lattr return attr.friendly_name
[ "def", "to_local_name", "(", "acs", ",", "attr", ")", ":", "for", "aconv", "in", "acs", ":", "lattr", "=", "aconv", ".", "from_format", "(", "attr", ")", "if", "lattr", ":", "return", "lattr", "return", "attr", ".", "friendly_name" ]
:param acs: List of AttributeConverter instances :param attr: an Attribute instance :return: The local attribute name
[ ":", "param", "acs", ":", "List", "of", "AttributeConverter", "instances", ":", "param", "attr", ":", "an", "Attribute", "instance", ":", "return", ":", "The", "local", "attribute", "name" ]
python
train
25
mfcloud/python-zvm-sdk
zvmsdk/api.py
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/api.py#L1448-L1457
def vswitch_query(self, vswitch_name): """Check the virtual switch status :param str vswitch_name: the name of the virtual switch :returns: Dictionary describing virtual switch info :rtype: dict """ action = "get virtual switch information" with zvmutils.log_and_...
[ "def", "vswitch_query", "(", "self", ",", "vswitch_name", ")", ":", "action", "=", "\"get virtual switch information\"", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "return", "self", ".", "_networkops", ".", "vswitch_query", "(...
Check the virtual switch status :param str vswitch_name: the name of the virtual switch :returns: Dictionary describing virtual switch info :rtype: dict
[ "Check", "the", "virtual", "switch", "status" ]
python
train
40.5
gwww/elkm1
elkm1_lib/zones.py
https://github.com/gwww/elkm1/blob/078d0de30840c3fab46f1f8534d98df557931e91/elkm1_lib/zones.py#L50-L56
def sync(self): """Retrieve zones from ElkM1""" self.elk.send(az_encode()) self.elk.send(zd_encode()) self.elk.send(zp_encode()) self.elk.send(zs_encode()) self.get_descriptions(TextDescriptions.ZONE.value)
[ "def", "sync", "(", "self", ")", ":", "self", ".", "elk", ".", "send", "(", "az_encode", "(", ")", ")", "self", ".", "elk", ".", "send", "(", "zd_encode", "(", ")", ")", "self", ".", "elk", ".", "send", "(", "zp_encode", "(", ")", ")", "self", ...
Retrieve zones from ElkM1
[ "Retrieve", "zones", "from", "ElkM1" ]
python
train
35.428571
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/rst/rs3/rs3tree.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/rst/rs3/rs3tree.py#L394-L405
def elem_wrap(self, tree, debug=False, root_id=None): """takes a DGParentedTree and puts a nucleus or satellite on top, depending on the nuclearity of the root element of the tree. """ if root_id is None: root_id = tree.root_id elem = self.elem_dict[root_id] ...
[ "def", "elem_wrap", "(", "self", ",", "tree", ",", "debug", "=", "False", ",", "root_id", "=", "None", ")", ":", "if", "root_id", "is", "None", ":", "root_id", "=", "tree", ".", "root_id", "elem", "=", "self", ".", "elem_dict", "[", "root_id", "]", ...
takes a DGParentedTree and puts a nucleus or satellite on top, depending on the nuclearity of the root element of the tree.
[ "takes", "a", "DGParentedTree", "and", "puts", "a", "nucleus", "or", "satellite", "on", "top", "depending", "on", "the", "nuclearity", "of", "the", "root", "element", "of", "the", "tree", "." ]
python
train
40.166667
saltstack/salt
salt/modules/poudriere.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/poudriere.py#L175-L204
def create_jail(name, arch, version="9.0-RELEASE"): ''' Creates a new poudriere jail if one does not exist *NOTE* creating a new jail will take some time the master is not hanging CLI Example: .. code-block:: bash salt '*' poudriere.create_jail 90amd64 amd64 ''' # Config file mus...
[ "def", "create_jail", "(", "name", ",", "arch", ",", "version", "=", "\"9.0-RELEASE\"", ")", ":", "# Config file must be on system to create a poudriere jail", "_check_config_exists", "(", ")", "# Check if the jail is there", "if", "is_jail", "(", "name", ")", ":", "ret...
Creates a new poudriere jail if one does not exist *NOTE* creating a new jail will take some time the master is not hanging CLI Example: .. code-block:: bash salt '*' poudriere.create_jail 90amd64 amd64
[ "Creates", "a", "new", "poudriere", "jail", "if", "one", "does", "not", "exist" ]
python
train
26.266667
pypa/pipenv
pipenv/vendor/attr/filters.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/filters.py#L11-L18
def _split_what(what): """ Returns a tuple of `frozenset`s of classes and attributes. """ return ( frozenset(cls for cls in what if isclass(cls)), frozenset(cls for cls in what if isinstance(cls, Attribute)), )
[ "def", "_split_what", "(", "what", ")", ":", "return", "(", "frozenset", "(", "cls", "for", "cls", "in", "what", "if", "isclass", "(", "cls", ")", ")", ",", "frozenset", "(", "cls", "for", "cls", "in", "what", "if", "isinstance", "(", "cls", ",", "...
Returns a tuple of `frozenset`s of classes and attributes.
[ "Returns", "a", "tuple", "of", "frozenset", "s", "of", "classes", "and", "attributes", "." ]
python
train
29.875
ColtonProvias/sqlalchemy-jsonapi
sqlalchemy_jsonapi/serializer.py
https://github.com/ColtonProvias/sqlalchemy-jsonapi/blob/40f8b5970d44935b27091c2bf3224482d23311bb/sqlalchemy_jsonapi/serializer.py#L882-L960
def patch_resource(self, session, json_data, api_type, obj_id): """ Replacement of resource values. :param session: SQLAlchemy session :param json_data: Request JSON Data :param api_type: Type of the resource :param obj_id: ID of the resource """ model = ...
[ "def", "patch_resource", "(", "self", ",", "session", ",", "json_data", ",", "api_type", ",", "obj_id", ")", ":", "model", "=", "self", ".", "_fetch_model", "(", "api_type", ")", "resource", "=", "self", ".", "_fetch_resource", "(", "session", ",", "api_ty...
Replacement of resource values. :param session: SQLAlchemy session :param json_data: Request JSON Data :param api_type: Type of the resource :param obj_id: ID of the resource
[ "Replacement", "of", "resource", "values", "." ]
python
train
40.253165
pyschool/story
story/translation.py
https://github.com/pyschool/story/blob/c23daf4a187b0df4cbae88ef06b36c396f1ffd57/story/translation.py#L134-L144
def gettext(message): """ Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default _default = _default or translation(DEFAULT_L...
[ "def", "gettext", "(", "message", ")", ":", "global", "_default", "_default", "=", "_default", "or", "translation", "(", "DEFAULT_LANGUAGE", ")", "translation_object", "=", "getattr", "(", "_active", ",", "'value'", ",", "_default", ")", "result", "=", "transl...
Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object.
[ "Translate", "the", "message", "string", ".", "It", "uses", "the", "current", "thread", "to", "find", "the", "translation", "object", "to", "use", ".", "If", "no", "current", "translation", "is", "activated", "the", "message", "will", "be", "run", "through",...
python
train
40.545455
ZeitOnline/briefkasten
deployment/appserver.py
https://github.com/ZeitOnline/briefkasten/blob/ce6b6eeb89196014fe21d68614c20059d02daa11/deployment/appserver.py#L42-L57
def upload_pgp_keys(): """ upload and/or update the PGP keys for editors, import them into PGP""" get_vars() upload_target = '/tmp/pgp_pubkeys.tmp' with fab.settings(fab.hide('running')): fab.run('rm -rf %s' % upload_target) fab.run('mkdir %s' % upload_target) local_key_path = pa...
[ "def", "upload_pgp_keys", "(", ")", ":", "get_vars", "(", ")", "upload_target", "=", "'/tmp/pgp_pubkeys.tmp'", "with", "fab", ".", "settings", "(", "fab", ".", "hide", "(", "'running'", ")", ")", ":", "fab", ".", "run", "(", "'rm -rf %s'", "%", "upload_tar...
upload and/or update the PGP keys for editors, import them into PGP
[ "upload", "and", "/", "or", "update", "the", "PGP", "keys", "for", "editors", "import", "them", "into", "PGP" ]
python
valid
54.0625
SuperCowPowers/workbench
workbench_apps/workbench_cli/workbench_shell.py
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/workbench_shell.py#L203-L216
def top_corr(self, df): """Give aggregation counts and correlations""" tag_freq = df.sum() tag_freq.sort(ascending=False) corr = df.corr().fillna(1) corr_dict = corr.to_dict() for tag, count in tag_freq.iteritems(): print ' %s%s: %s%s%s (' % (color.Green, t...
[ "def", "top_corr", "(", "self", ",", "df", ")", ":", "tag_freq", "=", "df", ".", "sum", "(", ")", "tag_freq", ".", "sort", "(", "ascending", "=", "False", ")", "corr", "=", "df", ".", "corr", "(", ")", ".", "fillna", "(", "1", ")", "corr_dict", ...
Give aggregation counts and correlations
[ "Give", "aggregation", "counts", "and", "correlations" ]
python
train
48.785714
aleju/imgaug
imgaug/augmenters/arithmetic.py
https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmenters/arithmetic.py#L1780-L1890
def CoarsePepper(p=0, size_px=None, size_percent=None, per_channel=False, min_size=4, name=None, deterministic=False, random_state=None): """ Adds coarse pepper noise to an image, i.e. rectangles that contain noisy black-ish pixels. dtype support:: See ``imgaug.augmenters.arithmet...
[ "def", "CoarsePepper", "(", "p", "=", "0", ",", "size_px", "=", "None", ",", "size_percent", "=", "None", ",", "per_channel", "=", "False", ",", "min_size", "=", "4", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=...
Adds coarse pepper noise to an image, i.e. rectangles that contain noisy black-ish pixels. dtype support:: See ``imgaug.augmenters.arithmetic.ReplaceElementwise``. Parameters ---------- p : float or tuple of float or list of float or imgaug.parameters.StochasticParameter, optional Pro...
[ "Adds", "coarse", "pepper", "noise", "to", "an", "image", "i", ".", "e", ".", "rectangles", "that", "contain", "noisy", "black", "-", "ish", "pixels", "." ]
python
valid
44.648649
softlayer/softlayer-python
SoftLayer/CLI/order/quote_list.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/quote_list.py#L13-L36
def cli(env): """List all active quotes on an account""" table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id' ]) table.align['Name'] = 'l' table.align['Package Name'] = 'r' table.align['Package Id'] = 'l' manager = ordering.Orderin...
[ "def", "cli", "(", "env", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Id'", ",", "'Name'", ",", "'Created'", ",", "'Expiration'", ",", "'Status'", ",", "'Package Name'", ",", "'Package Id'", "]", ")", "table", ".", "align", "[", "'N...
List all active quotes on an account
[ "List", "all", "active", "quotes", "on", "an", "account" ]
python
train
30.666667
log2timeline/dfvfs
dfvfs/lib/sqlite_database.py
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/lib/sqlite_database.py#L95-L134
def HasColumn(self, table_name, column_name): """Determines if a specific column exists. Args: table_name (str): name of the table. column_name (str): name of the column. Returns: bool: True if the column exists. Raises: IOError: if the database file is not opened. OSErr...
[ "def", "HasColumn", "(", "self", ",", "table_name", ",", "column_name", ")", ":", "if", "not", "self", ".", "_connection", ":", "raise", "IOError", "(", "'Not opened.'", ")", "if", "not", "column_name", ":", "return", "False", "table_name", "=", "table_name"...
Determines if a specific column exists. Args: table_name (str): name of the table. column_name (str): name of the column. Returns: bool: True if the column exists. Raises: IOError: if the database file is not opened. OSError: if the database file is not opened.
[ "Determines", "if", "a", "specific", "column", "exists", "." ]
python
train
27.175
Kortemme-Lab/klab
klab/bio/uniprot.py
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/uniprot.py#L542-L560
def _parse_sequence_tag(self): '''Parses the sequence and atomic mass.''' #main_tags = self._dom.getElementsByTagName("uniprot") #assert(len(main_tags) == 1) #entry_tags = main_tags[0].getElementsByTagName("entry") #assert(len(entry_tags) == 1) #entry_tags[0] ent...
[ "def", "_parse_sequence_tag", "(", "self", ")", ":", "#main_tags = self._dom.getElementsByTagName(\"uniprot\")", "#assert(len(main_tags) == 1)", "#entry_tags = main_tags[0].getElementsByTagName(\"entry\")", "#assert(len(entry_tags) == 1)", "#entry_tags[0]", "entry_tag", "=", "self", ".",...
Parses the sequence and atomic mass.
[ "Parses", "the", "sequence", "and", "atomic", "mass", "." ]
python
train
53.684211
RudolfCardinal/pythonlib
cardinal_pythonlib/file_io.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/file_io.py#L174-L188
def gen_lines_from_textfiles( files: Iterable[TextIO]) -> Generator[str, None, None]: """ Generates lines from file-like objects. Args: files: iterable of :class:`TextIO` objects Yields: each line of all the files """ for file in files: for line in file: ...
[ "def", "gen_lines_from_textfiles", "(", "files", ":", "Iterable", "[", "TextIO", "]", ")", "->", "Generator", "[", "str", ",", "None", ",", "None", "]", ":", "for", "file", "in", "files", ":", "for", "line", "in", "file", ":", "yield", "line" ]
Generates lines from file-like objects. Args: files: iterable of :class:`TextIO` objects Yields: each line of all the files
[ "Generates", "lines", "from", "file", "-", "like", "objects", "." ]
python
train
21.466667
kalefranz/auxlib
auxlib/_vendor/boltons/timeutils.py
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L30-L46
def total_seconds(td): """For those with older versions of Python, a pure-Python implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`. Args: td (datetime.timedelta): The timedelta to convert to seconds. Returns: float: total number of seconds >>> td = timedelta(...
[ "def", "total_seconds", "(", "td", ")", ":", "a_milli", "=", "1000000.0", "td_ds", "=", "td", ".", "seconds", "+", "(", "td", ".", "days", "*", "86400", ")", "# 24 * 60 * 60", "td_micro", "=", "td", ".", "microseconds", "+", "(", "td_ds", "*", "a_milli...
For those with older versions of Python, a pure-Python implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`. Args: td (datetime.timedelta): The timedelta to convert to seconds. Returns: float: total number of seconds >>> td = timedelta(days=4, seconds=33) >>> to...
[ "For", "those", "with", "older", "versions", "of", "Python", "a", "pure", "-", "Python", "implementation", "of", "Python", "2", ".", "7", "s", ":", "meth", ":", "~datetime", ".", "timedelta", ".", "total_seconds", "." ]
python
train
31.411765
gem/oq-engine
openquake/server/views.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/views.py#L426-L434
def calc_log_size(request, calc_id): """ Get the current number of lines in the log """ try: response_data = logs.dbcmd('get_log_size', calc_id) except dbapi.NotFound: return HttpResponseNotFound() return HttpResponse(content=json.dumps(response_data), content_type=JSON)
[ "def", "calc_log_size", "(", "request", ",", "calc_id", ")", ":", "try", ":", "response_data", "=", "logs", ".", "dbcmd", "(", "'get_log_size'", ",", "calc_id", ")", "except", "dbapi", ".", "NotFound", ":", "return", "HttpResponseNotFound", "(", ")", "return...
Get the current number of lines in the log
[ "Get", "the", "current", "number", "of", "lines", "in", "the", "log" ]
python
train
33.666667
isislovecruft/python-gnupg
pretty_bad_protocol/_parsers.py
https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_parsers.py#L1061-L1096
def _handle_status(self, key, value): """Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown. """ if key in ( "USERID_HINT", "NEED_PASSPHRASE", "BAD_PASSPHRASE", ...
[ "def", "_handle_status", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "in", "(", "\"USERID_HINT\"", ",", "\"NEED_PASSPHRASE\"", ",", "\"BAD_PASSPHRASE\"", ",", "\"GOOD_PASSPHRASE\"", ",", "\"MISSING_PASSPHRASE\"", ",", "\"PINENTRY_LAUNCHED\"", ",", ...
Parse a status code from the attached GnuPG process. :raises: :exc:`~exceptions.ValueError` if the status message is unknown.
[ "Parse", "a", "status", "code", "from", "the", "attached", "GnuPG", "process", "." ]
python
train
40.277778
arindampradhan/yaaHN
yaaHN/helpers.py
https://github.com/arindampradhan/yaaHN/blob/680e9fed49ef6b325ed7ca1b325aaae12290f314/yaaHN/helpers.py#L92-L110
def poll_parser(poll): """ Parses a poll object """ if __is_deleted(poll): return deleted_parser(poll) if poll['type'] not in poll_types: raise Exception('Not a poll type') return Poll( poll['id'], poll['by'], __check_key('kids', poll), # poll and pollopt...
[ "def", "poll_parser", "(", "poll", ")", ":", "if", "__is_deleted", "(", "poll", ")", ":", "return", "deleted_parser", "(", "poll", ")", "if", "poll", "[", "'type'", "]", "not", "in", "poll_types", ":", "raise", "Exception", "(", "'Not a poll type'", ")", ...
Parses a poll object
[ "Parses", "a", "poll", "object" ]
python
train
27.263158
bykof/billomapy
billomapy/billomapy.py
https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L2576-L2590
def get_items_of_credit_note_per_page(self, credit_note_id, per_page=1000, page=1): """ Get items of credit note per page :param credit_note_id: the credit note id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list...
[ "def", "get_items_of_credit_note_per_page", "(", "self", ",", "credit_note_id", ",", "per_page", "=", "1000", ",", "page", "=", "1", ")", ":", "return", "self", ".", "_get_resource_per_page", "(", "resource", "=", "CREDIT_NOTE_ITEMS", ",", "per_page", "=", "per_...
Get items of credit note per page :param credit_note_id: the credit note id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
[ "Get", "items", "of", "credit", "note", "per", "page" ]
python
train
34.733333
widdowquinn/pyani
pyani/pyani_files.py
https://github.com/widdowquinn/pyani/blob/2b24ec971401e04024bba896e4011984fe3f53f0/pyani/pyani_files.py#L27-L35
def get_input_files(dirname, *ext): """Returns files in passed directory, filtered by extension. - dirname - path to input directory - *ext - list of arguments describing permitted file extensions """ filelist = [f for f in os.listdir(dirname) if os.path.splitext(f)[-1] in ext] ...
[ "def", "get_input_files", "(", "dirname", ",", "*", "ext", ")", ":", "filelist", "=", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "dirname", ")", "if", "os", ".", "path", ".", "splitext", "(", "f", ")", "[", "-", "1", "]", "in", "ext...
Returns files in passed directory, filtered by extension. - dirname - path to input directory - *ext - list of arguments describing permitted file extensions
[ "Returns", "files", "in", "passed", "directory", "filtered", "by", "extension", "." ]
python
train
40.333333
nosegae/NoseGAE
nosegae.py
https://github.com/nosegae/NoseGAE/blob/fca9fab22b480bb9721ecaa0967a636107648d92/nosegae.py#L207-L211
def _init_datastore_v3_stub(self, **stub_kwargs): """Initializes the datastore stub using nosegae config magic""" task_args = dict(datastore_file=self._data_path) task_args.update(stub_kwargs) self.testbed.init_datastore_v3_stub(**task_args)
[ "def", "_init_datastore_v3_stub", "(", "self", ",", "*", "*", "stub_kwargs", ")", ":", "task_args", "=", "dict", "(", "datastore_file", "=", "self", ".", "_data_path", ")", "task_args", ".", "update", "(", "stub_kwargs", ")", "self", ".", "testbed", ".", "...
Initializes the datastore stub using nosegae config magic
[ "Initializes", "the", "datastore", "stub", "using", "nosegae", "config", "magic" ]
python
train
53.8
flo-compbio/genometools
genometools/ontology/term.py
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/term.py#L196-L225
def get_pretty_format(self, include_id=True, max_name_length=0, abbreviate=True): """Returns a nicely formatted string with the GO term information. Parameters ---------- include_id: bool, optional Include the GO term ID. max_name_length: in...
[ "def", "get_pretty_format", "(", "self", ",", "include_id", "=", "True", ",", "max_name_length", "=", "0", ",", "abbreviate", "=", "True", ")", ":", "name", "=", "self", ".", "name", "if", "abbreviate", ":", "for", "abb", "in", "self", ".", "_abbrev", ...
Returns a nicely formatted string with the GO term information. Parameters ---------- include_id: bool, optional Include the GO term ID. max_name_length: int, optional Truncate the formatted string so that its total length does not exceed this value. ...
[ "Returns", "a", "nicely", "formatted", "string", "with", "the", "GO", "term", "information", "." ]
python
train
34.333333
dagwieers/vmguestlib
vmguestlib.py
https://github.com/dagwieers/vmguestlib/blob/2ba9333a745628cf9e6b4c767427a5bd997a71ad/vmguestlib.py#L135-L147
def UpdateInfo(self): '''Updates information about the virtual machine. This information is associated with the VMGuestLibHandle. VMGuestLib_UpdateInfo requires similar CPU resources to a system call and therefore can affect performance. If you are concerned about performance, ...
[ "def", "UpdateInfo", "(", "self", ")", ":", "ret", "=", "vmGuestLib", ".", "VMGuestLib_UpdateInfo", "(", "self", ".", "handle", ".", "value", ")", "if", "ret", "!=", "VMGUESTLIB_ERROR_SUCCESS", ":", "raise", "VMGuestLibException", "(", "ret", ")" ]
Updates information about the virtual machine. This information is associated with the VMGuestLibHandle. VMGuestLib_UpdateInfo requires similar CPU resources to a system call and therefore can affect performance. If you are concerned about performance, minimize the number of...
[ "Updates", "information", "about", "the", "virtual", "machine", ".", "This", "information", "is", "associated", "with", "the", "VMGuestLibHandle", "." ]
python
train
60.461538
allenai/allennlp
allennlp/data/instance.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/instance.py#L74-L82
def get_padding_lengths(self) -> Dict[str, Dict[str, int]]: """ Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a mapping from padding keys to actual lengths, and we just key that dictionary by field name. """ lengths = {} for field_n...
[ "def", "get_padding_lengths", "(", "self", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "int", "]", "]", ":", "lengths", "=", "{", "}", "for", "field_name", ",", "field", "in", "self", ".", "fields", ".", "items", "(", ")", ":", "...
Returns a dictionary of padding lengths, keyed by field name. Each ``Field`` returns a mapping from padding keys to actual lengths, and we just key that dictionary by field name.
[ "Returns", "a", "dictionary", "of", "padding", "lengths", "keyed", "by", "field", "name", ".", "Each", "Field", "returns", "a", "mapping", "from", "padding", "keys", "to", "actual", "lengths", "and", "we", "just", "key", "that", "dictionary", "by", "field", ...
python
train
47.888889
pikepdf/pikepdf
src/pikepdf/models/metadata.py
https://github.com/pikepdf/pikepdf/blob/07154f4dec007e2e9c0c6a8c07b964fd06bc5f77/src/pikepdf/models/metadata.py#L377-L390
def _apply_changes(self): """Serialize our changes back to the PDF in memory Depending how we are initialized, leave our metadata mark and producer. """ if self.mark: self[QName(XMP_NS_XMP, 'MetadataDate')] = datetime.now().isoformat() self[QName(XMP_NS_PDF, 'Pro...
[ "def", "_apply_changes", "(", "self", ")", ":", "if", "self", ".", "mark", ":", "self", "[", "QName", "(", "XMP_NS_XMP", ",", "'MetadataDate'", ")", "]", "=", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", ")", "self", "[", "QName", "(", ...
Serialize our changes back to the PDF in memory Depending how we are initialized, leave our metadata mark and producer.
[ "Serialize", "our", "changes", "back", "to", "the", "PDF", "in", "memory" ]
python
train
44.285714
pdkit/pdkit
pdkit/models.py
https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/models.py#L165-L196
def DNN(input_shape, dense_layers, output_layer=[1, 'sigmoid'], optimizer='adam', loss='binary_crossentropy'): """Summary Args: input_shape (list): The shape of the input layer targets (int): Number of targets dense_layers (list): Dense la...
[ "def", "DNN", "(", "input_shape", ",", "dense_layers", ",", "output_layer", "=", "[", "1", ",", "'sigmoid'", "]", ",", "optimizer", "=", "'adam'", ",", "loss", "=", "'binary_crossentropy'", ")", ":", "inputs", "=", "Input", "(", "shape", "=", "input_shape"...
Summary Args: input_shape (list): The shape of the input layer targets (int): Number of targets dense_layers (list): Dense layer descriptor [fully_connected] optimizer (str or object optional): Keras optimizer as string or keras optimizer Returns: TYPE: model, b...
[ "Summary", "Args", ":", "input_shape", "(", "list", ")", ":", "The", "shape", "of", "the", "input", "layer", "targets", "(", "int", ")", ":", "Number", "of", "targets", "dense_layers", "(", "list", ")", ":", "Dense", "layer", "descriptor", "[", "fully_co...
python
train
29.15625
DC23/scriptabit
scriptabit/configuration.py
https://github.com/DC23/scriptabit/blob/0d0cf71814e98954850891fa0887bdcffcf7147d/scriptabit/configuration.py#L21-L64
def __add_min_max_value( parser, basename, default_min, default_max, initial, help_template): """ Generates parser entries for options with a min, max, and default value. Args: parser: the parser to use. basename: the base option name. Gen...
[ "def", "__add_min_max_value", "(", "parser", ",", "basename", ",", "default_min", ",", "default_max", ",", "initial", ",", "help_template", ")", ":", "help_template", "=", "Template", "(", "help_template", ")", "parser", ".", "add", "(", "'--{0}-min'", ".", "f...
Generates parser entries for options with a min, max, and default value. Args: parser: the parser to use. basename: the base option name. Generated options will have flags --basename-min, --basename-max, and --basename. default_min: the default min value default_max:...
[ "Generates", "parser", "entries", "for", "options", "with", "a", "min", "max", "and", "default", "value", "." ]
python
train
29.159091
sassoo/goldman
goldman/validators/__init__.py
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/validators/__init__.py#L24-L32
def validate_uuid(value): """ UUID 128-bit validator """ if value and not isinstance(value, UUID): try: return UUID(str(value), version=4) except (AttributeError, ValueError): raise ValidationError('not a valid UUID') return value
[ "def", "validate_uuid", "(", "value", ")", ":", "if", "value", "and", "not", "isinstance", "(", "value", ",", "UUID", ")", ":", "try", ":", "return", "UUID", "(", "str", "(", "value", ")", ",", "version", "=", "4", ")", "except", "(", "AttributeError...
UUID 128-bit validator
[ "UUID", "128", "-", "bit", "validator" ]
python
train
30.555556
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/filebrowser.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/filebrowser.py#L380-L395
def update_shot_browser(self, project, releasetype): """Update the shot browser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.mode...
[ "def", "update_shot_browser", "(", "self", ",", "project", ",", "releasetype", ")", ":", "if", "project", "is", "None", ":", "self", ".", "shotbrws", ".", "set_model", "(", "None", ")", "return", "shotmodel", "=", "self", ".", "create_shot_model", "(", "pr...
Update the shot browser to the given project :param releasetype: the releasetype for the model :type releasetype: :data:`djadapter.RELEASETYPES` :param project: the project of the shots :type project: :class:`djadapter.models.Project` :returns: None :rtype: None ...
[ "Update", "the", "shot", "browser", "to", "the", "given", "project" ]
python
train
36.9375
pantsbuild/pants
src/python/pants/goal/aggregated_timings.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/goal/aggregated_timings.py#L43-L49
def get_all(self): """Returns all the timings, sorted in decreasing order. Each value is a dict: { path: <path>, timing: <timing in seconds> } """ return [{'label': x[0], 'timing': x[1], 'is_tool': x[0] in self._tool_labels} for x in sorted(self._timings_by_path.items(), key=lambda x: x[1],...
[ "def", "get_all", "(", "self", ")", ":", "return", "[", "{", "'label'", ":", "x", "[", "0", "]", ",", "'timing'", ":", "x", "[", "1", "]", ",", "'is_tool'", ":", "x", "[", "0", "]", "in", "self", ".", "_tool_labels", "}", "for", "x", "in", "s...
Returns all the timings, sorted in decreasing order. Each value is a dict: { path: <path>, timing: <timing in seconds> }
[ "Returns", "all", "the", "timings", "sorted", "in", "decreasing", "order", "." ]
python
train
47
dahlia/sqlalchemy-imageattach
sqlalchemy_imageattach/entity.py
https://github.com/dahlia/sqlalchemy-imageattach/blob/b4bafa73f3bb576ecf67ed7b40b702704a0fbdc8/sqlalchemy_imageattach/entity.py#L415-L423
def _mark_image_file_deleted(cls, mapper, connection, target): """When the session flushes, marks images as deleted. The files of this marked images will be actually deleted in the image storage when the ongoing transaction succeeds. If it fails the :attr:`_deleted_images` queue will be ...
[ "def", "_mark_image_file_deleted", "(", "cls", ",", "mapper", ",", "connection", ",", "target", ")", ":", "cls", ".", "_deleted_images", ".", "add", "(", "(", "target", ",", "get_current_store", "(", ")", ")", ")" ]
When the session flushes, marks images as deleted. The files of this marked images will be actually deleted in the image storage when the ongoing transaction succeeds. If it fails the :attr:`_deleted_images` queue will be just empty.
[ "When", "the", "session", "flushes", "marks", "images", "as", "deleted", ".", "The", "files", "of", "this", "marked", "images", "will", "be", "actually", "deleted", "in", "the", "image", "storage", "when", "the", "ongoing", "transaction", "succeeds", ".", "I...
python
train
45.222222
pandas-dev/pandas
pandas/io/formats/format.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/formats/format.py#L1056-L1141
def get_result_as_array(self): """ Returns the float values converted into strings using the parameters given at initialisation, as a numpy array """ if self.formatter is not None: return np.array([self.formatter(x) for x in self.values]) if self.fixed_width...
[ "def", "get_result_as_array", "(", "self", ")", ":", "if", "self", ".", "formatter", "is", "not", "None", ":", "return", "np", ".", "array", "(", "[", "self", ".", "formatter", "(", "x", ")", "for", "x", "in", "self", ".", "values", "]", ")", "if",...
Returns the float values converted into strings using the parameters given at initialisation, as a numpy array
[ "Returns", "the", "float", "values", "converted", "into", "strings", "using", "the", "parameters", "given", "at", "initialisation", "as", "a", "numpy", "array" ]
python
train
38.418605
millar/provstore-api
provstore/document.py
https://github.com/millar/provstore-api/blob/0dd506b4f0e00623b95a52caa70debe758817179/provstore/document.py#L163-L183
def read_prov(self, document_id=None): """ Load the provenance of this document .. note:: This method is called automatically if needed when the :py:meth:`prov` property is accessed. Manual use of this method is unusual. :param document_id: (optional) set the docu...
[ "def", "read_prov", "(", "self", ",", "document_id", "=", "None", ")", ":", "if", "document_id", ":", "if", "not", "self", ".", "abstract", ":", "raise", "ImmutableDocumentException", "(", ")", "self", ".", "_id", "=", "document_id", "if", "self", ".", "...
Load the provenance of this document .. note:: This method is called automatically if needed when the :py:meth:`prov` property is accessed. Manual use of this method is unusual. :param document_id: (optional) set the document id if this is an :py:meth:`abstract` document ...
[ "Load", "the", "provenance", "of", "this", "document" ]
python
train
34.095238
rabitt/pysox
sox/transform.py
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L1155-L1168
def earwax(self): '''Makes audio easier to listen to on headphones. Adds ‘cues’ to 44.1kHz stereo audio so that when listened to on headphones the stereo image is moved from inside your head (standard for headphones) to outside and in front of the listener (standard for speakers). ...
[ "def", "earwax", "(", "self", ")", ":", "effect_args", "=", "[", "'earwax'", "]", "self", ".", "effects", ".", "extend", "(", "effect_args", ")", "self", ".", "effects_log", ".", "append", "(", "'earwax'", ")", "return", "self" ]
Makes audio easier to listen to on headphones. Adds ‘cues’ to 44.1kHz stereo audio so that when listened to on headphones the stereo image is moved from inside your head (standard for headphones) to outside and in front of the listener (standard for speakers). Warning: Will only work pr...
[ "Makes", "audio", "easier", "to", "listen", "to", "on", "headphones", ".", "Adds", "‘cues’", "to", "44", ".", "1kHz", "stereo", "audio", "so", "that", "when", "listened", "to", "on", "headphones", "the", "stereo", "image", "is", "moved", "from", "inside", ...
python
valid
36.928571
blue-yonder/tsfresh
tsfresh/feature_extraction/feature_calculators.py
https://github.com/blue-yonder/tsfresh/blob/c72c9c574371cf7dd7d54e00a466792792e5d202/tsfresh/feature_extraction/feature_calculators.py#L1439-L1461
def binned_entropy(x, max_bins): """ First bins the values of x into max_bins equidistant bins. Then calculates the value of .. math:: - \\sum_{k=0}^{min(max\\_bins, len(x))} p_k log(p_k) \\cdot \\mathbf{1}_{(p_k > 0)} where :math:`p_k` is the percentage of samples in bin :math:`k`. ...
[ "def", "binned_entropy", "(", "x", ",", "max_bins", ")", ":", "if", "not", "isinstance", "(", "x", ",", "(", "np", ".", "ndarray", ",", "pd", ".", "Series", ")", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "hist", ",", "bin_edges", ...
First bins the values of x into max_bins equidistant bins. Then calculates the value of .. math:: - \\sum_{k=0}^{min(max\\_bins, len(x))} p_k log(p_k) \\cdot \\mathbf{1}_{(p_k > 0)} where :math:`p_k` is the percentage of samples in bin :math:`k`. :param x: the time series to calculate the fe...
[ "First", "bins", "the", "values", "of", "x", "into", "max_bins", "equidistant", "bins", ".", "Then", "calculates", "the", "value", "of" ]
python
train
32.26087
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/connect/connect.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/connect.py#L588-L595
def delete_device_subscriptions(self, device_id): """Removes a device's subscriptions :param device_id: ID of the device (Required) :returns: None """ api = self._get_api(mds.SubscriptionsApi) return api.delete_endpoint_subscriptions(device_id)
[ "def", "delete_device_subscriptions", "(", "self", ",", "device_id", ")", ":", "api", "=", "self", ".", "_get_api", "(", "mds", ".", "SubscriptionsApi", ")", "return", "api", ".", "delete_endpoint_subscriptions", "(", "device_id", ")" ]
Removes a device's subscriptions :param device_id: ID of the device (Required) :returns: None
[ "Removes", "a", "device", "s", "subscriptions" ]
python
train
35.75
Yubico/python-yubico
yubico/yubikey_usb_hid.py
https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L127-L133
def status(self): """ Poll YubiKey for status. """ data = self._read() self._status = YubiKeyUSBHIDStatus(data) return self._status
[ "def", "status", "(", "self", ")", ":", "data", "=", "self", ".", "_read", "(", ")", "self", ".", "_status", "=", "YubiKeyUSBHIDStatus", "(", "data", ")", "return", "self", ".", "_status" ]
Poll YubiKey for status.
[ "Poll", "YubiKey", "for", "status", "." ]
python
train
24.714286
BlueBrain/NeuroM
neurom/morphmath.py
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/morphmath.py#L301-L313
def segment_radial_dist(seg, pos): '''Return the radial distance of a tree segment to a given point The radial distance is the euclidian distance between the mid-point of the segment and the point in question. Parameters: seg: tree segment pos: origin to which distances are measured. ...
[ "def", "segment_radial_dist", "(", "seg", ",", "pos", ")", ":", "return", "point_dist", "(", "pos", ",", "np", ".", "divide", "(", "np", ".", "add", "(", "seg", "[", "0", "]", ",", "seg", "[", "1", "]", ")", ",", "2.0", ")", ")" ]
Return the radial distance of a tree segment to a given point The radial distance is the euclidian distance between the mid-point of the segment and the point in question. Parameters: seg: tree segment pos: origin to which distances are measured. It must have at lease 3 components...
[ "Return", "the", "radial", "distance", "of", "a", "tree", "segment", "to", "a", "given", "point" ]
python
train
35.692308
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConscript.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Script/SConscript.py#L70-L89
def get_calling_namespaces(): """Return the locals and globals for the function that called into this module in the current call stack.""" try: 1//0 except ZeroDivisionError: # Don't start iterating with the current stack-frame to # prevent creating reference cycles (f_back is safe). ...
[ "def", "get_calling_namespaces", "(", ")", ":", "try", ":", "1", "//", "0", "except", "ZeroDivisionError", ":", "# Don't start iterating with the current stack-frame to", "# prevent creating reference cycles (f_back is safe).", "frame", "=", "sys", ".", "exc_info", "(", ")"...
Return the locals and globals for the function that called into this module in the current call stack.
[ "Return", "the", "locals", "and", "globals", "for", "the", "function", "that", "called", "into", "this", "module", "in", "the", "current", "call", "stack", "." ]
python
train
48.3
Gandi/gandi.cli
gandi/cli/commands/record.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/record.py#L31-L77
def list(gandi, domain, zone_id, output, format, limit): """List DNS zone records for a domain.""" options = { 'items_per_page': limit, } output_keys = ['name', 'type', 'value', 'ttl'] if not zone_id: result = gandi.domain.info(domain) zone_id = result['zone_id'] if not...
[ "def", "list", "(", "gandi", ",", "domain", ",", "zone_id", ",", "output", ",", "format", ",", "limit", ")", ":", "options", "=", "{", "'items_per_page'", ":", "limit", ",", "}", "output_keys", "=", "[", "'name'", ",", "'type'", ",", "'value'", ",", ...
List DNS zone records for a domain.
[ "List", "DNS", "zone", "records", "for", "a", "domain", "." ]
python
train
37.340426