text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def xpathNextDescendantOrSelf(self, cur): """Traversal function for the "descendant-or-self" direction the descendant-or-self axis contains the context node and the descendants of the context node in document order; thus the context node is the first node on the axis, and the ...
[ "def", "xpathNextDescendantOrSelf", "(", "self", ",", "cur", ")", ":", "if", "cur", "is", "None", ":", "cur__o", "=", "None", "else", ":", "cur__o", "=", "cur", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlXPathNextDescendantOrSelf", "(", "self", ".", "...
51.153846
16.923077
def y_grid(self, grid=None): """The vertical lines that run accross the chart from the y-ticks. If a boolean value is given, these gridlines will be turned on or off. Otherwise, the method will return their current state. :param bool grid: Turns the gridlines on or off. :rtype:...
[ "def", "y_grid", "(", "self", ",", "grid", "=", "None", ")", ":", "if", "grid", "is", "None", ":", "return", "self", ".", "_y_grid", "else", ":", "if", "not", "isinstance", "(", "grid", ",", "bool", ")", ":", "raise", "TypeError", "(", "\"grid must b...
35.866667
20.2
def dict_hist(item_list, weight_list=None, ordered=False, labels=None): r""" Builds a histogram of items in item_list Args: item_list (list): list with hashable items (usually containing duplicates) Returns: dict : dictionary where the keys are items in item_list, and the values ...
[ "def", "dict_hist", "(", "item_list", ",", "weight_list", "=", "None", ",", "ordered", "=", "False", ",", "labels", "=", "None", ")", ":", "if", "labels", "is", "None", ":", "# hist_ = defaultdict(lambda: 0)", "hist_", "=", "defaultdict", "(", "int", ")", ...
33.045455
18.659091
def _chorder(self): """Add <interleave> if child order is arbitrary.""" if (self.interleave and len([ c for c in self.children if ":" not in c.name ]) > 1): return "<interleave>%s</interleave>" return "%s"
[ "def", "_chorder", "(", "self", ")", ":", "if", "(", "self", ".", "interleave", "and", "len", "(", "[", "c", "for", "c", "in", "self", ".", "children", "if", "\":\"", "not", "in", "c", ".", "name", "]", ")", ">", "1", ")", ":", "return", "\"<in...
41.333333
15.166667
def get_limits_for_pool(self, pool): """ meterer.get_limits_for_pool(pool) -> dict Returns the limits for the given pool. If the pool does not have limits set, {} is returned. The resulting dict has the following format. Each item is optional and indicates no limit for ...
[ "def", "get_limits_for_pool", "(", "self", ",", "pool", ")", ":", "pool_limits", "=", "self", ".", "cache", ".", "get", "(", "\"LIMIT:%s\"", "%", "pool", ")", "if", "pool_limits", "is", "None", ":", "return", "{", "}", "return", "json_loads", "(", "pool_...
28.727273
19.363636
def _update(self): ''' Given degree, minute, and second information, clean up the variables and make them consistent (for example, if minutes > 60, add extra to degrees, or if degrees is a decimal, add extra to minutes). ''' self.decimal_degree = self._calc_decimaldegree(...
[ "def", "_update", "(", "self", ")", ":", "self", ".", "decimal_degree", "=", "self", ".", "_calc_decimaldegree", "(", "self", ".", "degree", ",", "self", ".", "minute", ",", "self", ".", "second", ")", "self", ".", "degree", ",", "self", ".", "minute",...
58.25
38.25
def create_serv_obj(self, tenant_id): """Creates and stores the service object associated with a tenant. """ self.service_attr[tenant_id] = ServiceIpSegTenantMap() self.store_tenant_obj(tenant_id, self.service_attr[tenant_id])
[ "def", "create_serv_obj", "(", "self", ",", "tenant_id", ")", ":", "self", ".", "service_attr", "[", "tenant_id", "]", "=", "ServiceIpSegTenantMap", "(", ")", "self", ".", "store_tenant_obj", "(", "tenant_id", ",", "self", ".", "service_attr", "[", "tenant_id"...
61.75
13.75
def simulate(self, ts_length, init=None, num_reps=None, random_state=None): """ Simulate time series of state transitions, where the states are annotated with their values (if `state_values` is not None). Parameters ---------- ts_length : scalar(int) Length o...
[ "def", "simulate", "(", "self", ",", "ts_length", ",", "init", "=", "None", ",", "num_reps", "=", "None", ",", "random_state", "=", "None", ")", ":", "if", "init", "is", "not", "None", ":", "init_idx", "=", "self", ".", "get_index", "(", "init", ")",...
37.173913
22.826087
def is_up_url(url, allow_redirects=False, timeout=5): r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "ht...
[ "def", "is_up_url", "(", "url", ",", "allow_redirects", "=", "False", ",", "timeout", "=", "5", ")", ":", "if", "not", "isinstance", "(", "url", ",", "basestring", ")", "or", "'.'", "not", "in", "url", ":", "return", "False", "normalized_url", "=", "pr...
36.875
20.8
def format_command( command_args, # type: List[str] command_output, # type: str ): # type: (...) -> str """ Format command information for logging. """ text = 'Command arguments: {}\n'.format(command_args) if not command_output: text += 'Command output: None' elif logger.g...
[ "def", "format_command", "(", "command_args", ",", "# type: List[str]", "command_output", ",", "# type: str", ")", ":", "# type: (...) -> str", "text", "=", "'Command arguments: {}\\n'", ".", "format", "(", "command_args", ")", "if", "not", "command_output", ":", "tex...
27.826087
15.304348
def model(self, inputs, mode='train'): """Build a simple convnet (BN before ReLU). Args: inputs: a tensor of size [batch_size, height, width, channels] mode: string in ['train', 'test'] Returns: the last op containing the predictions Note: ...
[ "def", "model", "(", "self", ",", "inputs", ",", "mode", "=", "'train'", ")", ":", "# Extract features", "training", "=", "(", "mode", "==", "'train'", ")", "with", "tf", ".", "variable_scope", "(", "'conv1'", ")", "as", "scope", ":", "conv", "=", "tf"...
52.55102
28.714286
def plfit_lsq(x,y): """ Returns A and B in y=Ax^B http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html """ n = len(x) btop = n * (log(x)*log(y)).sum() - (log(x)).sum()*(log(y)).sum() bbottom = n*(log(x)**2).sum() - (log(x).sum())**2 b = btop / bbottom a = ( log(y).sum() - b ...
[ "def", "plfit_lsq", "(", "x", ",", "y", ")", ":", "n", "=", "len", "(", "x", ")", "btop", "=", "n", "*", "(", "log", "(", "x", ")", "*", "log", "(", "y", ")", ")", ".", "sum", "(", ")", "-", "(", "log", "(", "x", ")", ")", ".", "sum",...
27.615385
18.538462
def _get_encrypted_masterpassword(self): """ Obtain the encrypted masterkey .. note:: The encrypted masterkey is checksummed, so that we can figure out that a provided password is correct or not. The checksum is only 4 bytes long! """ if not self.unlo...
[ "def", "_get_encrypted_masterpassword", "(", "self", ")", ":", "if", "not", "self", ".", "unlocked", "(", ")", ":", "raise", "WalletLocked", "aes", "=", "AESCipher", "(", "self", ".", "password", ")", "return", "\"{}${}\"", ".", "format", "(", "self", ".",...
38.846154
16.615385
def echo_event(data): """Echo a json dump of an object using click""" return click.echo(json.dumps(data, sort_keys=True, indent=2))
[ "def", "echo_event", "(", "data", ")", ":", "return", "click", ".", "echo", "(", "json", ".", "dumps", "(", "data", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ")", ")" ]
45.666667
14.666667
def create_refobj(self, ): """Create and return a new reftrack node :returns: the new reftrack node :rtype: str :raises: None """ n = cmds.createNode("jb_reftrack") cmds.lockNode(n, lock=True) return n
[ "def", "create_refobj", "(", "self", ",", ")", ":", "n", "=", "cmds", ".", "createNode", "(", "\"jb_reftrack\"", ")", "cmds", ".", "lockNode", "(", "n", ",", "lock", "=", "True", ")", "return", "n" ]
25.7
12.6
def _extract_actions_unique_topics(self, movement_counts, max_movements, cluster_topology, max_movement_size): """Extract actions limiting to given max value such that the resultant has the minimum possible number of duplicate topics. Algorithm: 1. Group actions by by topic-nam...
[ "def", "_extract_actions_unique_topics", "(", "self", ",", "movement_counts", ",", "max_movements", ",", "cluster_topology", ",", "max_movement_size", ")", ":", "# Group actions by topic", "topic_actions", "=", "defaultdict", "(", "list", ")", "for", "t_p", ",", "repl...
54.47619
24.738095
def Emulation_setCPUThrottlingRate(self, rate): """ Function path: Emulation.setCPUThrottlingRate Domain: Emulation Method name: setCPUThrottlingRate WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'rate' (type: number) -> Throttling rate as a slowdown fac...
[ "def", "Emulation_setCPUThrottlingRate", "(", "self", ",", "rate", ")", ":", "assert", "isinstance", "(", "rate", ",", "(", "float", ",", "int", ")", ")", ",", "\"Argument 'rate' must be of type '['float', 'int']'. Received type: '%s'\"", "%", "type", "(", "rate", "...
33
22.619048
def fetch_items(self, category, **kwargs): """Fetch the pages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] reviews_api = kwargs['reviews_api'] mediawi...
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "reviews_api", "=", "kwargs", "[", "'reviews_api'", "]", "mediawiki_version", "=", "self", ".", "client", ".", "get_...
36.115385
19.615385
def actuator_off(self, service_location_id, actuator_id, duration=None): """ Turn actuator off Parameters ---------- service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuato...
[ "def", "actuator_off", "(", "self", ",", "service_location_id", ",", "actuator_id", ",", "duration", "=", "None", ")", ":", "return", "self", ".", "_actuator_on_off", "(", "on_off", "=", "'off'", ",", "service_location_id", "=", "service_location_id", ",", "actu...
32.65
19.25
def get_name(self): """Return client name""" if self.given_name is None: # Name according to host if self.hostname is None: name = _("Console") else: name = self.hostname # Adding id to name client_id = ...
[ "def", "get_name", "(", "self", ")", ":", "if", "self", ".", "given_name", "is", "None", ":", "# Name according to host\r", "if", "self", ".", "hostname", "is", "None", ":", "name", "=", "_", "(", "\"Console\"", ")", "else", ":", "name", "=", "self", "...
40.235294
13.941176
def sun_ra_dec(utc_time): """Right ascension and declination of the sun at *utc_time*. """ jdate = jdays2000(utc_time) / 36525.0 eps = np.deg2rad(23.0 + 26.0 / 60.0 + 21.448 / 3600.0 - (46.8150 * jdate + 0.00059 * jdate * jdate - 0.001813 * jdate * jdate * jdat...
[ "def", "sun_ra_dec", "(", "utc_time", ")", ":", "jdate", "=", "jdays2000", "(", "utc_time", ")", "/", "36525.0", "eps", "=", "np", ".", "deg2rad", "(", "23.0", "+", "26.0", "/", "60.0", "+", "21.448", "/", "3600.0", "-", "(", "46.8150", "*", "jdate",...
39.529412
10.058824
def is_valid_short_number_for_region(short_numobj, region_dialing_from): """Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. Arguments: short_numobj -- th...
[ "def", "is_valid_short_number_for_region", "(", "short_numobj", ",", "region_dialing_from", ")", ":", "if", "not", "_region_dialing_from_matches_number", "(", "short_numobj", ",", "region_dialing_from", ")", ":", "return", "False", "metadata", "=", "PhoneMetadata", ".", ...
46.68
24.8
def get_tag_users(self, tag_id, first_user_id=None): """ 获取标签下粉丝列表 :param tag_id: 标签 ID :param first_user_id: 可选。第一个拉取的 OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包 """ data = { 'tagid': tag_id, } if first_user_id: data['next_op...
[ "def", "get_tag_users", "(", "self", ",", "tag_id", ",", "first_user_id", "=", "None", ")", ":", "data", "=", "{", "'tagid'", ":", "tag_id", ",", "}", "if", "first_user_id", ":", "data", "[", "'next_openid'", "]", "=", "first_user_id", "return", "self", ...
24.294118
16.529412
def resample_nn_1d(a, centers): """Return one-dimensional nearest-neighbor indexes based on user-specified centers. Parameters ---------- a : array-like 1-dimensional array of numeric values from which to extract indexes of nearest-neighbors centers : array-like 1-dimensiona...
[ "def", "resample_nn_1d", "(", "a", ",", "centers", ")", ":", "ix", "=", "[", "]", "for", "center", "in", "centers", ":", "index", "=", "(", "np", ".", "abs", "(", "a", "-", "center", ")", ")", ".", "argmin", "(", ")", "if", "index", "not", "in"...
29.045455
22.227273
def insert_many(self, it): """Inserts a collection of objects into the table.""" unique_indexes = self._uniqueIndexes # [ind for ind in self._indexes.values() if ind.is_unique] NO_SUCH_ATTR = object() new_objs = list(it) if unique_indexes: for ind in unique_indexes: ...
[ "def", "insert_many", "(", "self", ",", "it", ")", ":", "unique_indexes", "=", "self", ".", "_uniqueIndexes", "# [ind for ind in self._indexes.values() if ind.is_unique]", "NO_SUCH_ATTR", "=", "object", "(", ")", "new_objs", "=", "list", "(", "it", ")", "if", "uni...
51.888889
24.148148
def get_hierarchy_traversal_session_for_hierarchy(self, hierarchy_id, proxy): """Gets the ``OsidSession`` associated with the hierarchy traversal service for the given hierarchy. arg: hierarchy_id (osid.id.Id): the ``Id`` of the hierarchy arg: proxy (osid.proxy.Proxy): a proxy ret...
[ "def", "get_hierarchy_traversal_session_for_hierarchy", "(", "self", ",", "hierarchy_id", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_hierarchy_traversal", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "##", "# Also include check ...
51.458333
21.916667
def parse_exponent(source, start): """returns end of exponential, raises SyntaxError if failed""" if not source[start] in {'e', 'E'}: if source[start] in IDENTIFIER_PART: raise SyntaxError('Invalid number literal!') return start start += 1 if source[start] in {'-', '+'}: ...
[ "def", "parse_exponent", "(", "source", ",", "start", ")", ":", "if", "not", "source", "[", "start", "]", "in", "{", "'e'", ",", "'E'", "}", ":", "if", "source", "[", "start", "]", "in", "IDENTIFIER_PART", ":", "raise", "SyntaxError", "(", "'Invalid nu...
34.058824
13.352941
def container_unfreeze(name, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Unfreeze a container name : Name of the container to unfreeze remote_addr : An URL to a remote Server, you also have to give cert and key if you provide remote_addr...
[ "def", "container_unfreeze", "(", "name", ",", "remote_addr", "=", "None", ",", "cert", "=", "None", ",", "key", "=", "None", ",", "verify_cert", "=", "True", ")", ":", "container", "=", "container_get", "(", "name", ",", "remote_addr", ",", "cert", ",",...
25.736842
21.736842
def get_hosting_device_driver(self, context, id): """Returns device driver for hosting device template with <id>.""" if id is None: return try: return self._hosting_device_drivers[id] except KeyError: try: template = self._get_hosting_d...
[ "def", "get_hosting_device_driver", "(", "self", ",", "context", ",", "id", ")", ":", "if", "id", "is", "None", ":", "return", "try", ":", "return", "self", ".", "_hosting_device_drivers", "[", "id", "]", "except", "KeyError", ":", "try", ":", "template", ...
48
20.133333
def next(self): """ Return the next row of a query result set, respecting if cursor was closed. """ if self.rows is None: raise ProgrammingError( "No result available. " + "execute() or executemany() must be called first." )...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "rows", "is", "None", ":", "raise", "ProgrammingError", "(", "\"No result available. \"", "+", "\"execute() or executemany() must be called first.\"", ")", "elif", "not", "self", ".", "_closed", ":", "return...
31.357143
14.928571
def read_line(csv_contents, options, prop_indices, mol, ensemble_list=None): """ read csv line """ if not ensemble_list: score_field = options.score_field status_field = options.status_field active_label = options.active_label decoy_label = options.decoy_label # do the active/decoy la...
[ "def", "read_line", "(", "csv_contents", ",", "options", ",", "prop_indices", ",", "mol", ",", "ensemble_list", "=", "None", ")", ":", "if", "not", "ensemble_list", ":", "score_field", "=", "options", ".", "score_field", "status_field", "=", "options", ".", ...
32.916667
17.9375
def create_hit(self, hit_type=None, question=None, lifetime=datetime.timedelta(days=7), max_assignments=1, title=None, description=None, keywords=None, reward=None, duration=datetime.timedelta(days=7), approval_delay=None, a...
[ "def", "create_hit", "(", "self", ",", "hit_type", "=", "None", ",", "question", "=", "None", ",", "lifetime", "=", "datetime", ".", "timedelta", "(", "days", "=", "7", ")", ",", "max_assignments", "=", "1", ",", "title", "=", "None", ",", "description...
40.233766
18.935065
def queue(self, name, value, quality=None, timestamp=None, attributes=None): """ To reduce network traffic, you can buffer datapoints and then flush() anything in the queue. :param name: the name / label / tag for sensor data :param value: the sensor reading or valu...
[ "def", "queue", "(", "self", ",", "name", ",", "value", ",", "quality", "=", "None", ",", "timestamp", "=", "None", ",", "attributes", "=", "None", ")", ":", "# Get timestamp first in case delay opening websocket connection", "# and it must have millisecond accuracy", ...
39
23.25974
def _Main(self): """The main loop.""" # We need a resolver context per process to prevent multi processing # issues with file objects stored in images. resolver_context = context.Context() for credential_configuration in self._processing_configuration.credentials: resolver.Resolver.key_chain....
[ "def", "_Main", "(", "self", ")", ":", "# We need a resolver context per process to prevent multi processing", "# issues with file objects stored in images.", "resolver_context", "=", "context", ".", "Context", "(", ")", "for", "credential_configuration", "in", "self", ".", "...
35.814159
22.663717
def set_conn(self, **kwargs): """ takes a connection and creates the connection """ # log = logging.getLogger("%s.%s" % (self.log, inspect.stack()[0][3])) log.setLevel(kwargs.get('log_level',self.log_level)) conn_name = kwargs.get("name") if not conn_name: raise Nam...
[ "def", "set_conn", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# log = logging.getLogger(\"%s.%s\" % (self.log, inspect.stack()[0][3]))", "log", ".", "setLevel", "(", "kwargs", ".", "get", "(", "'log_level'", ",", "self", ".", "log_level", ")", ")", "conn_nam...
44.481481
19.851852
def print_build_help(build_path, default_build_path): """ Print help text after configuration step is done. """ print(' configure step is done') print(' now you need to compile the sources:') if (build_path == default_build_path): print(' $ cd build') else: print(' $ ...
[ "def", "print_build_help", "(", "build_path", ",", "default_build_path", ")", ":", "print", "(", "' configure step is done'", ")", "print", "(", "' now you need to compile the sources:'", ")", "if", "(", "build_path", "==", "default_build_path", ")", ":", "print", ...
31.909091
9.363636
async def _playnow(self, ctx, *, query: str): """ Plays immediately a song. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.queue and not player.is_playing: return await ctx.invoke(self._play, query=query) query = query.strip('<>') i...
[ "async", "def", "_playnow", "(", "self", ",", "ctx", ",", "*", ",", "query", ":", "str", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "if", "not", "player", ...
33.16
20.52
def _sin_to_angle(result, deriv, side=1): """Convert a sine and its derivatives to an angle and its derivatives""" v = np.arcsin(np.clip(result[0], -1, 1)) sign = side if sign == -1: if v < 0: offset = -np.pi else: offset = np.pi else: offset = 0.0 ...
[ "def", "_sin_to_angle", "(", "result", ",", "deriv", ",", "side", "=", "1", ")", ":", "v", "=", "np", ".", "arcsin", "(", "np", ".", "clip", "(", "result", "[", "0", "]", ",", "-", "1", ",", "1", ")", ")", "sign", "=", "side", "if", "sign", ...
30
15.6
def from_dict(data, ctx): """ Instantiate a new ClientConfigureTransaction from a dict (generally from loading a JSON response). The data used to instantiate the ClientConfigureTransaction is a shallow copy of the dict passed in, with any complex child types instantiated appropri...
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "if", "data", ".", "get", "(", "'marginRate'", ")", "is", "not", "None", ":", "data", "[", "'marginRate'", "]", "=", "ctx", ".", "convert_decimal_numbe...
35.25
21.125
def f_lock_parameters(self): """Locks all non-empty parameters""" for par in self._parameters.values(): if not par.f_is_empty(): par.f_lock()
[ "def", "f_lock_parameters", "(", "self", ")", ":", "for", "par", "in", "self", ".", "_parameters", ".", "values", "(", ")", ":", "if", "not", "par", ".", "f_is_empty", "(", ")", ":", "par", ".", "f_lock", "(", ")" ]
36.2
6.6
def fit(self, df, duration_col, event_col=None, weights_col=None, show_progress=False): """ Parameters ---------- Fit the Aalen Additive model to a dataset. Parameters ---------- df: DataFrame a Pandas DataFrame with necessary columns `duration_col` a...
[ "def", "fit", "(", "self", ",", "df", ",", "duration_col", ",", "event_col", "=", "None", ",", "weights_col", "=", "None", ",", "show_progress", "=", "False", ")", ":", "self", ".", "_time_fit_was_called", "=", "datetime", ".", "utcnow", "(", ")", ".", ...
36.526316
23.936842
def expand(fn, col, inputtype=pd.DataFrame): """ Wrap a function applying to a single column to make a function applying to a multi-dimensional dataframe or ndarray Parameters ---------- fn : function Function that applies to a series or vector. col : str or int Index of co...
[ "def", "expand", "(", "fn", ",", "col", ",", "inputtype", "=", "pd", ".", "DataFrame", ")", ":", "if", "inputtype", "==", "pd", ".", "DataFrame", ":", "if", "isinstance", "(", "col", ",", "int", ")", ":", "def", "_wrapper", "(", "*", "args", ",", ...
32.638889
17.583333
def _CaptureExpression(self, frame, expression): """Evalutes the expression and captures it into a Variable object. Args: frame: evaluation context. expression: watched expression to compile and evaluate. Returns: Variable object (which will have error status if the expression fails ...
[ "def", "_CaptureExpression", "(", "self", ",", "frame", ",", "expression", ")", ":", "rc", ",", "value", "=", "_EvaluateExpression", "(", "frame", ",", "expression", ")", "if", "not", "rc", ":", "return", "{", "'name'", ":", "expression", ",", "'status'", ...
33.941176
21.647059
def expandvars(text, environ=None): """Expand shell variables of form $var and ${var}. Unknown variables are left unchanged. Args: text (str): String to expand. environ (dict): Environ dict to use for expansions, defaults to os.environ. Returns: The expanded string...
[ "def", "expandvars", "(", "text", ",", "environ", "=", "None", ")", ":", "if", "'$'", "not", "in", "text", ":", "return", "text", "i", "=", "0", "if", "environ", "is", "None", ":", "environ", "=", "os", ".", "environ", "while", "True", ":", "m", ...
23.138889
19.166667
def to_output_script(address): ''' str -> bytes There's probably a better way to do this ''' parsed = parse(address) parsed_hash = b'' try: if (parsed.find(riemann.network.P2WPKH_PREFIX) == 0 and len(parsed) == 22): return parsed except TypeError: ...
[ "def", "to_output_script", "(", "address", ")", ":", "parsed", "=", "parse", "(", "address", ")", "parsed_hash", "=", "b''", "try", ":", "if", "(", "parsed", ".", "find", "(", "riemann", ".", "network", ".", "P2WPKH_PREFIX", ")", "==", "0", "and", "len...
33.894737
23.157895
def get(self, action, version=None): """Get the method class handing the given action and version.""" by_version = self._by_action[action] if version in by_version: return by_version[version] else: return by_version[None]
[ "def", "get", "(", "self", ",", "action", ",", "version", "=", "None", ")", ":", "by_version", "=", "self", ".", "_by_action", "[", "action", "]", "if", "version", "in", "by_version", ":", "return", "by_version", "[", "version", "]", "else", ":", "retu...
38.714286
7
def delta_stoichiometry( reactants, products ): """ Calculate the change in stoichiometry for reactants --> products. Args: reactants (list(vasppy.Calculation): A list of vasppy.Calculation objects. The initial state. products (list(vasppy.Calculation): A list of vasppy.Calculation objects...
[ "def", "delta_stoichiometry", "(", "reactants", ",", "products", ")", ":", "totals", "=", "Counter", "(", ")", "for", "r", "in", "reactants", ":", "totals", ".", "update", "(", "(", "r", "*", "-", "1.0", ")", ".", "stoichiometry", ")", "for", "p", "i...
32.238095
21.238095
def create(self, **kwargs): """Create a new instance of this resource type. As a general rule, the identifier should have been provided, but in some subclasses the identifier is server-side-generated. Those classes have to overload this method to deal with that scenario. """ ...
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "method", "=", "'post'", "if", "self", ".", "primary_key", "in", "kwargs", ":", "del", "kwargs", "[", "self", ".", "primary_key", "]", "data", "=", "self", ".", "_generate_...
41.692308
16.307692
def signed_to_float(hex: str) -> float: """Convert signed hexadecimal to floating value.""" if int(hex, 16) & 0x8000: return -(int(hex, 16) & 0x7FFF) / 10 else: return int(hex, 16) / 10
[ "def", "signed_to_float", "(", "hex", ":", "str", ")", "->", "float", ":", "if", "int", "(", "hex", ",", "16", ")", "&", "0x8000", ":", "return", "-", "(", "int", "(", "hex", ",", "16", ")", "&", "0x7FFF", ")", "/", "10", "else", ":", "return",...
34.666667
9.166667
def merge_in_place(self, others): """ Add the models present other predictors into the current predictor. Parameters ---------- others : list of Class1AffinityPredictor Other predictors to merge into the current predictor. Returns ------- lis...
[ "def", "merge_in_place", "(", "self", ",", "others", ")", ":", "new_model_names", "=", "[", "]", "for", "predictor", "in", "others", ":", "for", "model", "in", "predictor", ".", "class1_pan_allele_models", ":", "model_name", "=", "self", ".", "model_name", "...
43.16
19
def dlogpdf_df(self, f, y, Y_metadata=None): """ Evaluates the link function link(f) then computes the derivative of log likelihood using it Uses the Faa di Bruno's formula for the chain rule .. math:: \\frac{d\\log p(y|\\lambda(f))}{df} = \\frac{d\\log p(y|\\lambda(f))}{d\\...
[ "def", "dlogpdf_df", "(", "self", ",", "f", ",", "y", ",", "Y_metadata", "=", "None", ")", ":", "if", "isinstance", "(", "self", ".", "gp_link", ",", "link_functions", ".", "Identity", ")", ":", "return", "self", ".", "dlogpdf_dlink", "(", "f", ",", ...
44.695652
24.173913
def randomSplit(self, weights, seed=None): """ Randomly splits this RDD with the provided weights. :param weights: weights for splits, will be normalized if they don't sum to 1 :param seed: random seed :return: split RDDs in a list >>> rdd = sc.parallelize(range(500), 1...
[ "def", "randomSplit", "(", "self", ",", "weights", ",", "seed", "=", "None", ")", ":", "s", "=", "float", "(", "sum", "(", "weights", ")", ")", "cweights", "=", "[", "0.0", "]", "for", "w", "in", "weights", ":", "cweights", ".", "append", "(", "c...
35.04
16.56
def company(self, **kwargs): """ Search for companies by name. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. Returns: A dict respresentation of the JSON returned from the API. """ ...
[ "def", "company", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_path", "(", "'company'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_attrs_to_values", "(", "response",...
28.0625
17.3125
def config_string(self): """ See the class documentation. """ # Note: _write_to_conf is determined when the value is calculated. This # is a hidden function call due to property magic. val = self.str_value if not self._write_to_conf: return "" ...
[ "def", "config_string", "(", "self", ")", ":", "# Note: _write_to_conf is determined when the value is calculated. This", "# is a hidden function call due to property magic.", "val", "=", "self", ".", "str_value", "if", "not", "self", ".", "_write_to_conf", ":", "return", "\"...
36.416667
16.5
def check_hex_chain(chain): """Verify a merkle chain, with hashes hex encoded, to see if the Merkle root can be reproduced. """ return codecs.encode(check_chain([(codecs.decode(i[0], 'hex_codec'), i[1]) for i in chain]), 'hex_codec')
[ "def", "check_hex_chain", "(", "chain", ")", ":", "return", "codecs", ".", "encode", "(", "check_chain", "(", "[", "(", "codecs", ".", "decode", "(", "i", "[", "0", "]", ",", "'hex_codec'", ")", ",", "i", "[", "1", "]", ")", "for", "i", "in", "ch...
60.5
20.5
def create_position(self, params={}): """ Creates a position http://dev.wheniwork.com/#create-update-position """ url = "/2/positions/" body = params data = self._post_resource(url, body) return self.position_from_json(data["position"])
[ "def", "create_position", "(", "self", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"/2/positions/\"", "body", "=", "params", "data", "=", "self", ".", "_post_resource", "(", "url", ",", "body", ")", "return", "self", ".", "position_from_json", ...
26.545455
14.909091
def add_service_certificate(kwargs=None, conn=None, call=None): ''' .. versionadded:: 2015.8.0 Add a new service certificate CLI Example: .. code-block:: bash salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\ data='...CERT_DATA...' certificate_form...
[ "def", "add_service_certificate", "(", "kwargs", "=", "None", ",", "conn", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The add_service_certificate function must be called with -f or --f...
31.87234
27.106383
def connect_rds(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.rds.RDSConnectio...
[ "def", "connect_rds", "(", "aws_access_key_id", "=", "None", ",", "aws_secret_access_key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "boto", ".", "rds", "import", "RDSConnection", "return", "RDSConnection", "(", "aws_access_key_id", ",", "aws_secre...
35.923077
15.769231
def event_first_of(*events: _AbstractLinkable) -> Event: """ Waits until one of `events` is set. The event returned is /not/ cleared with any of the `events`, this value must not be reused if the clearing behavior is used. """ first_finished = Event() if not all(isinstance(e, _AbstractLinkable...
[ "def", "event_first_of", "(", "*", "events", ":", "_AbstractLinkable", ")", "->", "Event", ":", "first_finished", "=", "Event", "(", ")", "if", "not", "all", "(", "isinstance", "(", "e", ",", "_AbstractLinkable", ")", "for", "e", "in", "events", ")", ":"...
32.533333
21.6
def setup(cls, configuration=None, **kwargs): # type: (Optional['Configuration'], Any) -> None """ Set up the HDX configuration Args: configuration (Optional[Configuration]): Configuration instance. Defaults to setting one up from passed arguments. **kwargs: See ...
[ "def", "setup", "(", "cls", ",", "configuration", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (Optional['Configuration'], Any) -> None", "if", "configuration", "is", "None", ":", "cls", ".", "_configuration", "=", "Configuration", "(", "*", "*", "...
57.636364
34.060606
def is_name_expired( self, name, block_number ): """ Given a name and block number, determine if it is expired at that block. * names in revealed but not ready namespaces are never expired, unless the namespace itself is expired; * names in ready namespaces expire once max(ready_block, r...
[ "def", "is_name_expired", "(", "self", ",", "name", ",", "block_number", ")", ":", "cur", "=", "self", ".", "db", ".", "cursor", "(", ")", "return", "namedb_get_name", "(", "cur", ",", "name", ",", "block_number", ")", "is", "None" ]
49.090909
26.181818
def conflicting_events(self): """ conflicting_events() This will return a list of conflicting events. **Example**:: event = service.calendar().get_event(id='<event_id>') for conflict in event.conflicting_events(): print conflict.subject """ if not self.confli...
[ "def", "conflicting_events", "(", "self", ")", ":", "if", "not", "self", ".", "conflicting_event_ids", ":", "return", "[", "]", "body", "=", "soap_request", ".", "get_item", "(", "exchange_id", "=", "self", ".", "conflicting_event_ids", ",", "format", "=", "...
27.178571
25.321429
def rolling_max(self, window_start, window_end, min_observations=None): """ Calculate a new SArray of the maximum value of different subsets over this SArray. The subset that the maximum is calculated over is defined as an inclusive range relative to the position to each value i...
[ "def", "rolling_max", "(", "self", ",", "window_start", ",", "window_end", ",", "min_observations", "=", "None", ")", ":", "min_observations", "=", "self", ".", "__check_min_observations", "(", "min_observations", ")", "agg_op", "=", "'__builtin__max__'", "return", ...
29.535354
23.878788
def __yield_handlers(self, event_type): """ Yield all the handlers registered for the given event type. """ if event_type not in self.event_types: raise ValueError("%r not found in %r.event_types == %r" % (event_type, self, self.event_types)) # Search handler stack f...
[ "def", "__yield_handlers", "(", "self", ",", "event_type", ")", ":", "if", "event_type", "not", "in", "self", ".", "event_types", ":", "raise", "ValueError", "(", "\"%r not found in %r.event_types == %r\"", "%", "(", "event_type", ",", "self", ",", "self", ".", ...
38.866667
14.733333
def l(*members, meta=None) -> List: """Creates a new list from members.""" return List( # pylint: disable=abstract-class-instantiated plist(iterable=members), meta=meta )
[ "def", "l", "(", "*", "members", ",", "meta", "=", "None", ")", "->", "List", ":", "return", "List", "(", "# pylint: disable=abstract-class-instantiated", "plist", "(", "iterable", "=", "members", ")", ",", "meta", "=", "meta", ")" ]
37.4
13
def _init_map(self): """call these all manually because non-cooperative""" DecimalValuesFormRecord._init_map(self) IntegerValuesFormRecord._init_map(self) TextAnswerFormRecord._init_map(self) FilesAnswerFormRecord._init_map(self) FeedbackAnswerFormRecord._init_map(self) ...
[ "def", "_init_map", "(", "self", ")", ":", "DecimalValuesFormRecord", ".", "_init_map", "(", "self", ")", "IntegerValuesFormRecord", ".", "_init_map", "(", "self", ")", "TextAnswerFormRecord", ".", "_init_map", "(", "self", ")", "FilesAnswerFormRecord", ".", "_ini...
52.9
14.8
def position(parser, token): """ Render a given position for category. If some position is not defined for first category, position from its parent category is used unless nofallback is specified. Syntax:: {% position POSITION_NAME for CATEGORY [nofallback] %}{% endposition %} {% p...
[ "def", "position", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "nodelist", "=", "parser", ".", "parse", "(", "(", "'end'", "+", "bits", "[", "0", "]", ",", ")", ")", "parser", ".", "delete_first_token...
33.526316
21.947368
def scan(self, match="*", count=1000, cursor=0): """ :see::meth:RedisMap.scan """ cursor, results = self._client.hscan( self.key_prefix, cursor=cursor, match=match, count=count) return (cursor, list(map(self._decode, results)))
[ "def", "scan", "(", "self", ",", "match", "=", "\"*\"", ",", "count", "=", "1000", ",", "cursor", "=", "0", ")", ":", "cursor", ",", "results", "=", "self", ".", "_client", ".", "hscan", "(", "self", ".", "key_prefix", ",", "cursor", "=", "cursor",...
51.8
11.8
def get_recipe_env(self, arch, with_flags_in_cc=True): """ Adds openssl recipe to include and library path. """ env = super(ScryptRecipe, self).get_recipe_env(arch, with_flags_in_cc) openssl_recipe = self.get_recipe('openssl', self.ctx) env['CFLAGS'] += openssl_recipe.inc...
[ "def", "get_recipe_env", "(", "self", ",", "arch", ",", "with_flags_in_cc", "=", "True", ")", ":", "env", "=", "super", "(", "ScryptRecipe", ",", "self", ")", ".", "get_recipe_env", "(", "arch", ",", "with_flags_in_cc", ")", "openssl_recipe", "=", "self", ...
51.583333
20.083333
def predict(self, X, raw_score=False, num_iteration=None, pred_leaf=False, pred_contrib=False, **kwargs): """Return the predicted value for each sample. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] Input features ma...
[ "def", "predict", "(", "self", ",", "X", ",", "raw_score", "=", "False", ",", "num_iteration", "=", "None", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_n_features", "is", ...
52.862745
26.960784
def run_steps(node: Node, pipeline: RenderingPipeline, **args): """Runs instance node rendering steps""" for step in pipeline.steps: result = step(node, pipeline=pipeline, **args) if isinstance(result, dict): args = {**args, **result}
[ "def", "run_steps", "(", "node", ":", "Node", ",", "pipeline", ":", "RenderingPipeline", ",", "*", "*", "args", ")", ":", "for", "step", "in", "pipeline", ".", "steps", ":", "result", "=", "step", "(", "node", ",", "pipeline", "=", "pipeline", ",", "...
44.166667
8.833333
def get_or_create_shared_key(cls, force_new=False): """ Create a shared public/private key pair for certificate pushing, if the settings allow. """ if force_new: with transaction.atomic(): SharedKey.objects.filter(current=True).update(current=False) ...
[ "def", "get_or_create_shared_key", "(", "cls", ",", "force_new", "=", "False", ")", ":", "if", "force_new", ":", "with", "transaction", ".", "atomic", "(", ")", ":", "SharedKey", ".", "objects", ".", "filter", "(", "current", "=", "True", ")", ".", "upda...
44.1
16.1
def makeCubicxFunc(self,mLvl,pLvl,MedShk,xLvl): ''' Constructs the (unconstrained) expenditure function for this period using bilinear interpolation (over permanent income and the medical shock) among an array of cubic interpolations over market resources. Parameters ---...
[ "def", "makeCubicxFunc", "(", "self", ",", "mLvl", ",", "pLvl", ",", "MedShk", ",", "xLvl", ")", ":", "# Get state dimensions", "pCount", "=", "mLvl", ".", "shape", "[", "1", "]", "MedCount", "=", "mLvl", ".", "shape", "[", "0", "]", "# Calculate the MPC...
46.262295
25.180328
def associate_interface_environments(self, int_env_map): """ Method to add an interface. :param int_env_map: List containing interfaces and environments ids desired to be associates. :return: Id. """ data = {'interface_environments': int_env_map} return super(Api...
[ "def", "associate_interface_environments", "(", "self", ",", "int_env_map", ")", ":", "data", "=", "{", "'interface_environments'", ":", "int_env_map", "}", "return", "super", "(", "ApiInterfaceRequest", ",", "self", ")", ".", "post", "(", "'api/v3/interface/environ...
42.222222
23.111111
def td_type(): '''get type of the tomodir (complex or dc and whether fpi) ''' cfg = np.genfromtxt('exe/crtomo.cfg', skip_header=15, dtype='str', usecols=([0])) is_complex = False if cfg[0] == 'F': is_complex = True i...
[ "def", "td_type", "(", ")", ":", "cfg", "=", "np", ".", "genfromtxt", "(", "'exe/crtomo.cfg'", ",", "skip_header", "=", "15", ",", "dtype", "=", "'str'", ",", "usecols", "=", "(", "[", "0", "]", ")", ")", "is_complex", "=", "False", "if", "cfg", "[...
26.266667
16.8
def setInverted(self, state): """ Sets whether or not to invert the check state for collapsing. :param state | <bool> """ collapsed = self.isCollapsed() self._inverted = state if self.isCollapsible(): self.setCollapsed(collapsed)
[ "def", "setInverted", "(", "self", ",", "state", ")", ":", "collapsed", "=", "self", ".", "isCollapsed", "(", ")", "self", ".", "_inverted", "=", "state", "if", "self", ".", "isCollapsible", "(", ")", ":", "self", ".", "setCollapsed", "(", "collapsed", ...
31.1
9.3
def get_data_file_names_from_scan_base(scan_base, filter_str=['_analyzed.h5', '_interpreted.h5', '_cut.h5', '_result.h5', '_hists.h5'], sort_by_time=True, meta_data_v2=True): """ Generate a list of .h5 files which have a similar file name. Parameters ---------- scan_base : list, string List...
[ "def", "get_data_file_names_from_scan_base", "(", "scan_base", ",", "filter_str", "=", "[", "'_analyzed.h5'", ",", "'_interpreted.h5'", ",", "'_cut.h5'", ",", "'_result.h5'", ",", "'_hists.h5'", "]", ",", "sort_by_time", "=", "True", ",", "meta_data_v2", "=", "True"...
45.196429
27.589286
def persistent_write(self, address, byte, refresh_config=False): ''' Write a single byte to an address in persistent memory. Parameters ---------- address : int Address in persistent memory (e.g., EEPROM). byte : int Value to write to address. ...
[ "def", "persistent_write", "(", "self", ",", "address", ",", "byte", ",", "refresh_config", "=", "False", ")", ":", "self", ".", "_persistent_write", "(", "address", ",", "byte", ")", "if", "refresh_config", ":", "self", ".", "load_config", "(", "False", "...
34.058824
18.294118
def _project_perturbation(perturbation, epsilon, input_image, clip_min=None, clip_max=None): """Project `perturbation` onto L-infinity ball of radius `epsilon`. Also project into hypercube such that the resulting adversarial example is between clip_min and clip_max, if applicable. """ ...
[ "def", "_project_perturbation", "(", "perturbation", ",", "epsilon", ",", "input_image", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ")", ":", "if", "clip_min", "is", "None", "or", "clip_max", "is", "None", ":", "raise", "NotImplementedError", ...
44.434783
16
def _create_attach_record(self, id, timed): """ Create a new pivot attachement record. """ record = {} record[self._foreign_key] = self._parent.get_key() record[self._other_key] = id if timed: record = self._set_timestamps_on_attach(record) ...
[ "def", "_create_attach_record", "(", "self", ",", "id", ",", "timed", ")", ":", "record", "=", "{", "}", "record", "[", "self", ".", "_foreign_key", "]", "=", "self", ".", "_parent", ".", "get_key", "(", ")", "record", "[", "self", ".", "_other_key", ...
22.928571
19.5
def rotation(f, line = 'fast'): """ Find rotation of the survey Find the clock-wise rotation and origin of `line` as ``(rot, cdpx, cdpy)`` The clock-wise rotation is defined as the angle in radians between line given by the first and last trace of the first line and the axis that gives increasing ...
[ "def", "rotation", "(", "f", ",", "line", "=", "'fast'", ")", ":", "if", "f", ".", "unstructured", ":", "raise", "ValueError", "(", "\"Rotation requires a structured file\"", ")", "lines", "=", "{", "'fast'", ":", "f", ".", "fast", ",", "'slow'", ":", "f...
25.894737
25.824561
def post(self, url, data, headers={}): """ POST request for creating new objects. data should be a dictionary. """ response = self._run_method('POST', url, data=data, headers=headers) return self._handle_response(url, response)
[ "def", "post", "(", "self", ",", "url", ",", "data", ",", "headers", "=", "{", "}", ")", ":", "response", "=", "self", ".", "_run_method", "(", "'POST'", ",", "url", ",", "data", "=", "data", ",", "headers", "=", "headers", ")", "return", "self", ...
38.428571
8.428571
def subclass(cls, vt_code, vt_args): """Return a dynamic subclass that has the extra parameters built in""" from geoid import get_class import geoid.census parser = get_class(geoid.census, vt_args.strip('/')).parse cls = type(vt_code.replace('/', '_'), (cls,), {'vt_code': vt_co...
[ "def", "subclass", "(", "cls", ",", "vt_code", ",", "vt_args", ")", ":", "from", "geoid", "import", "get_class", "import", "geoid", ".", "census", "parser", "=", "get_class", "(", "geoid", ".", "census", ",", "vt_args", ".", "strip", "(", "'/'", ")", "...
34.583333
21.75
def deprecated(*args): """ Deprecation warning decorator. Takes optional deprecation message, otherwise will use a generic warning. """ def wrap(func): def wrapped_func(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return func(*args, **kwargs) retu...
[ "def", "deprecated", "(", "*", "args", ")", ":", "def", "wrap", "(", "func", ")", ":", "def", "wrapped_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "msg", ",", "category", "=", "DeprecationWarning", ")", ...
35.375
14.8125
def _traverse(self, start_paths, traversal_path): """ Traverse a multi-hop traversal path from a list of start instance paths, and return the resulting list of instance paths. Parameters: start_paths (list of CIMInstanceName): Instance paths to start traversal from...
[ "def", "_traverse", "(", "self", ",", "start_paths", ",", "traversal_path", ")", ":", "assert", "len", "(", "traversal_path", ")", ">=", "2", "assoc_class", "=", "traversal_path", "[", "0", "]", "far_class", "=", "traversal_path", "[", "1", "]", "total_next_...
40.966667
16.033333
def delete_probes(probes, test=False, commit=True, **kwargs): # pylint: disable=unused-argument ''' Removes RPM/SLA probes from the network device. Calls the configuration template 'delete_probes' from the NAPALM library, providing as input a rich formatted dictionary with the configuration details of...
[ "def", "delete_probes", "(", "probes", ",", "test", "=", "False", ",", "commit", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "return", "__salt__", "[", "'net.load_template'", "]", "(", "'delete_probes'", ",", "probes", ...
44.729167
28.020833
def clone(self): """Creates a clone of this aggregator.""" return type(self)(self.__cmp, self.__key, self.__reverse, name = self.name, dataFormat = self._dataFormat)
[ "def", "clone", "(", "self", ")", ":", "return", "type", "(", "self", ")", "(", "self", ".", "__cmp", ",", "self", ".", "__key", ",", "self", ".", "__reverse", ",", "name", "=", "self", ".", "name", ",", "dataFormat", "=", "self", ".", "_dataFormat...
57
31.333333
def _rule_id(self, id: int) -> str: """ Convert an integer into a gorule key id. """ if id is None or id == 0 or id >= 10000000: return "other" return "gorule-{:0>7}".format(id)
[ "def", "_rule_id", "(", "self", ",", "id", ":", "int", ")", "->", "str", ":", "if", "id", "is", "None", "or", "id", "==", "0", "or", "id", ">=", "10000000", ":", "return", "\"other\"", "return", "\"gorule-{:0>7}\"", ".", "format", "(", "id", ")" ]
27.875
9.875
def _cli_check_role(role): '''Checks that a basis set role exists and if not, raises a helpful exception''' if role is None: return None role = role.lower() if not role in api.get_roles(): errstr = "Role format '" + role + "' does not exist.\n" errstr += "For a complete list of...
[ "def", "_cli_check_role", "(", "role", ")", ":", "if", "role", "is", "None", ":", "return", "None", "role", "=", "role", ".", "lower", "(", ")", "if", "not", "role", "in", "api", ".", "get_roles", "(", ")", ":", "errstr", "=", "\"Role format '\"", "+...
30.846154
25.923077
def _get_min_distance_to_volcanic_front(lons, lats): """ Compute and return minimum distance between volcanic front and points specified by 'lon' and 'lat'. Distance is negative if point is located east of the volcanic front, positive otherwise. The method uses the same approach as :meth:`_get...
[ "def", "_get_min_distance_to_volcanic_front", "(", "lons", ",", "lats", ")", ":", "vf", "=", "_construct_surface", "(", "VOLCANIC_FRONT_LONS", ",", "VOLCANIC_FRONT_LATS", ",", "0.", ",", "10.", ")", "sites", "=", "Mesh", "(", "lons", ",", "lats", ",", "None", ...
40.285714
21.285714
def segwit_address(self): """The public segwit nested in P2SH address you share with others to receive funds.""" # Only make segwit address if public key is compressed if self._segwit_address is None and self.is_compressed(): self._segwit_address = public_key_to_segwit_addres...
[ "def", "segwit_address", "(", "self", ")", ":", "# Only make segwit address if public key is compressed", "if", "self", ".", "_segwit_address", "is", "None", "and", "self", ".", "is_compressed", "(", ")", ":", "self", ".", "_segwit_address", "=", "public_key_to_segwit...
50.875
13.25
def show_zoning_enabled_configuration_input_request_type_get_next_request_last_rcvd_zone_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_zoning_enabled_configuration = ET.Element("show_zoning_enabled_configuration") config = show_zoning_enabled...
[ "def", "show_zoning_enabled_configuration_input_request_type_get_next_request_last_rcvd_zone_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_zoning_enabled_configuration", "=", "ET", ".", "Element",...
55.357143
25.571429
def subscribe( self, plan, charge_immediately=True, application_fee_percent=None, coupon=None, quantity=None, metadata=None, tax_percent=None, billing_cycle_anchor=None, trial_end=None, trial_from_plan=None, trial_period_days=None, ): """ Subscribes this customer to a plan. :param plan: ...
[ "def", "subscribe", "(", "self", ",", "plan", ",", "charge_immediately", "=", "True", ",", "application_fee_percent", "=", "None", ",", "coupon", "=", "None", ",", "quantity", "=", "None", ",", "metadata", "=", "None", ",", "tax_percent", "=", "None", ",",...
41.436782
25.850575
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.""" AXU = self.AX + self.U self.Y[..., 0:-1] = sp.prox_l2(AXU[..., 0:-1], self.mu/self.rho) self.Y[..., -1] = sp.prox_l1(AXU[..., -1], (self.lmbda/self.rho)...
[ "def", "ystep", "(", "self", ")", ":", "AXU", "=", "self", ".", "AX", "+", "self", ".", "U", "self", ".", "Y", "[", "...", ",", "0", ":", "-", "1", "]", "=", "sp", ".", "prox_l2", "(", "AXU", "[", "...", ",", "0", ":", "-", "1", "]", ",...
40.625
18.25
def maybe_download_and_extract(): """Download and extract the tarball from Alex's website.""" dest_directory = "/tmp/cifar" if not os.path.exists(dest_directory): os.makedirs(dest_directory) filename = DATA_URL.split('/')[-1] filepath = os.path.join(dest_directory, filename) if not os.path.exists(filepa...
[ "def", "maybe_download_and_extract", "(", ")", ":", "dest_directory", "=", "\"/tmp/cifar\"", "if", "not", "os", ".", "path", ".", "exists", "(", "dest_directory", ")", ":", "os", ".", "makedirs", "(", "dest_directory", ")", "filename", "=", "DATA_URL", ".", ...
45.411765
14.529412
def open_filezip(file_path, find_str): """ Open the wrapped file. Read directly from the zip without extracting its content. """ if zipfile.is_zipfile(file_path): zipf = zipfile.ZipFile(file_path) interesting_files = [f for f in zipf.infolist() if find_str in f] for inside_f...
[ "def", "open_filezip", "(", "file_path", ",", "find_str", ")", ":", "if", "zipfile", ".", "is_zipfile", "(", "file_path", ")", ":", "zipf", "=", "zipfile", ".", "ZipFile", "(", "file_path", ")", "interesting_files", "=", "[", "f", "for", "f", "in", "zipf...
34.181818
10.909091
def convergence_criteria_small_relative_norm_weights_change( tolerance=1e-5, norm_order=2): """Returns Python `callable` which indicates fitting procedure has converged. Writing old, new `model_coefficients` as `w0`, `w1`, this function defines convergence as, ```python relative_euclidean_norm = (tf...
[ "def", "convergence_criteria_small_relative_norm_weights_change", "(", "tolerance", "=", "1e-5", ",", "norm_order", "=", "2", ")", ":", "def", "convergence_criteria_fn", "(", "is_converged_previous", ",", "# pylint: disable=unused-argument", "iter_", ",", "model_coefficients_...
41.931507
22.780822
def imap_unordered_async(self, func, iterable, chunksize=None, callback=None): """A variant of the imap_unordered() method which returns an ApplyResult object that provides an iterator (next method(timeout) available). If callback is specified then it should be a callable which ...
[ "def", "imap_unordered_async", "(", "self", ",", "func", ",", "iterable", ",", "chunksize", "=", "None", ",", "callback", "=", "None", ")", ":", "apply_result", "=", "ApplyResult", "(", "callback", "=", "callback", ")", "collector", "=", "UnorderedResultCollec...
55.214286
19.714286
def extract(dset, *d_slices): """ :param dset: a D-dimensional dataset or array :param d_slices: D slice objects (or similar) :returns: a reduced D-dimensional array >>> a = numpy.array([[1, 2, 3], [4, 5, 6]]) # shape (2, 3) >>> extract(a, slice(None), 1) array([[2], [5]]) >...
[ "def", "extract", "(", "dset", ",", "*", "d_slices", ")", ":", "shp", "=", "list", "(", "dset", ".", "shape", ")", "if", "len", "(", "shp", ")", "!=", "len", "(", "d_slices", ")", ":", "raise", "ValueError", "(", "'Array with %d dimensions but %d slices'...
34.130435
13.217391
def _set_return(self): """Sets the return parameter with description and rtype if any""" # TODO: manage return retrieved from element code (external) # TODO: manage different in/out styles if type(self.docs['in']['return']) is list and self.dst.style['out'] not in ['groups', 'numpydoc', ...
[ "def", "_set_return", "(", "self", ")", ":", "# TODO: manage return retrieved from element code (external)", "# TODO: manage different in/out styles", "if", "type", "(", "self", ".", "docs", "[", "'in'", "]", "[", "'return'", "]", ")", "is", "list", "and", "self", "...
52.470588
20.647059