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
johnbywater/eventsourcing
eventsourcing/infrastructure/base.py
https://github.com/johnbywater/eventsourcing/blob/de2c22c653fdccf2f5ee96faea74453ff1847e42/eventsourcing/infrastructure/base.py#L284-L295
def insert_tracking_record(self): """ SQL statement that inserts tracking records. """ if self._insert_tracking_record is None: self._insert_tracking_record = self._prepare_insert( tmpl=self._insert_values_tmpl, placeholder_for_id=True, ...
[ "def", "insert_tracking_record", "(", "self", ")", ":", "if", "self", ".", "_insert_tracking_record", "is", "None", ":", "self", ".", "_insert_tracking_record", "=", "self", ".", "_prepare_insert", "(", "tmpl", "=", "self", ".", "_insert_values_tmpl", ",", "plac...
SQL statement that inserts tracking records.
[ "SQL", "statement", "that", "inserts", "tracking", "records", "." ]
python
train
pyviz/holoviews
holoviews/plotting/plotly/util.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/plotly/util.py#L487-L508
def merge_figure(fig, subfig): """ Merge a sub-figure into a parent figure Note: This function mutates the input fig dict, but it does not mutate the subfig dict Parameters ---------- fig: dict The plotly figure dict into which the sub figure will be merged subfig: dict ...
[ "def", "merge_figure", "(", "fig", ",", "subfig", ")", ":", "# traces", "data", "=", "fig", ".", "setdefault", "(", "'data'", ",", "[", "]", ")", "data", ".", "extend", "(", "copy", ".", "deepcopy", "(", "subfig", ".", "get", "(", "'data'", ",", "[...
Merge a sub-figure into a parent figure Note: This function mutates the input fig dict, but it does not mutate the subfig dict Parameters ---------- fig: dict The plotly figure dict into which the sub figure will be merged subfig: dict The plotly figure dict that will be copied...
[ "Merge", "a", "sub", "-", "figure", "into", "a", "parent", "figure" ]
python
train
ThreatConnect-Inc/tcex
tcex/tcex.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L667-L682
def metric(self, name, description, data_type, interval, keyed=False): """Get instance of the Metrics module. Args: name (string): The name for the metric. description (string): The description of the metric. data_type (string): The type of metric: Sum, Count, Min, M...
[ "def", "metric", "(", "self", ",", "name", ",", "description", ",", "data_type", ",", "interval", ",", "keyed", "=", "False", ")", ":", "from", ".", "tcex_metrics_v2", "import", "TcExMetricsV2", "return", "TcExMetricsV2", "(", "self", ",", "name", ",", "de...
Get instance of the Metrics module. Args: name (string): The name for the metric. description (string): The description of the metric. data_type (string): The type of metric: Sum, Count, Min, Max, First, Last, and Average. interval (string): The metric interval: ...
[ "Get", "instance", "of", "the", "Metrics", "module", "." ]
python
train
aio-libs/yarl
yarl/__init__.py
https://github.com/aio-libs/yarl/blob/e47da02c00ad764e030ca7647a9565548c97d362/yarl/__init__.py#L347-L361
def origin(self): """Return an URL with scheme, host and port parts only. user, password, path, query and fragment are removed. """ # TODO: add a keyword-only option for keeping user/pass maybe? if not self.is_absolute(): raise ValueError("URL should be absolute") ...
[ "def", "origin", "(", "self", ")", ":", "# TODO: add a keyword-only option for keeping user/pass maybe?", "if", "not", "self", ".", "is_absolute", "(", ")", ":", "raise", "ValueError", "(", "\"URL should be absolute\"", ")", "if", "not", "self", ".", "_val", ".", ...
Return an URL with scheme, host and port parts only. user, password, path, query and fragment are removed.
[ "Return", "an", "URL", "with", "scheme", "host", "and", "port", "parts", "only", "." ]
python
train
O365/python-o365
O365/message.py
https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/message.py#L575-L611
def send(self, save_to_sent_folder=True): """ Sends this message :param bool save_to_sent_folder: whether or not to save it to sent folder :return: Success / Failure :rtype: bool """ if self.object_id and not self.__is_draft: return RuntimeError('No...
[ "def", "send", "(", "self", ",", "save_to_sent_folder", "=", "True", ")", ":", "if", "self", ".", "object_id", "and", "not", "self", ".", "__is_draft", ":", "return", "RuntimeError", "(", "'Not possible to send a message that is not '", "'new or a draft. Use Reply or ...
Sends this message :param bool save_to_sent_folder: whether or not to save it to sent folder :return: Success / Failure :rtype: bool
[ "Sends", "this", "message" ]
python
train
CalebBell/ht
ht/hx.py
https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/hx.py#L6001-L6064
def Ntubes_VDI(DBundle=None, Ntp=None, Do=None, pitch=None, angle=30.): r'''A rough equation presented in the VDI Heat Atlas for estimating the number of tubes in a tube bundle of differing geometries and tube sizes. No accuracy estimation given. Parameters ---------- DBundle : float Ou...
[ "def", "Ntubes_VDI", "(", "DBundle", "=", "None", ",", "Ntp", "=", "None", ",", "Do", "=", "None", ",", "pitch", "=", "None", ",", "angle", "=", "30.", ")", ":", "if", "Ntp", "==", "1", ":", "f2", "=", "0.", "elif", "Ntp", "==", "2", ":", "f2...
r'''A rough equation presented in the VDI Heat Atlas for estimating the number of tubes in a tube bundle of differing geometries and tube sizes. No accuracy estimation given. Parameters ---------- DBundle : float Outer diameter of tube bundle, [m] Ntp : float Number of tube pass...
[ "r", "A", "rough", "equation", "presented", "in", "the", "VDI", "Heat", "Atlas", "for", "estimating", "the", "number", "of", "tubes", "in", "a", "tube", "bundle", "of", "differing", "geometries", "and", "tube", "sizes", ".", "No", "accuracy", "estimation", ...
python
train
PyGithub/PyGithub
github/MainClass.py
https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/MainClass.py#L317-L328
def get_project(self, id): """ :calls: `GET /projects/:project_id <https://developer.github.com/v3/projects/#get-a-project>`_ :rtype: :class:`github.Project.Project` :param id: integer """ headers, data = self.__requester.requestJsonAndCheck( "GET", ...
[ "def", "get_project", "(", "self", ",", "id", ")", ":", "headers", ",", "data", "=", "self", ".", "__requester", ".", "requestJsonAndCheck", "(", "\"GET\"", ",", "\"/projects/%d\"", "%", "(", "id", ")", ",", "headers", "=", "{", "\"Accept\"", ":", "Const...
:calls: `GET /projects/:project_id <https://developer.github.com/v3/projects/#get-a-project>`_ :rtype: :class:`github.Project.Project` :param id: integer
[ ":", "calls", ":", "GET", "/", "projects", "/", ":", "project_id", "<https", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "projects", "/", "#get", "-", "a", "-", "project", ">", "_", ":", "rtype", ":", ":", "class", ":", "gi...
python
train
saltstack/salt
salt/utils/dns.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dns.py#L378-L401
def _lookup_gai(name, rdtype, timeout=None): ''' Use Python's socket interface to lookup addresses :param name: Name of record to search :param rdtype: A or AAAA :param timeout: ignored :return: [] of addresses or False if error ''' try: sock_t = { 'A': socket.AF_I...
[ "def", "_lookup_gai", "(", "name", ",", "rdtype", ",", "timeout", "=", "None", ")", ":", "try", ":", "sock_t", "=", "{", "'A'", ":", "socket", ".", "AF_INET", ",", "'AAAA'", ":", "socket", ".", "AF_INET6", "}", "[", "rdtype", "]", "except", "KeyError...
Use Python's socket interface to lookup addresses :param name: Name of record to search :param rdtype: A or AAAA :param timeout: ignored :return: [] of addresses or False if error
[ "Use", "Python", "s", "socket", "interface", "to", "lookup", "addresses", ":", "param", "name", ":", "Name", "of", "record", "to", "search", ":", "param", "rdtype", ":", "A", "or", "AAAA", ":", "param", "timeout", ":", "ignored", ":", "return", ":", "[...
python
train
QunarOPS/qg.core
qg/core/timeutils.py
https://github.com/QunarOPS/qg.core/blob/d5d7e36ea140cfe73e1b1850e8c96960b02a1ed3/qg/core/timeutils.py#L135-L142
def advance_time_delta(timedelta): """Advance overridden time using a datetime.timedelta.""" assert(utcnow.override_time is not None) try: for dt in utcnow.override_time: dt += timedelta except TypeError: utcnow.override_time += timedelta
[ "def", "advance_time_delta", "(", "timedelta", ")", ":", "assert", "(", "utcnow", ".", "override_time", "is", "not", "None", ")", "try", ":", "for", "dt", "in", "utcnow", ".", "override_time", ":", "dt", "+=", "timedelta", "except", "TypeError", ":", "utcn...
Advance overridden time using a datetime.timedelta.
[ "Advance", "overridden", "time", "using", "a", "datetime", ".", "timedelta", "." ]
python
train
wndhydrnt/python-oauth2
oauth2/grant.py
https://github.com/wndhydrnt/python-oauth2/blob/abe3bf5f27bda2ff737cab387b040e2e6e85c2e2/oauth2/grant.py#L262-L279
def read_validate_params(self, request): """ Reads and validates data in an incoming request as required by the Authorization Request of the Authorization Code Grant and the Implicit Grant. """ self.client = self.client_authenticator.by_identifier(request) respon...
[ "def", "read_validate_params", "(", "self", ",", "request", ")", ":", "self", ".", "client", "=", "self", ".", "client_authenticator", ".", "by_identifier", "(", "request", ")", "response_type", "=", "request", ".", "get_param", "(", "\"response_type\"", ")", ...
Reads and validates data in an incoming request as required by the Authorization Request of the Authorization Code Grant and the Implicit Grant.
[ "Reads", "and", "validates", "data", "in", "an", "incoming", "request", "as", "required", "by", "the", "Authorization", "Request", "of", "the", "Authorization", "Code", "Grant", "and", "the", "Implicit", "Grant", "." ]
python
train
ArchiveTeam/wpull
wpull/path.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/path.py#L221-L281
def safe_filename(filename, os_type='unix', no_control=True, ascii_only=True, case=None, encoding='utf8', max_length=None): '''Return a safe filename or path part. Args: filename (str): The filename or path component. os_type (str): If ``unix``, escape the slash. If ``windows`...
[ "def", "safe_filename", "(", "filename", ",", "os_type", "=", "'unix'", ",", "no_control", "=", "True", ",", "ascii_only", "=", "True", ",", "case", "=", "None", ",", "encoding", "=", "'utf8'", ",", "max_length", "=", "None", ")", ":", "assert", "isinsta...
Return a safe filename or path part. Args: filename (str): The filename or path component. os_type (str): If ``unix``, escape the slash. If ``windows``, escape extra Windows characters. no_control (bool): If True, escape control characters. ascii_only (bool): If True, es...
[ "Return", "a", "safe", "filename", "or", "path", "part", "." ]
python
train
deepmind/pysc2
pysc2/lib/renderer_human.py
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/renderer_human.py#L172-L186
def write_screen(self, font, color, screen_pos, text, align="left", valign="top"): """Write to the screen in font.size relative coordinates.""" pos = point.Point(*screen_pos) * point.Point(0.75, 1) * font.get_linesize() text_surf = font.render(str(text), True, color) rect = text_surf....
[ "def", "write_screen", "(", "self", ",", "font", ",", "color", ",", "screen_pos", ",", "text", ",", "align", "=", "\"left\"", ",", "valign", "=", "\"top\"", ")", ":", "pos", "=", "point", ".", "Point", "(", "*", "screen_pos", ")", "*", "point", ".", ...
Write to the screen in font.size relative coordinates.
[ "Write", "to", "the", "screen", "in", "font", ".", "size", "relative", "coordinates", "." ]
python
train
O365/python-o365
O365/calendar.py
https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/calendar.py#L1752-L1789
def list_calendars(self, limit=None, *, query=None, order_by=None): """ Gets a list of calendars To use query an order_by check the OData specification here: http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/ part2-url-conventions/odata-v4.0-errata03-os-part2-url-conventi...
[ "def", "list_calendars", "(", "self", ",", "limit", "=", "None", ",", "*", ",", "query", "=", "None", ",", "order_by", "=", "None", ")", ":", "url", "=", "self", ".", "build_url", "(", "self", ".", "_endpoints", ".", "get", "(", "'root_calendars'", "...
Gets a list of calendars To use query an order_by check the OData specification here: http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/ part2-url-conventions/odata-v4.0-errata03-os-part2-url-conventions -complete.html :param int limit: max no. of calendars to ge...
[ "Gets", "a", "list", "of", "calendars" ]
python
train
peterbrittain/asciimatics
asciimatics/widgets.py
https://github.com/peterbrittain/asciimatics/blob/f471427d7786ce2d5f1eeb2dae0e67d19e46e085/asciimatics/widgets.py#L1292-L1306
def find_widget(self, name): """ Look for a widget with a specified name. :param name: The name to search for. :returns: The widget that matches or None if one couldn't be found. """ result = None for column in self._columns: for widget in column: ...
[ "def", "find_widget", "(", "self", ",", "name", ")", ":", "result", "=", "None", "for", "column", "in", "self", ".", "_columns", ":", "for", "widget", "in", "column", ":", "if", "widget", ".", "name", "is", "not", "None", "and", "name", "==", "widget...
Look for a widget with a specified name. :param name: The name to search for. :returns: The widget that matches or None if one couldn't be found.
[ "Look", "for", "a", "widget", "with", "a", "specified", "name", "." ]
python
train
pip-services3-python/pip-services3-commons-python
pip_services3_commons/reflect/PropertyReflector.py
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/PropertyReflector.py#L73-L102
def get_property(obj, name): """ Gets value of object property specified by its name. :param obj: an object to read property from. :param name: a name of the property to get. :return: the property value or null if property doesn't exist or introspection failed. """ ...
[ "def", "get_property", "(", "obj", ",", "name", ")", ":", "if", "obj", "==", "None", ":", "raise", "Exception", "(", "\"Object cannot be null\"", ")", "if", "name", "==", "None", ":", "raise", "Exception", "(", "\"Property name cannot be null\"", ")", "name", ...
Gets value of object property specified by its name. :param obj: an object to read property from. :param name: a name of the property to get. :return: the property value or null if property doesn't exist or introspection failed.
[ "Gets", "value", "of", "object", "property", "specified", "by", "its", "name", "." ]
python
train
20c/vaping
vaping/plugins/__init__.py
https://github.com/20c/vaping/blob/c51f00586c99edb3d51e4abdbdfe3174755533ee/vaping/plugins/__init__.py#L413-L421
def format_filename(self, data, row): """ Returns a formatted filename using the template stored in self.filename - `data`: vaping message - `row`: vaping message data row """ return self.filename.format(**self.filename_formatters(data, row))
[ "def", "format_filename", "(", "self", ",", "data", ",", "row", ")", ":", "return", "self", ".", "filename", ".", "format", "(", "*", "*", "self", ".", "filename_formatters", "(", "data", ",", "row", ")", ")" ]
Returns a formatted filename using the template stored in self.filename - `data`: vaping message - `row`: vaping message data row
[ "Returns", "a", "formatted", "filename", "using", "the", "template", "stored", "in", "self", ".", "filename" ]
python
train
GNS3/gns3-server
gns3server/compute/port_manager.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/port_manager.py#L209-L253
def reserve_tcp_port(self, port, project, port_range_start=None, port_range_end=None): """ Reserve a specific TCP port number. If not available replace it by another. :param port: TCP port number :param project: Project instance :param port_range_start: Port range to use...
[ "def", "reserve_tcp_port", "(", "self", ",", "port", ",", "project", ",", "port_range_start", "=", "None", ",", "port_range_end", "=", "None", ")", ":", "# use the default range is not specific one is given", "if", "port_range_start", "is", "None", "and", "port_range_...
Reserve a specific TCP port number. If not available replace it by another. :param port: TCP port number :param project: Project instance :param port_range_start: Port range to use :param port_range_end: Port range to use :returns: The TCP port
[ "Reserve", "a", "specific", "TCP", "port", "number", ".", "If", "not", "available", "replace", "it", "by", "another", "." ]
python
train
emirozer/fake2db
fake2db/redis_handler.py
https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/redis_handler.py#L143-L166
def data_filler_customer(self, number_of_rows, pipe): '''creates keys with customer data ''' try: for i in range(number_of_rows): pipe.hmset('customer:%s' % i, { 'id': rnd_id_generator(self), 'name': self.faker.first_name(), ...
[ "def", "data_filler_customer", "(", "self", ",", "number_of_rows", ",", "pipe", ")", ":", "try", ":", "for", "i", "in", "range", "(", "number_of_rows", ")", ":", "pipe", ".", "hmset", "(", "'customer:%s'", "%", "i", ",", "{", "'id'", ":", "rnd_id_generat...
creates keys with customer data
[ "creates", "keys", "with", "customer", "data" ]
python
train
saltstack/salt
salt/modules/boto_s3_bucket.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_s3_bucket.py#L562-L597
def put_logging(Bucket, TargetBucket=None, TargetPrefix=None, TargetGrants=None, region=None, key=None, keyid=None, profile=None): ''' Given a valid config, update the logging parameters for a bucket. Returns {updated: true} if parameters were updated and returns {updated: False} ...
[ "def", "put_logging", "(", "Bucket", ",", "TargetBucket", "=", "None", ",", "TargetPrefix", "=", "None", ",", "TargetGrants", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")",...
Given a valid config, update the logging parameters for a bucket. Returns {updated: true} if parameters were updated and returns {updated: False} if parameters were not updated. CLI Example: .. code-block:: bash salt myminion boto_s3_bucket.put_logging my_bucket log_bucket '[{...}]' prefix
[ "Given", "a", "valid", "config", "update", "the", "logging", "parameters", "for", "a", "bucket", "." ]
python
train
AguaClara/aguaclara
aguaclara/design/sed_tank.py
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L527-L547
def L_channel(Q_plant, sed_inputs=sed_dict): """Return the length of the inlet and exit channels for the sedimentation tank. Parameters ---------- Q_plant : float Total plant flow rate sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank ...
[ "def", "L_channel", "(", "Q_plant", ",", "sed_inputs", "=", "sed_dict", ")", ":", "n_tanks", "=", "n_tanks", "(", "Q_plant", ",", "sed_inputs", ")", "return", "(", "(", "n_tanks", "*", "sed_inputs", "[", "'tank'", "]", "[", "'W'", "]", ")", "+", "sed_i...
Return the length of the inlet and exit channels for the sedimentation tank. Parameters ---------- Q_plant : float Total plant flow rate sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ...
[ "Return", "the", "length", "of", "the", "inlet", "and", "exit", "channels", "for", "the", "sedimentation", "tank", ".", "Parameters", "----------", "Q_plant", ":", "float", "Total", "plant", "flow", "rate", "sed_inputs", ":", "dict", "A", "dictionary", "of", ...
python
train
martinpitt/python-dbusmock
dbusmock/templates/ofono.py
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L169-L190
def add_voice_call_api(mock): '''Add org.ofono.VoiceCallManager API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock.AddProperty('org.ofono.VoiceCallManager', 'EmergencyNumbers', ['911', '13373']) mock.calls = [...
[ "def", "add_voice_call_api", "(", "mock", ")", ":", "# also add an emergency number which is not a real one, in case one runs a", "# test case against a production ofono :-)", "mock", ".", "AddProperty", "(", "'org.ofono.VoiceCallManager'", ",", "'EmergencyNumbers'", ",", "[", "'91...
Add org.ofono.VoiceCallManager API to a mock
[ "Add", "org", ".", "ofono", ".", "VoiceCallManager", "API", "to", "a", "mock" ]
python
train
devries/bottle-session
bottle_session.py
https://github.com/devries/bottle-session/blob/aaa33eecbf977d6b2ad7d3835d2176f40b3231e5/bottle_session.py#L293-L300
def keys(self): """Return a list of all keys in the dictionary. Returns: list of str: [key1,key2,...,keyN] """ all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()] return all_keys
[ "def", "keys", "(", "self", ")", ":", "all_keys", "=", "[", "k", ".", "decode", "(", "'utf-8'", ")", "for", "k", ",", "v", "in", "self", ".", "rdb", ".", "hgetall", "(", "self", ".", "session_hash", ")", ".", "items", "(", ")", "]", "return", "...
Return a list of all keys in the dictionary. Returns: list of str: [key1,key2,...,keyN]
[ "Return", "a", "list", "of", "all", "keys", "in", "the", "dictionary", "." ]
python
train
thiagopbueno/rddl2tf
rddl2tf/fluent.py
https://github.com/thiagopbueno/rddl2tf/blob/f7c03d3a74d2663807c1e23e04eeed2e85166b71/rddl2tf/fluent.py#L601-L619
def _varslist2axis(cls, fluent: 'TensorFluent', vars_list: List[str]) -> List[int]: '''Maps the `vars_list` into a list of axis indices corresponding to the `fluent` scope. Args: x: The fluent. vars_list: The list of variables to be aggregated over. Returns: ...
[ "def", "_varslist2axis", "(", "cls", ",", "fluent", ":", "'TensorFluent'", ",", "vars_list", ":", "List", "[", "str", "]", ")", "->", "List", "[", "int", "]", ":", "axis", "=", "[", "]", "for", "var", "in", "vars_list", ":", "if", "var", "in", "flu...
Maps the `vars_list` into a list of axis indices corresponding to the `fluent` scope. Args: x: The fluent. vars_list: The list of variables to be aggregated over. Returns: List[int]: a list of axis.
[ "Maps", "the", "vars_list", "into", "a", "list", "of", "axis", "indices", "corresponding", "to", "the", "fluent", "scope", "." ]
python
train
kapot65/python-df-parser
dfparser/rsh_parser.py
https://github.com/kapot65/python-df-parser/blob/bb3eec0fb7ca85d72cb1d9ed7415efe074594f26/dfparser/rsh_parser.py#L351-L379
def get_event(self, num): """Extract event from dataset.""" if num < 0 or num >= self.params["events_num"]: raise IndexError("Index out of range [0:%s]" % (self.params["events_num"])) ch_num = self.params['channel_number'] ev_size = self.params['...
[ "def", "get_event", "(", "self", ",", "num", ")", ":", "if", "num", "<", "0", "or", "num", ">=", "self", ".", "params", "[", "\"events_num\"", "]", ":", "raise", "IndexError", "(", "\"Index out of range [0:%s]\"", "%", "(", "self", ".", "params", "[", ...
Extract event from dataset.
[ "Extract", "event", "from", "dataset", "." ]
python
train
CEA-COSMIC/ModOpt
modopt/opt/proximity.py
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/opt/proximity.py#L295-L314
def _op_method(self, data, extra_factor=1.0): r"""Operator method This method returns the scaled version of the proximity operator as given by Lemma 2.8 of [CW2005]. Parameters ---------- data : np.ndarray Input data array extra_factor : float ...
[ "def", "_op_method", "(", "self", ",", "data", ",", "extra_factor", "=", "1.0", ")", ":", "return", "self", ".", "linear_op", ".", "adj_op", "(", "self", ".", "prox_op", ".", "op", "(", "self", ".", "linear_op", ".", "op", "(", "data", ")", ",", "e...
r"""Operator method This method returns the scaled version of the proximity operator as given by Lemma 2.8 of [CW2005]. Parameters ---------- data : np.ndarray Input data array extra_factor : float Additional multiplication factor Return...
[ "r", "Operator", "method" ]
python
train
materialsproject/pymatgen
pymatgen/io/vasp/outputs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/outputs.py#L1916-L1933
def read_cs_core_contribution(self): """ Parse the core contribution of NMR chemical shielding. Returns: G0 contribution matrix as list of list. """ header_pattern = r'^\s+Core NMR properties\s*$\n' \ r'\n' \ ...
[ "def", "read_cs_core_contribution", "(", "self", ")", ":", "header_pattern", "=", "r'^\\s+Core NMR properties\\s*$\\n'", "r'\\n'", "r'^\\s+typ\\s+El\\s+Core shift \\(ppm\\)\\s*$\\n'", "r'^\\s+-{20,}$\\n'", "row_pattern", "=", "r'\\d+\\s+(?P<element>[A-Z][a-z]?\\w?)\\s+(?P<shift>[-]?\\d+\...
Parse the core contribution of NMR chemical shielding. Returns: G0 contribution matrix as list of list.
[ "Parse", "the", "core", "contribution", "of", "NMR", "chemical", "shielding", "." ]
python
train
ansible/tacacs_plus
tacacs_plus/packet.py
https://github.com/ansible/tacacs_plus/blob/de0d01372169c8849fa284d75097e57367c8930f/tacacs_plus/packet.py#L7-L70
def crypt(header, body_bytes, secret): """ TACACS+ uses a shared secret key (known to both the client and server) to obfuscate the body of sent packets. Only the packet body (not the header) is obfuscated. https://datatracker.ietf.org/doc/draft-ietf-opsawg-tacacs/?include_text=1#section-3.7 E...
[ "def", "crypt", "(", "header", ",", "body_bytes", ",", "secret", ")", ":", "# noqa", "# B = unsigned char", "# !I = network-order (big-endian) unsigned int", "body_length", "=", "len", "(", "body_bytes", ")", "unhashed", "=", "(", "struct", ".", "pack", "(", "'!I'...
TACACS+ uses a shared secret key (known to both the client and server) to obfuscate the body of sent packets. Only the packet body (not the header) is obfuscated. https://datatracker.ietf.org/doc/draft-ietf-opsawg-tacacs/?include_text=1#section-3.7 ENCRYPTED {data} == data ^ pseudo_pad The pad i...
[ "TACACS", "+", "uses", "a", "shared", "secret", "key", "(", "known", "to", "both", "the", "client", "and", "server", ")", "to", "obfuscate", "the", "body", "of", "sent", "packets", ".", "Only", "the", "packet", "body", "(", "not", "the", "header", ")",...
python
train
pydata/xarray
xarray/core/common.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/common.py#L252-L280
def squeeze(self, dim: Union[Hashable, Iterable[Hashable], None] = None, drop: bool = False, axis: Union[int, Iterable[int], None] = None): """Return a new object with squeezed data. Parameters ---------- dim : None or Hashable or iterable of Hashable, op...
[ "def", "squeeze", "(", "self", ",", "dim", ":", "Union", "[", "Hashable", ",", "Iterable", "[", "Hashable", "]", ",", "None", "]", "=", "None", ",", "drop", ":", "bool", "=", "False", ",", "axis", ":", "Union", "[", "int", ",", "Iterable", "[", "...
Return a new object with squeezed data. Parameters ---------- dim : None or Hashable or iterable of Hashable, optional Selects a subset of the length one dimensions. If a dimension is selected with length greater than one, an error is raised. If None, all len...
[ "Return", "a", "new", "object", "with", "squeezed", "data", "." ]
python
train
taskcluster/taskcluster-client.py
taskcluster/aio/auth.py
https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/aio/auth.py#L457-L468
async def azureAccounts(self, *args, **kwargs): """ List Accounts Managed by Auth Retrieve a list of all Azure accounts managed by Taskcluster Auth. This method gives output: ``v1/azure-account-list-response.json#`` This method is ``stable`` """ return await s...
[ "async", "def", "azureAccounts", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"azureAccounts\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ...
List Accounts Managed by Auth Retrieve a list of all Azure accounts managed by Taskcluster Auth. This method gives output: ``v1/azure-account-list-response.json#`` This method is ``stable``
[ "List", "Accounts", "Managed", "by", "Auth" ]
python
train
mitsei/dlkit
dlkit/json_/assessment_authoring/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment_authoring/sessions.py#L1488-L1507
def unassign_assessment_part_from_bank(self, assessment_part_id, bank_id): """Removes an ``AssessmentPart`` from an ``Bank``. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank`` raise: No...
[ "def", "unassign_assessment_part_from_bank", "(", "self", ",", "assessment_part_id", ",", "bank_id", ")", ":", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'ASSESSMENT'", ",", "local", "=", "True", ")", "lookup_session", "=", "mgr", ".", "get_bank_looku...
Removes an ``AssessmentPart`` from an ``Bank``. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank`` raise: NotFound - ``assessment_part_id`` or ``bank_id`` not found or ``assessme...
[ "Removes", "an", "AssessmentPart", "from", "an", "Bank", "." ]
python
train
COALAIP/pycoalaip
coalaip/data_formats.py
https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/data_formats.py#L34-L53
def _make_context_immutable(context): """Best effort attempt at turning a properly formatted context (either a string, dict, or array of strings and dicts) into an immutable data structure. If we get an array, make it immutable by creating a tuple; if we get a dict, copy it into a MappingProxyType....
[ "def", "_make_context_immutable", "(", "context", ")", ":", "def", "make_immutable", "(", "val", ")", ":", "if", "isinstance", "(", "val", ",", "Mapping", ")", ":", "return", "MappingProxyType", "(", "val", ")", "else", ":", "return", "val", "if", "not", ...
Best effort attempt at turning a properly formatted context (either a string, dict, or array of strings and dicts) into an immutable data structure. If we get an array, make it immutable by creating a tuple; if we get a dict, copy it into a MappingProxyType. Otherwise, return as-is.
[ "Best", "effort", "attempt", "at", "turning", "a", "properly", "formatted", "context", "(", "either", "a", "string", "dict", "or", "array", "of", "strings", "and", "dicts", ")", "into", "an", "immutable", "data", "structure", "." ]
python
train
saltstack/salt
salt/cloud/clouds/digitalocean.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L245-L262
def get_location(vm_): ''' Return the VM's location ''' locations = avail_locations() vm_location = six.text_type(config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False )) for location in locations: if vm_location in (locations[location]['name'], ...
[ "def", "get_location", "(", "vm_", ")", ":", "locations", "=", "avail_locations", "(", ")", "vm_location", "=", "six", ".", "text_type", "(", "config", ".", "get_cloud_config_value", "(", "'location'", ",", "vm_", ",", "__opts__", ",", "search_global", "=", ...
Return the VM's location
[ "Return", "the", "VM", "s", "location" ]
python
train
bioasp/caspo
caspo/core/graph.py
https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/graph.py#L48-L67
def read_sif(cls, path): """ Creates a graph from a `simple interaction format (SIF)`_ file Parameters ---------- path : str Absolute path to a SIF file Returns ------- caspo.core.graph.Graph Created object instance .. _...
[ "def", "read_sif", "(", "cls", ",", "path", ")", ":", "df", "=", "pd", ".", "read_csv", "(", "path", ",", "delim_whitespace", "=", "True", ",", "names", "=", "[", "'source'", ",", "'sign'", ",", "'target'", "]", ")", ".", "drop_duplicates", "(", ")",...
Creates a graph from a `simple interaction format (SIF)`_ file Parameters ---------- path : str Absolute path to a SIF file Returns ------- caspo.core.graph.Graph Created object instance .. _simple interaction format (SIF): http://wiki....
[ "Creates", "a", "graph", "from", "a", "simple", "interaction", "format", "(", "SIF", ")", "_", "file" ]
python
train
sepandhaghighi/pycm
pycm/pycm_overall_func.py
https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_overall_func.py#L682-L700
def PC_PI_calc(P, TOP, POP): """ Calculate percent chance agreement for Scott's Pi. :param P: condition positive :type P : dict :param TOP: test outcome positive :type TOP : dict :param POP: population :type POP:dict :return: percent chance agreement as float """ try: ...
[ "def", "PC_PI_calc", "(", "P", ",", "TOP", ",", "POP", ")", ":", "try", ":", "result", "=", "0", "for", "i", "in", "P", ".", "keys", "(", ")", ":", "result", "+=", "(", "(", "P", "[", "i", "]", "+", "TOP", "[", "i", "]", ")", "/", "(", ...
Calculate percent chance agreement for Scott's Pi. :param P: condition positive :type P : dict :param TOP: test outcome positive :type TOP : dict :param POP: population :type POP:dict :return: percent chance agreement as float
[ "Calculate", "percent", "chance", "agreement", "for", "Scott", "s", "Pi", "." ]
python
train
Jammy2211/PyAutoLens
autolens/model/galaxy/galaxy.py
https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy.py#L159-L180
def luminosity_within_ellipse_in_units(self, major_axis : dim.Length, unit_luminosity='eps', kpc_per_arcsec=None, exposure_time=None): """Compute the total luminosity of the galaxy's light profiles, within an ellipse of specified major axis. This is performed via integration of each light profile and i...
[ "def", "luminosity_within_ellipse_in_units", "(", "self", ",", "major_axis", ":", "dim", ".", "Length", ",", "unit_luminosity", "=", "'eps'", ",", "kpc_per_arcsec", "=", "None", ",", "exposure_time", "=", "None", ")", ":", "if", "self", ".", "has_light_profile",...
Compute the total luminosity of the galaxy's light profiles, within an ellipse of specified major axis. This is performed via integration of each light profile and is centred, oriented and aligned with each light model's individual geometry. See *light_profiles.luminosity_within_ellipse* for d...
[ "Compute", "the", "total", "luminosity", "of", "the", "galaxy", "s", "light", "profiles", "within", "an", "ellipse", "of", "specified", "major", "axis", ".", "This", "is", "performed", "via", "integration", "of", "each", "light", "profile", "and", "is", "cen...
python
valid
cltk/cltk
cltk/prosody/latin/verse_scanner.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/prosody/latin/verse_scanner.py#L51-L88
def transform_i_to_j(self, line: str) -> str: """ Transform instances of consonantal i to j :param line: :return: >>> print(VerseScanner().transform_i_to_j("iactātus")) jactātus >>> print(VerseScanner().transform_i_to_j("bracchia")) bracchia """ ...
[ "def", "transform_i_to_j", "(", "self", ",", "line", ":", "str", ")", "->", "str", ":", "words", "=", "line", ".", "split", "(", "\" \"", ")", "space_list", "=", "string_utils", ".", "space_list", "(", "line", ")", "corrected_words", "=", "[", "]", "fo...
Transform instances of consonantal i to j :param line: :return: >>> print(VerseScanner().transform_i_to_j("iactātus")) jactātus >>> print(VerseScanner().transform_i_to_j("bracchia")) bracchia
[ "Transform", "instances", "of", "consonantal", "i", "to", "j", ":", "param", "line", ":", ":", "return", ":" ]
python
train
twilio/twilio-python
twilio/rest/api/v2010/account/incoming_phone_number/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py#L583-L597
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: IncomingPhoneNumberContext for this IncomingPhoneNumberInstance :rtype: twilio.rest.api.v2010.acc...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "IncomingPhoneNumberContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]"...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: IncomingPhoneNumberContext for this IncomingPhoneNumberInstance :rtype: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPho...
[ "Generate", "an", "instance", "context", "for", "the", "instance", "the", "context", "is", "capable", "of", "performing", "various", "actions", ".", "All", "instance", "actions", "are", "proxied", "to", "the", "context" ]
python
train
wandb/client
wandb/vendor/prompt_toolkit/interface.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L202-L216
def start_completion(self, buffer_name=None, select_first=False, select_last=False, insert_common_part=False, complete_event=None): """ Start asynchronous autocompletion of this buffer. (This will do nothing if a previous completion was still in ...
[ "def", "start_completion", "(", "self", ",", "buffer_name", "=", "None", ",", "select_first", "=", "False", ",", "select_last", "=", "False", ",", "insert_common_part", "=", "False", ",", "complete_event", "=", "None", ")", ":", "buffer_name", "=", "buffer_nam...
Start asynchronous autocompletion of this buffer. (This will do nothing if a previous completion was still in progress.)
[ "Start", "asynchronous", "autocompletion", "of", "this", "buffer", ".", "(", "This", "will", "do", "nothing", "if", "a", "previous", "completion", "was", "still", "in", "progress", ".", ")" ]
python
train
pyslackers/slack-sansio
slack/sansio.py
https://github.com/pyslackers/slack-sansio/blob/068ddd6480c6d2f9bf14fa4db498c9fe1017f4ab/slack/sansio.py#L355-L389
def validate_request_signature( body: str, headers: MutableMapping, signing_secret: str ) -> None: """ Validate incoming request signature using the application signing secret. Contrary to the ``team_id`` and ``verification_token`` verification this method is not called by ``slack-sansio`` when creatin...
[ "def", "validate_request_signature", "(", "body", ":", "str", ",", "headers", ":", "MutableMapping", ",", "signing_secret", ":", "str", ")", "->", "None", ":", "request_timestamp", "=", "int", "(", "headers", "[", "\"X-Slack-Request-Timestamp\"", "]", ")", "if",...
Validate incoming request signature using the application signing secret. Contrary to the ``team_id`` and ``verification_token`` verification this method is not called by ``slack-sansio`` when creating object from incoming HTTP request. Because the body of the request needs to be provided as text and not decoded a...
[ "Validate", "incoming", "request", "signature", "using", "the", "application", "signing", "secret", "." ]
python
train
globality-corp/microcosm
microcosm/registry.py
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/registry.py#L43-L51
def all(self): """ Return a synthetic dictionary of all factories. """ return { key: value for key, value in chain(self.entry_points.items(), self.factories.items()) }
[ "def", "all", "(", "self", ")", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "chain", "(", "self", ".", "entry_points", ".", "items", "(", ")", ",", "self", ".", "factories", ".", "items", "(", ")", ")", "}" ]
Return a synthetic dictionary of all factories.
[ "Return", "a", "synthetic", "dictionary", "of", "all", "factories", "." ]
python
train
Microsoft/nni
tools/nni_annotation/code_generator.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_annotation/code_generator.py#L254-L281
def parse(code): """Annotate user code. Return annotated code (str) if annotation detected; return None if not. code: original user code (str) """ try: ast_tree = ast.parse(code) except Exception: raise RuntimeError('Bad Python code') transformer = Transformer() try: ...
[ "def", "parse", "(", "code", ")", ":", "try", ":", "ast_tree", "=", "ast", ".", "parse", "(", "code", ")", "except", "Exception", ":", "raise", "RuntimeError", "(", "'Bad Python code'", ")", "transformer", "=", "Transformer", "(", ")", "try", ":", "trans...
Annotate user code. Return annotated code (str) if annotation detected; return None if not. code: original user code (str)
[ "Annotate", "user", "code", ".", "Return", "annotated", "code", "(", "str", ")", "if", "annotation", "detected", ";", "return", "None", "if", "not", ".", "code", ":", "original", "user", "code", "(", "str", ")" ]
python
train
ray-project/ray
python/ray/tune/scripts.py
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/scripts.py#L75-L79
def list_experiments(project_path, sort, output, filter_op, columns): """Lists experiments in the directory subtree.""" if columns: columns = columns.split(",") commands.list_experiments(project_path, sort, output, filter_op, columns)
[ "def", "list_experiments", "(", "project_path", ",", "sort", ",", "output", ",", "filter_op", ",", "columns", ")", ":", "if", "columns", ":", "columns", "=", "columns", ".", "split", "(", "\",\"", ")", "commands", ".", "list_experiments", "(", "project_path"...
Lists experiments in the directory subtree.
[ "Lists", "experiments", "in", "the", "directory", "subtree", "." ]
python
train
opencobra/cobrapy
cobra/util/solver.py
https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/util/solver.py#L316-L360
def add_absolute_expression(model, expression, name="abs_var", ub=None, difference=0, add=True): """Add the absolute value of an expression to the model. Also defines a variable for the absolute value that can be used in other objectives or constraints. Parameters -----...
[ "def", "add_absolute_expression", "(", "model", ",", "expression", ",", "name", "=", "\"abs_var\"", ",", "ub", "=", "None", ",", "difference", "=", "0", ",", "add", "=", "True", ")", ":", "Components", "=", "namedtuple", "(", "'Components'", ",", "[", "'...
Add the absolute value of an expression to the model. Also defines a variable for the absolute value that can be used in other objectives or constraints. Parameters ---------- model : a cobra model The model to which to add the absolute expression. expression : A sympy expression ...
[ "Add", "the", "absolute", "value", "of", "an", "expression", "to", "the", "model", "." ]
python
valid
SheffieldML/GPy
GPy/plotting/gpy_plot/latent_plots.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/plotting/gpy_plot/latent_plots.py#L305-L346
def plot_steepest_gradient_map(self, output_labels=None, data_labels=None, which_indices=None, resolution=15, legend=True, plot_limits=None, updates=False, kern=None, marker='<>^vsd', num_samples=1000, annotation_kwargs=None...
[ "def", "plot_steepest_gradient_map", "(", "self", ",", "output_labels", "=", "None", ",", "data_labels", "=", "None", ",", "which_indices", "=", "None", ",", "resolution", "=", "15", ",", "legend", "=", "True", ",", "plot_limits", "=", "None", ",", "updates"...
Plot the latent space of the GP on the inputs. This is the density of the GP posterior as a grey scale and the scatter plot of the input dimemsions selected by which_indices. :param array-like labels: a label for each data point (row) of the inputs :param (int, int) which_indices: which input dimension...
[ "Plot", "the", "latent", "space", "of", "the", "GP", "on", "the", "inputs", ".", "This", "is", "the", "density", "of", "the", "GP", "posterior", "as", "a", "grey", "scale", "and", "the", "scatter", "plot", "of", "the", "input", "dimemsions", "selected", ...
python
train
calmjs/calmjs.parse
src/calmjs/parse/handlers/obfuscation.py
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/obfuscation.py#L322-L331
def reference(self, symbol, count=1): """ However, if referenced, ensure that the counter is applied to the catch symbol. """ if symbol == self.catch_symbol: self.catch_symbol_usage += count else: self.parent.reference(symbol, count)
[ "def", "reference", "(", "self", ",", "symbol", ",", "count", "=", "1", ")", ":", "if", "symbol", "==", "self", ".", "catch_symbol", ":", "self", ".", "catch_symbol_usage", "+=", "count", "else", ":", "self", ".", "parent", ".", "reference", "(", "symb...
However, if referenced, ensure that the counter is applied to the catch symbol.
[ "However", "if", "referenced", "ensure", "that", "the", "counter", "is", "applied", "to", "the", "catch", "symbol", "." ]
python
train
saltstack/salt
salt/proxy/ssh_sample.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/ssh_sample.py#L94-L104
def ping(): ''' Required. Ping the device on the other end of the connection ''' try: out, err = DETAILS['server'].sendline('help') return True except TerminalException as e: log.error(e) return False
[ "def", "ping", "(", ")", ":", "try", ":", "out", ",", "err", "=", "DETAILS", "[", "'server'", "]", ".", "sendline", "(", "'help'", ")", "return", "True", "except", "TerminalException", "as", "e", ":", "log", ".", "error", "(", "e", ")", "return", "...
Required. Ping the device on the other end of the connection
[ "Required", ".", "Ping", "the", "device", "on", "the", "other", "end", "of", "the", "connection" ]
python
train
carlcarl/grabflickr
grabflickr/grabflickr.py
https://github.com/carlcarl/grabflickr/blob/e9cb2365de80c1819cfd5083c032d0d985f3c614/grabflickr/grabflickr.py#L150-L170
def get_photo_url(photo_id): """Request the photo download url with the photo id :param photo_id: The photo id of flickr :type photo_id: str :return: Photo download url :rtype: str """ args = _get_request_args( 'flickr.photos.getSizes', photo_id=photo_id ) resp = requ...
[ "def", "get_photo_url", "(", "photo_id", ")", ":", "args", "=", "_get_request_args", "(", "'flickr.photos.getSizes'", ",", "photo_id", "=", "photo_id", ")", "resp", "=", "requests", ".", "post", "(", "API_URL", ",", "data", "=", "args", ")", "resp_json", "="...
Request the photo download url with the photo id :param photo_id: The photo id of flickr :type photo_id: str :return: Photo download url :rtype: str
[ "Request", "the", "photo", "download", "url", "with", "the", "photo", "id", ":", "param", "photo_id", ":", "The", "photo", "id", "of", "flickr", ":", "type", "photo_id", ":", "str", ":", "return", ":", "Photo", "download", "url", ":", "rtype", ":", "st...
python
train
collectiveacuity/labPack
labpack/records/time.py
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/time.py#L88-L119
def pyLocal(self, time_zone=''): ''' a method to report a python datetime from a labDT object :param time_zone: [optional] string with timezone to report in :return: string with date and time info ''' # validate inputs get_tz = get_localzone() title = 'Ti...
[ "def", "pyLocal", "(", "self", ",", "time_zone", "=", "''", ")", ":", "# validate inputs\r", "get_tz", "=", "get_localzone", "(", ")", "title", "=", "'Timezone input for labDT.pyLocal'", "if", "time_zone", ":", "# if time_zone.lower() in ('utc', 'uct', 'universal', 'zulu'...
a method to report a python datetime from a labDT object :param time_zone: [optional] string with timezone to report in :return: string with date and time info
[ "a", "method", "to", "report", "a", "python", "datetime", "from", "a", "labDT", "object", ":", "param", "time_zone", ":", "[", "optional", "]", "string", "with", "timezone", "to", "report", "in", ":", "return", ":", "string", "with", "date", "and", "time...
python
train
boriel/zxbasic
asmparse.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/asmparse.py#L244-L252
def eval(self): """ Recursively evals the node. Exits with an error if not resolved. """ Expr.ignore = False result = self.try_eval() Expr.ignore = True return result
[ "def", "eval", "(", "self", ")", ":", "Expr", ".", "ignore", "=", "False", "result", "=", "self", ".", "try_eval", "(", ")", "Expr", ".", "ignore", "=", "True", "return", "result" ]
Recursively evals the node. Exits with an error if not resolved.
[ "Recursively", "evals", "the", "node", ".", "Exits", "with", "an", "error", "if", "not", "resolved", "." ]
python
train
humilis/humilis-lambdautils
lambdautils/state.py
https://github.com/humilis/humilis-lambdautils/blob/58f75eb5ace23523c283708d56a9193181ea7e8e/lambdautils/state.py#L151-L204
def get_state(key, namespace=None, table_name=None, environment=None, layer=None, stage=None, shard_id=None, consistent=True, deserializer=json.loads, wait_exponential_multiplier=500, wait_exponential_max=5000, stop_max_delay=10000): """Get Lambda state value(s).""" if ...
[ "def", "get_state", "(", "key", ",", "namespace", "=", "None", ",", "table_name", "=", "None", ",", "environment", "=", "None", ",", "layer", "=", "None", ",", "stage", "=", "None", ",", "shard_id", "=", "None", ",", "consistent", "=", "True", ",", "...
Get Lambda state value(s).
[ "Get", "Lambda", "state", "value", "(", "s", ")", "." ]
python
train
cameronmaske/celery-once
celery_once/backends/redis.py
https://github.com/cameronmaske/celery-once/blob/ffd21cbdf486444b4b1fcc6f7354436b895285c6/celery_once/backends/redis.py#L91-L109
def raise_or_lock(self, key, timeout): """ Checks if the task is locked and raises an exception, else locks the task. By default, the tasks and the key expire after 60 minutes. (meaning it will not be executed and the lock will clear). """ acquired = Lock( sel...
[ "def", "raise_or_lock", "(", "self", ",", "key", ",", "timeout", ")", ":", "acquired", "=", "Lock", "(", "self", ".", "redis", ",", "key", ",", "timeout", "=", "timeout", ",", "blocking", "=", "self", ".", "blocking", ",", "blocking_timeout", "=", "sel...
Checks if the task is locked and raises an exception, else locks the task. By default, the tasks and the key expire after 60 minutes. (meaning it will not be executed and the lock will clear).
[ "Checks", "if", "the", "task", "is", "locked", "and", "raises", "an", "exception", "else", "locks", "the", "task", ".", "By", "default", "the", "tasks", "and", "the", "key", "expire", "after", "60", "minutes", ".", "(", "meaning", "it", "will", "not", ...
python
train
VingtCinq/python-mailchimp
mailchimp3/entities/authorizedapps.py
https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/entities/authorizedapps.py#L27-L44
def create(self, data): """ Retrieve OAuth2-based credentials to associate API calls with your application. :param data: The request body parameters :type data: :py:class:`dict` data = { "client_id": string*, "client_secret": string* } ...
[ "def", "create", "(", "self", ",", "data", ")", ":", "self", ".", "app_id", "=", "None", "if", "'client_id'", "not", "in", "data", ":", "raise", "KeyError", "(", "'The authorized app must have a client_id'", ")", "if", "'client_secret'", "not", "in", "data", ...
Retrieve OAuth2-based credentials to associate API calls with your application. :param data: The request body parameters :type data: :py:class:`dict` data = { "client_id": string*, "client_secret": string* }
[ "Retrieve", "OAuth2", "-", "based", "credentials", "to", "associate", "API", "calls", "with", "your", "application", "." ]
python
valid
NoneGG/aredis
aredis/client.py
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/client.py#L261-L282
def from_url(cls, url, db=None, skip_full_coverage_check=False, **kwargs): """ Return a Redis client object configured from the given URL, which must use either `the ``redis://`` scheme <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ for RESP connections or the ``unix:...
[ "def", "from_url", "(", "cls", ",", "url", ",", "db", "=", "None", ",", "skip_full_coverage_check", "=", "False", ",", "*", "*", "kwargs", ")", ":", "connection_pool", "=", "ClusterConnectionPool", ".", "from_url", "(", "url", ",", "db", "=", "db", ",", ...
Return a Redis client object configured from the given URL, which must use either `the ``redis://`` scheme <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ for RESP connections or the ``unix://`` scheme for Unix domain sockets. For example:: redis://[:password]@localhos...
[ "Return", "a", "Redis", "client", "object", "configured", "from", "the", "given", "URL", "which", "must", "use", "either", "the", "redis", ":", "//", "scheme", "<http", ":", "//", "www", ".", "iana", ".", "org", "/", "assignments", "/", "uri", "-", "sc...
python
train
google/grr
grr/server/grr_response_server/databases/mysql_events.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_events.py#L22-L68
def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None, cursor=None): """Returns audit entries stored in the database.""" quer...
[ "def", "ReadAPIAuditEntries", "(", "self", ",", "username", "=", "None", ",", "router_method_names", "=", "None", ",", "min_timestamp", "=", "None", ",", "max_timestamp", "=", "None", ",", "cursor", "=", "None", ")", ":", "query", "=", "\"\"\"SELECT details, t...
Returns audit entries stored in the database.
[ "Returns", "audit", "entries", "stored", "in", "the", "database", "." ]
python
train
SwissDataScienceCenter/renku-python
renku/cli/update.py
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/cli/update.py#L143-L190
def update(client, revision, no_output, siblings, paths): """Update existing files by rerunning their outdated workflow.""" graph = Graph(client) outputs = graph.build(revision=revision, can_be_cwl=no_output, paths=paths) outputs = {node for node in outputs if graph.need_update(node)} if not output...
[ "def", "update", "(", "client", ",", "revision", ",", "no_output", ",", "siblings", ",", "paths", ")", ":", "graph", "=", "Graph", "(", "client", ")", "outputs", "=", "graph", ".", "build", "(", "revision", "=", "revision", ",", "can_be_cwl", "=", "no_...
Update existing files by rerunning their outdated workflow.
[ "Update", "existing", "files", "by", "rerunning", "their", "outdated", "workflow", "." ]
python
train
reingart/pyafipws
wslpg.py
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L1442-L1464
def AjustarLiquidacionContrato(self): "Ajustar Liquidación activas relacionadas a un contrato" # limpiar arrays no enviados: if not self.ajuste['ajusteBase']['certificados']: del self.ajuste['ajusteBase']['certificados'] for k1 in ('ajusteCredito', 'ajusteDebito'): ...
[ "def", "AjustarLiquidacionContrato", "(", "self", ")", ":", "# limpiar arrays no enviados:", "if", "not", "self", ".", "ajuste", "[", "'ajusteBase'", "]", "[", "'certificados'", "]", ":", "del", "self", ".", "ajuste", "[", "'ajusteBase'", "]", "[", "'certificado...
Ajustar Liquidación activas relacionadas a un contrato
[ "Ajustar", "Liquidación", "activas", "relacionadas", "a", "un", "contrato" ]
python
train
pauleveritt/kaybee
kaybee/plugins/events.py
https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/events.py#L115-L122
def call_env_before_read_docs(cls, kb_app, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docnames: List[str]): """ On env-read-docs, do callbacks""" for callback in EventAction.get_callbacks(kb_app, ...
[ "def", "call_env_before_read_docs", "(", "cls", ",", "kb_app", ",", "sphinx_app", ":", "Sphinx", ",", "sphinx_env", ":", "BuildEnvironment", ",", "docnames", ":", "List", "[", "str", "]", ")", ":", "for", "callback", "in", "EventAction", ".", "get_callbacks", ...
On env-read-docs, do callbacks
[ "On", "env", "-", "read", "-", "docs", "do", "callbacks" ]
python
train
nuSTORM/gnomon
gnomon/Configuration.py
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/Configuration.py#L143-L173
def populate_args_level(schema, parser): """Use a schema to populate a command line argument parser""" for key, value in schema['properties'].iteritems(): if key == 'name': continue arg = '--%s' % key desc = value['description'] if 'type' in value: if va...
[ "def", "populate_args_level", "(", "schema", ",", "parser", ")", ":", "for", "key", ",", "value", "in", "schema", "[", "'properties'", "]", ".", "iteritems", "(", ")", ":", "if", "key", "==", "'name'", ":", "continue", "arg", "=", "'--%s'", "%", "key",...
Use a schema to populate a command line argument parser
[ "Use", "a", "schema", "to", "populate", "a", "command", "line", "argument", "parser" ]
python
train
ebroecker/canmatrix
src/canmatrix/canmatrix.py
https://github.com/ebroecker/canmatrix/blob/d6150b7a648350f051a11c431e9628308c8d5593/src/canmatrix/canmatrix.py#L523-L548
def unpack_bitstring(length, is_float, is_signed, bits): # type: (int, bool, bool, typing.Any) -> typing.Union[float, int] """ returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_si...
[ "def", "unpack_bitstring", "(", "length", ",", "is_float", ",", "is_signed", ",", "bits", ")", ":", "# type: (int, bool, bool, typing.Any) -> typing.Union[float, int]", "if", "is_float", ":", "types", "=", "{", "32", ":", "'>f'", ",", "64", ":", "'>d'", "}", "fl...
returns a value calculated from bits :param length: length of signal in bits :param is_float: value is float :param bits: value as bits (array/iterable) :param is_signed: value is signed :return:
[ "returns", "a", "value", "calculated", "from", "bits", ":", "param", "length", ":", "length", "of", "signal", "in", "bits", ":", "param", "is_float", ":", "value", "is", "float", ":", "param", "bits", ":", "value", "as", "bits", "(", "array", "/", "ite...
python
train
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L385-L388
def delete(sql, *args, **kwargs): """Deletes and commits with an insert sql statement""" assert "delete" in sql.lower(), 'This function requires a delete statement, provided: {}'.format(sql) CoyoteDb.execute_and_commit(sql, *args, **kwargs)
[ "def", "delete", "(", "sql", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "\"delete\"", "in", "sql", ".", "lower", "(", ")", ",", "'This function requires a delete statement, provided: {}'", ".", "format", "(", "sql", ")", "CoyoteDb", ".", ...
Deletes and commits with an insert sql statement
[ "Deletes", "and", "commits", "with", "an", "insert", "sql", "statement" ]
python
train
rwl/godot
godot/ui/graph_view_model.py
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view_model.py#L251-L266
def save(self, info): """ Handles saving the current model to the last file. """ save_file = self.save_file if not isfile(save_file): self.save_as(info) else: fd = None try: fd = open(save_file, "wb") dot_code =...
[ "def", "save", "(", "self", ",", "info", ")", ":", "save_file", "=", "self", ".", "save_file", "if", "not", "isfile", "(", "save_file", ")", ":", "self", ".", "save_as", "(", "info", ")", "else", ":", "fd", "=", "None", "try", ":", "fd", "=", "op...
Handles saving the current model to the last file.
[ "Handles", "saving", "the", "current", "model", "to", "the", "last", "file", "." ]
python
test
hsolbrig/pyjsg
pyjsg/parser_impl/jsg_objectexpr_parser.py
https://github.com/hsolbrig/pyjsg/blob/9b2b8fa8e3b8448abe70b09f804a79f0f31b32b7/pyjsg/parser_impl/jsg_objectexpr_parser.py#L196-L211
def members_entries(self, all_are_optional: bool=False) -> List[Tuple[str, str]]: """ Return an ordered list of elements for the _members section :param all_are_optional: True means we're in a choice situation so everything is optional :return: """ rval = [] if self._mem...
[ "def", "members_entries", "(", "self", ",", "all_are_optional", ":", "bool", "=", "False", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ":", "rval", "=", "[", "]", "if", "self", ".", "_members", ":", "for", "member", "in", "se...
Return an ordered list of elements for the _members section :param all_are_optional: True means we're in a choice situation so everything is optional :return:
[ "Return", "an", "ordered", "list", "of", "elements", "for", "the", "_members", "section" ]
python
train
LabKey/labkey-api-python
labkey/security.py
https://github.com/LabKey/labkey-api-python/blob/3c8d393384d7cbb2785f8a7f5fe34007b17a76b8/labkey/security.py#L194-L213
def __make_security_group_api_request(server_context, api, user_ids, group_id, container_path): """ Execute a request against the LabKey Security Controller Group Membership apis :param server_context: A LabKey server context. See utils.create_server_context. :param api: Action to execute :param use...
[ "def", "__make_security_group_api_request", "(", "server_context", ",", "api", ",", "user_ids", ",", "group_id", ",", "container_path", ")", ":", "url", "=", "server_context", ".", "build_url", "(", "security_controller", ",", "api", ",", "container_path", ")", "#...
Execute a request against the LabKey Security Controller Group Membership apis :param server_context: A LabKey server context. See utils.create_server_context. :param api: Action to execute :param user_ids: user ids to apply action to :param group_id: group id to apply action to :param container_pat...
[ "Execute", "a", "request", "against", "the", "LabKey", "Security", "Controller", "Group", "Membership", "apis", ":", "param", "server_context", ":", "A", "LabKey", "server", "context", ".", "See", "utils", ".", "create_server_context", ".", ":", "param", "api", ...
python
train
globality-corp/microcosm
microcosm/config/types.py
https://github.com/globality-corp/microcosm/blob/6856200ca295da4269c8c1c9de7db0b97c1f4523/microcosm/config/types.py#L8-L21
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
[ "def", "boolean", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "if", "value", "==", "\"\"", ":", "return", "False", "return", "strtobool", "(", "value", ")" ]
Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars).
[ "Configuration", "-", "friendly", "boolean", "type", "converter", "." ]
python
train
log2timeline/plaso
utils/plot_task_queue.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/utils/plot_task_queue.py#L22-L75
def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser(description=( 'Plots memory usage from profiling data.')) argument_parser.add_argument( '--output', dest='output_file', type=str, help=( 'path ...
[ "def", "Main", "(", ")", ":", "argument_parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "(", "'Plots memory usage from profiling data.'", ")", ")", "argument_parser", ".", "add_argument", "(", "'--output'", ",", "dest", "=", "'output_file'"...
The main program function. Returns: bool: True if successful or False if not.
[ "The", "main", "program", "function", "." ]
python
train
saulpw/visidata
visidata/vdtui.py
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/vdtui.py#L626-L641
def execAsync(self, func, *args, **kwargs): 'Execute `func(*args, **kwargs)` in a separate thread.' thread = threading.Thread(target=self.toplevelTryFunc, daemon=True, args=(func,)+args, kwargs=kwargs) self.addThread(thread) if self.sheets: currentSheet = self.sheets[0] ...
[ "def", "execAsync", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "toplevelTryFunc", ",", "daemon", "=", "True", ",", "args", "=", "(", "fu...
Execute `func(*args, **kwargs)` in a separate thread.
[ "Execute", "func", "(", "*", "args", "**", "kwargs", ")", "in", "a", "separate", "thread", "." ]
python
train
pimusicbox/mopidy-websettings
mopidy_websettings/__init__.py
https://github.com/pimusicbox/mopidy-websettings/blob/a9aca8e15a29f323e7d91e3f2237f4605e2892e3/mopidy_websettings/__init__.py#L33-L45
def restart_program(): """ DOES NOT WORK WELL WITH MOPIDY Hack from https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program to support updating the settings, since mopidy is not able to do that yet Restarts the current program Note: this function does not ...
[ "def", "restart_program", "(", ")", ":", "python", "=", "sys", ".", "executable", "os", ".", "execl", "(", "python", ",", "python", ",", "*", "sys", ".", "argv", ")" ]
DOES NOT WORK WELL WITH MOPIDY Hack from https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program to support updating the settings, since mopidy is not able to do that yet Restarts the current program Note: this function does not return. Any cleanup action (like ...
[ "DOES", "NOT", "WORK", "WELL", "WITH", "MOPIDY", "Hack", "from", "https", ":", "//", "www", ".", "daniweb", ".", "com", "/", "software", "-", "development", "/", "python", "/", "code", "/", "260268", "/", "restart", "-", "your", "-", "python", "-", "...
python
train
senaite/senaite.core
bika/lims/content/worksheet.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/worksheet.py#L150-L156
def setLayout(self, value): """ Sets the worksheet layout, keeping it sorted by position :param value: the layout to set """ new_layout = sorted(value, key=lambda k: k['position']) self.getField('Layout').set(self, new_layout)
[ "def", "setLayout", "(", "self", ",", "value", ")", ":", "new_layout", "=", "sorted", "(", "value", ",", "key", "=", "lambda", "k", ":", "k", "[", "'position'", "]", ")", "self", ".", "getField", "(", "'Layout'", ")", ".", "set", "(", "self", ",", ...
Sets the worksheet layout, keeping it sorted by position :param value: the layout to set
[ "Sets", "the", "worksheet", "layout", "keeping", "it", "sorted", "by", "position", ":", "param", "value", ":", "the", "layout", "to", "set" ]
python
train
pyhys/minimalmodbus
minimalmodbus.py
https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py#L2019-L2034
def _checkMode(mode): """Check that the Modbus mode is valie. Args: mode (string): The Modbus mode (MODE_RTU or MODE_ASCII) Raises: TypeError, ValueError """ if not isinstance(mode, str): raise TypeError('The {0} should be a string. Given: {1!r}'.format("mode", mode)) ...
[ "def", "_checkMode", "(", "mode", ")", ":", "if", "not", "isinstance", "(", "mode", ",", "str", ")", ":", "raise", "TypeError", "(", "'The {0} should be a string. Given: {1!r}'", ".", "format", "(", "\"mode\"", ",", "mode", ")", ")", "if", "mode", "not", "...
Check that the Modbus mode is valie. Args: mode (string): The Modbus mode (MODE_RTU or MODE_ASCII) Raises: TypeError, ValueError
[ "Check", "that", "the", "Modbus", "mode", "is", "valie", "." ]
python
train
yueyoum/social-oauth
example/_bottle.py
https://github.com/yueyoum/social-oauth/blob/80600ea737355b20931c8a0b5223f5b68175d930/example/_bottle.py#L1946-L1953
def cookie_decode(data, key): ''' Verify and decode an encoded string. Return an object or None.''' data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1) if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg).digest())): return pickle.loads(base64.b...
[ "def", "cookie_decode", "(", "data", ",", "key", ")", ":", "data", "=", "tob", "(", "data", ")", "if", "cookie_is_encoded", "(", "data", ")", ":", "sig", ",", "msg", "=", "data", ".", "split", "(", "tob", "(", "'?'", ")", ",", "1", ")", "if", "...
Verify and decode an encoded string. Return an object or None.
[ "Verify", "and", "decode", "an", "encoded", "string", ".", "Return", "an", "object", "or", "None", "." ]
python
train
apacha/OMR-Datasets
omrdatasettools/downloaders/MuscimaPlusPlusDatasetDownloader.py
https://github.com/apacha/OMR-Datasets/blob/d0a22a03ae35caeef211729efa340e1ec0e01ea5/omrdatasettools/downloaders/MuscimaPlusPlusDatasetDownloader.py#L33-L54
def download_and_extract_dataset(self, destination_directory: str): """ Downloads and extracts the MUSCIMA++ dataset along with the images from the CVC-MUSCIMA dataset that were manually annotated (140 out of 1000 images). """ if not os.path.exists(self.get_dataset_filename()): ...
[ "def", "download_and_extract_dataset", "(", "self", ",", "destination_directory", ":", "str", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "get_dataset_filename", "(", ")", ")", ":", "print", "(", "\"Downloading MUSCIMA++ Dataset......
Downloads and extracts the MUSCIMA++ dataset along with the images from the CVC-MUSCIMA dataset that were manually annotated (140 out of 1000 images).
[ "Downloads", "and", "extracts", "the", "MUSCIMA", "++", "dataset", "along", "with", "the", "images", "from", "the", "CVC", "-", "MUSCIMA", "dataset", "that", "were", "manually", "annotated", "(", "140", "out", "of", "1000", "images", ")", "." ]
python
train
fbradyirl/hikvision
hikvision/api.py
https://github.com/fbradyirl/hikvision/blob/3bc3b20b8f7d793cf9dd94777e4b8e82bfd4abc6/hikvision/api.py#L117-L163
def get_about(self, element_to_query=None): """ Returns ElementTree containing the result of <host>/System/deviceInfo or if element_to_query is not None, the value of that element """ url = '%s/System/deviceInfo' % self._base _LOGGING.info('url: %s', url) ...
[ "def", "get_about", "(", "self", ",", "element_to_query", "=", "None", ")", ":", "url", "=", "'%s/System/deviceInfo'", "%", "self", ".", "_base", "_LOGGING", ".", "info", "(", "'url: %s'", ",", "url", ")", "response", "=", "requests", ".", "get", "(", "u...
Returns ElementTree containing the result of <host>/System/deviceInfo or if element_to_query is not None, the value of that element
[ "Returns", "ElementTree", "containing", "the", "result", "of", "<host", ">", "/", "System", "/", "deviceInfo", "or", "if", "element_to_query", "is", "not", "None", "the", "value", "of", "that", "element" ]
python
train
carter-j-h/iterable-python-wrapper
iterablepythonwrapper/client.py
https://github.com/carter-j-h/iterable-python-wrapper/blob/10d5db034ddfdfc3333efeee07fc9228b6a998c4/iterablepythonwrapper/client.py#L575-L640
def export_data_json(self, return_response_object, chunk_size=1024, path=None, data_type_name=None, date_range=None, delimiter=None, start_date_time=None, end_date_time=None, omit_fields=None, only_fields=None, campaign_id=None): """ Custom Keyword arguments: 1. return_resp...
[ "def", "export_data_json", "(", "self", ",", "return_response_object", ",", "chunk_size", "=", "1024", ",", "path", "=", "None", ",", "data_type_name", "=", "None", ",", "date_range", "=", "None", ",", "delimiter", "=", "None", ",", "start_date_time", "=", "...
Custom Keyword arguments: 1. return_response_object: if set to 'True', the 'r' response object will be returned. The benefit of this is that you can manipulate the data in any way you want. If set to false, we will write the response to a file where each Iterable activity you're exporting is a single-l...
[ "Custom", "Keyword", "arguments", ":" ]
python
train
openstack/proliantutils
proliantutils/ilo/ris.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ris.py#L897-L909
def get_http_boot_url(self): """Request the http boot url from system in uefi boot mode. :returns: URL for http boot :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedInBiosError, if the system is in the bios boot mode. """ if(self....
[ "def", "get_http_boot_url", "(", "self", ")", ":", "if", "(", "self", ".", "_is_boot_mode_uefi", "(", ")", "is", "True", ")", ":", "return", "self", ".", "_get_bios_setting", "(", "'UefiShellStartupUrl'", ")", "else", ":", "msg", "=", "'get_http_boot_url is no...
Request the http boot url from system in uefi boot mode. :returns: URL for http boot :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedInBiosError, if the system is in the bios boot mode.
[ "Request", "the", "http", "boot", "url", "from", "system", "in", "uefi", "boot", "mode", "." ]
python
train
ericsuh/dirichlet
dirichlet/dirichlet.py
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L324-L337
def _ipsi(y, tol=1.48e-9, maxiter=10): '''Inverse of psi (digamma) using Newton's method. For the purposes of Dirichlet MLE, since the parameters a[i] must always satisfy a > 0, we define ipsi :: R -> (0,inf).''' y = asanyarray(y, dtype='float') x0 = _piecewise(y, [y >= -2.22, y < -2.22], ...
[ "def", "_ipsi", "(", "y", ",", "tol", "=", "1.48e-9", ",", "maxiter", "=", "10", ")", ":", "y", "=", "asanyarray", "(", "y", ",", "dtype", "=", "'float'", ")", "x0", "=", "_piecewise", "(", "y", ",", "[", "y", ">=", "-", "2.22", ",", "y", "<"...
Inverse of psi (digamma) using Newton's method. For the purposes of Dirichlet MLE, since the parameters a[i] must always satisfy a > 0, we define ipsi :: R -> (0,inf).
[ "Inverse", "of", "psi", "(", "digamma", ")", "using", "Newton", "s", "method", ".", "For", "the", "purposes", "of", "Dirichlet", "MLE", "since", "the", "parameters", "a", "[", "i", "]", "must", "always", "satisfy", "a", ">", "0", "we", "define", "ipsi"...
python
train
ByteInternet/amqpconsumer
amqpconsumer/events.py
https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L78-L89
def connect(self): """Connect to RabbitMQ, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ logger.debug('Connecting to %s', self._url) return pika.Selec...
[ "def", "connect", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Connecting to %s'", ",", "self", ".", "_url", ")", "return", "pika", ".", "SelectConnection", "(", "pika", ".", "URLParameters", "(", "self", ".", "_url", ")", ",", "self", ".", "o...
Connect to RabbitMQ, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection
[ "Connect", "to", "RabbitMQ", "returning", "the", "connection", "handle", "." ]
python
train
tdryer/hangups
hangups/event.py
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/event.py#L53-L59
async def fire(self, *args, **kwargs): """Fire this event, calling all observers with the same arguments.""" logger.debug('Fired {}'.format(self)) for observer in self._observers: gen = observer(*args, **kwargs) if asyncio.iscoroutinefunction(observer): aw...
[ "async", "def", "fire", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "'Fired {}'", ".", "format", "(", "self", ")", ")", "for", "observer", "in", "self", ".", "_observers", ":", "gen", "=", "observe...
Fire this event, calling all observers with the same arguments.
[ "Fire", "this", "event", "calling", "all", "observers", "with", "the", "same", "arguments", "." ]
python
valid
SiLab-Bonn/pyBAR
pybar/fei4/register_utils.py
https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/fei4/register_utils.py#L678-L738
def make_pixel_mask(steps, shift, default=0, value=1, enable_columns=None, mask=None): '''Generate pixel mask. Parameters ---------- steps : int Number of mask steps, e.g. steps=3 (every third pixel is enabled), steps=336 (one pixel per column), steps=672 (one pixel per double column). ...
[ "def", "make_pixel_mask", "(", "steps", ",", "shift", ",", "default", "=", "0", ",", "value", "=", "1", ",", "enable_columns", "=", "None", ",", "mask", "=", "None", ")", ":", "shape", "=", "(", "80", ",", "336", ")", "# value = np.zeros(dimension, dtype...
Generate pixel mask. Parameters ---------- steps : int Number of mask steps, e.g. steps=3 (every third pixel is enabled), steps=336 (one pixel per column), steps=672 (one pixel per double column). shift : int Shift mask by given value to the bottom (towards higher row numbers). F...
[ "Generate", "pixel", "mask", ".", "Parameters", "----------", "steps", ":", "int", "Number", "of", "mask", "steps", "e", ".", "g", ".", "steps", "=", "3", "(", "every", "third", "pixel", "is", "enabled", ")", "steps", "=", "336", "(", "one", "pixel", ...
python
train
spacetelescope/synphot_refactor
synphot/spectrum.py
https://github.com/spacetelescope/synphot_refactor/blob/9c064f3cff0c41dd8acadc0f67c6350931275b9f/synphot/spectrum.py#L242-L248
def _process_generic_param(pval, def_unit, equivalencies=[]): """Process generic model parameter.""" if isinstance(pval, u.Quantity): outval = pval.to(def_unit, equivalencies).value else: # Assume already in desired unit outval = pval return outval
[ "def", "_process_generic_param", "(", "pval", ",", "def_unit", ",", "equivalencies", "=", "[", "]", ")", ":", "if", "isinstance", "(", "pval", ",", "u", ".", "Quantity", ")", ":", "outval", "=", "pval", ".", "to", "(", "def_unit", ",", "equivalencies", ...
Process generic model parameter.
[ "Process", "generic", "model", "parameter", "." ]
python
train
dlancer/django-pages-cms
pages/templatetags/pages_tags.py
https://github.com/dlancer/django-pages-cms/blob/441fad674d5ad4f6e05c953508950525dc0fa789/pages/templatetags/pages_tags.py#L34-L59
def get_page_object_by_name(context, name): """ **Arguments** ``name` name for object selection :return selected object """ selected_object = None try: for obj_type in context['page']['content']: for obj in context['page']['content'][obj_type]: ...
[ "def", "get_page_object_by_name", "(", "context", ",", "name", ")", ":", "selected_object", "=", "None", "try", ":", "for", "obj_type", "in", "context", "[", "'page'", "]", "[", "'content'", "]", ":", "for", "obj", "in", "context", "[", "'page'", "]", "[...
**Arguments** ``name` name for object selection :return selected object
[ "**", "Arguments", "**" ]
python
train
chrisjrn/registrasion
registrasion/reporting/views.py
https://github.com/chrisjrn/registrasion/blob/461d5846c6f9f3b7099322a94f5d9911564448e4/registrasion/reporting/views.py#L117-L167
def sales_payment_summary(): ''' Summarises paid items and payments. ''' def value_or_zero(aggregate, key): return aggregate[key] or 0 def sum_amount(payment_set): a = payment_set.values("amount").aggregate(total=Sum("amount")) return value_or_zero(a, "total") headings = ["Cat...
[ "def", "sales_payment_summary", "(", ")", ":", "def", "value_or_zero", "(", "aggregate", ",", "key", ")", ":", "return", "aggregate", "[", "key", "]", "or", "0", "def", "sum_amount", "(", "payment_set", ")", ":", "a", "=", "payment_set", ".", "values", "...
Summarises paid items and payments.
[ "Summarises", "paid", "items", "and", "payments", "." ]
python
test
nschloe/pygmsh
pygmsh/built_in/geometry.py
https://github.com/nschloe/pygmsh/blob/1a1a07481aebe6c161b60dd31e0fbe1ddf330d61/pygmsh/built_in/geometry.py#L1006-L1019
def translate(self, input_entity, vector): """Translates input_entity itself by vector. Changes the input object. """ d = {1: "Line", 2: "Surface", 3: "Volume"} self._GMSH_CODE.append( "Translate {{{}}} {{ {}{{{}}}; }}".format( ", ".join([str(co) for ...
[ "def", "translate", "(", "self", ",", "input_entity", ",", "vector", ")", ":", "d", "=", "{", "1", ":", "\"Line\"", ",", "2", ":", "\"Surface\"", ",", "3", ":", "\"Volume\"", "}", "self", ".", "_GMSH_CODE", ".", "append", "(", "\"Translate {{{}}} {{ {}{{...
Translates input_entity itself by vector. Changes the input object.
[ "Translates", "input_entity", "itself", "by", "vector", "." ]
python
train
apple/turicreate
deps/src/boost_1_68_0/tools/litre/cplusplus.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/litre/cplusplus.py#L320-L325
def _execute(self, code): """Override of litre._execute; sets up variable context before evaluating code """ self.globals['example'] = self.example eval(code, self.globals)
[ "def", "_execute", "(", "self", ",", "code", ")", ":", "self", ".", "globals", "[", "'example'", "]", "=", "self", ".", "example", "eval", "(", "code", ",", "self", ".", "globals", ")" ]
Override of litre._execute; sets up variable context before evaluating code
[ "Override", "of", "litre", ".", "_execute", ";", "sets", "up", "variable", "context", "before", "evaluating", "code" ]
python
train
ellethee/argparseinator
argparseinator/utils.py
https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/utils.py#L174-L215
def get_functarguments(func): """ Recupera gli argomenti dalla funzione stessa. """ argspec = inspect.getargspec(func) if argspec.defaults is not None: args = argspec.args[:-len(argspec.defaults)] kwargs = dict( zip(argspec.args[-len(argspec.defaults):], argspec.defaults)...
[ "def", "get_functarguments", "(", "func", ")", ":", "argspec", "=", "inspect", ".", "getargspec", "(", "func", ")", "if", "argspec", ".", "defaults", "is", "not", "None", ":", "args", "=", "argspec", ".", "args", "[", ":", "-", "len", "(", "argspec", ...
Recupera gli argomenti dalla funzione stessa.
[ "Recupera", "gli", "argomenti", "dalla", "funzione", "stessa", "." ]
python
train
miguelgrinberg/python-socketio
socketio/base_manager.py
https://github.com/miguelgrinberg/python-socketio/blob/c0c1bf8d21e3597389b18938550a0724dd9676b7/socketio/base_manager.py#L89-L95
def enter_room(self, sid, namespace, room): """Add a client to a room.""" if namespace not in self.rooms: self.rooms[namespace] = {} if room not in self.rooms[namespace]: self.rooms[namespace][room] = {} self.rooms[namespace][room][sid] = True
[ "def", "enter_room", "(", "self", ",", "sid", ",", "namespace", ",", "room", ")", ":", "if", "namespace", "not", "in", "self", ".", "rooms", ":", "self", ".", "rooms", "[", "namespace", "]", "=", "{", "}", "if", "room", "not", "in", "self", ".", ...
Add a client to a room.
[ "Add", "a", "client", "to", "a", "room", "." ]
python
train
google/openhtf
openhtf/plugs/usb/local_usb.py
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/local_usb.py#L158-L178
def open(cls, **kwargs): """See iter_open, but raises if multiple or no matches found.""" handle_iter = cls.iter_open(**kwargs) try: handle = six.next(handle_iter) except StopIteration: # No matching interface, raise. raise usb_exceptions.DeviceNotFoundError( 'Open failed wi...
[ "def", "open", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "handle_iter", "=", "cls", ".", "iter_open", "(", "*", "*", "kwargs", ")", "try", ":", "handle", "=", "six", ".", "next", "(", "handle_iter", ")", "except", "StopIteration", ":", "# No mat...
See iter_open, but raises if multiple or no matches found.
[ "See", "iter_open", "but", "raises", "if", "multiple", "or", "no", "matches", "found", "." ]
python
train
reingart/pyafipws
wslum.py
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslum.py#L254-L261
def AgregarBalanceLitrosPorcentajesSolidos(self, litros_remitidos, litros_decomisados, kg_grasa, kg_proteina, **kwargs): "Agrega balance litros y porcentajes sólidos a la liq. (obligatorio)" d = {'litrosRemitidos': litros_remitidos, 'litrosDec...
[ "def", "AgregarBalanceLitrosPorcentajesSolidos", "(", "self", ",", "litros_remitidos", ",", "litros_decomisados", ",", "kg_grasa", ",", "kg_proteina", ",", "*", "*", "kwargs", ")", ":", "d", "=", "{", "'litrosRemitidos'", ":", "litros_remitidos", ",", "'litrosDecomi...
Agrega balance litros y porcentajes sólidos a la liq. (obligatorio)
[ "Agrega", "balance", "litros", "y", "porcentajes", "sólidos", "a", "la", "liq", ".", "(", "obligatorio", ")" ]
python
train
respondcreate/django-versatileimagefield
versatileimagefield/datastructures/base.py
https://github.com/respondcreate/django-versatileimagefield/blob/d41e279c39cccffafbe876c67596184704ae8877/versatileimagefield/datastructures/base.py#L60-L104
def preprocess(self, image, image_format): """ Preprocess an image. An API hook for image pre-processing. Calls any image format specific pre-processors (if defined). I.E. If `image_format` is 'JPEG', this method will look for a method named `preprocess_JPEG`, if found `...
[ "def", "preprocess", "(", "self", ",", "image", ",", "image_format", ")", ":", "save_kwargs", "=", "{", "'format'", ":", "image_format", "}", "# Ensuring image is properly rotated", "if", "hasattr", "(", "image", ",", "'_getexif'", ")", ":", "exif_datadict", "="...
Preprocess an image. An API hook for image pre-processing. Calls any image format specific pre-processors (if defined). I.E. If `image_format` is 'JPEG', this method will look for a method named `preprocess_JPEG`, if found `image` will be passed to it. Arguments: * ...
[ "Preprocess", "an", "image", "." ]
python
test
Neurita/boyle
boyle/utils/imports.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/imports.py#L6-L27
def import_pyfile(filepath, mod_name=None): """ Imports the contents of filepath as a Python module. :param filepath: string :param mod_name: string Name of the module when imported :return: module Imported module """ import sys if sys.version_info.major == 3: import i...
[ "def", "import_pyfile", "(", "filepath", ",", "mod_name", "=", "None", ")", ":", "import", "sys", "if", "sys", ".", "version_info", ".", "major", "==", "3", ":", "import", "importlib", ".", "machinery", "loader", "=", "importlib", ".", "machinery", ".", ...
Imports the contents of filepath as a Python module. :param filepath: string :param mod_name: string Name of the module when imported :return: module Imported module
[ "Imports", "the", "contents", "of", "filepath", "as", "a", "Python", "module", "." ]
python
valid
apache/incubator-mxnet
python/mxnet/kvstore.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/kvstore.py#L565-L603
def _set_updater(self, updater): """Sets a push updater into the store. This function only changes the local store. When running on multiple machines one must use `set_optimizer`. Parameters ---------- updater : function The updater function. Exampl...
[ "def", "_set_updater", "(", "self", ",", "updater", ")", ":", "self", ".", "_updater", "=", "updater", "# set updater with int keys", "_updater_proto", "=", "ctypes", ".", "CFUNCTYPE", "(", "None", ",", "ctypes", ".", "c_int", ",", "NDArrayHandle", ",", "NDArr...
Sets a push updater into the store. This function only changes the local store. When running on multiple machines one must use `set_optimizer`. Parameters ---------- updater : function The updater function. Examples -------- >>> def update(k...
[ "Sets", "a", "push", "updater", "into", "the", "store", "." ]
python
train
openearth/bmi-python
bmi/wrapper.py
https://github.com/openearth/bmi-python/blob/2f53f24d45515eb0711c2d28ddd6c1582045248f/bmi/wrapper.py#L364-L381
def finalize(self): """Shutdown the library and clean up the model. Note that the Fortran library's cleanup code is not up to snuff yet, so the cleanup is not perfect. Note also that the working directory is changed back to the original one. """ self.library.finalize.ar...
[ "def", "finalize", "(", "self", ")", ":", "self", ".", "library", ".", "finalize", ".", "argtypes", "=", "[", "]", "self", ".", "library", ".", "finalize", ".", "restype", "=", "c_int", "ierr", "=", "wrap", "(", "self", ".", "library", ".", "finalize...
Shutdown the library and clean up the model. Note that the Fortran library's cleanup code is not up to snuff yet, so the cleanup is not perfect. Note also that the working directory is changed back to the original one.
[ "Shutdown", "the", "library", "and", "clean", "up", "the", "model", "." ]
python
train
TheRealLink/pylgtv
pylgtv/webos_client.py
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L146-L172
def _command(self, msg): """Send a command to the tv.""" logger.debug('send command to %s', "ws://{}:{}".format(self.ip, self.port)); try: websocket = yield from websockets.connect( "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect) except:...
[ "def", "_command", "(", "self", ",", "msg", ")", ":", "logger", ".", "debug", "(", "'send command to %s'", ",", "\"ws://{}:{}\"", ".", "format", "(", "self", ".", "ip", ",", "self", ".", "port", ")", ")", "try", ":", "websocket", "=", "yield", "from", ...
Send a command to the tv.
[ "Send", "a", "command", "to", "the", "tv", "." ]
python
train
guaix-ucm/numina
numina/array/interpolation.py
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/interpolation.py#L123-L128
def _create_s(y, h): """Estimate secants""" s = np.zeros_like(y) s[:-1] = (y[1:] - y[:-1]) / h[:-1] s[-1] = 0.0 return s
[ "def", "_create_s", "(", "y", ",", "h", ")", ":", "s", "=", "np", ".", "zeros_like", "(", "y", ")", "s", "[", ":", "-", "1", "]", "=", "(", "y", "[", "1", ":", "]", "-", "y", "[", ":", "-", "1", "]", ")", "/", "h", "[", ":", "-", "1...
Estimate secants
[ "Estimate", "secants" ]
python
train
kubernetes-client/python
kubernetes/client/apis/core_v1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/core_v1_api.py#L11706-L11733
def list_namespaced_config_map(self, namespace, **kwargs): """ list or watch objects of kind ConfigMap This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_config_map(namespace, ...
[ "def", "list_namespaced_config_map", "(", "self", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "list_namespa...
list or watch objects of kind ConfigMap This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_config_map(namespace, async_req=True) >>> result = thread.get() :param async_req boo...
[ "list", "or", "watch", "objects", "of", "kind", "ConfigMap", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", ">>>", "th...
python
train
mlenzen/collections-extended
collections_extended/range_map.py
https://github.com/mlenzen/collections-extended/blob/ee9e86f6bbef442dbebcb3a5970642c5c969e2cf/collections_extended/range_map.py#L330-L346
def delete(self, start=None, stop=None): """Delete the range from start to stop from self. Raises: KeyError: If part of the passed range isn't mapped. """ _check_start_stop(start, stop) start_loc = self._bisect_right(start) - 1 if stop is None: stop_loc = len(self._keys) else: stop_loc = self._b...
[ "def", "delete", "(", "self", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "_check_start_stop", "(", "start", ",", "stop", ")", "start_loc", "=", "self", ".", "_bisect_right", "(", "start", ")", "-", "1", "if", "stop", "is", "None",...
Delete the range from start to stop from self. Raises: KeyError: If part of the passed range isn't mapped.
[ "Delete", "the", "range", "from", "start", "to", "stop", "from", "self", "." ]
python
train
Cog-Creators/Red-Lavalink
lavalink/utils.py
https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/utils.py#L1-L6
def format_time(time): """ Formats the given time into HH:MM:SS """ h, r = divmod(time / 1000, 3600) m, s = divmod(r, 60) return "%02d:%02d:%02d" % (h, m, s)
[ "def", "format_time", "(", "time", ")", ":", "h", ",", "r", "=", "divmod", "(", "time", "/", "1000", ",", "3600", ")", "m", ",", "s", "=", "divmod", "(", "r", ",", "60", ")", "return", "\"%02d:%02d:%02d\"", "%", "(", "h", ",", "m", ",", "s", ...
Formats the given time into HH:MM:SS
[ "Formats", "the", "given", "time", "into", "HH", ":", "MM", ":", "SS" ]
python
train
e7dal/bubble3
behave4cmd0/textutil.py
https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/behave4cmd0/textutil.py#L164-L172
def text_remove_empty_lines(text): """ Whitespace normalization: - Strip empty lines - Strip trailing whitespace """ lines = [ line.rstrip() for line in text.splitlines() if line.strip() ] return "\n".join(lines)
[ "def", "text_remove_empty_lines", "(", "text", ")", ":", "lines", "=", "[", "line", ".", "rstrip", "(", ")", "for", "line", "in", "text", ".", "splitlines", "(", ")", "if", "line", ".", "strip", "(", ")", "]", "return", "\"\\n\"", ".", "join", "(", ...
Whitespace normalization: - Strip empty lines - Strip trailing whitespace
[ "Whitespace", "normalization", ":" ]
python
train
hydpy-dev/hydpy
hydpy/auxs/iuhtools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/iuhtools.py#L195-L208
def delay_response_series(self): """A tuple of two numpy arrays, which hold the time delays and the associated iuh values respectively.""" delays = [] responses = [] sum_responses = 0. for t in itertools.count(self.dt_response/2., self.dt_response): delays.app...
[ "def", "delay_response_series", "(", "self", ")", ":", "delays", "=", "[", "]", "responses", "=", "[", "]", "sum_responses", "=", "0.", "for", "t", "in", "itertools", ".", "count", "(", "self", ".", "dt_response", "/", "2.", ",", "self", ".", "dt_respo...
A tuple of two numpy arrays, which hold the time delays and the associated iuh values respectively.
[ "A", "tuple", "of", "two", "numpy", "arrays", "which", "hold", "the", "time", "delays", "and", "the", "associated", "iuh", "values", "respectively", "." ]
python
train
secdev/scapy
scapy/utils6.py
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/utils6.py#L282-L338
def in6_getLinkScopedMcastAddr(addr, grpid=None, scope=2): """ Generate a Link-Scoped Multicast Address as described in RFC 4489. Returned value is in printable notation. 'addr' parameter specifies the link-local address to use for generating Link-scoped multicast address IID. By default, the ...
[ "def", "in6_getLinkScopedMcastAddr", "(", "addr", ",", "grpid", "=", "None", ",", "scope", "=", "2", ")", ":", "if", "scope", "not", "in", "[", "0", ",", "1", ",", "2", "]", ":", "return", "None", "try", ":", "if", "not", "in6_islladdr", "(", "addr...
Generate a Link-Scoped Multicast Address as described in RFC 4489. Returned value is in printable notation. 'addr' parameter specifies the link-local address to use for generating Link-scoped multicast address IID. By default, the function returns a ::/96 prefix (aka last 32 bits of returned addre...
[ "Generate", "a", "Link", "-", "Scoped", "Multicast", "Address", "as", "described", "in", "RFC", "4489", ".", "Returned", "value", "is", "in", "printable", "notation", "." ]
python
train
PaulHancock/Aegean
AegeanTools/fitting.py
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/fitting.py#L228-L279
def lmfit_jacobian(pars, x, y, errs=None, B=None, emp=False): """ Wrapper around :func:`AegeanTools.fitting.jacobian` and :func:`AegeanTools.fitting.emp_jacobian` which gives the output in a format that is required for lmfit. Parameters ---------- pars : lmfit.Model The model parameters...
[ "def", "lmfit_jacobian", "(", "pars", ",", "x", ",", "y", ",", "errs", "=", "None", ",", "B", "=", "None", ",", "emp", "=", "False", ")", ":", "if", "emp", ":", "matrix", "=", "emp_jacobian", "(", "pars", ",", "x", ",", "y", ")", "else", ":", ...
Wrapper around :func:`AegeanTools.fitting.jacobian` and :func:`AegeanTools.fitting.emp_jacobian` which gives the output in a format that is required for lmfit. Parameters ---------- pars : lmfit.Model The model parameters x, y : list Locations at which the jacobian is being evaluat...
[ "Wrapper", "around", ":", "func", ":", "AegeanTools", ".", "fitting", ".", "jacobian", "and", ":", "func", ":", "AegeanTools", ".", "fitting", ".", "emp_jacobian", "which", "gives", "the", "output", "in", "a", "format", "that", "is", "required", "for", "lm...
python
train