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
pywbem/pywbem
try/run_central_instances.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L488-L505
def get_associated_profiles(profile_path, result_role, server): """ Get the associated CIM_ReferencedProfile (i.e. the Reference) for the profile defined by profile_path. This allows the ResultRolefor the association to be set as part of the call to either "Dependent" or "Antecedent". """ a...
[ "def", "get_associated_profiles", "(", "profile_path", ",", "result_role", ",", "server", ")", ":", "associated_profiles", "=", "server", ".", "conn", ".", "Associators", "(", "ObjectName", "=", "profile_path", ",", "AssocClass", "=", "\"CIM_ReferencedProfile\"", ",...
Get the associated CIM_ReferencedProfile (i.e. the Reference) for the profile defined by profile_path. This allows the ResultRolefor the association to be set as part of the call to either "Dependent" or "Antecedent".
[ "Get", "the", "associated", "CIM_ReferencedProfile", "(", "i", ".", "e", ".", "the", "Reference", ")", "for", "the", "profile", "defined", "by", "profile_path", ".", "This", "allows", "the", "ResultRolefor", "the", "association", "to", "be", "set", "as", "pa...
python
train
saltstack/salt
salt/modules/boto_ec2.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L647-L693
def find_images(ami_name=None, executable_by=None, owners=None, image_ids=None, tags=None, region=None, key=None, keyid=None, profile=None, return_objs=False): ''' Given image properties, find and return matching AMI ids CLI Examples: .. code-block:: bash salt myminion boto_e...
[ "def", "find_images", "(", "ami_name", "=", "None", ",", "executable_by", "=", "None", ",", "owners", "=", "None", ",", "image_ids", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None"...
Given image properties, find and return matching AMI ids CLI Examples: .. code-block:: bash salt myminion boto_ec2.find_images tags='{"mytag": "value"}'
[ "Given", "image", "properties", "find", "and", "return", "matching", "AMI", "ids" ]
python
train
rocky/python3-trepan
trepan/lib/term_background.py
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/term_background.py#L40-L59
def is_dark_rgb(r, g, b): """Pass as parameters R G B values in hex On return, variable is_dark_bg is set """ try: midpoint = int(environ.get('TERMINAL_COLOR_MIDPOINT', None)) except: pass if not midpoint: term = environ.get('TERM', None) # 117963 = (* .6 (+ 6553...
[ "def", "is_dark_rgb", "(", "r", ",", "g", ",", "b", ")", ":", "try", ":", "midpoint", "=", "int", "(", "environ", ".", "get", "(", "'TERMINAL_COLOR_MIDPOINT'", ",", "None", ")", ")", "except", ":", "pass", "if", "not", "midpoint", ":", "term", "=", ...
Pass as parameters R G B values in hex On return, variable is_dark_bg is set
[ "Pass", "as", "parameters", "R", "G", "B", "values", "in", "hex", "On", "return", "variable", "is_dark_bg", "is", "set" ]
python
test
minio/minio-py
minio/parsers.py
https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L367-L389
def parse_get_bucket_notification(data): """ Parser for a get_bucket_notification response from S3. :param data: Body of response from get_bucket_notification. :return: Returns bucket notification configuration """ root = S3Element.fromstring('GetBucketNotificationResult', data) notificati...
[ "def", "parse_get_bucket_notification", "(", "data", ")", ":", "root", "=", "S3Element", ".", "fromstring", "(", "'GetBucketNotificationResult'", ",", "data", ")", "notifications", "=", "_parse_add_notifying_service_config", "(", "root", ",", "{", "}", ",", "'TopicC...
Parser for a get_bucket_notification response from S3. :param data: Body of response from get_bucket_notification. :return: Returns bucket notification configuration
[ "Parser", "for", "a", "get_bucket_notification", "response", "from", "S3", "." ]
python
train
dantezhu/haven
haven/contrib/websocket_gevent_impl.py
https://github.com/dantezhu/haven/blob/7bf7edab07fa2ade7644a548d6ab9d89cf3d259d/haven/contrib/websocket_gevent_impl.py#L89-L105
def wsgi_app(self, environ, start_response): """ 将原始的app,包装为包括websocket的app """ path = environ['PATH_INFO'] if re.match(self.path_pattern, path): ws = environ['wsgi.websocket'] address = (environ.get('REMOTE_ADDR'), environ.get('REMOTE_PORT')) ...
[ "def", "wsgi_app", "(", "self", ",", "environ", ",", "start_response", ")", ":", "path", "=", "environ", "[", "'PATH_INFO'", "]", "if", "re", ".", "match", "(", "self", ".", "path_pattern", ",", "path", ")", ":", "ws", "=", "environ", "[", "'wsgi.webso...
将原始的app,包装为包括websocket的app
[ "将原始的app,包装为包括websocket的app" ]
python
train
Metatab/metapack
metapack/package/excel.py
https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/package/excel.py#L91-L100
def _load_resources(self): """Remove the geography from the files, since it isn't particularly useful in Excel""" for t in self.doc.find('Root.Table'): for c in t.find('Table.Column'): if c.get_value('datatype') == 'geometry': c['transform'] = '^empty_str...
[ "def", "_load_resources", "(", "self", ")", ":", "for", "t", "in", "self", ".", "doc", ".", "find", "(", "'Root.Table'", ")", ":", "for", "c", "in", "t", ".", "find", "(", "'Table.Column'", ")", ":", "if", "c", ".", "get_value", "(", "'datatype'", ...
Remove the geography from the files, since it isn't particularly useful in Excel
[ "Remove", "the", "geography", "from", "the", "files", "since", "it", "isn", "t", "particularly", "useful", "in", "Excel" ]
python
train
mdsol/rwslib
rwslib/extras/local_cv.py
https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/local_cv.py#L178-L181
def name_type_from_viewname(viewname): """Have format V_<studyname>_<view>[_RAW], return name and view type REGULAR or RAW""" matched = VIEW_REX.match(viewname) return matched.group('view'), matched.group('type') or 'REGULAR'
[ "def", "name_type_from_viewname", "(", "viewname", ")", ":", "matched", "=", "VIEW_REX", ".", "match", "(", "viewname", ")", "return", "matched", ".", "group", "(", "'view'", ")", ",", "matched", ".", "group", "(", "'type'", ")", "or", "'REGULAR'" ]
Have format V_<studyname>_<view>[_RAW], return name and view type REGULAR or RAW
[ "Have", "format", "V_<studyname", ">", "_<view", ">", "[", "_RAW", "]", "return", "name", "and", "view", "type", "REGULAR", "or", "RAW" ]
python
train
chrisrink10/basilisp
src/basilisp/lang/runtime.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/runtime.py#L617-L642
def __complete_imports_and_aliases( self, prefix: str, name_in_module: Optional[str] = None ) -> Iterable[str]: """Return an iterable of possible completions matching the given prefix from the list of imports and aliased imports. If name_in_module is given, further attempt to refine ...
[ "def", "__complete_imports_and_aliases", "(", "self", ",", "prefix", ":", "str", ",", "name_in_module", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Iterable", "[", "str", "]", ":", "imports", "=", "self", ".", "imports", "aliases", "=", "l...
Return an iterable of possible completions matching the given prefix from the list of imports and aliased imports. If name_in_module is given, further attempt to refine the list to matching names in that namespace.
[ "Return", "an", "iterable", "of", "possible", "completions", "matching", "the", "given", "prefix", "from", "the", "list", "of", "imports", "and", "aliased", "imports", ".", "If", "name_in_module", "is", "given", "further", "attempt", "to", "refine", "the", "li...
python
test
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L4085-L4112
def fix_multiple_files(filenames, options, output=None): """Fix list of files. Optionally fix files recursively. """ results = [] filenames = find_files(filenames, options.recursive, options.exclude) if options.jobs > 1: import multiprocessing pool = multiprocessing.Pool(option...
[ "def", "fix_multiple_files", "(", "filenames", ",", "options", ",", "output", "=", "None", ")", ":", "results", "=", "[", "]", "filenames", "=", "find_files", "(", "filenames", ",", "options", ".", "recursive", ",", "options", ".", "exclude", ")", "if", ...
Fix list of files. Optionally fix files recursively.
[ "Fix", "list", "of", "files", "." ]
python
train
wright-group/WrightTools
WrightTools/data/_spcm.py
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_spcm.py#L28-L145
def from_spcm(filepath, name=None, *, delimiter=",", parent=None, verbose=True) -> Data: """Create a ``Data`` object from a Becker & Hickl spcm file (ASCII-exported, ``.asc``). If provided, setup parameters are stored in the ``attrs`` dictionary of the ``Data`` object. See the `spcm`__ software hompage fo...
[ "def", "from_spcm", "(", "filepath", ",", "name", "=", "None", ",", "*", ",", "delimiter", "=", "\",\"", ",", "parent", "=", "None", ",", "verbose", "=", "True", ")", "->", "Data", ":", "filestr", "=", "os", ".", "fspath", "(", "filepath", ")", "fi...
Create a ``Data`` object from a Becker & Hickl spcm file (ASCII-exported, ``.asc``). If provided, setup parameters are stored in the ``attrs`` dictionary of the ``Data`` object. See the `spcm`__ software hompage for more info. __ http://www.becker-hickl.com/software/spcm.htm Parameters ---------...
[ "Create", "a", "Data", "object", "from", "a", "Becker", "&", "Hickl", "spcm", "file", "(", "ASCII", "-", "exported", ".", "asc", ")", "." ]
python
train
T-002/pycast
pycast/errors/meanabsolutescalederror.py
https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/errors/meanabsolutescalederror.py#L86-L140
def initialize(self, originalTimeSeries, calculatedTimeSeries): """Initializes the ErrorMeasure. During initialization, all :py:meth:`BaseErrorMeasure.local_error()` are calculated. :param TimeSeries originalTimeSeries: TimeSeries containing the original data. :param TimeSeries calc...
[ "def", "initialize", "(", "self", ",", "originalTimeSeries", ",", "calculatedTimeSeries", ")", ":", "# ErrorMeasure was already initialized.", "if", "0", "<", "len", "(", "self", ".", "_errorValues", ")", ":", "raise", "StandardError", "(", "\"An ErrorMeasure can only...
Initializes the ErrorMeasure. During initialization, all :py:meth:`BaseErrorMeasure.local_error()` are calculated. :param TimeSeries originalTimeSeries: TimeSeries containing the original data. :param TimeSeries calculatedTimeSeries: TimeSeries containing calculated data. Cal...
[ "Initializes", "the", "ErrorMeasure", "." ]
python
train
pyparsing/pyparsing
examples/sparser.py
https://github.com/pyparsing/pyparsing/blob/f0264bd8d1a548a50b3e5f7d99cfefd577942d14/examples/sparser.py#L77-L81
def debug(ftn, txt): """Used for debugging.""" if debug_p: sys.stdout.write("{0}.{1}:{2}\n".format(modname, ftn, txt)) sys.stdout.flush()
[ "def", "debug", "(", "ftn", ",", "txt", ")", ":", "if", "debug_p", ":", "sys", ".", "stdout", ".", "write", "(", "\"{0}.{1}:{2}\\n\"", ".", "format", "(", "modname", ",", "ftn", ",", "txt", ")", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Used for debugging.
[ "Used", "for", "debugging", "." ]
python
train
msmbuilder/msmbuilder
msmbuilder/lumping/pcca_plus.py
https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca_plus.py#L183-L225
def metastability(alpha, T, right_eigenvectors, square_map, pi): """Return the metastability PCCA+ objective function. Parameters ---------- alpha : ndarray Parameters of objective function (e.g. flattened A) T : csr sparse matrix Transition matrix right_eigenvectors : ndarray ...
[ "def", "metastability", "(", "alpha", ",", "T", ",", "right_eigenvectors", ",", "square_map", ",", "pi", ")", ":", "num_micro", ",", "num_eigen", "=", "right_eigenvectors", ".", "shape", "A", ",", "chi", ",", "mapping", "=", "calculate_fuzzy_chi", "(", "alph...
Return the metastability PCCA+ objective function. Parameters ---------- alpha : ndarray Parameters of objective function (e.g. flattened A) T : csr sparse matrix Transition matrix right_eigenvectors : ndarray The right eigenvectors. square_map : ndarray Mapping ...
[ "Return", "the", "metastability", "PCCA", "+", "objective", "function", "." ]
python
train
jtambasco/modesolverpy
modesolverpy/structure_base.py
https://github.com/jtambasco/modesolverpy/blob/85254a13b5aed2404187c52ac93b9b3ce99ee3a3/modesolverpy/structure_base.py#L392-L415
def change_wavelength(self, wavelength): ''' Changes the wavelength of the structure. This will affect the mode solver and potentially the refractive indices used (provided functions were provided as refractive indices). Args: wavelength (float): The new wav...
[ "def", "change_wavelength", "(", "self", ",", "wavelength", ")", ":", "for", "name", ",", "slab", "in", "self", ".", "slabs", ".", "items", "(", ")", ":", "const_args", "=", "slab", ".", "_const_args", "mat_args", "=", "slab", ".", "_mat_params", "const_...
Changes the wavelength of the structure. This will affect the mode solver and potentially the refractive indices used (provided functions were provided as refractive indices). Args: wavelength (float): The new wavelength.
[ "Changes", "the", "wavelength", "of", "the", "structure", "." ]
python
train
acutesoftware/AIKIF
aikif/cls_file_mapping.py
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/cls_file_mapping.py#L105-L115
def find_type(self, txt): """ top level function used to simply return the ONE ACTUAL string used for data types """ searchString = txt.upper() match = 'Unknown' for i in self.lst_type: if searchString in i: match = i return ma...
[ "def", "find_type", "(", "self", ",", "txt", ")", ":", "searchString", "=", "txt", ".", "upper", "(", ")", "match", "=", "'Unknown'", "for", "i", "in", "self", ".", "lst_type", ":", "if", "searchString", "in", "i", ":", "match", "=", "i", "return", ...
top level function used to simply return the ONE ACTUAL string used for data types
[ "top", "level", "function", "used", "to", "simply", "return", "the", "ONE", "ACTUAL", "string", "used", "for", "data", "types" ]
python
train
edx/edx-django-utils
edx_django_utils/cache/utils.py
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L152-L169
def get_cached_response(cls, key): """ Retrieves a CachedResponse for the provided key. Args: key (string) Returns: A CachedResponse with is_found status and value. """ request_cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(key) ...
[ "def", "get_cached_response", "(", "cls", ",", "key", ")", ":", "request_cached_response", "=", "DEFAULT_REQUEST_CACHE", ".", "get_cached_response", "(", "key", ")", "if", "not", "request_cached_response", ".", "is_found", ":", "django_cached_response", "=", "cls", ...
Retrieves a CachedResponse for the provided key. Args: key (string) Returns: A CachedResponse with is_found status and value.
[ "Retrieves", "a", "CachedResponse", "for", "the", "provided", "key", "." ]
python
train
manns/pyspread
pyspread/src/gui/_cairo_export_dialog.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_cairo_export_dialog.py#L257-L293
def get_info(self): """Returns a dict with the dialog PDF info Dict keys are: top_row, bottom_row, left_col, right_col, first_tab, last_tab, paper_width, paper_height """ info = {} info["top_row"] = self.top_row_text_ctrl.GetValue() info["bottom_row"] ...
[ "def", "get_info", "(", "self", ")", ":", "info", "=", "{", "}", "info", "[", "\"top_row\"", "]", "=", "self", ".", "top_row_text_ctrl", ".", "GetValue", "(", ")", "info", "[", "\"bottom_row\"", "]", "=", "self", ".", "bottom_row_text_ctrl", ".", "GetVal...
Returns a dict with the dialog PDF info Dict keys are: top_row, bottom_row, left_col, right_col, first_tab, last_tab, paper_width, paper_height
[ "Returns", "a", "dict", "with", "the", "dialog", "PDF", "info" ]
python
train
joopert/nad_receiver
nad_receiver/__init__.py
https://github.com/joopert/nad_receiver/blob/416de0173a330c75cc73f9c90b0c5df32e5e0ba3/nad_receiver/__init__.py#L215-L237
def status(self): """ Return the status of the device. Returns a dictionary with keys 'volume' (int 0-200) , 'power' (bool), 'muted' (bool) and 'source' (str). """ nad_reply = self._send(self.POLL_VOLUME + self.POLL_POWER + ...
[ "def", "status", "(", "self", ")", ":", "nad_reply", "=", "self", ".", "_send", "(", "self", ".", "POLL_VOLUME", "+", "self", ".", "POLL_POWER", "+", "self", ".", "POLL_MUTED", "+", "self", ".", "POLL_SOURCE", ",", "read_reply", "=", "True", ")", "if",...
Return the status of the device. Returns a dictionary with keys 'volume' (int 0-200) , 'power' (bool), 'muted' (bool) and 'source' (str).
[ "Return", "the", "status", "of", "the", "device", "." ]
python
test
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/ResourceMeta.py
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/ResourceMeta.py#L133-L146
def update(self): """Gets the latest version of your metadata from the infrastructure and updates your local copy Returns `True` if successful, `False` otherwise - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrast...
[ "def", "update", "(", "self", ")", ":", "graph", "=", "Graph", "(", ")", "graph", ".", "parse", "(", "data", "=", "self", ".", "__parent", ".", "get_meta_rdf", "(", "fmt", "=", "self", ".", "__fmt", ")", ",", "format", "=", "self", ".", "__fmt", ...
Gets the latest version of your metadata from the infrastructure and updates your local copy Returns `True` if successful, `False` otherwise - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem ...
[ "Gets", "the", "latest", "version", "of", "your", "metadata", "from", "the", "infrastructure", "and", "updates", "your", "local", "copy" ]
python
train
teepark/junction
junction/client.py
https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/client.py#L207-L234
def rpc_receiver_count(self, service, routing_id, method, timeout=None): '''Get the number of peers that would handle a particular RPC This method will block until a response arrives :param service: the service name :type service: anything hash-able :param routing_id: ...
[ "def", "rpc_receiver_count", "(", "self", ",", "service", ",", "routing_id", ",", "method", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "_peer", ".", "up", ":", "raise", "errors", ".", "Unroutable", "(", ")", "return", "self", ".",...
Get the number of peers that would handle a particular RPC This method will block until a response arrives :param service: the service name :type service: anything hash-able :param routing_id: the id used for narrowing within the service handlers :type routing_id: i...
[ "Get", "the", "number", "of", "peers", "that", "would", "handle", "a", "particular", "RPC" ]
python
train
jtauber/sebastian
sebastian/midi/write_midi.py
https://github.com/jtauber/sebastian/blob/4e460c3aeab332b45c74fe78e65e76ec87d5cfa8/sebastian/midi/write_midi.py#L135-L141
def write_meta_info(self, byte1, byte2, data): "Worker method for writing meta info" write_varlen(self.data, 0) # tick write_byte(self.data, byte1) write_byte(self.data, byte2) write_varlen(self.data, len(data)) write_chars(self.data, data)
[ "def", "write_meta_info", "(", "self", ",", "byte1", ",", "byte2", ",", "data", ")", ":", "write_varlen", "(", "self", ".", "data", ",", "0", ")", "# tick", "write_byte", "(", "self", ".", "data", ",", "byte1", ")", "write_byte", "(", "self", ".", "d...
Worker method for writing meta info
[ "Worker", "method", "for", "writing", "meta", "info" ]
python
train
glomex/gcdt
gcdt/gcdt_lifecycle.py
https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/gcdt_lifecycle.py#L174-L217
def main(doc, tool, dispatch_only=None): """gcdt tools parametrized main function to initiate gcdt lifecycle. :param doc: docopt string :param tool: gcdt tool (gcdt, kumo, tenkai, ramuda, yugen) :param dispatch_only: list of commands which do not use gcdt lifecycle :return: exit_code """ # ...
[ "def", "main", "(", "doc", ",", "tool", ",", "dispatch_only", "=", "None", ")", ":", "# Use signal handler to throw exception which can be caught to allow", "# graceful exit.", "# here: https://stackoverflow.com/questions/26414704/how-does-a-python-process-exit-gracefully-after-receiving...
gcdt tools parametrized main function to initiate gcdt lifecycle. :param doc: docopt string :param tool: gcdt tool (gcdt, kumo, tenkai, ramuda, yugen) :param dispatch_only: list of commands which do not use gcdt lifecycle :return: exit_code
[ "gcdt", "tools", "parametrized", "main", "function", "to", "initiate", "gcdt", "lifecycle", "." ]
python
train
toumorokoshi/jenks
jenks/subcommand/build.py
https://github.com/toumorokoshi/jenks/blob/d3333a7b86ba290b7185aa5b8da75e76a28124f5/jenks/subcommand/build.py#L58-L82
def get_build_info(api_instance, build_id=None, keys=DEFAULT_BUILD_KEYS, wait=False): """ print build info about a job """ build = (api_instance.get_build(build_id) if build_id else api_instance.get_last_build()) output = "" if wait: build.block_until_complete() ...
[ "def", "get_build_info", "(", "api_instance", ",", "build_id", "=", "None", ",", "keys", "=", "DEFAULT_BUILD_KEYS", ",", "wait", "=", "False", ")", ":", "build", "=", "(", "api_instance", ".", "get_build", "(", "build_id", ")", "if", "build_id", "else", "a...
print build info about a job
[ "print", "build", "info", "about", "a", "job" ]
python
train
LedgerHQ/btchip-python
btchip/btchipKeyRecovery.py
https://github.com/LedgerHQ/btchip-python/blob/fe82d7f5638169f583a445b8e200fd1c9f3ea218/btchip/btchipKeyRecovery.py#L10-L33
def from_signature(klass, sig, recid, h, curve): """ See http://www.secg.org/download/aid-780/sec1-v2.pdf, chapter 4.1.6 """ from ecdsa import util, numbertheory import msqr curveFp = curve.curve G = curve.generator order = G.order() # extract r,s from signature ...
[ "def", "from_signature", "(", "klass", ",", "sig", ",", "recid", ",", "h", ",", "curve", ")", ":", "from", "ecdsa", "import", "util", ",", "numbertheory", "import", "msqr", "curveFp", "=", "curve", ".", "curve", "G", "=", "curve", ".", "generator", "or...
See http://www.secg.org/download/aid-780/sec1-v2.pdf, chapter 4.1.6
[ "See", "http", ":", "//", "www", ".", "secg", ".", "org", "/", "download", "/", "aid", "-", "780", "/", "sec1", "-", "v2", ".", "pdf", "chapter", "4", ".", "1", ".", "6" ]
python
train
etingof/pysnmp
pysnmp/hlapi/v3arch/asyncio/cmdgen.py
https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/hlapi/v3arch/asyncio/cmdgen.py#L58-L164
def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform SNMP GET query. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP GET request is send (:RFC:`1905#section-4.2.1`). The iterator yields :py:class:`asyncio.Fut...
[ "def", "getCmd", "(", "snmpEngine", ",", "authData", ",", "transportTarget", ",", "contextData", ",", "*", "varBinds", ",", "*", "*", "options", ")", ":", "def", "__cbFun", "(", "snmpEngine", ",", "sendRequestHandle", ",", "errorIndication", ",", "errorStatus"...
Creates a generator to perform SNMP GET query. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP GET request is send (:RFC:`1905#section-4.2.1`). The iterator yields :py:class:`asyncio.Future` which gets done whenever response arrives or error occurs. Parameters ---------- s...
[ "Creates", "a", "generator", "to", "perform", "SNMP", "GET", "query", "." ]
python
train
saltstack/salt
salt/roster/range.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/range.py#L35-L66
def targets(tgt, tgt_type='range', **kwargs): ''' Return the targets from a range query ''' r = seco.range.Range(__opts__['range_server']) log.debug('Range connection to \'%s\' established', __opts__['range_server']) hosts = [] try: log.debug('Querying range for \'%s\'', tgt) ...
[ "def", "targets", "(", "tgt", ",", "tgt_type", "=", "'range'", ",", "*", "*", "kwargs", ")", ":", "r", "=", "seco", ".", "range", ".", "Range", "(", "__opts__", "[", "'range_server'", "]", ")", "log", ".", "debug", "(", "'Range connection to \\'%s\\' est...
Return the targets from a range query
[ "Return", "the", "targets", "from", "a", "range", "query" ]
python
train
boriel/zxbasic
arch/zx48k/backend/__16bit.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__16bit.py#L874-L881
def _neg16(ins): ''' Negates top of the stack (16 bits in HL) ''' output = _16bit_oper(ins.quad[2]) output.append('call __NEGHL') output.append('push hl') REQUIRES.add('neg16.asm') return output
[ "def", "_neg16", "(", "ins", ")", ":", "output", "=", "_16bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ")", "output", ".", "append", "(", "'call __NEGHL'", ")", "output", ".", "append", "(", "'push hl'", ")", "REQUIRES", ".", "add", "(", "'neg1...
Negates top of the stack (16 bits in HL)
[ "Negates", "top", "of", "the", "stack", "(", "16", "bits", "in", "HL", ")" ]
python
train
MisterY/gnucash-portfolio
gnucash_portfolio/model/price_model.py
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/model/price_model.py#L22-L25
def parse_euro_date(self, date_string: str): """ Parses dd/MM/yyyy dates """ self.date = datetime.strptime(date_string, "%d/%m/%Y") return self.date
[ "def", "parse_euro_date", "(", "self", ",", "date_string", ":", "str", ")", ":", "self", ".", "date", "=", "datetime", ".", "strptime", "(", "date_string", ",", "\"%d/%m/%Y\"", ")", "return", "self", ".", "date" ]
Parses dd/MM/yyyy dates
[ "Parses", "dd", "/", "MM", "/", "yyyy", "dates" ]
python
train
ssato/python-anyconfig
src/anyconfig/backend/base.py
https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L477-L486
def dump_to_path(self, cnf, filepath, **kwargs): """ Dump config 'cnf' to a file 'filepath'. :param cnf: Configuration data to dump :param filepath: Config file path :param kwargs: optional keyword parameters to be sanitized :: dict """ with self.wopen(filepath) ...
[ "def", "dump_to_path", "(", "self", ",", "cnf", ",", "filepath", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "wopen", "(", "filepath", ")", "as", "out", ":", "out", ".", "write", "(", "self", ".", "dump_to_string", "(", "cnf", ",", "*",...
Dump config 'cnf' to a file 'filepath'. :param cnf: Configuration data to dump :param filepath: Config file path :param kwargs: optional keyword parameters to be sanitized :: dict
[ "Dump", "config", "cnf", "to", "a", "file", "filepath", "." ]
python
train
webpages/webpages
webpages/router.py
https://github.com/webpages/webpages/blob/9ea34a38dcf69220eb6e022190191aff8365addf/webpages/router.py#L14-L29
def load_routes(self): """ Load all routes in project's folder 'controllers'. Ignore files with leading underscore (for example: controllers/_blog.py) """ for file_name in os.listdir(os.path.join(self._project_dir, 'controllers')): # ignore disabled controllers ...
[ "def", "load_routes", "(", "self", ")", ":", "for", "file_name", "in", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_project_dir", ",", "'controllers'", ")", ")", ":", "# ignore disabled controllers", "if", "not", "file_nam...
Load all routes in project's folder 'controllers'. Ignore files with leading underscore (for example: controllers/_blog.py)
[ "Load", "all", "routes", "in", "project", "s", "folder", "controllers", "." ]
python
train
networks-lab/metaknowledge
metaknowledge/recordCollection.py
https://github.com/networks-lab/metaknowledge/blob/8162bf95e66bb6f9916081338e6e2a6132faff75/metaknowledge/recordCollection.py#L1709-L1760
def makeNodeTuple(citation, idVal, nodeInfo, fullInfo, nodeType, count, coreCitesDict, coreValues, detailedValues, addCR): """Makes a tuple of idVal and a dict of the selected attributes""" d = {} if nodeInfo: if nodeType == 'full': if coreValues: if citation in coreCites...
[ "def", "makeNodeTuple", "(", "citation", ",", "idVal", ",", "nodeInfo", ",", "fullInfo", ",", "nodeType", ",", "count", ",", "coreCitesDict", ",", "coreValues", ",", "detailedValues", ",", "addCR", ")", ":", "d", "=", "{", "}", "if", "nodeInfo", ":", "if...
Makes a tuple of idVal and a dict of the selected attributes
[ "Makes", "a", "tuple", "of", "idVal", "and", "a", "dict", "of", "the", "selected", "attributes" ]
python
train
boto/s3transfer
s3transfer/download.py
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/download.py#L283-L309
def _get_download_output_manager_cls(self, transfer_future, osutil): """Retrieves a class for managing output for a download :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future for the request :type osutil: s3transfer.utils.OSUtils ...
[ "def", "_get_download_output_manager_cls", "(", "self", ",", "transfer_future", ",", "osutil", ")", ":", "download_manager_resolver_chain", "=", "[", "DownloadSpecialFilenameOutputManager", ",", "DownloadFilenameOutputManager", ",", "DownloadSeekableOutputManager", ",", "Downlo...
Retrieves a class for managing output for a download :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future for the request :type osutil: s3transfer.utils.OSUtils :param osutil: The os utility associated to the transfer :rtype: cla...
[ "Retrieves", "a", "class", "for", "managing", "output", "for", "a", "download" ]
python
test
pkkid/python-plexapi
plexapi/myplex.py
https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L356-L363
def _filterDictToStr(self, filterDict): """ Converts friend filters to a string representation for transport. """ values = [] for key, vals in filterDict.items(): if key not in ('contentRating', 'label'): raise BadRequest('Unknown filter key: %s', key) val...
[ "def", "_filterDictToStr", "(", "self", ",", "filterDict", ")", ":", "values", "=", "[", "]", "for", "key", ",", "vals", "in", "filterDict", ".", "items", "(", ")", ":", "if", "key", "not", "in", "(", "'contentRating'", ",", "'label'", ")", ":", "rai...
Converts friend filters to a string representation for transport.
[ "Converts", "friend", "filters", "to", "a", "string", "representation", "for", "transport", "." ]
python
train
ebu/PlugIt
plugit_proxy/views.py
https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/views.py#L298-L308
def find_in_cache(cacheKey): """Check if the content exists in cache and return it""" # If we have to use cache, we try to find the result in cache if cacheKey: data = cache.get('plugit-cache-' + cacheKey, None) # We found a result, we can return it if data: return (dat...
[ "def", "find_in_cache", "(", "cacheKey", ")", ":", "# If we have to use cache, we try to find the result in cache", "if", "cacheKey", ":", "data", "=", "cache", ".", "get", "(", "'plugit-cache-'", "+", "cacheKey", ",", "None", ")", "# We found a result, we can return it",...
Check if the content exists in cache and return it
[ "Check", "if", "the", "content", "exists", "in", "cache", "and", "return", "it" ]
python
train
AtomHash/evernode
evernode/scripts/sendemail.py
https://github.com/AtomHash/evernode/blob/b2fb91555fb937a3f3eba41db56dee26f9b034be/evernode/scripts/sendemail.py#L119-L129
def create_email(self): """ main function to construct and send email """ self.connect() if self.send_as_one: self.construct_message() self.send() elif self.send_as_one is False: for email in self.addresses: self.construct_messa...
[ "def", "create_email", "(", "self", ")", ":", "self", ".", "connect", "(", ")", "if", "self", ".", "send_as_one", ":", "self", ".", "construct_message", "(", ")", "self", ".", "send", "(", ")", "elif", "self", ".", "send_as_one", "is", "False", ":", ...
main function to construct and send email
[ "main", "function", "to", "construct", "and", "send", "email" ]
python
train
CalebBell/fluids
fluids/nrlmsise00/nrlmsise_00.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/nrlmsise00/nrlmsise_00.py#L838-L924
def glob7s(p, Input, flags): ''' /* VERSION OF GLOBE FOR LOWER ATMOSPHERE 10/26/99 */ ''' pset = 2.0 t = [0.0]*14 dr=1.72142E-2; dgtr=1.74533E-2; #/* confirm parameter set */ if (p[99]==0): # pragma: no cover p[99]=pset; #for j in range(14): #Already taken care of ...
[ "def", "glob7s", "(", "p", ",", "Input", ",", "flags", ")", ":", "pset", "=", "2.0", "t", "=", "[", "0.0", "]", "*", "14", "dr", "=", "1.72142E-2", "dgtr", "=", "1.74533E-2", "#/* confirm parameter set */", "if", "(", "p", "[", "99", "]", "==", "0"...
/* VERSION OF GLOBE FOR LOWER ATMOSPHERE 10/26/99 */
[ "/", "*", "VERSION", "OF", "GLOBE", "FOR", "LOWER", "ATMOSPHERE", "10", "/", "26", "/", "99", "*", "/" ]
python
train
raymontag/kppy
kppy/database.py
https://github.com/raymontag/kppy/blob/a43f1fff7d49da1da4b3d8628a1b3ebbaf47f43a/kppy/database.py#L912-L960
def _read_entry_field(self, entry, field_type, field_size, decrypted_content): """This method handles the different fields of an entry""" if field_type == 0x0000: # Ignored pass elif field_type == 0x0001: entry.uuid = decrypted_conte...
[ "def", "_read_entry_field", "(", "self", ",", "entry", ",", "field_type", ",", "field_size", ",", "decrypted_content", ")", ":", "if", "field_type", "==", "0x0000", ":", "# Ignored", "pass", "elif", "field_type", "==", "0x0001", ":", "entry", ".", "uuid", "=...
This method handles the different fields of an entry
[ "This", "method", "handles", "the", "different", "fields", "of", "an", "entry" ]
python
train
rjw57/throw
throw/minus/minus.py
https://github.com/rjw57/throw/blob/74a7116362ba5b45635ab247472b25cfbdece4ee/throw/minus/minus.py#L102-L114
def CreateGallery(): """Creates a Gallery on the server. Returns a Gallery object with the editor_id and reader_id. """ url = 'http://min.us/api/CreateGallery' response = _dopost(url) _editor_id = response["editor_id"] _reader_id = response["reader_id"] return Gallery(_reader_id, edi...
[ "def", "CreateGallery", "(", ")", ":", "url", "=", "'http://min.us/api/CreateGallery'", "response", "=", "_dopost", "(", "url", ")", "_editor_id", "=", "response", "[", "\"editor_id\"", "]", "_reader_id", "=", "response", "[", "\"reader_id\"", "]", "return", "Ga...
Creates a Gallery on the server. Returns a Gallery object with the editor_id and reader_id.
[ "Creates", "a", "Gallery", "on", "the", "server", ".", "Returns", "a", "Gallery", "object", "with", "the", "editor_id", "and", "reader_id", "." ]
python
train
apache/incubator-mxnet
python/mxnet/optimizer/optimizer.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/optimizer/optimizer.py#L1692-L1699
def set_states(self, states): """Sets updater states.""" states = pickle.loads(states) if isinstance(states, tuple) and len(states) == 2: self.states, self.optimizer = states else: self.states = states self.states_synced = dict.fromkeys(self.states.keys(),...
[ "def", "set_states", "(", "self", ",", "states", ")", ":", "states", "=", "pickle", ".", "loads", "(", "states", ")", "if", "isinstance", "(", "states", ",", "tuple", ")", "and", "len", "(", "states", ")", "==", "2", ":", "self", ".", "states", ","...
Sets updater states.
[ "Sets", "updater", "states", "." ]
python
train
sveetch/boussole
boussole/conf/post_processor.py
https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/post_processor.py#L86-L101
def _patch_expand_paths(self, settings, name, value): """ Apply ``SettingsPostProcessor._patch_expand_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Ret...
[ "def", "_patch_expand_paths", "(", "self", ",", "settings", ",", "name", ",", "value", ")", ":", "return", "[", "self", ".", "_patch_expand_path", "(", "settings", ",", "name", ",", "item", ")", "for", "item", "in", "value", "]" ]
Apply ``SettingsPostProcessor._patch_expand_path`` to each element in list. Args: settings (dict): Current settings. name (str): Setting name. value (list): List of paths to patch. Returns: list: Patched path list to an absolute path.
[ "Apply", "SettingsPostProcessor", ".", "_patch_expand_path", "to", "each", "element", "in", "list", "." ]
python
train
cmbruns/pyopenvr
src/openvr/__init__.py
https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L3520-L3525
def getApplicationsErrorNameFromEnum(self, error): """Returns a string for an applications error""" fn = self.function_table.getApplicationsErrorNameFromEnum result = fn(error) return result
[ "def", "getApplicationsErrorNameFromEnum", "(", "self", ",", "error", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getApplicationsErrorNameFromEnum", "result", "=", "fn", "(", "error", ")", "return", "result" ]
Returns a string for an applications error
[ "Returns", "a", "string", "for", "an", "applications", "error" ]
python
train
tradenity/python-sdk
tradenity/resources/store_credit.py
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/store_credit.py#L778-L799
def update_store_credit_by_id(cls, store_credit_id, store_credit, **kwargs): """Update StoreCredit Update attributes of StoreCredit This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_store...
[ "def", "update_store_credit_by_id", "(", "cls", ",", "store_credit_id", ",", "store_credit", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls"...
Update StoreCredit Update attributes of StoreCredit This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_store_credit_by_id(store_credit_id, store_credit, async=True) >>> result = thread.get...
[ "Update", "StoreCredit" ]
python
train
opencobra/cobrapy
cobra/flux_analysis/room.py
https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/flux_analysis/room.py#L53-L150
def add_room(model, solution=None, linear=False, delta=0.03, epsilon=1E-03): r""" Add constraints and objective for ROOM. This function adds variables and constraints for applying regulatory on/off minimization (ROOM) to the model. Parameters ---------- model : cobra.Model The mode...
[ "def", "add_room", "(", "model", ",", "solution", "=", "None", ",", "linear", "=", "False", ",", "delta", "=", "0.03", ",", "epsilon", "=", "1E-03", ")", ":", "if", "'room_old_objective'", "in", "model", ".", "solver", ".", "variables", ":", "raise", "...
r""" Add constraints and objective for ROOM. This function adds variables and constraints for applying regulatory on/off minimization (ROOM) to the model. Parameters ---------- model : cobra.Model The model to add ROOM constraints and objective to. solution : cobra.Solution, option...
[ "r", "Add", "constraints", "and", "objective", "for", "ROOM", "." ]
python
valid
apache/incubator-mxnet
python/mxnet/operator.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/operator.py#L560-L612
def infer_storage_type_backward(self, ograd_stype, in_stype, out_stype, igrad_stype, aux_stype): """infer_storage_type_backward interface. Used to infer storage type of inputs and outputs in the backward pass. Will raise an error if undefined storage type is returned. Returned lists hav...
[ "def", "infer_storage_type_backward", "(", "self", ",", "ograd_stype", ",", "in_stype", ",", "out_stype", ",", "igrad_stype", ",", "aux_stype", ")", ":", "for", "i", ",", "stype", "in", "enumerate", "(", "ograd_stype", ")", ":", "assert", "stype", "==", "_ST...
infer_storage_type_backward interface. Used to infer storage type of inputs and outputs in the backward pass. Will raise an error if undefined storage type is returned. Returned lists have to be the same size as the input lists to infer_storage_type_backward, otherwise an exception will...
[ "infer_storage_type_backward", "interface", ".", "Used", "to", "infer", "storage", "type", "of", "inputs", "and", "outputs", "in", "the", "backward", "pass", "." ]
python
train
contraslash/django-crud-generator
django_crud_generator/django_crud_generator.py
https://github.com/contraslash/django-crud-generator/blob/9080a227291a36cf0d93b49d20601e55a616da1e/django_crud_generator/django_crud_generator.py#L77-L100
def generic_insert_module(module_name, args, **kwargs): """ In general we have a initial template and then insert new data, so we dont repeat the schema for each module :param module_name: String with module name :paran **kwargs: Args to be rendered in template """ file = create_or_open( ...
[ "def", "generic_insert_module", "(", "module_name", ",", "args", ",", "*", "*", "kwargs", ")", ":", "file", "=", "create_or_open", "(", "'{}.py'", ".", "format", "(", "module_name", ")", ",", "os", ".", "path", ".", "join", "(", "BASE_TEMPLATES_DIR", ",", ...
In general we have a initial template and then insert new data, so we dont repeat the schema for each module :param module_name: String with module name :paran **kwargs: Args to be rendered in template
[ "In", "general", "we", "have", "a", "initial", "template", "and", "then", "insert", "new", "data", "so", "we", "dont", "repeat", "the", "schema", "for", "each", "module", ":", "param", "module_name", ":", "String", "with", "module", "name", ":", "paran", ...
python
train
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L32278-L32288
def add_approval(self, reason): """Adds an approval on this event. in reason of type str Reason for approval, could be null or empty string. """ if not isinstance(reason, basestring): raise TypeError("reason can only be an instance of type basestring") s...
[ "def", "add_approval", "(", "self", ",", "reason", ")", ":", "if", "not", "isinstance", "(", "reason", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"reason can only be an instance of type basestring\"", ")", "self", ".", "_call", "(", "\"addApproval\"...
Adds an approval on this event. in reason of type str Reason for approval, could be null or empty string.
[ "Adds", "an", "approval", "on", "this", "event", "." ]
python
train
django-fluent/fluentcms-emailtemplates
fluentcms_emailtemplates/extensions.py
https://github.com/django-fluent/fluentcms-emailtemplates/blob/29f032dab9f60d05db852d2a1adcbd16e18017d1/fluentcms_emailtemplates/extensions.py#L87-L105
def render_text(self, request, instance, context): """ Custom rendering function for HTML output """ render_template = self.get_render_template(request, instance, email_format='text') if not render_template: # If there is no TEXT variation, create it by removing the H...
[ "def", "render_text", "(", "self", ",", "request", ",", "instance", ",", "context", ")", ":", "render_template", "=", "self", ".", "get_render_template", "(", "request", ",", "instance", ",", "email_format", "=", "'text'", ")", "if", "not", "render_template", ...
Custom rendering function for HTML output
[ "Custom", "rendering", "function", "for", "HTML", "output" ]
python
train
uber/doubles
doubles/expectation.py
https://github.com/uber/doubles/blob/15e68dcf98f709b19a581915fa6af5ef49ebdd8a/doubles/expectation.py#L79-L90
def is_satisfied(self): """ Returns a boolean indicating whether or not the double has been satisfied. Stubs are always satisfied, but mocks are only satisfied if they've been called as was declared, or if call is expected not to happen. :return: Whether or not the double is sat...
[ "def", "is_satisfied", "(", "self", ")", ":", "return", "self", ".", "_call_counter", ".", "has_correct_call_count", "(", ")", "and", "(", "self", ".", "_call_counter", ".", "never", "(", ")", "or", "self", ".", "_is_satisfied", ")" ]
Returns a boolean indicating whether or not the double has been satisfied. Stubs are always satisfied, but mocks are only satisfied if they've been called as was declared, or if call is expected not to happen. :return: Whether or not the double is satisfied. :rtype: bool
[ "Returns", "a", "boolean", "indicating", "whether", "or", "not", "the", "double", "has", "been", "satisfied", ".", "Stubs", "are", "always", "satisfied", "but", "mocks", "are", "only", "satisfied", "if", "they", "ve", "been", "called", "as", "was", "declared...
python
train
OCR-D/core
ocrd/ocrd/workspace.py
https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace.py#L73-L93
def download_file(self, f): """ Download a :py:mod:`ocrd.model.ocrd_file.OcrdFile` to the workspace. """ # os.chdir(self.directory) # log.info('f=%s' % f) oldpwd = os.getcwd() try: os.chdir(self.directory) if is_local_filename(f.url): ...
[ "def", "download_file", "(", "self", ",", "f", ")", ":", "# os.chdir(self.directory)", "# log.info('f=%s' % f)", "oldpwd", "=", "os", ".", "getcwd", "(", ")", "try", ":", "os", ".", "chdir", "(", "self", ".", "directory", ")", "if", "is_local_filename", "(...
Download a :py:mod:`ocrd.model.ocrd_file.OcrdFile` to the workspace.
[ "Download", "a", ":", "py", ":", "mod", ":", "ocrd", ".", "model", ".", "ocrd_file", ".", "OcrdFile", "to", "the", "workspace", "." ]
python
train
eqcorrscan/EQcorrscan
eqcorrscan/utils/mag_calc.py
https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/mag_calc.py#L825-L1027
def svd_moments(u, s, v, stachans, event_list, n_svs=2): """ Calculate relative moments/amplitudes using singular-value decomposition. Convert basis vectors calculated by singular value \ decomposition (see the SVD functions in clustering) into relative \ moments. For more information see the ...
[ "def", "svd_moments", "(", "u", ",", "s", ",", "v", ",", "stachans", ",", "event_list", ",", "n_svs", "=", "2", ")", ":", "# Define maximum number of events, will be the width of K", "K_width", "=", "max", "(", "[", "max", "(", "ev_list", ")", "for", "ev_lis...
Calculate relative moments/amplitudes using singular-value decomposition. Convert basis vectors calculated by singular value \ decomposition (see the SVD functions in clustering) into relative \ moments. For more information see the paper by \ `Rubinstein & Ellsworth (2010). <http://www.bssaon...
[ "Calculate", "relative", "moments", "/", "amplitudes", "using", "singular", "-", "value", "decomposition", "." ]
python
train
camptocamp/Studio
studio/controllers/datastores.py
https://github.com/camptocamp/Studio/blob/43cb7298434fb606b15136801b79b03571a2f27e/studio/controllers/datastores.py#L53-L64
def create(self): """POST /datastores: Create a new item.""" # url('datastores') content = request.environ['wsgi.input'].read(int(request.environ['CONTENT_LENGTH'])) content = content.decode('utf8') content = simplejson.loads(content) new = DataStore(content['name'], ...
[ "def", "create", "(", "self", ")", ":", "# url('datastores')", "content", "=", "request", ".", "environ", "[", "'wsgi.input'", "]", ".", "read", "(", "int", "(", "request", ".", "environ", "[", "'CONTENT_LENGTH'", "]", ")", ")", "content", "=", "content", ...
POST /datastores: Create a new item.
[ "POST", "/", "datastores", ":", "Create", "a", "new", "item", "." ]
python
train
sci-bots/svg-model
svg_model/detect_connections.py
https://github.com/sci-bots/svg-model/blob/2d119650f995e62b29ce0b3151a23f3b957cb072/svg_model/detect_connections.py#L13-L95
def auto_detect_adjacent_shapes(svg_source, shape_i_attr='id', layer_name='Connections', shapes_xpath='//svg:path | //svg:polygon', extend=1.5): ''' Attempt to automatically find "adjacent" shapes in a SVG layer. ...
[ "def", "auto_detect_adjacent_shapes", "(", "svg_source", ",", "shape_i_attr", "=", "'id'", ",", "layer_name", "=", "'Connections'", ",", "shapes_xpath", "=", "'//svg:path | //svg:polygon'", ",", "extend", "=", "1.5", ")", ":", "# Read SVG polygons into dataframe, one row ...
Attempt to automatically find "adjacent" shapes in a SVG layer. In a layer within a new SVG document, draw each detected connection between the center points of the corresponding shapes. Parameters ---------- svg_source : str Input SVG file as a filepath (or file-like object). shape_i_...
[ "Attempt", "to", "automatically", "find", "adjacent", "shapes", "in", "a", "SVG", "layer", "." ]
python
train
genialis/resolwe
resolwe/flow/managers/dispatcher.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/managers/dispatcher.py#L564-L629
async def handle_control_event(self, message): """Handle an event from the Channels layer. Channels layer callback, do not call directly. """ cmd = message[WorkerProtocol.COMMAND] logger.debug(__("Manager worker got channel command '{}'.", cmd)) # Prepare settings for u...
[ "async", "def", "handle_control_event", "(", "self", ",", "message", ")", ":", "cmd", "=", "message", "[", "WorkerProtocol", ".", "COMMAND", "]", "logger", ".", "debug", "(", "__", "(", "\"Manager worker got channel command '{}'.\"", ",", "cmd", ")", ")", "# P...
Handle an event from the Channels layer. Channels layer callback, do not call directly.
[ "Handle", "an", "event", "from", "the", "Channels", "layer", "." ]
python
train
FlaskGuys/Flask-Imagine
flask_imagine/filters/watermark.py
https://github.com/FlaskGuys/Flask-Imagine/blob/f79c6517ecb5480b63a2b3b8554edb6e2ac8be8c/flask_imagine/filters/watermark.py#L210-L223
def _reduce_opacity(self): """ Reduce opacity for watermark image. """ if self.image.mode != 'RGBA': image = self.image.convert('RGBA') else: image = self.image.copy() alpha = image.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance...
[ "def", "_reduce_opacity", "(", "self", ")", ":", "if", "self", ".", "image", ".", "mode", "!=", "'RGBA'", ":", "image", "=", "self", ".", "image", ".", "convert", "(", "'RGBA'", ")", "else", ":", "image", "=", "self", ".", "image", ".", "copy", "("...
Reduce opacity for watermark image.
[ "Reduce", "opacity", "for", "watermark", "image", "." ]
python
train
kwarunek/file2py
file2py/conv.py
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L36-L46
def set_template(self, template): """ Sets template to be used when generating output :param template TEmplate instance :type instance of BasicTemplate """ if isinstance(template, templates.BasicTemplate): self.template = template else: raise Type...
[ "def", "set_template", "(", "self", ",", "template", ")", ":", "if", "isinstance", "(", "template", ",", "templates", ".", "BasicTemplate", ")", ":", "self", ".", "template", "=", "template", "else", ":", "raise", "TypeError", "(", "'converter#set_template:'",...
Sets template to be used when generating output :param template TEmplate instance :type instance of BasicTemplate
[ "Sets", "template", "to", "be", "used", "when", "generating", "output" ]
python
train
nion-software/nionswift
nion/typeshed/API_1_0.py
https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/typeshed/API_1_0.py#L751-L765
def get_data_item_for_hardware_source(self, hardware_source, channel_id: str=None, processor_id: str=None, create_if_needed: bool=False, large_format: bool=False) -> DataItem: """Get the data item associated with hardware source and (optional) channel id and processor_id. Optionally create if missing. ...
[ "def", "get_data_item_for_hardware_source", "(", "self", ",", "hardware_source", ",", "channel_id", ":", "str", "=", "None", ",", "processor_id", ":", "str", "=", "None", ",", "create_if_needed", ":", "bool", "=", "False", ",", "large_format", ":", "bool", "="...
Get the data item associated with hardware source and (optional) channel id and processor_id. Optionally create if missing. :param hardware_source: The hardware_source. :param channel_id: The (optional) channel id. :param processor_id: The (optional) processor id for the channel. :param...
[ "Get", "the", "data", "item", "associated", "with", "hardware", "source", "and", "(", "optional", ")", "channel", "id", "and", "processor_id", ".", "Optionally", "create", "if", "missing", "." ]
python
train
unfoldingWord-dev/python-gogs-client
gogs_client/interface.py
https://github.com/unfoldingWord-dev/python-gogs-client/blob/b7f27f4995abf914c0db8a424760f5b27331939d/gogs_client/interface.py#L377-L392
def get_repo_hooks(self, auth, username, repo_name): """ Returns all hooks of repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :par...
[ "def", "get_repo_hooks", "(", "self", ",", "auth", ",", "username", ",", "repo_name", ")", ":", "path", "=", "\"/repos/{u}/{r}/hooks\"", ".", "format", "(", "u", "=", "username", ",", "r", "=", "repo_name", ")", "response", "=", "self", ".", "get", "(", ...
Returns all hooks of repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: a list of hooks for...
[ "Returns", "all", "hooks", "of", "repository", "with", "name", "repo_name", "owned", "by", "the", "user", "with", "username", "username", "." ]
python
train
diogobaeder/pycket
pycket/notification.py
https://github.com/diogobaeder/pycket/blob/b21d1553b4100d820a6922eeb55baa2329bc02c2/pycket/notification.py#L17-L27
def get(self, name, default=None): ''' Retrieves the object with "name", like with SessionManager.get(), but removes the object from the database after retrieval, so that it can be retrieved only once ''' session_object = super(NotificationManager, self).get(name, defaul...
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "session_object", "=", "super", "(", "NotificationManager", ",", "self", ")", ".", "get", "(", "name", ",", "default", ")", "if", "session_object", "is", "not", "None", ":",...
Retrieves the object with "name", like with SessionManager.get(), but removes the object from the database after retrieval, so that it can be retrieved only once
[ "Retrieves", "the", "object", "with", "name", "like", "with", "SessionManager", ".", "get", "()", "but", "removes", "the", "object", "from", "the", "database", "after", "retrieval", "so", "that", "it", "can", "be", "retrieved", "only", "once" ]
python
train
lsbardel/python-stdnet
stdnet/odm/struct.py
https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/odm/struct.py#L653-L658
def block_pop_front(self, timeout=10): '''Remove the first element from of the list. If no elements are available, blocks for at least ``timeout`` seconds.''' value = yield self.backend_structure().block_pop_front(timeout) if value is not None: yield self.value_pickler.loads(val...
[ "def", "block_pop_front", "(", "self", ",", "timeout", "=", "10", ")", ":", "value", "=", "yield", "self", ".", "backend_structure", "(", ")", ".", "block_pop_front", "(", "timeout", ")", "if", "value", "is", "not", "None", ":", "yield", "self", ".", "...
Remove the first element from of the list. If no elements are available, blocks for at least ``timeout`` seconds.
[ "Remove", "the", "first", "element", "from", "of", "the", "list", ".", "If", "no", "elements", "are", "available", "blocks", "for", "at", "least", "timeout", "seconds", "." ]
python
train
sludgedesk/metoffer
metoffer.py
https://github.com/sludgedesk/metoffer/blob/449748d31f913d961d6f0406542bb784e931a95b/metoffer.py#L276-L286
def text_uk_extremes(self, request): """ Return textual data of UK extremes. request: metoffer.CAPABILITIES Returns available extreme date and issue time metoffer.LATEST Returns data of late...
[ "def", "text_uk_extremes", "(", "self", ",", "request", ")", ":", "return", "json", ".", "loads", "(", "self", ".", "_query", "(", "TEXT", ",", "OBSERVATIONS", ",", "UK_EXTREMES", ",", "request", ",", "\"\"", ")", ".", "decode", "(", "errors", "=", "\"...
Return textual data of UK extremes. request: metoffer.CAPABILITIES Returns available extreme date and issue time metoffer.LATEST Returns data of latest extremes ...
[ "Return", "textual", "data", "of", "UK", "extremes", ".", "request", ":", "metoffer", ".", "CAPABILITIES", "Returns", "available", "extreme", "date", "and", "issue", "time", "metoffer", ".", "LATEST", "Returns", "data", "of", "latest", "extremes", "for", "all"...
python
train
googleapis/google-cloud-python
pubsub/google/cloud/pubsub_v1/futures.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/futures.py#L115-L140
def exception(self, timeout=None): """Return the exception raised by the call, if any. This blocks until the message has successfully been published, and returns the exception. If the call succeeded, return None. Args: timeout (Union[int, float]): The number of seconds befo...
[ "def", "exception", "(", "self", ",", "timeout", "=", "None", ")", ":", "# Wait until the future is done.", "if", "not", "self", ".", "_completed", ".", "wait", "(", "timeout", "=", "timeout", ")", ":", "raise", "exceptions", ".", "TimeoutError", "(", "\"Tim...
Return the exception raised by the call, if any. This blocks until the message has successfully been published, and returns the exception. If the call succeeded, return None. Args: timeout (Union[int, float]): The number of seconds before this call times out and rai...
[ "Return", "the", "exception", "raised", "by", "the", "call", "if", "any", "." ]
python
train
secdev/scapy
scapy/contrib/http2.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/contrib/http2.py#L504-L515
def h2i(self, pkt, x): # type: (Optional[packet.Packet], int) -> int """ h2i is overloaded to restrict the acceptable x values (not None) @param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501 @param int x: the value to convert....
[ "def", "h2i", "(", "self", ",", "pkt", ",", "x", ")", ":", "# type: (Optional[packet.Packet], int) -> int", "ret", "=", "super", "(", "UVarIntField", ",", "self", ")", ".", "h2i", "(", "pkt", ",", "x", ")", "assert", "(", "not", "isinstance", "(", "ret",...
h2i is overloaded to restrict the acceptable x values (not None) @param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501 @param int x: the value to convert. @return int: the converted value. @raise AssertionError
[ "h2i", "is", "overloaded", "to", "restrict", "the", "acceptable", "x", "values", "(", "not", "None", ")" ]
python
train
mikicz/arca
arca/utils.py
https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/utils.py#L158-L167
def get_hash_for_file(repo: Repo, path: Union[str, Path]) -> str: """ Returns the hash for the specified path. Equivalent to ``git rev-parse HEAD:X`` :param repo: The repo to check in :param path: The path to a file or folder to get hash for :return: The hash """ return repo.git.rev_parse(...
[ "def", "get_hash_for_file", "(", "repo", ":", "Repo", ",", "path", ":", "Union", "[", "str", ",", "Path", "]", ")", "->", "str", ":", "return", "repo", ".", "git", ".", "rev_parse", "(", "f\"HEAD:{str(path)}\"", ")" ]
Returns the hash for the specified path. Equivalent to ``git rev-parse HEAD:X`` :param repo: The repo to check in :param path: The path to a file or folder to get hash for :return: The hash
[ "Returns", "the", "hash", "for", "the", "specified", "path", "." ]
python
train
ptmcg/littletable
littletable.py
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1450-L1469
def as_html(self, fields='*'): """ Output the table as a rudimentary HTML table. @param fields: fields in the table to be shown in the table - listing '*' as a field will add all unnamed fields - starting a field name with '-' will suppress that name...
[ "def", "as_html", "(", "self", ",", "fields", "=", "'*'", ")", ":", "fields", "=", "self", ".", "_parse_fields_string", "(", "fields", ")", "def", "td_value", "(", "v", ")", ":", "return", "'<td><div align=\"{}\">{}</div></td>'", ".", "format", "(", "(", "...
Output the table as a rudimentary HTML table. @param fields: fields in the table to be shown in the table - listing '*' as a field will add all unnamed fields - starting a field name with '-' will suppress that name @type fields: list of strings or a single ...
[ "Output", "the", "table", "as", "a", "rudimentary", "HTML", "table", "." ]
python
train
inveniosoftware-attic/invenio-upgrader
invenio_upgrader/cli.py
https://github.com/inveniosoftware-attic/invenio-upgrader/blob/cee4bcb118515463ecf6de1421642007f79a9fcd/invenio_upgrader/cli.py#L183-L203
def pending(): """Command for showing upgrades ready to be applied.""" upgrader = InvenioUpgrader() logger = upgrader.get_logger() try: upgrades = upgrader.get_upgrades() if not upgrades: logger.info("All upgrades have been applied.") return logger.info...
[ "def", "pending", "(", ")", ":", "upgrader", "=", "InvenioUpgrader", "(", ")", "logger", "=", "upgrader", ".", "get_logger", "(", ")", "try", ":", "upgrades", "=", "upgrader", ".", "get_upgrades", "(", ")", "if", "not", "upgrades", ":", "logger", ".", ...
Command for showing upgrades ready to be applied.
[ "Command", "for", "showing", "upgrades", "ready", "to", "be", "applied", "." ]
python
train
wandb/client
wandb/__init__.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/__init__.py#L489-L495
def uninit(): """Undo the effects of init(). Useful for testing. """ global run, config, watch_called, _saved_files run = config = None watch_called = False _saved_files = set()
[ "def", "uninit", "(", ")", ":", "global", "run", ",", "config", ",", "watch_called", ",", "_saved_files", "run", "=", "config", "=", "None", "watch_called", "=", "False", "_saved_files", "=", "set", "(", ")" ]
Undo the effects of init(). Useful for testing.
[ "Undo", "the", "effects", "of", "init", "()", ".", "Useful", "for", "testing", "." ]
python
train
Spinmob/spinmob
_pylab_colormap.py
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_pylab_colormap.py#L64-L96
def load_colormap(self, name=None): """ Loads a colormap of the supplied name. None means used the internal name. (See self.get_name()) """ if name == None: name = self.get_name() if name == "" or not type(name)==str: return "Error: Bad name." # assemble the pat...
[ "def", "load_colormap", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "==", "None", ":", "name", "=", "self", ".", "get_name", "(", ")", "if", "name", "==", "\"\"", "or", "not", "type", "(", "name", ")", "==", "str", ":", "return...
Loads a colormap of the supplied name. None means used the internal name. (See self.get_name())
[ "Loads", "a", "colormap", "of", "the", "supplied", "name", ".", "None", "means", "used", "the", "internal", "name", ".", "(", "See", "self", ".", "get_name", "()", ")" ]
python
train
wonambi-python/wonambi
wonambi/widgets/traces.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L907-L980
def mouseReleaseEvent(self, event): """Create a new event or marker, or show the previous power spectrum """ if not self.scene: return if self.event_sel: return if self.deselect: self.deselect = False return if not self.r...
[ "def", "mouseReleaseEvent", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "scene", ":", "return", "if", "self", ".", "event_sel", ":", "return", "if", "self", ".", "deselect", ":", "self", ".", "deselect", "=", "False", "return", "if",...
Create a new event or marker, or show the previous power spectrum
[ "Create", "a", "new", "event", "or", "marker", "or", "show", "the", "previous", "power", "spectrum" ]
python
train
LettError/MutatorMath
Lib/mutatorMath/objects/mutator.py
https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/mutator.py#L380-L454
def getLimits(locations, current, sortResults=True, verbose=False): """ Find the projections for each delta in the list of locations, relative to the current location. Return only the dimensions that are relevant for current. """ limit = {} for l in locations: a, b = current.comm...
[ "def", "getLimits", "(", "locations", ",", "current", ",", "sortResults", "=", "True", ",", "verbose", "=", "False", ")", ":", "limit", "=", "{", "}", "for", "l", "in", "locations", ":", "a", ",", "b", "=", "current", ".", "common", "(", "l", ")", ...
Find the projections for each delta in the list of locations, relative to the current location. Return only the dimensions that are relevant for current.
[ "Find", "the", "projections", "for", "each", "delta", "in", "the", "list", "of", "locations", "relative", "to", "the", "current", "location", ".", "Return", "only", "the", "dimensions", "that", "are", "relevant", "for", "current", "." ]
python
train
apache/airflow
airflow/models/pool.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/pool.py#L60-L69
def open_slots(self, session): """ Returns the number of slots open at the moment """ from airflow.models.taskinstance import \ TaskInstance as TI # Avoid circular import used_slots = session.query(func.count()).filter(TI.pool == self.pool).filter( TI.st...
[ "def", "open_slots", "(", "self", ",", "session", ")", ":", "from", "airflow", ".", "models", ".", "taskinstance", "import", "TaskInstance", "as", "TI", "# Avoid circular import", "used_slots", "=", "session", ".", "query", "(", "func", ".", "count", "(", ")...
Returns the number of slots open at the moment
[ "Returns", "the", "number", "of", "slots", "open", "at", "the", "moment" ]
python
test
Murali-group/halp
halp/utilities/directed_graph_transformations.py
https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/utilities/directed_graph_transformations.py#L81-L110
def from_networkx_digraph(nx_digraph): """Returns a DirectedHypergraph object that is the graph equivalent of the given NetworkX DiGraph object. :param nx_digraph: the NetworkX directed graph object to transform. :returns: DirectedHypergraph -- hypergraph object equivalent to the NetworkX d...
[ "def", "from_networkx_digraph", "(", "nx_digraph", ")", ":", "import", "networkx", "as", "nx", "if", "not", "isinstance", "(", "nx_digraph", ",", "nx", ".", "DiGraph", ")", ":", "raise", "TypeError", "(", "\"Transformation only applicable to directed \\\n ...
Returns a DirectedHypergraph object that is the graph equivalent of the given NetworkX DiGraph object. :param nx_digraph: the NetworkX directed graph object to transform. :returns: DirectedHypergraph -- hypergraph object equivalent to the NetworkX directed graph. :raises: TypeError -- Trans...
[ "Returns", "a", "DirectedHypergraph", "object", "that", "is", "the", "graph", "equivalent", "of", "the", "given", "NetworkX", "DiGraph", "object", "." ]
python
train
rwl/pylon
contrib/cvxopf.py
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/contrib/cvxopf.py#L627-L648
def d2Sbus_dV2(Ybus, V, lam): """ Computes 2nd derivatives of power injection w.r.t. voltage. """ n = len(V) Ibus = Ybus * V diaglam = spdiag(lam) diagV = spdiag(V) A = spmatrix(mul(lam, V), range(n), range(n)) B = Ybus * diagV C = A * conj(B) D = Ybus.H * diagV E = conj(dia...
[ "def", "d2Sbus_dV2", "(", "Ybus", ",", "V", ",", "lam", ")", ":", "n", "=", "len", "(", "V", ")", "Ibus", "=", "Ybus", "*", "V", "diaglam", "=", "spdiag", "(", "lam", ")", "diagV", "=", "spdiag", "(", "V", ")", "A", "=", "spmatrix", "(", "mul...
Computes 2nd derivatives of power injection w.r.t. voltage.
[ "Computes", "2nd", "derivatives", "of", "power", "injection", "w", ".", "r", ".", "t", ".", "voltage", "." ]
python
train
SBRG/ssbio
ssbio/protein/structure/properties/dssp.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/properties/dssp.py#L256-L272
def calc_sasa(dssp_df): """ Calculation of SASA utilizing the DSSP program. DSSP must be installed for biopython to properly call it. Install using apt-get on Ubuntu or from: http://swift.cmbi.ru.nl/gv/dssp/ Input: PDB or CIF structure file Output: SASA (integer) of structure """ ...
[ "def", "calc_sasa", "(", "dssp_df", ")", ":", "infodict", "=", "{", "'ssb_sasa'", ":", "dssp_df", ".", "exposure_asa", ".", "sum", "(", ")", ",", "'ssb_mean_rel_exposed'", ":", "dssp_df", ".", "exposure_rsa", ".", "mean", "(", ")", ",", "'ssb_size'", ":", ...
Calculation of SASA utilizing the DSSP program. DSSP must be installed for biopython to properly call it. Install using apt-get on Ubuntu or from: http://swift.cmbi.ru.nl/gv/dssp/ Input: PDB or CIF structure file Output: SASA (integer) of structure
[ "Calculation", "of", "SASA", "utilizing", "the", "DSSP", "program", "." ]
python
train
oscarlazoarjona/fast
build/lib/fast/atomic_structure.py
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/atomic_structure.py#L342-L381
def find_decays(self, fine_state): r"""Find all possible decays from a given fine state. This function finds all the states to which a given fine structure state can decay (through electric dipole selection rules). >>> atom=Atom("Cs",133) >>> e=State("Cs",133,6,"P",3/Integer(2)...
[ "def", "find_decays", "(", "self", ",", "fine_state", ")", ":", "def", "decays_from", "(", "fine_state", ",", "transitions", ")", ":", "states_below", "=", "[", "]", "for", "t", "in", "transitions", ":", "if", "t", ".", "e2", "==", "fine_state", ":", "...
r"""Find all possible decays from a given fine state. This function finds all the states to which a given fine structure state can decay (through electric dipole selection rules). >>> atom=Atom("Cs",133) >>> e=State("Cs",133,6,"P",3/Integer(2)) >>> atom.find_decays(e) [...
[ "r", "Find", "all", "possible", "decays", "from", "a", "given", "fine", "state", "." ]
python
train
KE-works/pykechain
pykechain/models/part.py
https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/part.py#L236-L253
def instance(self): """ Retrieve the single (expected) instance of this 'Part' (of `Category.MODEL`) as a 'Part'. See :func:`Part.instances()` method for documentation. :return: :class:`Part` with category `INSTANCE` :raises NotFoundError: if the instance does not exist ...
[ "def", "instance", "(", "self", ")", ":", "instances_list", "=", "list", "(", "self", ".", "instances", "(", ")", ")", "if", "len", "(", "instances_list", ")", "==", "1", ":", "return", "instances_list", "[", "0", "]", "elif", "len", "(", "instances_li...
Retrieve the single (expected) instance of this 'Part' (of `Category.MODEL`) as a 'Part'. See :func:`Part.instances()` method for documentation. :return: :class:`Part` with category `INSTANCE` :raises NotFoundError: if the instance does not exist :raises MultipleFoundError: if there ar...
[ "Retrieve", "the", "single", "(", "expected", ")", "instance", "of", "this", "Part", "(", "of", "Category", ".", "MODEL", ")", "as", "a", "Part", "." ]
python
train
aleju/imgaug
imgaug/imgaug.py
https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/imgaug.py#L1537-L1616
def pool(arr, block_size, func, cval=0, preserve_dtype=True): """ Resize an array by pooling values within blocks. dtype support:: * ``uint8``: yes; fully tested * ``uint16``: yes; tested * ``uint32``: yes; tested (2) * ``uint64``: no (1) * ``int8``: yes; tested ...
[ "def", "pool", "(", "arr", ",", "block_size", ",", "func", ",", "cval", "=", "0", ",", "preserve_dtype", "=", "True", ")", ":", "# TODO find better way to avoid circular import", "from", ".", "import", "dtypes", "as", "iadt", "iadt", ".", "gate_dtypes", "(", ...
Resize an array by pooling values within blocks. dtype support:: * ``uint8``: yes; fully tested * ``uint16``: yes; tested * ``uint32``: yes; tested (2) * ``uint64``: no (1) * ``int8``: yes; tested * ``int16``: yes; tested * ``int32``: yes; tested (2) ...
[ "Resize", "an", "array", "by", "pooling", "values", "within", "blocks", "." ]
python
valid
abn/cafeteria
cafeteria/logging/__init__.py
https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/logging/__init__.py#L17-L30
def set_level(cls, level): """ :raises: ValueError """ level = ( level if not is_str(level) else int(LOGGING_LEVELS.get(level.upper(), level)) ) for handler in root.handlers: handler.setLevel(level) root.setLevel(l...
[ "def", "set_level", "(", "cls", ",", "level", ")", ":", "level", "=", "(", "level", "if", "not", "is_str", "(", "level", ")", "else", "int", "(", "LOGGING_LEVELS", ".", "get", "(", "level", ".", "upper", "(", ")", ",", "level", ")", ")", ")", "fo...
:raises: ValueError
[ ":", "raises", ":", "ValueError" ]
python
train
myusuf3/delorean
delorean/dates.py
https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L553-L570
def replace(self, **kwargs): """ Returns a new Delorean object after applying replace on the existing datetime object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:: >>> d...
[ "def", "replace", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "Delorean", "(", "datetime", "=", "self", ".", "_dt", ".", "replace", "(", "*", "*", "kwargs", ")", ",", "timezone", "=", "self", ".", "timezone", ")" ]
Returns a new Delorean object after applying replace on the existing datetime object. .. testsetup:: from datetime import datetime from delorean import Delorean .. doctest:: >>> d = Delorean(datetime(2015, 1, 1, 12, 15), timezone='U...
[ "Returns", "a", "new", "Delorean", "object", "after", "applying", "replace", "on", "the", "existing", "datetime", "object", "." ]
python
train
bastikr/boolean.py
boolean/boolean.py
https://github.com/bastikr/boolean.py/blob/e984df480afc60605e9501a0d3d54d667e8f7dbf/boolean/boolean.py#L626-L644
def subs(self, substitutions, default=None, simplify=False): """ Return an expression where the expression or all subterms equal to a key expression are substituted with the corresponding value expression using a mapping of: {expr->expr to substitute.} Return this expression unm...
[ "def", "subs", "(", "self", ",", "substitutions", ",", "default", "=", "None", ",", "simplify", "=", "False", ")", ":", "# shortcut: check if we have our whole expression as a possible", "# subsitution source", "for", "expr", ",", "substitution", "in", "substitutions", ...
Return an expression where the expression or all subterms equal to a key expression are substituted with the corresponding value expression using a mapping of: {expr->expr to substitute.} Return this expression unmodified if nothing could be substituted. Note that this can be used to t...
[ "Return", "an", "expression", "where", "the", "expression", "or", "all", "subterms", "equal", "to", "a", "key", "expression", "are", "substituted", "with", "the", "corresponding", "value", "expression", "using", "a", "mapping", "of", ":", "{", "expr", "-", "...
python
train
ttroy50/pyirishrail
pyirishrail/pyirishrail.py
https://github.com/ttroy50/pyirishrail/blob/83232a65a53317fbcc2a41938165912c51b23515/pyirishrail/pyirishrail.py#L32-L41
def _parse(data, obj_name, attr_map): """parse xml data into a python map""" parsed_xml = minidom.parseString(data) parsed_objects = [] for obj in parsed_xml.getElementsByTagName(obj_name): parsed_obj = {} for (py_name, xml_name) in attr_map.items(): parsed_obj[py_name] = _ge...
[ "def", "_parse", "(", "data", ",", "obj_name", ",", "attr_map", ")", ":", "parsed_xml", "=", "minidom", ".", "parseString", "(", "data", ")", "parsed_objects", "=", "[", "]", "for", "obj", "in", "parsed_xml", ".", "getElementsByTagName", "(", "obj_name", "...
parse xml data into a python map
[ "parse", "xml", "data", "into", "a", "python", "map" ]
python
train
saltstack/salt
salt/states/panos.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/panos.py#L268-L289
def add_config_lock(name): ''' Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock ''' ret = _default_ret(name) ret....
[ "def", "add_config_lock", "(", "name", ")", ":", "ret", "=", "_default_ret", "(", "name", ")", "ret", ".", "update", "(", "{", "'changes'", ":", "__salt__", "[", "'panos.add_config_lock'", "]", "(", ")", ",", "'result'", ":", "True", "}", ")", "return", ...
Prevent other users from changing configuration until the lock is released. name: The name of the module function to execute. SLS Example: .. code-block:: yaml panos/takelock: panos.add_config_lock
[ "Prevent", "other", "users", "from", "changing", "configuration", "until", "the", "lock", "is", "released", "." ]
python
train
astrocatalogs/astrocats
astrocats/catalog/entry.py
https://github.com/astrocatalogs/astrocats/blob/11abc3131c6366ecd23964369e55ff264add7805/astrocats/catalog/entry.py#L199-L224
def _ordered(self, odict): """Convert the object into a plain OrderedDict.""" ndict = OrderedDict() if isinstance(odict, CatDict) or isinstance(odict, Entry): key = odict.sort_func else: key = None nkeys = list(sorted(odict.keys(), key=key)) for ...
[ "def", "_ordered", "(", "self", ",", "odict", ")", ":", "ndict", "=", "OrderedDict", "(", ")", "if", "isinstance", "(", "odict", ",", "CatDict", ")", "or", "isinstance", "(", "odict", ",", "Entry", ")", ":", "key", "=", "odict", ".", "sort_func", "el...
Convert the object into a plain OrderedDict.
[ "Convert", "the", "object", "into", "a", "plain", "OrderedDict", "." ]
python
train
msmbuilder/msmbuilder
msmbuilder/lumping/bace.py
https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/bace.py#L173-L202
def from_msm(cls, msm, n_macrostates, filter=1.1, save_all_maps=True, n_proc=1, chunk_size=100): """Create and fit lumped model from pre-existing MSM. Parameters ---------- msm : MarkovStateModel The input microstate msm to use. n_macrostates : int ...
[ "def", "from_msm", "(", "cls", ",", "msm", ",", "n_macrostates", ",", "filter", "=", "1.1", ",", "save_all_maps", "=", "True", ",", "n_proc", "=", "1", ",", "chunk_size", "=", "100", ")", ":", "params", "=", "msm", ".", "get_params", "(", ")", "lumpe...
Create and fit lumped model from pre-existing MSM. Parameters ---------- msm : MarkovStateModel The input microstate msm to use. n_macrostates : int The number of macrostates Returns ------- lumper : cls The fit MVCA object.
[ "Create", "and", "fit", "lumped", "model", "from", "pre", "-", "existing", "MSM", "." ]
python
train
napalm-automation/napalm
napalm/nxos_ssh/nxos_ssh.py
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L350-L426
def bgp_summary_parser(bgp_summary): """Parse 'show bgp all summary vrf' output information from NX-OS devices.""" bgp_summary_dict = {} # Check for BGP summary information lines that have no data if len(bgp_summary.strip().splitlines()) <= 1: return {} allowed_afi = ["ipv4", "ipv6", "l2vp...
[ "def", "bgp_summary_parser", "(", "bgp_summary", ")", ":", "bgp_summary_dict", "=", "{", "}", "# Check for BGP summary information lines that have no data", "if", "len", "(", "bgp_summary", ".", "strip", "(", ")", ".", "splitlines", "(", ")", ")", "<=", "1", ":", ...
Parse 'show bgp all summary vrf' output information from NX-OS devices.
[ "Parse", "show", "bgp", "all", "summary", "vrf", "output", "information", "from", "NX", "-", "OS", "devices", "." ]
python
train
fcurella/django-fakery
django_fakery/shortcuts.py
https://github.com/fcurella/django-fakery/blob/05b6d6a9bf4b8fab98bf91fe1dce5a812d951987/django_fakery/shortcuts.py#L49-L66
def past_datetime(start='-30d'): """ Returns a ``datetime`` object in the past between 1 second ago and the specified ``start``. ``start`` can be a string, another datetime, or a timedelta. If it's a string, it must start with `-`, followed by and integer and a unit, Eg: ``'-30d'``. Defaults to `'-3...
[ "def", "past_datetime", "(", "start", "=", "'-30d'", ")", ":", "return", "lambda", "n", ",", "f", ":", "f", ".", "past_datetime", "(", "start_date", "=", "start", ",", "tzinfo", "=", "get_timezone", "(", ")", ",", ")" ]
Returns a ``datetime`` object in the past between 1 second ago and the specified ``start``. ``start`` can be a string, another datetime, or a timedelta. If it's a string, it must start with `-`, followed by and integer and a unit, Eg: ``'-30d'``. Defaults to `'-30d'` Valid units are: * ``'years'``,...
[ "Returns", "a", "datetime", "object", "in", "the", "past", "between", "1", "second", "ago", "and", "the", "specified", "start", ".", "start", "can", "be", "a", "string", "another", "datetime", "or", "a", "timedelta", ".", "If", "it", "s", "a", "string", ...
python
train
notanumber/xapian-haystack
xapian_backend.py
https://github.com/notanumber/xapian-haystack/blob/2247b23d3cb6322ce477d45f84d52da47a940348/xapian_backend.py#L719-L815
def more_like_this(self, model_instance, additional_query=None, start_offset=0, end_offset=None, limit_to_registered_models=True, result_class=None, **kwargs): """ Given a model instance, returns a result set of similar documents. Required arguments...
[ "def", "more_like_this", "(", "self", ",", "model_instance", ",", "additional_query", "=", "None", ",", "start_offset", "=", "0", ",", "end_offset", "=", "None", ",", "limit_to_registered_models", "=", "True", ",", "result_class", "=", "None", ",", "*", "*", ...
Given a model instance, returns a result set of similar documents. Required arguments: `model_instance` -- The model instance to use as a basis for retrieving similar documents. Optional arguments: `additional_query` -- An additional query to nar...
[ "Given", "a", "model", "instance", "returns", "a", "result", "set", "of", "similar", "documents", "." ]
python
train
taskcluster/taskcluster-client.py
taskcluster/aio/queue.py
https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/aio/queue.py#L287-L300
async def claimTask(self, *args, **kwargs): """ Claim Task claim a task - never documented This method takes input: ``v1/task-claim-request.json#`` This method gives output: ``v1/task-claim-response.json#`` This method is ``deprecated`` """ return awa...
[ "async", "def", "claimTask", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"claimTask\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Claim Task claim a task - never documented This method takes input: ``v1/task-claim-request.json#`` This method gives output: ``v1/task-claim-response.json#`` This method is ``deprecated``
[ "Claim", "Task" ]
python
train
Esri/ArcREST
src/arcrest/manageorg/_content.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_content.py#L91-L109
def group(self, groupId): """ The group's content provides access to the items that are shared with the group. Group items are stored by reference and are not physically stored in a group. Rather, they are stored as links to the original item in the item resource (/conten...
[ "def", "group", "(", "self", ",", "groupId", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/groups/%s\"", "%", "groupId", "return", "Group", "(", "groupId", "=", "groupId", ",", "contentURL", "=", "url", ",", "securityHandler", "=", "self", ".", "...
The group's content provides access to the items that are shared with the group. Group items are stored by reference and are not physically stored in a group. Rather, they are stored as links to the original item in the item resource (/content/items/<itemId>). Available only to t...
[ "The", "group", "s", "content", "provides", "access", "to", "the", "items", "that", "are", "shared", "with", "the", "group", ".", "Group", "items", "are", "stored", "by", "reference", "and", "are", "not", "physically", "stored", "in", "a", "group", ".", ...
python
train
boriel/zxbasic
outfmt/tap.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/outfmt/tap.py#L28-L39
def standard_block(self, bytes_): """Adds a standard block of bytes. For TAP files, it's just the Low + Hi byte plus the content (here, the bytes plus the checksum) """ self.out(self.LH(len(bytes_) + 1)) # + 1 for CHECKSUM byte checksum = 0 for i in bytes_: ...
[ "def", "standard_block", "(", "self", ",", "bytes_", ")", ":", "self", ".", "out", "(", "self", ".", "LH", "(", "len", "(", "bytes_", ")", "+", "1", ")", ")", "# + 1 for CHECKSUM byte", "checksum", "=", "0", "for", "i", "in", "bytes_", ":", "checksum...
Adds a standard block of bytes. For TAP files, it's just the Low + Hi byte plus the content (here, the bytes plus the checksum)
[ "Adds", "a", "standard", "block", "of", "bytes", ".", "For", "TAP", "files", "it", "s", "just", "the", "Low", "+", "Hi", "byte", "plus", "the", "content", "(", "here", "the", "bytes", "plus", "the", "checksum", ")" ]
python
train
biolink/ontobio
ontobio/sparql/sparql_ontol_utils.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/sparql/sparql_ontol_utils.py#L266-L283
def fetchall_textdefs(ont): """ fetch all text defs for an ontology """ logging.info("fetching text defs for: "+ont) namedGraph = get_named_graph(ont) query = """ prefix IAO: <http://purl.obolibrary.org/obo/IAO_> SELECT * WHERE {{ GRAPH <{g}> {{ ?c IAO:0000115 ?d }} FI...
[ "def", "fetchall_textdefs", "(", "ont", ")", ":", "logging", ".", "info", "(", "\"fetching text defs for: \"", "+", "ont", ")", "namedGraph", "=", "get_named_graph", "(", "ont", ")", "query", "=", "\"\"\"\n prefix IAO: <http://purl.obolibrary.org/obo/IAO_>\n SELECT ...
fetch all text defs for an ontology
[ "fetch", "all", "text", "defs", "for", "an", "ontology" ]
python
train
chaoss/grimoirelab-elk
grimoire_elk/enriched/jira.py
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/jira.py#L109-L142
def get_item_sh(self, item, roles=None, date_field=None): """Add sorting hat enrichment fields""" eitem_sh = {} created = str_to_datetime(date_field) for rol in roles: identity = self.get_sh_identity(item, rol) eitem_sh.update(self.get_item_sh_fields(identity, c...
[ "def", "get_item_sh", "(", "self", ",", "item", ",", "roles", "=", "None", ",", "date_field", "=", "None", ")", ":", "eitem_sh", "=", "{", "}", "created", "=", "str_to_datetime", "(", "date_field", ")", "for", "rol", "in", "roles", ":", "identity", "="...
Add sorting hat enrichment fields
[ "Add", "sorting", "hat", "enrichment", "fields" ]
python
train
readbeyond/aeneas
aeneas/syncmap/fragmentlist.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L311-L331
def has_adjacent_fragments_only(self, min_index=None, max_index=None): """ Return ``True`` if the list contains only adjacent fragments, that is, if it does not have gaps. :param int min_index: examine fragments with index greater than or equal to this index (i.e., included) :pa...
[ "def", "has_adjacent_fragments_only", "(", "self", ",", "min_index", "=", "None", ",", "max_index", "=", "None", ")", ":", "min_index", ",", "max_index", "=", "self", ".", "_check_min_max_indices", "(", "min_index", ",", "max_index", ")", "for", "i", "in", "...
Return ``True`` if the list contains only adjacent fragments, that is, if it does not have gaps. :param int min_index: examine fragments with index greater than or equal to this index (i.e., included) :param int max_index: examine fragments with index smaller than this index (i.e., excluded) ...
[ "Return", "True", "if", "the", "list", "contains", "only", "adjacent", "fragments", "that", "is", "if", "it", "does", "not", "have", "gaps", "." ]
python
train
bram85/topydo
topydo/lib/Graph.py
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Graph.py#L196-L213
def dot(self, p_print_labels=True): """ Prints the graph in Dot format. """ out = 'digraph g {\n' for from_node, neighbors in sorted(self._edges.items()): out += " {}\n".format(from_node) for neighbor in sorted(neighbors): out += " {} -> {}".format(fro...
[ "def", "dot", "(", "self", ",", "p_print_labels", "=", "True", ")", ":", "out", "=", "'digraph g {\\n'", "for", "from_node", ",", "neighbors", "in", "sorted", "(", "self", ".", "_edges", ".", "items", "(", ")", ")", ":", "out", "+=", "\" {}\\n\"", "."...
Prints the graph in Dot format.
[ "Prints", "the", "graph", "in", "Dot", "format", "." ]
python
train
materialsproject/pymatgen
pymatgen/analysis/elasticity/elastic.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/elasticity/elastic.py#L739-L749
def get_strain_from_stress(self, stress): """ Gets the strain from a stress state according to the compliance expansion corresponding to the tensor expansion. """ compl_exp = self.get_compliance_expansion() strain = 0 for n, compl in enumerate(compl_exp): ...
[ "def", "get_strain_from_stress", "(", "self", ",", "stress", ")", ":", "compl_exp", "=", "self", ".", "get_compliance_expansion", "(", ")", "strain", "=", "0", "for", "n", ",", "compl", "in", "enumerate", "(", "compl_exp", ")", ":", "strain", "+=", "compl"...
Gets the strain from a stress state according to the compliance expansion corresponding to the tensor expansion.
[ "Gets", "the", "strain", "from", "a", "stress", "state", "according", "to", "the", "compliance", "expansion", "corresponding", "to", "the", "tensor", "expansion", "." ]
python
train
pip-services3-python/pip-services3-commons-python
pip_services3_commons/data/AnyValueMap.py
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/data/AnyValueMap.py#L210-L219
def get_as_boolean(self, key): """ Converts map element into a boolean or returns false if conversion is not possible. :param key: an index of element to get. :return: boolean value ot the element or false if conversion is not supported. """ value = self.get(key) ...
[ "def", "get_as_boolean", "(", "self", ",", "key", ")", ":", "value", "=", "self", ".", "get", "(", "key", ")", "return", "BooleanConverter", ".", "to_boolean", "(", "value", ")" ]
Converts map element into a boolean or returns false if conversion is not possible. :param key: an index of element to get. :return: boolean value ot the element or false if conversion is not supported.
[ "Converts", "map", "element", "into", "a", "boolean", "or", "returns", "false", "if", "conversion", "is", "not", "possible", "." ]
python
train
CalebBell/thermo
thermo/eos.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L764-L787
def V_g_sat(self, T): r'''Method to calculate molar volume of the vapor phase along the saturation line. Parameters ---------- T : float Temperature, [K] Returns ------- V_g_sat : float Gas molar volume along the saturatio...
[ "def", "V_g_sat", "(", "self", ",", "T", ")", ":", "Psat", "=", "self", ".", "Psat", "(", "T", ")", "a_alpha", "=", "self", ".", "a_alpha_and_derivatives", "(", "T", ",", "full", "=", "False", ")", "Vs", "=", "self", ".", "volume_solutions", "(", "...
r'''Method to calculate molar volume of the vapor phase along the saturation line. Parameters ---------- T : float Temperature, [K] Returns ------- V_g_sat : float Gas molar volume along the saturation line, [m^3/mol] ...
[ "r", "Method", "to", "calculate", "molar", "volume", "of", "the", "vapor", "phase", "along", "the", "saturation", "line", ".", "Parameters", "----------", "T", ":", "float", "Temperature", "[", "K", "]" ]
python
valid
hishnash/djangochannelsrestframework
djangochannelsrestframework/observer/observer.py
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/observer/observer.py#L171-L187
def pre_change_receiver(self, instance: Model, action: Action): """ Entry point for triggering the old_binding from save signals. """ if action == Action.CREATE: group_names = set() else: group_names = set(self.group_names(instance)) # use a threa...
[ "def", "pre_change_receiver", "(", "self", ",", "instance", ":", "Model", ",", "action", ":", "Action", ")", ":", "if", "action", "==", "Action", ".", "CREATE", ":", "group_names", "=", "set", "(", ")", "else", ":", "group_names", "=", "set", "(", "sel...
Entry point for triggering the old_binding from save signals.
[ "Entry", "point", "for", "triggering", "the", "old_binding", "from", "save", "signals", "." ]
python
train
pandas-dev/pandas
pandas/core/sorting.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sorting.py#L151-L173
def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull): """ reconstruct labels from observed group ids Parameters ---------- xnull: boolean, if nulls are excluded; i.e. -1 labels are passed through """ if not xnull: lift = np.fromiter(((a == -1).any() for a in la...
[ "def", "decons_obs_group_ids", "(", "comp_ids", ",", "obs_ids", ",", "shape", ",", "labels", ",", "xnull", ")", ":", "if", "not", "xnull", ":", "lift", "=", "np", ".", "fromiter", "(", "(", "(", "a", "==", "-", "1", ")", ".", "any", "(", ")", "fo...
reconstruct labels from observed group ids Parameters ---------- xnull: boolean, if nulls are excluded; i.e. -1 labels are passed through
[ "reconstruct", "labels", "from", "observed", "group", "ids" ]
python
train
MisterY/pydatum
pydatum/datum.py
https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L196-L202
def to_datetime_string(self) -> str: """ Returns a human-readable string representation with iso date and time Example: 2018-12-06 12:32:56 """ date_display = self.to_iso_date_string() time_display = self.to_long_time_string() return f"{date_display} {time_display}"
[ "def", "to_datetime_string", "(", "self", ")", "->", "str", ":", "date_display", "=", "self", ".", "to_iso_date_string", "(", ")", "time_display", "=", "self", ".", "to_long_time_string", "(", ")", "return", "f\"{date_display} {time_display}\"" ]
Returns a human-readable string representation with iso date and time Example: 2018-12-06 12:32:56
[ "Returns", "a", "human", "-", "readable", "string", "representation", "with", "iso", "date", "and", "time", "Example", ":", "2018", "-", "12", "-", "06", "12", ":", "32", ":", "56" ]
python
train
intel-analytics/BigDL
pyspark/bigdl/dlframes/dl_image_transformer.py
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/dlframes/dl_image_transformer.py#L44-L50
def transform(self, dataset): """ Apply the transformer to the images in "inputCol" and store the transformed result into "outputCols" """ self._transfer_params_to_java() return callBigDlFunc(self.bigdl_type, "dlImageTransform", self.value, dataset)
[ "def", "transform", "(", "self", ",", "dataset", ")", ":", "self", ".", "_transfer_params_to_java", "(", ")", "return", "callBigDlFunc", "(", "self", ".", "bigdl_type", ",", "\"dlImageTransform\"", ",", "self", ".", "value", ",", "dataset", ")" ]
Apply the transformer to the images in "inputCol" and store the transformed result into "outputCols"
[ "Apply", "the", "transformer", "to", "the", "images", "in", "inputCol", "and", "store", "the", "transformed", "result", "into", "outputCols" ]
python
test