text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _set_prefix(self): """ Called by ``__init()__`` to set the object's ``_prefix`` attribute, which determines the prefix app users must use when overriding settings associated with this helper. For example: If the ``_prefix`` attribute were to be set to "YOURAPP", and there ...
[ "def", "_set_prefix", "(", "self", ")", ":", "if", "self", ".", "prefix", "is", "not", "None", ":", "value", "=", "self", ".", "prefix", ".", "rstrip", "(", "'_'", ")", "else", ":", "module_path_parts", "=", "self", ".", "__module_path_split", "[", ":"...
46.6
24.666667
def is_parent_of_repository(self, id_, repository_id): """Tests if an ``Id`` is a direct parent of a repository. arg: id (osid.id.Id): an ``Id`` arg: repository_id (osid.id.Id): the ``Id`` of a repository return: (boolean) - ``true`` if this ``id`` is a parent of `...
[ "def", "is_parent_of_repository", "(", "self", ",", "id_", ",", "repository_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchySession.is_parent_of_bin", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", ...
53.2
21.5
def run(self, start_point=None, stop_before=None, stop_after=None): """ Run the pipeline, optionally specifying start and/or stop points. :param str start_point: Name of stage at which to begin execution. :param str stop_before: Name of stage at which to cease execution; exc...
[ "def", "run", "(", "self", ",", "start_point", "=", "None", ",", "stop_before", "=", "None", ",", "stop_after", "=", "None", ")", ":", "# Start the run with a clean slate of Stage status/label tracking.", "self", ".", "_reset", "(", ")", "# TODO: validate starting poi...
43.096154
23.153846
def GetIpForwardTable2(AF=AF_UNSPEC): """Return all Windows routes (IPv4/IPv6) from iphlpapi""" if WINDOWS_XP: raise OSError("Not available on Windows XP !") table = PMIB_IPFORWARD_TABLE2() res = _GetIpForwardTable2(AF, byref(table)) if res != NO_ERROR: raise RuntimeError("Error retr...
[ "def", "GetIpForwardTable2", "(", "AF", "=", "AF_UNSPEC", ")", ":", "if", "WINDOWS_XP", ":", "raise", "OSError", "(", "\"Not available on Windows XP !\"", ")", "table", "=", "PMIB_IPFORWARD_TABLE2", "(", ")", "res", "=", "_GetIpForwardTable2", "(", "AF", ",", "b...
38.923077
14.076923
def finalize(self, shutit): """Finalizes the target, exiting for us back to the original shell and performing any repository work required. """ # Finish with the target target_child_pexpect_session = shutit.get_shutit_pexpect_session_from_id('target_child') assert not target_child_pexpect_session.sendline(S...
[ "def", "finalize", "(", "self", ",", "shutit", ")", ":", "# Finish with the target", "target_child_pexpect_session", "=", "shutit", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", "assert", "not", "target_child_pexpect_session", ".", "sendline", "("...
53.5
27.875
def _get_variables(self): """Get the requested variables.""" if self._specs_in[_VARIABLES_STR] == 'all': return _get_all_objs_of_type( Var, getattr(self._obj_lib, 'variables', self._obj_lib) ) else: return set(self._specs_in[_VARIABLES_STR])
[ "def", "_get_variables", "(", "self", ")", ":", "if", "self", ".", "_specs_in", "[", "_VARIABLES_STR", "]", "==", "'all'", ":", "return", "_get_all_objs_of_type", "(", "Var", ",", "getattr", "(", "self", ".", "_obj_lib", ",", "'variables'", ",", "self", "....
38.75
15.75
def _start_new_timer(self): """Create a timer that will be used to periodically check the connection for heartbeats. :return: """ if not self._running.is_set(): return False self._timer = self.timer_impl( interval=self._interval, funct...
[ "def", "_start_new_timer", "(", "self", ")", ":", "if", "not", "self", ".", "_running", ".", "is_set", "(", ")", ":", "return", "False", "self", ".", "_timer", "=", "self", ".", "timer_impl", "(", "interval", "=", "self", ".", "_interval", ",", "functi...
28.533333
12.4
def ConsultarCTGActivosPorPatente(self, patente="ZZZ999"): "Consulta de CTGs activos por patente" ret = self.client.consultarCTGActivosPorPatente(request=dict( auth={ 'token': self.Token, 'sign': self.Sign, 'cuitRepresentado...
[ "def", "ConsultarCTGActivosPorPatente", "(", "self", ",", "patente", "=", "\"ZZZ999\"", ")", ":", "ret", "=", "self", ".", "client", ".", "consultarCTGActivosPorPatente", "(", "request", "=", "dict", "(", "auth", "=", "{", "'token'", ":", "self", ".", "Token...
40.823529
14.705882
def bump(self, target): """ Bumps the Version given a target The target can be either MAJOR, MINOR or PATCH """ if target == 'patch': return Version(self.major, self.minor, self.patch + 1) if target == 'minor': return Version(self.major, self.mino...
[ "def", "bump", "(", "self", ",", "target", ")", ":", "if", "target", "==", "'patch'", ":", "return", "Version", "(", "self", ".", "major", ",", "self", ".", "minor", ",", "self", ".", "patch", "+", "1", ")", "if", "target", "==", "'minor'", ":", ...
32.615385
12.923077
def should_raptorize(self, req, resp): """ Determine if this request should be raptorized. Boolean. """ if resp.status != "200 OK": return False content_type = resp.headers.get('Content-Type', 'text/plain').lower() if not 'html' in content_type: return False ...
[ "def", "should_raptorize", "(", "self", ",", "req", ",", "resp", ")", ":", "if", "resp", ".", "status", "!=", "\"200 OK\"", ":", "return", "False", "content_type", "=", "resp", ".", "headers", ".", "get", "(", "'Content-Type'", ",", "'text/plain'", ")", ...
29
18.421053
def remove_priors(self): """Clear all priors.""" for src in self.roi.sources: for par in self.like[src.name].funcs["Spectrum"].params.values(): par.removePrior()
[ "def", "remove_priors", "(", "self", ")", ":", "for", "src", "in", "self", ".", "roi", ".", "sources", ":", "for", "par", "in", "self", ".", "like", "[", "src", ".", "name", "]", ".", "funcs", "[", "\"Spectrum\"", "]", ".", "params", ".", "values",...
28.714286
20.571429
def twos_complement(rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat): ''' Two's complement conversion of a binary number Input handshake & data rx_rdy - (o) Ready rx_vld - (i) Valid rx_dat - (i) Data Output handshake & data tx_rdy - (i) Ready ...
[ "def", "twos_complement", "(", "rst", ",", "clk", ",", "rx_rdy", ",", "rx_vld", ",", "rx_dat", ",", "tx_rdy", ",", "tx_vld", ",", "tx_dat", ")", ":", "DATA_WIDTH", "=", "len", "(", "rx_dat", ")", "NUM_STAGES", "=", "3", "stage_en", "=", "Signal", "(", ...
29.606061
21.757576
def execute_file(self, path, hidden=False): """ Reimplemented to use the 'run' magic. """ # Use forward slashes on Windows to avoid escaping each separator. if sys.platform == 'win32': path = os.path.normpath(path).replace('\\', '/') # Perhaps we should not be using ...
[ "def", "execute_file", "(", "self", ",", "path", ",", "hidden", "=", "False", ")", ":", "# Use forward slashes on Windows to avoid escaping each separator.", "if", "sys", ".", "platform", "==", "'win32'", ":", "path", "=", "os", ".", "path", ".", "normpath", "("...
52.16
24.24
def convert(self, json, fout): """Convert json to markdown. Takes in a .json file as input and convert it to Markdown format, saving the generated .png images into ./images. """ self.build_markdown_body(json) # create the body self.build_header(json['name']) # create t...
[ "def", "convert", "(", "self", ",", "json", ",", "fout", ")", ":", "self", ".", "build_markdown_body", "(", "json", ")", "# create the body", "self", ".", "build_header", "(", "json", "[", "'name'", "]", ")", "# create the md header", "self", ".", "build_out...
39.555556
16.333333
def write_file(self, filepath, filename=None, directory=None): """ write_file: Write local file to zip Args: filepath: (str) location to local file directory: (str) directory in zipfile to write file to (optional) Returns: path to file in zip ...
[ "def", "write_file", "(", "self", ",", "filepath", ",", "filename", "=", "None", ",", "directory", "=", "None", ")", ":", "arcname", "=", "None", "if", "filename", "or", "directory", ":", "directory", "=", "directory", ".", "rstrip", "(", "\"/\"", ")", ...
43.5
16.625
def get_orderbook_ticker(self, **params): """Latest price for a symbol or symbols. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-order-book-ticker :param symbol: :type symbol: str :returns: API response .. code-block:: py...
[ "def", "get_orderbook_ticker", "(", "self", ",", "*", "*", "params", ")", ":", "return", "self", ".", "_get", "(", "'ticker/bookTicker'", ",", "data", "=", "params", ",", "version", "=", "self", ".", "PRIVATE_API_VERSION", ")" ]
28.288889
19.911111
def setRepoData(self, searchString, category="", extension="", math=False, game=False, searchFiles=False): """Call this function with all the settings to use for future operations on a repository, must be called FIRST""" self.searchString = searchString self.category = category self.math = math self.game = ga...
[ "def", "setRepoData", "(", "self", ",", "searchString", ",", "category", "=", "\"\"", ",", "extension", "=", "\"\"", ",", "math", "=", "False", ",", "game", "=", "False", ",", "searchFiles", "=", "False", ")", ":", "self", ".", "searchString", "=", "se...
47.125
18.75
def Z_from_virial_pressure_form(P, *args): r'''Calculates the compressibility factor of a gas given its pressure, and pressure-form virial coefficients. Any number of coefficients is supported. .. math:: Z = \frac{Pv}{RT} = 1 + B'P + C'P^2 + D'P^3 + E'P^4 \dots Parameters ---------- P...
[ "def", "Z_from_virial_pressure_form", "(", "P", ",", "*", "args", ")", ":", "return", "1", "+", "P", "*", "sum", "(", "[", "coeff", "*", "P", "**", "i", "for", "i", ",", "coeff", "in", "enumerate", "(", "args", ")", "]", ")" ]
34.12
29.28
def save(self, inplace=True): """ Saves all modification to the marker on the server. :param inplace Apply edits on the current instance or get a new one. :return: Marker instance. """ modified_data = self._modified_data() if bool(modified_data): extra...
[ "def", "save", "(", "self", ",", "inplace", "=", "True", ")", ":", "modified_data", "=", "self", ".", "_modified_data", "(", ")", "if", "bool", "(", "modified_data", ")", ":", "extra", "=", "{", "'resource'", ":", "self", ".", "__class__", ".", "__name...
37.454545
14.545455
def control_change(self, channel, control, value): """Send a control change message. See the MIDI specification for more information. """ if control < 0 or control > 128: return False if value < 0 or value > 128: return False self.cc_event(channel...
[ "def", "control_change", "(", "self", ",", "channel", ",", "control", ",", "value", ")", ":", "if", "control", "<", "0", "or", "control", ">", "128", ":", "return", "False", "if", "value", "<", "0", "or", "value", ">", "128", ":", "return", "False", ...
36.384615
13.461538
def get_key(self, key, target='in'): """Get the name of a key in current style. e.g.: in javadoc style, the returned key for 'param' is '@param' :param key: the key wanted (param, type, return, rtype,..) :param target: the target docstring is 'in' for the input or 'out' for th...
[ "def", "get_key", "(", "self", ",", "key", ",", "target", "=", "'in'", ")", ":", "target", "=", "'out'", "if", "target", "==", "'out'", "else", "'in'", "return", "self", ".", "opt", "[", "key", "]", "[", "self", ".", "style", "[", "target", "]", ...
43.272727
20.272727
def get_bytes(self): """ p_q_inner_data#83c95aec pq:bytes p:bytes q:bytes nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data """ pq_io = BytesIO() serialize_string(pq_io, self.pq) serialize_string(pq_io, self.p) serialize_string(pq_io, self.q) print("\nP...
[ "def", "get_bytes", "(", "self", ")", ":", "pq_io", "=", "BytesIO", "(", ")", "serialize_string", "(", "pq_io", ",", "self", ".", "pq", ")", "serialize_string", "(", "pq_io", ",", "self", ".", "p", ")", "serialize_string", "(", "pq_io", ",", "self", "....
24.722222
22.361111
def authorized_get(self): '''xxxxx.xxxxx.customers.authorized.get =================================== 取得当前登录用户的授权账户列表''' request = TOPRequest('xxxxx.xxxxx.customers.authorized.get') self.create(self.execute(request)) return self.result
[ "def", "authorized_get", "(", "self", ")", ":", "request", "=", "TOPRequest", "(", "'xxxxx.xxxxx.customers.authorized.get'", ")", "self", ".", "create", "(", "self", ".", "execute", "(", "request", ")", ")", "return", "self", ".", "result" ]
39.571429
11.857143
def get_injected_modules(classname): r""" Example: >>> # DISABLE_DOCTEST >>> from utool.util_class import __CLASSNAME_CLASSKEY_REGISTER__ # NOQA """ modname_list = __CLASSNAME_CLASSKEY_REGISTER__[classname] injected_modules = [] for modstr in modname_list: parts = modst...
[ "def", "get_injected_modules", "(", "classname", ")", ":", "modname_list", "=", "__CLASSNAME_CLASSKEY_REGISTER__", "[", "classname", "]", "injected_modules", "=", "[", "]", "for", "modstr", "in", "modname_list", ":", "parts", "=", "modstr", ".", "split", "(", "'...
35.15
16.7
def observed(self, band, corrected=True): """Return observed values in the given band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] corrected : bool (optional) If true, correct for extinction Return...
[ "def", "observed", "(", "self", ",", "band", ",", "corrected", "=", "True", ")", ":", "if", "band", "not", "in", "'ugriz'", ":", "raise", "ValueError", "(", "\"band='{0}' not recognized\"", ".", "format", "(", "band", ")", ")", "i", "=", "'ugriz'", ".", ...
31.423077
21.038462
def create_subscriptions(config, profile_name): ''' Adds supported subscriptions ''' if 'kinesis' in config.subscription.keys(): data = config.subscription['kinesis'] function_name = config.name stream_name = data['stream'] batch_size = data['batch_size'] starting_positio...
[ "def", "create_subscriptions", "(", "config", ",", "profile_name", ")", ":", "if", "'kinesis'", "in", "config", ".", "subscription", ".", "keys", "(", ")", ":", "data", "=", "config", ".", "subscription", "[", "'kinesis'", "]", "function_name", "=", "config"...
48.176471
12.176471
def _derive_distinct_intervals(self, rows): """ Returns the set of distinct intervals in a row set. :param list[dict[str,T]] rows: The rows set. :rtype: set[(int,int)] """ ret = set() for row in rows: self._add_interval(ret, (row[self._key_start_date...
[ "def", "_derive_distinct_intervals", "(", "self", ",", "rows", ")", ":", "ret", "=", "set", "(", ")", "for", "row", "in", "rows", ":", "self", ".", "_add_interval", "(", "ret", ",", "(", "row", "[", "self", ".", "_key_start_date", "]", ",", "row", "[...
27.384615
20.923077
def td_tr(points, dist_threshold): """ Top-Down Time-Ratio Trajectory Compression Algorithm Detailed in https://www.itc.nl/library/Papers_2003/peer_ref_conf/meratnia_new.pdf Args: points (:obj:`list` of :obj:`Point`): trajectory or part of it dist_threshold (float): max distance error, in ...
[ "def", "td_tr", "(", "points", ",", "dist_threshold", ")", ":", "if", "len", "(", "points", ")", "<=", "2", ":", "return", "points", "else", ":", "max_dist_threshold", "=", "0", "found_index", "=", "0", "delta_e", "=", "time_dist", "(", "points", "[", ...
32.761905
18.261905
def corr_vs_pval(r, pval, plim=0.01, rlim=0.4, dpi=96): """Histogram for correlation coefficients and its p-values (colored) Parameters: ----------- r : np.ndarray Correlation coefficient matrix. The upper triangular elements are extracted if a NxN is provided. Otherwise provide...
[ "def", "corr_vs_pval", "(", "r", ",", "pval", ",", "plim", "=", "0.01", ",", "rlim", "=", "0.4", ",", "dpi", "=", "96", ")", ":", "# reshape", "if", "len", "(", "r", ".", "shape", ")", "==", "2", ":", "idx", "=", "(", "np", ".", "tri", "(", ...
28.545455
19.106061
def _insert(self, trigram): """ Insert a trigram in the DB """ words = list(map(self._sanitize, trigram)) key = self._WSEP.join(words[:2]).lower() next_word = words[2] self._db.setdefault(key, []) # we could use a set here, but sets are not serializables...
[ "def", "_insert", "(", "self", ",", "trigram", ")", ":", "words", "=", "list", "(", "map", "(", "self", ".", "_sanitize", ",", "trigram", ")", ")", "key", "=", "self", ".", "_WSEP", ".", "join", "(", "words", "[", ":", "2", "]", ")", ".", "lowe...
33.928571
14.5
def _read_conf_file(path): ''' Read in a config file from a given path and process it into a dictionary ''' log.debug('Reading configuration from %s', path) with salt.utils.files.fopen(path, 'r') as conf_file: try: conf_opts = salt.utils.yaml.safe_load(conf_file) or {} ex...
[ "def", "_read_conf_file", "(", "path", ")", ":", "log", ".", "debug", "(", "'Reading configuration from %s'", ",", "path", ")", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "path", ",", "'r'", ")", "as", "conf_file", ":", "try", ":", ...
46
24.428571
def get_gconf_http_proxy (): """Return host:port for GConf HTTP proxy if found, else None.""" try: import gconf except ImportError: return None try: client = gconf.client_get_default() if client.get_bool("/system/http_proxy/use_http_proxy"): host = client.get_...
[ "def", "get_gconf_http_proxy", "(", ")", ":", "try", ":", "import", "gconf", "except", "ImportError", ":", "return", "None", "try", ":", "client", "=", "gconf", ".", "client_get_default", "(", ")", "if", "client", ".", "get_bool", "(", "\"/system/http_proxy/us...
34.684211
18.473684
def _graph_get_node(self, block_id, terminator_for_nonexistent_node=False): """ Get an existing VFGNode instance from the graph. :param BlockID block_id: The block ID for the node to get. :param bool terminator_for_nonexistent_node: True if a Terminator (which is a S...
[ "def", "_graph_get_node", "(", "self", ",", "block_id", ",", "terminator_for_nonexistent_node", "=", "False", ")", ":", "if", "block_id", "not", "in", "self", ".", "_nodes", ":", "l", ".", "error", "(", "\"Trying to look up a node that we don't have yet. Is this okay?...
45.351351
22.864865
def bitswap_wantlist(self, peer=None, **kwargs): """Returns blocks currently on the bitswap wantlist. .. code-block:: python >>> c.bitswap_wantlist() {'Keys': [ 'QmeV6C6XVt1wf7V7as7Yak3mxPma8jzpqyhtRtCvpKcfBb', 'QmdCWFLDXqgdWQY9kVubbEHBbkieKd3uo7...
[ "def", "bitswap_wantlist", "(", "self", ",", "peer", "=", "None", ",", "*", "*", "kwargs", ")", ":", "args", "=", "(", "peer", ",", ")", "return", "self", ".", "_client", ".", "request", "(", "'/bitswap/wantlist'", ",", "args", ",", "decoder", "=", "...
30.083333
19.958333
def new(cls, freeform_builder, x, y): """Return a new _LineSegment object ending at point *(x, y)*. Both *x* and *y* are rounded to the nearest integer before use. """ return cls(freeform_builder, int(round(x)), int(round(y)))
[ "def", "new", "(", "cls", ",", "freeform_builder", ",", "x", ",", "y", ")", ":", "return", "cls", "(", "freeform_builder", ",", "int", "(", "round", "(", "x", ")", ")", ",", "int", "(", "round", "(", "y", ")", ")", ")" ]
42.333333
16.666667
def fasta_records(files): """ Use SeqIO to create dictionaries of all records for each FASTA file :param files: dictionary of stain name: /sequencepath/strain_name.extension :return: file_records: dictionary of all contig records for all strains """ # Initialise the dictionary file_records =...
[ "def", "fasta_records", "(", "files", ")", ":", "# Initialise the dictionary", "file_records", "=", "dict", "(", ")", "for", "file_name", ",", "fasta", "in", "files", ".", "items", "(", ")", ":", "# Create a dictionary of records for each file", "record_dict", "=", ...
43.857143
16.571429
def run(self, steps=float('inf')): """ Execute agenda activations """ self.running = True activation = None execution = 0 while steps > 0 and self.running: added, removed = self.get_activations() self.strategy.update_agenda(self.agenda, a...
[ "def", "run", "(", "self", ",", "steps", "=", "float", "(", "'inf'", ")", ")", ":", "self", ".", "running", "=", "True", "activation", "=", "None", "execution", "=", "0", "while", "steps", ">", "0", "and", "self", ".", "running", ":", "added", ",",...
30.428571
17.142857
def post(json_data, url, dry_run=False): """ POST json data to the url provided and verify the requests was successful """ if dry_run: info('POST: %s' % json.dumps(json_data, indent=4)) else: response = SESSION.post(url, data=json.d...
[ "def", "post", "(", "json_data", ",", "url", ",", "dry_run", "=", "False", ")", ":", "if", "dry_run", ":", "info", "(", "'POST: %s'", "%", "json", ".", "dumps", "(", "json_data", ",", "indent", "=", "4", ")", ")", "else", ":", "response", "=", "SES...
32.222222
23.111111
def view_for(self, action='view'): """ Return the classview viewhandler that handles the specified action """ app = current_app._get_current_object() view, attr = self.view_for_endpoints[app][action] return getattr(view(self), attr)
[ "def", "view_for", "(", "self", ",", "action", "=", "'view'", ")", ":", "app", "=", "current_app", ".", "_get_current_object", "(", ")", "view", ",", "attr", "=", "self", ".", "view_for_endpoints", "[", "app", "]", "[", "action", "]", "return", "getattr"...
39.142857
9.142857
def get(self): """API endpoint to get validators set. Return: A JSON string containing the validator set of the current node. """ pool = current_app.config['bigchain_pool'] with pool() as bigchain: validators = bigchain.get_validators() return ...
[ "def", "get", "(", "self", ")", ":", "pool", "=", "current_app", ".", "config", "[", "'bigchain_pool'", "]", "with", "pool", "(", ")", "as", "bigchain", ":", "validators", "=", "bigchain", ".", "get_validators", "(", ")", "return", "validators" ]
24.461538
22.230769
def _should_trigger_abbreviation(self, buffer): """ Checks whether, based on the settings for the abbreviation and the given input, the abbreviation should trigger. @param buffer Input buffer to be checked (as string) """ return any(self.__checkInput(buffer, abbr) for ab...
[ "def", "_should_trigger_abbreviation", "(", "self", ",", "buffer", ")", ":", "return", "any", "(", "self", ".", "__checkInput", "(", "buffer", ",", "abbr", ")", "for", "abbr", "in", "self", ".", "abbreviations", ")" ]
42.25
19.5
def populateBufferContextMenu(self, parentMenu): """Populates the editing buffer context menu. The buffer context menu shown for the current edited/viewed file will have an item with a plugin name and subitems which are populated here. If no items were populated then the plugin menu ...
[ "def", "populateBufferContextMenu", "(", "self", ",", "parentMenu", ")", ":", "parentMenu", ".", "addAction", "(", "\"Configure\"", ",", "self", ".", "configure", ")", "parentMenu", ".", "addAction", "(", "\"Collect garbage\"", ",", "self", ".", "__collectGarbage"...
51.454545
22.454545
def toggle(self): """ This method is used to toggle the smart LED (software managed off). This method is defined because sometimes user may just want to flip the state without knowing the current state """ # Send command self.api_call.operate_on_bulb("...
[ "def", "toggle", "(", "self", ")", ":", "# Send command", "self", ".", "api_call", ".", "operate_on_bulb", "(", "\"toggle\"", ")", "# Update property", "if", "self", ".", "is_on", "(", ")", ":", "self", ".", "property", "[", "self", ".", "PROPERTY_NAME_POWER...
40.923077
20.769231
def initialize_env_specs(hparams, env_problem_name): """Initializes env_specs using the appropriate env.""" if env_problem_name: env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size) else: env = rl_utils.setup_env(hparams, hparams.batch_size, hparams.eval...
[ "def", "initialize_env_specs", "(", "hparams", ",", "env_problem_name", ")", ":", "if", "env_problem_name", ":", "env", "=", "registry", ".", "env_problem", "(", "env_problem_name", ",", "batch_size", "=", "hparams", ".", "batch_size", ")", "else", ":", "env", ...
42.333333
19.666667
def decode_map_element(self, item_type, value): """Decode a single element for a map""" import urllib key = value if ":" in value: key, value = value.split(':',1) key = urllib.unquote(key) if Model in item_type.mro(): value = item_type(id=value...
[ "def", "decode_map_element", "(", "self", ",", "item_type", ",", "value", ")", ":", "import", "urllib", "key", "=", "value", "if", "\":\"", "in", "value", ":", "key", ",", "value", "=", "value", ".", "split", "(", "':'", ",", "1", ")", "key", "=", ...
33.5
10.25
def __flush(self): """Flush the file to the database. """ def on_md5(md5): self._file["md5"] = md5 self._file["length"] = self._position self._file["uploadDate"] = datetime.datetime.utcnow() return self._coll.files.insert(self._file) retur...
[ "def", "__flush", "(", "self", ")", ":", "def", "on_md5", "(", "md5", ")", ":", "self", ".", "_file", "[", "\"md5\"", "]", "=", "md5", "self", ".", "_file", "[", "\"length\"", "]", "=", "self", ".", "_position", "self", ".", "_file", "[", "\"upload...
36
13.916667
def document_did_save_notification(self, params): """ Handle the textDocument/didSave message received from an LSP server. """ text = None if 'text' in params: text = params['text'] params = { 'textDocument': { 'uri': path_as_uri(pa...
[ "def", "document_did_save_notification", "(", "self", ",", "params", ")", ":", "text", "=", "None", "if", "'text'", "in", "params", ":", "text", "=", "params", "[", "'text'", "]", "params", "=", "{", "'textDocument'", ":", "{", "'uri'", ":", "path_as_uri",...
28.533333
14.933333
def record_set_details(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /record-xxxx/setDetails API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Details-and-Links#API-method%3A-%2Fclass-xxxx%2FsetDetails """ return DXHTTPRequest('/%s/setDet...
[ "def", "record_set_details", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/setDetails'", "%", "object_id", ",", "input_params", ",", "always_retr...
54.714286
35.571429
def values(self, objs: List, insert_fields: List, update_fields: List=[]): """Sets the values to be used in this query. Insert fields are fields that are definitely going to be inserted, and if an existing row is found, are going to be overwritten with the specified value. ...
[ "def", "values", "(", "self", ",", "objs", ":", "List", ",", "insert_fields", ":", "List", ",", "update_fields", ":", "List", "=", "[", "]", ")", ":", "self", ".", "insert_values", "(", "insert_fields", ",", "objs", ",", "raw", "=", "False", ")", "se...
34.36
21.36
def eval_algorithm(curr, prev): """ Evaluates OBV Args: curr: Dict of current volume and close prev: Dict of previous OBV and close Returns: Float of OBV """ if curr['close'] > prev['close']: v = curr['volume'] elif curr['...
[ "def", "eval_algorithm", "(", "curr", ",", "prev", ")", ":", "if", "curr", "[", "'close'", "]", ">", "prev", "[", "'close'", "]", ":", "v", "=", "curr", "[", "'volume'", "]", "elif", "curr", "[", "'close'", "]", "<", "prev", "[", "'close'", "]", ...
25.117647
14.882353
def __del_running_bp(self, tid, bp): "Auxiliary method." self.__runningBP[tid].remove(bp) if not self.__runningBP[tid]: del self.__runningBP[tid]
[ "def", "__del_running_bp", "(", "self", ",", "tid", ",", "bp", ")", ":", "self", ".", "__runningBP", "[", "tid", "]", ".", "remove", "(", "bp", ")", "if", "not", "self", ".", "__runningBP", "[", "tid", "]", ":", "del", "self", ".", "__runningBP", "...
35.4
4.6
def get_neighbor_cell_ngrams( mention, dist=1, directions=False, attrib="words", n_min=1, n_max=1, lower=True ): """ Get the ngrams from all Cells that are within a given Cell distance in one direction from the given Mention. Note that if a candidate is passed in, all of its Mentions will be se...
[ "def", "get_neighbor_cell_ngrams", "(", "mention", ",", "dist", "=", "1", ",", "directions", "=", "False", ",", "attrib", "=", "\"words\"", ",", "n_min", "=", "1", ",", "n_max", "=", "1", ",", "lower", "=", "True", ")", ":", "# TODO: Fix this to be more ef...
45.267606
17.633803
def license_name(self, license_name): """Sets the license_name of this DatasetNewRequest. The license that should be associated with the dataset # noqa: E501 :param license_name: The license_name of this DatasetNewRequest. # noqa: E501 :type: str """ allowed_values = ...
[ "def", "license_name", "(", "self", ",", "license_name", ")", ":", "allowed_values", "=", "[", "\"CC0-1.0\"", ",", "\"CC-BY-SA-4.0\"", ",", "\"GPL-2.0\"", ",", "\"ODbL-1.0\"", ",", "\"CC-BY-NC-SA-4.0\"", ",", "\"unknown\"", ",", "\"DbCL-1.0\"", ",", "\"CC-BY-SA-3.0\...
47.75
31.25
def documentation(self, level='first'): """ Return the documentation of the type. By default, this is the first docstring on a top-level term. By setting *level* to `"top"`, the list of all docstrings on top-level terms is returned, including the type's `docstring` value...
[ "def", "documentation", "(", "self", ",", "level", "=", "'first'", ")", ":", "docs", "=", "(", "t", ".", "docstring", "for", "t", "in", "list", "(", "self", ".", "conjunction", ".", "terms", ")", "+", "[", "self", "]", "if", "t", ".", "docstring", ...
36.826087
18.478261
def scatter(x,Ns,start): """ Sample a baseband digital communications waveform at the symbol spacing. Parameters ---------- x : ndarray of the input digital comm signal Ns : number of samples per symbol (bit) start : the array index to start the sampling Returns ------- xI : nd...
[ "def", "scatter", "(", "x", ",", "Ns", ",", "start", ")", ":", "xI", "=", "np", ".", "real", "(", "x", "[", "start", ":", ":", "Ns", "]", ")", "xQ", "=", "np", ".", "imag", "(", "x", "[", "start", ":", ":", "Ns", "]", ")", "return", "xI",...
29.44186
20.325581
def collect_conflicts_between_fragments( context: ValidationContext, conflicts: List[Conflict], cached_fields_and_fragment_names: Dict, compared_fragment_pairs: "PairSet", are_mutually_exclusive: bool, fragment_name1: str, fragment_name2: str, ) -> None: """Collect conflicts between frag...
[ "def", "collect_conflicts_between_fragments", "(", "context", ":", "ValidationContext", ",", "conflicts", ":", "List", "[", "Conflict", "]", ",", "cached_fields_and_fragment_names", ":", "Dict", ",", "compared_fragment_pairs", ":", "\"PairSet\"", ",", "are_mutually_exclus...
32.866667
19
def move_window(pymux, variables): """ Move window to a new index. """ dst_window = variables['<dst-window>'] try: new_index = int(dst_window) except ValueError: raise CommandException('Invalid window index: %r' % (dst_window, )) # Check first whether the index was not yet t...
[ "def", "move_window", "(", "pymux", ",", "variables", ")", ":", "dst_window", "=", "variables", "[", "'<dst-window>'", "]", "try", ":", "new_index", "=", "int", "(", "dst_window", ")", "except", "ValueError", ":", "raise", "CommandException", "(", "'Invalid wi...
32.117647
16.352941
def create(self, **kwargs): """Create a notification.""" body = self.client.create(url=self.base_url, json=kwargs) return body
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "body", "=", "self", ".", "client", ".", "create", "(", "url", "=", "self", ".", "base_url", ",", "json", "=", "kwargs", ")", "return", "body" ]
36
10.4
def page(self, activity_name=values.unset, activity_sid=values.unset, available=values.unset, friendly_name=values.unset, target_workers_expression=values.unset, task_queue_name=values.unset, task_queue_sid=values.unset, page_token=values.unset, page_number=values.uns...
[ "def", "page", "(", "self", ",", "activity_name", "=", "values", ".", "unset", ",", "activity_sid", "=", "values", ".", "unset", ",", "available", "=", "values", ".", "unset", ",", "friendly_name", "=", "values", ".", "unset", ",", "target_workers_expression...
49.023256
24.930233
def array_from_adus_to_electrons_per_second(self, array, gain): """ For an array (in counts) and an exposure time mappers, convert the array to units electrons per second Parameters ---------- array : ndarray The array the values are to be converted from counts to el...
[ "def", "array_from_adus_to_electrons_per_second", "(", "self", ",", "array", ",", "gain", ")", ":", "if", "array", "is", "not", "None", ":", "return", "np", ".", "divide", "(", "gain", "*", "array", ",", "self", ".", "exposure_time_map", ")", "else", ":", ...
36.461538
24.923077
def blog_info(self, blogname): """ Gets the information of the given blog :param blogname: the name of the blog you want to information on. eg: codingjester.tumblr.com :returns: a dict created from the JSON response of information """ url = "/v2...
[ "def", "blog_info", "(", "self", ",", "blogname", ")", ":", "url", "=", "\"/v2/blog/{}/info\"", ".", "format", "(", "blogname", ")", "return", "self", ".", "send_api_request", "(", "\"get\"", ",", "url", ",", "{", "}", ",", "[", "'api_key'", "]", ",", ...
37.545455
19.181818
def cleanup(self): """ Clean up children and remove the directory. Directory will only be removed if the cleanup flag is set. """ for k in self._children: self._children[k].cleanup() if self._cleanup: self.remove(True)
[ "def", "cleanup", "(", "self", ")", ":", "for", "k", "in", "self", ".", "_children", ":", "self", ".", "_children", "[", "k", "]", ".", "cleanup", "(", ")", "if", "self", ".", "_cleanup", ":", "self", ".", "remove", "(", "True", ")" ]
25.636364
15.818182
def get_free_dims(model, visible_dims, fixed_dims): """ work out what the inputs are for plotting (1D or 2D) The visible dimensions are the dimensions, which are visible. the fixed_dims are the fixed dimensions for this. The free_dims are then the visible dims without the fixed dims. """ i...
[ "def", "get_free_dims", "(", "model", ",", "visible_dims", ",", "fixed_dims", ")", ":", "if", "visible_dims", "is", "None", ":", "visible_dims", "=", "np", ".", "arange", "(", "model", ".", "input_dim", ")", "dims", "=", "np", ".", "asanyarray", "(", "vi...
38.533333
16.8
def view_fields(self, *attributes, **options): """ Returns a list with the selected field *attribute* or a list with the dictionaries of the selected field *attributes* for each :class:`Field` *nested* in the `Sequence`. The *attributes* of each :class:`Field` for containers *nested* in...
[ "def", "view_fields", "(", "self", ",", "*", "attributes", ",", "*", "*", "options", ")", ":", "items", "=", "list", "(", ")", "for", "index", ",", "item", "in", "enumerate", "(", "self", ")", ":", "if", "is_container", "(", "item", ")", ":", "# Co...
44.625
21.025
def insertFileParents(self, businput): """ This is a special function for WMAgent only. input block_name: is a child block name. input chils_parent_id_list: is a list of file id of child, parent pair: [[cid1, pid1],[cid2,pid2],[cid3,pid3],...] The requirment for this API...
[ "def", "insertFileParents", "(", "self", ",", "businput", ")", ":", "if", "\"block_name\"", "not", "in", "businput", ".", "keys", "(", ")", "or", "\"child_parent_id_list\"", "not", "in", "businput", ".", "keys", "(", ")", "or", "not", "businput", "[", "\"c...
56.232558
28.418605
def address(random=random, *args, **kwargs): """ A street name plus a number! >>> mock_random.seed(0) >>> address(random=mock_random) '0000 amazingslap boardwalk' >>> address(random=mock_random, capitalize=True) '0000 South Throbbingjump Boulevard' >>> address(random=mock_random, slugif...
[ "def", "address", "(", "random", "=", "random", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "random", ".", "choice", "(", "[", "\"{number}{other_number}{number}{other_number} {street}\"", ",", "\"{number}{other_number} {street}\"", ",", "\"{number...
38.125
12.541667
def clean(self, value): """Clean Cleans and returns the new value Arguments: value {mixed} -- The value to clean Returns: mixed """ # If the value is None and it's optional, return as is if value is None and self._optional: return None # If it's an ANY, there is no reasonable expectation t...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "# If the value is None and it's optional, return as is", "if", "value", "is", "None", "and", "self", ".", "_optional", ":", "return", "None", "# If it's an ANY, there is no reasonable expectation that we know what", "#\t...
22.761905
21.244048
def get_dfa_conjecture(self): """ Utilize the observation table to construct a Mealy Machine. The library used for representing the Mealy Machine is the python bindings of the openFST library (pyFST). Args: None Returns: MealyMachine: A mealy machi...
[ "def", "get_dfa_conjecture", "(", "self", ")", ":", "dfa", "=", "DFA", "(", "self", ".", "alphabet", ")", "for", "s", "in", "self", ".", "observation_table", ".", "sm_vector", ":", "for", "i", "in", "self", ".", "alphabet", ":", "dst", "=", "self", "...
41.2
19.266667
def create_volume(self, availability_zone, size=None, snapshot_id=None): """Create a new volume.""" params = {"AvailabilityZone": availability_zone} if ((snapshot_id is None and size is None) or (snapshot_id is not None and size is not None)): raise ValueError("Please pro...
[ "def", "create_volume", "(", "self", ",", "availability_zone", ",", "size", "=", "None", ",", "snapshot_id", "=", "None", ")", ":", "params", "=", "{", "\"AvailabilityZone\"", ":", "availability_zone", "}", "if", "(", "(", "snapshot_id", "is", "None", "and",...
47.933333
14.466667
def install(self): """ Run the actual installation """ self._start_install() mr_link = self._get_mr_link() # Set up the progress bar pbar = ProgressBar(100, 'Running installation...') pbar.start() mr_j, mr_r = self._ajax(mr_link) # Loop u...
[ "def", "install", "(", "self", ")", ":", "self", ".", "_start_install", "(", ")", "mr_link", "=", "self", ".", "_get_mr_link", "(", ")", "# Set up the progress bar", "pbar", "=", "ProgressBar", "(", "100", ",", "'Running installation...'", ")", "pbar", ".", ...
30.605263
19.342105
def plot_points(points, show=True): """ Plot an (n,3) list of points using matplotlib Parameters ------------- points : (n, 3) float Points in space show : bool If False, will not show until plt.show() is called """ import matplotlib.pyplot as plt from mpl_toolkits.mplot...
[ "def", "plot_points", "(", "points", ",", "show", "=", "True", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", "mpl_toolkits", ".", "mplot3d", "import", "Axes3D", "# NOQA", "points", "=", "np", ".", "asanyarray", "(", "points", ",", ...
25.129032
18.225806
def createClient(self): """Create a UDP connection to Riemann""" server = self.config.get('server', '127.0.0.1') port = self.config.get('port', 5555) def connect(ip): self.protocol = riemann.RiemannUDP(ip, port) self.endpoint = reactor.listenUDP(0, self.protocol)...
[ "def", "createClient", "(", "self", ")", ":", "server", "=", "self", ".", "config", ".", "get", "(", "'server'", ",", "'127.0.0.1'", ")", "port", "=", "self", ".", "config", ".", "get", "(", "'port'", ",", "5555", ")", "def", "connect", "(", "ip", ...
32.833333
17.5
def evaluate_familytree(self, family_tree, image_set): """ Evaluate strategy for the given family tree and return a dict of images to analyze that match the strategy :param family_tree: the family tree to traverse and evaluate :param image_set: list of all images in the context ...
[ "def", "evaluate_familytree", "(", "self", ",", "family_tree", ",", "image_set", ")", ":", "if", "family_tree", "is", "None", "or", "image_set", "is", "None", ":", "raise", "ValueError", "(", "'Cannot execute analysis strategy on None image or image with no familytree dat...
39.3
25.3
def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.symbols = self.symbols.copy() return rv
[ "def", "copy", "(", "self", ")", ":", "rv", "=", "object", ".", "__new__", "(", "self", ".", "__class__", ")", "rv", ".", "__dict__", ".", "update", "(", "self", ".", "__dict__", ")", "rv", ".", "symbols", "=", "self", ".", "symbols", ".", "copy", ...
33.833333
8.666667
def _encode_request(self, request): """Encode a request object""" return pickle.dumps(request_to_dict(request, self.spider), protocol=-1)
[ "def", "_encode_request", "(", "self", ",", "request", ")", ":", "return", "pickle", ".", "dumps", "(", "request_to_dict", "(", "request", ",", "self", ".", "spider", ")", ",", "protocol", "=", "-", "1", ")" ]
50.333333
14.666667
def outputs_of(self, idx, create=False): """ Get a set of the outputs for a given node index. """ if create and not idx in self.edges: self.edges[idx] = set() return self.edges[idx]
[ "def", "outputs_of", "(", "self", ",", "idx", ",", "create", "=", "False", ")", ":", "if", "create", "and", "not", "idx", "in", "self", ".", "edges", ":", "self", ".", "edges", "[", "idx", "]", "=", "set", "(", ")", "return", "self", ".", "edges"...
36.666667
3.166667
def deep_copy(self): '''Return a deep copy of the state''' c = KalmanState(self.observation_matrix, self.translation_matrix) c.state_vec = self.state_vec.copy() c.state_cov = self.state_cov.copy() c.noise_var = self.noise_var.copy() c.state_noise = self.state_noise.copy()...
[ "def", "deep_copy", "(", "self", ")", ":", "c", "=", "KalmanState", "(", "self", ".", "observation_matrix", ",", "self", ".", "translation_matrix", ")", "c", ".", "state_vec", "=", "self", ".", "state_vec", ".", "copy", "(", ")", "c", ".", "state_cov", ...
42.777778
12.555556
def summarize_attr(key, value, col_width=None): """Summary for __repr__ - use ``X.attrs[key]`` for full value.""" # Indent key and add ':', then right-pad if col_width is not None k_str = ' {}:'.format(key) if col_width is not None: k_str = pretty_print(k_str, col_width) # Replace tabs an...
[ "def", "summarize_attr", "(", "key", ",", "value", ",", "col_width", "=", "None", ")", ":", "# Indent key and add ':', then right-pad if col_width is not None", "k_str", "=", "' {}:'", ".", "format", "(", "key", ")", "if", "col_width", "is", "not", "None", ":",...
53.272727
13.909091
def get_profile(self, user_id, timeout=None): """Call get profile API. https://devdocs.line.me/en/#bot-api-get-profile Get user profile information. :param str user_id: User ID :param timeout: (optional) How long to wait for the server to send data before giving up...
[ "def", "get_profile", "(", "self", ",", "user_id", ",", "timeout", "=", "None", ")", ":", "response", "=", "self", ".", "_get", "(", "'/v2/bot/profile/{user_id}'", ".", "format", "(", "user_id", "=", "user_id", ")", ",", "timeout", "=", "timeout", ")", "...
35.045455
17.636364
def from_html(html_style_colour_str: str): """ Parser for KDialog output, which outputs a HTML style hex code like #55aa00 @param html_style_colour_str: HTML style hex string encoded colour. (#rrggbb) @return: ColourData instance @rtype: ColourData """ html_style_...
[ "def", "from_html", "(", "html_style_colour_str", ":", "str", ")", ":", "html_style_colour_str", "=", "html_style_colour_str", ".", "lstrip", "(", "\"#\"", ")", "components", "=", "list", "(", "map", "(", "\"\"", ".", "join", ",", "zip", "(", "*", "[", "it...
50.7
20.1
def links( self, page: 'WikipediaPage', **kwargs ) -> PagesDict: """ Returns links to other pages with respect to parameters API Calls for parameters: - https://www.mediawiki.org/w/api.php?action=help&modules=query%2Blinks - https://www.m...
[ "def", "links", "(", "self", ",", "page", ":", "'WikipediaPage'", ",", "*", "*", "kwargs", ")", "->", "PagesDict", ":", "params", "=", "{", "'action'", ":", "'query'", ",", "'prop'", ":", "'links'", ",", "'titles'", ":", "page", ".", "title", ",", "'...
27.18
18.5
def iterall(Class, session, names=None): """Iterate over all Library rows found in `session`. :param names: Optional sequence of names to filter on. """ names = set(names if names else []) for lib in session.query(Class).filter(Class.id > NULL_LIB_ID).all(): if not na...
[ "def", "iterall", "(", "Class", ",", "session", ",", "names", "=", "None", ")", ":", "names", "=", "set", "(", "names", "if", "names", "else", "[", "]", ")", "for", "lib", "in", "session", ".", "query", "(", "Class", ")", ".", "filter", "(", "Cla...
45.75
10.625
def delete_trigger(self, trigger): """ Deletes from the Alert API the trigger record identified by the ID of the provided `pyowm.alertapi30.trigger.Trigger`, along with all related alerts :param trigger: the `pyowm.alertapi30.trigger.Trigger` object to be deleted :type trigger: ...
[ "def", "delete_trigger", "(", "self", ",", "trigger", ")", ":", "assert", "trigger", "is", "not", "None", "assert", "isinstance", "(", "trigger", ".", "id", ",", "str", ")", ",", "\"Value must be a string\"", "status", ",", "_", "=", "self", ".", "http_cli...
48.133333
18.933333
def dannots2dalignbed2dannotsagg(cfg): """ Aggregate annotations per query step#8 :param cfg: configuration dict """ datatmpd=cfg['datatmpd'] daannotp=f'{datatmpd}/08_dannot.tsv' cfg['daannotp']=daannotp dannotsaggp=cfg['dannotsaggp'] logging.info(basename(daannotp)) if...
[ "def", "dannots2dalignbed2dannotsagg", "(", "cfg", ")", ":", "datatmpd", "=", "cfg", "[", "'datatmpd'", "]", "daannotp", "=", "f'{datatmpd}/08_dannot.tsv'", "cfg", "[", "'daannotp'", "]", "=", "daannotp", "dannotsaggp", "=", "cfg", "[", "'dannotsaggp'", "]", "lo...
41.901639
14.42623
def uses_na_format(station: str) -> bool: """ Returns True if the station uses the North American format, False if the International format """ if station[0] in NA_REGIONS: return True if station[0] in IN_REGIONS: return False if station[:2] in M_NA_REGIONS: return Tr...
[ "def", "uses_na_format", "(", "station", ":", "str", ")", "->", "bool", ":", "if", "station", "[", "0", "]", "in", "NA_REGIONS", ":", "return", "True", "if", "station", "[", "0", "]", "in", "IN_REGIONS", ":", "return", "False", "if", "station", "[", ...
31.714286
12.285714
def windows(self): """Return a list of all open windows. Returns: list: List of FoxPuppet BrowserWindow objects. """ from foxpuppet.windows import BrowserWindow return [ BrowserWindow(self.selenium, handle) for handle in self.selenium.window...
[ "def", "windows", "(", "self", ")", ":", "from", "foxpuppet", ".", "windows", "import", "BrowserWindow", "return", "[", "BrowserWindow", "(", "self", ".", "selenium", ",", "handle", ")", "for", "handle", "in", "self", ".", "selenium", ".", "window_handles", ...
25.076923
20.923077
def offline_plotly_scatter_bubble(df, x='x', y='y', size_col='size', text_col='text', category_col='category', possible_categories=None, filename=None, config={'displaylogo': False}, x...
[ "def", "offline_plotly_scatter_bubble", "(", "df", ",", "x", "=", "'x'", ",", "y", "=", "'y'", ",", "size_col", "=", "'size'", ",", "text_col", "=", "'text'", ",", "category_col", "=", "'category'", ",", "possible_categories", "=", "None", ",", "filename", ...
51.573333
25.693333
def can(obj): """Prepare an object for pickling.""" import_needed = False for cls, canner in iteritems(can_map): if isinstance(cls, string_types): import_needed = True break elif istype(obj, cls): return canner(obj) if import_needed: # perfor...
[ "def", "can", "(", "obj", ")", ":", "import_needed", "=", "False", "for", "cls", ",", "canner", "in", "iteritems", "(", "can_map", ")", ":", "if", "isinstance", "(", "cls", ",", "string_types", ")", ":", "import_needed", "=", "True", "break", "elif", "...
26.277778
16.777778
def clean_regex(regex): """ Escape any regex special characters other than alternation. :param regex: regex from datatables interface :type regex: str :rtype: str with regex to use with database """ # copy for return ret_regex = regex # these characters are escaped (all except alte...
[ "def", "clean_regex", "(", "regex", ")", ":", "# copy for return", "ret_regex", "=", "regex", "# these characters are escaped (all except alternation | and escape \\)", "# see http://www.regular-expressions.info/refquick.html", "escape_chars", "=", "'[^$.?*+(){}'", "# remove any escape...
32.775
19.275
def _installed_packages(self) -> Generator[str, None, None]: """Extract installed packages as list from `package.json`.""" with (self._build_dir / 'package.json').open('r') as f: packages = json.load(f) yield from packages['dependencies'].keys()
[ "def", "_installed_packages", "(", "self", ")", "->", "Generator", "[", "str", ",", "None", ",", "None", "]", ":", "with", "(", "self", ".", "_build_dir", "/", "'package.json'", ")", ".", "open", "(", "'r'", ")", "as", "f", ":", "packages", "=", "jso...
55.4
11.6
def elliptic_fourier_descriptors(contour, order=10, normalize=False): """Calculate elliptical Fourier descriptors for a contour. :param numpy.ndarray contour: A contour array of size ``[M x 2]``. :param int order: The order of Fourier coefficients to calculate. :param bool normalize: If the coefficient...
[ "def", "elliptic_fourier_descriptors", "(", "contour", ",", "order", "=", "10", ",", "normalize", "=", "False", ")", ":", "dxy", "=", "np", ".", "diff", "(", "contour", ",", "axis", "=", "0", ")", "dt", "=", "np", ".", "sqrt", "(", "(", "dxy", "**"...
36.970588
19.058824
def mysql(host, user, passwd, db, charset): """Set MySQL/MariaDB connection""" connection_string = database.set_mysql_connection(host=host, user=user, passwd=passwd, db=db, charset=charset) test_connection(connection_string)
[ "def", "mysql", "(", "host", ",", "user", ",", "passwd", ",", "db", ",", "charset", ")", ":", "connection_string", "=", "database", ".", "set_mysql_connection", "(", "host", "=", "host", ",", "user", "=", "user", ",", "passwd", "=", "passwd", ",", "db"...
58.25
19.75
def negative_binomial(k=1, p=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs): """Draw random samples from a negative binomial distribution. Samples are distributed according to a negative binomial distribution parametrized by *k* (limit of unsuccessful experiments) and *p* ...
[ "def", "negative_binomial", "(", "k", "=", "1", ",", "p", "=", "1", ",", "shape", "=", "_Null", ",", "dtype", "=", "_Null", ",", "ctx", "=", "None", ",", "out", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_random_helper", "(", "_in...
40.666667
22.962963
async def load_by_path(self, path): """ Load a module by full path. If there are dependencies, they are also loaded. """ try: p, module = findModule(path, True) except KeyError as exc: raise ModuleLoadException('Cannot load module ' + repr(path) + ': ' + s...
[ "async", "def", "load_by_path", "(", "self", ",", "path", ")", ":", "try", ":", "p", ",", "module", "=", "findModule", "(", "path", ",", "True", ")", "except", "KeyError", "as", "exc", ":", "raise", "ModuleLoadException", "(", "'Cannot load module '", "+",...
47.846154
22.153846
def decode_name(name, barcodemap): """ rename seq/taxon name, typically for a tree display, according to a barcode map given in a dictionary By definition barcodes should be distinctive. """ for barcode in barcodemap: if barcode in name: return barcodemap[barcode] retur...
[ "def", "decode_name", "(", "name", ",", "barcodemap", ")", ":", "for", "barcode", "in", "barcodemap", ":", "if", "barcode", "in", "name", ":", "return", "barcodemap", "[", "barcode", "]", "return", "name" ]
26.25
14.416667
def create_app_from_template(self, image_name, name, template, name_in_template, other_images=None, oc_new_app_args=None, project=None): """ Helper function to create app from template :param image_name: image to be used as builder image :param name: name...
[ "def", "create_app_from_template", "(", "self", ",", "image_name", ",", "name", ",", "template", ",", "name_in_template", ",", "other_images", "=", "None", ",", "oc_new_app_args", "=", "None", ",", "project", "=", "None", ")", ":", "self", ".", "project", "=...
47.697674
26.627907
def to_dict(self): """Return a dict representation of the person.""" d = {} if self.query_params_match is not None: d['@query_params_match'] = self.query_params_match if self.sources: d['sources'] = [source.to_dict() for source in self.sources] d.update(se...
[ "def", "to_dict", "(", "self", ")", ":", "d", "=", "{", "}", "if", "self", ".", "query_params_match", "is", "not", "None", ":", "d", "[", "'@query_params_match'", "]", "=", "self", ".", "query_params_match", "if", "self", ".", "sources", ":", "d", "[",...
38.777778
16.666667
def _check_devices_active_licensed(self): '''All devices should be in an active/licensed state. :raises: UnexpectedClusterState ''' if len(self._get_devices_by_activation_state('active')) != \ len(self.devices): msg = "One or more devices not in 'Active' and...
[ "def", "_check_devices_active_licensed", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_get_devices_by_activation_state", "(", "'active'", ")", ")", "!=", "len", "(", "self", ".", "devices", ")", ":", "msg", "=", "\"One or more devices not in 'Active' and...
37.8
21
def signal_handler_as(sig, handler): """Temporarily replaces a signal handler for the given signal and restores the old handler. :param int sig: The target signal to replace the handler for (e.g. signal.SIGINT). :param func handler: The new temporary handler. """ old_handler = signal.signal(sig, handler) t...
[ "def", "signal_handler_as", "(", "sig", ",", "handler", ")", ":", "old_handler", "=", "signal", ".", "signal", "(", "sig", ",", "handler", ")", "try", ":", "yield", "finally", ":", "signal", ".", "signal", "(", "sig", ",", "old_handler", ")" ]
33.636364
18.181818
def get_zero_task_agent(generators, market, nOffer, maxSteps): """ Returns a task-agent tuple whose action is always zero. """ env = pyreto.discrete.MarketEnvironment(generators, market, nOffer) task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps) agent = pyreto.util.ZeroAgent(env.outdim, env.i...
[ "def", "get_zero_task_agent", "(", "generators", ",", "market", ",", "nOffer", ",", "maxSteps", ")", ":", "env", "=", "pyreto", ".", "discrete", ".", "MarketEnvironment", "(", "generators", ",", "market", ",", "nOffer", ")", "task", "=", "pyreto", ".", "di...
48.857143
15.428571