text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def channels_voice_greeting_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/voice-api/greetings#create-greetings" api_path = "/api/v2/channels/voice/greetings.json" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "channels_voice_greeting_create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/channels/voice/greetings.json\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", ...
68.75
28.75
def do_indent(s, width=4, indentfirst=False): """Return a copy of the passed string, each line indented by 4 spaces. The first line is not indented. If you want to change the number of spaces or indent the first line too you can pass additional parameters to the filter: .. sourcecode:: jinja ...
[ "def", "do_indent", "(", "s", ",", "width", "=", "4", ",", "indentfirst", "=", "False", ")", ":", "indention", "=", "u' '", "*", "width", "rv", "=", "(", "u'\\n'", "+", "indention", ")", ".", "join", "(", "s", ".", "splitlines", "(", ")", ")", "i...
34.3125
16.375
def legacy_write(self, request_id, msg, max_doc_size, with_last_error): """Send OP_INSERT, etc., optionally returning response as a dict. Can raise ConnectionFailure or OperationFailure. :Parameters: - `request_id`: an int. - `msg`: bytes, an OP_INSERT, OP_UPDATE, or OP_DEL...
[ "def", "legacy_write", "(", "self", ",", "request_id", ",", "msg", ",", "max_doc_size", ",", "with_last_error", ")", ":", "self", ".", "_raise_if_not_writable", "(", "not", "with_last_error", ")", "self", ".", "send_message", "(", "msg", ",", "max_doc_size", "...
44.055556
21.611111
def download_object(container_name, object_name, destination_path, profile, overwrite_existing=False, delete_on_failure=True, **libcloud_kwargs): ''' Download an object to the specified destination path. :param container_name: Container name :type container_name: ``str`` :para...
[ "def", "download_object", "(", "container_name", ",", "object_name", ",", "destination_path", ",", "profile", ",", "overwrite_existing", "=", "False", ",", "delete_on_failure", "=", "True", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", ...
36.333333
26.244444
def zharkov_panh(v, temp, v0, a0, m, n, z, t_ref=300., three_r=3. * constants.R): """ calculate pressure from anharmonicity for Zharkov equation the equation is from Dorogokupets 2015 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in...
[ "def", "zharkov_panh", "(", "v", ",", "temp", ",", "v0", ",", "a0", ",", "m", ",", "n", ",", "z", ",", "t_ref", "=", "300.", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ")", ":", "v_mol", "=", "vol_uc2mol", "(", "v", ",", "z", ")",...
34.208333
15.208333
def register_file_monitor(filename, target=None): """Maps a specific file/directory modification event to a signal. :param str|unicode filename: File or a directory to watch for its modification. :param int|Signal|str|unicode target: Existing signal to raise or Signal Target to register signal imp...
[ "def", "register_file_monitor", "(", "filename", ",", "target", "=", "None", ")", ":", "return", "_automate_signal", "(", "target", ",", "func", "=", "lambda", "sig", ":", "uwsgi", ".", "add_file_monitor", "(", "int", "(", "sig", ")", ",", "filename", ")",...
48.2
31.88
async def send_event(self, con, name, payload): """Send an event to a client connection. This method will push an event message to the client with the given name and payload. You need to have access to the the ``connection`` object for the client, which is only available once the clien...
[ "async", "def", "send_event", "(", "self", ",", "con", ",", "name", ",", "payload", ")", ":", "message", "=", "dict", "(", "type", "=", "\"event\"", ",", "name", "=", "name", ",", "payload", "=", "payload", ")", "encoded", "=", "pack", "(", "message"...
41.578947
21.631579
async def CharmArchiveSha256(self, urls): ''' urls : typing.Sequence[~CharmURL] Returns -> typing.Sequence[~StringResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Uniter', request='CharmArchiveSha256', ...
[ "async", "def", "CharmArchiveSha256", "(", "self", ",", "urls", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'Uniter'", ",", "request", "=", "'CharmArchiveSha256'", ",", "version", "=", "5...
31.571429
11.142857
def multiChoiceParam(parameters, name, type_converter = str): """ multi choice parameter values. :param parameters: the parameters tree. :param name: the name of the parameter. :param type_converter: function to convert the chosen value to a different type (e.g. str, float, int). default = 'str' :re...
[ "def", "multiChoiceParam", "(", "parameters", ",", "name", ",", "type_converter", "=", "str", ")", ":", "param", "=", "parameters", ".", "find", "(", "\".//MultiChoiceParam[@Name='{name}']\"", ".", "format", "(", "name", "=", "name", ")", ")", "value", "=", ...
53.909091
20
def role_get(user): ''' List roles for user user : string username CLI Example: .. code-block:: bash salt '*' rbac.role_get leo ''' user_roles = [] ## read user_attr file (user:qualifier:res1:res2:attr) with salt.utils.files.fopen('/etc/user_attr', 'r') as user_a...
[ "def", "role_get", "(", "user", ")", ":", "user_roles", "=", "[", "]", "## read user_attr file (user:qualifier:res1:res2:attr)", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "'/etc/user_attr'", ",", "'r'", ")", "as", "user_attr", ":", "for", ...
26.829268
21.853659
def write_block(self, block_, body): """Outputs the boilerplate necessary for code blocks like functions. Args: block_: The Block object representing the code block. body: String containing Go code making up the body of the code block. """ self.write('for ; πF.State() >= 0; πF.PopCheckpoint...
[ "def", "write_block", "(", "self", ",", "block_", ",", "body", ")", ":", "self", ".", "write", "(", "'for ; πF.State() >= 0; πF.PopCheckpoint() {')", "", "with", "self", ".", "indent_block", "(", ")", ":", "self", ".", "write", "(", "'switch πF.State() {')", "...
39.157895
16.368421
def multi_option(*param_decls, **attrs): """modify help text and indicate option is permitted multiple times :param param_decls: :param attrs: :return: """ attrhelp = attrs.get('help', None) if attrhelp is not None: newhelp = attrhelp + " (multiple occurrence permitted)" at...
[ "def", "multi_option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "attrhelp", "=", "attrs", ".", "get", "(", "'help'", ",", "None", ")", "if", "attrhelp", "is", "not", "None", ":", "newhelp", "=", "attrhelp", "+", "\" (multiple occurrence...
28.857143
15.142857
def _create_request_map(cls, input_map): """Create request map.""" mapped = super(Certificate, cls)._create_request_map(input_map) if mapped.get('service') == CertificateType.developer: mapped['service'] = CertificateType.bootstrap return mapped
[ "def", "_create_request_map", "(", "cls", ",", "input_map", ")", ":", "mapped", "=", "super", "(", "Certificate", ",", "cls", ")", ".", "_create_request_map", "(", "input_map", ")", "if", "mapped", ".", "get", "(", "'service'", ")", "==", "CertificateType", ...
47.333333
14.833333
def schedule(self, callback, timeout=100): '''Schedule a function to be called repeated time. This method can be used to perform animations. **Example** This is a typical way to perform an animation, just:: from chemlab.graphics.qt import QtViewer ...
[ "def", "schedule", "(", "self", ",", "callback", ",", "timeout", "=", "100", ")", ":", "timer", "=", "QTimer", "(", "self", ")", "timer", ".", "timeout", ".", "connect", "(", "callback", ")", "timer", ".", "start", "(", "timeout", ")", "return", "tim...
30.395349
20.860465
def getAttributeValueData(self, index): """ Return the data of the attribute at the given index :param index: index of the attribute """ offset = self._get_attribute_offset(index) return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_DATA]
[ "def", "getAttributeValueData", "(", "self", ",", "index", ")", ":", "offset", "=", "self", ".", "_get_attribute_offset", "(", "index", ")", "return", "self", ".", "m_attributes", "[", "offset", "+", "const", ".", "ATTRIBUTE_IX_VALUE_DATA", "]" ]
35.75
13.25
def angvel(target, current, scale): '''Use sigmoid function to choose a delta that will help smoothly steer from current angle to target angle.''' delta = target - current while delta < -180: delta += 360; while delta > 180: delta -= 360; return (old_div(2.0, (1.0 + math.exp(old_div(...
[ "def", "angvel", "(", "target", ",", "current", ",", "scale", ")", ":", "delta", "=", "target", "-", "current", "while", "delta", "<", "-", "180", ":", "delta", "+=", "360", "while", "delta", ">", "180", ":", "delta", "-=", "360", "return", "(", "o...
42
24.5
def H3(self): "Correlation." multiplied = np.dot(self.levels[:, np.newaxis] + 1, self.levels[np.newaxis] + 1) repeated = np.tile(multiplied[np.newaxis], (self.nobjects, 1, 1)) summed = (repeated * self.P).sum(2).sum(1) h3 = (summed - self.mux * self.mu...
[ "def", "H3", "(", "self", ")", ":", "multiplied", "=", "np", ".", "dot", "(", "self", ".", "levels", "[", ":", ",", "np", ".", "newaxis", "]", "+", "1", ",", "self", ".", "levels", "[", "np", ".", "newaxis", "]", "+", "1", ")", "repeated", "=...
43.444444
21.222222
def _read_object(self, correlation_id, parameters): """ Reads configuration file, parameterizes its content and converts it into JSON object. :param correlation_id: (optional) transaction id to trace execution through call chain. :param parameters: values to parameters the configuratio...
[ "def", "_read_object", "(", "self", ",", "correlation_id", ",", "parameters", ")", ":", "path", "=", "self", ".", "get_path", "(", ")", "if", "path", "==", "None", ":", "raise", "ConfigException", "(", "correlation_id", ",", "\"NO_PATH\"", ",", "\"Missing co...
38.551724
22.758621
def check_2d(inp): """ Check input to be a matrix. Converts lists of lists to np.ndarray. Also allows the input to be a scipy sparse matrix. Parameters ---------- inp : obj Input matrix Returns ------- numpy.ndarray, scipy.sparse or None Input matrix or None ...
[ "def", "check_2d", "(", "inp", ")", ":", "if", "isinstance", "(", "inp", ",", "list", ")", ":", "return", "check_2d", "(", "np", ".", "array", "(", "inp", ")", ")", "if", "isinstance", "(", "inp", ",", "(", "np", ".", "ndarray", ",", "np", ".", ...
22.030303
21.727273
def ar_path_to_x_path(ar_path, dest_element=None): # type: (str, typing.Optional[str]) -> str """Get path in translation-dictionary.""" ar_path_elements = ar_path.strip('/').split('/') xpath = "." for element in ar_path_elements[:-1]: xpath += "//A:SHORT-NAME[text()='" + element + "']/.." ...
[ "def", "ar_path_to_x_path", "(", "ar_path", ",", "dest_element", "=", "None", ")", ":", "# type: (str, typing.Optional[str]) -> str", "ar_path_elements", "=", "ar_path", ".", "strip", "(", "'/'", ")", ".", "split", "(", "'/'", ")", "xpath", "=", "\".\"", "for", ...
37.785714
23.142857
def detect_member(row, key): ''' properly detects if a an attribute exists ''' (target, tkey, tvalue) = dict_crawl(row, key) if target: return True return False
[ "def", "detect_member", "(", "row", ",", "key", ")", ":", "(", "target", ",", "tkey", ",", "tvalue", ")", "=", "dict_crawl", "(", "row", ",", "key", ")", "if", "target", ":", "return", "True", "return", "False" ]
29.833333
17.5
def get_subgraph_list(self): """Get the list of Subgraph instances. This method returns the list of Subgraph instances in the graph. """ sgraph_objs = list() for sgraph in self.obj_dict['subgraphs']: obj_dict_list = self.obj_dict['subgraphs'][sgraph] ...
[ "def", "get_subgraph_list", "(", "self", ")", ":", "sgraph_objs", "=", "list", "(", ")", "for", "sgraph", "in", "self", ".", "obj_dict", "[", "'subgraphs'", "]", ":", "obj_dict_list", "=", "self", ".", "obj_dict", "[", "'subgraphs'", "]", "[", "sgraph", ...
28.875
18.0625
def portgroups_configured(name, dvs, portgroups): ''' Configures portgroups on a DVS. Creates/updates/removes portgroups in a provided DVS dvs Name of the DVS portgroups Portgroup dict representations (see module sysdocs) ''' datacenter = _get_datacenter_name() log.inf...
[ "def", "portgroups_configured", "(", "name", ",", "dvs", ",", "portgroups", ")", ":", "datacenter", "=", "_get_datacenter_name", "(", ")", "log", ".", "info", "(", "'Running state %s on DVS \\'%s\\', datacenter \\'%s\\''", ",", "name", ",", "dvs", ",", "datacenter",...
45.462687
18.671642
def Q_srk(self, k): """ function (k). Returns the square root of noise matrix of dynamic model on iteration k. k (iteration number). starts at 0 This function is implemented to use SVD prediction step. """ ind = self.index[self.Q_time_var_index,...
[ "def", "Q_srk", "(", "self", ",", "k", ")", ":", "ind", "=", "self", ".", "index", "[", "self", ".", "Q_time_var_index", ",", "k", "]", "Q", "=", "self", ".", "Q", "[", ":", ",", ":", ",", "ind", "]", "if", "(", "Q", ".", "shape", "[", "0",...
36.210526
21.315789
def check_event(self, sim_time): """ Check for event occurrance for``Event`` group models at ``sim_time`` Parameters ---------- sim_time : float The current simulation time Returns ------- list A list of model names who report (an...
[ "def", "check_event", "(", "self", ",", "sim_time", ")", ":", "ret", "=", "[", "]", "for", "model", "in", "self", ".", "__dict__", "[", "'Event'", "]", ".", "all_models", ":", "if", "self", ".", "__dict__", "[", "model", "]", ".", "is_time", "(", "...
25.913043
20.347826
def import_vboxapi(): """This import is designed to help when loading vboxapi inside of alternative Python environments (virtualenvs etc). :rtype: vboxapi module """ try: import vboxapi except ImportError: system = platform.system() py_mm_ver = sys.version_info[:2] ...
[ "def", "import_vboxapi", "(", ")", ":", "try", ":", "import", "vboxapi", "except", "ImportError", ":", "system", "=", "platform", ".", "system", "(", ")", "py_mm_ver", "=", "sys", ".", "version_info", "[", ":", "2", "]", "py_major", "=", "sys", ".", "v...
40.881579
21.407895
def extract(self, msg): """Yield an ordered dictionary if msg['type'] is in keys_by_type.""" def normal(key): v = msg.get(key) if v is None: return v normalizer = self.normalizers.get(key, lambda x: x) return normalizer(v) def odic...
[ "def", "extract", "(", "self", ",", "msg", ")", ":", "def", "normal", "(", "key", ")", ":", "v", "=", "msg", ".", "get", "(", "key", ")", "if", "v", "is", "None", ":", "return", "v", "normalizer", "=", "self", ".", "normalizers", ".", "get", "(...
32.6
19
def updater(f): "Decorate a function with named arguments into updater for transact" @functools.wraps(f) def wrapped_updater(keys, values): result = f(*values) return (keys[:len(result)], result) return wrapped_updater
[ "def", "updater", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapped_updater", "(", "keys", ",", "values", ")", ":", "result", "=", "f", "(", "*", "values", ")", "return", "(", "keys", "[", ":", "len", "(", "result...
34.857143
15.142857
def centroid_refine_triangulation_by_triangles(self, triangles): """ return points defining a refined triangulation obtained by bisection of all edges in the triangulation that are associated with the triangles in the list provided. Notes ----- The triangles are here re...
[ "def", "centroid_refine_triangulation_by_triangles", "(", "self", ",", "triangles", ")", ":", "# Remove duplicates from the list of triangles", "triangles", "=", "np", ".", "unique", "(", "np", ".", "array", "(", "triangles", ")", ")", "mlons", ",", "mlats", "=", ...
35.47619
27.47619
def index_search(right_eigenvectors): """Find simplex structure in eigenvectors to begin PCCA+. Parameters ---------- right_eigenvectors : ndarray Right eigenvectors of transition matrix Returns ------- index : ndarray Indices of simplex """ num_micro, num_eigen ...
[ "def", "index_search", "(", "right_eigenvectors", ")", ":", "num_micro", ",", "num_eigen", "=", "right_eigenvectors", ".", "shape", "index", "=", "np", ".", "zeros", "(", "num_eigen", ",", "'int'", ")", "# first vertex: row with largest norm", "index", "[", "0", ...
25.789474
22.631579
def new( name, bucket, timeout, memory, description, subnet_ids, security_group_ids ): """ Create a new lambda project """ config = {} if timeout: config['timeout'] = timeout if memory: config['memory'] = memory if description: config['description'...
[ "def", "new", "(", "name", ",", "bucket", ",", "timeout", ",", "memory", ",", "description", ",", "subnet_ids", ",", "security_group_ids", ")", ":", "config", "=", "{", "}", "if", "timeout", ":", "config", "[", "'timeout'", "]", "=", "timeout", "if", "...
22.130435
20.347826
def find(self, addr, what, max_search=None, max_symbolic_bytes=None, default=None, step=1, disable_actions=False, inspect=True, chunk_size=None): """ Returns the address of bytes equal to 'what', starting from 'start'. Note that, if you don't specify a default value, this search co...
[ "def", "find", "(", "self", ",", "addr", ",", "what", ",", "max_search", "=", "None", ",", "max_symbolic_bytes", "=", "None", ",", "default", "=", "None", ",", "step", "=", "1", ",", "disable_actions", "=", "False", ",", "inspect", "=", "True", ",", ...
55.935484
34.516129
def disasm_symbol_app(_parser, _, args): # pragma: no cover """ Disassemble a symbol from an ELF file. """ parser = argparse.ArgumentParser( prog=_parser.prog, description=_parser.description, ) parser.add_argument( '--syntax', '-s', choices=AsmSyntax.__members_...
[ "def", "disasm_symbol_app", "(", "_parser", ",", "_", ",", "args", ")", ":", "# pragma: no cover", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "_parser", ".", "prog", ",", "description", "=", "_parser", ".", "description", ",", ")", ...
31.16
17.64
def trainSuperimposedSequenceObjects(exp, numRepetitions, sequences, objects): """ Train the network on the given object and sequence simultaneously for N repetitions each. The total number of training inputs is N * seqLength = M (Ideally numPoints = seqLength) Create a ...
[ "def", "trainSuperimposedSequenceObjects", "(", "exp", ",", "numRepetitions", ",", "sequences", ",", "objects", ")", ":", "trainingSensations", "=", "{", "}", "objectSDRs", "=", "objects", ".", "provideObjectsToLearn", "(", ")", "sequenceSDRs", "=", "sequences", "...
42.037037
23.555556
def _is_possible_loh(rec, vcf_rec, params, somatic_info, use_status=False, max_normal_depth=None): """Check if the VCF record is a het in the normal with sufficient support. Only returns SNPs, since indels tend to have less precise frequency measurements. """ if _is_biallelic_snp(rec) and _passes_plus_...
[ "def", "_is_possible_loh", "(", "rec", ",", "vcf_rec", ",", "params", ",", "somatic_info", ",", "use_status", "=", "False", ",", "max_normal_depth", "=", "None", ")", ":", "if", "_is_biallelic_snp", "(", "rec", ")", "and", "_passes_plus_germline", "(", "rec", ...
60.619048
27.047619
def __get_distribution_tags(self, client, arn): """Returns a dict containing the tags for a CloudFront distribution Args: client (botocore.client.CloudFront): Boto3 CloudFront client object arn (str): ARN of the distribution to get tags for Returns: `dict` ...
[ "def", "__get_distribution_tags", "(", "self", ",", "client", ",", "arn", ")", ":", "return", "{", "t", "[", "'Key'", "]", ":", "t", "[", "'Value'", "]", "for", "t", "in", "client", ".", "list_tags_for_resource", "(", "Resource", "=", "arn", ")", "[", ...
31.2
22.533333
def evaluate_callables(data): """ Call any callable values in the input dictionary; return a new dictionary containing the evaluated results. Useful for lazily evaluating default values in ``build`` methods. >>> data = {"spam": "ham", "eggs": (lambda: 123)} >>> result = evaluate_callables(data)...
[ "def", "evaluate_callables", "(", "data", ")", ":", "sequence", "=", "(", "(", "k", ",", "v", "(", ")", "if", "callable", "(", "v", ")", "else", "v", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ")", "return", "type", "(", ...
36.692308
15.923077
def forceutc(t: Union[str, datetime.datetime, datetime.date, np.datetime64]) -> Union[datetime.datetime, datetime.date]: """ Add UTC to datetime-naive and convert to UTC for datetime aware input: python datetime (naive, utc, non-utc) or Numpy datetime64 #FIXME add Pandas and AstroPy time classes outpu...
[ "def", "forceutc", "(", "t", ":", "Union", "[", "str", ",", "datetime", ".", "datetime", ",", "datetime", ".", "date", ",", "np", ".", "datetime64", "]", ")", "->", "Union", "[", "datetime", ".", "datetime", ",", "datetime", ".", "date", "]", ":", ...
37.5
20.714286
def get_filter_form(self, **kwargs): """ If there is a filter_form, initializes that form with the contents of request.GET and returns it. """ form = None if self.filter_form: form = self.filter_form(self.request.GET) elif self.model and hasat...
[ "def", "get_filter_form", "(", "self", ",", "*", "*", "kwargs", ")", ":", "form", "=", "None", "if", "self", ".", "filter_form", ":", "form", "=", "self", ".", "filter_form", "(", "self", ".", "request", ".", "GET", ")", "elif", "self", ".", "model",...
32
14.769231
def remove_state(self, state_id, recursive=True, force=False, destroy=True): """Remove a state from the container state. :param state_id: the id of the state to remove :param recursive: a flag to indicate a recursive disassembling of all substates :param force: a flag to indicate forcef...
[ "def", "remove_state", "(", "self", ",", "state_id", ",", "recursive", "=", "True", ",", "force", "=", "False", ",", "destroy", "=", "True", ")", ":", "if", "state_id", "not", "in", "self", ".", "states", ":", "raise", "AttributeError", "(", "\"State_id ...
46.809524
23.761905
def derivesha512address(self): """ Derive address using ``RIPEMD160(SHA512(x))`` """ pkbin = unhexlify(repr(self._pubkey)) addressbin = ripemd160(hexlify(hashlib.sha512(pkbin).digest())) return Base58(hexlify(addressbin).decode('ascii'))
[ "def", "derivesha512address", "(", "self", ")", ":", "pkbin", "=", "unhexlify", "(", "repr", "(", "self", ".", "_pubkey", ")", ")", "addressbin", "=", "ripemd160", "(", "hexlify", "(", "hashlib", ".", "sha512", "(", "pkbin", ")", ".", "digest", "(", ")...
53
12.8
def new_floating_ip(self, **kwargs): """ Creates a Floating IP and assigns it to a Droplet or reserves it to a region. """ droplet_id = kwargs.get('droplet_id') region = kwargs.get('region') if self.api_version == 2: if droplet_id is not None and region is no...
[ "def", "new_floating_ip", "(", "self", ",", "*", "*", "kwargs", ")", ":", "droplet_id", "=", "kwargs", ".", "get", "(", "'droplet_id'", ")", "region", "=", "kwargs", ".", "get", "(", "'region'", ")", "if", "self", ".", "api_version", "==", "2", ":", ...
44.166667
20.166667
def lrange(self, key, start, end): """ Returns the specified elements of the list stored at key. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param int start: zero-based index to start retrieving elements from :param int end: zero-based index at wh...
[ "def", "lrange", "(", "self", ",", "key", ",", "start", ",", "end", ")", ":", "return", "self", ".", "_execute", "(", "[", "b'LRANGE'", ",", "key", ",", "start", ",", "end", "]", ")" ]
43.365854
26.439024
def transform_ipy_prompt(line): """Handle inputs that start classic IPython prompt syntax.""" if not line or line.isspace(): return line #print 'LINE: %r' % line # dbg m = _ipy_prompt_re.match(line) if m: #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg retur...
[ "def", "transform_ipy_prompt", "(", "line", ")", ":", "if", "not", "line", "or", "line", ".", "isspace", "(", ")", ":", "return", "line", "#print 'LINE: %r' % line # dbg", "m", "=", "_ipy_prompt_re", ".", "match", "(", "line", ")", "if", "m", ":", "#print...
30.25
17
def participation_policy_changed(ob, event): """ Move all the existing users to a new group """ workspace = IWorkspace(ob) old_group_name = workspace.group_for_policy(event.old_policy) old_group = api.group.get(old_group_name) for member in old_group.getAllGroupMembers(): groups = workspace....
[ "def", "participation_policy_changed", "(", "ob", ",", "event", ")", ":", "workspace", "=", "IWorkspace", "(", "ob", ")", "old_group_name", "=", "workspace", ".", "group_for_policy", "(", "event", ".", "old_policy", ")", "old_group", "=", "api", ".", "group", ...
48.111111
8.777778
def process_element(self, element, key, **params): """ The process_element method allows a single element to be operated on given an externally supplied key. """ self.p = param.ParamOverrides(self, params) return self._apply(element, key)
[ "def", "process_element", "(", "self", ",", "element", ",", "key", ",", "*", "*", "params", ")", ":", "self", ".", "p", "=", "param", ".", "ParamOverrides", "(", "self", ",", "params", ")", "return", "self", ".", "_apply", "(", "element", ",", "key",...
40
8.285714
def token(cls: Type[SIGType], pubkey: str) -> SIGType: """ Return SIG instance from pubkey :param pubkey: Public key of the signature issuer :return: """ sig = cls() sig.pubkey = pubkey return sig
[ "def", "token", "(", "cls", ":", "Type", "[", "SIGType", "]", ",", "pubkey", ":", "str", ")", "->", "SIGType", ":", "sig", "=", "cls", "(", ")", "sig", ".", "pubkey", "=", "pubkey", "return", "sig" ]
25.2
15.2
def add_store(name, store, saltenv='base'): ''' Store a certificate to the given store name The certificate to store, this can use local paths or salt:// paths store The store to add the certificate to saltenv The salt environment to use, this is ignored if a local...
[ "def", "add_store", "(", "name", ",", "store", ",", "saltenv", "=", "'base'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "cert_file", "=", "__sa...
29
22.45
def get_current_url(request, ignore_params=None): """ Giving a django request, return the current http url, possibly ignoring some GET parameters :param django.http.HttpRequest request: The current request object. :param set ignore_params: An optional set of GET parameters to ignore ...
[ "def", "get_current_url", "(", "request", ",", "ignore_params", "=", "None", ")", ":", "if", "ignore_params", "is", "None", ":", "ignore_params", "=", "set", "(", ")", "protocol", "=", "u'https'", "if", "request", ".", "is_secure", "(", ")", "else", "u\"ht...
43.789474
22
def get_gnmt_encoder_decoder(cell_type='lstm', attention_cell='scaled_luong', num_layers=2, num_bi_layers=1, hidden_size=128, dropout=0.0, use_residual=False, i2h_weight_initializer=None, h2h_weight_initializer=None, i2h_bias_initial...
[ "def", "get_gnmt_encoder_decoder", "(", "cell_type", "=", "'lstm'", ",", "attention_cell", "=", "'scaled_luong'", ",", "num_layers", "=", "2", ",", "num_bi_layers", "=", "1", ",", "hidden_size", "=", "128", ",", "dropout", "=", "0.0", ",", "use_residual", "=",...
47.816327
23.734694
def _check_cell_methods_paren_info(self, paren_contents, var): """ Checks that the spacing and/or comment info contained inside the parentheses in cell_methods is well-formed """ valid_info = TestCtx(BaseCheck.MEDIUM, self.section_titles['7.3']) ...
[ "def", "_check_cell_methods_paren_info", "(", "self", ",", "paren_contents", ",", "var", ")", ":", "valid_info", "=", "TestCtx", "(", "BaseCheck", ".", "MEDIUM", ",", "self", ".", "section_titles", "[", "'7.3'", "]", ")", "# if there are no colons, this is a simple ...
56.915493
28.295775
def makeLabel(self, value): """Create a label for the specified value. Create a label string containing the value and its units (if any), based on the values of self.step, self.span, and self.unitSystem. """ value, prefix = format_units(value, self.step, ...
[ "def", "makeLabel", "(", "self", ",", "value", ")", ":", "value", ",", "prefix", "=", "format_units", "(", "value", ",", "self", ".", "step", ",", "system", "=", "self", ".", "unitSystem", ")", "span", ",", "spanPrefix", "=", "format_units", "(", "self...
40.185185
16.444444
def hessian(self, x, y, theta_E, r_trunc, center_x=0, center_y=0): """ returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy """ x_shift = x - center_x y_shift = y - center_y dphi_dr = self._dphi_dr(x_shift, y_shift, theta_E, r_trunc) d2phi_dr2 = self._...
[ "def", "hessian", "(", "self", ",", "x", ",", "y", ",", "theta_E", ",", "r_trunc", ",", "center_x", "=", "0", ",", "center_y", "=", "0", ")", ":", "x_shift", "=", "x", "-", "center_x", "y_shift", "=", "y", "-", "center_y", "dphi_dr", "=", "self", ...
46.571429
14.857143
def start_host(session=None): """Promote the current process into python plugin host for Nvim. Start msgpack-rpc event loop for `session`, listening for Nvim requests and notifications. It registers Nvim commands for loading/unloading python plugins. The sys.stdout and sys.stderr streams are redir...
[ "def", "start_host", "(", "session", "=", "None", ")", ":", "plugins", "=", "[", "]", "for", "arg", "in", "sys", ".", "argv", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "arg", ")", "if", "ext", "==", "'.py'", ":", "plug...
33.245283
19.830189
def transformString( self, instring ): """Extension to scanString, to modify matching text with modified tokens that may be returned from a parse action. To use transformString, define a grammar and attach a parse action to it that modifies the returned token list. Invoking tra...
[ "def", "transformString", "(", "self", ",", "instring", ")", ":", "out", "=", "[", "]", "lastE", "=", "0", "# force preservation of <TAB>s, to minimize unwanted transformation of string, and to", "# keep string locs straight between transformString and scanString", "self", ".", ...
49.166667
17.875
def rename_document(self, did, name): ''' Renames the specified document. Args: - did (str): Document ID - name (str): New document name Returns: - requests.Response: Onshape response data ''' payload = { 'name': name ...
[ "def", "rename_document", "(", "self", ",", "did", ",", "name", ")", ":", "payload", "=", "{", "'name'", ":", "name", "}", "return", "self", ".", "_api", ".", "request", "(", "'post'", ",", "'/api/documents/'", "+", "did", ",", "body", "=", "payload", ...
23
23.588235
def doit(self, classes=None, recursive=True, **kwargs): """Write out commutator Write out the commutator according to its definition $[\Op{A}, \Op{B}] = \Op{A}\Op{B} - \Op{A}\Op{B}$. See :meth:`.Expression.doit`. """ return super().doit(classes, recursive, **kwargs)
[ "def", "doit", "(", "self", ",", "classes", "=", "None", ",", "recursive", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", ")", ".", "doit", "(", "classes", ",", "recursive", ",", "*", "*", "kwargs", ")" ]
34.222222
16.888889
def get(self, url=None, parse_data=True, key=None, parameters=None): """ Issue a GET request. Kwargs: url (str): Destination URL parse_data (bool): If true, parse response data key (string): If parse_data==True, look for this key when parsing data paramet...
[ "def", "get", "(", "self", ",", "url", "=", "None", ",", "parse_data", "=", "True", ",", "key", "=", "None", ",", "parameters", "=", "None", ")", ":", "return", "self", ".", "_fetch", "(", "\"GET\"", ",", "url", ",", "post_data", "=", "None", ",", ...
42.75
29.5625
def publish_scene_remove(self, scene_id): """publish the removal of a scene""" self.sequence_number += 1 self.publisher.send_multipart(msgs.MessageBuilder.scene_remove(self.sequence_number, scene_id)) return self.sequence_number
[ "def", "publish_scene_remove", "(", "self", ",", "scene_id", ")", ":", "self", ".", "sequence_number", "+=", "1", "self", ".", "publisher", ".", "send_multipart", "(", "msgs", ".", "MessageBuilder", ".", "scene_remove", "(", "self", ".", "sequence_number", ","...
51.2
15.2
def set_dhw_on(self, until=None): """Set DHW to on, either indefinitely, or until a specified time. When On, the DHW controller will work to keep its target temperature at/above its target temperature. After the specified time, it will revert to its scheduled behaviour. """ ...
[ "def", "set_dhw_on", "(", "self", ",", "until", "=", "None", ")", ":", "time_until", "=", "None", "if", "until", "is", "None", "else", "until", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "self", ".", "_set_dhw", "(", "status", "=", "\"Hold\"", ",...
39.833333
21.833333
def _parse_number(klass, number): """Parse ``number`` into an ``int`` or return ``number`` if a valid expression for a INFO/FORMAT "Number". :param str number: ``str`` to parse and check """ try: return int(number) except ValueError as e: if numbe...
[ "def", "_parse_number", "(", "klass", ",", "number", ")", ":", "try", ":", "return", "int", "(", "number", ")", "except", "ValueError", "as", "e", ":", "if", "number", "in", "VALID_NUMBERS", ":", "return", "number", "else", ":", "raise", "e" ]
30.692308
12.692308
def set_patient_medhx_flag(self, patient_id, medhx_status): """ invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param patient_id :param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and erro...
[ "def", "set_patient_medhx_flag", "(", "self", ",", "patient_id", ",", "medhx_status", ")", ":", "magic", "=", "self", ".", "_magic_json", "(", "action", "=", "TouchWorksMagicConstants", ".", "ACTION_SET_PATIENT_MEDHX_FLAG", ",", "patient_id", "=", "patient_id", ",",...
39.304348
17.73913
def move(self, destination): """Reconfigure and move the virtual environment to another path. Args: destination (str): The target path of the virtual environment. Note: Unlike `relocate`, this method *will* move the virtual to the given path. """ ...
[ "def", "move", "(", "self", ",", "destination", ")", ":", "self", ".", "relocate", "(", "destination", ")", "shutil", ".", "move", "(", "self", ".", "path", ",", "destination", ")", "self", ".", "_path", "=", "destination" ]
32
19
def get_stack_var(name, depth=0): '''This function may fiddle with the locals of the calling function, to make it the root function of the fiber. If called from a short-lived function be sure to use a bigger frame depth. Returns the fiber state or None.''' base_frame = _get_base_frame(depth) if...
[ "def", "get_stack_var", "(", "name", ",", "depth", "=", "0", ")", ":", "base_frame", "=", "_get_base_frame", "(", "depth", ")", "if", "not", "base_frame", ":", "# Frame not found", "raise", "RuntimeError", "(", "\"Base frame not found\"", ")", "# Lookup up the fra...
34.148148
18.296296
def get_instance_for_uuid(self, uuid, project_id): """Return instance name for given uuid of an instance and project. :uuid: Instance's UUID :project_id: UUID of project (tenant) """ instance_name = self._inst_info_cache.get((uuid, project_id)) if instance_name: ...
[ "def", "get_instance_for_uuid", "(", "self", ",", "uuid", ",", "project_id", ")", ":", "instance_name", "=", "self", ".", "_inst_info_cache", ".", "get", "(", "(", "uuid", ",", "project_id", ")", ")", "if", "instance_name", ":", "return", "instance_name", "i...
42.647059
14
def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] ...
[ "def", "parse_dict_header", "(", "value", ")", ":", "result", "=", "{", "}", "for", "item", "in", "parse_http_list", "(", "value", ")", ":", "if", "'='", "not", "in", "item", ":", "result", "[", "item", "]", "=", "None", "continue", "name", ",", "val...
29.709677
16.16129
def add_comment(self, issue, body, visibility=None, is_internal=False): """Add a comment from the current authenticated user on the specified issue and return a Resource for it. The issue identifier and comment body are required. :param issue: ID or key of the issue to add the comment to ...
[ "def", "add_comment", "(", "self", ",", "issue", ",", "body", ",", "visibility", "=", "None", ",", "is_internal", "=", "False", ")", ":", "data", "=", "{", "'body'", ":", "body", ",", "}", "if", "is_internal", ":", "data", ".", "update", "(", "{", ...
37.121951
23.609756
def path(self): """Return the path to the file, if the ref is a file""" if not isinstance(self.ref, str): return None u = parse_app_url(self.ref) if u.inner.proto != 'file': return None return u.path
[ "def", "path", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "ref", ",", "str", ")", ":", "return", "None", "u", "=", "parse_app_url", "(", "self", ".", "ref", ")", "if", "u", ".", "inner", ".", "proto", "!=", "'file'", ":",...
21.333333
20.75
def next(self): """ Returns the next sequence of results, given stride and n. """ try: results = self._stride_buffer.pop() except (IndexError, AttributeError): self._rebuffer() results = self._stride_buffer.pop() if not results...
[ "def", "next", "(", "self", ")", ":", "try", ":", "results", "=", "self", ".", "_stride_buffer", ".", "pop", "(", ")", "except", "(", "IndexError", ",", "AttributeError", ")", ":", "self", ".", "_rebuffer", "(", ")", "results", "=", "self", ".", "_st...
28
14.153846
def get_direct_band_gap_dict(self): """ Returns a dictionary of information about the direct band gap Returns: a dictionary of the band gaps indexed by spin along with their band indices and k-point index """ if self.is_metal(): raise ...
[ "def", "get_direct_band_gap_dict", "(", "self", ")", ":", "if", "self", ".", "is_metal", "(", ")", ":", "raise", "ValueError", "(", "\"get_direct_band_gap_dict should\"", "\"only be used with non-metals\"", ")", "direct_gap_dict", "=", "{", "}", "for", "spin", ",", ...
43.384615
15.461538
def del_device_notification(self, notification_handle, user_handle): # type: (int, int) -> None """Remove a device notification. :param notification_handle: address of the variable that contains the handle of the notification :param user_handle: user handle ...
[ "def", "del_device_notification", "(", "self", ",", "notification_handle", ",", "user_handle", ")", ":", "# type: (int, int) -> None\r", "if", "self", ".", "_port", "is", "not", "None", ":", "adsSyncDelDeviceNotificationReqEx", "(", "self", ".", "_port", ",", "self"...
37.153846
16.923077
def groups(self): """ returns the group object """ return Groups(url="%s/groups" % self.root, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initalize=False)
[ "def", "groups", "(", "self", ")", ":", "return", "Groups", "(", "url", "=", "\"%s/groups\"", "%", "self", ".", "root", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", ...
43.857143
10.714286
def set_value(self, column, row, value): """Set the value of the Matrix at the specified column and row. :param integer column: The index for the column (starting at 0) :param integer row: The index for the row (starting at 0) :param numeric value: The new value at the given colu...
[ "def", "set_value", "(", "self", ",", "column", ",", "row", ",", "value", ")", ":", "self", ".", "matrix", "[", "column", "]", "[", "row", "]", "=", "value" ]
45.3
21.1
def cancel(self, nids=None): """ Cancel all the tasks that are in the queue. nids is an optional list of node identifiers used to filter the tasks. Returns: Number of jobs cancelled, negative value if error """ if self.has_chrooted: # TODO: Use pa...
[ "def", "cancel", "(", "self", ",", "nids", "=", "None", ")", ":", "if", "self", ".", "has_chrooted", ":", "# TODO: Use paramiko to kill the job?", "warnings", ".", "warn", "(", "\"Cannot cancel the flow via sshfs!\"", ")", "return", "-", "1", "# If we are running wi...
35.454545
20.848485
def begin(self): """ connects and optionally authenticates a connection.""" self.connect(self.host, self.port) if self.user: self.starttls() self.login(self.user, self.password)
[ "def", "begin", "(", "self", ")", ":", "self", ".", "connect", "(", "self", ".", "host", ",", "self", ".", "port", ")", "if", "self", ".", "user", ":", "self", ".", "starttls", "(", ")", "self", ".", "login", "(", "self", ".", "user", ",", "sel...
36.666667
11
def contract(self, x): """ Run .contract(x) on all segmentlists. """ for value in self.itervalues(): value.contract(x) return self
[ "def", "contract", "(", "self", ",", "x", ")", ":", "for", "value", "in", "self", ".", "itervalues", "(", ")", ":", "value", ".", "contract", "(", "x", ")", "return", "self" ]
19.571429
10.428571
def _create_latent_variables(self): """ Creates model latent variables Returns ---------- None (changes model attributes) """ self.latent_variables.add_z('Sigma^2 irregular', fam.Flat(transform='exp'), fam.Normal(0,3)) for parm in range(self.z_no-1): ...
[ "def", "_create_latent_variables", "(", "self", ")", ":", "self", ".", "latent_variables", ".", "add_z", "(", "'Sigma^2 irregular'", ",", "fam", ".", "Flat", "(", "transform", "=", "'exp'", ")", ",", "fam", ".", "Normal", "(", "0", ",", "3", ")", ")", ...
34.583333
25.833333
def MetatagDistinctValuesGet(self, metatag_name, namespace = None): """ Find the distinct value of a metatag name in a certain namespace @param metatag_name (string) - Name of the metatag for which to find the distinct values @param namespace (stirng) - Name...
[ "def", "MetatagDistinctValuesGet", "(", "self", ",", "metatag_name", ",", "namespace", "=", "None", ")", ":", "ns", "=", "\"default\"", "if", "namespace", "is", "None", "else", "namespace", "if", "self", ".", "__SenseApiCall__", "(", "\"/metatag_name/{0}/distinct_...
51.2
29.866667
def logpdf(self, mu): """ Log PDF for t prior Parameters ---------- mu : float Latent variable for which the prior is being formed over Returns ---------- - log(p(mu)) """ if self.transform is not None: mu = self.t...
[ "def", "logpdf", "(", "self", ",", "mu", ")", ":", "if", "self", ".", "transform", "is", "not", "None", ":", "mu", "=", "self", ".", "transform", "(", "mu", ")", "return", "ss", ".", "t", ".", "logpdf", "(", "mu", ",", "df", "=", "self", ".", ...
24.9375
19.5625
def _process_service_check( self, data, url, tag_by_host=False, services_incl_filter=None, services_excl_filter=None, custom_tags=None ): ''' Report a service check, tagged by the service and the backend. Statuses are defined in `STATUS_TO_SERVICE_CHECK` mapping. ''' cust...
[ "def", "_process_service_check", "(", "self", ",", "data", ",", "url", ",", "tag_by_host", "=", "False", ",", "services_incl_filter", "=", "None", ",", "services_excl_filter", "=", "None", ",", "custom_tags", "=", "None", ")", ":", "custom_tags", "=", "[", "...
48.481481
28.407407
def sanitize(func): """ NFC is the normalization form recommended by W3C. """ @functools.wraps(func) def wrapper(*args, **kwargs): return normalize('NFC', func(*args, **kwargs)) return wrapper
[ "def", "sanitize", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "normalize", "(", "'NFC'", ",", "func", "(", "*", "args", ",", "*", "*", ...
30.142857
16.857143
def nano_sub(bind, tables): """Nanomsg fanout sub. (Experimental) This sub will use nanomsg to fanout the events. :param bind: the zmq pub socket or zmq device socket. :param tables: the events of tables to follow. """ logger = logging.getLogger("meepo.sub.nano_sub") from nanomsg import S...
[ "def", "nano_sub", "(", "bind", ",", "tables", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"meepo.sub.nano_sub\"", ")", "from", "nanomsg", "import", "Socket", ",", "PUB", "pub_socket", "=", "Socket", "(", "PUB", ")", "pub_socket", ".", "bi...
29.153846
19.692308
def get_privileges(self, application=None, name=None, params=None): """ `<TODO>`_ :arg application: Application name :arg name: Privilege name """ return self.transport.perform_request( "GET", _make_path("_security", "privilege", application, name...
[ "def", "get_privileges", "(", "self", ",", "application", "=", "None", ",", "name", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"GET\"", ",", "_make_path", "(", "\"_security\"", ",",...
29
16.666667
def get_broker_queue(self, code): """ 获取股票的经纪队列 :param code: 股票代码 :return: (ret, bid_frame_table, ask_frame_table)或(ret, err_message) ret == RET_OK 返回pd dataframe数据,数据列格式如下 ret != RET_OK 后面两项为错误字符串 bid_frame_table 经纪买盘数据 ...
[ "def", "get_broker_queue", "(", "self", ",", "code", ")", ":", "if", "code", "is", "None", "or", "is_str", "(", "code", ")", "is", "False", ":", "error_str", "=", "ERROR_STR_PREFIX", "+", "\"the type of param in code is wrong\"", "return", "RET_ERROR", ",", "e...
44.610169
28.067797
def simple_beam_splitter(ax, p0, size=2.54, width=0.1, alpha=0, format=None, **kwds): r"""Draw a simple beam splitter.""" if format is None: format = 'k-' a = size/2 b = width/2 x0 = [a, -a, -a, a, a] y0 = [b, b, -b, -b, b] cur_list = [(x0, y0)] cur_li...
[ "def", "simple_beam_splitter", "(", "ax", ",", "p0", ",", "size", "=", "2.54", ",", "width", "=", "0.1", ",", "alpha", "=", "0", ",", "format", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "format", "is", "None", ":", "format", "=", "'k-'"...
32.615385
18.769231
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` clas...
[ "def", "checkArgs", "(", "args", ")", ":", "# Check if we have the tped and the tfam files", "for", "fileName", "in", "[", "args", ".", "bfile", "+", "i", "for", "i", "in", "[", "\".bed\"", ",", "\".bim\"", ",", "\".fam\"", "]", "]", ":", "if", "not", "os"...
31.884615
20.384615
def return_secondary_learner(self): """Returns secondary learner using its origin and the given hyperparameters Returns: est (estimator): Estimator object """ estimator = self.base_learner_origin.return_estimator() estimator = estimator.set_params(**self.secondary_le...
[ "def", "return_secondary_learner", "(", "self", ")", ":", "estimator", "=", "self", ".", "base_learner_origin", ".", "return_estimator", "(", ")", "estimator", "=", "estimator", ".", "set_params", "(", "*", "*", "self", ".", "secondary_learner_hyperparameters", ")...
39.888889
17.222222
def launch_notebook(argv=None): """ Launch a Jupyter Notebook, with custom Untitled filenames and a prepopulated first cell with necessary boilerplate code. Notes ----- To populate the first cell, the function `new_notebook` imported in notebook.services.contents needs to be monkey patched....
[ "def", "launch_notebook", "(", "argv", "=", "None", ")", ":", "try", ":", "import", "nbformat", ".", "v4", "as", "nbf", "from", "notebook", ".", "notebookapp", "import", "NotebookApp", "from", "notebook", ".", "services", ".", "contents", "import", "manager"...
43.25
21.916667
def Floor(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Applies the Floor operator to a vertex. This maps a vertex to the biggest integer less than or equal to its value :param input_vertex: the vertex to be floor'd """ return Double(context.jvm_vie...
[ "def", "Floor", "(", "input_vertex", ":", "vertex_constructor_param_types", ",", "label", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Vertex", ":", "return", "Double", "(", "context", ".", "jvm_view", "(", ")", ".", "FloorVertex", ",", "labe...
46.625
23.875
def retinotopic_field_sign(m, element='vertices', retinotopy=Ellipsis, invert_field=False): ''' retinotopic_field_sign(mesh) yields a property array of the field sign of every vertex in the mesh m; this value may not be exactly 1 (same as VF) or -1 (mirror-image) but some value in-between; this is beca...
[ "def", "retinotopic_field_sign", "(", "m", ",", "element", "=", "'vertices'", ",", "retinotopy", "=", "Ellipsis", ",", "invert_field", "=", "False", ")", ":", "tsign", "=", "_retinotopic_field_sign_triangles", "(", "m", ",", "retinotopy", ")", "t", "=", "m", ...
64.192308
37.038462
def _add_global_counter(self): """Adds a global counter, called once for setup by @property global_step.""" assert self._global_step is None # Force this into the top-level namescope. Instead of forcing top-level # here, we could always call this in __init__() and then keep whatever # namescopes ar...
[ "def", "_add_global_counter", "(", "self", ")", ":", "assert", "self", ".", "_global_step", "is", "None", "# Force this into the top-level namescope. Instead of forcing top-level", "# here, we could always call this in __init__() and then keep whatever", "# namescopes are around then.", ...
46.916667
21.75
def decorator(caller, func=None): """ decorator(caller) converts a caller function into a decorator; decorator(caller, func) decorates a function using a caller. """ if func is not None: # returns a decorated function evaldict = func.func_globals.copy() evaldict['_call_'] = caller ...
[ "def", "decorator", "(", "caller", ",", "func", "=", "None", ")", ":", "if", "func", "is", "not", "None", ":", "# returns a decorated function", "evaldict", "=", "func", ".", "func_globals", ".", "copy", "(", ")", "evaldict", "[", "'_call_'", "]", "=", "...
43.76
9.76
def Parse(self, stat, file_object, knowledge_base): """Parse the History file.""" _, _ = stat, knowledge_base # TODO(user): Convert this to use the far more intelligent plaso parser. ie = IEParser(file_object) for dat in ie.Parse(): yield rdf_webhistory.BrowserHistoryItem( url=dat["u...
[ "def", "Parse", "(", "self", ",", "stat", ",", "file_object", ",", "knowledge_base", ")", ":", "_", ",", "_", "=", "stat", ",", "knowledge_base", "# TODO(user): Convert this to use the far more intelligent plaso parser.", "ie", "=", "IEParser", "(", "file_object", "...
40.916667
10.166667
def dhcp_request(iface=None, **kargs): """Send a DHCP discover request and return the answer""" if conf.checkIPaddr != 0: warning("conf.checkIPaddr is not 0, I may not be able to match the answer") # noqa: E501 if iface is None: iface = conf.iface fam, hw = get_if_raw_hwaddr(iface) ...
[ "def", "dhcp_request", "(", "iface", "=", "None", ",", "*", "*", "kargs", ")", ":", "if", "conf", ".", "checkIPaddr", "!=", "0", ":", "warning", "(", "\"conf.checkIPaddr is not 0, I may not be able to match the answer\"", ")", "# noqa: E501", "if", "iface", "is", ...
61
29.444444
def filter(self, **kwargs): """ Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contain all listed attributes and in which all values match for all listed attributes will be returned. """ ...
[ "def", "filter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", "sqlalchemy", "import", "or_", "Statement", "=", "self", ".", "get_model", "(", "'statement'", ")", "Tag", "=", "self", ".", "get_model", "(", "'tag'", ")", "session", "=", "self"...
32.666667
21.025641
def _compose(self, name, attributes): """Construct a style taking `attributes` from the column styles. Parameters ---------- name : str Name of main style (e.g., "header_"). attributes : set of str Adopt these elements from the column styles. Ret...
[ "def", "_compose", "(", "self", ",", "name", ",", "attributes", ")", ":", "name_style", "=", "_safe_get", "(", "self", ".", "init_style", ",", "name", ",", "elements", ".", "default", "(", "name", ")", ")", "if", "self", ".", "init_style", "is", "not",...
35.136364
17.272727
def process_rewards(self, rewards): """Clips, rounds, and changes to integer type. Args: rewards: numpy array of raw (float) rewards. Returns: processed_rewards: numpy array of np.int64 """ min_reward, max_reward = self.reward_range # Clips at min and max reward. rewards = np...
[ "def", "process_rewards", "(", "self", ",", "rewards", ")", ":", "min_reward", ",", "max_reward", "=", "self", ".", "reward_range", "# Clips at min and max reward.", "rewards", "=", "np", ".", "clip", "(", "rewards", ",", "min_reward", ",", "max_reward", ")", ...
28.352941
19.352941
def value(self, datatype): """Return the :class:`SensorValue` for the given data type. sensor.value(TELLSTICK_TEMPERATURE) is identical to calling sensor.temperature(). """ value = self.lib.tdSensorValue( self.protocol, self.model, self.id, datatype) return S...
[ "def", "value", "(", "self", ",", "datatype", ")", ":", "value", "=", "self", ".", "lib", ".", "tdSensorValue", "(", "self", ".", "protocol", ",", "self", ".", "model", ",", "self", ".", "id", ",", "datatype", ")", "return", "SensorValue", "(", "data...
40.888889
15.777778
def _parse_text(self, page_text): """Extract the s2config and the content from the raw page text.""" # 1 sanitize: remove leading blank lines # 2 separate "config text" from content, store content # 3 convert config text + \n to obtain Meta, this is the config. lines = page_tex...
[ "def", "_parse_text", "(", "self", ",", "page_text", ")", ":", "# 1 sanitize: remove leading blank lines", "# 2 separate \"config text\" from content, store content", "# 3 convert config text + \\n to obtain Meta, this is the config.", "lines", "=", "page_text", ".", "split", "(", ...
40.48
25.04
def friendly_type_name(self) -> str: """ :return: friendly type name for the end-user :rtype: str """ _constraints_set = [] if self._must_be_dir: _constraints_set.append('must be a directory') if self._must_be_file: _constraints_set.append(...
[ "def", "friendly_type_name", "(", "self", ")", "->", "str", ":", "_constraints_set", "=", "[", "]", "if", "self", ".", "_must_be_dir", ":", "_constraints_set", ".", "append", "(", "'must be a directory'", ")", "if", "self", ".", "_must_be_file", ":", "_constra...
39.571429
13.571429