text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def record_manifest(self): """ Called after a deployment to record any data necessary to detect changes for a future deployment. """ manifest = super(GitTrackerSatchel, self).record_manifest() manifest[CURRENT_COMMIT] = self.get_current_commit() return manifest
[ "def", "record_manifest", "(", "self", ")", ":", "manifest", "=", "super", "(", "GitTrackerSatchel", ",", "self", ")", ".", "record_manifest", "(", ")", "manifest", "[", "CURRENT_COMMIT", "]", "=", "self", ".", "get_current_commit", "(", ")", "return", "mani...
38.75
15.75
def items(self): """Get an iter of VenvDirs and VenvFiles within the directory.""" contents = self.paths contents = ( VenvFile(path.path) if path.is_file else VenvDir(path.path) for path in contents ) return contents
[ "def", "items", "(", "self", ")", ":", "contents", "=", "self", ".", "paths", "contents", "=", "(", "VenvFile", "(", "path", ".", "path", ")", "if", "path", ".", "is_file", "else", "VenvDir", "(", "path", ".", "path", ")", "for", "path", "in", "con...
34.125
17.75
def clip_by_extent(layer, extent): """Clip a raster using a bounding box using processing. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to clip. :type layer: QgsRasterLayer :param extent: The extent. :type extent: QgsRectangle :return: Clipped layer. :...
[ "def", "clip_by_extent", "(", "layer", ",", "extent", ")", ":", "parameters", "=", "dict", "(", ")", "# noinspection PyBroadException", "try", ":", "output_layer_name", "=", "quick_clip_steps", "[", "'output_layer_name'", "]", "output_layer_name", "=", "output_layer_n...
34.904762
18.085714
def handle(self, **options): """ Command handler. """ self.flushdb = options.get('flushdb') self._pre_tasks() self._create_users() self._create_badges() self._create_awards()
[ "def", "handle", "(", "self", ",", "*", "*", "options", ")", ":", "self", ".", "flushdb", "=", "options", ".", "get", "(", "'flushdb'", ")", "self", ".", "_pre_tasks", "(", ")", "self", ".", "_create_users", "(", ")", "self", ".", "_create_badges", "...
25.555556
9.111111
def process(self, input_data, topic=None, **kwargs): """ Splits tuple received from PacketHandler into packet UID and packet message. Decodes packet and inserts into database backend. Logs any exceptions raised. Params: input_data: message received from inbound stre...
[ "def", "process", "(", "self", ",", "input_data", ",", "topic", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "split", "=", "input_data", "[", "1", ":", "-", "1", "]", ".", "split", "(", "','", ",", "1", ")", "uid", ",", "pkt", ...
44.473684
18.894737
def encode_uvarint(n, data): '''encodes integer into variable-length format into data.''' if n < 0: raise ValueError('only support positive integer') while True: this_byte = n & 127 n >>= 7 if n == 0: data.append(this_byte) break data.append(th...
[ "def", "encode_uvarint", "(", "n", ",", "data", ")", ":", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "'only support positive integer'", ")", "while", "True", ":", "this_byte", "=", "n", "&", "127", "n", ">>=", "7", "if", "n", "==", "0", ":...
29.454545
18
def failed_update(self, exception): """Update cluster state given a failed MetadataRequest.""" f = None with self._lock: if self._future: f = self._future self._future = None if f: f.failure(exception) self._last_refresh_ms ...
[ "def", "failed_update", "(", "self", ",", "exception", ")", ":", "f", "=", "None", "with", "self", ".", "_lock", ":", "if", "self", ".", "_future", ":", "f", "=", "self", ".", "_future", "self", ".", "_future", "=", "None", "if", "f", ":", "f", "...
33.1
11.5
def _make_sj_out_dict(fns, jxns=None, define_sample_name=None): """Read multiple sj_outs, return dict with keys as sample names and values as sj_out dataframes. Parameters ---------- fns : list of strs of filenames or file handles List of filename of the SJ.out.tab files to read in jxn...
[ "def", "_make_sj_out_dict", "(", "fns", ",", "jxns", "=", "None", ",", "define_sample_name", "=", "None", ")", ":", "if", "define_sample_name", "==", "None", ":", "define_sample_name", "=", "lambda", "x", ":", "x", "else", ":", "assert", "len", "(", "set",...
35.382979
21.319149
def contiguous_slice(in1): """ This function unpads an array on the GPU in such a way as to make it contiguous. INPUTS: in1 (no default): Array containing data which has been padded. OUTPUTS: gpu_out1 Array containing unpadded, contiguous data. """ ker = SourceMod...
[ "def", "contiguous_slice", "(", "in1", ")", ":", "ker", "=", "SourceModule", "(", "\"\"\"\n __global__ void contiguous_slice_ker(float *in1, float *out1)\n {\n const int len = gridDim.x*blockDim.x;\n ...
39.305556
30.583333
def _makeResult(self): """Return a Result that doesn't print dots. Nose's ResultProxy will wrap it, and other plugins can still print stuff---but without smashing into our progress bar, care of ProgressivePlugin's stderr/out wrapping. """ return ProgressiveResult(self._...
[ "def", "_makeResult", "(", "self", ")", ":", "return", "ProgressiveResult", "(", "self", ".", "_cwd", ",", "self", ".", "_totalTests", ",", "self", ".", "stream", ",", "config", "=", "self", ".", "config", ")" ]
38.583333
16.416667
def update(self, key, value): """Updates the map by updating the value of a key :type key: :class: '~opencensus.tags.tag_key.TagKey' :param key: A tag key to be updated :type value: :class: '~opencensus.tags.tag_value.TagValue' :param value: The value to update the key to in th...
[ "def", "update", "(", "self", ",", "key", ",", "value", ")", ":", "if", "key", "in", "self", ".", "map", ":", "self", ".", "map", "[", "key", "]", "=", "value" ]
32.416667
18.583333
def error_handler(_, err, arg): """Update the mutable integer `arg` with the error code.""" arg.value = err.error return libnl.handlers.NL_STOP
[ "def", "error_handler", "(", "_", ",", "err", ",", "arg", ")", ":", "arg", ".", "value", "=", "err", ".", "error", "return", "libnl", ".", "handlers", ".", "NL_STOP" ]
38
7.75
def get_event_times(self): """ Return event times of Fault, Breaker and other timed events Returns ------- list A sorted list of event times """ times = [] times.extend(self.Breaker.get_times()) for model in self.__dict__['Event'].al...
[ "def", "get_event_times", "(", "self", ")", ":", "times", "=", "[", "]", "times", ".", "extend", "(", "self", ".", "Breaker", ".", "get_times", "(", ")", ")", "for", "model", "in", "self", ".", "__dict__", "[", "'Event'", "]", ".", "all_models", ":",...
22.75
21.35
def add_group_user(self, group_id, user_id): """ Adds an existing user to a group. :param group_id: The unique ID of the group. :type group_id: ``str`` :param user_id: The unique ID of the user. :type user_id: ``str`` """ data = { ...
[ "def", "add_group_user", "(", "self", ",", "group_id", ",", "user_id", ")", ":", "data", "=", "{", "\"id\"", ":", "user_id", "}", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/um/groups/%s/users'", "%", "group_id", ",", "method", "=...
24.52381
17.190476
def variables(self) -> tuple: """Variables.""" try: assert self._variables is not None except (AssertionError, AttributeError): self._variables = [self[n] for n in self.variable_names] finally: return tuple(self._variables)
[ "def", "variables", "(", "self", ")", "->", "tuple", ":", "try", ":", "assert", "self", ".", "_variables", "is", "not", "None", "except", "(", "AssertionError", ",", "AttributeError", ")", ":", "self", ".", "_variables", "=", "[", "self", "[", "n", "]"...
35.5
13.25
def _score(estimator, X_test, y_test, scorer): """Compute the score of an estimator on a given test set.""" if y_test is None: score = scorer(estimator, X_test) else: score = scorer(estimator, X_test, y_test) if not isinstance(score, numbers.Number): raise ValueError("scoring mus...
[ "def", "_score", "(", "estimator", ",", "X_test", ",", "y_test", ",", "scorer", ")", ":", "if", "y_test", "is", "None", ":", "score", "=", "scorer", "(", "estimator", ",", "X_test", ")", "else", ":", "score", "=", "scorer", "(", "estimator", ",", "X_...
42.2
14.4
def to_query(self, fields=None): """ Return a Query for this Table. Args: fields: the fields to return. If None, all fields will be returned. This can be a string which will be injected into the Query after SELECT, or a list of field names. Returns: A Query object that will return th...
[ "def", "to_query", "(", "self", ",", "fields", "=", "None", ")", ":", "# Do import here to avoid top-level circular dependencies.", "from", ".", "import", "_query", "if", "fields", "is", "None", ":", "fields", "=", "'*'", "elif", "isinstance", "(", "fields", ","...
38.588235
26.294118
def decode_sent_msg(pref, message, pretty=False): """decode_sent_msg: Return a string of the decoded message """ newline = "\n" if pretty else " " indent = " " if pretty else "" start = newline + indent out = [] out.append("%s%s{%sSEQNUM: %d," % (pref, newline, start, message[Const.W_SEQ...
[ "def", "decode_sent_msg", "(", "pref", ",", "message", ",", "pretty", "=", "False", ")", ":", "newline", "=", "\"\\n\"", "if", "pretty", "else", "\" \"", "indent", "=", "\" \"", "if", "pretty", "else", "\"\"", "start", "=", "newline", "+", "indent", "...
59.47619
33.619048
def get_value(self) -> Decimal: """ Returns the current value of stocks """ quantity = self.get_quantity() price = self.get_last_available_price() if not price: # raise ValueError("no price found for", self.full_symbol) return Decimal(0) value = quantity ...
[ "def", "get_value", "(", "self", ")", "->", "Decimal", ":", "quantity", "=", "self", ".", "get_quantity", "(", ")", "price", "=", "self", ".", "get_last_available_price", "(", ")", "if", "not", "price", ":", "# raise ValueError(\"no price found for\", self.full_sy...
34.5
14
def fingerprint(self): """Returns a fingerprint for the identity of the task. A task fingerprint is composed of the options the task is currently running under. Useful for invalidating unchanging targets being executed beneath changing task options that affect outputted artifacts. A task's fingerp...
[ "def", "fingerprint", "(", "self", ")", ":", "hasher", "=", "sha1", "(", ")", "hasher", ".", "update", "(", "self", ".", "stable_name", "(", ")", ".", "encode", "(", "'utf-8'", ")", ")", "hasher", ".", "update", "(", "self", ".", "_options_fingerprint"...
50.1875
26
def SA_tank(D, L, sideA=None, sideB=None, sideA_a=0, sideB_a=0, sideA_f=None, sideA_k=None, sideB_f=None, sideB_k=None, full_output=False): r'''Calculates the surface are of a cylindrical tank with optional heads. In the degenerate case of being provided with only `D` and `L`, provides...
[ "def", "SA_tank", "(", "D", ",", "L", ",", "sideA", "=", "None", ",", "sideB", "=", "None", ",", "sideA_a", "=", "0", ",", "sideB_a", "=", "0", ",", "sideA_f", "=", "None", ",", "sideA_k", "=", "None", ",", "sideB_f", "=", "None", ",", "sideB_k",...
36.291667
21
def request(self, action, data={}, headers={}, method='GET'): """ Append the REST headers to every request """ headers = { "Authorization": "Bearer " + self.token, "Content-Type": "application/json", "X-Version": "1", "Accept": "application...
[ "def", "request", "(", "self", ",", "action", ",", "data", "=", "{", "}", ",", "headers", "=", "{", "}", ",", "method", "=", "'GET'", ")", ":", "headers", "=", "{", "\"Authorization\"", ":", "\"Bearer \"", "+", "self", ".", "token", ",", "\"Content-T...
33
15
def sparse_var(X): ''' Compute variance from :param X: :return: ''' Xc = X.copy() Xc.data **= 2 return np.array(Xc.mean(axis=0) - np.power(X.mean(axis=0), 2))[0]
[ "def", "sparse_var", "(", "X", ")", ":", "Xc", "=", "X", ".", "copy", "(", ")", "Xc", ".", "data", "**=", "2", "return", "np", ".", "array", "(", "Xc", ".", "mean", "(", "axis", "=", "0", ")", "-", "np", ".", "power", "(", "X", ".", "mean",...
20.555556
25.888889
def properties_for(self, index): """ Returns a list of properties, such that each entry in the list corresponds to the element of the index given. Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] >>> properties_for([2,3,5]) [['one'], ['one', 'two'], ['two...
[ "def", "properties_for", "(", "self", ",", "index", ")", ":", "return", "vectorize", "(", "lambda", "i", ":", "[", "prop", "for", "prop", "in", "self", ".", "properties", "(", ")", "if", "i", "in", "self", "[", "prop", "]", "]", ",", "otypes", "=",...
36.5
20.833333
def unseal(self, data, return_options=False): '''Unseal data''' data = self._remove_magic(data) data = urlsafe_nopadding_b64decode(data) options = self._read_header(data) data = self._add_magic(data) data = self._unsign_data(data, options) data = self._remove_mag...
[ "def", "unseal", "(", "self", ",", "data", ",", "return_options", "=", "False", ")", ":", "data", "=", "self", ".", "_remove_magic", "(", "data", ")", "data", "=", "urlsafe_nopadding_b64decode", "(", "data", ")", "options", "=", "self", ".", "_read_header"...
34.111111
12.666667
def empty_like(array, dtype=None, keepmeta=True): """Create an array of empty with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, t...
[ "def", "empty_like", "(", "array", ",", "dtype", "=", "None", ",", "keepmeta", "=", "True", ")", ":", "if", "keepmeta", ":", "return", "dc", ".", "empty", "(", "array", ".", "shape", ",", "dtype", ",", "tcoords", "=", "array", ".", "dca", ".", "tco...
42.142857
23.238095
def inserir(self, name, id_equipment_type, id_model, id_group, maintenance=False): """Inserts a new Equipment and returns its identifier Além de inserir o equipamento, a networkAPI também associa o equipamento ao grupo informado. :param name: Equipment name. String with a minimum 3 and...
[ "def", "inserir", "(", "self", ",", "name", ",", "id_equipment_type", ",", "id_model", ",", "id_group", ",", "maintenance", "=", "False", ")", ":", "equip_map", "=", "dict", "(", ")", "equip_map", "[", "'id_tipo_equipamento'", "]", "=", "id_equipment_type", ...
45.658537
28.585366
async def workerTypeStats(self, *args, **kwargs): """ Look up the resource stats for a workerType Return an object which has a generic state description. This only contains counts of instances This method gives output: ``v1/worker-type-resources.json#`` This method is ``experi...
[ "async", "def", "workerTypeStats", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"workerTypeStats\"", "]", ",", "*", "args", ",", "*", "*", "kwargs...
35
26.666667
def Update(self, size): ''' Custom wrapper calculator to account for the increased size of the _msg widget after being inlined with the wx.CheckBox ''' if self._msg is None: return help_msg = self._msg width, height = size content_area = int((width / 3) * .70) wiggle_room ...
[ "def", "Update", "(", "self", ",", "size", ")", ":", "if", "self", ".", "_msg", "is", "None", ":", "return", "help_msg", "=", "self", ".", "_msg", "width", ",", "height", "=", "size", "content_area", "=", "int", "(", "(", "width", "/", "3", ")", ...
33.8125
20.3125
def get_dataset(ds,dataDir,removecompressed=1): """ A function which attempts downloads and uncompresses the latest version of an openfmri.fmri dataset. PARAMETERS :ds: dataset number of the openfMRI.org dataset (integer) without zero padding. I.e. can just be 212 (doesn't need to be 000212). :da...
[ "def", "get_dataset", "(", "ds", ",", "dataDir", ",", "removecompressed", "=", "1", ")", ":", "#Convert input ds to string incase it is put in via function", "ds", "=", "str", "(", "ds", ")", "#The final character of the dataset can be a letter", "lettersuffix", "=", "''"...
44.9
30.585714
def notimplemented (func): """Raises a NotImplementedError if the function is called.""" def newfunc (*args, **kwargs): """Raise NotImplementedError""" co = func.func_code attrs = (co.co_name, co.co_filename, co.co_firstlineno) raise NotImplementedError("function %s at %s:%d is n...
[ "def", "notimplemented", "(", "func", ")", ":", "def", "newfunc", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Raise NotImplementedError\"\"\"", "co", "=", "func", ".", "func_code", "attrs", "=", "(", "co", ".", "co_name", ",", "co", ".", ...
47.5
12.75
def scale_xy(self, x=0, y=None): """Scale element separately across the two axes x and y. If y is not provided, it is assumed equal to x (according to the W3 specification). Parameters ---------- x : float x-axis scaling factor. To scale down x < 1, s...
[ "def", "scale_xy", "(", "self", ",", "x", "=", "0", ",", "y", "=", "None", ")", ":", "self", ".", "root", ".", "set", "(", "\"transform\"", ",", "\"%s scale(%f %f)\"", "%", "(", "self", ".", "root", ".", "get", "(", "\"transform\"", ")", "or", "''"...
37.5
19.9375
def get_banks_by_assessment_taken(self, assessment_taken_id): """Gets the list of ``Banks`` mapped to an ``AssessmentTaken``. arg: assessment_taken_id (osid.id.Id): ``Id`` of an ``AssessmentTaken`` return: (osid.assessment.BankList) - list of banks raise: NotFound - ...
[ "def", "get_banks_by_assessment_taken", "(", "self", ",", "assessment_taken_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinSession.get_bins_by_resource", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'ASSESSMENT'", ",", "local", "=", "...
51.368421
20.315789
def c2r(self): """Get real matrix from complex one suitable for solving complex linear system with real solver. For matrix :math:`M(i_1,j_1,\\ldots,i_d,j_d) = \\Re M + i\\Im M` returns (d+1)-dimensional matrix :math:`\\tilde{M}(i_1,j_1,\\ldots,i_d,j_d,i_{d+1},j_{d+1})` of form :math:`\\...
[ "def", "c2r", "(", "self", ")", ":", "return", "matrix", "(", "a", "=", "self", ".", "tt", ".", "__complex_op", "(", "'M'", ")", ",", "n", "=", "_np", ".", "concatenate", "(", "(", "self", ".", "n", ",", "[", "2", "]", ")", ")", ",", "m", "...
52.777778
30.944444
def get_edgestore_handle( client: arango.client.ArangoClient, username=None, password=None, edgestore_db_name: str = edgestore_db_name, edgestore_edges_name: str = edgestore_edges_name, edgestore_nodes_name: str = edgestore_nodes_name, edgestore_pipeline_name: str = edgestore_pipeline_name, ...
[ "def", "get_edgestore_handle", "(", "client", ":", "arango", ".", "client", ".", "ArangoClient", ",", "username", "=", "None", ",", "password", "=", "None", ",", "edgestore_db_name", ":", "str", "=", "edgestore_db_name", ",", "edgestore_edges_name", ":", "str", ...
36.155556
22.8
def getheaderAnim(self, im): """ getheaderAnim(im) Get animation header. To replace PILs getheader()[0] """ bb = "GIF89a" bb += intToBin(im.size[0]) bb += intToBin(im.size[1]) bb += "\x87\x00\x00" return bb
[ "def", "getheaderAnim", "(", "self", ",", "im", ")", ":", "bb", "=", "\"GIF89a\"", "bb", "+=", "intToBin", "(", "im", ".", "size", "[", "0", "]", ")", "bb", "+=", "intToBin", "(", "im", ".", "size", "[", "1", "]", ")", "bb", "+=", "\"\\x87\\x00\\...
23.818182
16.181818
def rsys2dot(rsys, tex=False, rprefix='r', rref0=1, nodeparams='[label="{}",shape=diamond]', colors=('maroon', 'darkgreen'), penwidths=None, include_inactive=True): """ Returns list of lines of DOT (graph description language) formated graph. Parameters ========== rsys: ReactionSys...
[ "def", "rsys2dot", "(", "rsys", ",", "tex", "=", "False", ",", "rprefix", "=", "'r'", ",", "rref0", "=", "1", ",", "nodeparams", "=", "'[label=\"{}\",shape=diamond]'", ",", "colors", "=", "(", "'maroon'", ",", "'darkgreen'", ")", ",", "penwidths", "=", "...
34.797468
19.835443
def save(name, data, rc_file='~/.odoorpcrc'): """Save the `data` session configuration under the name `name` in the `rc_file` file. >>> import odoorpc >>> odoorpc.session.save( ... 'foo', ... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc', ... 'port': 8069, 'timeou...
[ "def", "save", "(", "name", ",", "data", ",", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "if", "not", "conf"...
35.09375
17.5
def find_first_TP(self): """ Find first TP of the TPAGB phase and returns the model number at its LHe maximum. Parameters ---------- """ star_mass = self.get('star_mass') he_lumi = self.get('log_LHe') h_lumi = self....
[ "def", "find_first_TP", "(", "self", ")", ":", "star_mass", "=", "self", ".", "get", "(", "'star_mass'", ")", "he_lumi", "=", "self", ".", "get", "(", "'log_LHe'", ")", "h_lumi", "=", "self", ".", "get", "(", "'log_LH'", ")", "mx2_bot", "=", "self", ...
37.596154
19.596154
def roster(self, year): """Returns the roster table for the given year. :year: The year for which we want the roster; defaults to current year. :returns: A DataFrame containing roster information for that year. """ doc = self.get_year_doc('{}_roster'.format(year)) roster...
[ "def", "roster", "(", "self", ",", "year", ")", ":", "doc", "=", "self", ".", "get_year_doc", "(", "'{}_roster'", ".", "format", "(", "year", ")", ")", "roster_table", "=", "doc", "(", "'table#games_played_team'", ")", "df", "=", "sportsref", ".", "utils...
47.35
19.25
def __format_filters(filters): """ Format filters for the api query (to filter[<filter-name>]) :param filters: dict: can be None, filters for the query :return: the formatted filters, or None """ if filters is not None: for k in filters: if 'f...
[ "def", "__format_filters", "(", "filters", ")", ":", "if", "filters", "is", "not", "None", ":", "for", "k", "in", "filters", ":", "if", "'filter['", "not", "in", "k", ":", "filters", "[", "'filter[{}]'", ".", "format", "(", "k", ")", "]", "=", "filte...
34.833333
14.666667
def data_to_binary(self): """ :return: bytes """ return bytes([ COMMAND_CODE, int(self.temp_type), int(self.temp) ])
[ "def", "data_to_binary", "(", "self", ")", ":", "return", "bytes", "(", "[", "COMMAND_CODE", ",", "int", "(", "self", ".", "temp_type", ")", ",", "int", "(", "self", ".", "temp", ")", "]", ")" ]
20.444444
13.111111
def _serialize_model_helper(self, model, field_dict=None): """ A recursive function for serializing a model into a json ready format. """ field_dict = field_dict or self.dot_field_list_to_dict() if model is None: return None if isinstance(model, Query...
[ "def", "_serialize_model_helper", "(", "self", ",", "model", ",", "field_dict", "=", "None", ")", ":", "field_dict", "=", "field_dict", "or", "self", ".", "dot_field_list_to_dict", "(", ")", "if", "model", "is", "None", ":", "return", "None", "if", "isinstan...
33.136364
16.590909
def decode(self): "Decode self.buffer, populating instance variables and return self." buflen = len(self.buffer) tftpassert(buflen >= 4, "malformed ERR packet, too short") log.debug("Decoding ERR packet, length %s bytes", buflen) if buflen == 4: log.debug("Allowing th...
[ "def", "decode", "(", "self", ")", ":", "buflen", "=", "len", "(", "self", ".", "buffer", ")", "tftpassert", "(", "buflen", ">=", "4", ",", "\"malformed ERR packet, too short\"", ")", "log", ".", "debug", "(", "\"Decoding ERR packet, length %s bytes\"", ",", "...
51.65
22.75
def addResource(self, key, filePath, text): """ The add resource operation allows the administrator to add a file resource, for example, the organization's logo or custom banner. The resource can be used by any member of the organization. File resources use storage space from you...
[ "def", "addResource", "(", "self", ",", "key", ",", "filePath", ",", "text", ")", ":", "url", "=", "self", ".", "root", "+", "\"/addresource\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"token\"", ":", "self", ".", "_securityHandler", ".", ...
37.032258
18.451613
def validate(cls, cpf): u""" Válida o CPF. >>> CPF.validate(58119443659) True >>> CPF.validate(58119443650) False >>> CPF.validate('58119443659') True >>> CPF.validate('581.194.436-59') True """ if cpf is None: ...
[ "def", "validate", "(", "cls", ",", "cpf", ")", ":", "if", "cpf", "is", "None", ":", "return", "False", "cpf", "=", "CPF", ".", "clean", "(", "cpf", ")", "def", "mod11", "(", "value", ")", ":", "return", "(", "value", "%", "11", ")", "%", "10",...
23.92
19.64
def parse_arg(arg): """ Parses arguments for convenience. Argument can be a csv list ('a,b,c'), a string, a list, a tuple. Returns a list. """ # handle string input if type(arg) == str: arg = arg.strip() # parse csv as tickers and create children if ',' in arg: ...
[ "def", "parse_arg", "(", "arg", ")", ":", "# handle string input", "if", "type", "(", "arg", ")", "==", "str", ":", "arg", "=", "arg", ".", "strip", "(", ")", "# parse csv as tickers and create children", "if", "','", "in", "arg", ":", "arg", "=", "arg", ...
25.421053
16.684211
def _view_clear_queue(self, queue_type, queue_id): """remove queueu from SharQ based on the queue_type and queue_id.""" response = { 'status': 'failure' } try: request_data = json.loads(request.data) except Exception, e: response['message'] = e...
[ "def", "_view_clear_queue", "(", "self", ",", "queue_type", ",", "queue_id", ")", ":", "response", "=", "{", "'status'", ":", "'failure'", "}", "try", ":", "request_data", "=", "json", ".", "loads", "(", "request", ".", "data", ")", "except", "Exception", ...
31.681818
14.590909
def datetime_f(dttm): """Formats datetime to take less room when it is recent""" if dttm: dttm = dttm.isoformat() now_iso = datetime.now().isoformat() if now_iso[:10] == dttm[:10]: dttm = dttm[11:] elif now_iso[:4] == dttm[:4]: dttm = dttm[5:] return '...
[ "def", "datetime_f", "(", "dttm", ")", ":", "if", "dttm", ":", "dttm", "=", "dttm", ".", "isoformat", "(", ")", "now_iso", "=", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", ")", "if", "now_iso", "[", ":", "10", "]", "==", "dttm", "[",...
34
9.2
def _merge_simple_selectors(a, b): """Merge two simple selectors, for the purposes of the LCS algorithm below. In practice this returns the more specific selector if one is a subset of the other, else it returns None. """ # TODO what about combinators if a.is_superset_of(b): return b ...
[ "def", "_merge_simple_selectors", "(", "a", ",", "b", ")", ":", "# TODO what about combinators", "if", "a", ".", "is_superset_of", "(", "b", ")", ":", "return", "b", "elif", "b", ".", "is_superset_of", "(", "a", ")", ":", "return", "a", "else", ":", "ret...
29.384615
16.769231
def _prune_hit(hit, model): """ Check whether a document should be pruned. This method uses the SearchDocumentManagerMixin.in_search_queryset method to determine whether a 'hit' (search document) should be pruned from an index, and if so it returns the hit as a Django object(id=hit_id). Args: ...
[ "def", "_prune_hit", "(", "hit", ",", "model", ")", ":", "hit_id", "=", "hit", "[", "\"_id\"", "]", "hit_index", "=", "hit", "[", "\"_index\"", "]", "if", "model", ".", "objects", ".", "in_search_queryset", "(", "hit_id", ",", "index", "=", "hit_index", ...
38.421053
26.263158
def callgrind(self, out, filename=None, commandline=None, relative_path=False): """ Dump statistics in callgrind format. Contains: - per-line hit count, time and time-per-hit - call associations (call tree) Note: hit count is not inclusive, in that it is not the sum of ...
[ "def", "callgrind", "(", "self", ",", "out", ",", "filename", "=", "None", ",", "commandline", "=", "None", ",", "relative_path", "=", "False", ")", ":", "print", "(", "u'# callgrind format'", ",", "file", "=", "out", ")", "print", "(", "u'version: 1'", ...
48.954545
16.518182
def assertion(func): """Extend sure with a custom assertion method.""" func = assertionmethod(func) setattr(AssertionBuilder, func.__name__, func) return func
[ "def", "assertion", "(", "func", ")", ":", "func", "=", "assertionmethod", "(", "func", ")", "setattr", "(", "AssertionBuilder", ",", "func", ".", "__name__", ",", "func", ")", "return", "func" ]
34
12.6
def collect_info(self): """ Collect info about the connection and fill the info dictionary. """ try: info = {} res = self._send_request('GET', "/") info['server'] = {} info['server']['name'] = res['name'] info['server']['version...
[ "def", "collect_info", "(", "self", ")", ":", "try", ":", "info", "=", "{", "}", "res", "=", "self", ".", "_send_request", "(", "'GET'", ",", "\"/\"", ")", "info", "[", "'server'", "]", "=", "{", "}", "info", "[", "'server'", "]", "[", "'name'", ...
32.277778
13.722222
def get_interpolated(self, target, extent): """ Return a new vector that has been moved towards the given target by the given extent. The extent should be between 0 and 1. """ result = self.copy() result.interpolate(target, extent) return result
[ "def", "get_interpolated", "(", "self", ",", "target", ",", "extent", ")", ":", "result", "=", "self", ".", "copy", "(", ")", "result", ".", "interpolate", "(", "target", ",", "extent", ")", "return", "result" ]
47
6
def _ReadPropertySet(self, property_set): """Reads properties from a property set. Args: property_set (pyolecf.property_set): OLECF property set. """ # Combine the values of multiple property sections # but do not override properties that are already set. for property_section in property_...
[ "def", "_ReadPropertySet", "(", "self", ",", "property_set", ")", ":", "# Combine the values of multiple property sections", "# but do not override properties that are already set.", "for", "property_section", "in", "property_set", ".", "sections", ":", "if", "property_section", ...
39.228571
17.714286
def from_thread(cls,thread): """Convert a vanilla thread object into an instance of this class. This method "upgrades" a vanilla thread object to an instance of this extended class. You might need to call this if you obtain a reference to a thread by some means other than (a) creating ...
[ "def", "from_thread", "(", "cls", ",", "thread", ")", ":", "new_classes", "=", "[", "]", "for", "new_cls", "in", "cls", ".", "__mro__", ":", "if", "new_cls", "not", "in", "thread", ".", "__class__", ".", "__mro__", ":", "new_classes", ".", "append", "(...
40
14.791667
def set_shaders(self, vert, frag): """ This function takes care of setting the shading code and compiling+linking it into a working program object that is ready to use. """ self._linked = False # Create temporary shader objects vert_handle = gl.glCreateShader(gl.G...
[ "def", "set_shaders", "(", "self", ",", "vert", ",", "frag", ")", ":", "self", ".", "_linked", "=", "False", "# Create temporary shader objects", "vert_handle", "=", "gl", ".", "glCreateShader", "(", "gl", ".", "GL_VERTEX_SHADER", ")", "frag_handle", "=", "gl"...
50.225
16.15
def get_percentage_lattice_parameter_changes(self): """ Returns the percentage lattice parameter changes. Returns: A dict of the percentage change in lattice parameter, e.g., {'a': 0.012, 'b': 0.021, 'c': -0.031} implies a change of 1.2%, 2.1% and -3.1% in th...
[ "def", "get_percentage_lattice_parameter_changes", "(", "self", ")", ":", "initial_latt", "=", "self", ".", "initial", ".", "lattice", "final_latt", "=", "self", ".", "final", ".", "lattice", "d", "=", "{", "l", ":", "getattr", "(", "final_latt", ",", "l", ...
41
18.142857
def response_to_dict(self): """This method helps in returning the output JSON data from the URL and also it helps in converting the XML output/response (string) to a JSON object Returns: data (dict): JSON data from the output/response """ try: ret...
[ "def", "response_to_dict", "(", "self", ")", ":", "try", ":", "return", "json", ".", "loads", "(", "self", ".", "incidents_data", ".", "text", ")", "except", "Exception", ":", "return", "json", ".", "loads", "(", "json", ".", "dumps", "(", "xmltodict", ...
36.615385
17.846154
def add_data(self, minimum_address, maximum_address, data, overwrite): """Add given data to this segment. The added data must be adjacent to the current segment data, otherwise an exception is thrown. """ if minimum_address == self.maximum_address: self.maximum_address = ma...
[ "def", "add_data", "(", "self", ",", "minimum_address", ",", "maximum_address", ",", "data", ",", "overwrite", ")", ":", "if", "minimum_address", "==", "self", ".", "maximum_address", ":", "self", ".", "maximum_address", "=", "maximum_address", "self", ".", "d...
39.642857
17.738095
def calculate_rate(phone_number, address_country_code=None, address_exception=None): """ Calculates the VAT rate based on a telephone number :param phone_number: The string phone number, in international format with leading + :param address_country_code: The user's country_code, as det...
[ "def", "calculate_rate", "(", "phone_number", ",", "address_country_code", "=", "None", ",", "address_exception", "=", "None", ")", ":", "if", "not", "phone_number", ":", "raise", "ValueError", "(", "'No phone number provided'", ")", "if", "not", "isinstance", "("...
36.788732
26.985915
def name(self): """ Return the String assosciated with the tag name """ if self.m_name == -1 or (self.m_event != START_TAG and self.m_event != END_TAG): return '' return self.sb[self.m_name]
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "m_name", "==", "-", "1", "or", "(", "self", ".", "m_event", "!=", "START_TAG", "and", "self", ".", "m_event", "!=", "END_TAG", ")", ":", "return", "''", "return", "self", ".", "sb", "[", "...
29.5
19
def handle_response(self, msg, address): """Deal with incoming response packets. All answers are held in the cache, and listeners are notified.""" now = current_time_millis() sigs = [] precache = [] for record in msg.answers: if isinstance(record, DNSSignat...
[ "def", "handle_response", "(", "self", ",", "msg", ",", "address", ")", ":", "now", "=", "current_time_millis", "(", ")", "sigs", "=", "[", "]", "precache", "=", "[", "]", "for", "record", "in", "msg", ".", "answers", ":", "if", "isinstance", "(", "r...
38.882353
11.741176
def dispatch(self, request, *args, **kwargs): """Validate if user can use view""" if False: # TODO do permission check based on Model raise PermissionDenied return super().dispatch(request, *args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "False", ":", "# TODO do permission check based on Model", "raise", "PermissionDenied", "return", "super", "(", ")", ".", "dispatch", "(", "request", "...
47.8
9.6
def reboot(name, **kwargs): ''' Reboot a domain via ACPI request :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versionadded:: 2019.2.0 :param p...
[ "def", "reboot", "(", "name", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__get_conn", "(", "*", "*", "kwargs", ")", "ret", "=", "_get_domain", "(", "conn", ",", "name", ")", ".", "reboot", "(", "libvirt", ".", "VIR_DOMAIN_REBOOT_DEFAULT", ")", ...
24.88
24.56
def wf_info(workflow_path): """ Returns the version of the file and the file extension. Assumes that the file path is to the file directly ie, ends with a valid file extension.Supports checking local files as well as files at http:// and https:// locations. Files at these remote locations are recreated...
[ "def", "wf_info", "(", "workflow_path", ")", ":", "supported_formats", "=", "[", "'py'", ",", "'wdl'", ",", "'cwl'", "]", "file_type", "=", "workflow_path", ".", "lower", "(", ")", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "# Grab the file exten...
56.241379
32.172414
def oauth_authenticate(client_id, user, require_existing_link=False): """Authenticate an oauth authorized callback. :param client_id: The client id. :param user: A user instance. :param require_existing_link: If ``True``, check if remote account exists. (Default: ``False``) :returns: ``True...
[ "def", "oauth_authenticate", "(", "client_id", ",", "user", ",", "require_existing_link", "=", "False", ")", ":", "# Authenticate via the access token (access token used to get user_id)", "if", "not", "requires_confirmation", "(", "user", ")", ":", "after_this_request", "("...
39.8
14.3
def _get_subcounters(self, elapsed): """ Args: elapsed(float): Time since started. Returns: :py:class:`tuple`: list of subcounters and dictionary of additional fields Each subcounter in the list will be in a tuple of (subcounter, percentage) Fields in th...
[ "def", "_get_subcounters", "(", "self", ",", "elapsed", ")", ":", "fields", "=", "{", "}", "subcounters", "=", "[", "]", "for", "num", ",", "subcounter", "in", "enumerate", "(", "self", ".", "_subcounters", ",", "1", ")", ":", "if", "self", ".", "tot...
34.340426
25.744681
def threaded(callback, listargs): """ Returns the result of <callback> for each set of \*args in listargs. Each call to <callback> is called concurrently in their own separate threads. Parameters: callback (func): Callback function to apply to each set of \*args. listargs (l...
[ "def", "threaded", "(", "callback", ",", "listargs", ")", ":", "threads", ",", "results", "=", "[", "]", ",", "[", "]", "job_is_done_event", "=", "Event", "(", ")", "for", "args", "in", "listargs", ":", "args", "+=", "[", "results", ",", "len", "(", ...
39.681818
18.454545
def in_global_expression(self): """Currently inside an expression""" return (self.parenthesis_count == 0 and self.curly_bracket_count == 0 and self.square_bracket_count == 0 and not self.in_single_quote and not self.in_double_quote)
[ "def", "in_global_expression", "(", "self", ")", ":", "return", "(", "self", ".", "parenthesis_count", "==", "0", "and", "self", ".", "curly_bracket_count", "==", "0", "and", "self", ".", "square_bracket_count", "==", "0", "and", "not", "self", ".", "in_sing...
55.2
18
def update_queue(self): """Update queue""" started = 0 for parent_id, threadlist in list(self.started_threads.items()): still_running = [] for thread in threadlist: if thread.isFinished(): end_callback = self.end_callbacks.pop(id...
[ "def", "update_queue", "(", "self", ")", ":", "started", "=", "0", "for", "parent_id", ",", "threadlist", "in", "list", "(", "self", ".", "started_threads", ".", "items", "(", ")", ")", ":", "still_running", "=", "[", "]", "for", "thread", "in", "threa...
46.032258
15.096774
def block_idxmat_sets(idxmat, b): """Reshapes idxmat into the idx vectors for the training set and validation set Parameters: ----------- idxmat : ndarray Matrix with N shuffled row indicies assigned to K blocks/columns from the oxyba.block_idxmat_shuffle function b : int T...
[ "def", "block_idxmat_sets", "(", "idxmat", ",", "b", ")", ":", "import", "numpy", "as", "np", "idx_train", "=", "idxmat", "[", ":", ",", "[", "c", "for", "c", "in", "range", "(", "idxmat", ".", "shape", "[", "1", "]", ")", "if", "c", "is", "not",...
31.764706
22.529412
def restore_state(self, system): """Called after unpickling to restore some attributes manually.""" Impl.restore_state(self, system) BaseSpaceContainerImpl.restore_state(self, system) mapping = {} for node in self.cellgraph: if isinstance(node, tuple): ...
[ "def", "restore_state", "(", "self", ",", "system", ")", ":", "Impl", ".", "restore_state", "(", "self", ",", "system", ")", "BaseSpaceContainerImpl", ".", "restore_state", "(", "self", ",", "system", ")", "mapping", "=", "{", "}", "for", "node", "in", "...
39
11.857143
def EnableNetworkInterfaces( self, interfaces, logger, dhclient_script=None): """Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path ...
[ "def", "EnableNetworkInterfaces", "(", "self", ",", "interfaces", ",", "logger", ",", "dhclient_script", "=", "None", ")", ":", "helpers", ".", "CallDhclient", "(", "interfaces", ",", "logger", ",", "dhclient_script", "=", "dhclient_script", ")" ]
43.5
22.9
def _validate_default_privileges(object_type, defprivs, defprivileges): ''' Validate the supplied privileges ''' if object_type != 'group': _defperms = [_DEFAULT_PRIVILEGES_MAP[defperm] for defperm in _DEFAULT_PRIVILEGE_TYPE_MAP[object_type]] _defperms.append('ALL') ...
[ "def", "_validate_default_privileges", "(", "object_type", ",", "defprivs", ",", "defprivileges", ")", ":", "if", "object_type", "!=", "'group'", ":", "_defperms", "=", "[", "_DEFAULT_PRIVILEGES_MAP", "[", "defperm", "]", "for", "defperm", "in", "_DEFAULT_PRIVILEGE_...
39.636364
19.727273
def gradients(ys, xs, grad_ys=None): """Compute gradients in dtf. Args: ys: a list of Tensors xs: a list of Tensors grad_ys: an optional list of Tensors Returns: grad_xs: a list of Tensors """ graph = ys[0].graph if not grad_ys: grad_ys = [Constant(y.mesh, 1.0, y.shape, y.dtype).output...
[ "def", "gradients", "(", "ys", ",", "xs", ",", "grad_ys", "=", "None", ")", ":", "graph", "=", "ys", "[", "0", "]", ".", "graph", "if", "not", "grad_ys", ":", "grad_ys", "=", "[", "Constant", "(", "y", ".", "mesh", ",", "1.0", ",", "y", ".", ...
35
15.090909
def generate_permutations(elements, n): """ Heap's algorithm for generating all n! permutations in a list https://en.wikipedia.org/wiki/Heap%27s_algorithm """ c = [0] * n yield elements i = 0 while i < n: if c[i] < i: if i % 2 == 0: elements[0], eleme...
[ "def", "generate_permutations", "(", "elements", ",", "n", ")", ":", "c", "=", "[", "0", "]", "*", "n", "yield", "elements", "i", "=", "0", "while", "i", "<", "n", ":", "if", "c", "[", "i", "]", "<", "i", ":", "if", "i", "%", "2", "==", "0"...
26
20.095238
def go_to_line(self, line=None): """Go to line dialog""" if line is not None: # When this method is called from the flileswitcher, a line # number is specified, so there is no need for the dialog. self.get_current_editor().go_to_line(line) else: ...
[ "def", "go_to_line", "(", "self", ",", "line", "=", "None", ")", ":", "if", "line", "is", "not", "None", ":", "# When this method is called from the flileswitcher, a line\r", "# number is specified, so there is no need for the dialog.\r", "self", ".", "get_current_editor", ...
43.888889
17.666667
def checkCompatibleParams(initialParams, laterParams): """ Check a later set of BLAST parameters against those originally found. @param initialParams: A C{dict} with the originally encountered BLAST parameter settings. @param laterParams: A C{dict} with BLAST parameter settings encountered ...
[ "def", "checkCompatibleParams", "(", "initialParams", ",", "laterParams", ")", ":", "# Note that although the params contains a 'date', its value is empty", "# (as far as I've seen). This could become an issue one day if it", "# becomes non-empty and differs between JSON files that we cat", "#...
44.257143
21.971429
def get_event_tags_from_dn(dn): """ This grabs the event tags from the dn designator. They look like this: uni/tn-DataDog/ap-DtDg-AP1-EcommerceApp/epg-DtDg-Ecomm/HDl2IngrPktsAg1h """ tags = [] node = get_node_from_dn(dn) if node: tags.append("node:" + node) app = get_app_from_dn(...
[ "def", "get_event_tags_from_dn", "(", "dn", ")", ":", "tags", "=", "[", "]", "node", "=", "get_node_from_dn", "(", "dn", ")", "if", "node", ":", "tags", ".", "append", "(", "\"node:\"", "+", "node", ")", "app", "=", "get_app_from_dn", "(", "dn", ")", ...
26.2
16.68
def get_domain_and_name(self, domain_or_name): """ Given a ``str`` or :class:`boto.sdb.domain.Domain`, return a ``tuple`` with the following members (in order): * In instance of :class:`boto.sdb.domain.Domain` for the requested domain * The domain's...
[ "def", "get_domain_and_name", "(", "self", ",", "domain_or_name", ")", ":", "if", "(", "isinstance", "(", "domain_or_name", ",", "Domain", ")", ")", ":", "return", "(", "domain_or_name", ",", "domain_or_name", ".", "name", ")", "else", ":", "return", "(", ...
40.434783
20.347826
def parse_cli_args(): """parse args from the CLI and return a dict""" parser = argparse.ArgumentParser(description='2048 in your terminal') parser.add_argument('--mode', dest='mode', type=str, default=None, help='colors mode (dark or light)') parser.add_argument('--az', dest='azm...
[ "def", "parse_cli_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'2048 in your terminal'", ")", "parser", ".", "add_argument", "(", "'--mode'", ",", "dest", "=", "'mode'", ",", "type", "=", "str", ",", "defa...
59.166667
22.083333
def set_all_pattern_variables(self, patternnumber, \ sp0, ti0, sp1, ti1, sp2, ti2, sp3, ti3, sp4, ti4, sp5, ti5, sp6, ti6, sp7, ti7, \ actual_step, additional_cycles, link_pattern): """Set all variables for a given pattern at one time. Args: * patternnumber (integer): 0-7 ...
[ "def", "set_all_pattern_variables", "(", "self", ",", "patternnumber", ",", "sp0", ",", "ti0", ",", "sp1", ",", "ti1", ",", "sp2", ",", "ti2", ",", "sp3", ",", "ti3", ",", "sp4", ",", "ti4", ",", "sp5", ",", "ti5", ",", "sp6", ",", "ti6", ",", "s...
51.914286
19.514286
def refresh(self): """ Even though blocks never change, you freshly obtain its contents from an API with this method """ block = self.blockchain.rpc.get_block(self.identifier) if not block: raise BlockDoesNotExistsException super(Block, self).__init__( ...
[ "def", "refresh", "(", "self", ")", ":", "block", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_block", "(", "self", ".", "identifier", ")", "if", "not", "block", ":", "raise", "BlockDoesNotExistsException", "super", "(", "Block", ",", "self", ")...
39.9
14.4
def shape(self): """Total spaces per axis, computed recursively. The recursion ends at the fist level that does not have a shape. Examples -------- >>> r2, r3 = odl.rn(2), odl.rn(3) >>> pspace = odl.ProductSpace(r2, r3) >>> pspace.shape (2,) >>> ...
[ "def", "shape", "(", "self", ")", ":", "if", "len", "(", "self", ")", "==", "0", ":", "return", "(", ")", "elif", "self", ".", "is_power_space", ":", "try", ":", "sub_shape", "=", "self", "[", "0", "]", ".", "shape", "except", "AttributeError", ":"...
25.909091
18.757576
def encodeUcs2(text): """ UCS2 text encoding algorithm Encodes the specified text string into UCS2-encoded bytes. :param text: the text string to encode :return: A bytearray containing the string encoded in UCS2 encoding :rtype: bytearray """ result = bytearray() for b in ...
[ "def", "encodeUcs2", "(", "text", ")", ":", "result", "=", "bytearray", "(", ")", "for", "b", "in", "map", "(", "ord", ",", "text", ")", ":", "result", ".", "append", "(", "b", ">>", "8", ")", "result", ".", "append", "(", "b", "&", "0xFF", ")"...
26.733333
18.133333
def to_datetime(jdc): '''Return a datetime for the input floating point Julian Day Count''' year, month, day = gregorian.from_jd(jdc) # in jdc: 0.0 = noon, 0.5 = midnight # the 0.5 changes it to 0.0 = midnight, 0.5 = noon frac = (jdc + 0.5) % 1 hours = int(24 * frac) mfrac = frac * 24 - h...
[ "def", "to_datetime", "(", "jdc", ")", ":", "year", ",", "month", ",", "day", "=", "gregorian", ".", "from_jd", "(", "jdc", ")", "# in jdc: 0.0 = noon, 0.5 = midnight", "# the 0.5 changes it to 0.0 = midnight, 0.5 = noon", "frac", "=", "(", "jdc", "+", "0.5", ")",...
28.181818
21.818182
def _add_text_size_ngrams(self, text_id, size, ngrams): """Adds `ngrams`, that are of size `size`, to the data store. The added `ngrams` are associated with `text_id`. :param text_id: database ID of text associated with `ngrams` :type text_id: `int` :param size: size of n-grams...
[ "def", "_add_text_size_ngrams", "(", "self", ",", "text_id", ",", "size", ",", "ngrams", ")", ":", "unique_ngrams", "=", "len", "(", "ngrams", ")", "self", ".", "_logger", ".", "info", "(", "'Adding {} unique {}-grams'", ".", "format", "(", "unique_ngrams", ...
40.818182
17.090909
def pltexp(iverts, delta): """ Expand a triangular plate by a specified amount. The expanded plate is co-planar with, and has the same orientation as, the original. The centroids of the two plates coincide. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltexp_c.html :para...
[ "def", "pltexp", "(", "iverts", ",", "delta", ")", ":", "iverts", "=", "stypes", ".", "toDoubleMatrix", "(", "iverts", ")", "delta", "=", "ctypes", ".", "c_double", "(", "delta", ")", "overts", "=", "stypes", ".", "emptyDoubleMatrix", "(", ")", "libspice...
39.1
13.5
def _get_action_strings(cls, possible_actions: List[List[ProductionRule]], action_indices: Dict[int, List[List[int]]]) -> List[List[List[str]]]: """ Takes a list of possible actions and indices of decoded actions into those possible actions ...
[ "def", "_get_action_strings", "(", "cls", ",", "possible_actions", ":", "List", "[", "List", "[", "ProductionRule", "]", "]", ",", "action_indices", ":", "Dict", "[", "int", ",", "List", "[", "List", "[", "int", "]", "]", "]", ")", "->", "List", "[", ...
57.736842
25.105263
def _search(self, searchstring): """ search users @str searchstring: search string @rtype: dict, {<user>: {<attr>: <value>}} """ if searchstring is None: return {} ret = {} for b in self.backends: tmp = self.backends[b].search(searchstring)...
[ "def", "_search", "(", "self", ",", "searchstring", ")", ":", "if", "searchstring", "is", "None", ":", "return", "{", "}", "ret", "=", "{", "}", "for", "b", "in", "self", ".", "backends", ":", "tmp", "=", "self", ".", "backends", "[", "b", "]", "...
31.6
10.866667
def findfirst(f, coll): """Return first occurrence matching f, otherwise None""" result = list(dropwhile(f, coll)) return result[0] if result else None
[ "def", "findfirst", "(", "f", ",", "coll", ")", ":", "result", "=", "list", "(", "dropwhile", "(", "f", ",", "coll", ")", ")", "return", "result", "[", "0", "]", "if", "result", "else", "None" ]
40.75
4.5
def _is_missing_tags_strict(self): """ Return whether missing_tags is set to strict. """ val = self.missing_tags if val == MissingTags.strict: return True elif val == MissingTags.ignore: return False raise Exception("Unsupported 'missing...
[ "def", "_is_missing_tags_strict", "(", "self", ")", ":", "val", "=", "self", ".", "missing_tags", "if", "val", "==", "MissingTags", ".", "strict", ":", "return", "True", "elif", "val", "==", "MissingTags", ".", "ignore", ":", "return", "False", "raise", "E...
26
16.923077
def _get_choice_attribute(self, value): """Get a choice attribute for the given value. Parameters ---------- value: ? The value for which we want a choice attribute. Returns ------- An instance of a class based on ``ChoiceAttributeMixin`` for the giv...
[ "def", "_get_choice_attribute", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "raise", "ValueError", "(", "'Using `None` in a `Choices` object is not supported. You may '", "'use an empty string.'", ")", "return", "create_choice_attribute", "(", "...
28.958333
26.916667
async def close(self): """Close this transaction. If this transaction is the base transaction in a begin/commit nesting, the transaction will rollback(). Otherwise, the method returns. This is used to cancel a Transaction without affecting the scope of an enclosing tra...
[ "async", "def", "close", "(", "self", ")", ":", "if", "not", "self", ".", "_parent", ".", "_is_active", ":", "return", "if", "self", ".", "_parent", "is", "self", ":", "await", "self", ".", "rollback", "(", ")", "else", ":", "self", ".", "_is_active"...
31.375
17.5625
def Record(self, value): """Records given value.""" self.sum += value self.count += 1 pos = bisect.bisect(self.bins, value) - 1 if pos < 0: pos = 0 elif pos == len(self.bins): pos = len(self.bins) - 1 self.heights[pos] += 1
[ "def", "Record", "(", "self", ",", "value", ")", ":", "self", ".", "sum", "+=", "value", "self", ".", "count", "+=", "1", "pos", "=", "bisect", ".", "bisect", "(", "self", ".", "bins", ",", "value", ")", "-", "1", "if", "pos", "<", "0", ":", ...
21.166667
18.833333
def convert(self, value, view): """Check that the value is a string and matches the pattern. """ if isinstance(value, BASESTRING): if self.pattern and not self.regex.match(value): self.fail( u"must match the pattern {0}".format(self.pattern), ...
[ "def", "convert", "(", "self", ",", "value", ",", "view", ")", ":", "if", "isinstance", "(", "value", ",", "BASESTRING", ")", ":", "if", "self", ".", "pattern", "and", "not", "self", ".", "regex", ".", "match", "(", "value", ")", ":", "self", ".", ...
36.666667
14.25
def is_valid_interval(self, lower, upper): """Return False if [lower:upper] is not a valid subitems interval. If it is, then returns a tuple of (lower index, upper index)""" try: lower_idx = self.data.index(lower) upper_idx = self.data.index(upper) return (low...
[ "def", "is_valid_interval", "(", "self", ",", "lower", ",", "upper", ")", ":", "try", ":", "lower_idx", "=", "self", ".", "data", ".", "index", "(", "lower", ")", "upper_idx", "=", "self", ".", "data", ".", "index", "(", "upper", ")", "return", "(", ...
46.555556
12.222222
def _get_comments_count(session, group_or_user_id, wall_id): """ https://vk.com/dev/wall.getComments """ response = session.fetch("wall.getComments", count=100, owner_id=group_or_user_id, post_id=wall_id) return response.get('count')
[ "def", "_get_comments_count", "(", "session", ",", "group_or_user_id", ",", "wall_id", ")", ":", "response", "=", "session", ".", "fetch", "(", "\"wall.getComments\"", ",", "count", "=", "100", ",", "owner_id", "=", "group_or_user_id", ",", "post_id", "=", "wa...
44.666667
15.666667