repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
wonambi-python/wonambi
wonambi/detect/spindle.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/detect/spindle.py#L2130-L2158
def _realwavelets(s_freq, freqs, dur, width): """Create real wavelets, for UCSD. Parameters ---------- s_freq : int sampling frequency freqs : ndarray vector with frequencies of interest dur : float duration of the wavelets in s width : float parameter contro...
[ "def", "_realwavelets", "(", "s_freq", ",", "freqs", ",", "dur", ",", "width", ")", ":", "x", "=", "arange", "(", "-", "dur", "/", "2", ",", "dur", "/", "2", ",", "1", "/", "s_freq", ")", "wavelets", "=", "empty", "(", "(", "len", "(", "freqs",...
Create real wavelets, for UCSD. Parameters ---------- s_freq : int sampling frequency freqs : ndarray vector with frequencies of interest dur : float duration of the wavelets in s width : float parameter controlling gaussian shape Returns ------- nda...
[ "Create", "real", "wavelets", "for", "UCSD", "." ]
python
train
ashleysommer/sanicpluginsframework
spf/plugin.py
https://github.com/ashleysommer/sanicpluginsframework/blob/2cb1656d9334f04c30c738074784b0450c1b893e/spf/plugin.py#L154-L174
def static(self, uri, file_or_directory, *args, **kwargs): """Create a websocket route from a decorated function :param uri: endpoint at which the socket endpoint will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(...
[ "def", "static", "(", "self", ",", "uri", ",", "file_or_directory", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'pattern'", ",", "r'/?.+'", ")", "kwargs", ".", "setdefault", "(", "'use_modified_since'", ",", "T...
Create a websocket route from a decorated function :param uri: endpoint at which the socket endpoint will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :param kwargs: captures the keyword arguments passed in ...
[ "Create", "a", "websocket", "route", "from", "a", "decorated", "function", ":", "param", "uri", ":", "endpoint", "at", "which", "the", "socket", "endpoint", "will", "be", "accessible", ".", ":", "type", "uri", ":", "str", ":", "param", "args", ":", "capt...
python
train
idlesign/torrentool
torrentool/torrent.py
https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/torrent.py#L428-L436
def from_file(cls, filepath): """Alternative constructor to get Torrent object from file. :param str filepath: :rtype: Torrent """ torrent = cls(Bencode.read_file(filepath)) torrent._filepath = filepath return torrent
[ "def", "from_file", "(", "cls", ",", "filepath", ")", ":", "torrent", "=", "cls", "(", "Bencode", ".", "read_file", "(", "filepath", ")", ")", "torrent", ".", "_filepath", "=", "filepath", "return", "torrent" ]
Alternative constructor to get Torrent object from file. :param str filepath: :rtype: Torrent
[ "Alternative", "constructor", "to", "get", "Torrent", "object", "from", "file", "." ]
python
train
wandb/client
wandb/vendor/prompt_toolkit/shortcuts.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/shortcuts.py#L514-L548
def prompt(message='', **kwargs): """ Get input from the user and return it. This is a wrapper around a lot of ``prompt_toolkit`` functionality and can be a replacement for `raw_input`. (or GNU readline.) If you want to keep your history across several calls, create one :class:`~prompt_toolkit...
[ "def", "prompt", "(", "message", "=", "''", ",", "*", "*", "kwargs", ")", ":", "patch_stdout", "=", "kwargs", ".", "pop", "(", "'patch_stdout'", ",", "False", ")", "return_asyncio_coroutine", "=", "kwargs", ".", "pop", "(", "'return_asyncio_coroutine'", ",",...
Get input from the user and return it. This is a wrapper around a lot of ``prompt_toolkit`` functionality and can be a replacement for `raw_input`. (or GNU readline.) If you want to keep your history across several calls, create one :class:`~prompt_toolkit.history.History` instance and pass it every t...
[ "Get", "input", "from", "the", "user", "and", "return", "it", "." ]
python
train
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/itsdangerous.py#L322-L342
def derive_key(self): """This method is called to derive the key. If you're unhappy with the default key derivation choices you can override them here. Keep in mind that the key derivation in itsdangerous is not intended to be used as a security method to make a complex key out of a sho...
[ "def", "derive_key", "(", "self", ")", ":", "salt", "=", "want_bytes", "(", "self", ".", "salt", ")", "if", "self", ".", "key_derivation", "==", "'concat'", ":", "return", "self", ".", "digest_method", "(", "salt", "+", "self", ".", "secret_key", ")", ...
This method is called to derive the key. If you're unhappy with the default key derivation choices you can override them here. Keep in mind that the key derivation in itsdangerous is not intended to be used as a security method to make a complex key out of a short password. Instead you...
[ "This", "method", "is", "called", "to", "derive", "the", "key", ".", "If", "you", "re", "unhappy", "with", "the", "default", "key", "derivation", "choices", "you", "can", "override", "them", "here", ".", "Keep", "in", "mind", "that", "the", "key", "deriv...
python
test
Celeo/Pycord
pycord/__init__.py
https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L374-L399
def connect_to_websocket(self): """Call this method to make the connection to the Discord websocket This method is not blocking, so you'll probably want to call it after initializating your Pycord object, and then move on with your code. When you want to block on just maintaining the we...
[ "def", "connect_to_websocket", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "'Making websocket connection'", ")", "try", ":", "if", "hasattr", "(", "self", ",", "'_ws'", ")", ":", "self", ".", "_ws", ".", "close", "(", ")", "except", ...
Call this method to make the connection to the Discord websocket This method is not blocking, so you'll probably want to call it after initializating your Pycord object, and then move on with your code. When you want to block on just maintaining the websocket connection, then call ``kee...
[ "Call", "this", "method", "to", "make", "the", "connection", "to", "the", "Discord", "websocket" ]
python
train
ff0000/scarlet
scarlet/versioning/models.py
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/versioning/models.py#L171-L187
def _delete_reverses(self): """ Delete all objects that would have been cloned on a clone command. This is done separately because there may be m2m and other relationships that would have not been deleted otherwise. """ for reverse in self.clone_related: ...
[ "def", "_delete_reverses", "(", "self", ")", ":", "for", "reverse", "in", "self", ".", "clone_related", ":", "self", ".", "_delete_reverse", "(", "reverse", ")", "for", "field", "in", "self", ".", "_meta", ".", "local_many_to_many", ":", "if", "field", "."...
Delete all objects that would have been cloned on a clone command. This is done separately because there may be m2m and other relationships that would have not been deleted otherwise.
[ "Delete", "all", "objects", "that", "would", "have", "been", "cloned", "on", "a", "clone", "command", ".", "This", "is", "done", "separately", "because", "there", "may", "be", "m2m", "and", "other", "relationships", "that", "would", "have", "not", "been", ...
python
train
LISE-B26/pylabcontrol
pylabcontrol/core/script_iterator.py
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/pylabcontrol/core/script_iterator.py#L351-L359
def _receive_signal(self, progress_subscript): """ this function takes care of signals emitted by the subscripts Args: progress_subscript: progress of subscript """ self.progress = self._estimate_progress() self.updateProgress.emit(int(self.progress))
[ "def", "_receive_signal", "(", "self", ",", "progress_subscript", ")", ":", "self", ".", "progress", "=", "self", ".", "_estimate_progress", "(", ")", "self", ".", "updateProgress", ".", "emit", "(", "int", "(", "self", ".", "progress", ")", ")" ]
this function takes care of signals emitted by the subscripts Args: progress_subscript: progress of subscript
[ "this", "function", "takes", "care", "of", "signals", "emitted", "by", "the", "subscripts", "Args", ":", "progress_subscript", ":", "progress", "of", "subscript" ]
python
train
dlanger/inlinestyler
inlinestyler/converter.py
https://github.com/dlanger/inlinestyler/blob/335c4fbab892f0ed67466a6beaea6a91f395ad12/inlinestyler/converter.py#L66-L74
def styleattribute(self, element): """ returns css.CSSStyleDeclaration of inline styles, for html: @style """ css_text = element.get('style') if css_text: return cssutils.css.CSSStyleDeclaration(cssText=css_text) else: return None
[ "def", "styleattribute", "(", "self", ",", "element", ")", ":", "css_text", "=", "element", ".", "get", "(", "'style'", ")", "if", "css_text", ":", "return", "cssutils", ".", "css", ".", "CSSStyleDeclaration", "(", "cssText", "=", "css_text", ")", "else", ...
returns css.CSSStyleDeclaration of inline styles, for html: @style
[ "returns", "css", ".", "CSSStyleDeclaration", "of", "inline", "styles", "for", "html", ":" ]
python
train
google/grr
grr/server/grr_response_server/data_store.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/data_store.py#L289-L345
def QueueClaimRecords(self, queue_id, item_rdf_type, limit=10000, timeout="30m", start_time=None, record_filter=lambda x: False, max_filtered=1000): ...
[ "def", "QueueClaimRecords", "(", "self", ",", "queue_id", ",", "item_rdf_type", ",", "limit", "=", "10000", ",", "timeout", "=", "\"30m\"", ",", "start_time", "=", "None", ",", "record_filter", "=", "lambda", "x", ":", "False", ",", "max_filtered", "=", "1...
Claims records from a queue. See server/aff4_objects/queue.py.
[ "Claims", "records", "from", "a", "queue", ".", "See", "server", "/", "aff4_objects", "/", "queue", ".", "py", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/envs/env_problem.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/env_problem.py#L199-L235
def _verify_same_spaces(self): """Verifies that all the envs have the same observation and action space.""" # Pre-conditions: self._envs is initialized. if self._envs is None: raise ValueError("Environments not initialized.") if not isinstance(self._envs, list): tf.logging.warning("Not ch...
[ "def", "_verify_same_spaces", "(", "self", ")", ":", "# Pre-conditions: self._envs is initialized.", "if", "self", ".", "_envs", "is", "None", ":", "raise", "ValueError", "(", "\"Environments not initialized.\"", ")", "if", "not", "isinstance", "(", "self", ".", "_e...
Verifies that all the envs have the same observation and action space.
[ "Verifies", "that", "all", "the", "envs", "have", "the", "same", "observation", "and", "action", "space", "." ]
python
train
senaite/senaite.api
src/senaite/api/__init__.py
https://github.com/senaite/senaite.api/blob/c79c53abcbe6e3a5ab3ced86d2f455275efa20cf/src/senaite/api/__init__.py#L458-L496
def get_object_by_path(path, default=_marker): """Find an object by a given physical path or absolute_url :param path: The physical path of the object to find :type path: string :returns: Found Object or None """ # nothing to do here if not path: if default is not _marker: ...
[ "def", "get_object_by_path", "(", "path", ",", "default", "=", "_marker", ")", ":", "# nothing to do here", "if", "not", "path", ":", "if", "default", "is", "not", "_marker", ":", "return", "default", "fail", "(", "\"get_object_by_path first argument must be a path;...
Find an object by a given physical path or absolute_url :param path: The physical path of the object to find :type path: string :returns: Found Object or None
[ "Find", "an", "object", "by", "a", "given", "physical", "path", "or", "absolute_url" ]
python
train
majerteam/sqla_inspect
sqla_inspect/py3o.py
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/py3o.py#L228-L250
def _get_formatted_val(self, obj, attribute, column): """ Return the formatted value of the attribute "attribute" of the obj "obj" regarding the column's description :param obj obj: The instance we manage :param str attribute: The string defining the path to access the end ...
[ "def", "_get_formatted_val", "(", "self", ",", "obj", ",", "attribute", ",", "column", ")", ":", "attr_path", "=", "attribute", ".", "split", "(", "'.'", ")", "val", "=", "None", "tmp_val", "=", "obj", "for", "attr", "in", "attr_path", ":", "tmp_val", ...
Return the formatted value of the attribute "attribute" of the obj "obj" regarding the column's description :param obj obj: The instance we manage :param str attribute: The string defining the path to access the end attribute we want to manage :param dict column: The column desc...
[ "Return", "the", "formatted", "value", "of", "the", "attribute", "attribute", "of", "the", "obj", "obj", "regarding", "the", "column", "s", "description" ]
python
train
materialsproject/pymatgen
pymatgen/io/qchem/outputs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/qchem/outputs.py#L374-L402
def _read_mulliken(self): """ Parses Mulliken charges. Also parses spins given an unrestricted SCF. """ if self.data.get('unrestricted', []): header_pattern = r"\-+\s+Ground-State Mulliken Net Atomic Charges\s+Atom\s+Charge \(a\.u\.\)\s+Spin\s\(a\.u\.\)\s+\-+" tab...
[ "def", "_read_mulliken", "(", "self", ")", ":", "if", "self", ".", "data", ".", "get", "(", "'unrestricted'", ",", "[", "]", ")", ":", "header_pattern", "=", "r\"\\-+\\s+Ground-State Mulliken Net Atomic Charges\\s+Atom\\s+Charge \\(a\\.u\\.\\)\\s+Spin\\s\\(a\\.u\\.\\)\\s+\\...
Parses Mulliken charges. Also parses spins given an unrestricted SCF.
[ "Parses", "Mulliken", "charges", ".", "Also", "parses", "spins", "given", "an", "unrestricted", "SCF", "." ]
python
train
wummel/dosage
scripts/smackjeeves.py
https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/scripts/smackjeeves.py#L295-L307
def get_results(): """Parse all search result pages.""" base = "http://www.smackjeeves.com/search.php?submit=Search+for+Webcomics&search_mode=webcomics&comic_title=&special=all&last_update=3&style_all=on&genre_all=on&format_all=on&sort_by=2&start=%d" session = requests.Session() # store info in a dictio...
[ "def", "get_results", "(", ")", ":", "base", "=", "\"http://www.smackjeeves.com/search.php?submit=Search+for+Webcomics&search_mode=webcomics&comic_title=&special=all&last_update=3&style_all=on&genre_all=on&format_all=on&sort_by=2&start=%d\"", "session", "=", "requests", ".", "Session", "("...
Parse all search result pages.
[ "Parse", "all", "search", "result", "pages", "." ]
python
train
horejsek/python-fastjsonschema
fastjsonschema/draft04.py
https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft04.py#L151-L177
def generate_one_of(self): """ Means that value have to be valid by only one of those definitions. It can't be valid by two or more of them. .. code-block:: python { 'oneOf': [ {'type': 'number', 'multipleOf': 3}, {'ty...
[ "def", "generate_one_of", "(", "self", ")", ":", "self", ".", "l", "(", "'{variable}_one_of_count = 0'", ")", "for", "definition_item", "in", "self", ".", "_definition", "[", "'oneOf'", "]", ":", "# When we know it's failing (one of means exactly once), we do not need to ...
Means that value have to be valid by only one of those definitions. It can't be valid by two or more of them. .. code-block:: python { 'oneOf': [ {'type': 'number', 'multipleOf': 3}, {'type': 'number', 'multipleOf': 5}, ...
[ "Means", "that", "value", "have", "to", "be", "valid", "by", "only", "one", "of", "those", "definitions", ".", "It", "can", "t", "be", "valid", "by", "two", "or", "more", "of", "them", "." ]
python
train
fermiPy/fermipy
fermipy/gtanalysis.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/gtanalysis.py#L2349-L2436
def profile_norm(self, name, logemin=None, logemax=None, reoptimize=False, xvals=None, npts=None, fix_shape=True, savestate=True, **kwargs): """Profile the normalization of a source. Parameters ---------- name : str Source name. ...
[ "def", "profile_norm", "(", "self", ",", "name", ",", "logemin", "=", "None", ",", "logemax", "=", "None", ",", "reoptimize", "=", "False", ",", "xvals", "=", "None", ",", "npts", "=", "None", ",", "fix_shape", "=", "True", ",", "savestate", "=", "Tr...
Profile the normalization of a source. Parameters ---------- name : str Source name. reoptimize : bool Re-optimize free parameters in the model at each point in the profile likelihood scan.
[ "Profile", "the", "normalization", "of", "a", "source", "." ]
python
train
nerdvegas/rez
src/rez/vendor/yaml/__init__.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/yaml/__init__.py#L64-L73
def load(stream, Loader=Loader): """ Parse the first YAML document in a stream and produce the corresponding Python object. """ loader = Loader(stream) try: return loader.get_single_data() finally: loader.dispose()
[ "def", "load", "(", "stream", ",", "Loader", "=", "Loader", ")", ":", "loader", "=", "Loader", "(", "stream", ")", "try", ":", "return", "loader", ".", "get_single_data", "(", ")", "finally", ":", "loader", ".", "dispose", "(", ")" ]
Parse the first YAML document in a stream and produce the corresponding Python object.
[ "Parse", "the", "first", "YAML", "document", "in", "a", "stream", "and", "produce", "the", "corresponding", "Python", "object", "." ]
python
train
bububa/pyTOP
pyTOP/increment.py
https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/increment.py#L50-L56
def customer_permit(self, session): '''taobao.increment.customer.permit 开通增量消息服务 提供app为自己的用户开通增量消息服务功能''' request = TOPRequest('taobao.increment.customer.permit') self.create(self.execute(request, session), fields=['app_customer',], models={'app_customer':AppCustomer}) r...
[ "def", "customer_permit", "(", "self", ",", "session", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.increment.customer.permit'", ")", "self", ".", "create", "(", "self", ".", "execute", "(", "request", ",", "session", ")", ",", "fields", "=", "[", ...
taobao.increment.customer.permit 开通增量消息服务 提供app为自己的用户开通增量消息服务功能
[ "taobao", ".", "increment", ".", "customer", ".", "permit", "开通增量消息服务", "提供app为自己的用户开通增量消息服务功能" ]
python
train
tanghaibao/jcvi
jcvi/variation/str.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/variation/str.py#L1427-L1482
def lobstrindex(args): """ %prog lobstrindex hg38.trf.bed hg38.upper.fa Make lobSTR index. Make sure the FASTA contain only upper case (so use fasta.format --upper to convert from UCSC fasta). The bed file is generated by str(). """ p = OptionParser(lobstrindex.__doc__) p.add_option("--...
[ "def", "lobstrindex", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "lobstrindex", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--notreds\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Remove TR...
%prog lobstrindex hg38.trf.bed hg38.upper.fa Make lobSTR index. Make sure the FASTA contain only upper case (so use fasta.format --upper to convert from UCSC fasta). The bed file is generated by str().
[ "%prog", "lobstrindex", "hg38", ".", "trf", ".", "bed", "hg38", ".", "upper", ".", "fa" ]
python
train
prawn-cake/vk-requests
vk_requests/session.py
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L85-L134
def do_login(self, http_session): """Do vk login :param http_session: vk_requests.utils.VerboseHTTPSession: http session """ response = http_session.get(self.LOGIN_URL) action_url = parse_form_action_url(response.text) # Stop login it action url is not found if...
[ "def", "do_login", "(", "self", ",", "http_session", ")", ":", "response", "=", "http_session", ".", "get", "(", "self", ".", "LOGIN_URL", ")", "action_url", "=", "parse_form_action_url", "(", "response", ".", "text", ")", "# Stop login it action url is not found"...
Do vk login :param http_session: vk_requests.utils.VerboseHTTPSession: http session
[ "Do", "vk", "login" ]
python
train
usc-isi-i2/etk
etk/extractors/table_extractor.py
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/table_extractor.py#L67-L73
def add_glossary(self, glossary: List[str], attr_name: str) -> None: """ Adds a glossary for the given attribute name :param glossary: a list of possible mentions of the attribute name :param attr_name: the attribute name (field name) """ self.glossaries[attr_name] = glos...
[ "def", "add_glossary", "(", "self", ",", "glossary", ":", "List", "[", "str", "]", ",", "attr_name", ":", "str", ")", "->", "None", ":", "self", ".", "glossaries", "[", "attr_name", "]", "=", "glossary" ]
Adds a glossary for the given attribute name :param glossary: a list of possible mentions of the attribute name :param attr_name: the attribute name (field name)
[ "Adds", "a", "glossary", "for", "the", "given", "attribute", "name", ":", "param", "glossary", ":", "a", "list", "of", "possible", "mentions", "of", "the", "attribute", "name", ":", "param", "attr_name", ":", "the", "attribute", "name", "(", "field", "name...
python
train
openstack/horizon
openstack_dashboard/utils/config_types.py
https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/utils/config_types.py#L117-L154
def validate(self, result, spec): # noqa Yes, it's too complex. """Validate that the result has the correct structure.""" if spec is None: # None matches anything. return if isinstance(spec, dict): if not isinstance(result, dict): raise ValueE...
[ "def", "validate", "(", "self", ",", "result", ",", "spec", ")", ":", "# noqa Yes, it's too complex.", "if", "spec", "is", "None", ":", "# None matches anything.", "return", "if", "isinstance", "(", "spec", ",", "dict", ")", ":", "if", "not", "isinstance", "...
Validate that the result has the correct structure.
[ "Validate", "that", "the", "result", "has", "the", "correct", "structure", "." ]
python
train
robotpy/pyfrc
lib/pyfrc/physics/core.py
https://github.com/robotpy/pyfrc/blob/7672ea3f17c8d4b702a9f18a7372d95feee7e37d/lib/pyfrc/physics/core.py#L332-L338
def get_position(self): """ :returns: Robot's current position on the field as `(x,y,angle)`. `x` and `y` are specified in feet, `angle` is in radians """ with self._lock: return self.x, self.y, self.angle
[ "def", "get_position", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "return", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "angle" ]
:returns: Robot's current position on the field as `(x,y,angle)`. `x` and `y` are specified in feet, `angle` is in radians
[ ":", "returns", ":", "Robot", "s", "current", "position", "on", "the", "field", "as", "(", "x", "y", "angle", ")", ".", "x", "and", "y", "are", "specified", "in", "feet", "angle", "is", "in", "radians" ]
python
train
lago-project/lago
lago/subnet_lease.py
https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L196-L217
def _lease_valid(self, lease): """ Check if the given lease exist and still has a prefix that owns it. If the lease exist but its prefix isn't, remove the lease from this store. Args: lease (lago.subnet_lease.Lease): Object representation of the lease...
[ "def", "_lease_valid", "(", "self", ",", "lease", ")", ":", "if", "not", "lease", ".", "exist", ":", "return", "None", "if", "lease", ".", "has_env", ":", "return", "lease", ".", "uuid_path", "else", ":", "self", ".", "_release", "(", "lease", ")", "...
Check if the given lease exist and still has a prefix that owns it. If the lease exist but its prefix isn't, remove the lease from this store. Args: lease (lago.subnet_lease.Lease): Object representation of the lease Returns: str or None: If the ...
[ "Check", "if", "the", "given", "lease", "exist", "and", "still", "has", "a", "prefix", "that", "owns", "it", ".", "If", "the", "lease", "exist", "but", "its", "prefix", "isn", "t", "remove", "the", "lease", "from", "this", "store", "." ]
python
train
lpantano/seqcluster
seqcluster/function/coral.py
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/function/coral.py#L123-L163
def create_features(bam_in, loci_file, reference, out_dir): """ Use feature extraction module from CoRaL """ lenvec_plus = op.join(out_dir, 'genomic_lenvec.plus') lenvec_minus = op.join(out_dir, 'genomic_lenvec.minus') compute_genomic_cmd = ("compute_genomic_lenvectors " ...
[ "def", "create_features", "(", "bam_in", ",", "loci_file", ",", "reference", ",", "out_dir", ")", ":", "lenvec_plus", "=", "op", ".", "join", "(", "out_dir", ",", "'genomic_lenvec.plus'", ")", "lenvec_minus", "=", "op", ".", "join", "(", "out_dir", ",", "'...
Use feature extraction module from CoRaL
[ "Use", "feature", "extraction", "module", "from", "CoRaL" ]
python
train
angr/claripy
claripy/backends/__init__.py
https://github.com/angr/claripy/blob/4ed61924880af1ea8fb778047d896ec0156412a6/claripy/backends/__init__.py#L437-L445
def add(self, s, c, track=False): """ This function adds constraints to the backend solver. :param c: A sequence of ASTs :param s: A backend solver object :param bool track: True to enable constraint tracking, which is used in unsat_core() """ return self._add(s,...
[ "def", "add", "(", "self", ",", "s", ",", "c", ",", "track", "=", "False", ")", ":", "return", "self", ".", "_add", "(", "s", ",", "self", ".", "convert_list", "(", "c", ")", ",", "track", "=", "track", ")" ]
This function adds constraints to the backend solver. :param c: A sequence of ASTs :param s: A backend solver object :param bool track: True to enable constraint tracking, which is used in unsat_core()
[ "This", "function", "adds", "constraints", "to", "the", "backend", "solver", "." ]
python
train
saltstack/salt
salt/modules/aliases.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aliases.py#L40-L61
def __parse_aliases(): ''' Parse the aliases file, and return a list of line components: [ (alias1, target1, comment1), (alias2, target2, comment2), ] ''' afn = __get_aliases_filename() ret = [] if not os.path.isfile(afn): return ret with salt.utils.files.fopen(a...
[ "def", "__parse_aliases", "(", ")", ":", "afn", "=", "__get_aliases_filename", "(", ")", "ret", "=", "[", "]", "if", "not", "os", ".", "path", ".", "isfile", "(", "afn", ")", ":", "return", "ret", "with", "salt", ".", "utils", ".", "files", ".", "f...
Parse the aliases file, and return a list of line components: [ (alias1, target1, comment1), (alias2, target2, comment2), ]
[ "Parse", "the", "aliases", "file", "and", "return", "a", "list", "of", "line", "components", ":" ]
python
train
w1ll1am23/pyeconet
src/pyeconet/api.py
https://github.com/w1ll1am23/pyeconet/blob/05abf965f67c7445355508a38f11992d13adac4f/src/pyeconet/api.py#L114-L123
def get_vacations(): """ Pull the accounts vacations. """ arequest = requests.get(VACATIONS_URL, headers=HEADERS) status_code = str(arequest.status_code) if status_code == '401': _LOGGER.error("Token expired.") return False return arequest....
[ "def", "get_vacations", "(", ")", ":", "arequest", "=", "requests", ".", "get", "(", "VACATIONS_URL", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_code", "==", "'401'", ":", "_LOGGE...
Pull the accounts vacations.
[ "Pull", "the", "accounts", "vacations", "." ]
python
valid
rapidpro/expressions
python/temba_expressions/functions/excel.py
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L164-L189
def datedif(ctx, start_date, end_date, unit): """ Calculates the number of days, months, or years between two dates. """ start_date = conversions.to_date(start_date, ctx) end_date = conversions.to_date(end_date, ctx) unit = conversions.to_string(unit, ctx).lower() if start_date > end_date: ...
[ "def", "datedif", "(", "ctx", ",", "start_date", ",", "end_date", ",", "unit", ")", ":", "start_date", "=", "conversions", ".", "to_date", "(", "start_date", ",", "ctx", ")", "end_date", "=", "conversions", ".", "to_date", "(", "end_date", ",", "ctx", ")...
Calculates the number of days, months, or years between two dates.
[ "Calculates", "the", "number", "of", "days", "months", "or", "years", "between", "two", "dates", "." ]
python
train
saltstack/salt
salt/modules/znc.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/znc.py#L34-L58
def _makepass(password, hasher='sha256'): ''' Create a znc compatible hashed password ''' # Setup the hasher if hasher == 'sha256': h = hashlib.sha256(password) elif hasher == 'md5': h = hashlib.md5(password) else: return NotImplemented c = "abcdefghijklmnopqrstu...
[ "def", "_makepass", "(", "password", ",", "hasher", "=", "'sha256'", ")", ":", "# Setup the hasher", "if", "hasher", "==", "'sha256'", ":", "h", "=", "hashlib", ".", "sha256", "(", "password", ")", "elif", "hasher", "==", "'md5'", ":", "h", "=", "hashlib...
Create a znc compatible hashed password
[ "Create", "a", "znc", "compatible", "hashed", "password" ]
python
train
miguelgrinberg/python-socketio
socketio/asyncio_server.py
https://github.com/miguelgrinberg/python-socketio/blob/c0c1bf8d21e3597389b18938550a0724dd9676b7/socketio/asyncio_server.py#L205-L218
async def close_room(self, room, namespace=None): """Close a room. This function removes all the clients from the given room. :param room: Room name. :param namespace: The Socket.IO namespace for the event. If this argument is omitted the default namespace is ...
[ "async", "def", "close_room", "(", "self", ",", "room", ",", "namespace", "=", "None", ")", ":", "namespace", "=", "namespace", "or", "'/'", "self", ".", "logger", ".", "info", "(", "'room %s is closing [%s]'", ",", "room", ",", "namespace", ")", "await", ...
Close a room. This function removes all the clients from the given room. :param room: Room name. :param namespace: The Socket.IO namespace for the event. If this argument is omitted the default namespace is used. Note: this method is a coroutine.
[ "Close", "a", "room", "." ]
python
train
SteveMcGrath/pySecurityCenter
securitycenter/sc4.py
https://github.com/SteveMcGrath/pySecurityCenter/blob/f0b10b1bcd4fd23a8d4d09ca6774cdf5e1cfd880/securitycenter/sc4.py#L641-L671
def plugin_counts(self): """plugin_counts Returns the plugin counts as dictionary with the last updated info if its available. """ ret = { 'total': 0, } # As ususal, we need data before we can actually do anything ;) data = self.raw_query('plu...
[ "def", "plugin_counts", "(", "self", ")", ":", "ret", "=", "{", "'total'", ":", "0", ",", "}", "# As ususal, we need data before we can actually do anything ;)", "data", "=", "self", ".", "raw_query", "(", "'plugin'", ",", "'init'", ")", "# For backwards compatabili...
plugin_counts Returns the plugin counts as dictionary with the last updated info if its available.
[ "plugin_counts", "Returns", "the", "plugin", "counts", "as", "dictionary", "with", "the", "last", "updated", "info", "if", "its", "available", "." ]
python
train
cnt-dev/cnt.rulebase
cnt/rulebase/rules/sentence_segmentation/sentence_segmenter.py
https://github.com/cnt-dev/cnt.rulebase/blob/d1c767c356d8ee05b23ec5b04aaac84784ee547c/cnt/rulebase/rules/sentence_segmentation/sentence_segmenter.py#L108-L170
def result(self) -> workflow.IntervalGeneratorType: """ Generate intervals indicating the valid sentences. """ config = cast(SentenceSegementationConfig, self.config) index = -1 labels = None while True: # 1. Find the start of the sentence. ...
[ "def", "result", "(", "self", ")", "->", "workflow", ".", "IntervalGeneratorType", ":", "config", "=", "cast", "(", "SentenceSegementationConfig", ",", "self", ".", "config", ")", "index", "=", "-", "1", "labels", "=", "None", "while", "True", ":", "# 1. F...
Generate intervals indicating the valid sentences.
[ "Generate", "intervals", "indicating", "the", "valid", "sentences", "." ]
python
train
mitsei/dlkit
dlkit/services/repository.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/repository.py#L1810-L1818
def use_plenary_asset_composition_view(self): """Pass through to provider AssetCompositionSession.use_plenary_asset_composition_view""" self._object_views['asset_composition'] = PLENARY # self._get_provider_session('asset_composition_session') # To make sure the session is tracked for se...
[ "def", "use_plenary_asset_composition_view", "(", "self", ")", ":", "self", ".", "_object_views", "[", "'asset_composition'", "]", "=", "PLENARY", "# self._get_provider_session('asset_composition_session') # To make sure the session is tracked", "for", "session", "in", "self", ...
Pass through to provider AssetCompositionSession.use_plenary_asset_composition_view
[ "Pass", "through", "to", "provider", "AssetCompositionSession", ".", "use_plenary_asset_composition_view" ]
python
train
vtkiorg/vtki
vtki/qt_plotting.py
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L418-L420
def scale_axes_dialog(self, show=True): """ Open scale axes dialog """ return ScaleAxesDialog(self.app_window, self, show=show)
[ "def", "scale_axes_dialog", "(", "self", ",", "show", "=", "True", ")", ":", "return", "ScaleAxesDialog", "(", "self", ".", "app_window", ",", "self", ",", "show", "=", "show", ")" ]
Open scale axes dialog
[ "Open", "scale", "axes", "dialog" ]
python
train
iotile/coretools
iotilecore/iotile/core/hw/reports/flexible_dictionary.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/reports/flexible_dictionary.py#L28-L80
def FromReadings(cls, uuid, readings, events, report_id=IOTileReading.InvalidReadingID, selector=0xFFFF, streamer=0x100, sent_timestamp=0, received_time=None): """Create a flexible dictionary report from a list of readings and events. Args: uuid (int): The uuid of the d...
[ "def", "FromReadings", "(", "cls", ",", "uuid", ",", "readings", ",", "events", ",", "report_id", "=", "IOTileReading", ".", "InvalidReadingID", ",", "selector", "=", "0xFFFF", ",", "streamer", "=", "0x100", ",", "sent_timestamp", "=", "0", ",", "received_ti...
Create a flexible dictionary report from a list of readings and events. Args: uuid (int): The uuid of the device that this report came from readings (list of IOTileReading): A list of IOTileReading objects containing the data in the report events (list of IOTileEvent): A lis...
[ "Create", "a", "flexible", "dictionary", "report", "from", "a", "list", "of", "readings", "and", "events", "." ]
python
train
neithere/argh
argh/assembling.py
https://github.com/neithere/argh/blob/dcd3253f2994400a6a58a700c118c53765bc50a4/argh/assembling.py#L188-L318
def set_default_command(parser, function): """ Sets default command (i.e. a function) for given parser. If `parser.description` is empty and the function has a docstring, it is used as the description. .. note:: An attempt to set default command to a parser which already has subpars...
[ "def", "set_default_command", "(", "parser", ",", "function", ")", ":", "if", "parser", ".", "_subparsers", ":", "_require_support_for_default_command_with_subparsers", "(", ")", "spec", "=", "get_arg_spec", "(", "function", ")", "declared_args", "=", "getattr", "("...
Sets default command (i.e. a function) for given parser. If `parser.description` is empty and the function has a docstring, it is used as the description. .. note:: An attempt to set default command to a parser which already has subparsers (e.g. added with :func:`~argh.assembling.add_comman...
[ "Sets", "default", "command", "(", "i", ".", "e", ".", "a", "function", ")", "for", "given", "parser", "." ]
python
test
noxdafox/clipspy
clips/agenda.py
https://github.com/noxdafox/clipspy/blob/b22d71a6da821c1715d8fa00d7d75cabc09ed364/clips/agenda.py#L269-L287
def matches(self, verbosity=Verbosity.TERSE): """Shows partial matches and activations. Returns a tuple containing the combined sum of the matches for each pattern, the combined sum of partial matches and the number of activations. The verbosity parameter controls how much to o...
[ "def", "matches", "(", "self", ",", "verbosity", "=", "Verbosity", ".", "TERSE", ")", ":", "data", "=", "clips", ".", "data", ".", "DataObject", "(", "self", ".", "_env", ")", "lib", ".", "EnvMatches", "(", "self", ".", "_env", ",", "self", ".", "_...
Shows partial matches and activations. Returns a tuple containing the combined sum of the matches for each pattern, the combined sum of partial matches and the number of activations. The verbosity parameter controls how much to output: * Verbosity.VERBOSE: detailed matches a...
[ "Shows", "partial", "matches", "and", "activations", "." ]
python
train
cloudtools/stacker
stacker/hooks/ecs.py
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/hooks/ecs.py#L15-L45
def create_clusters(provider, context, **kwargs): """Creates ECS clusters. Expects a "clusters" argument, which should contain a list of cluster names to create. Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.contex...
[ "def", "create_clusters", "(", "provider", ",", "context", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "get_session", "(", "provider", ".", "region", ")", ".", "client", "(", "'ecs'", ")", "try", ":", "clusters", "=", "kwargs", "[", "\"clusters\"", ...
Creates ECS clusters. Expects a "clusters" argument, which should contain a list of cluster names to create. Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance Returns: boolean for w...
[ "Creates", "ECS", "clusters", "." ]
python
train
apache/spark
python/pyspark/rdd.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L150-L160
def ignore_unicode_prefix(f): """ Ignore the 'u' prefix of string in doc tests, to make it works in both python 2 and 3 """ if sys.version >= '3': # the representation of unicode string in Python 3 does not have prefix 'u', # so remove the prefix 'u' for doc tests literal_re ...
[ "def", "ignore_unicode_prefix", "(", "f", ")", ":", "if", "sys", ".", "version", ">=", "'3'", ":", "# the representation of unicode string in Python 3 does not have prefix 'u',", "# so remove the prefix 'u' for doc tests", "literal_re", "=", "re", ".", "compile", "(", "r\"(...
Ignore the 'u' prefix of string in doc tests, to make it works in both python 2 and 3
[ "Ignore", "the", "u", "prefix", "of", "string", "in", "doc", "tests", "to", "make", "it", "works", "in", "both", "python", "2", "and", "3" ]
python
train
stitchfix/pyxley
pyxley/charts/mg/graphic.py
https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/graphic.py#L74-L87
def chart_type(self, value): """Set the MetricsGraphics chart type. Allowed charts are: line, histogram, point, and bar Args: value (str): chart type. Raises: ValueError: Not a valid chart type. """ if value not in self._allow...
[ "def", "chart_type", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "self", ".", "_allowed_charts", ":", "raise", "ValueError", "(", "\"Not a valid chart type\"", ")", "self", ".", "options", "[", "\"chart_type\"", "]", "=", "value" ]
Set the MetricsGraphics chart type. Allowed charts are: line, histogram, point, and bar Args: value (str): chart type. Raises: ValueError: Not a valid chart type.
[ "Set", "the", "MetricsGraphics", "chart", "type", ".", "Allowed", "charts", "are", ":", "line", "histogram", "point", "and", "bar" ]
python
train
Microsoft/LightGBM
python-package/lightgbm/basic.py
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2063-L2090
def save_model(self, filename, num_iteration=None, start_iteration=0): """Save Booster to file. Parameters ---------- filename : string Filename to save Booster. num_iteration : int or None, optional (default=None) Index of the iteration that should be sa...
[ "def", "save_model", "(", "self", ",", "filename", ",", "num_iteration", "=", "None", ",", "start_iteration", "=", "0", ")", ":", "if", "num_iteration", "is", "None", ":", "num_iteration", "=", "self", ".", "best_iteration", "_safe_call", "(", "_LIB", ".", ...
Save Booster to file. Parameters ---------- filename : string Filename to save Booster. num_iteration : int or None, optional (default=None) Index of the iteration that should be saved. If None, if the best iteration exists, it is saved; otherwise, al...
[ "Save", "Booster", "to", "file", "." ]
python
train
pypa/pipenv
pipenv/patched/notpip/_internal/cache.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cache.py#L132-L151
def get_path_for_link(self, link): # type: (Link) -> str """Return a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only inse...
[ "def", "get_path_for_link", "(", "self", ",", "link", ")", ":", "# type: (Link) -> str", "parts", "=", "self", ".", "_get_cache_path_parts", "(", "link", ")", "# Store wheels within the root cache_dir", "return", "os", ".", "path", ".", "join", "(", "self", ".", ...
Return a directory to store cached wheels for link Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so ...
[ "Return", "a", "directory", "to", "store", "cached", "wheels", "for", "link" ]
python
train
SeabornGames/Meta
seaborn_meta/calling_function.py
https://github.com/SeabornGames/Meta/blob/f2a38ad8bcc5ac177e537645853593225895df46/seaborn_meta/calling_function.py#L290-L303
def trace_error(function_index=2): """ This will return the line number and line text of the last error :param function_index: int to tell what frame to look from :return: int, str of the line number and line text """ info = function_info(function_index) traces = traceback.format_stack(limit...
[ "def", "trace_error", "(", "function_index", "=", "2", ")", ":", "info", "=", "function_info", "(", "function_index", ")", "traces", "=", "traceback", ".", "format_stack", "(", "limit", "=", "10", ")", "for", "trace", "in", "traces", ":", "file_", ",", "...
This will return the line number and line text of the last error :param function_index: int to tell what frame to look from :return: int, str of the line number and line text
[ "This", "will", "return", "the", "line", "number", "and", "line", "text", "of", "the", "last", "error", ":", "param", "function_index", ":", "int", "to", "tell", "what", "frame", "to", "look", "from", ":", "return", ":", "int", "str", "of", "the", "lin...
python
train
marl/jams
jams/schema.py
https://github.com/marl/jams/blob/b16778399b9528efbd71434842a079f7691a7a66/jams/schema.py#L35-L47
def add_namespace(filename): '''Add a namespace definition to our working set. Namespace files consist of partial JSON schemas defining the behavior of the `value` and `confidence` fields of an Annotation. Parameters ---------- filename : str Path to json file defining the namespace ob...
[ "def", "add_namespace", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "mode", "=", "'r'", ")", "as", "fileobj", ":", "__NAMESPACE__", ".", "update", "(", "json", ".", "load", "(", "fileobj", ")", ")" ]
Add a namespace definition to our working set. Namespace files consist of partial JSON schemas defining the behavior of the `value` and `confidence` fields of an Annotation. Parameters ---------- filename : str Path to json file defining the namespace object
[ "Add", "a", "namespace", "definition", "to", "our", "working", "set", "." ]
python
valid
readbeyond/aeneas
aeneas/textfile.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L879-L896
def _read_parsed(self, lines): """ Read text fragments from a parsed format text file. :param list lines: the lines of the parsed text file :param dict parameters: additional parameters for parsing (e.g., class/id regex strings) """ self.l...
[ "def", "_read_parsed", "(", "self", ",", "lines", ")", ":", "self", ".", "log", "(", "u\"Parsing fragments from parsed text format\"", ")", "pairs", "=", "[", "]", "for", "line", "in", "lines", ":", "pieces", "=", "line", ".", "split", "(", "gc", ".", "P...
Read text fragments from a parsed format text file. :param list lines: the lines of the parsed text file :param dict parameters: additional parameters for parsing (e.g., class/id regex strings)
[ "Read", "text", "fragments", "from", "a", "parsed", "format", "text", "file", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_span.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_span.py#L128-L141
def monitor_session_span_command_dest_vlan_val(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") monitor = ET.SubElement(config, "monitor", xmlns="urn:brocade.com:mgmt:brocade-span") session = ET.SubElement(monitor, "session") session_number_key = ...
[ "def", "monitor_session_span_command_dest_vlan_val", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "monitor", "=", "ET", ".", "SubElement", "(", "config", ",", "\"monitor\"", ",", "xmlns", "=", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
Arello-Mobile/swagger2rst
swg2rst/utils/exampilators.py
https://github.com/Arello-Mobile/swagger2rst/blob/e519f70701477dcc9f0bb237ee5b8e08e848701b/swg2rst/utils/exampilators.py#L169-L186
def get_response_example(cls, operation, response): """ Get example for response object by operation object :param Operation operation: operation object :param Response response: response object """ path = "#/paths/'{}'/{}/responses/{}".format( operation.path, operat...
[ "def", "get_response_example", "(", "cls", ",", "operation", ",", "response", ")", ":", "path", "=", "\"#/paths/'{}'/{}/responses/{}\"", ".", "format", "(", "operation", ".", "path", ",", "operation", ".", "method", ",", "response", ".", "name", ")", "kwargs",...
Get example for response object by operation object :param Operation operation: operation object :param Response response: response object
[ "Get", "example", "for", "response", "object", "by", "operation", "object" ]
python
train
RedHatInsights/insights-core
insights/contrib/pyparsing.py
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/pyparsing.py#L3683-L3755
def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ): """Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to ...
[ "def", "infixNotation", "(", "baseExpr", ",", "opList", ",", "lpar", "=", "Suppress", "(", "'('", ")", ",", "rpar", "=", "Suppress", "(", "')'", ")", ")", ":", "ret", "=", "Forward", "(", ")", "lastExpr", "=", "baseExpr", "|", "(", "lpar", "+", "re...
Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to operator expressions. Parameters: - baseExpr - expression representing...
[ "Helper", "method", "for", "constructing", "grammars", "of", "expressions", "made", "up", "of", "operators", "working", "in", "a", "precedence", "hierarchy", ".", "Operators", "may", "be", "unary", "or", "binary", "left", "-", "or", "right", "-", "associative"...
python
train
ryan-roemer/django-cloud-browser
cloud_browser/cloud/fs.py
https://github.com/ryan-roemer/django-cloud-browser/blob/b06cdd24885a6309e843ed924dbf1705b67e7f48/cloud_browser/cloud/fs.py#L65-L80
def from_path(cls, container, path): """Create object from path.""" from datetime import datetime path = path.strip(SEP) full_path = os.path.join(container.base_path, path) last_modified = datetime.fromtimestamp(os.path.getmtime(full_path)) obj_type = cls.type_cls.SUBDIR...
[ "def", "from_path", "(", "cls", ",", "container", ",", "path", ")", ":", "from", "datetime", "import", "datetime", "path", "=", "path", ".", "strip", "(", "SEP", ")", "full_path", "=", "os", ".", "path", ".", "join", "(", "container", ".", "base_path",...
Create object from path.
[ "Create", "object", "from", "path", "." ]
python
train
OSSOS/MOP
src/ossos/core/ossos/storage.py
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L138-L212
def cone_search(ra, dec, dra=0.01, ddec=0.01, mjdate=None, calibration_level=2, use_ssos=True, collection='CFHTMEGAPIPE'): """Do a QUERY on the TAP service for all observations that are part of OSSOS (*P05/*P016) where taken after mjd and have calibration 'observable'. @param ra: RA center ...
[ "def", "cone_search", "(", "ra", ",", "dec", ",", "dra", "=", "0.01", ",", "ddec", "=", "0.01", ",", "mjdate", "=", "None", ",", "calibration_level", "=", "2", ",", "use_ssos", "=", "True", ",", "collection", "=", "'CFHTMEGAPIPE'", ")", ":", "if", "u...
Do a QUERY on the TAP service for all observations that are part of OSSOS (*P05/*P016) where taken after mjd and have calibration 'observable'. @param ra: RA center of search cont @type ra: Quantity @param dec: float degrees @type dec: Quantity @param dra: float degrees @type dra: Quantity ...
[ "Do", "a", "QUERY", "on", "the", "TAP", "service", "for", "all", "observations", "that", "are", "part", "of", "OSSOS", "(", "*", "P05", "/", "*", "P016", ")", "where", "taken", "after", "mjd", "and", "have", "calibration", "observable", "." ]
python
train
dineshappavoo/virtdc
vmonere/sockets/vmonere_sender.socket.py
https://github.com/dineshappavoo/virtdc/blob/e61872cdc860092ab7affac8f13a7ca1f9e46a49/vmonere/sockets/vmonere_sender.socket.py#L68-L90
def report_usage_to_host(host_ip, vmid): #base value cpu_usage = 0.0 os_mem_usage = 0.0 task_mem_usage = 0.0 io_usage = 0.0 cpu_usage = get_cpu_usage() os_mem_usage = get_os_mem_usage() task_mem_usage = get_task_mem_usage() io_usage = get_io_usage() usage = str(vmid.strip())+' | '+str(cpu_usage)+' | '+str...
[ "def", "report_usage_to_host", "(", "host_ip", ",", "vmid", ")", ":", "#base value", "cpu_usage", "=", "0.0", "os_mem_usage", "=", "0.0", "task_mem_usage", "=", "0.0", "io_usage", "=", "0.0", "cpu_usage", "=", "get_cpu_usage", "(", ")", "os_mem_usage", "=", "g...
cmd = '/bin/ssh -n -q -o StrictHostKeyChecking=no root@host_ip \"/bin/nohup /bin/python /var/lib/virtdc/vmonere/host/vmonere_listener.py '+usage+' &\"' cmd = cmd.replace("host_ip",str(host_ip).strip())
[ "cmd", "=", "/", "bin", "/", "ssh", "-", "n", "-", "q", "-", "o", "StrictHostKeyChecking", "=", "no", "root" ]
python
train
yoavaviram/python-amazon-simple-product-api
amazon/api.py
https://github.com/yoavaviram/python-amazon-simple-product-api/blob/f1cb0e209145fcfac9444e4c733dd19deb59d31a/amazon/api.py#L795-L816
def creators(self): """Creators. Creators are not the authors. These are usually editors, translators, narrators, etc. :return: Returns a list of creators where each is a tuple containing: 1. The creators name (string). 2. The creators role ...
[ "def", "creators", "(", "self", ")", ":", "# return tuples of name and role", "result", "=", "[", "]", "creators", "=", "self", ".", "_safe_get_element", "(", "'ItemAttributes.Creator'", ")", "if", "creators", "is", "not", "None", ":", "for", "creator", "in", ...
Creators. Creators are not the authors. These are usually editors, translators, narrators, etc. :return: Returns a list of creators where each is a tuple containing: 1. The creators name (string). 2. The creators role (string).
[ "Creators", "." ]
python
train
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAFetch/Fetcher.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/Fetcher.py#L118-L201
def QA_quotation(code, start, end, frequence, market, source=DATASOURCE.TDX, output=OUTPUT_FORMAT.DATAFRAME): """一个统一的获取k线的方法 如果使用mongo,从本地数据库获取,失败则在线获取 Arguments: code {str/list} -- 期货/股票的代码 start {str} -- 开始日期 end {str} -- 结束日期 frequence {enum} -- 频率 QA.FREQUENCE m...
[ "def", "QA_quotation", "(", "code", ",", "start", ",", "end", ",", "frequence", ",", "market", ",", "source", "=", "DATASOURCE", ".", "TDX", ",", "output", "=", "OUTPUT_FORMAT", ".", "DATAFRAME", ")", ":", "res", "=", "None", "if", "market", "==", "MAR...
一个统一的获取k线的方法 如果使用mongo,从本地数据库获取,失败则在线获取 Arguments: code {str/list} -- 期货/股票的代码 start {str} -- 开始日期 end {str} -- 结束日期 frequence {enum} -- 频率 QA.FREQUENCE market {enum} -- 市场 QA.MARKET_TYPE source {enum} -- 来源 QA.DATASOURCE output {enum} -- 输出类型 QA.OUTPUT_F...
[ "一个统一的获取k线的方法", "如果使用mongo", "从本地数据库获取", "失败则在线获取" ]
python
train
PeerAssets/pypeerassets
pypeerassets/transactions.py
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/transactions.py#L259-L267
def tx_output(network: str, value: Decimal, n: int, script: ScriptSig) -> TxOut: '''create TxOut object''' network_params = net_query(network) return TxOut(network=network_params, value=int(value * network_params.to_unit), n=n, script_pubkey=script)
[ "def", "tx_output", "(", "network", ":", "str", ",", "value", ":", "Decimal", ",", "n", ":", "int", ",", "script", ":", "ScriptSig", ")", "->", "TxOut", ":", "network_params", "=", "net_query", "(", "network", ")", "return", "TxOut", "(", "network", "=...
create TxOut object
[ "create", "TxOut", "object" ]
python
train
GoogleCloudPlatform/appengine-mapreduce
python/src/mapreduce/datastore_range_iterators.py
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/datastore_range_iterators.py#L405-L419
def to_json(self): """Serializes all states into json form. Returns: all states in json-compatible map. """ cursor = self._get_cursor() cursor_object = False if cursor and isinstance(cursor, datastore_query.Cursor): cursor = cursor.to_websafe_string() cursor_object = True ...
[ "def", "to_json", "(", "self", ")", ":", "cursor", "=", "self", ".", "_get_cursor", "(", ")", "cursor_object", "=", "False", "if", "cursor", "and", "isinstance", "(", "cursor", ",", "datastore_query", ".", "Cursor", ")", ":", "cursor", "=", "cursor", "."...
Serializes all states into json form. Returns: all states in json-compatible map.
[ "Serializes", "all", "states", "into", "json", "form", "." ]
python
train
openid/python-openid
openid/server/server.py
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1262-L1295
def getAssociation(self, assoc_handle, dumb, checkExpiration=True): """Get the association with the specified handle. @type assoc_handle: str @param dumb: Is this association used with dumb mode? @type dumb: bool @returns: the association, or None if no valid association with ...
[ "def", "getAssociation", "(", "self", ",", "assoc_handle", ",", "dumb", ",", "checkExpiration", "=", "True", ")", ":", "# Hmm. We've created an interface that deals almost entirely with", "# assoc_handles. The only place outside the Signatory that uses this", "# (and thus the only ...
Get the association with the specified handle. @type assoc_handle: str @param dumb: Is this association used with dumb mode? @type dumb: bool @returns: the association, or None if no valid association with that handle was found. @returntype: L{openid.association.As...
[ "Get", "the", "association", "with", "the", "specified", "handle", "." ]
python
train
orbingol/NURBS-Python
geomdl/multi.py
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/multi.py#L1080-L1111
def select_color(cpcolor, evalcolor, idx=0): """ Selects item color for plotting. :param cpcolor: color for control points grid item :type cpcolor: str, list, tuple :param evalcolor: color for evaluated points grid item :type evalcolor: str, list, tuple :param idx: index of the current geometry...
[ "def", "select_color", "(", "cpcolor", ",", "evalcolor", ",", "idx", "=", "0", ")", ":", "# Random colors by default", "color", "=", "utilities", ".", "color_generator", "(", ")", "# Constant color for control points grid", "if", "isinstance", "(", "cpcolor", ",", ...
Selects item color for plotting. :param cpcolor: color for control points grid item :type cpcolor: str, list, tuple :param evalcolor: color for evaluated points grid item :type evalcolor: str, list, tuple :param idx: index of the current geometry object :type idx: int :return: a list of col...
[ "Selects", "item", "color", "for", "plotting", "." ]
python
train
rchatterjee/pwmodels
src/pwmodel/models.py
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/models.py#L25-L81
def create_model(modelfunc, fname='', listw=[], outfname='', limit=int(3e6), min_pwlen=6, topk=10000, sep=r'\s+'): """:modelfunc: is a function that takes a word and returns its splits. for ngram model this function returns all the ngrams of a word, for PCFG it will return splits of the pa...
[ "def", "create_model", "(", "modelfunc", ",", "fname", "=", "''", ",", "listw", "=", "[", "]", ",", "outfname", "=", "''", ",", "limit", "=", "int", "(", "3e6", ")", ",", "min_pwlen", "=", "6", ",", "topk", "=", "10000", ",", "sep", "=", "r'\\s+'...
:modelfunc: is a function that takes a word and returns its splits. for ngram model this function returns all the ngrams of a word, for PCFG it will return splits of the password. @modelfunc: func: string -> [list of strings] @fname: name of the file to read from @listw: list of passwords. Used pas...
[ ":", "modelfunc", ":", "is", "a", "function", "that", "takes", "a", "word", "and", "returns", "its", "splits", ".", "for", "ngram", "model", "this", "function", "returns", "all", "the", "ngrams", "of", "a", "word", "for", "PCFG", "it", "will", "return", ...
python
train
blockstack/blockstack-core
api/resolver.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/api/resolver.py#L250-L281
def get_users(username): """ Fetch data from username in .id namespace """ reply = {} log.debug('Begin /v[x]/users/' + username) if username is None: reply['error'] = "No username given" return jsonify(reply), 404 if ',' in username: reply['error'] = 'Multiple username...
[ "def", "get_users", "(", "username", ")", ":", "reply", "=", "{", "}", "log", ".", "debug", "(", "'Begin /v[x]/users/'", "+", "username", ")", "if", "username", "is", "None", ":", "reply", "[", "'error'", "]", "=", "\"No username given\"", "return", "jsoni...
Fetch data from username in .id namespace
[ "Fetch", "data", "from", "username", "in", ".", "id", "namespace" ]
python
train
twilio/twilio-python
twilio/rest/api/v2010/account/new_key.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/new_key.py#L83-L92
def get_instance(self, payload): """ Build an instance of NewKeyInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.new_key.NewKeyInstance :rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance """ return New...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "NewKeyInstance", "(", "self", ".", "_version", ",", "payload", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ")" ]
Build an instance of NewKeyInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.new_key.NewKeyInstance :rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance
[ "Build", "an", "instance", "of", "NewKeyInstance" ]
python
train
gpiantoni/bidso
bidso/files.py
https://github.com/gpiantoni/bidso/blob/af163b921ec4e3d70802de07f174de184491cfce/bidso/files.py#L37-L87
def get_filename(self, base_dir=None, modality=None): """Construct filename based on the attributes. Parameters ---------- base_dir : Path path of the root directory. If specified, the return value is a Path, with base_dir / sub-XXX / (ses-XXX /) modality / filen...
[ "def", "get_filename", "(", "self", ",", "base_dir", "=", "None", ",", "modality", "=", "None", ")", ":", "filename", "=", "'sub-'", "+", "self", ".", "subject", "if", "self", ".", "session", "is", "not", "None", ":", "filename", "+=", "'_ses-'", "+", ...
Construct filename based on the attributes. Parameters ---------- base_dir : Path path of the root directory. If specified, the return value is a Path, with base_dir / sub-XXX / (ses-XXX /) modality / filename otherwise the return value is a string. m...
[ "Construct", "filename", "based", "on", "the", "attributes", "." ]
python
train
juju/charm-helpers
charmhelpers/contrib/mellanox/infiniband.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/mellanox/infiniband.py#L137-L153
def ipoib_interfaces(): """Return a list of IPOIB capable ethernet interfaces""" interfaces = [] for interface in network_interfaces(): try: driver = re.search('^driver: (.+)$', subprocess.check_output([ 'ethtool', '-i', interface]), re.M).group(1) ...
[ "def", "ipoib_interfaces", "(", ")", ":", "interfaces", "=", "[", "]", "for", "interface", "in", "network_interfaces", "(", ")", ":", "try", ":", "driver", "=", "re", ".", "search", "(", "'^driver: (.+)$'", ",", "subprocess", ".", "check_output", "(", "[",...
Return a list of IPOIB capable ethernet interfaces
[ "Return", "a", "list", "of", "IPOIB", "capable", "ethernet", "interfaces" ]
python
train
awacha/sastool
sastool/fitting/fitfunctions/basic.py
https://github.com/awacha/sastool/blob/deaddfa3002f3f6818697e36139633b7e30427a3/sastool/fitting/fitfunctions/basic.py#L110-L124
def Exponential(x, a, tau, y0): """Exponential function Inputs: ------- ``x``: independent variable ``a``: scaling factor ``tau``: time constant ``y0``: additive constant Formula: -------- ``a*exp(x/tau)+y0`` """ return np.exp(x / tau) * a + y0
[ "def", "Exponential", "(", "x", ",", "a", ",", "tau", ",", "y0", ")", ":", "return", "np", ".", "exp", "(", "x", "/", "tau", ")", "*", "a", "+", "y0" ]
Exponential function Inputs: ------- ``x``: independent variable ``a``: scaling factor ``tau``: time constant ``y0``: additive constant Formula: -------- ``a*exp(x/tau)+y0``
[ "Exponential", "function" ]
python
train
emory-libraries/eulcommon
eulcommon/djangoextras/auth/decorators.py
https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/djangoextras/auth/decorators.py#L132-L147
def permission_required_with_ajax(perm, login_url=None): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary, but returns a special response for ajax requests. See :meth:`eulcore.django.auth.decorators.user_passes_test_...
[ "def", "permission_required_with_ajax", "(", "perm", ",", "login_url", "=", "None", ")", ":", "return", "user_passes_test_with_ajax", "(", "lambda", "u", ":", "u", ".", "has_perm", "(", "perm", ")", ",", "login_url", "=", "login_url", ")" ]
Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary, but returns a special response for ajax requests. See :meth:`eulcore.django.auth.decorators.user_passes_test_with_ajax`. Usage is the same as :meth:`django.contrib.auth....
[ "Decorator", "for", "views", "that", "checks", "whether", "a", "user", "has", "a", "particular", "permission", "enabled", "redirecting", "to", "the", "log", "-", "in", "page", "if", "necessary", "but", "returns", "a", "special", "response", "for", "ajax", "r...
python
train
jazzband/django-ddp
dddp/__init__.py
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/__init__.py#L180-L185
def autodiscover(): """Import all `ddp` submodules from `settings.INSTALLED_APPS`.""" from django.utils.module_loading import autodiscover_modules from dddp.api import API autodiscover_modules('ddp', register_to=API) return API
[ "def", "autodiscover", "(", ")", ":", "from", "django", ".", "utils", ".", "module_loading", "import", "autodiscover_modules", "from", "dddp", ".", "api", "import", "API", "autodiscover_modules", "(", "'ddp'", ",", "register_to", "=", "API", ")", "return", "AP...
Import all `ddp` submodules from `settings.INSTALLED_APPS`.
[ "Import", "all", "ddp", "submodules", "from", "settings", ".", "INSTALLED_APPS", "." ]
python
test
offu/WeRoBot
werobot/robot.py
https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/robot.py#L556-L573
def parse_message( self, body, timestamp=None, nonce=None, msg_signature=None ): """ 解析获取到的 Raw XML ,如果需要的话进行解密,返回 WeRoBot Message。 :param body: 微信服务器发来的请求中的 Body。 :return: WeRoBot Message """ message_dict = parse_xml(body) if "Encrypt" in message_dict...
[ "def", "parse_message", "(", "self", ",", "body", ",", "timestamp", "=", "None", ",", "nonce", "=", "None", ",", "msg_signature", "=", "None", ")", ":", "message_dict", "=", "parse_xml", "(", "body", ")", "if", "\"Encrypt\"", "in", "message_dict", ":", "...
解析获取到的 Raw XML ,如果需要的话进行解密,返回 WeRoBot Message。 :param body: 微信服务器发来的请求中的 Body。 :return: WeRoBot Message
[ "解析获取到的", "Raw", "XML", ",如果需要的话进行解密,返回", "WeRoBot", "Message。", ":", "param", "body", ":", "微信服务器发来的请求中的", "Body。", ":", "return", ":", "WeRoBot", "Message" ]
python
train
quantmind/pulsar
pulsar/utils/config.py
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/config.py#L184-L195
def update(self, data, default=False): """Update this :attr:`Config` with ``data``. :param data: must be a ``Mapping`` like object exposing the ``item`` method for iterating through key-value pairs. :param default: if ``True`` the updated :attr:`settings` will also set t...
[ "def", "update", "(", "self", ",", "data", ",", "default", "=", "False", ")", ":", "for", "name", ",", "value", "in", "data", ".", "items", "(", ")", ":", "if", "value", "is", "not", "None", ":", "self", ".", "set", "(", "name", ",", "value", "...
Update this :attr:`Config` with ``data``. :param data: must be a ``Mapping`` like object exposing the ``item`` method for iterating through key-value pairs. :param default: if ``True`` the updated :attr:`settings` will also set their :attr:`~Setting.default` attribute with the ...
[ "Update", "this", ":", "attr", ":", "Config", "with", "data", "." ]
python
train
payu-org/payu
payu/calendar.py
https://github.com/payu-org/payu/blob/1442a9a226012eff248b8097cc1eaabc3e224867/payu/calendar.py#L7-L16
def int_to_date(date): """ Convert an int of form yyyymmdd to a python date object. """ year = date // 10**4 month = date % 10**4 // 10**2 day = date % 10**2 return datetime.date(year, month, day)
[ "def", "int_to_date", "(", "date", ")", ":", "year", "=", "date", "//", "10", "**", "4", "month", "=", "date", "%", "10", "**", "4", "//", "10", "**", "2", "day", "=", "date", "%", "10", "**", "2", "return", "datetime", ".", "date", "(", "year"...
Convert an int of form yyyymmdd to a python date object.
[ "Convert", "an", "int", "of", "form", "yyyymmdd", "to", "a", "python", "date", "object", "." ]
python
train
brunato/lograptor
lograptor/cache.py
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/cache.py#L139-L164
def gethost(self, ip_addr): """ Do reverse lookup on an ip address """ # Handle silly fake ipv6 addresses try: if ip_addr[:7] == '::ffff:': ip_addr = ip_addr[7:] except TypeError: pass if ip_addr[0] in string.letters: ...
[ "def", "gethost", "(", "self", ",", "ip_addr", ")", ":", "# Handle silly fake ipv6 addresses", "try", ":", "if", "ip_addr", "[", ":", "7", "]", "==", "'::ffff:'", ":", "ip_addr", "=", "ip_addr", "[", "7", ":", "]", "except", "TypeError", ":", "pass", "if...
Do reverse lookup on an ip address
[ "Do", "reverse", "lookup", "on", "an", "ip", "address" ]
python
train
xtrementl/focus
focus/environment/__init__.py
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/environment/__init__.py#L125-L136
def _setup_task(self, load): """ Sets up the ``Task`` object and loads active file for task. `load` Set to ``True`` to load task after setup. """ if not self._task: self._task = Task(self._data_dir) if load: self._task.load()
[ "def", "_setup_task", "(", "self", ",", "load", ")", ":", "if", "not", "self", ".", "_task", ":", "self", ".", "_task", "=", "Task", "(", "self", ".", "_data_dir", ")", "if", "load", ":", "self", ".", "_task", ".", "load", "(", ")" ]
Sets up the ``Task`` object and loads active file for task. `load` Set to ``True`` to load task after setup.
[ "Sets", "up", "the", "Task", "object", "and", "loads", "active", "file", "for", "task", "." ]
python
train
artizirk/python-axp209
axp209.py
https://github.com/artizirk/python-axp209/blob/dc48015b23ea3695bf1ee076355c96ea434b77e4/axp209.py#L207-L214
def battery_discharge_current(self): """ Returns current in mA """ msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_DISCHARGE_CURRENT_MSB_REG) lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_DISCHARGE_CURRENT_LSB_REG) # 13bits discharge_bin = msb << 5 | lsb & 0x1f ...
[ "def", "battery_discharge_current", "(", "self", ")", ":", "msb", "=", "self", ".", "bus", ".", "read_byte_data", "(", "AXP209_ADDRESS", ",", "BATTERY_DISCHARGE_CURRENT_MSB_REG", ")", "lsb", "=", "self", ".", "bus", ".", "read_byte_data", "(", "AXP209_ADDRESS", ...
Returns current in mA
[ "Returns", "current", "in", "mA" ]
python
train
edx/edx-enterprise
enterprise/utils.py
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L446-L467
def update_query_parameters(url, query_parameters): """ Return url with updated query parameters. Arguments: url (str): Original url whose query parameters need to be updated. query_parameters (dict): A dictionary containing query parameters to be added to course selection url. Returns...
[ "def", "update_query_parameters", "(", "url", ",", "query_parameters", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "query_string", ",", "fragment", "=", "urlsplit", "(", "url", ")", "url_params", "=", "parse_qs", "(", "query_string", ")", "# Update ur...
Return url with updated query parameters. Arguments: url (str): Original url whose query parameters need to be updated. query_parameters (dict): A dictionary containing query parameters to be added to course selection url. Returns: (slug): slug identifier for the identity provider that...
[ "Return", "url", "with", "updated", "query", "parameters", "." ]
python
valid
Opentrons/opentrons
api/src/opentrons/protocol_api/contexts.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/contexts.py#L146-L166
def temp_connect(self, hardware: hc.API): """ Connect temporarily to the specified hardware controller. This should be used as a context manager: .. code-block :: python with ctx.temp_connect(hw): # do some tasks ctx.home() # after the w...
[ "def", "temp_connect", "(", "self", ",", "hardware", ":", "hc", ".", "API", ")", ":", "old_hw", "=", "self", ".", "_hw_manager", ".", "hardware", "try", ":", "self", ".", "_hw_manager", ".", "set_hw", "(", "hardware", ")", "yield", "self", "finally", "...
Connect temporarily to the specified hardware controller. This should be used as a context manager: .. code-block :: python with ctx.temp_connect(hw): # do some tasks ctx.home() # after the with block, the context is connected to the same ...
[ "Connect", "temporarily", "to", "the", "specified", "hardware", "controller", "." ]
python
train
blockstack/blockstack-core
blockstack/lib/operations/__init__.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/operations/__init__.py#L360-L370
def op_get_consensus_fields( op_name ): """ Get the set of consensus-generating fields for an operation. """ global SERIALIZE_FIELDS if op_name not in SERIALIZE_FIELDS.keys(): raise Exception("No such operation '%s'" % op_name ) fields = SERIALIZE_FIELDS[op_name][:] return fiel...
[ "def", "op_get_consensus_fields", "(", "op_name", ")", ":", "global", "SERIALIZE_FIELDS", "if", "op_name", "not", "in", "SERIALIZE_FIELDS", ".", "keys", "(", ")", ":", "raise", "Exception", "(", "\"No such operation '%s'\"", "%", "op_name", ")", "fields", "=", "...
Get the set of consensus-generating fields for an operation.
[ "Get", "the", "set", "of", "consensus", "-", "generating", "fields", "for", "an", "operation", "." ]
python
train
brocade/pynos
pynos/versions/base/interface.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/interface.py#L299-L344
def remove_port_channel(self, **kwargs): """ Remove a port channel interface. Args: port_int (str): port-channel number (1, 2, 3, etc). callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will ...
[ "def", "remove_port_channel", "(", "self", ",", "*", "*", "kwargs", ")", ":", "port_int", "=", "kwargs", ".", "pop", "(", "'port_int'", ")", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ",", "self", ".", "_callback", ")", "if", "re", ".", ...
Remove a port channel interface. Args: port_int (str): port-channel number (1, 2, 3, etc). callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Re...
[ "Remove", "a", "port", "channel", "interface", "." ]
python
train
rfosterslo/wagtailplus
wagtailplus/wagtailrelations/models.py
https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtailrelations/models.py#L343-L356
def for_category(self, category, live_only=False): """ Returns queryset of EntryTag instances for specified category. :param category: the Category instance. :param live_only: flag to include only "live" entries. :rtype: django.db.models.query.QuerySet. """ filte...
[ "def", "for_category", "(", "self", ",", "category", ",", "live_only", "=", "False", ")", ":", "filters", "=", "{", "'tag'", ":", "category", ".", "tag", "}", "if", "live_only", ":", "filters", ".", "update", "(", "{", "'entry__live'", ":", "True", "}"...
Returns queryset of EntryTag instances for specified category. :param category: the Category instance. :param live_only: flag to include only "live" entries. :rtype: django.db.models.query.QuerySet.
[ "Returns", "queryset", "of", "EntryTag", "instances", "for", "specified", "category", "." ]
python
train
bunq/sdk_python
bunq/sdk/model/generated/endpoint.py
https://github.com/bunq/sdk_python/blob/da6c9b83e6d83ee8062617f53c6eb7293c0d863d/bunq/sdk/model/generated/endpoint.py#L29642-L29788
def update(cls, first_name=None, middle_name=None, last_name=None, public_nick_name=None, address_main=None, address_postal=None, avatar_uuid=None, tax_resident=None, document_type=None, document_number=None, document_country_of_issuance=None, document_front_a...
[ "def", "update", "(", "cls", ",", "first_name", "=", "None", ",", "middle_name", "=", "None", ",", "last_name", "=", "None", ",", "public_nick_name", "=", "None", ",", "address_main", "=", "None", ",", "address_postal", "=", "None", ",", "avatar_uuid", "="...
Modify a specific person object's data. :type user_person_id: int :param first_name: The person's first name. :type first_name: str :param middle_name: The person's middle name. :type middle_name: str :param last_name: The person's last name. :type last_name: str...
[ "Modify", "a", "specific", "person", "object", "s", "data", "." ]
python
train
riga/tfdeploy
tfdeploy.py
https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L1070-L1078
def RandomShuffle(a, seed): """ Random uniform op. """ if seed: np.random.seed(seed) r = a.copy() np.random.shuffle(r) return r,
[ "def", "RandomShuffle", "(", "a", ",", "seed", ")", ":", "if", "seed", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "r", "=", "a", ".", "copy", "(", ")", "np", ".", "random", ".", "shuffle", "(", "r", ")", "return", "r", "," ]
Random uniform op.
[ "Random", "uniform", "op", "." ]
python
train
wndhydrnt/python-oauth2
oauth2/store/dbapi/__init__.py
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/store/dbapi/__init__.py#L118-L138
def fetch_by_refresh_token(self, refresh_token): """ Retrieves an access token by its refresh token. :param refresh_token: The refresh token of an access token as a `str`. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNo...
[ "def", "fetch_by_refresh_token", "(", "self", ",", "refresh_token", ")", ":", "row", "=", "self", ".", "fetchone", "(", "self", ".", "fetch_by_refresh_token_query", ",", "refresh_token", ")", "if", "row", "is", "None", ":", "raise", "AccessTokenNotFound", "scope...
Retrieves an access token by its refresh token. :param refresh_token: The refresh token of an access token as a `str`. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNotFound` if not access token could be retrieved.
[ "Retrieves", "an", "access", "token", "by", "its", "refresh", "token", "." ]
python
train
bird-house/twitcher
twitcher/tokengenerator.py
https://github.com/bird-house/twitcher/blob/e6a36b3aeeacf44eec537434b0fb87c09ab54b5f/twitcher/tokengenerator.py#L22-L34
def create_access_token(self, valid_in_hours=1, data=None): """ Creates an access token. TODO: check valid in hours TODO: maybe specify how often a token can be used """ data = data or {} token = AccessToken( token=self.generate(), expires...
[ "def", "create_access_token", "(", "self", ",", "valid_in_hours", "=", "1", ",", "data", "=", "None", ")", ":", "data", "=", "data", "or", "{", "}", "token", "=", "AccessToken", "(", "token", "=", "self", ".", "generate", "(", ")", ",", "expires_at", ...
Creates an access token. TODO: check valid in hours TODO: maybe specify how often a token can be used
[ "Creates", "an", "access", "token", "." ]
python
valid
miLibris/flask-rest-jsonapi
flask_rest_jsonapi/data_layers/filtering/alchemy.py
https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L41-L62
def resolve(self): """Create filter for a particular node of the filter tree""" if 'or' not in self.filter_ and 'and' not in self.filter_ and 'not' not in self.filter_: value = self.value if isinstance(value, dict): value = Node(self.related_model, value, self.re...
[ "def", "resolve", "(", "self", ")", ":", "if", "'or'", "not", "in", "self", ".", "filter_", "and", "'and'", "not", "in", "self", ".", "filter_", "and", "'not'", "not", "in", "self", ".", "filter_", ":", "value", "=", "self", ".", "value", "if", "is...
Create filter for a particular node of the filter tree
[ "Create", "filter", "for", "a", "particular", "node", "of", "the", "filter", "tree" ]
python
train
blockstack/blockstack-core
blockstack/lib/atlas.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/atlas.py#L1191-L1213
def atlasdb_get_old_peers( now, con=None, path=None ): """ Get peers older than now - PEER_LIFETIME """ with AtlasDBOpen(con=con, path=path) as dbcon: if now is None: now = time.time() expire = now - atlas_peer_max_age() sql = "SELECT * FROM peers WHERE discovery_ti...
[ "def", "atlasdb_get_old_peers", "(", "now", ",", "con", "=", "None", ",", "path", "=", "None", ")", ":", "with", "AtlasDBOpen", "(", "con", "=", "con", ",", "path", "=", "path", ")", "as", "dbcon", ":", "if", "now", "is", "None", ":", "now", "=", ...
Get peers older than now - PEER_LIFETIME
[ "Get", "peers", "older", "than", "now", "-", "PEER_LIFETIME" ]
python
train
osrg/ryu
ryu/lib/ovs/bridge.py
https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/ovs/bridge.py#L425-L433
def add_gre_port(self, name, remote_ip, local_ip=None, key=None, ofport=None): """ Creates a GRE tunnel port. See the description of ``add_tunnel_port()``. """ self.add_tunnel_port(name, 'gre', remote_ip, local_ip=local_ip, key=k...
[ "def", "add_gre_port", "(", "self", ",", "name", ",", "remote_ip", ",", "local_ip", "=", "None", ",", "key", "=", "None", ",", "ofport", "=", "None", ")", ":", "self", ".", "add_tunnel_port", "(", "name", ",", "'gre'", ",", "remote_ip", ",", "local_ip"...
Creates a GRE tunnel port. See the description of ``add_tunnel_port()``.
[ "Creates", "a", "GRE", "tunnel", "port", "." ]
python
train
robertmartin8/PyPortfolioOpt
pypfopt/risk_models.py
https://github.com/robertmartin8/PyPortfolioOpt/blob/dfad1256cb6995c7fbd7a025eedb54b1ca04b2fc/pypfopt/risk_models.py#L182-L195
def format_and_annualise(self, raw_cov_array): """ Helper method which annualises the output of shrinkage calculations, and formats the result into a dataframe :param raw_cov_array: raw covariance matrix of daily returns :type raw_cov_array: np.ndarray :return: annualise...
[ "def", "format_and_annualise", "(", "self", ",", "raw_cov_array", ")", ":", "assets", "=", "self", ".", "X", ".", "columns", "return", "(", "pd", ".", "DataFrame", "(", "raw_cov_array", ",", "index", "=", "assets", ",", "columns", "=", "assets", ")", "*"...
Helper method which annualises the output of shrinkage calculations, and formats the result into a dataframe :param raw_cov_array: raw covariance matrix of daily returns :type raw_cov_array: np.ndarray :return: annualised covariance matrix :rtype: pd.DataFrame
[ "Helper", "method", "which", "annualises", "the", "output", "of", "shrinkage", "calculations", "and", "formats", "the", "result", "into", "a", "dataframe" ]
python
train
Neurita/boyle
boyle/utils/logger.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/logger.py#L13-L31
def setup_logging(log_config_file=op.join(op.dirname(__file__), 'logger.yml'), log_default_level=LOG_LEVEL, env_key=MODULE_NAME.upper() + '_LOG_CFG'): """Setup logging configuration.""" path = log_config_file value = os.getenv(env_key, None) if value: path = v...
[ "def", "setup_logging", "(", "log_config_file", "=", "op", ".", "join", "(", "op", ".", "dirname", "(", "__file__", ")", ",", "'logger.yml'", ")", ",", "log_default_level", "=", "LOG_LEVEL", ",", "env_key", "=", "MODULE_NAME", ".", "upper", "(", ")", "+", ...
Setup logging configuration.
[ "Setup", "logging", "configuration", "." ]
python
valid
tcalmant/ipopo
pelix/ipopo/waiting.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/waiting.py#L172-L197
def handle_ipopo_event(self, event): # type: (IPopoEvent) -> None """ Handles an iPOPO event :param event: iPOPO event bean """ kind = event.get_kind() if kind == IPopoEvent.REGISTERED: # A factory has been registered try: ...
[ "def", "handle_ipopo_event", "(", "self", ",", "event", ")", ":", "# type: (IPopoEvent) -> None", "kind", "=", "event", ".", "get_kind", "(", ")", "if", "kind", "==", "IPopoEvent", ".", "REGISTERED", ":", "# A factory has been registered", "try", ":", "with", "u...
Handles an iPOPO event :param event: iPOPO event bean
[ "Handles", "an", "iPOPO", "event" ]
python
train
log2timeline/plaso
plaso/output/json_out.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/output/json_out.py#L31-L50
def WriteEventBody(self, event): """Writes the body of an event object to the output. Args: event (EventObject): event. """ inode = getattr(event, 'inode', None) if inode is None: event.inode = 0 json_dict = self._JSON_SERIALIZER.WriteSerializedDict(event) json_string = json.du...
[ "def", "WriteEventBody", "(", "self", ",", "event", ")", ":", "inode", "=", "getattr", "(", "event", ",", "'inode'", ",", "None", ")", "if", "inode", "is", "None", ":", "event", ".", "inode", "=", "0", "json_dict", "=", "self", ".", "_JSON_SERIALIZER",...
Writes the body of an event object to the output. Args: event (EventObject): event.
[ "Writes", "the", "body", "of", "an", "event", "object", "to", "the", "output", "." ]
python
train
Miserlou/SoundScrape
soundscrape/soundscrape.py
https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L307-L366
def download_track(track, album_name=u'', keep_previews=False, folders=False, filenames=[], custom_path=''): """ Given a track, force scrape it. """ hard_track_url = get_hard_track_url(track['id']) # We have no info on this track whatsoever. if not 'title' in track: return None if...
[ "def", "download_track", "(", "track", ",", "album_name", "=", "u''", ",", "keep_previews", "=", "False", ",", "folders", "=", "False", ",", "filenames", "=", "[", "]", ",", "custom_path", "=", "''", ")", ":", "hard_track_url", "=", "get_hard_track_url", "...
Given a track, force scrape it.
[ "Given", "a", "track", "force", "scrape", "it", "." ]
python
train
dev-pipeline/dev-pipeline-build
lib/devpipeline_build/builder.py
https://github.com/dev-pipeline/dev-pipeline-build/blob/52e3e22b1c433fb7c3902acc46d6f3ac2c6fc426/lib/devpipeline_build/builder.py#L93-L106
def _make_builder(config, current_target): """ Create and return a Builder for a component. Arguments component - The component the builder should be created for. """ tool_key = devpipeline_core.toolsupport.choose_tool_key( current_target, _BUILD_TOOL_KEYS ) return devpipeline_...
[ "def", "_make_builder", "(", "config", ",", "current_target", ")", ":", "tool_key", "=", "devpipeline_core", ".", "toolsupport", ".", "choose_tool_key", "(", "current_target", ",", "_BUILD_TOOL_KEYS", ")", "return", "devpipeline_core", ".", "toolsupport", ".", "tool...
Create and return a Builder for a component. Arguments component - The component the builder should be created for.
[ "Create", "and", "return", "a", "Builder", "for", "a", "component", "." ]
python
train
PyCQA/pylint
pylint/checkers/refactoring.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/refactoring.py#L611-L614
def _check_exception_inherit_from_stopiteration(exc): """Return True if the exception node in argument inherit from StopIteration""" stopiteration_qname = "{}.StopIteration".format(utils.EXCEPTIONS_MODULE) return any(_class.qname() == stopiteration_qname for _class in exc.mro())
[ "def", "_check_exception_inherit_from_stopiteration", "(", "exc", ")", ":", "stopiteration_qname", "=", "\"{}.StopIteration\"", ".", "format", "(", "utils", ".", "EXCEPTIONS_MODULE", ")", "return", "any", "(", "_class", ".", "qname", "(", ")", "==", "stopiteration_q...
Return True if the exception node in argument inherit from StopIteration
[ "Return", "True", "if", "the", "exception", "node", "in", "argument", "inherit", "from", "StopIteration" ]
python
test
ranaroussi/qtpylib
qtpylib/indicators.py
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L339-L349
def vwap(bars): """ calculate vwap of entire time series (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] """ typical = ((bars['high'] + bars['low'] + bars['close']) / 3).values volume = bars['volume'].values return pd.Series(index=ba...
[ "def", "vwap", "(", "bars", ")", ":", "typical", "=", "(", "(", "bars", "[", "'high'", "]", "+", "bars", "[", "'low'", "]", "+", "bars", "[", "'close'", "]", ")", "/", "3", ")", ".", "values", "volume", "=", "bars", "[", "'volume'", "]", ".", ...
calculate vwap of entire time series (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ]
[ "calculate", "vwap", "of", "entire", "time", "series", "(", "input", "can", "be", "pandas", "series", "or", "numpy", "array", ")", "bars", "are", "usually", "mid", "[", "(", "h", "+", "l", ")", "/", "2", "]", "or", "typical", "[", "(", "h", "+", ...
python
train
genialis/resolwe-runtime-utils
resolwe_runtime_utils.py
https://github.com/genialis/resolwe-runtime-utils/blob/5657d7cf981972a5259b9b475eae220479401001/resolwe_runtime_utils.py#L146-L173
def save_dir(key, dir_path, *refs): """Convert the given parameters to a special JSON object. JSON object is of the form: { key: {"dir": dir_path}}, or { key: {"dir": dir_path, "refs": [refs[0], refs[1], ... ]}} """ if not os.path.isdir(dir_path): return error( "Output '{}'...
[ "def", "save_dir", "(", "key", ",", "dir_path", ",", "*", "refs", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", ":", "return", "error", "(", "\"Output '{}' set to a missing directory: '{}'.\"", ".", "format", "(", "key", ","...
Convert the given parameters to a special JSON object. JSON object is of the form: { key: {"dir": dir_path}}, or { key: {"dir": dir_path, "refs": [refs[0], refs[1], ... ]}}
[ "Convert", "the", "given", "parameters", "to", "a", "special", "JSON", "object", "." ]
python
train
rigetti/pyquil
pyquil/quil.py
https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quil.py#L194-L211
def gate(self, name, params, qubits): """ Add a gate to the program. .. note:: The matrix elements along each axis are ordered by bitstring. For two qubits the order is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index, i.e...
[ "def", "gate", "(", "self", ",", "name", ",", "params", ",", "qubits", ")", ":", "return", "self", ".", "inst", "(", "Gate", "(", "name", ",", "params", ",", "[", "unpack_qubit", "(", "q", ")", "for", "q", "in", "qubits", "]", ")", ")" ]
Add a gate to the program. .. note:: The matrix elements along each axis are ordered by bitstring. For two qubits the order is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index, i.e., for qubits 0 and 1 the bitstring ``01`` indicates that ...
[ "Add", "a", "gate", "to", "the", "program", "." ]
python
train
bhmm/bhmm
bhmm/output_models/gaussian.py
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L382-L418
def generate_observation_trajectory(self, s_t): """ Generate synthetic observation data from a given state sequence. Parameters ---------- s_t : numpy.array with shape (T,) of int type s_t[t] is the hidden state sampled at time t Returns ------- ...
[ "def", "generate_observation_trajectory", "(", "self", ",", "s_t", ")", ":", "# Determine number of samples to generate.", "T", "=", "s_t", ".", "shape", "[", "0", "]", "o_t", "=", "np", ".", "zeros", "(", "[", "T", "]", ",", "dtype", "=", "config", ".", ...
Generate synthetic observation data from a given state sequence. Parameters ---------- s_t : numpy.array with shape (T,) of int type s_t[t] is the hidden state sampled at time t Returns ------- o_t : numpy.array with shape (T,) of type dtype o_t[...
[ "Generate", "synthetic", "observation", "data", "from", "a", "given", "state", "sequence", "." ]
python
train
globocom/GloboNetworkAPI-client-python
networkapiclient/ApiVrf.py
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiVrf.py#L66-L75
def delete(self, ids): """ Method to delete vrf's by their id's :param ids: Identifiers of vrf's :return: None """ url = build_uri_with_ids('api/v3/vrf/%s/', ids) return super(ApiVrf, self).delete(url)
[ "def", "delete", "(", "self", ",", "ids", ")", ":", "url", "=", "build_uri_with_ids", "(", "'api/v3/vrf/%s/'", ",", "ids", ")", "return", "super", "(", "ApiVrf", ",", "self", ")", ".", "delete", "(", "url", ")" ]
Method to delete vrf's by their id's :param ids: Identifiers of vrf's :return: None
[ "Method", "to", "delete", "vrf", "s", "by", "their", "id", "s" ]
python
train
google/grumpy
third_party/stdlib/threading.py
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/threading.py#L309-L371
def wait(self, timeout=None): """Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method releases the underlying lock, and then blocks until it is awakened by a notify() or ...
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "_is_owned", "(", ")", ":", "raise", "RuntimeError", "(", "\"cannot wait on un-acquired lock\"", ")", "waiter", "=", "_allocate_lock", "(", ")", "waiter", ".", "ac...
Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method releases the underlying lock, and then blocks until it is awakened by a notify() or notifyAll() call for the same condition ...
[ "Wait", "until", "notified", "or", "until", "a", "timeout", "occurs", "." ]
python
valid
ejeschke/ginga
ginga/rv/plugins/TVMark.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/plugins/TVMark.py#L678-L686
def set_marktype_cb(self, w, index): """Set type of marking.""" self.marktype = self._mark_options[index] # Mark size is not used for point if self.marktype != 'point': self.w.mark_size.set_enabled(True) else: self.w.mark_size.set_enabled(False)
[ "def", "set_marktype_cb", "(", "self", ",", "w", ",", "index", ")", ":", "self", ".", "marktype", "=", "self", ".", "_mark_options", "[", "index", "]", "# Mark size is not used for point", "if", "self", ".", "marktype", "!=", "'point'", ":", "self", ".", "...
Set type of marking.
[ "Set", "type", "of", "marking", "." ]
python
train
zarr-developers/zarr
zarr/hierarchy.py
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L858-L861
def empty(self, name, **kwargs): """Create an array. Keyword arguments as per :func:`zarr.creation.empty`.""" return self._write_op(self._empty_nosync, name, **kwargs)
[ "def", "empty", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_write_op", "(", "self", ".", "_empty_nosync", ",", "name", ",", "*", "*", "kwargs", ")" ]
Create an array. Keyword arguments as per :func:`zarr.creation.empty`.
[ "Create", "an", "array", ".", "Keyword", "arguments", "as", "per", ":", "func", ":", "zarr", ".", "creation", ".", "empty", "." ]
python
train