text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def update(): ''' Execute an svn update on all of the repos ''' # data for the fileserver event data = {'changed': False, 'backend': 'svnfs'} # _clear_old_remotes runs init(), so use the value from there to avoid a # second init() data['changed'], repos = _clear_old_remotes()...
[ "def", "update", "(", ")", ":", "# data for the fileserver event", "data", "=", "{", "'changed'", ":", "False", ",", "'backend'", ":", "'svnfs'", "}", "# _clear_old_remotes runs init(), so use the value from there to avoid a", "# second init()", "data", "[", "'changed'", ...
37.216216
18.945946
def get_stop_times(feed: "Feed", date: Optional[str] = None) -> DataFrame: """ Return a subset of ``feed.stop_times``. Parameters ---------- feed : Feed date : string YYYYMMDD date string restricting the output to trips active on the date Returns ------- DataFrame ...
[ "def", "get_stop_times", "(", "feed", ":", "\"Feed\"", ",", "date", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "DataFrame", ":", "f", "=", "feed", ".", "stop_times", ".", "copy", "(", ")", "if", "date", "is", "None", ":", "return", "...
21.1
22.766667
def sys_pipes(encoding=_default_encoding): """Redirect C-level stdout/stderr to sys.stdout/stderr This is useful of sys.sdout/stderr are already being forwarded somewhere. DO NOT USE THIS if sys.stdout and sys.stderr are not already being forwarded. """ return pipes(sys.stdout, sys.stderr,...
[ "def", "sys_pipes", "(", "encoding", "=", "_default_encoding", ")", ":", "return", "pipes", "(", "sys", ".", "stdout", ",", "sys", ".", "stderr", ",", "encoding", "=", "encoding", ")" ]
41.5
21.375
def sparkify(series): u"""Converts <series> to a sparkline string. Example: >>> sparkify([ 0.5, 1.2, 3.5, 7.3, 8.0, 12.5, 13.2, 15.0, 14.2, 11.8, 6.1, ... 1.9 ]) u'▁▁▂▄▅▇▇██▆▄▂' >>> sparkify([1, 1, -2, 3, -5, 8, -13]) u'▆▆▅▆▄█▁' Raises ValueError if input data cannot be converted ...
[ "def", "sparkify", "(", "series", ")", ":", "series", "=", "[", "float", "(", "i", ")", "for", "i", "in", "series", "]", "minimum", "=", "min", "(", "series", ")", "maximum", "=", "max", "(", "series", ")", "data_range", "=", "maximum", "-", "minim...
30.333333
19.037037
def phantom_decorate(f, get_or_add): """ Decorator for version-dependent fields. If get_or_add is True (means get), we return s, self.phantom_value. If it is False (means add), we return s. """ def wrapper(*args): self, pkt, s = args[:3] if phantom_mode(pkt): if get_o...
[ "def", "phantom_decorate", "(", "f", ",", "get_or_add", ")", ":", "def", "wrapper", "(", "*", "args", ")", ":", "self", ",", "pkt", ",", "s", "=", "args", "[", ":", "3", "]", "if", "phantom_mode", "(", "pkt", ")", ":", "if", "get_or_add", ":", "r...
30.142857
11.142857
def comment_request(self, request_id, body, commit=None, filename=None, row=None): """ Create a comment on the request. :param request_id: the id of the request :param body: the comment body :param commit: which commit to comment on :param filename...
[ "def", "comment_request", "(", "self", ",", "request_id", ",", "body", ",", "commit", "=", "None", ",", "filename", "=", "None", ",", "row", "=", "None", ")", ":", "request_url", "=", "(", "\"{}pull-request/{}/comment\"", ".", "format", "(", "self", ".", ...
35.346154
13.115385
def create_db(self, models): """Creates the in-memory SQLite database from the model configuration.""" # first create the table definitions self.tables = dict( [ (model_name, self.create_model_table(model)) for model_name, model in iteritems(mo...
[ "def", "create_db", "(", "self", ",", "models", ")", ":", "# first create the table definitions", "self", ".", "tables", "=", "dict", "(", "[", "(", "model_name", ",", "self", ".", "create_model_table", "(", "model", ")", ")", "for", "model_name", ",", "mode...
36.45
15.55
def from_pyfile(self, filename): """ 在一个 Python 文件中读取配置。 :param filename: 配置文件的文件名 :return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常 """ d = types.ModuleType('config') d.__file__ = filename with open(filename) as config_file: exec(compile(config_file.r...
[ "def", "from_pyfile", "(", "self", ",", "filename", ")", ":", "d", "=", "types", ".", "ModuleType", "(", "'config'", ")", "d", ".", "__file__", "=", "filename", "with", "open", "(", "filename", ")", "as", "config_file", ":", "exec", "(", "compile", "("...
30.230769
12.384615
def _get_diffs(cls, dict1, dict2, ignore_missing_keys): ''' Returns a dict with the differences between dict1 and dict2 Notes: Keys that only exist in dict2 are not included in the diff if ignore_missing_keys is True, otherwise they are Simple compares are do...
[ "def", "_get_diffs", "(", "cls", ",", "dict1", ",", "dict2", ",", "ignore_missing_keys", ")", ":", "ret_dict", "=", "{", "}", "for", "p", "in", "dict1", ".", "keys", "(", ")", ":", "if", "p", "not", "in", "dict2", ":", "ret_dict", ".", "update", "(...
44.37037
20.296296
def scrape(ctx, url): """ Rip the events from a given rss feed, normalize the data and store. """ data = load_feed(url) feed = data['feed'] entries = data['entries'] # THIS IS SPECIFIC TO # http://konfery.cz/rss/ _type = 'community' country = 'Czech Republic' # title, title_de...
[ "def", "scrape", "(", "ctx", ",", "url", ")", ":", "data", "=", "load_feed", "(", "url", ")", "feed", "=", "data", "[", "'feed'", "]", "entries", "=", "data", "[", "'entries'", "]", "# THIS IS SPECIFIC TO # http://konfery.cz/rss/", "_type", "=", "'community'...
29.16
17.64
def update_gl_state(self, *args, **kwargs): """Modify the set of GL state parameters to use when drawing Parameters ---------- *args : tuple Arguments. **kwargs : dict Keyword argments. """ for v in self._subvisuals: v.update_g...
[ "def", "update_gl_state", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "v", "in", "self", ".", "_subvisuals", ":", "v", ".", "update_gl_state", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
27.75
13.666667
def c_handle_array(objs): """Create ctypes const void ** from a list of MXNet objects with handles. Parameters ---------- objs : list of NDArray/Symbol. MXNet objects. Returns ------- (ctypes.c_void_p * len(objs)) A void ** pointer that can be passed to C API. """ a...
[ "def", "c_handle_array", "(", "objs", ")", ":", "arr", "=", "(", "ctypes", ".", "c_void_p", "*", "len", "(", "objs", ")", ")", "(", ")", "arr", "[", ":", "]", "=", "[", "o", ".", "handle", "for", "o", "in", "objs", "]", "return", "arr" ]
24.625
17.5
def read_features(self, tol=1e-3): """Reads the features from a file and stores them in the current object. Parameters ---------- tol: float Tolerance level to detect duration of audio. """ try: # Read JSON file with open(self....
[ "def", "read_features", "(", "self", ",", "tol", "=", "1e-3", ")", ":", "try", ":", "# Read JSON file", "with", "open", "(", "self", ".", "file_struct", ".", "features_file", ")", "as", "f", ":", "feats", "=", "json", ".", "load", "(", "f", ")", "# S...
45.445946
18.594595
def serialize_value(self, parent_elem, value): """ Serializes str, Attrib, or PathAttrib objects. Example:: <attribute>foobar</attribute> """ if isinstance(value, (str, int)) or type(value).__name__ == 'str': parent_elem.text = str(value) elif va...
[ "def", "serialize_value", "(", "self", ",", "parent_elem", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "str", ",", "int", ")", ")", "or", "type", "(", "value", ")", ".", "__name__", "==", "'str'", ":", "parent_elem", ".", "tex...
30.214286
15.5
def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile): """ Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object. """ pixels = array('B') pixels.fromfile(ppmfile, (self.bitdepth/8) *...
[ "def", "convert_ppm_and_pgm", "(", "self", ",", "ppmfile", ",", "pgmfile", ",", "outfile", ")", ":", "pixels", "=", "array", "(", "'B'", ")", "pixels", ".", "fromfile", "(", "ppmfile", ",", "(", "self", ".", "bitdepth", "/", "8", ")", "*", "self", "....
44.95
15.95
def connect(self, **settings): """ Connect to redis and cache the new connection """ # compute a unique key for this settings, for caching. Work on the whole # dict without directly using known keys to allow the use of unix socket # connection or any other (future ?) way ...
[ "def", "connect", "(", "self", ",", "*", "*", "settings", ")", ":", "# compute a unique key for this settings, for caching. Work on the whole", "# dict without directly using known keys to allow the use of unix socket", "# connection or any other (future ?) way to connect to redis", "if", ...
51.857143
19.714286
def _get_required_fn(fn, root_path): """ Definition of the MD5 file requires, that all paths will be absolute for the package directory, not for the filesystem. This function converts filesystem-absolute paths to package-absolute paths. Args: fn (str): Local/absolute path to the file. ...
[ "def", "_get_required_fn", "(", "fn", ",", "root_path", ")", ":", "if", "not", "fn", ".", "startswith", "(", "root_path", ")", ":", "raise", "ValueError", "(", "\"Both paths have to be absolute or local!\"", ")", "replacer", "=", "\"/\"", "if", "root_path", ".",...
31.583333
23.083333
def _parse_message_to_mqtt(self, data): """Parse a mysensors command string. Return a MQTT topic, payload and qos-level as a tuple. """ msg = Message(data, self) payload = str(msg.payload) msg.payload = '' # prefix/node/child/type/ack/subtype : payload re...
[ "def", "_parse_message_to_mqtt", "(", "self", ",", "data", ")", ":", "msg", "=", "Message", "(", "data", ",", "self", ")", "payload", "=", "str", "(", "msg", ".", "payload", ")", "msg", ".", "payload", "=", "''", "# prefix/node/child/type/ack/subtype : paylo...
36.818182
13.090909
def _parse_metadata(self, meta): """Return the dict containing document metadata""" formatted_fields = self.settings['FORMATTED_FIELDS'] output = collections.OrderedDict() for name, value in meta.items(): name = name.lower() if name in formatted_fields: ...
[ "def", "_parse_metadata", "(", "self", ",", "meta", ")", ":", "formatted_fields", "=", "self", ".", "settings", "[", "'FORMATTED_FIELDS'", "]", "output", "=", "collections", ".", "OrderedDict", "(", ")", "for", "name", ",", "value", "in", "meta", ".", "ite...
40.615385
14.461538
def vmstats(): ''' .. versionchanged:: 2016.3.2 Return the virtual memory stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.vmstats ''' def linux_vmstats(): ''' linux specifi...
[ "def", "vmstats", "(", ")", ":", "def", "linux_vmstats", "(", ")", ":", "'''\n linux specific implementation of vmstats\n '''", "ret", "=", "{", "}", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "'/proc/vmstat'", ",", ...
28.236364
21.472727
def _srvc_set_config(self, trajectory): """Sets a config value to the Trajectory or changes it if the trajectory was loaded a the settings no longer match""" def _set_config(name, value, comment): if not trajectory.f_contains('config.'+name, shortcuts=False): trajecto...
[ "def", "_srvc_set_config", "(", "self", ",", "trajectory", ")", ":", "def", "_set_config", "(", "name", ",", "value", ",", "comment", ")", ":", "if", "not", "trajectory", ".", "f_contains", "(", "'config.'", "+", "name", ",", "shortcuts", "=", "False", "...
48.465517
24.5
def fix_related_item_tag(dom): """ Remove <mods:relatedItem> tag in case that there is only <mods:location> subtag. """ location = dom.match( "mods:mods", "mods:relatedItem", "mods:location" ) if not location: return location = first(location) locati...
[ "def", "fix_related_item_tag", "(", "dom", ")", ":", "location", "=", "dom", ".", "match", "(", "\"mods:mods\"", ",", "\"mods:relatedItem\"", ",", "\"mods:location\"", ")", "if", "not", "location", ":", "return", "location", "=", "first", "(", "location", ")",...
23.5
21.142857
def get_opt_val(obj_pyxb, attr_str, default_val=None): """Get an optional Simple Content value from a PyXB element. The attributes for elements that are optional according to the schema and not set in the PyXB object are present and set to None. PyXB validation will fail if required elements are missi...
[ "def", "get_opt_val", "(", "obj_pyxb", ",", "attr_str", ",", "default_val", "=", "None", ")", ":", "try", ":", "return", "get_req_val", "(", "getattr", "(", "obj_pyxb", ",", "attr_str", ")", ")", "except", "(", "ValueError", ",", "AttributeError", ")", ":"...
29.4
24.16
def command_callback(result=None): """ :type result: opendnp3.ICommandTaskResult """ print("Received command result with summary: {}".format(opendnp3.TaskCompletionToString(result.summary))) result.ForeachItem(collection_callback)
[ "def", "command_callback", "(", "result", "=", "None", ")", ":", "print", "(", "\"Received command result with summary: {}\"", ".", "format", "(", "opendnp3", ".", "TaskCompletionToString", "(", "result", ".", "summary", ")", ")", ")", "result", ".", "ForeachItem"...
40.833333
13.833333
def make_light_tarfile(self, name=None): """Lightweight tarball file. Mainly used for debugging. Return the name of the tarball file.""" name = os.path.basename(self.workdir) + "-light.tar.gz" if name is None else name return self.make_tarfile(name=name, exclude_dirs=["outdata", "indata", "tmpda...
[ "def", "make_light_tarfile", "(", "self", ",", "name", "=", "None", ")", ":", "name", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "workdir", ")", "+", "\"-light.tar.gz\"", "if", "name", "is", "None", "else", "name", "return", "self", "."...
80.5
24.75
def _result(self) -> ResultLazyType: """ ``self.config.replacer_function``(``Callable[[str], str]``) must exists. """ config = cast(IntervalsCollectionBasedReplacerConfig, self.config) diff_acc = 0 for interval, aggregated_mark in self.continuous_intervals(): ...
[ "def", "_result", "(", "self", ")", "->", "ResultLazyType", ":", "config", "=", "cast", "(", "IntervalsCollectionBasedReplacerConfig", ",", "self", ".", "config", ")", "diff_acc", "=", "0", "for", "interval", ",", "aggregated_mark", "in", "self", ".", "continu...
40.5
23.285714
def apnumber(value): """For numbers 1-9, returns the number spelled out. Otherwise, returns the number. This follows Associated Press style. This always returns a string unless the value was not int-able, unlike the Django filter.""" try: value = int(value) except (TypeError, ValueError): ...
[ "def", "apnumber", "(", "value", ")", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "value", "if", "not", "0", "<", "value", "<", "10", ":", "return", "str", "(", "value"...
42.916667
17.5
def cut_video_stream(stream, start, end, fmt): """ cut video stream from `start` to `end` time Parameters ---------- stream : bytes video file content start : float start time end : float end time Returns ------- result : bytes content of cut video ...
[ "def", "cut_video_stream", "(", "stream", ",", "start", ",", "end", ",", "fmt", ")", ":", "with", "TemporaryDirectory", "(", ")", "as", "tmp", ":", "in_file", "=", "Path", "(", "tmp", ")", "/", "f\"in{fmt}\"", "out_file", "=", "Path", "(", "tmp", ")", ...
22.285714
17.836735
def _validate_xor_args(self, p): """ Raises ValueError if 2 arguments are not passed to an XOR """ if len(p[1]) != 2: raise ValueError('Invalid syntax: XOR only accepts 2 arguments, got {0}: {1}'.format(len(p[1]), p))
[ "def", "_validate_xor_args", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", "[", "1", "]", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Invalid syntax: XOR only accepts 2 arguments, got {0}: {1}'", ".", "format", "(", "len", "(", "p", "[", "...
42.666667
19.666667
async def change_presence(self, *, activity=None, status=None, afk=False): """|coro| Changes the client's presence. The activity parameter is a :class:`.Activity` object (not a string) that represents the activity being done currently. This could also be the slimmed down versions, ...
[ "async", "def", "change_presence", "(", "self", ",", "*", ",", "activity", "=", "None", ",", "status", "=", "None", ",", "afk", "=", "False", ")", ":", "if", "status", "is", "None", ":", "status", "=", "'online'", "status_enum", "=", "Status", ".", "...
33.555556
22.518519
def _send_notification(self, handle, payload): """Send a notification over BLE It is executed in the baBLE working thread: should not be blocking. Args: handle (int): The handle to notify on payload (bytearray): The value to notify """ self.bable.notify(...
[ "def", "_send_notification", "(", "self", ",", "handle", ",", "payload", ")", ":", "self", ".", "bable", ".", "notify", "(", "connection_handle", "=", "self", ".", "_connection_handle", ",", "attribute_handle", "=", "handle", ",", "value", "=", "payload", ")...
31.071429
17.642857
def set_change_request_state(change_id, state='approved'): ''' Set the approval state of a change request/record :param change_id: The ID of the change request, e.g. CHG123545 :type change_id: ``str`` :param state: The target state, e.g. approved :type state: ``str`` CLI Example: ....
[ "def", "set_change_request_state", "(", "change_id", ",", "state", "=", "'approved'", ")", ":", "client", "=", "_get_client", "(", ")", "client", ".", "table", "=", "'change_request'", "# Get the change record first", "record", "=", "client", ".", "get", "(", "{...
32
22.642857
def to_string(self, value): """ In python3, json.dumps() cannot sort keys of different types, so preconvert None to 'null'. """ self.enforce_type(value) if isinstance(value, dict) and None in value: value = value.copy() value['null'] = value[None] ...
[ "def", "to_string", "(", "self", ",", "value", ")", ":", "self", ".", "enforce_type", "(", "value", ")", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "None", "in", "value", ":", "value", "=", "value", ".", "copy", "(", ")", "value", "...
35.181818
8.818182
def set_bp(cls, ctx, register, address, trigger, watch): """ Sets a hardware breakpoint. @see: clear_bp, find_slot @type ctx: dict( str S{->} int ) @param ctx: Thread context dictionary. @type register: int @param register: Slot (debug register). @ty...
[ "def", "set_bp", "(", "cls", ",", "ctx", ",", "register", ",", "address", ",", "trigger", ",", "watch", ")", ":", "Dr7", "=", "ctx", "[", "'Dr7'", "]", "Dr7", "|=", "cls", ".", "enableMask", "[", "register", "]", "orMask", ",", "andMask", "=", "cls...
29.322581
17.83871
def execute(commands, serial=None): """ Sends the command to the connected micro:bit via serial and returns the result. If no serial connection is provided, attempts to autodetect the device. For this to work correctly, a particular sequence of commands needs to be sent to put the device into a...
[ "def", "execute", "(", "commands", ",", "serial", "=", "None", ")", ":", "close_serial", "=", "False", "if", "serial", "is", "None", ":", "serial", "=", "get_serial", "(", ")", "close_serial", "=", "True", "time", ".", "sleep", "(", "0.1", ")", "result...
33.864865
20.675676
def to_kaf(self): """ Converts the object to KAF (if it is NAF) """ if self.type == 'NAF': self.type = 'KAF' for node in self.__get_node_terms(): node.set('cid', node.get('id')) del node.attrib['id']
[ "def", "to_kaf", "(", "self", ")", ":", "if", "self", ".", "type", "==", "'NAF'", ":", "self", ".", "type", "=", "'KAF'", "for", "node", "in", "self", ".", "__get_node_terms", "(", ")", ":", "node", ".", "set", "(", "'cid'", ",", "node", ".", "ge...
31
7.888889
def guess_timefmt(datestr): """ Try to guess the format a date is written in. The following formats are supported: ================= ============== =============== Format Example Python format ----------------- -------------- --------------- ``YYYY-MM-DD`` 2002-04-21 ...
[ "def", "guess_timefmt", "(", "datestr", ")", ":", "if", "isinstance", "(", "datestr", ",", "float", ")", "or", "isinstance", "(", "datestr", ",", "int", ")", ":", "return", "None", "seasonal_key", "=", "str", "(", "config", ".", "get", "(", "'DEFAULT'", ...
33.87395
17.773109
def _encode_ndef_text_params(self, data): """ Prepend language and enconding information to data, according to nfcforum-ts-rtd-text-1-0.pdf """ status = len(self.ndef_text_lang) if self.ndef_text_enc == 'UTF16': status = status & 0b10000000 return yubi...
[ "def", "_encode_ndef_text_params", "(", "self", ",", "data", ")", ":", "status", "=", "len", "(", "self", ".", "ndef_text_lang", ")", "if", "self", ".", "ndef_text_enc", "==", "'UTF16'", ":", "status", "=", "status", "&", "0b10000000", "return", "yubico_util...
40.555556
7.888889
def modify_conf(): """ pip install redbaron """ import redbaron import ubelt as ub conf_path = 'docs/conf.py' source = ub.readfrom(conf_path) red = redbaron.RedBaron(source) # Insert custom extensions extra_extensions = [ '"sphinxcontrib.napoleon"' ] ext_node =...
[ "def", "modify_conf", "(", ")", ":", "import", "redbaron", "import", "ubelt", "as", "ub", "conf_path", "=", "'docs/conf.py'", "source", "=", "ub", ".", "readfrom", "(", "conf_path", ")", "red", "=", "redbaron", ".", "RedBaron", "(", "source", ")", "# Inser...
24.25
17.666667
def get_acl(self, key_name='', headers=None, version_id=None): """returns a bucket's acl. We include a version_id argument to support a polymorphic interface for callers, however, version_id is not relevant for Google Cloud Storage buckets and is therefore ignored here.""" ...
[ "def", "get_acl", "(", "self", ",", "key_name", "=", "''", ",", "headers", "=", "None", ",", "version_id", "=", "None", ")", ":", "return", "self", ".", "get_acl_helper", "(", "key_name", ",", "headers", ",", "STANDARD_ACL", ")" ]
63.333333
18
def _round_hex(q, r): ''' Round floating point axial hex coordinates to integer *(q,r)* coordinates. This code was adapted from: https://www.redblobgames.com/grids/hexagons/#rounding Args: q (array[float]) : NumPy array of Floating point axial *q* coordinates to round ...
[ "def", "_round_hex", "(", "q", ",", "r", ")", ":", "x", "=", "q", "z", "=", "r", "y", "=", "-", "x", "-", "z", "rx", "=", "np", ".", "round", "(", "x", ")", "ry", "=", "np", ".", "round", "(", "y", ")", "rz", "=", "np", ".", "round", ...
21.888889
25.777778
def compute_start_timeperiod(self, process_name, timeperiod): """ computes lowest *inclusive* timeperiod boundary for job to process for process with time_grouping == 1, it returns given timeperiod with no change for process with time_grouping != 1, it computes first timeperiod, not proc...
[ "def", "compute_start_timeperiod", "(", "self", ",", "process_name", ",", "timeperiod", ")", ":", "time_grouping", "=", "context", ".", "process_context", "[", "process_name", "]", ".", "time_grouping", "if", "time_grouping", "==", "1", ":", "return", "timeperiod"...
64.641026
36.512821
def pretty_print_match(match, parameterized=True): """Return a human-readable representation of a parameterized MATCH query string.""" left_curly = '{{' if parameterized else '{' right_curly = '}}' if parameterized else '}' match = remove_custom_formatting(match) parts = re.split('({}|{})'.format(le...
[ "def", "pretty_print_match", "(", "match", ",", "parameterized", "=", "True", ")", ":", "left_curly", "=", "'{{'", "if", "parameterized", "else", "'{'", "right_curly", "=", "'}}'", "if", "parameterized", "else", "'}'", "match", "=", "remove_custom_formatting", "...
48.74
21.68
def init(context, reset, force): """Setup the database.""" existing_tables = context.obj['store'].engine.table_names() if force or reset: if existing_tables and not force: message = f"Delete existing tables? [{', '.join(existing_tables)}]" click.confirm(click.style(message, f...
[ "def", "init", "(", "context", ",", "reset", ",", "force", ")", ":", "existing_tables", "=", "context", ".", "obj", "[", "'store'", "]", ".", "engine", ".", "table_names", "(", ")", "if", "force", "or", "reset", ":", "if", "existing_tables", "and", "no...
45.333333
20.333333
def regex(self, regex = None): """Regex Sets or gets the regular expression used to validate the Node Arguments: regex {str} -- A standard regular expression string Raises: ValueError Returns: None | str """ # If regex was not set, this is a getter if regex is None: return self._regex ...
[ "def", "regex", "(", "self", ",", "regex", "=", "None", ")", ":", "# If regex was not set, this is a getter", "if", "regex", "is", "None", ":", "return", "self", ".", "_regex", "# If the type is not a string", "if", "self", ".", "_type", "!=", "'string'", ":", ...
19.933333
23.033333
def list_all_zones_by_id(region=None, key=None, keyid=None, profile=None): ''' List, by their IDs, all hosted zones in the bound account. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and k...
[ "def", "list_all_zones_by_id", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "describe_hosted_zones", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid...
25.807692
27.346154
def force_overlap(move_this, from_positions, to_positions, add_bond=True): """Computes an affine transformation that maps the from_positions to the respective to_positions, and applies this transformation to the compound. Parameters ---------- move_this : mb.Compound The Compound to be move...
[ "def", "force_overlap", "(", "move_this", ",", "from_positions", ",", "to_positions", ",", "add_bond", "=", "True", ")", ":", "from", "mbuild", ".", "port", "import", "Port", "T", "=", "None", "if", "isinstance", "(", "from_positions", ",", "(", "list", ",...
44.674419
24.186047
def insertBefore(self, child, beforeChild): ''' insertBefore - Inserts a child before #beforeChild @param child <AdvancedTag/str> - Child block to insert @param beforeChild <AdvancedTag/str> - Child block to insert before. if None, will be appended @r...
[ "def", "insertBefore", "(", "self", ",", "child", ",", "beforeChild", ")", ":", "# When the second arg is null/None, the node is appended. The argument is required per JS API, but null is acceptable..", "if", "beforeChild", "is", "None", ":", "return", "self", ".", "appendBlock...
40.3
30.45
def grid_coords_from_corners(upper_left_corner, lower_right_corner, size): ''' Points are the outer edges of the UL and LR pixels. Size is rows, columns. GC projection type is taken from Points. ''' assert upper_left_corner.wkt == lower_right_corner.wkt geotransform = np.array([upper_left_corner.lon, -(...
[ "def", "grid_coords_from_corners", "(", "upper_left_corner", ",", "lower_right_corner", ",", "size", ")", ":", "assert", "upper_left_corner", ".", "wkt", "==", "lower_right_corner", ".", "wkt", "geotransform", "=", "np", ".", "array", "(", "[", "upper_left_corner", ...
70.8
30.8
def pull(iterable, n): """Return last n items of the iterable as a list. Example:: >>> pull([0, 1, 2], 3) [1, 2] **中文文档** 取出可循环对象中的最后n个元素。等效于list(iterable)[-n:], 但占用极小的内存。 因为list(iterable)要将所有元素放在内存中并生成一个新列表。该方法常用语对于 那些取index操作被改写了的可循环对象。 """ fifo = collections.deque(...
[ "def", "pull", "(", "iterable", ",", "n", ")", ":", "fifo", "=", "collections", ".", "deque", "(", "maxlen", "=", "n", ")", "for", "i", "in", "iterable", ":", "fifo", ".", "append", "(", "i", ")", "return", "list", "(", "fifo", ")" ]
21.111111
20.111111
def quantize(self): ''' Clone self and quantize it, at last return a new quantized model. :return: A new quantized model. >>> fc = Linear(4, 2) creating: createLinear >>> fc.set_weights([np.ones((2, 4)), np.ones((2,))]) >>> input = np.ones((2, 4)) >>> out...
[ "def", "quantize", "(", "self", ")", ":", "quantized_model", "=", "callBigDlFunc", "(", "self", ".", "bigdl_type", ",", "\"quantize\"", ",", "self", ".", "value", ")", "return", "Layer", ".", "of", "(", "quantized_model", ")" ]
55.122449
24.673469
def decouple(fn): """ Inverse operation of couple. Create two functions of one argument and one return from a function that takes two arguments and has two returns Examples -------- >>> h = lambda x: (2*x**3, 6*x**2) >>> f, g = decouple(h) >>> f(5) 250 >>> g(5) 150 ...
[ "def", "decouple", "(", "fn", ")", ":", "def", "fst", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "[", "0", "]", "def", "snd", "(", "*", "args", ",", "*", "*", "kwargs...
18.36
22.12
def corrdfs(df1,df2,method): """ df1 in columns df2 in rows """ dcorr=pd.DataFrame(columns=df1.columns,index=df2.columns) dpval=pd.DataFrame(columns=df1.columns,index=df2.columns) for c1 in df1: for c2 in df2: if method=='spearman': dcorr.loc[c2,c1],dp...
[ "def", "corrdfs", "(", "df1", ",", "df2", ",", "method", ")", ":", "dcorr", "=", "pd", ".", "DataFrame", "(", "columns", "=", "df1", ".", "columns", ",", "index", "=", "df2", ".", "columns", ")", "dpval", "=", "pd", ".", "DataFrame", "(", "columns"...
39.96
15.08
def remove_chartjunk(ax, spines, grid=None, ticklabels=None, show_ticks=False, xkcd=False): ''' Removes "chartjunk", such as extra lines of axes and tick marks. If grid="y" or "x", will add a white grid at the "y" or "x" axes, respectively If ticklabels="y" or "x", or ['x', 'y...
[ "def", "remove_chartjunk", "(", "ax", ",", "spines", ",", "grid", "=", "None", ",", "ticklabels", "=", "None", ",", "show_ticks", "=", "False", ",", "xkcd", "=", "False", ")", ":", "all_spines", "=", "[", "'top'", ",", "'bottom'", ",", "'right'", ",", ...
37.971831
18.760563
def generate_additional_context(self, matching_datasets): """Return top tags for a source.""" top_tags = Tag.objects.filter( dataset__in=matching_datasets ).annotate( tag_count=Count('word') ).order_by('-tag_count')[:3] return { 'top_tags': to...
[ "def", "generate_additional_context", "(", "self", ",", "matching_datasets", ")", ":", "top_tags", "=", "Tag", ".", "objects", ".", "filter", "(", "dataset__in", "=", "matching_datasets", ")", ".", "annotate", "(", "tag_count", "=", "Count", "(", "'word'", ")"...
29.636364
13.909091
def request_sync_events(blink, network): """ Request events from sync module. :param blink: Blink instance. :param network: Sync module network id. """ url = "{}/events/network/{}".format(blink.urls.base_url, network) return http_get(blink, url)
[ "def", "request_sync_events", "(", "blink", ",", "network", ")", ":", "url", "=", "\"{}/events/network/{}\"", ".", "format", "(", "blink", ".", "urls", ".", "base_url", ",", "network", ")", "return", "http_get", "(", "blink", ",", "url", ")" ]
29.555556
10.222222
def get_path(filename): """ Get absolute path for filename. :param filename: file :return: path """ path = abspath(filename) if os.path.isdir(filename) else dirname(abspath(filename)) return path
[ "def", "get_path", "(", "filename", ")", ":", "path", "=", "abspath", "(", "filename", ")", "if", "os", ".", "path", ".", "isdir", "(", "filename", ")", "else", "dirname", "(", "abspath", "(", "filename", ")", ")", "return", "path" ]
24
19.111111
def to_array(self): """ Serializes this ChatPhoto to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ChatPhoto, self).to_array() array['small_file_id'] = u(self.small_file_id) # py2: type unicode, py3: type str ...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "ChatPhoto", ",", "self", ")", ".", "to_array", "(", ")", "array", "[", "'small_file_id'", "]", "=", "u", "(", "self", ".", "small_file_id", ")", "# py2: type unicode, py3: type str", "a...
31.846154
24.153846
def plot_gos(fout_img, goids, go2obj, **kws): """Given GO ids and the obo_dag, create a plot of paths from GO ids.""" gosubdag = GoSubDag(goids, go2obj, rcntobj=True) godagplot = GoSubDagPlot(gosubdag, **kws) godagplot.plt_dag(fout_img)
[ "def", "plot_gos", "(", "fout_img", ",", "goids", ",", "go2obj", ",", "*", "*", "kws", ")", ":", "gosubdag", "=", "GoSubDag", "(", "goids", ",", "go2obj", ",", "rcntobj", "=", "True", ")", "godagplot", "=", "GoSubDagPlot", "(", "gosubdag", ",", "*", ...
49.6
6.2
def import_bin(filename, **kwargs): """Read a .bin file generated by the IRIS Instruments Syscal Pro System and return a curated dataframe for further processing. This dataframe contains only information currently deemed important. Use the function reda.importers.iris_syscal_pro_binary._import_bin to ex...
[ "def", "import_bin", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "metadata", ",", "data_raw", "=", "_import_bin", "(", "filename", ")", "skip_rows", "=", "kwargs", ".", "get", "(", "'skip_rows'", ",", "0", ")", "if", "skip_rows", ">", "0", ":",...
40.271028
21
def _recycle(self): """ Reclaim buffer space before the origin. Note: modifies buffer size """ origin = self._origin if origin == 0: return False available = self._extent - origin self._data[:available] = self._data[origin:self._extent] self._...
[ "def", "_recycle", "(", "self", ")", ":", "origin", "=", "self", ".", "_origin", "if", "origin", "==", "0", ":", "return", "False", "available", "=", "self", ".", "_extent", "-", "origin", "self", ".", "_data", "[", ":", "available", "]", "=", "self"...
29.928571
13.5
def QA_indicator_MIKE(DataFrame, N=12): """ MIKE指标 指标说明 MIKE是另外一种形式的路径指标。 买卖原则 1 WEAK-S,MEDIUM-S,STRONG-S三条线代表初级、中级、强力支撑。 2 WEAK-R,MEDIUM-R,STRONG-R三条线代表初级、中级、强力压力。 """ HIGH = DataFrame.high LOW = DataFrame.low CLOSE = DataFrame.close TYP = (HIGH+LOW+CLOSE)/3 LL = ...
[ "def", "QA_indicator_MIKE", "(", "DataFrame", ",", "N", "=", "12", ")", ":", "HIGH", "=", "DataFrame", ".", "high", "LOW", "=", "DataFrame", ".", "low", "CLOSE", "=", "DataFrame", ".", "close", "TYP", "=", "(", "HIGH", "+", "LOW", "+", "CLOSE", ")", ...
20.592593
18
def _update_imageinfo(self): """ calls get_imageinfo() if data image missing info """ missing = self._missing_imageinfo() deferred = self.flags.get('defer_imageinfo') continuing = self.data.get('continue') if missing and not deferred and not continuing: ...
[ "def", "_update_imageinfo", "(", "self", ")", ":", "missing", "=", "self", ".", "_missing_imageinfo", "(", ")", "deferred", "=", "self", ".", "flags", ".", "get", "(", "'defer_imageinfo'", ")", "continuing", "=", "self", ".", "data", ".", "get", "(", "'c...
34.4
10.6
def _read_cwl_record(rec): """Read CWL records, handling multiple nesting and batching cases. """ keys = set([]) out = [] if isinstance(rec, dict): is_batched = all([isinstance(v, (list, tuple)) for v in rec.values()]) cur = [{} for _ in range(len(rec.values()[0]) if is_batched else ...
[ "def", "_read_cwl_record", "(", "rec", ")", ":", "keys", "=", "set", "(", "[", "]", ")", "out", "=", "[", "]", "if", "isinstance", "(", "rec", ",", "dict", ")", ":", "is_batched", "=", "all", "(", "[", "isinstance", "(", "v", ",", "(", "list", ...
34.037037
15.259259
def get_strategy(name_or_cls): """Return the strategy identified by its name. If ``name_or_class`` is a class, it will be simply returned. """ if isinstance(name_or_cls, six.string_types): if name_or_cls not in STRATS: raise MutationError("strat is not defined") return STRATS...
[ "def", "get_strategy", "(", "name_or_cls", ")", ":", "if", "isinstance", "(", "name_or_cls", ",", "six", ".", "string_types", ")", ":", "if", "name_or_cls", "not", "in", "STRATS", ":", "raise", "MutationError", "(", "\"strat is not defined\"", ")", "return", "...
35.2
10.6
def _single_site(self): """ Make sure the queryset is filtered on a parent site, if that didn't happen already. """ if appsettings.FLUENT_CONTENTS_FILTER_SITE_ID and self._parent_site is None: return self.parent_site(settings.SITE_ID) else: return self
[ "def", "_single_site", "(", "self", ")", ":", "if", "appsettings", ".", "FLUENT_CONTENTS_FILTER_SITE_ID", "and", "self", ".", "_parent_site", "is", "None", ":", "return", "self", ".", "parent_site", "(", "settings", ".", "SITE_ID", ")", "else", ":", "return", ...
38.625
21.125
def _path_with_dir_fd(self, path, fct, dir_fd): """Return the path considering dir_fd. Raise on nmvalid parameters.""" if dir_fd is not None: if sys.version_info < (3, 3): raise TypeError("%s() got an unexpected keyword " "argument 'dir_fd'" % ...
[ "def", "_path_with_dir_fd", "(", "self", ",", "path", ",", "fct", ",", "dir_fd", ")", ":", "if", "dir_fd", "is", "not", "None", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "3", ")", ":", "raise", "TypeError", "(", "\"%s() got an unexpect...
51.052632
12.842105
def _pre_md5_skip_on_check(self, lpath, rfile): # type: (Downloader, pathlib.Path, # blobxfer.models.azure.StorageEntity) -> None """Perform pre MD5 skip on check :param Downloader self: this :param pathlib.Path lpath: local path :param blobxfer.models.azure.Storag...
[ "def", "_pre_md5_skip_on_check", "(", "self", ",", "lpath", ",", "rfile", ")", ":", "# type: (Downloader, pathlib.Path,", "# blobxfer.models.azure.StorageEntity) -> None", "md5", "=", "blobxfer", ".", "models", ".", "metadata", ".", "get_md5_from_metadata", "(", "r...
44.153846
15.038462
def create_missing(self): """Conditionally mark ``docker_upstream_name`` as required. Mark ``docker_upstream_name`` as required if ``content_type`` is "docker". """ if getattr(self, 'content_type', '') == 'docker': self._fields['docker_upstream_name'].required = Tru...
[ "def", "create_missing", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'content_type'", ",", "''", ")", "==", "'docker'", ":", "self", ".", "_fields", "[", "'docker_upstream_name'", "]", ".", "required", "=", "True", "super", "(", "Repository"...
36.1
19.9
async def send_heartbeat(self, short_name): """Post a heartbeat for a service. Args: short_name (string): The short name of the service to query """ if short_name not in self.services: raise ArgumentError("Unknown service name", short_name=short_name) s...
[ "async", "def", "send_heartbeat", "(", "self", ",", "short_name", ")", ":", "if", "short_name", "not", "in", "self", ".", "services", ":", "raise", "ArgumentError", "(", "\"Unknown service name\"", ",", "short_name", "=", "short_name", ")", "self", ".", "servi...
34.416667
21.166667
def get_api_url(server): """Formats the server URL properly in order to query the API. :return: A valid MyGeotab API request URL. :rtype: str """ parsed = urlparse(server) base_url = parsed.netloc if parsed.netloc else parsed.path base_url.replace('/', '') return 'https://' + base_url +...
[ "def", "get_api_url", "(", "server", ")", ":", "parsed", "=", "urlparse", "(", "server", ")", "base_url", "=", "parsed", ".", "netloc", "if", "parsed", ".", "netloc", "else", "parsed", ".", "path", "base_url", ".", "replace", "(", "'/'", ",", "''", ")"...
32
13.4
def feature_needs(*feas): """ Get info about the FUSE API version needed for the support of some features. This function takes a variable number of feature patterns. A feature pattern is either: - an integer (directly referring to a FUSE API version number) - a built-in feature specifier st...
[ "def", "feature_needs", "(", "*", "feas", ")", ":", "fmap", "=", "{", "'stateful_files'", ":", "22", ",", "'stateful_dirs'", ":", "23", ",", "'stateful_io'", ":", "(", "'stateful_files'", ",", "'stateful_dirs'", ")", ",", "'stateful_files_keep_cache'", ":", "2...
37.728261
19.75
def _killall(self, force=False): """Kill all remaining processes, forcefully if requested.""" for_termination = [] for n, p in iteritems(self._processes): if 'returncode' not in p: for_termination.append(n) for n in for_termination: p = self._pro...
[ "def", "_killall", "(", "self", ",", "force", "=", "False", ")", ":", "for_termination", "=", "[", "]", "for", "n", ",", "p", "in", "iteritems", "(", "self", ".", "_processes", ")", ":", "if", "'returncode'", "not", "in", "p", ":", "for_termination", ...
36.117647
13.058824
def instance(self, name=None, *args, **kwargs): """Create a new instance using key ``name``. :param name: the name of the class (by default) or the key name of the class used to find the class :param args: given to the ``__init__`` method :param kwargs: given to the ``__init...
[ "def", "instance", "(", "self", ",", "name", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "f'new instance of {name}'", ")", "t0", "=", "time", "(", ")", "name", "=", "self", ".", "default_name", "if", ...
42.034483
12.758621
def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None, **kwds): """ Generate a hexagonal binning plot. Generate a hexagonal binning plot of `x` versus `y`. If `C` is `None` (the default), this is a histogram of the number of occurrences of the obser...
[ "def", "hexbin", "(", "self", ",", "x", ",", "y", ",", "C", "=", "None", ",", "reduce_C_function", "=", "None", ",", "gridsize", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "reduce_C_function", "is", "not", "None", ":", "kwds", "[", "'reduc...
40.954545
21.977273
def strip_comments(text): """Comment stripper for JSON. """ regex = r'\s*(#|\/{2}).*$' regex_inline = r'(:?(?:\s)*([A-Za-z\d\.{}]*)|((?<=\").*\"),?)(?:\s)*(((#|(\/{2})).*)|)$' # noqa lines = text.split('\n') for index, line in enumerate(lines): if re.search(regex, line): i...
[ "def", "strip_comments", "(", "text", ")", ":", "regex", "=", "r'\\s*(#|\\/{2}).*$'", "regex_inline", "=", "r'(:?(?:\\s)*([A-Za-z\\d\\.{}]*)|((?<=\\\").*\\\"),?)(?:\\s)*(((#|(\\/{2})).*)|)$'", "# noqa", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "for", "index"...
33
18.375
def getMirrorTextureGL(self, eEye): """Access to mirror textures from OpenGL.""" fn = self.function_table.getMirrorTextureGL pglTextureId = glUInt_t() pglSharedTextureHandle = glSharedTextureHandle_t() result = fn(eEye, byref(pglTextureId), byref(pglSharedTextureHandle)) ...
[ "def", "getMirrorTextureGL", "(", "self", ",", "eEye", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getMirrorTextureGL", "pglTextureId", "=", "glUInt_t", "(", ")", "pglSharedTextureHandle", "=", "glSharedTextureHandle_t", "(", ")", "result", "=", "f...
45.625
17.125
def min_abs(self): '''Returns minimum absolute value.''' if self.__len__() == 0: return ArgumentError('empty set has no minimum absolute value.') if self.contains(0): return 0 return numpy.min([numpy.abs(val) for val in [self.max_neg(), s...
[ "def", "min_abs", "(", "self", ")", ":", "if", "self", ".", "__len__", "(", ")", "==", "0", ":", "return", "ArgumentError", "(", "'empty set has no minimum absolute value.'", ")", "if", "self", ".", "contains", "(", "0", ")", ":", "return", "0", "return", ...
41.444444
15.444444
def get_driver(self, namespace, parsed_args, **kwargs): """Get mutually-exlusive plugin for plugin namespace. """ option, dest = self._namespace_to_option(namespace) dest_prefix = '{0}_'.format(dest) driver_name = getattr(parsed_args, dest, 'default') driver_extension = ...
[ "def", "get_driver", "(", "self", ",", "namespace", ",", "parsed_args", ",", "*", "*", "kwargs", ")", ":", "option", ",", "dest", "=", "self", ".", "_namespace_to_option", "(", "namespace", ")", "dest_prefix", "=", "'{0}_'", ".", "format", "(", "dest", "...
45.3
14.1
def img2img_transformer_tiny(): """Tiny params.""" hparams = img2img_transformer2d_base() hparams.num_hidden_layers = 2 hparams.hidden_size = 128 hparams.batch_size = 4 hparams.max_length = 128 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.filter_size = 128 hparams.num_...
[ "def", "img2img_transformer_tiny", "(", ")", ":", "hparams", "=", "img2img_transformer2d_base", "(", ")", "hparams", ".", "num_hidden_layers", "=", "2", "hparams", ".", "hidden_size", "=", "128", "hparams", ".", "batch_size", "=", "4", "hparams", ".", "max_lengt...
30
13.5
def fold(self, **_3to2kwargs): policy = _3to2kwargs['policy']; del _3to2kwargs['policy'] """Fold header according to policy. The parsed representation of the header is folded according to RFC5322 rules, as modified by the policy. If the parse tree contains surrogateescaped byte...
[ "def", "fold", "(", "self", ",", "*", "*", "_3to2kwargs", ")", ":", "policy", "=", "_3to2kwargs", "[", "'policy'", "]", "del", "_3to2kwargs", "[", "'policy'", "]", "# At some point we need to only put fws here if it was in the source.", "header", "=", "parser", ".",...
45.68
22
def namedb_genesis_txid(address, metadata): """ Make a "fake" txid for a genesis block entry. Returns a 32-byte hash (double-sha256), hex-encoded """ preimage = '{} genesis {}'.format(address, metadata) return virtualchain.lib.hashing.bin_double_sha256(preimage).encode('hex')
[ "def", "namedb_genesis_txid", "(", "address", ",", "metadata", ")", ":", "preimage", "=", "'{} genesis {}'", ".", "format", "(", "address", ",", "metadata", ")", "return", "virtualchain", ".", "lib", ".", "hashing", ".", "bin_double_sha256", "(", "preimage", "...
42
11.428571
def normalise_tensor(tensor): ''' Normalise the tensor by dividing it by its norm, defined such that np.sqrt(X:X) ''' tensor_norm = np.linalg.norm(tensor) return tensor / tensor_norm, tensor_norm
[ "def", "normalise_tensor", "(", "tensor", ")", ":", "tensor_norm", "=", "np", ".", "linalg", ".", "norm", "(", "tensor", ")", "return", "tensor", "/", "tensor_norm", ",", "tensor_norm" ]
30.428571
19.285714
async def list_instances(self, project, page_size=100, instance_filter=None): """Fetch all instances in a GCE project. You can find the endpoint documentation `here <https://cloud. google.com/compute/docs/ref...
[ "async", "def", "list_instances", "(", "self", ",", "project", ",", "page_size", "=", "100", ",", "instance_filter", "=", "None", ")", ":", "url", "=", "(", "f'{self.BASE_URL}{self.api_version}/projects/{project}'", "'/aggregated/instances'", ")", "params", "=", "{"...
41.5
18
def _oauth_request_parameters(self, url, access_token, parameters={}, method="GET"): """Returns the OAuth parameters as a dict for the given request. parameters should include all POST arguments and query string arguments that will be sent with the request. ...
[ "def", "_oauth_request_parameters", "(", "self", ",", "url", ",", "access_token", ",", "parameters", "=", "{", "}", ",", "method", "=", "\"GET\"", ")", ":", "consumer_token", "=", "self", ".", "_oauth_consumer_token", "(", ")", "base_args", "=", "dict", "(",...
45
17.555556
def PhyDMSComprehensiveParser(): """Returns *argparse.ArgumentParser* for ``phdyms_comprehensive`` script.""" parser = ArgumentParserNoArgHelp(description=("Comprehensive phylogenetic " "model comparison and detection of selection informed by deep " "mutational scanning data. This progra...
[ "def", "PhyDMSComprehensiveParser", "(", ")", ":", "parser", "=", "ArgumentParserNoArgHelp", "(", "description", "=", "(", "\"Comprehensive phylogenetic \"", "\"model comparison and detection of selection informed by deep \"", "\"mutational scanning data. This program runs 'phydms' repea...
60.914894
23.042553
def artifactCreated(self, *args, **kwargs): """ Artifact Creation Messages Whenever the `createArtifact` end-point is called, the queue will create a record of the artifact and post a message on this exchange. All of this happens before the queue returns a signed URL for the cal...
[ "def", "artifactCreated", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ref", "=", "{", "'exchange'", ":", "'artifact-created'", ",", "'name'", ":", "'artifactCreated'", ",", "'routingKey'", ":", "[", "{", "'constant'", ":", "'primary'...
40.557895
26.031579
def get_dimensions_units(names): """Create dictionary of unit dimensions.""" dimensions_uni = {} for name in names: key = get_key_from_dimensions(names[name].dimensions) dimensions_uni[key] = names[name] plain_dimensions = [{'base': name, 'power': 1}] key = get_key_from_dim...
[ "def", "get_dimensions_units", "(", "names", ")", ":", "dimensions_uni", "=", "{", "}", "for", "name", "in", "names", ":", "key", "=", "get_key_from_dimensions", "(", "names", "[", "name", "]", ".", "dimensions", ")", "dimensions_uni", "[", "key", "]", "="...
33.95
19.6
def _validate_field(self, validation_spec, dictionary_to_validate, parent=None, force_optional=False): """ Validates if field is OK. :param validation_spec: specification of the field :type validation_spec: dict :param dictionary_to_validate: dictionary w...
[ "def", "_validate_field", "(", "self", ",", "validation_spec", ",", "dictionary_to_validate", ",", "parent", "=", "None", ",", "force_optional", "=", "False", ")", ":", "field_name", "=", "validation_spec", "[", "'name'", "]", "field_type", "=", "validation_spec",...
50.649485
21.391753
def loadtoc(self): """Load the table of contents into memory.""" self.toc = self.TOCTMPLT() self.lib.seek(self.pkgstart+self.tocpos) tocstr = self.lib.read(self.toclen) self.toc.frombinary(tocstr)
[ "def", "loadtoc", "(", "self", ")", ":", "self", ".", "toc", "=", "self", ".", "TOCTMPLT", "(", ")", "self", ".", "lib", ".", "seek", "(", "self", ".", "pkgstart", "+", "self", ".", "tocpos", ")", "tocstr", "=", "self", ".", "lib", ".", "read", ...
38.5
7.333333
def _convert_to_dict(cls, term, replace_value_names=True): """Converts a record heirarchy to nested dicts. :param term: Root term at which to start conversion """ from collections import OrderedDict if not term: return None if term.children: ...
[ "def", "_convert_to_dict", "(", "cls", ",", "term", ",", "replace_value_names", "=", "True", ")", ":", "from", "collections", "import", "OrderedDict", "if", "not", "term", ":", "return", "None", "if", "term", ".", "children", ":", "d", "=", "OrderedDict", ...
38.203125
29.671875
def construct_time_based_cache_middleware( cache_class, cache_expire_seconds=15, rpc_whitelist=TIME_BASED_CACHE_RPC_WHITELIST, should_cache_fn=_should_cache): """ Constructs a middleware which caches responses based on the request ``method`` and ``params`` for a maximum amoun...
[ "def", "construct_time_based_cache_middleware", "(", "cache_class", ",", "cache_expire_seconds", "=", "15", ",", "rpc_whitelist", "=", "TIME_BASED_CACHE_RPC_WHITELIST", ",", "should_cache_fn", "=", "_should_cache", ")", ":", "def", "time_based_cache_middleware", "(", "make_...
40.45098
20.254902
def sendMessage(self, MsgType, CorpNum, Sender, SenderName, Subject, Contents, Messages, reserveDT, adsYN=False, UserID=None, RequestNum=None): """ 문자 메시지 전송 args MsgType : 문자 전송 유형(단문:SMS, 장문:LMS, 단/장문:XMS) CorpNum : 팝빌회원 사업자번호 ...
[ "def", "sendMessage", "(", "self", ",", "MsgType", ",", "CorpNum", ",", "Sender", ",", "SenderName", ",", "Subject", ",", "Contents", ",", "Messages", ",", "reserveDT", ",", "adsYN", "=", "False", ",", "UserID", "=", "None", ",", "RequestNum", "=", "None...
36.583333
14.791667
def GetFileEntryByPathSpec(self, path_spec): """Retrieves a file entry for a path specification. Args: path_spec (PathSpec): path specification. Returns: BDEFileEntry: file entry or None. """ return bde_file_entry.BDEFileEntry( self._resolver_context, self, path_spec, is_root=T...
[ "def", "GetFileEntryByPathSpec", "(", "self", ",", "path_spec", ")", ":", "return", "bde_file_entry", ".", "BDEFileEntry", "(", "self", ".", "_resolver_context", ",", "self", ",", "path_spec", ",", "is_root", "=", "True", ",", "is_virtual", "=", "True", ")" ]
30.090909
17.363636
def _cimdatetime_representer(dumper, cimdatetime): """ PyYAML representer function for CIMDateTime objects. This is needed for yaml.safe_dump() to support CIMDateTime. """ cimdatetime_str = str(cimdatetime) node = dumper.represent_scalar(CIMDATETIME_TAG, cimdatetime_str) return node
[ "def", "_cimdatetime_representer", "(", "dumper", ",", "cimdatetime", ")", ":", "cimdatetime_str", "=", "str", "(", "cimdatetime", ")", "node", "=", "dumper", ".", "represent_scalar", "(", "CIMDATETIME_TAG", ",", "cimdatetime_str", ")", "return", "node" ]
38
13
def phiME_dens(R,z,phi,dens,Sigma,dSigmadR,d2SigmadR2,hz,Hz,dHzdz,Sigma_amp): """The density corresponding to phi_ME""" r= numpy.sqrt(R**2.+z**2.) out= dens(R,z,phi) for a,s,ds,d2s,h,H,dH \ in zip(Sigma_amp,Sigma,dSigmadR,d2SigmadR2,hz,Hz,dHzdz): out-= a*(s(r)*h(z)+d2s(r)*H(z)+2./r*d...
[ "def", "phiME_dens", "(", "R", ",", "z", ",", "phi", ",", "dens", ",", "Sigma", ",", "dSigmadR", ",", "d2SigmadR2", ",", "hz", ",", "Hz", ",", "dHzdz", ",", "Sigma_amp", ")", ":", "r", "=", "numpy", ".", "sqrt", "(", "R", "**", "2.", "+", "z", ...
43.5
19.625
def get_channel_property(self, channel_id, property_name): '''This function returns the data stored under the property name from the given channel. Parameters ---------- channel_id: int The channel id for which the property will be returned property_name: str...
[ "def", "get_channel_property", "(", "self", ",", "channel_id", ",", "property_name", ")", ":", "if", "isinstance", "(", "channel_id", ",", "(", "int", ",", "np", ".", "integer", ")", ")", ":", "if", "channel_id", "in", "self", ".", "get_channel_ids", "(", ...
44.75
26.5
def triggers(self): """ Access the triggers :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerList :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerList """ if self._triggers is None: self._triggers = TriggerList(self._version, account_si...
[ "def", "triggers", "(", "self", ")", ":", "if", "self", ".", "_triggers", "is", "None", ":", "self", ".", "_triggers", "=", "TriggerList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ...
37.5
21.5
def add_route(route, endpoint=None, **kw): """Add a new JSON API route """ def wrapper(f): try: router.DefaultRouter.add_url_rule(route, endpoint=endpoint, view_func=f, ...
[ "def", "add_route", "(", "route", ",", "endpoint", "=", "None", ",", "*", "*", "kw", ")", ":", "def", "wrapper", "(", "f", ")", ":", "try", ":", "router", ".", "DefaultRouter", ".", "add_url_rule", "(", "route", ",", "endpoint", "=", "endpoint", ",",...
37.230769
16.153846
def status_load(): ''' Return load CLI Example: .. code-block:: bash salt '*' apcups.status_load ''' data = status() if 'LOADPCT' in data: load = data['LOADPCT'].split() if load[1].lower() == 'percent': return float(load[0]) return {'Error': 'Load ...
[ "def", "status_load", "(", ")", ":", "data", "=", "status", "(", ")", "if", "'LOADPCT'", "in", "data", ":", "load", "=", "data", "[", "'LOADPCT'", "]", ".", "split", "(", ")", "if", "load", "[", "1", "]", ".", "lower", "(", ")", "==", "'percent'"...
18.823529
21.529412