text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_compatible_canvas_layers(self, category): """Collect layers from map canvas, compatible for the given category and selected impact function .. note:: Returns layers with keywords and layermode matching the category and compatible with the selected impact function. ...
[ "def", "get_compatible_canvas_layers", "(", "self", ",", "category", ")", ":", "# Collect compatible layers", "layers", "=", "[", "]", "for", "layer", "in", "self", ".", "iface", ".", "mapCanvas", "(", ")", ".", "layers", "(", ")", ":", "try", ":", "keywor...
36.046512
0.002513
def get_note_names(self): """Return a list of unique note names in the Bar.""" res = [] for cont in self.bar: for x in cont[2].get_note_names(): if x not in res: res.append(x) return res
[ "def", "get_note_names", "(", "self", ")", ":", "res", "=", "[", "]", "for", "cont", "in", "self", ".", "bar", ":", "for", "x", "in", "cont", "[", "2", "]", ".", "get_note_names", "(", ")", ":", "if", "x", "not", "in", "res", ":", "res", ".", ...
32.375
0.007519
def init_app(self, app, sessionstore=None, register_blueprint=True): """Flask application initialization. :param app: The Flask application. :param sessionstore: store for sessions. Passed to ``flask-kvsession``. If ``None`` then Redis is configured. (Default: ``None``) ...
[ "def", "init_app", "(", "self", ",", "app", ",", "sessionstore", "=", "None", ",", "register_blueprint", "=", "True", ")", ":", "self", ".", "make_session_permanent", "(", "app", ")", "return", "super", "(", "InvenioAccountsUI", ",", "self", ")", ".", "ini...
42.666667
0.003058
def _expand_base_distribution_mean(self): """Ensures `self.distribution.mean()` has `[batch, event]` shape.""" single_draw_shape = concat_vectors(self.batch_shape_tensor(), self.event_shape_tensor()) m = tf.reshape( self.distribution.mean(), # A scalar. ...
[ "def", "_expand_base_distribution_mean", "(", "self", ")", ":", "single_draw_shape", "=", "concat_vectors", "(", "self", ".", "batch_shape_tensor", "(", ")", ",", "self", ".", "event_shape_tensor", "(", ")", ")", "m", "=", "tf", ".", "reshape", "(", "self", ...
48.727273
0.001832
def get_3d_markers_no_label( self, component_info=None, data=None, component_position=None ): """Get 3D markers without label.""" return self._get_3d_markers( RT3DMarkerPositionNoLabel, component_info, data, component_position )
[ "def", "get_3d_markers_no_label", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "return", "self", ".", "_get_3d_markers", "(", "RT3DMarkerPositionNoLabel", ",", "component_info", ",", ...
38.571429
0.01087
def createPartyFromName(apps, name): ''' For creating/matching TransactionParty objects using names alone. Look for staff members with the same name and match to them first if there is exactly one match. Then, look for users and match them if there is exactly one match. Otherwise, just generate a T...
[ "def", "createPartyFromName", "(", "apps", ",", "name", ")", ":", "TransactionParty", "=", "apps", ".", "get_model", "(", "'financial'", ",", "'TransactionParty'", ")", "StaffMember", "=", "apps", ".", "get_model", "(", "'core'", ",", "'StaffMember'", ")", "Us...
34.444444
0.001882
def _validate_config(self): """ Handle and check configuration. """ groups = dict( job=defaultdict(Bunch), httpd=defaultdict(Bunch), ) for key, val in config.torque.items(): # Auto-convert numbers and bools if val.isdigit(): ...
[ "def", "_validate_config", "(", "self", ")", ":", "groups", "=", "dict", "(", "job", "=", "defaultdict", "(", "Bunch", ")", ",", "httpd", "=", "defaultdict", "(", "Bunch", ")", ",", ")", "for", "key", ",", "val", "in", "config", ".", "torque", ".", ...
42.6
0.003755
def list(self, policy_id, page=None): """ This API endpoint returns a paginated list of alert conditions associated with the given policy_id. This API endpoint returns a paginated list of the alert conditions associated with your New Relic account. Alert conditions can be filter...
[ "def", "list", "(", "self", ",", "policy_id", ",", "page", "=", "None", ")", ":", "filters", "=", "[", "'policy_id={0}'", ".", "format", "(", "policy_id", ")", ",", "'page={0}'", ".", "format", "(", "page", ")", "if", "page", "else", "None", "]", "re...
33.9375
0.00179
def merge_ndx(*args): """ Takes one or more index files and optionally one structure file and returns a path for a new merged index file. :param args: index files and zero or one structure file :return: path for the new merged index file """ ndxs = [] struct = None for fname in args: ...
[ "def", "merge_ndx", "(", "*", "args", ")", ":", "ndxs", "=", "[", "]", "struct", "=", "None", "for", "fname", "in", "args", ":", "if", "fname", ".", "endswith", "(", "'.ndx'", ")", ":", "ndxs", ".", "append", "(", "fname", ")", "else", ":", "if",...
31.25
0.001109
def split(self, data): """ Split data into list of string, each (self.width() - 1) length or less. If nul-length string specified then empty list is returned :param data: data to split :return: list of str """ line = deepcopy(data) line_width = (self.width() - 1) lines = [] while len(line): new_...
[ "def", "split", "(", "self", ",", "data", ")", ":", "line", "=", "deepcopy", "(", "data", ")", "line_width", "=", "(", "self", ".", "width", "(", ")", "-", "1", ")", "lines", "=", "[", "]", "while", "len", "(", "line", ")", ":", "new_line", "="...
21.48
0.037433
def MakeRequest(self, data): """Make a HTTP Post request to the server 'control' endpoint.""" stats_collector_instance.Get().IncrementCounter("grr_client_sent_bytes", len(data)) # Verify the response is as it should be from the control endpoint. respo...
[ "def", "MakeRequest", "(", "self", ",", "data", ")", ":", "stats_collector_instance", ".", "Get", "(", ")", ".", "IncrementCounter", "(", "\"grr_client_sent_bytes\"", ",", "len", "(", "data", ")", ")", "# Verify the response is as it should be from the control endpoint....
36.391304
0.005821
def Filter(self, match=None, **_): """Filter the current expression.""" arg = self.stack.pop(-1) # Filters can be specified as a comma separated list. for filter_name in match.group(1).split(","): filter_object = ConfigFilter.classes_by_name.get(filter_name) if filter_object is None: ...
[ "def", "Filter", "(", "self", ",", "match", "=", "None", ",", "*", "*", "_", ")", ":", "arg", "=", "self", ".", "stack", ".", "pop", "(", "-", "1", ")", "# Filters can be specified as a comma separated list.", "for", "filter_name", "in", "match", ".", "g...
36.8125
0.009934
def apply_T5(word): '''If a (V)VVV-sequence contains a VV-sequence that could be an /i/-final diphthong, there is a syllable boundary between it and the third vowel, e.g., [raa.ois.sa], [huo.uim.me], [la.eis.sa], [sel.vi.äi.si], [tai.an], [säi.e], [oi.om.me].''' WORD = _split_consonants_and_vowels(w...
[ "def", "apply_T5", "(", "word", ")", ":", "WORD", "=", "_split_consonants_and_vowels", "(", "word", ")", "for", "k", ",", "v", "in", "WORD", ".", "iteritems", "(", ")", ":", "if", "len", "(", "v", ")", ">=", "3", "and", "is_vowel", "(", "v", "[", ...
29.833333
0.001353
def endpoint_delete(auth=None, **kwargs): ''' Delete an endpoint CLI Example: .. code-block:: bash salt '*' keystoneng.endpoint_delete id=3bee4bd8c2b040ee966adfda1f0bfca9 ''' cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.delete_endpoint(**kwarg...
[ "def", "endpoint_delete", "(", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cloud", "=", "get_operator_cloud", "(", "auth", ")", "kwargs", "=", "_clean_kwargs", "(", "*", "*", "kwargs", ")", "return", "cloud", ".", "delete_endpoint", "(", "*"...
23.846154
0.003106
def pingback_url(self, server_name, target_url): """ Do a pingback call for the target URL. """ try: server = ServerProxy(server_name) reply = server.pingback.ping(self.entry_url, target_url) except (Error, socket.error): reply = '%s cannot be ...
[ "def", "pingback_url", "(", "self", ",", "server_name", ",", "target_url", ")", ":", "try", ":", "server", "=", "ServerProxy", "(", "server_name", ")", "reply", "=", "server", ".", "pingback", ".", "ping", "(", "self", ".", "entry_url", ",", "target_url", ...
35.3
0.005525
def write_profile(name, repo, token): """Save a profile to the CONFIG_FILE. After you use this method to save a profile, you can load it anytime later with the ``read_profile()`` function defined above. Args: name The name of the profile to save. repo The Gith...
[ "def", "write_profile", "(", "name", ",", "repo", ",", "token", ")", ":", "make_sure_folder_exists", "(", "CONFIG_FOLDER", ")", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "CONFIG_FILE", ")", "profile", "=", "{",...
29.322581
0.001065
def memoized(func=None, key_factory=equal_args, cache_factory=dict): """Memoizes the results of a function call. By default, exactly one result is memoized for each unique combination of function arguments. Note that memoization is not thread-safe and the default result cache will grow without bound; so care ...
[ "def", "memoized", "(", "func", "=", "None", ",", "key_factory", "=", "equal_args", ",", "cache_factory", "=", "dict", ")", ":", "if", "func", "is", "None", ":", "# We're being applied as a decorator factory; ie: the user has supplied args, like so:", "# >>> @memoized(cac...
45.961538
0.010923
def extract_zipdir(zip_file): """ Extract contents of zip file into subfolder in parent directory. Parameters ---------- zip_file : str Path to zip file Returns ------- str : folder where the zip was extracted """ if not os.path.exists(zip_file): rai...
[ "def", "extract_zipdir", "(", "zip_file", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "zip_file", ")", ":", "raise", "ValueError", "(", "'{} does not exist'", ".", "format", "(", "zip_file", ")", ")", "directory", "=", "os", ".", "path"...
27.217391
0.00463
def protocol(self): """ - | A (ipproto, proto_start) tuple. | ``ipproto`` is the IP protocol in use, e.g. Protocol.TCP or Protocol.UDP. | ``proto_start`` denotes the beginning of the protocol data. | If the packet does not match our expectations, both ipproto and proto_star...
[ "def", "protocol", "(", "self", ")", ":", "if", "self", ".", "address_family", "==", "socket", ".", "AF_INET", ":", "proto", "=", "i", "(", "self", ".", "raw", "[", "9", "]", ")", "start", "=", "(", "i", "(", "self", ".", "raw", "[", "0", "]", ...
39.133333
0.003324
def power_off(self, timeout_sec=TIMEOUT_SEC): """Power off Bluetooth.""" # Turn off bluetooth. self._powered_off.clear() IOBluetoothPreferenceSetControllerPowerState(0) if not self._powered_off.wait(timeout_sec): raise RuntimeError('Exceeded timeout waiting for adapte...
[ "def", "power_off", "(", "self", ",", "timeout_sec", "=", "TIMEOUT_SEC", ")", ":", "# Turn off bluetooth.", "self", ".", "_powered_off", ".", "clear", "(", ")", "IOBluetoothPreferenceSetControllerPowerState", "(", "0", ")", "if", "not", "self", ".", "_powered_off"...
47.285714
0.008902
def parse_properties(parent_index_name, parent_name, nested_path, esProperties): """ RETURN THE COLUMN DEFINITIONS IN THE GIVEN esProperties OBJECT """ columns = FlatList() for name, property in esProperties.items(): index_name = parent_index_name column_name = concat_field(parent_na...
[ "def", "parse_properties", "(", "parent_index_name", ",", "parent_name", ",", "nested_path", ",", "esProperties", ")", ":", "columns", "=", "FlatList", "(", ")", "for", "name", ",", "property", "in", "esProperties", ".", "items", "(", ")", ":", "index_name", ...
38.395604
0.003069
def _read_content(self): """ Reads metadata from location (and path_in_arc if archive) This function is called during the init process and should not be used in isolation: it overwrites unsafed metadata. """ if self._path_in_arc: with zipfile.ZipFile(file=str...
[ "def", "_read_content", "(", "self", ")", ":", "if", "self", ".", "_path_in_arc", ":", "with", "zipfile", ".", "ZipFile", "(", "file", "=", "str", "(", "self", ".", "_metadata_file", ")", ")", "as", "zf", ":", "self", ".", "_content", "=", "json", "....
42.625
0.002869
def load_tags(self, max_pages=30): """ Load all WordPress tags from the given site. :param max_pages: kill counter to avoid infinite looping :return: None """ logger.info("loading tags") # clear them all out so we don't get dupes if requested if self.pur...
[ "def", "load_tags", "(", "self", ",", "max_pages", "=", "30", ")", ":", "logger", ".", "info", "(", "\"loading tags\"", ")", "# clear them all out so we don't get dupes if requested", "if", "self", ".", "purge_first", ":", "Tag", ".", "objects", ".", "filter", "...
32.314815
0.003337
def check_rights(self, resources, request=None): """ Check rights for resources. :return bool: True if operation is success else HTTP_403_FORBIDDEN """ if not self.auth: return True try: if not self.auth.test_rights(resources, request=request): ...
[ "def", "check_rights", "(", "self", ",", "resources", ",", "request", "=", "None", ")", ":", "if", "not", "self", ".", "auth", ":", "return", "True", "try", ":", "if", "not", "self", ".", "auth", ".", "test_rights", "(", "resources", ",", "request", ...
31.133333
0.006237
def preamble(): """ Log the Andes command-line preamble at the `logging.INFO` level Returns ------- None """ from . import __version__ as version logger.info('ANDES {ver} (Build {b}, Python {p} on {os})' .format(ver=version[:5], b=version[-8:], p=...
[ "def", "preamble", "(", ")", ":", "from", ".", "import", "__version__", "as", "version", "logger", ".", "info", "(", "'ANDES {ver} (Build {b}, Python {p} on {os})'", ".", "format", "(", "ver", "=", "version", "[", ":", "5", "]", ",", "b", "=", "version", "...
27.857143
0.001653
def execute(self, globals_=None, _locals=None): """ Execute a code object The inputs and behavior of this function should match those of eval_ and exec_. .. _eval: https://docs.python.org/3/library/functions.html?highlight=eval#eval .. _exec: https://docs.python...
[ "def", "execute", "(", "self", ",", "globals_", "=", "None", ",", "_locals", "=", "None", ")", ":", "if", "globals_", "is", "None", ":", "globals_", "=", "globals", "(", ")", "if", "_locals", "is", "None", ":", "self", ".", "_locals", "=", "globals_"...
33
0.006869
def safe_to_exit(self, *args, **kargs): """ Overrided to prevent user from exiting selection until they have selected the right amount of instances """ if len(self.value) == self.instance_num: return True return False
[ "def", "safe_to_exit", "(", "self", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "if", "len", "(", "self", ".", "value", ")", "==", "self", ".", "instance_num", ":", "return", "True", "return", "False" ]
33.75
0.00722
def alltoall(self, x, mesh_axis, split_axis, concat_axis): """Grouped alltoall (like MPI alltoall with splitting and concatenation). Args: x: a LaidOutTensor mesh_axis: an integer the mesh axis along which to group split_axis: an integer (the Tensor axis along which to split) concat_axi...
[ "def", "alltoall", "(", "self", ",", "x", ",", "mesh_axis", ",", "split_axis", ",", "concat_axis", ")", ":", "x", "=", "x", ".", "to_laid_out_tensor", "(", ")", "t", "=", "x", ".", "one_slice", "group_assignment", "=", "self", ".", "_create_group_assignmen...
34.310345
0.004888
def publish_events( self, topic_hostname, events, custom_headers=None, raw=False, **operation_config): """Publishes a batch of events to an Azure Event Grid topic. :param topic_hostname: The host name of the topic, e.g. topic1.westus2-1.eventgrid.azure.net :type topic_hostn...
[ "def", "publish_events", "(", "self", ",", "topic_hostname", ",", "events", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "*", "*", "operation_config", ")", ":", "# Construct URL", "url", "=", "self", ".", "publish_events", ".", "metadat...
43.32
0.002709
def hardware_version(self): """Get a hardware identification string.""" hardware_string = self.hardware_string if not isinstance(hardware_string, bytes): hardware_string = self.hardware_string.encode('utf-8') if len(hardware_string) > 10: self._logger.warn("Tru...
[ "def", "hardware_version", "(", "self", ")", ":", "hardware_string", "=", "self", ".", "hardware_string", "if", "not", "isinstance", "(", "hardware_string", ",", "bytes", ")", ":", "hardware_string", "=", "self", ".", "hardware_string", ".", "encode", "(", "'u...
35
0.005566
def demultiplex_cells(fastq, out_dir, readnumber, prefix, cb_histogram, cb_cutoff): ''' Demultiplex a fastqtransformed FASTQ file into a FASTQ file for each cell. ''' annotations = detect_fastq_annotations(fastq) re_string = construct_transformed_regex(annotations) parser_...
[ "def", "demultiplex_cells", "(", "fastq", ",", "out_dir", ",", "readnumber", ",", "prefix", ",", "cb_histogram", ",", "cb_cutoff", ")", ":", "annotations", "=", "detect_fastq_annotations", "(", "fastq", ")", "re_string", "=", "construct_transformed_regex", "(", "a...
39.871795
0.001255
def do_loop_turn(self): """Receiver daemon main loop :return: None """ # Begin to clean modules self.check_and_del_zombie_modules() # Maybe the arbiter pushed a new configuration... if self.watch_for_new_conf(timeout=0.05): logger.info("I got a new ...
[ "def", "do_loop_turn", "(", "self", ")", ":", "# Begin to clean modules", "self", ".", "check_and_del_zombie_modules", "(", ")", "# Maybe the arbiter pushed a new configuration...", "if", "self", ".", "watch_for_new_conf", "(", "timeout", "=", "0.05", ")", ":", "logger"...
34.714286
0.002402
def maps_get_default_rules_output_rules_groupname(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_default_rules = ET.Element("maps_get_default_rules") config = maps_get_default_rules output = ET.SubElement(maps_get_default_rules, "output...
[ "def", "maps_get_default_rules_output_rules_groupname", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "maps_get_default_rules", "=", "ET", ".", "Element", "(", "\"maps_get_default_rules\"", ")", "confi...
42.384615
0.003552
def _send(self, data): """ Send data to statsite. Data that can not be sent will be queued. """ retry = self.RETRY # Attempt to send any data in the queue while retry > 0: # Check socket if not self.socket: # Log Error ...
[ "def", "_send", "(", "self", ",", "data", ")", ":", "retry", "=", "self", ".", "RETRY", "# Attempt to send any data in the queue", "while", "retry", ">", "0", ":", "# Check socket", "if", "not", "self", ".", "socket", ":", "# Log Error", "self", ".", "log", ...
33.848485
0.001741
def _redirect_complete(self, text: str, line: str, begidx: int, endidx: int, compfunc: Callable) -> List[str]: """Called by complete() as the first tab completion function for all commands It determines if it should tab complete for redirection (|, <, >, >>) or use the completer function for the...
[ "def", "_redirect_complete", "(", "self", ",", "text", ":", "str", ",", "line", ":", "str", ",", "begidx", ":", "int", ",", "endidx", ":", "int", ",", "compfunc", ":", "Callable", ")", "->", "List", "[", "str", "]", ":", "if", "self", ".", "allow_r...
49.846154
0.00454
def imagenet_clamp_batch(batch, low, high): """ Not necessary in practice """ F.clip(batch[:,0,:,:],low-123.680, high-123.680) F.clip(batch[:,1,:,:],low-116.779, high-116.779) F.clip(batch[:,2,:,:],low-103.939, high-103.939)
[ "def", "imagenet_clamp_batch", "(", "batch", ",", "low", ",", "high", ")", ":", "F", ".", "clip", "(", "batch", "[", ":", ",", "0", ",", ":", ",", ":", "]", ",", "low", "-", "123.680", ",", "high", "-", "123.680", ")", "F", ".", "clip", "(", ...
47.2
0.054167
def create_rules(self): '''Adds rules for the command line options''' dmp = apps.get_app_config('django_mako_plus') # the default rules = [ # files are included by default Rule('*', level=None, filetype=TYPE_FILE, score=1), ...
[ "def", "create_rules", "(", "self", ")", ":", "dmp", "=", "apps", ".", "get_app_config", "(", "'django_mako_plus'", ")", "# the default", "rules", "=", "[", "# files are included by default", "Rule", "(", "'*'", ",", "level", "=", "None", ",", "filetype", "=",...
66.707317
0.006847
def gut_message(message: Message) -> Message: """ Remove body from a message, and wrap in a message/external-body. """ wrapper = Message() wrapper.add_header('Content-Type', 'message/external-body', access_type='x-spam-deleted', expiration=time.strftime(...
[ "def", "gut_message", "(", "message", ":", "Message", ")", "->", "Message", ":", "wrapper", "=", "Message", "(", ")", "wrapper", ".", "add_header", "(", "'Content-Type'", ",", "'message/external-body'", ",", "access_type", "=", "'x-spam-deleted'", ",", "expirati...
34.285714
0.002028
def pipe(self, func: Union[Callable[..., T], Tuple[Callable[..., T], str]], *args, **kwargs) -> T: """ Apply func(self, *args, **kwargs) This method replicates the pandas method of the same name. Parameters ---------- func : function function to...
[ "def", "pipe", "(", "self", ",", "func", ":", "Union", "[", "Callable", "[", "...", ",", "T", "]", ",", "Tuple", "[", "Callable", "[", "...", ",", "T", "]", ",", "str", "]", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "T", ":...
32.067797
0.001538
def get_area_code(self, ip): ''' Get area_code ''' rec = self.get_all(ip) return rec and rec.area_code
[ "def", "get_area_code", "(", "self", ",", "ip", ")", ":", "rec", "=", "self", ".", "get_all", "(", "ip", ")", "return", "rec", "and", "rec", ".", "area_code" ]
30.75
0.015873
def error(self, msg, *args, **kwargs) -> Task: # type: ignore """ Log msg with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. await logger.error("Houston, we have a major problem", exc_info=1) """ retu...
[ "def", "error", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Task", ":", "# type: ignore", "return", "self", ".", "_make_log_task", "(", "logging", ".", "ERROR", ",", "msg", ",", "args", ",", "*", "*", "kwargs", "...
36.9
0.005291
def ignore(self, filename): """Ignore a given filename or not.""" _, ext = os.path.splitext(filename) return ext in ['.pyc', '.pyo', '.o', '.swp']
[ "def", "ignore", "(", "self", ",", "filename", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "return", "ext", "in", "[", "'.pyc'", ",", "'.pyo'", ",", "'.o'", ",", "'.swp'", "]" ]
41.75
0.011765
def apps(self): """ Dictionary with loaded applications. """ logger.debug("initialize applications ...") enabled = None apps = self.args.apps or self._config_apps.keys() unknown = set(apps) - set(self._config_apps.keys()) if unknown: raise LogR...
[ "def", "apps", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"initialize applications ...\"", ")", "enabled", "=", "None", "apps", "=", "self", ".", "args", ".", "apps", "or", "self", ".", "_config_apps", ".", "keys", "(", ")", "unknown", "=", ...
40.066667
0.006504
def versions_from_trove(trove): """Finds out python version from list of trove classifiers. Args: trove: list of trove classifiers Returns: python version string """ versions = set() for classifier in trove: if 'Programming Language :: Python ::' in classifier: ...
[ "def", "versions_from_trove", "(", "trove", ")", ":", "versions", "=", "set", "(", ")", "for", "classifier", "in", "trove", ":", "if", "'Programming Language :: Python ::'", "in", "classifier", ":", "ver", "=", "classifier", ".", "split", "(", "'::'", ")", "...
33.3125
0.001825
def get_line_pts(pt0i, pt0j, pt1i, pt1j): '''Retrieve the coordinates of the points along lines pt0i, pt0j - the starting coordinates of the lines (1-d nparray) pt1i, pt1j - the ending coordinates of the lines (1-d nparray) use the Bresenham algorithm to find the coordinates along the lines ...
[ "def", "get_line_pts", "(", "pt0i", ",", "pt0j", ",", "pt1i", ",", "pt1j", ")", ":", "assert", "len", "(", "pt0i", ")", "==", "len", "(", "pt0j", ")", "assert", "len", "(", "pt0i", ")", "==", "len", "(", "pt1i", ")", "assert", "len", "(", "pt0i",...
33.081633
0.001597
def _distribution(gtfs, table, column): """Count occurrences of values AND return it as a string. Example return value: '1:5 2:15'""" cur = gtfs.conn.cursor() cur.execute('SELECT {column}, count(*) ' 'FROM {table} GROUP BY {column} ' 'ORDER BY {column}'.format(column=c...
[ "def", "_distribution", "(", "gtfs", ",", "table", ",", "column", ")", ":", "cur", "=", "gtfs", ".", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT {column}, count(*) '", "'FROM {table} GROUP BY {column} '", "'ORDER BY {column}'", ".", "fo...
42.888889
0.002538
def _filter_commands(ctx, commands=None): """Return list of used commands.""" lookup = getattr(ctx.command, 'commands', {}) if not lookup and isinstance(ctx.command, click.MultiCommand): lookup = _get_lazyload_commands(ctx.command) if commands is None: return sorted(lookup.values(), key...
[ "def", "_filter_commands", "(", "ctx", ",", "commands", "=", "None", ")", ":", "lookup", "=", "getattr", "(", "ctx", ".", "command", ",", "'commands'", ",", "{", "}", ")", "if", "not", "lookup", "and", "isinstance", "(", "ctx", ".", "command", ",", "...
41.454545
0.002146
def validate_file(parser, arg): """Validates that `arg` is a valid file.""" if not os.path.isfile(arg): parser.error("%s is not a file." % arg) return arg
[ "def", "validate_file", "(", "parser", ",", "arg", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "arg", ")", ":", "parser", ".", "error", "(", "\"%s is not a file.\"", "%", "arg", ")", "return", "arg" ]
34
0.005747
def parse_address(address: str) -> str: """ Parse an email address, falling back to the raw string given. """ display_name, parsed_address = email.utils.parseaddr(address) return parsed_address or address
[ "def", "parse_address", "(", "address", ":", "str", ")", "->", "str", ":", "display_name", ",", "parsed_address", "=", "email", ".", "utils", ".", "parseaddr", "(", "address", ")", "return", "parsed_address", "or", "address" ]
31.285714
0.004444
def search(cls, five9, filters): """Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should confo...
[ "def", "search", "(", "cls", ",", "five9", ",", "filters", ")", ":", "return", "cls", ".", "_name_search", "(", "five9", ".", "configuration", ".", "getWebConnectors", ",", "filters", ")" ]
43.769231
0.003442
def hrule(n=1, width=WIDTH, linestyle=LineStyle('', '─', '─', '')): """Returns a formatted string used as a border between table rows Parameters ---------- n : int The number of columns in the table width : int The width of each column (Default: 11) linestyle : tuple A...
[ "def", "hrule", "(", "n", "=", "1", ",", "width", "=", "WIDTH", ",", "linestyle", "=", "LineStyle", "(", "''", ",", "'─', ", "'", "', ''", ")", ":", "", "", "", "widths", "=", "parse_width", "(", "width", ",", "n", ")", "hrstr", "=", "linestyle",...
30.833333
0.003932
def route_handler(context, content, pargs, kwargs): """ Route shortcode works a lot like rendering a page based on the url or route. This allows inserting in rendered HTML within another page. Activate it with the 'shortcodes' template filter. Within the content use the chill route shortcode: "[ch...
[ "def", "route_handler", "(", "context", ",", "content", ",", "pargs", ",", "kwargs", ")", ":", "(", "node", ",", "rule_kw", ")", "=", "node_from_uri", "(", "pargs", "[", "0", "]", ")", "if", "node", "==", "None", ":", "return", "u\"<!-- 404 '{0}' -->\"",...
35.166667
0.006149
def _update_proxy(self, change): """ An observer which sends the state change to the proxy. """ if change['type'] == 'event' and self.proxy_is_active: self.proxy.set_opened(change['name'] == 'show') else: super(ActionMenuView, self)._update_proxy(change)
[ "def", "_update_proxy", "(", "self", ",", "change", ")", ":", "if", "change", "[", "'type'", "]", "==", "'event'", "and", "self", ".", "proxy_is_active", ":", "self", ".", "proxy", ".", "set_opened", "(", "change", "[", "'name'", "]", "==", "'show'", "...
38
0.006431
def from_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing): """ Create and return a fault surface using fault source data. :param openquake.hazardlib.geo.line.Line fault_trace: Geographical line representing the...
[ "def", "from_fault_data", "(", "cls", ",", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ",", "mesh_spacing", ")", ":", "cls", ".", "check_fault_data", "(", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismog...
47.806452
0.000992
def _get_values(self): """ Get unique index value for each bar """ (gi, _), (ci, _), (si, _) = self._get_dims(self.hmap.last) ndims = self.hmap.last.ndims dims = self.hmap.last.kdims dimensions = [] values = {} for vidx, vtype in zip([gi, ci, si], ...
[ "def", "_get_values", "(", "self", ")", ":", "(", "gi", ",", "_", ")", ",", "(", "ci", ",", "_", ")", ",", "(", "si", ",", "_", ")", "=", "self", ".", "_get_dims", "(", "self", ".", "hmap", ".", "last", ")", "ndims", "=", "self", ".", "hmap...
34.684211
0.002954
def set_widgets(self): """Set widgets on the Extra Keywords tab.""" existing_inasafe_default_values = self.parent.get_existing_keyword( 'inasafe_default_values') # Remove old container and parameter if self.parameter_container: self.default_values_grid.removeWidge...
[ "def", "set_widgets", "(", "self", ")", ":", "existing_inasafe_default_values", "=", "self", ".", "parent", ".", "get_existing_keyword", "(", "'inasafe_default_values'", ")", "# Remove old container and parameter", "if", "self", ".", "parameter_container", ":", "self", ...
46.207547
0.0008
def spin1x_from_xi1_phi_a_phi_s(xi1, phi_a, phi_s): """Returns x-component spin for primary mass. """ phi1 = phi1_from_phi_a_phi_s(phi_a, phi_s) return xi1 * numpy.cos(phi1)
[ "def", "spin1x_from_xi1_phi_a_phi_s", "(", "xi1", ",", "phi_a", ",", "phi_s", ")", ":", "phi1", "=", "phi1_from_phi_a_phi_s", "(", "phi_a", ",", "phi_s", ")", "return", "xi1", "*", "numpy", ".", "cos", "(", "phi1", ")" ]
37
0.005291
def delete(self, index, doc_type, id, bulk=False, **query_params): """ Delete a typed JSON document from a specific index based on its id. If bulk is True, the delete operation is put in bulk mode. """ if bulk: cmd = {"delete": {"_index": index, "_type": doc_type, ...
[ "def", "delete", "(", "self", ",", "index", ",", "doc_type", ",", "id", ",", "bulk", "=", "False", ",", "*", "*", "query_params", ")", ":", "if", "bulk", ":", "cmd", "=", "{", "\"delete\"", ":", "{", "\"_index\"", ":", "index", ",", "\"_type\"", ":...
43.384615
0.003472
def runSearchVariantAnnotationSets(self, request): """ Runs the specified SearchVariantAnnotationSetsRequest. """ return self.runSearchRequest( request, protocol.SearchVariantAnnotationSetsRequest, protocol.SearchVariantAnnotationSetsResponse, self.var...
[ "def", "runSearchVariantAnnotationSets", "(", "self", ",", "request", ")", ":", "return", "self", ".", "runSearchRequest", "(", "request", ",", "protocol", ".", "SearchVariantAnnotationSetsRequest", ",", "protocol", ".", "SearchVariantAnnotationSetsResponse", ",", "self...
42.625
0.005747
def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613 ''' List all available package upgrades on this system CLI Example: .. code-block:: bash salt '*' pkgutil.list_upgrades ''' if salt.utils.data.is_true(refresh): refresh_db() upgrades = {} lines = __sal...
[ "def", "list_upgrades", "(", "refresh", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "if", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "refresh", ")", ":", "refresh_db", "(", ")", "upgrades", "=", "{", "}", "li...
26.217391
0.0016
def get_platform(): """Return a DHT platform interface for the currently detected platform.""" plat = platform_detect.platform_detect() if plat == platform_detect.RASPBERRY_PI: # Check for version 1 or 2 of the pi. version = platform_detect.pi_version() if version == 1: f...
[ "def", "get_platform", "(", ")", ":", "plat", "=", "platform_detect", ".", "platform_detect", "(", ")", "if", "plat", "==", "platform_detect", ".", "RASPBERRY_PI", ":", "# Check for version 1 or 2 of the pi.", "version", "=", "platform_detect", ".", "pi_version", "(...
39.304348
0.00216
def update_manual_intervention(self, manual_intervention_update_metadata, project, release_id, manual_intervention_id): """UpdateManualIntervention. [Preview API] Update manual intervention. :param :class:`<ManualInterventionUpdateMetadata> <azure.devops.v5_1.release.models.ManualInterventionUpd...
[ "def", "update_manual_intervention", "(", "self", ",", "manual_intervention_update_metadata", ",", "project", ",", "release_id", ",", "manual_intervention_id", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", ...
69.347826
0.006184
def add_replace(self, selector, replacement, upsert=False, collation=None): """Create a replace document and add it to the list of ops. """ validate_ok_for_replace(replacement) cmd = SON([('q', selector), ('u', replacement), ('multi', False), ('upse...
[ "def", "add_replace", "(", "self", ",", "selector", ",", "replacement", ",", "upsert", "=", "False", ",", "collation", "=", "None", ")", ":", "validate_ok_for_replace", "(", "replacement", ")", "cmd", "=", "SON", "(", "[", "(", "'q'", ",", "selector", ")...
44.583333
0.005495
def segment_raised_funds_average(df): """ Return some info about raised funds. """ grouped = df.groupby('Segmento') aggregated = grouped.agg(['mean', 'std']) aggregated.columns = aggregated.columns.droplevel(0) return aggregated
[ "def", "segment_raised_funds_average", "(", "df", ")", ":", "grouped", "=", "df", ".", "groupby", "(", "'Segmento'", ")", "aggregated", "=", "grouped", ".", "agg", "(", "[", "'mean'", ",", "'std'", "]", ")", "aggregated", ".", "columns", "=", "aggregated",...
27.666667
0.003891
def select_grid_model_residential(lvgd): """Selects typified model grid based on population Parameters ---------- lvgd : LVGridDistrictDing0 Low-voltage grid district object Returns ------- :pandas:`pandas.DataFrame<dataframe>` Selected string of typified model grid :pa...
[ "def", "select_grid_model_residential", "(", "lvgd", ")", ":", "# Load properties of LV typified model grids", "string_properties", "=", "lvgd", ".", "lv_grid", ".", "network", ".", "static_data", "[", "'LV_model_grids_strings'", "]", "# Load relational table of apartment count...
37.872727
0.001404
def compute_wcs(key, challenge): """ Compute an WAMP-CRA authentication signature from an authentication challenge and a (derived) key. :param key: The key derived (via PBKDF2) from the secret. :type key: str/bytes :param challenge: The authentication challenge to sign. :type challenge: str...
[ "def", "compute_wcs", "(", "key", ",", "challenge", ")", ":", "key", "=", "key", ".", "encode", "(", "'utf8'", ")", "challenge", "=", "challenge", ".", "encode", "(", "'utf8'", ")", "sig", "=", "hmac", ".", "new", "(", "key", ",", "challenge", ",", ...
32.588235
0.001754
def _decode16(self, offset): """ Decode an UTF-16 String at the given offset :param offset: offset of the string inside the data :return: str """ str_len, skip = self._decode_length(offset, 2) offset += skip # The len is the string len in utf-16 units ...
[ "def", "_decode16", "(", "self", ",", "offset", ")", ":", "str_len", ",", "skip", "=", "self", ".", "_decode_length", "(", "offset", ",", "2", ")", "offset", "+=", "skip", "# The len is the string len in utf-16 units", "encoded_bytes", "=", "str_len", "*", "2"...
33.684211
0.004559
def ancestor_paths(start=None, limit={}): """ All paths above you """ import utool as ut limit = ut.ensure_iterable(limit) limit = {expanduser(p) for p in limit}.union(set(limit)) if start is None: start = os.getcwd() path = start prev = None while path != prev and prev n...
[ "def", "ancestor_paths", "(", "start", "=", "None", ",", "limit", "=", "{", "}", ")", ":", "import", "utool", "as", "ut", "limit", "=", "ut", ".", "ensure_iterable", "(", "limit", ")", "limit", "=", "{", "expanduser", "(", "p", ")", "for", "p", "in...
25.733333
0.0025
def choices(self): """Gets the experiment choices""" if self._choices == None: self._choices = [ExperimentChoice(self, choice_name) for choice_name in self.choice_names] return self._choices
[ "def", "choices", "(", "self", ")", ":", "if", "self", ".", "_choices", "==", "None", ":", "self", ".", "_choices", "=", "[", "ExperimentChoice", "(", "self", ",", "choice_name", ")", "for", "choice_name", "in", "self", ".", "choice_names", "]", "return"...
31.714286
0.017544
def calibrate(self, data, key): """Data calibration.""" # logger.debug('Calibration: %s' % key.calibration) logger.warning('Calibration disabled!') if key.calibration == 'brightness_temperature': # self._ir_calibrate(data, key) pass elif key.calibration =...
[ "def", "calibrate", "(", "self", ",", "data", ",", "key", ")", ":", "# logger.debug('Calibration: %s' % key.calibration)", "logger", ".", "warning", "(", "'Calibration disabled!'", ")", "if", "key", ".", "calibration", "==", "'brightness_temperature'", ":", "# self._i...
29.066667
0.004444
def kv(d): """Equivalent to dict.items(). Usage:: >>> for key, node in DictTree.kv(d): >>> print(key, DictTree.getattr(node, "population")) MD 200000 VA 100000 """ return ((key, value) for key, value in iteritems(d) ...
[ "def", "kv", "(", "d", ")", ":", "return", "(", "(", "key", ",", "value", ")", "for", "key", ",", "value", "in", "iteritems", "(", "d", ")", "if", "key", "!=", "_meta", ")" ]
29.636364
0.014881
def iterateEM(self, count): ''' Iterate through all transmissions of english to foreign words. keep count of repeated occurences do until convergence set count(e|f) to 0 for all e,f set total(f) to 0 for all f for all sentence pairs (e_s,f_s) ...
[ "def", "iterateEM", "(", "self", ",", "count", ")", ":", "for", "iter", "in", "range", "(", "count", ")", ":", "countef", "=", "{", "}", "totalf", "=", "{", "}", "# set the count of the words to zero", "for", "word", "in", "self", ".", "en_words", ":", ...
32.883117
0.000767
def create(self, friendly_name=values.unset): """ Create a new AccountInstance :param unicode friendly_name: A human readable description of the account :returns: Newly created AccountInstance :rtype: twilio.rest.api.v2010.account.AccountInstance """ data = valu...
[ "def", "create", "(", "self", ",", "friendly_name", "=", "values", ".", "unset", ")", ":", "data", "=", "values", ".", "of", "(", "{", "'FriendlyName'", ":", "friendly_name", ",", "}", ")", "payload", "=", "self", ".", "_version", ".", "create", "(", ...
28.777778
0.005607
def build_backend(self, backend_node): """parse `backend` sections Args: backend_node (TreeNode): Description Returns: config.Backend: an object """ proxy_name = backend_node.backend_header.proxy_name.text config_block_lines = self.__build_config...
[ "def", "build_backend", "(", "self", ",", "backend_node", ")", ":", "proxy_name", "=", "backend_node", ".", "backend_header", ".", "proxy_name", ".", "text", "config_block_lines", "=", "self", ".", "__build_config_block", "(", "backend_node", ".", "config_block", ...
33.384615
0.004484
def get_info(pdb_id, url_root='http://www.rcsb.org/pdb/rest/describeMol?structureId='): '''Look up all information about a given PDB ID Parameters ---------- pdb_id : string A 4 character string giving a pdb entry of interest url_root : string The string root of the specific url f...
[ "def", "get_info", "(", "pdb_id", ",", "url_root", "=", "'http://www.rcsb.org/pdb/rest/describeMol?structureId='", ")", ":", "url", "=", "url_root", "+", "pdb_id", "req", "=", "urllib", ".", "request", ".", "Request", "(", "url", ")", "f", "=", "urllib", ".", ...
22.37931
0.004431
def sing(a, b, c=False, name='yetone'): """sing a song hehe :param a: I'm a :param b: I'm b :param c: I'm c :param name: I'm name """ print('test0.sing: <a: {}, b: {}, c: {}> by {}'.format(a, b, c, name))
[ "def", "sing", "(", "a", ",", "b", ",", "c", "=", "False", ",", "name", "=", "'yetone'", ")", ":", "print", "(", "'test0.sing: <a: {}, b: {}, c: {}> by {}'", ".", "format", "(", "a", ",", "b", ",", "c", ",", "name", ")", ")" ]
22.8
0.004219
async def add_ssh_key(self, user, key): """Add a public SSH key to this model. :param str user: The username of the user :param str key: The public ssh key """ key_facade = client.KeyManagerFacade.from_connection(self.connection()) return await key_facade.AddKeys([key],...
[ "async", "def", "add_ssh_key", "(", "self", ",", "user", ",", "key", ")", ":", "key_facade", "=", "client", ".", "KeyManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "return", "await", "key_facade", ".", "AddKeys", "("...
35.333333
0.006135
def kfactor(R, k=2, algorithm='COBYLA'): """k-Factor Nearest Correlation Matrix Fit Parameters: ----------- R : ndarray an illconditioned <d x d> correlation matrix, e.g. oxyba.illcond_corrmat k : int Number of factors (Default: 2) algorithm : str 'COBYLA' (Def...
[ "def", "kfactor", "(", "R", ",", "k", "=", "2", ",", "algorithm", "=", "'COBYLA'", ")", ":", "# subfunctions", "def", "corradjusteigen", "(", "C", ")", ":", "\"\"\"Reset negative diagonal elements 'D' to +1e-308\n This trick ensures that C semipositive definite.\...
29.2
0.000237
def _is_txn_to_replay(self, txn_id, possible_successor, already_seen): """Decide if possible_successor should be replayed. Args: txn_id (str): Id of txn in failed batch. possible_successor (str): Id of txn to possibly replay. already_seen (list): A list of possible_s...
[ "def", "_is_txn_to_replay", "(", "self", ",", "txn_id", ",", "possible_successor", ",", "already_seen", ")", ":", "is_successor", "=", "self", ".", "_is_predecessor_of_possible_successor", "(", "txn_id", ",", "possible_successor", ")", "in_different_batch", "=", "not"...
40.333333
0.002307
def list_commands(self, ctx): """Override for showing commands in particular order""" commands = super(LegitGroup, self).list_commands(ctx) return [cmd for cmd in order_manually(commands)]
[ "def", "list_commands", "(", "self", ",", "ctx", ")", ":", "commands", "=", "super", "(", "LegitGroup", ",", "self", ")", ".", "list_commands", "(", "ctx", ")", "return", "[", "cmd", "for", "cmd", "in", "order_manually", "(", "commands", ")", "]" ]
52.25
0.009434
def get_sphinx_ref(self, url, label=None): """ Get an internal sphinx cross reference corresponding to `url` into the online docs, associated with a link with label `label` (if not None). """ # Raise an exception if the initial part of url does not match # the ba...
[ "def", "get_sphinx_ref", "(", "self", ",", "url", ",", "label", "=", "None", ")", ":", "# Raise an exception if the initial part of url does not match", "# the base url for this object", "n", "=", "len", "(", "self", ".", "baseurl", ")", "if", "url", "[", "0", ":"...
38.382353
0.001495
def setDebug(string): """Set the DEBUG string. This controls the log output.""" global _DEBUG global _ENV_VAR_NAME global _categories _DEBUG = string debug('log', "%s set to %s" % (_ENV_VAR_NAME, _DEBUG)) # reparse all already registered category levels for category in _categories: ...
[ "def", "setDebug", "(", "string", ")", ":", "global", "_DEBUG", "global", "_ENV_VAR_NAME", "global", "_categories", "_DEBUG", "=", "string", "debug", "(", "'log'", ",", "\"%s set to %s\"", "%", "(", "_ENV_VAR_NAME", ",", "_DEBUG", ")", ")", "# reparse all alread...
28.416667
0.002841
def _oauth10a_signature( consumer_token: Dict[str, Any], method: str, url: str, parameters: Dict[str, Any] = {}, token: Dict[str, Any] = None, ) -> bytes: """Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request. See http://oauth.net/core/1.0a/#signing_process """ part...
[ "def", "_oauth10a_signature", "(", "consumer_token", ":", "Dict", "[", "str", ",", "Any", "]", ",", "method", ":", "str", ",", "url", ":", "str", ",", "parameters", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", ",", "token", ":", "Dict",...
32.636364
0.003607
def checkAuthentication(): """ The request will have a parameter 'key' if it came from the command line client, or have a session key of 'key' if it's the browser. If the token is not found, start the login process. If there is no oidcClient, we are running naked and we don't check. If we're be...
[ "def", "checkAuthentication", "(", ")", ":", "if", "app", ".", "oidcClient", "is", "None", ":", "return", "if", "flask", ".", "request", ".", "endpoint", "==", "'oidcCallback'", ":", "return", "key", "=", "flask", ".", "session", ".", "get", "(", "'key'"...
41.56
0.000941
def _get_all_taskpaper_files( self, workspaceRoot): """*get a list of all the taskpaper filepaths in the workspace (excluding the sync directory)* **Key Arguments:** - ``workspaceRoot`` -- path to the root folder of a workspace containing taskpaper files **R...
[ "def", "_get_all_taskpaper_files", "(", "self", ",", "workspaceRoot", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_get_all_taskpaper_files`` method'", ")", "theseFiles", "=", "recursive_directory_listing", "(", "log", "=", "self", ".", "log", ",...
37.92
0.005144
def get(**kwargs): ''' Return system rc configuration variables CLI Example: .. code-block:: bash salt '*' sysrc.get includeDefaults=True ''' cmd = 'sysrc -v' if 'file' in kwargs: cmd += ' -f '+kwargs['file'] if 'jail' in kwargs: cmd += ' -j '+kwargs['jail...
[ "def", "get", "(", "*", "*", "kwargs", ")", ":", "cmd", "=", "'sysrc -v'", "if", "'file'", "in", "kwargs", ":", "cmd", "+=", "' -f '", "+", "kwargs", "[", "'file'", "]", "if", "'jail'", "in", "kwargs", ":", "cmd", "+=", "' -j '", "+", "kwargs", "["...
22.6
0.000943
def get(self, key, ttl=0, quiet=None, replica=False, no_format=False): """Obtain an object stored in Couchbase by given key. :param string key: The key to fetch. The type of key is the same as mentioned in :meth:`upsert` :param int ttl: If specified, indicates that the key's expira...
[ "def", "get", "(", "self", ",", "key", ",", "ttl", "=", "0", ",", "quiet", "=", "None", ",", "replica", "=", "False", ",", "no_format", "=", "False", ")", ":", "return", "_Base", ".", "get", "(", "self", ",", "key", ",", "ttl", "=", "ttl", ",",...
39.577465
0.000694
def subtract_params(param_list_left, param_list_right): """Subtract two lists of parameters :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res.a...
[ "def", "subtract_params", "(", "param_list_left", ",", "param_list_right", ")", ":", "res", "=", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "param_list_left", ",", "param_list_right", ")", ":", "res", ".", "append", "(", "x", "-", "y", ")", "ret...
30.636364
0.002882
def _on_scan_request(self, sequence, topic, message): """Process a request for scanning information Args: sequence (int:) The sequence number of the packet received topic (string): The topic this message was received on message_type (string): The type of the packet r...
[ "def", "_on_scan_request", "(", "self", ",", "sequence", ",", "topic", ",", "message", ")", ":", "if", "messages", ".", "ProbeCommand", ".", "matches", "(", "message", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Received probe message on topic %s, ...
47.8
0.00684
def _disable(name, started, result=True, skip_verify=False, **kwargs): ''' Disable the service ''' ret = {} if not skip_verify: # is service available? try: if not _available(name, ret): ret['result'] = True return ret except Comma...
[ "def", "_disable", "(", "name", ",", "started", ",", "result", "=", "True", ",", "skip_verify", "=", "False", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "if", "not", "skip_verify", ":", "# is service available?", "try", ":", "if", "not", ...
40.663158
0.000505
def password_change(self, wallet, password): """ Changes the password for **wallet** to **password** .. enable_control required :param wallet: Wallet to change password for :type wallet: str :param password: Password to set :type password: str :raises:...
[ "def", "password_change", "(", "self", ",", "wallet", ",", "password", ")", ":", "wallet", "=", "self", ".", "_process_value", "(", "wallet", ",", "'wallet'", ")", "payload", "=", "{", "\"wallet\"", ":", "wallet", ",", "\"password\"", ":", "password", "}",...
26.071429
0.003963
def int_global_to_local_start(self, index, axis=0): """ Calculate local index from global index from start_index :param index: global index as integer :param axis: current axis to process :return: """ if index >= self.__mask[axis].stop-self.__halos[1][axis]: ...
[ "def", "int_global_to_local_start", "(", "self", ",", "index", ",", "axis", "=", "0", ")", ":", "if", "index", ">=", "self", ".", "__mask", "[", "axis", "]", ".", "stop", "-", "self", ".", "__halos", "[", "1", "]", "[", "axis", "]", ":", "return", ...
30.714286
0.004515
def post_migrate(cls, sender=None, **kwargs): """ Iterate over fake_proxy_models and add contenttypes and permissions for missing proxy models, if this has not been done by Django yet """ ContentType = apps.get_model('contenttypes', 'ContentType') for model_name, proxy_m...
[ "def", "post_migrate", "(", "cls", ",", "sender", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ContentType", "=", "apps", ".", "get_model", "(", "'contenttypes'", ",", "'ContentType'", ")", "for", "model_name", ",", "proxy_model", "in", "sender", ".", ...
48.636364
0.007339
def encode_to_json(history_list): """ Encodes this MarketHistoryList instance to a JSON string. :param MarketHistoryList history_list: The history instance to serialize. :rtype: str """ rowsets = [] for items_in_region_list in history_list._history.values(): region_id = items_in_reg...
[ "def", "encode_to_json", "(", "history_list", ")", ":", "rowsets", "=", "[", "]", "for", "items_in_region_list", "in", "history_list", ".", "_history", ".", "values", "(", ")", ":", "region_id", "=", "items_in_region_list", ".", "region_id", "type_id", "=", "i...
32.5625
0.00559
def transit_decrypt_data(self, name, ciphertext, context=None, nonce=None, batch_input=None, mount_point='transit'): """POST /<mount_point>/decrypt/<name> :param name: :type name: :param ciphertext: :type ciphertext: :param context: :type context: :param ...
[ "def", "transit_decrypt_data", "(", "self", ",", "name", ",", "ciphertext", ",", "context", "=", "None", ",", "nonce", "=", "None", ",", "batch_input", "=", "None", ",", "mount_point", "=", "'transit'", ")", ":", "url", "=", "'/v1/{0}/decrypt/{1}'", ".", "...
29.433333
0.003289
def exists(name, path=None): ''' Returns whether the named container exists. path path to the container parent directory (default: /var/lib/lxc) .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' lxc.exists name ''' _exists = name in ls_(path...
[ "def", "exists", "(", "name", ",", "path", "=", "None", ")", ":", "_exists", "=", "name", "in", "ls_", "(", "path", "=", "path", ")", "# container may be just created but we did cached earlier the", "# lxc-ls results", "if", "not", "_exists", ":", "_exists", "="...
21.043478
0.001976
def Replace(self, resource, path, type, id, initial_headers, options=None): """Replaces a Azure Cosmos resource and returns it. :param dict resource: :param str path: :param str type: :param str id: :param dict initial_headers: :param dict options: Th...
[ "def", "Replace", "(", "self", ",", "resource", ",", "path", ",", "type", ",", "id", ",", "initial_headers", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "initial_headers", "=", "initial_headers", ...
37.657895
0.003406
def get_available_name(self, name): """Returns a filename that's free on the target storage system, and available for new content to be written to. Found at http://djangosnippets.org/snippets/976/ This file storage solves overwrite on upload problem. Another proposed solution w...
[ "def", "get_available_name", "(", "self", ",", "name", ")", ":", "# If the filename already exists, remove it as if it was a true file system", "if", "self", ".", "exists", "(", "name", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "se...
42.681818
0.003125
def _deserialize_primitive(data, klass): """ Deserializes to primitive type. :param data: data to deserialize. :param klass: class literal. :return: int, long, float, str, bool. :rtype: int | long | float | str | bool """ try: value = klass(data) except UnicodeEncodeError: ...
[ "def", "_deserialize_primitive", "(", "data", ",", "klass", ")", ":", "try", ":", "value", "=", "klass", "(", "data", ")", "except", "UnicodeEncodeError", ":", "value", "=", "unicode", "(", "data", ")", "except", "TypeError", ":", "value", "=", "data", "...
23.117647
0.002445
def modularity_louvain_dir(W, gamma=1, hierarchy=False, seed=None): ''' The optimal community structure is a subdivision of the network into nonoverlapping groups of nodes in a way that maximizes the number of within-group edges, and minimizes the number of between-group edges. The modularity is a s...
[ "def", "modularity_louvain_dir", "(", "W", ",", "gamma", "=", "1", ",", "hierarchy", "=", "False", ",", "seed", "=", "None", ")", ":", "rng", "=", "get_rng", "(", "seed", ")", "n", "=", "len", "(", "W", ")", "# number of nodes", "s", "=", "np", "."...
37.507813
0.000812