text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
async def can_place(self, building: Union[AbilityData, AbilityId, UnitTypeId], position: Point2) -> bool: """Tests if a building can be placed in the given location.""" assert isinstance(building, (AbilityData, AbilityId, UnitTypeId)) if isinstance(building, UnitTypeId): building =...
[ "async", "def", "can_place", "(", "self", ",", "building", ":", "Union", "[", "AbilityData", ",", "AbilityId", ",", "UnitTypeId", "]", ",", "position", ":", "Point2", ")", "->", "bool", ":", "assert", "isinstance", "(", "building", ",", "(", "AbilityData",...
49.833333
27.333333
def transform_grid_to_reference_frame(self, grid): """Transform a grid of (y,x) coordinates to the reference frame of the profile, including a translation to \ its centre. Parameters ---------- grid : ndarray The (y, x) coordinates in the original reference frame of ...
[ "def", "transform_grid_to_reference_frame", "(", "self", ",", "grid", ")", ":", "transformed", "=", "np", ".", "subtract", "(", "grid", ",", "self", ".", "centre", ")", "return", "transformed", ".", "view", "(", "TransformedGrid", ")" ]
39.363636
17.454545
def pointInsidePolygon(x, y, poly): """ Determine if a point is inside a given polygon or not Polygon is a list of (x,y) pairs. [code taken from: http://www.ariel.com.au/a/python-point-int-poly.html] let's make an easy square: >>> poly = [ (0,0),\ (1,0),\ (1,...
[ "def", "pointInsidePolygon", "(", "x", ",", "y", ",", "poly", ")", ":", "n", "=", "len", "(", "poly", ")", "inside", "=", "False", "p1x", ",", "p1y", "=", "poly", "[", "0", "]", "for", "i", "in", "range", "(", "n", "+", "1", ")", ":", "p2x", ...
28.28125
16.15625
def radiance_to_bt(arr, wc_, a__, b__): """Convert to BT. """ return a__ + b__ * (C2 * wc_ / (da.log(1 + (C1 * (wc_ ** 3) / arr))))
[ "def", "radiance_to_bt", "(", "arr", ",", "wc_", ",", "a__", ",", "b__", ")", ":", "return", "a__", "+", "b__", "*", "(", "C2", "*", "wc_", "/", "(", "da", ".", "log", "(", "1", "+", "(", "C1", "*", "(", "wc_", "**", "3", ")", "/", "arr", ...
35
8.5
def diff_sevice_by_text(service_name, service, environment, cf_client, repo_root): """ Render the local template and compare it to the template that was last applied in the target environment. """ global ret_code logger.info('Investigating textual diff for `%s`:`%s` in environment `%s`', ...
[ "def", "diff_sevice_by_text", "(", "service_name", ",", "service", ",", "environment", ",", "cf_client", ",", "repo_root", ")", ":", "global", "ret_code", "logger", ".", "info", "(", "'Investigating textual diff for `%s`:`%s` in environment `%s`'", ",", "service", "[", ...
37.53125
25.09375
def calculate_extents(labels, indexes): """Return the area of each object divided by the area of its bounding box""" fix = fixup_scipy_ndimage_result areas = fix(scind.sum(np.ones(labels.shape),labels,np.array(indexes, dtype=np.int32))) y,x = np.mgrid[0:labels.shape[0],0:labels.shape[1]] xmin = fix(...
[ "def", "calculate_extents", "(", "labels", ",", "indexes", ")", ":", "fix", "=", "fixup_scipy_ndimage_result", "areas", "=", "fix", "(", "scind", ".", "sum", "(", "np", ".", "ones", "(", "labels", ".", "shape", ")", ",", "labels", ",", "np", ".", "arra...
51.181818
11
def _traverse_toc(pdf_base, visitor_fn, log): """ Walk the table of contents, calling visitor_fn() at each node The /Outlines data structure is a messy data structure, but rather than navigating hierarchically we just track unique nodes. Enqueue nodes when we find them, and never visit them again....
[ "def", "_traverse_toc", "(", "pdf_base", ",", "visitor_fn", ",", "log", ")", ":", "visited", "=", "set", "(", ")", "queue", "=", "set", "(", ")", "link_keys", "=", "(", "'/Parent'", ",", "'/First'", ",", "'/Last'", ",", "'/Prev'", ",", "'/Next'", ")", ...
34.52381
20.52381
def save_imgs(x, fname): """Helper method to save a grid of images to a PNG file. Args: x: A numpy array of shape [n_images, height, width]. fname: The filename to write to (including extension). """ n = x.shape[0] fig = figure.Figure(figsize=(n, 1), frameon=False) canvas = backend_agg.FigureCanvas...
[ "def", "save_imgs", "(", "x", ",", "fname", ")", ":", "n", "=", "x", ".", "shape", "[", "0", "]", "fig", "=", "figure", ".", "Figure", "(", "figsize", "=", "(", "n", ",", "1", ")", ",", "frameon", "=", "False", ")", "canvas", "=", "backend_agg"...
31.444444
13.388889
def add_token(self, uri, http_method='GET', body=None, headers=None, token_placement=None, **kwargs): """Add token to the request uri, body or authorization header. The access token type provides the client with the information required to successfully utilize the access token...
[ "def", "add_token", "(", "self", ",", "uri", ",", "http_method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "token_placement", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_secure_transport", "(", "uri"...
43.528302
26.45283
def convert_permute(builder, layer, input_names, output_names, keras_layer): """Convert a softmax layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output...
[ "def", "convert_permute", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "0", "]", ")", "keras_dims", ...
34.878788
18.606061
def _extract_numbers(arg: Message_T) -> List[float]: """Extract all numbers (integers and floats) from a message-like object.""" s = str(arg) return list(map(float, re.findall(r'[+-]?(\d*\.?\d+|\d+\.?\d*)', s)))
[ "def", "_extract_numbers", "(", "arg", ":", "Message_T", ")", "->", "List", "[", "float", "]", ":", "s", "=", "str", "(", "arg", ")", "return", "list", "(", "map", "(", "float", ",", "re", ".", "findall", "(", "r'[+-]?(\\d*\\.?\\d+|\\d+\\.?\\d*)'", ",", ...
55
17.25
def call(self, inputs): """Call `Layer`.""" # if context.executing_eagerly(): # if not self.initialized: # self._data_dep_init(inputs) self._compute_weights() # Recompute weights for each forward pass output = self.layer.call(inputs) return output
[ "def", "call", "(", "self", ",", "inputs", ")", ":", "# if context.executing_eagerly():", "# if not self.initialized:", "# self._data_dep_init(inputs)", "self", ".", "_compute_weights", "(", ")", "# Recompute weights for each forward pass", "output", "=", "self", ".", ...
30.555556
14.222222
def parse_section_entry_points(self, section_options): """Parses `entry_points` configuration file section. :param dict section_options: """ parsed = self._parse_section_to_dict(section_options, self._parse_list) self['entry_points'] = parsed
[ "def", "parse_section_entry_points", "(", "self", ",", "section_options", ")", ":", "parsed", "=", "self", ".", "_parse_section_to_dict", "(", "section_options", ",", "self", ".", "_parse_list", ")", "self", "[", "'entry_points'", "]", "=", "parsed" ]
39.571429
14.285714
def add_months(self, month_int): """ addition of a number of months :param BusinessDate d: :param int month_int: :return bankdate: """ month_int += self.month while month_int > 12: self = BusinessDate.add_years(self, 1) month_int ...
[ "def", "add_months", "(", "self", ",", "month_int", ")", ":", "month_int", "+=", "self", ".", "month", "while", "month_int", ">", "12", ":", "self", "=", "BusinessDate", ".", "add_years", "(", "self", ",", "1", ")", "month_int", "-=", "12", "while", "m...
30.111111
13.777778
def custom_filter_tags(self, value, search): """Support tags query.""" if not isinstance(value, list): value = value.split(',') filters = [Q('match', **{'tags': item}) for item in value] search = search.query('bool', must=filters) return search
[ "def", "custom_filter_tags", "(", "self", ",", "value", ",", "search", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "value", ".", "split", "(", "','", ")", "filters", "=", "[", "Q", "(", "'match'", ",", "*...
32.222222
16.111111
def start_trial(self, trial, checkpoint=None): """Starts the trial. Will not return resources if trial repeatedly fails on start. Args: trial (Trial): Trial to be started. checkpoint (Checkpoint): A Python object or path storing the state of trial. ...
[ "def", "start_trial", "(", "self", ",", "trial", ",", "checkpoint", "=", "None", ")", ":", "self", ".", "_commit_resources", "(", "trial", ".", "resources", ")", "try", ":", "self", ".", "_start_trial", "(", "trial", ",", "checkpoint", ")", "except", "Ex...
40.029412
18.117647
def getpeptides(self, chain): """If peptide ligand chains are defined via the command line options, try to extract the underlying ligand formed by all residues in the given chain without water """ all_from_chain = [o for o in pybel.ob.OBResidueIter( self.proteincomple...
[ "def", "getpeptides", "(", "self", ",", "chain", ")", ":", "all_from_chain", "=", "[", "o", "for", "o", "in", "pybel", ".", "ob", ".", "OBResidueIter", "(", "self", ".", "proteincomplex", ".", "OBMol", ")", "if", "o", ".", "GetChain", "(", ")", "==",...
46.538462
18.384615
def databasesKEGG(organism,ens_ids): """ Finds KEGG database identifiers for a respective organism given example ensembl ids. :param organism: an organism as listed in organismsKEGG() :param ens_ids: a list of ensenbl ids of the respective organism :returns: nothing if no database was found, or a...
[ "def", "databasesKEGG", "(", "organism", ",", "ens_ids", ")", ":", "all_genes", "=", "urlopen", "(", "\"http://rest.kegg.jp/list/\"", "+", "organism", ")", ".", "read", "(", ")", "all_genes", "=", "all_genes", ".", "split", "(", "\"\\n\"", ")", "dbs", "=", ...
39.666667
20.644444
async def gantry_position( self, mount: top_types.Mount, critical_point: CriticalPoint = None) -> top_types.Point: """ Return the position of the critical point as pertains to the gantry This ignores the plunger position and gives the Z-axis a predictable nam...
[ "async", "def", "gantry_position", "(", "self", ",", "mount", ":", "top_types", ".", "Mount", ",", "critical_point", ":", "CriticalPoint", "=", "None", ")", "->", "top_types", ".", "Point", ":", "cur_pos", "=", "await", "self", ".", "current_position", "(", ...
44.0625
18.9375
def create(self, *args, **kwargs): """ Allow an 'author' kwarg to automatically fill in the created_by and last_modified_by fields. """ if kwargs.has_key('author'): kwargs['created_by'] = kwargs['author'] kwargs['last_modified_by'] = kwargs['author'] d...
[ "def", "create", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "has_key", "(", "'author'", ")", ":", "kwargs", "[", "'created_by'", "]", "=", "kwargs", "[", "'author'", "]", "kwargs", "[", "'last_modified_by'", ...
44.222222
14.666667
def eval(self, script, numkeys, *keys_and_args): """Emulate eval""" sha = self.script_load(script) return self.evalsha(sha, numkeys, *keys_and_args)
[ "def", "eval", "(", "self", ",", "script", ",", "numkeys", ",", "*", "keys_and_args", ")", ":", "sha", "=", "self", ".", "script_load", "(", "script", ")", "return", "self", ".", "evalsha", "(", "sha", ",", "numkeys", ",", "*", "keys_and_args", ")" ]
42.25
6.75
def adaptive_grid_archiver(random, population, archive, args): """Archive only the best individual(s) using a fixed size grid. This function archives the best solutions by using a fixed-size grid to determine which existing solutions should be removed in order to make room for new ones. This archiv...
[ "def", "adaptive_grid_archiver", "(", "random", ",", "population", ",", "archive", ",", "args", ")", ":", "def", "get_grid_location", "(", "fitness", ",", "num_grid_divisions", ",", "global_smallest", ",", "global_largest", ")", ":", "loc", "=", "0", "n", "=",...
48.794118
21.691176
def delete_namespace(self): '''Remove all keys from the namespace ''' conn = redis.Redis(connection_pool=self.pool) keys = conn.keys("%s*" % self._namespace_str) for i in xrange(0, len(keys), 10000): conn.delete(*keys[i:i+10000]) logger.debug('tearing down %r...
[ "def", "delete_namespace", "(", "self", ")", ":", "conn", "=", "redis", ".", "Redis", "(", "connection_pool", "=", "self", ".", "pool", ")", "keys", "=", "conn", ".", "keys", "(", "\"%s*\"", "%", "self", ".", "_namespace_str", ")", "for", "i", "in", ...
37.222222
15.444444
def wait_for_close( raiden: 'RaidenService', payment_network_id: PaymentNetworkID, token_address: TokenAddress, channel_ids: List[ChannelID], retry_timeout: float, ) -> None: """Wait until all channels are closed. Note: This does not time out, use gevent.Timeout....
[ "def", "wait_for_close", "(", "raiden", ":", "'RaidenService'", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "channel_ids", ":", "List", "[", "ChannelID", "]", ",", "retry_timeout", ":", "float", ",", ")", "...
29.05
12.5
def get_xpath_branch(xroot, xpath): """ :return: the relative part of an XPATH: that which extends past the root provided """ if xroot and xpath and xpath.startswith(xroot): xpath = xpath[len(xroot):] xpath = xpath.lstrip(XPATH_DELIM) return xpath
[ "def", "get_xpath_branch", "(", "xroot", ",", "xpath", ")", ":", "if", "xroot", "and", "xpath", "and", "xpath", ".", "startswith", "(", "xroot", ")", ":", "xpath", "=", "xpath", "[", "len", "(", "xroot", ")", ":", "]", "xpath", "=", "xpath", ".", "...
33.75
15.875
def schema(ds): """ Convert the table and column descriptions of a `Dataset` into specifications for the DB schema. :param ds: :return: A pair (tables, reference_tables). """ tables, ref_tables = {}, {} table_lookup = {t.url.string: t for t in ds.tables if ds.get_tabletype(t)} for t...
[ "def", "schema", "(", "ds", ")", ":", "tables", ",", "ref_tables", "=", "{", "}", ",", "{", "}", "table_lookup", "=", "{", "t", ".", "url", ".", "string", ":", "t", "for", "t", "in", "ds", ".", "tables", "if", "ds", ".", "get_tabletype", "(", "...
48.153061
20.234694
def get_indexes(self, schema, **kwargs): """ get all the indexes schema -- Schema() return -- dict -- the indexes in {indexname: fields} format """ with self.connection(**kwargs) as connection: kwargs['connection'] = connection return self._get_i...
[ "def", "get_indexes", "(", "self", ",", "schema", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "connection", "(", "*", "*", "kwargs", ")", "as", "connection", ":", "kwargs", "[", "'connection'", "]", "=", "connection", "return", "self", ".",...
30.363636
15.090909
def loc_forecast(self, request, step, isotime=None): """ Return location-specific forecast data (including lists of available sites and time capabilities) for given time step. request: metoffer.SITELIST Returns available sites metoffer.CAPABILITIES...
[ "def", "loc_forecast", "(", "self", ",", "request", ",", "step", ",", "isotime", "=", "None", ")", ":", "return", "json", ".", "loads", "(", "self", ".", "_query", "(", "VAL", ",", "FORECAST", ",", "ALL", ",", "request", ",", "step", ",", "isotime", ...
52.045455
24.409091
def delete(self, pk, **kwargs): """ Delete the object by primary_key: .. code-block:: python DBSession.sacrud(Users).delete(1) DBSession.sacrud(Users).delete('1') DBSession.sacrud(User2Groups).delete({'user_id': 4, 'group_id': 2}) JSON support: ...
[ "def", "delete", "(", "self", ",", "pk", ",", "*", "*", "kwargs", ")", ":", "pk", "=", "unjson", "(", "pk", ")", "obj", "=", "get_obj", "(", "self", ".", "session", ",", "self", ".", "table", ",", "pk", ")", "if", "self", ".", "_delete", "(", ...
28.884615
19.807692
def get_view(name, context=None, request=None): """Get the view by name :param name: The name of the view :type name: str :param context: The context to query the view :type context: ATContentType/DexterityContentType/CatalogBrain :param request: The request to query the view :type request:...
[ "def", "get_view", "(", "name", ",", "context", "=", "None", ",", "request", "=", "None", ")", ":", "context", "=", "context", "or", "get_portal", "(", ")", "request", "=", "request", "or", "get_request", "(", ")", "or", "None", "return", "getMultiAdapte...
37.533333
11.8
def _http_request(url, headers=None, data=None): ''' Make the HTTP request and return the body as python object. ''' if not headers: headers = _get_headers() session = requests.session() log.debug('Querying %s', url) req = session.post(url, ...
[ "def", "_http_request", "(", "url", ",", "headers", "=", "None", ",", "data", "=", "None", ")", ":", "if", "not", "headers", ":", "headers", "=", "_get_headers", "(", ")", "session", "=", "requests", ".", "session", "(", ")", "log", ".", "debug", "("...
28.25
16.25
def group_memberships_destroy_many(self, ids=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/group_memberships#bulk-delete-memberships" api_path = "/api/v2/group_memberships/destroy_many.json" api_query = {} if "query" in kwargs.keys(): api_query.update(kwa...
[ "def", "group_memberships_destroy_many", "(", "self", ",", "ids", "=", "None", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/group_memberships/destroy_many.json\"", "api_query", "=", "{", "}", "if", "\"query\"", "in", "kwargs", ".", "keys", "(",...
43.583333
21.083333
def loads(self, schema_txt: str) -> ShExJ.Schema: """ Parse and return schema as a ShExJ Schema :param schema_txt: ShExC or ShExJ representation of a ShEx Schema :return: ShEx Schema representation of schema """ self.schema_text = schema_txt if schema_txt.strip()[0] == '...
[ "def", "loads", "(", "self", ",", "schema_txt", ":", "str", ")", "->", "ShExJ", ".", "Schema", ":", "self", ".", "schema_text", "=", "schema_txt", "if", "schema_txt", ".", "strip", "(", ")", "[", "0", "]", "==", "'{'", ":", "# TODO: figure out how to pro...
45.416667
18.416667
def enumerate(vendor_id=0, product_id=0): """ Enumerate the HID Devices. Returns a generator that yields all of the HID devices attached to the system. :param vendor_id: Only return devices which match this vendor id :type vendor_id: int :param product_id: Only return devices which match...
[ "def", "enumerate", "(", "vendor_id", "=", "0", ",", "product_id", "=", "0", ")", ":", "info", "=", "hidapi", ".", "hid_enumerate", "(", "vendor_id", ",", "product_id", ")", "while", "info", ":", "yield", "DeviceInfo", "(", "info", ")", "info", "=", "i...
33.75
19.1
def _raw(self, msg): """ Print any command sent in raw format :param msg: arbitrary code to be printed :type msg: bytes """ self.device.write(self.out_ep, msg, self.timeout)
[ "def", "_raw", "(", "self", ",", "msg", ")", ":", "self", ".", "device", ".", "write", "(", "self", ".", "out_ep", ",", "msg", ",", "self", ".", "timeout", ")" ]
29.714286
14.428571
def bin_centers(self, axis=None): """Return bin centers along an axis, or if axis=None, list of bin_centers along each axis""" if axis is None: return np.array([self.bin_centers(axis=i) for i in range(self.dimensions)]) axis = self.get_axis_number(axis) return 0.5 * (self.bin...
[ "def", "bin_centers", "(", "self", ",", "axis", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "return", "np", ".", "array", "(", "[", "self", ".", "bin_centers", "(", "axis", "=", "i", ")", "for", "i", "in", "range", "(", "self", ".", ...
60
17.666667
def check_subsequent_web_request(self, item_session: ItemSession, is_redirect: bool=False) -> Tuple[bool, str]: '''Check URL filters and scripting hook. Returns: tuple: (bool, str) ''' verdict, reason, test_info = self.consult_filters( ...
[ "def", "check_subsequent_web_request", "(", "self", ",", "item_session", ":", "ItemSession", ",", "is_redirect", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":", "verdict", ",", "reason", ",", "test_info", "=", "self", ".",...
35.789474
22.315789
def change_port_speed(self, hardware_id, public, speed): """Allows you to change the port speed of a server's NICs. :param int hardware_id: The ID of the server :param bool public: Flag to indicate which interface to change. True (default) means the public interface....
[ "def", "change_port_speed", "(", "self", ",", "hardware_id", ",", "public", ",", "speed", ")", ":", "if", "public", ":", "return", "self", ".", "client", ".", "call", "(", "'Hardware_Server'", ",", "'setPublicNetworkInterfaceSpeed'", ",", "speed", ",", "id", ...
43.37037
22.148148
def _find_scc(self): """ Set ``self._num_scc`` and ``self._scc_proj`` by calling ``scipy.sparse.csgraph.connected_components``: * docs.scipy.org/doc/scipy/reference/sparse.csgraph.html * github.com/scipy/scipy/blob/master/scipy/sparse/csgraph/_traversal.pyx ``self._scc_p...
[ "def", "_find_scc", "(", "self", ")", ":", "# Find the strongly connected components", "self", ".", "_num_scc", ",", "self", ".", "_scc_proj", "=", "csgraph", ".", "connected_components", "(", "self", ".", "csgraph", ",", "connection", "=", "'strong'", ")" ]
44.071429
22.5
def identify_and_tag_URLs(line): """Given a reference line, identify URLs in the line, record the information about them, and replace them with a "<cds.URL />" tag. URLs are identified in 2 forms: + Raw: http://invenio-software.org/ + HTML marked-up: <a href="http://invenio-software.or...
[ "def", "identify_and_tag_URLs", "(", "line", ")", ":", "# Take a copy of the line:", "line_pre_url_check", "=", "line", "# Dictionaries to record details of matched URLs:", "found_url_full_matchlen", "=", "{", "}", "found_url_urlstring", "=", "{", "}", "found_url_urldescr", "...
47.756757
19
def iter_blocks(block_list): """A generator for blocks contained in a block list. Yields tuples containing the block name, the depth that the block was found at, and finally a handle to the block itself. """ # queue the block and the depth of the block queue = [(block, ...
[ "def", "iter_blocks", "(", "block_list", ")", ":", "# queue the block and the depth of the block", "queue", "=", "[", "(", "block", ",", "0", ")", "for", "block", "in", "block_list", "if", "isinstance", "(", "block", ",", "kurt", ".", "Block", ")", "]", "whi...
41.25
14.2
def _init_table(self): """ Initialize the observation table. """ self.observation_table.sm_vector.append(self.epsilon) self.observation_table.smi_vector = [random.choice(self.alphabet)] self.observation_table.em_vector.append(self.epsilon) self._fill_table_entry(...
[ "def", "_init_table", "(", "self", ")", ":", "self", ".", "observation_table", ".", "sm_vector", ".", "append", "(", "self", ".", "epsilon", ")", "self", ".", "observation_table", ".", "smi_vector", "=", "[", "random", ".", "choice", "(", "self", ".", "a...
40.090909
15.909091
def silent(duration=1000, frame_rate=11025): """ Creates an AudioSegment object of the specified duration/frame_rate filled with digital silence. :param duration: The duration of the returned object in ms. :param frame_rate: The samples per second of the returned object. :returns: AudioSegment obje...
[ "def", "silent", "(", "duration", "=", "1000", ",", "frame_rate", "=", "11025", ")", ":", "seg", "=", "pydub", ".", "AudioSegment", ".", "silent", "(", "duration", "=", "duration", ",", "frame_rate", "=", "frame_rate", ")", "return", "AudioSegment", "(", ...
46.6
22.8
def remove(self, *args): """Remove the instance tied to the field for the given "value" (via `args`) from the index For the parameters, see ``BaseIndex.remove`` """ key = self.get_storage_key(*args) pk = self.instance.pk.get() logger.debug("removing %s from index %s" %...
[ "def", "remove", "(", "self", ",", "*", "args", ")", ":", "key", "=", "self", ".", "get_storage_key", "(", "*", "args", ")", "pk", "=", "self", ".", "instance", ".", "pk", ".", "get", "(", ")", "logger", ".", "debug", "(", "\"removing %s from index %...
33.833333
15.416667
def compress_histogram(buckets, bps=NORMAL_HISTOGRAM_BPS): """Creates fixed size histogram by adding compression to accumulated state. This routine transforms a histogram at a particular step by linearly interpolating its variable number of buckets to represent their cumulative weight at a constant number of c...
[ "def", "compress_histogram", "(", "buckets", ",", "bps", "=", "NORMAL_HISTOGRAM_BPS", ")", ":", "# See also: Histogram::Percentile() in core/lib/histogram/histogram.cc", "buckets", "=", "np", ".", "array", "(", "buckets", ")", "if", "not", "buckets", ".", "size", ":",...
36.54717
22.283019
def unpack_messages(msgs): import msgpack """ Deserialize a message to python structures """ for key, msg in msgs: record = msgpack.unpackb(msg) record['_key'] = key yield record
[ "def", "unpack_messages", "(", "msgs", ")", ":", "import", "msgpack", "for", "key", ",", "msg", "in", "msgs", ":", "record", "=", "msgpack", ".", "unpackb", "(", "msg", ")", "record", "[", "'_key'", "]", "=", "key", "yield", "record" ]
29
13.5
def handshake(self, protocol='vnc', width=1024, height=768, dpi=96, audio=None, video=None, image=None, **kwargs): """ Establish connection with Guacamole guacd server via handshake. """ if protocol not in PROTOCOLS: self.logger.debug('Invalid protocol: %s' ...
[ "def", "handshake", "(", "self", ",", "protocol", "=", "'vnc'", ",", "width", "=", "1024", ",", "height", "=", "768", ",", "dpi", "=", "96", ",", "audio", "=", "None", ",", "video", "=", "None", ",", "image", "=", "None", ",", "*", "*", "kwargs",...
37.184211
22.078947
def deploy( config, name, bucket, timeout, memory, description, subnet_ids, security_group_ids ): """ Deploy/Update a function from a project directory """ # options should override config if it is there myname = name or config.name mybucket = bucket or config.bucket ...
[ "def", "deploy", "(", "config", ",", "name", ",", "bucket", ",", "timeout", ",", "memory", ",", "description", ",", "subnet_ids", ",", "security_group_ids", ")", ":", "# options should override config if it is there", "myname", "=", "name", "or", "config", ".", ...
26.833333
20.805556
def get_all_organization_names(configuration=None, **kwargs): # type: (Optional[Configuration], Any) -> List[str] """Get all organization names in HDX Args: configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration. **kwargs: See below ...
[ "def", "get_all_organization_names", "(", "configuration", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (Optional[Configuration], Any) -> List[str]", "organization", "=", "Organization", "(", "configuration", "=", "configuration", ")", "organization", "[", "...
65.95
41.2
def get_ipaths(self): """ Returns generator of paths from nodes marked as added, changed or removed. """ for node in itertools.chain(self.added, self.changed, self.removed): yield node.path
[ "def", "get_ipaths", "(", "self", ")", ":", "for", "node", "in", "itertools", ".", "chain", "(", "self", ".", "added", ",", "self", ".", "changed", ",", "self", ".", "removed", ")", ":", "yield", "node", ".", "path" ]
33.571429
17.857143
def get_dataset(self, key, info): """Load a dataset.""" logger.debug('Reading %s.', key.name) variable = self.nc[key.name] return variable
[ "def", "get_dataset", "(", "self", ",", "key", ",", "info", ")", ":", "logger", ".", "debug", "(", "'Reading %s.'", ",", "key", ".", "name", ")", "variable", "=", "self", ".", "nc", "[", "key", ".", "name", "]", "return", "variable" ]
27.666667
12.166667
def fetch_task_to_run(self): """ Returns the first task that is ready to run or None if no task can be submitted at present" Raises: `StopIteration` if all tasks are done. """ # All the tasks are done so raise an exception # that will be handled by th...
[ "def", "fetch_task_to_run", "(", "self", ")", ":", "# All the tasks are done so raise an exception", "# that will be handled by the client code.", "if", "all", "(", "task", ".", "is_completed", "for", "task", "in", "self", ")", ":", "raise", "StopIteration", "(", "\"All...
33.857143
17.380952
def run(self, timeout=POD_RUN_WAIT_TIMEOUT_SECONDS): """ Forces a K8sCronJob to run immediately. - Fail if the K8sCronJob is currently running on-schedule. - Suspend the K8sCronJob. - Spawn a K8sPod. - Unsuspend a K8sCronJob. :param timeout: The timeout, in seco...
[ "def", "run", "(", "self", ",", "timeout", "=", "POD_RUN_WAIT_TIMEOUT_SECONDS", ")", ":", "if", "not", "isinstance", "(", "timeout", ",", "int", ")", ":", "raise", "SyntaxError", "(", "\"K8sCronJob.run() timeout: [ {} ] is invalid.\"", ")", "if", "len", "(", "se...
29.681818
21.681818
def parse_image_response(self, response): """ Parse multiple objects from the RETS feed. A lot of string methods are used to handle the response before encoding it back into bytes for the object. :param response: The response from the feed :return: list of SingleObjectParser ...
[ "def", "parse_image_response", "(", "self", ",", "response", ")", ":", "if", "'xml'", "in", "response", ".", "headers", ".", "get", "(", "'Content-Type'", ")", ":", "# Got an XML response, likely an error code.", "xml", "=", "xmltodict", ".", "parse", "(", "resp...
45.456522
19.891304
def get_certificate(order_id=None, certificate_id=None, minion_id=None, cert_format='pem_all', filename=None): ''' Retrieve a certificate by order_id or certificate_id and write it to stdout or a filename. A list of permissible cert_formats is here: https://www.digicert.com/services/v2/documentatio...
[ "def", "get_certificate", "(", "order_id", "=", "None", ",", "certificate_id", "=", "None", ",", "minion_id", "=", "None", ",", "cert_format", "=", "'pem_all'", ",", "filename", "=", "None", ")", ":", "if", "order_id", ":", "order_cert", "=", "salt", ".", ...
35.651163
23.899225
def help(route): r"""Displays help for the given route. Args: route (str): A route that resolves a member. """ help_text = getRouteHelp(route.split('/') if route else []) if help_text is None: err('Can\'t help :(') else: print '\n%s' % help_text
[ "def", "help", "(", "route", ")", ":", "help_text", "=", "getRouteHelp", "(", "route", ".", "split", "(", "'/'", ")", "if", "route", "else", "[", "]", ")", "if", "help_text", "is", "None", ":", "err", "(", "'Can\\'t help :('", ")", "else", ":", "prin...
20
21.769231
def add_edge(self, source: Node, target: Node, weight: float = 1, save_to_cache: bool = True) -> None: """ Adds an edge to the edge list that will connect the specified nodes. Arguments: source (Node): The ...
[ "def", "add_edge", "(", "self", ",", "source", ":", "Node", ",", "target", ":", "Node", ",", "weight", ":", "float", "=", "1", ",", "save_to_cache", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "not", "isinstance", "(", "source", ",", "N...
42.368421
20.578947
def get_changelog_date_packager(self): """Returns part of the changelog entry, containing date and packager. """ try: packager = subprocess.Popen( 'rpmdev-packager', stdout=subprocess.PIPE).communicate( )[0].strip() except OSError: ...
[ "def", "get_changelog_date_packager", "(", "self", ")", ":", "try", ":", "packager", "=", "subprocess", ".", "Popen", "(", "'rpmdev-packager'", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "communicate", "(", ")", "[", "0", "]", ".", "strip", ...
46.8125
14.3125
def update_webhook(self, webhook_url, webhook_id, events=None): """Register webhook (if it doesn't exit).""" hooks = self._request(MINUT_WEBHOOKS_URL, request_type='GET')['hooks'] try: self._webhook = next( hook for hook in hooks if hook['url'] == webhook_url) ...
[ "def", "update_webhook", "(", "self", ",", "webhook_url", ",", "webhook_id", ",", "events", "=", "None", ")", ":", "hooks", "=", "self", ".", "_request", "(", "MINUT_WEBHOOKS_URL", ",", "request_type", "=", "'GET'", ")", "[", "'hooks'", "]", "try", ":", ...
51.461538
18.692308
def addDiscreteOutcomeConstantMean(distribution, x, p, sort = False): ''' Adds a discrete outcome of x with probability p to an existing distribution, holding constant the relative probabilities of other outcomes and overall mean. Parameters ---------- distribution : [np.array] Two elem...
[ "def", "addDiscreteOutcomeConstantMean", "(", "distribution", ",", "x", ",", "p", ",", "sort", "=", "False", ")", ":", "X", "=", "np", ".", "append", "(", "x", ",", "distribution", "[", "1", "]", "*", "(", "1", "-", "p", "*", "x", ")", "/", "(", ...
30.2
24.6
def clean(matrix): """Return a copy of given matrix where keys associated to space values are discarded""" return defaultdict(lambda: ' ', { k: v for k, v in matrix.items() if v != ' ' })
[ "def", "clean", "(", "matrix", ")", ":", "return", "defaultdict", "(", "lambda", ":", "' '", ",", "{", "k", ":", "v", "for", "k", ",", "v", "in", "matrix", ".", "items", "(", ")", "if", "v", "!=", "' '", "}", ")" ]
34.333333
11.666667
def delete_instance(self, *args, **kwargs): """Send signals.""" self.pre_delete.send(self) super(Model, self).delete_instance(*args, **kwargs) self.post_delete.send(self)
[ "def", "delete_instance", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "pre_delete", ".", "send", "(", "self", ")", "super", "(", "Model", ",", "self", ")", ".", "delete_instance", "(", "*", "args", ",", "*", "*", ...
39.6
6.6
def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0...
[ "def", "get", "(", "path", ",", "profile", "=", "None", ",", "hosts", "=", "None", ",", "scheme", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "default_acl", "=", "None", ")", ":", "conn", "=", "_get_zk_conn", "(", ...
25.944444
30
def create_hosted_service(self, service_name, label, description=None, location=None, affinity_group=None, extended_properties=None): ''' Creates a new hosted service in Windows Azure. service_name: A name for the hosted se...
[ "def", "create_hosted_service", "(", "self", ",", "service_name", ",", "label", ",", "description", "=", "None", ",", "location", "=", "None", ",", "affinity_group", "=", "None", ",", "extended_properties", "=", "None", ")", ":", "_validate_not_none", "(", "'s...
52.372549
22.45098
def _get_available_extensions(): """Get a list of available file extensions to make it easy for tab-completion and exception handling. """ extensions = [] # from filenames parsers_dir = os.path.join(os.path.dirname(__file__)) glob_filename = os.path.join(parsers_dir, "*" + _FILENAME_SUFFIX ...
[ "def", "_get_available_extensions", "(", ")", ":", "extensions", "=", "[", "]", "# from filenames", "parsers_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "glob_filename", "=", "os", ".", "p...
35.478261
14.652174
def run(self, conn, tmp, module_name, module_args, inject): ''' transfer the given module name, plus the async module, then run it ''' # shell and command module are the same if module_name == 'shell': module_name = 'command' module_args += " #USE_SHELL" (module...
[ "def", "run", "(", "self", ",", "conn", ",", "tmp", ",", "module_name", ",", "module_args", ",", "inject", ")", ":", "# shell and command module are the same", "if", "module_name", "==", "'shell'", ":", "module_name", "=", "'command'", "module_args", "+=", "\" #...
43.705882
25.117647
def _check_flavors_exist(self, parsed_args): """Ensure that selected flavors (--ROLE-flavor) exist in nova.""" compute_client = self.app.client_manager.compute flavors = {f.name: f for f in compute_client.flavors.list()} message = "Provided --{}-flavor, '{}', does not exist" f...
[ "def", "_check_flavors_exist", "(", "self", ",", "parsed_args", ")", ":", "compute_client", "=", "self", ".", "app", ".", "client_manager", ".", "compute", "flavors", "=", "{", "f", ".", "name", ":", "f", "for", "f", "in", "compute_client", ".", "flavors",...
45.12
16.04
def has_reg(self, reg_name): """Check if a register is used in the instruction.""" return any(operand.has_reg(reg_name) for operand in self.operands)
[ "def", "has_reg", "(", "self", ",", "reg_name", ")", ":", "return", "any", "(", "operand", ".", "has_reg", "(", "reg_name", ")", "for", "operand", "in", "self", ".", "operands", ")" ]
54.333333
15.333333
def unmount(self, remove_rw=False, allow_lazy=False): """Removes all ties of this disk to the filesystem, so the image can be unmounted successfully. :raises SubsystemError: when one of the underlying commands fails. Some are swallowed. :raises CleanupError: when actual cleanup fails. Some are ...
[ "def", "unmount", "(", "self", ",", "remove_rw", "=", "False", ",", "allow_lazy", "=", "False", ")", ":", "for", "m", "in", "list", "(", "sorted", "(", "self", ".", "volumes", ",", "key", "=", "lambda", "v", ":", "v", ".", "mountpoint", "or", "\"\"...
39.527778
23.472222
def get_help(obj, env, subcmds): """Interpolate complete help doc of given object Assumption that given object as a specific interface: obj.__doc__ is the basic help object. obj.get_actions_titles() returns the subcommand if any. """ doc = txt.dedent(obj.__doc__ or "") env = env.copy() ...
[ "def", "get_help", "(", "obj", ",", "env", ",", "subcmds", ")", ":", "doc", "=", "txt", ".", "dedent", "(", "obj", ".", "__doc__", "or", "\"\"", ")", "env", "=", "env", ".", "copy", "(", ")", "## get a local copy", "doc", "=", "doc", ".", "strip", ...
31.735294
17.25
def execute(self, stmt, **params): """Execute a SQL statement. The statement may be a string SQL string, an :func:`sqlalchemy.sql.expression.select` construct, or a :func:`sqlalchemy.sql.expression.text` construct. """ return self.session.execute(sql.text(stmt...
[ "def", "execute", "(", "self", ",", "stmt", ",", "*", "*", "params", ")", ":", "return", "self", ".", "session", ".", "execute", "(", "sql", ".", "text", "(", "stmt", ",", "bind", "=", "self", ".", "bind", ")", ",", "*", "*", "params", ")" ]
33.9
18.9
def uninstall_handler(self, event_type, handler, user_handle=None): """Uninstalls handlers for events in this resource. :param event_type: Logical event identifier. :param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application. :param user_handl...
[ "def", "uninstall_handler", "(", "self", ",", "event_type", ",", "handler", ",", "user_handle", "=", "None", ")", ":", "self", ".", "visalib", ".", "uninstall_visa_handler", "(", "self", ".", "session", ",", "event_type", ",", "handler", ",", "user_handle", ...
54.222222
33.111111
def validate_cbarpos(value): """Validate a colorbar position Parameters ---------- value: bool or str A string can be a combination of 'sh|sv|fl|fr|ft|fb|b|r' Returns ------- list list of strings with possible colorbar positions Raises ------ ValueError""" ...
[ "def", "validate_cbarpos", "(", "value", ")", ":", "patt", "=", "'sh|sv|fl|fr|ft|fb|b|r'", "if", "value", "is", "True", ":", "value", "=", "{", "'b'", "}", "elif", "not", "value", ":", "value", "=", "set", "(", ")", "elif", "isinstance", "(", "value", ...
26.84375
19.59375
def set_template(path, template, context, defaults, saltenv='base', **kwargs): ''' Set answers to debconf questions from a template. path location of the file containing the package selections template template format context variables to add to the template environment ...
[ "def", "set_template", "(", "path", ",", "template", ",", "context", ",", "defaults", ",", "saltenv", "=", "'base'", ",", "*", "*", "kwargs", ")", ":", "path", "=", "__salt__", "[", "'cp.get_template'", "]", "(", "path", "=", "path", ",", "dest", "=", ...
21.735294
26.970588
def subseparable_conv(inputs, filters, kernel_size, **kwargs): """Sub-separable convolution. If separability == 0 it's a separable_conv.""" def conv_fn(inputs, filters, kernel_size, **kwargs): """Sub-separable convolution, splits into separability-many blocks.""" separability = None if "separability" i...
[ "def", "subseparable_conv", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "*", "*", "kwargs", ")", ":", "def", "conv_fn", "(", "inputs", ",", "filters", ",", "kernel_size", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Sub-separable convolution, splits i...
42.027778
19.138889
def getresponse(self): """ Pass-thru method to make this class behave a little like HTTPConnection """ resp = self.http.getresponse() self.log.info("resp is %s", str(resp)) if resp.status < 400: return resp else: errtext = resp.read() ...
[ "def", "getresponse", "(", "self", ")", ":", "resp", "=", "self", ".", "http", ".", "getresponse", "(", ")", "self", ".", "log", ".", "info", "(", "\"resp is %s\"", ",", "str", "(", "resp", ")", ")", "if", "resp", ".", "status", "<", "400", ":", ...
38.416667
17.25
def format_api_version(self, api_version): """ Return QualysGuard API version for api_version specified. """ # Convert to int. if type(api_version) == str: api_version = api_version.lower() if api_version[0] == 'v' and api_version[1].isdigit(): # ...
[ "def", "format_api_version", "(", "self", ",", "api_version", ")", ":", "# Convert to int.", "if", "type", "(", "api_version", ")", "==", "str", ":", "api_version", "=", "api_version", ".", "lower", "(", ")", "if", "api_version", "[", "0", "]", "==", "'v'"...
44.115385
13.653846
def base_dict_to_string(base_dict): """ Converts a dictionary to a string. {'C': 12, 'A':4} gets converted to C:12;A:4 :param base_dict: Dictionary of bases and counts created by find_if_multibase :return: String representing that dictionary. """ outstr = '' # First, sort base_dict so that m...
[ "def", "base_dict_to_string", "(", "base_dict", ")", ":", "outstr", "=", "''", "# First, sort base_dict so that major allele always comes first - makes output report nicer to look at.", "base_list", "=", "sorted", "(", "base_dict", ".", "items", "(", ")", ",", "key", "=", ...
46.583333
22.416667
def add_ptr_records(self, device, records): """ Adds one or more PTR records to the specified device. """ device_type = self._resolve_device_type(device) href, svc_name = self._get_ptr_details(device, device_type) if not isinstance(records, (list, tuple)): rec...
[ "def", "add_ptr_records", "(", "self", ",", "device", ",", "records", ")", ":", "device_type", "=", "self", ".", "_resolve_device_type", "(", "device", ")", "href", ",", "svc_name", "=", "self", ".", "_get_ptr_details", "(", "device", ",", "device_type", ")"...
50.378378
19.567568
def get_chain_sequence_string(self, chain_id, use_seqres_sequences_if_possible, raise_Exception_if_not_found = True): '''Similar to get_annotated_chain_sequence_string except that we only return the Sequence and do not state which sequence it was.''' chain_pair = self.get_annotated_chain_sequence_string...
[ "def", "get_chain_sequence_string", "(", "self", ",", "chain_id", ",", "use_seqres_sequences_if_possible", ",", "raise_Exception_if_not_found", "=", "True", ")", ":", "chain_pair", "=", "self", ".", "get_annotated_chain_sequence_string", "(", "chain_id", ",", "use_seqres_...
82.666667
58.333333
def frame_from_firmware(self, firmware): '''extract information from firmware, return pretty string to user''' # see Tools/scripts/generate-manifest for this map: frame_to_mavlink_dict = { "quad": "QUADROTOR", "hexa": "HEXAROTOR", "y6": "ARDUPILOT_Y6", ...
[ "def", "frame_from_firmware", "(", "self", ",", "firmware", ")", ":", "# see Tools/scripts/generate-manifest for this map:", "frame_to_mavlink_dict", "=", "{", "\"quad\"", ":", "\"QUADROTOR\"", ",", "\"hexa\"", ":", "\"HEXAROTOR\"", ",", "\"y6\"", ":", "\"ARDUPILOT_Y6\"",...
37.291667
13.125
def send_request(self, method, url, headers=None, json_data=None, retry=True): """Send requests to Skybell.""" if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL: self.login() if not headers: headers = {} if self.cache(CONST.AC...
[ "def", "send_request", "(", "self", ",", "method", ",", "url", ",", "headers", "=", "None", ",", "json_data", "=", "None", ",", "retry", "=", "True", ")", ":", "if", "not", "self", ".", "cache", "(", "CONST", ".", "ACCESS_TOKEN", ")", "and", "url", ...
35.725
20.85
def bullseye_position(self) -> typing.Tuple[float, float]: """ Returns: bullseye position """ return self.bullseye_x, self.bullseye_y
[ "def", "bullseye_position", "(", "self", ")", "->", "typing", ".", "Tuple", "[", "float", ",", "float", "]", ":", "return", "self", ".", "bullseye_x", ",", "self", ".", "bullseye_y" ]
32.2
6.2
def generate_add_sub(self): ''' Generates prefixes/suffixes in a short form to parse and remove some redundancy ''' # Prefix or Suffix affix_type = 'p:' if self.opt == "PFX" else 's:' remove_char = '-' + self.char_to_strip if self.char_to_strip != '' else '' return affix_type + ...
[ "def", "generate_add_sub", "(", "self", ")", ":", "# Prefix or Suffix", "affix_type", "=", "'p:'", "if", "self", ".", "opt", "==", "\"PFX\"", "else", "'s:'", "remove_char", "=", "'-'", "+", "self", ".", "char_to_strip", "if", "self", ".", "char_to_strip", "!...
49.142857
28.285714
def add_holiday(self, start_dt, holiday_name, end_dt = None, calendar_id = 'notices'): '''Adds a holiday event to the calendar. start_dt and end_dt (if supplied) should be date objects. Returns True if the event was added.''' assert(calendar_id in self.configured_calendar_ids.keys()) calendarId...
[ "def", "add_holiday", "(", "self", ",", "start_dt", ",", "holiday_name", ",", "end_dt", "=", "None", ",", "calendar_id", "=", "'notices'", ")", ":", "assert", "(", "calendar_id", "in", "self", ".", "configured_calendar_ids", ".", "keys", "(", ")", ")", "ca...
62.153846
42.769231
def localize_date(date, city): """ Localize date into city Date: datetime City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'.. """ local = pytz.timezone(city) local_dt = local.localize(date, is_dst=None) return local_dt
[ "def", "localize_date", "(", "date", ",", "city", ")", ":", "local", "=", "pytz", ".", "timezone", "(", "city", ")", "local_dt", "=", "local", ".", "localize", "(", "date", ",", "is_dst", "=", "None", ")", "return", "local_dt" ]
29.111111
16.444444
def _bracket_complete_sig(self, symbol, fullsymbol): """Returns the call signature and docstring for the executable immediately preceding a bracket '(' that was typed.""" if symbol != fullsymbol: #We have a sym%sym%... chain and the completion just needs to #be the signat...
[ "def", "_bracket_complete_sig", "(", "self", ",", "symbol", ",", "fullsymbol", ")", ":", "if", "symbol", "!=", "fullsymbol", ":", "#We have a sym%sym%... chain and the completion just needs to", "#be the signature of the member method.", "target", ",", "targmod", "=", "self...
49.966667
16.7
def _msgmerge(po_path, pot_file, backup): """Merge an existing .po file with new translations. :arg po_path: path to the .po file :arg pot_file: a file-like object for the related templates :arg backup: whether or not to create backup .po files """ pot_file.seek(0) command = [ 'msgm...
[ "def", "_msgmerge", "(", "po_path", ",", "pot_file", ",", "backup", ")", ":", "pot_file", ".", "seek", "(", "0", ")", "command", "=", "[", "'msgmerge'", ",", "'--update'", ",", "'--width=200'", ",", "'--backup=%s'", "%", "(", "'simple'", "if", "backup", ...
28.055556
17.444444
def _collect(self, lines): """ This routine reads the following from the Siesta file: - atomic positions - cell_parameters - atomic_species """ for tag,value,unit in re.findall( '([\.A-Za-z]+)\s+%s\s+([A-Za-z]+)?' % self._num_re...
[ "def", "_collect", "(", "self", ",", "lines", ")", ":", "for", "tag", ",", "value", ",", "unit", "in", "re", ".", "findall", "(", "'([\\.A-Za-z]+)\\s+%s\\s+([A-Za-z]+)?'", "%", "self", ".", "_num_regex", ",", "lines", ")", ":", "tag", "=", "tag", ".", ...
45.52459
16.131148
def marketShortInterestDF(date=None, token='', version=''): '''The consolidated market short interest positions in all IEX-listed securities are included in the IEX Short Interest Report. The report data will be published daily at 4:00pm ET. https://iexcloud.io/docs/api/#listed-short-interest-list-in-dev ...
[ "def", "marketShortInterestDF", "(", "date", "=", "None", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "marketShortInterest", "(", "date", ",", "token", ",", "version", ")", ")", "_toDatetime", "...
32.166667
27.944444
def create_healthcheck(ip_addr=None, fqdn=None, region=None, key=None, keyid=None, profile=None, port=53, hc_type='TCP', resource_path='', string_match=None, request_interval=30, failure_threshold=3, retry_on_errors=True, error_retries=5): ''' Create a Route53 healthc...
[ "def", "create_healthcheck", "(", "ip_addr", "=", "None", ",", "fqdn", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "port", "=", "53", ",", "hc_type", "=", "'TCP'", "...
30.96
29.62
def inputAnalysis(allSequences, model, numColumns): """ Calculates the overlap score of each SDR used as input to the temporal memory. Generates an overlap matrix with entries (i,j) = overlapScore(i, j) @param allSequences (array) sequences using during the experiment @param model (string) string specifyin...
[ "def", "inputAnalysis", "(", "allSequences", ",", "model", ",", "numColumns", ")", ":", "records", "=", "np", ".", "shape", "(", "allSequences", ")", "[", "0", "]", "symbols", "=", "np", ".", "shape", "(", "allSequences", ")", "[", "1", "]", "totalItem...
41.371429
21.371429
def _next_move_direction(self): """ pick a move at random from the list of moves """ nmoves = len(self.moves) move = np.random.randint(1, nmoves+1) while self.prev_move == (move + 3) % nmoves: move = np.random.randint(1, nmoves+1) self.prev_move = move...
[ "def", "_next_move_direction", "(", "self", ")", ":", "nmoves", "=", "len", "(", "self", ".", "moves", ")", "move", "=", "np", ".", "random", ".", "randint", "(", "1", ",", "nmoves", "+", "1", ")", "while", "self", ".", "prev_move", "==", "(", "mov...
35.3
6.7
def his_from_sql(self, db_name, point): """ Retrive point histories from SQL database """ his = self._read_from_sql('select * from "%s"' % "history", db_name) his.index = his["index"].apply(Timestamp) return his.set_index("index")[point]
[ "def", "his_from_sql", "(", "self", ",", "db_name", ",", "point", ")", ":", "his", "=", "self", ".", "_read_from_sql", "(", "'select * from \"%s\"'", "%", "\"history\"", ",", "db_name", ")", "his", ".", "index", "=", "his", "[", "\"index\"", "]", ".", "a...
39.857143
8.428571
def _find_server(account, servername=None): """ Find and return a PlexServer object. """ servers = servers = [s for s in account.resources() if 'server' in s.provides] # If servername specified find and return it if servername is not None: for server in servers: if server.name == ser...
[ "def", "_find_server", "(", "account", ",", "servername", "=", "None", ")", ":", "servers", "=", "servers", "=", "[", "s", "for", "s", "in", "account", ".", "resources", "(", ")", "if", "'server'", "in", "s", ".", "provides", "]", "# If servername specif...
49.909091
13
def mine_blocks(num_blocks: int, chain: MiningChain) -> MiningChain: """ Variadic argument version of :func:`~eth.tools.builder.chain.mine_block` """ if not isinstance(chain, MiningChain): raise ValidationError('`mine_block` may only be used on MiningChain instances') for _ in range(num_bloc...
[ "def", "mine_blocks", "(", "num_blocks", ":", "int", ",", "chain", ":", "MiningChain", ")", "->", "MiningChain", ":", "if", "not", "isinstance", "(", "chain", ",", "MiningChain", ")", ":", "raise", "ValidationError", "(", "'`mine_block` may only be used on MiningC...
40
17.777778
def _M2_sparse(Xvar, mask_X, Yvar, mask_Y, weights=None): """ 2nd moment matrix exploiting zero input columns """ C = np.zeros((len(mask_X), len(mask_Y))) C[np.ix_(mask_X, mask_Y)] = _M2_dense(Xvar, Yvar, weights=weights) return C
[ "def", "_M2_sparse", "(", "Xvar", ",", "mask_X", ",", "Yvar", ",", "mask_Y", ",", "weights", "=", "None", ")", ":", "C", "=", "np", ".", "zeros", "(", "(", "len", "(", "mask_X", ")", ",", "len", "(", "mask_Y", ")", ")", ")", "C", "[", "np", "...
48.4
15.8
def events_client(self, client): """ Get a client's events. Uses GET to /events/clients/<client> interface. :Args: * *client*: (str) Client's ID :Returns: (list) Events """ # TODO Add paging to this client = self._client_id(client) response = ...
[ "def", "events_client", "(", "self", ",", "client", ")", ":", "# TODO Add paging to this", "client", "=", "self", ".", "_client_id", "(", "client", ")", "response", "=", "self", ".", "_get", "(", "url", ".", "events_clients_id", ".", "format", "(", "id", "...
33
15.857143
def format_modes(modes, full_modes=False, current_mode=None): """ Creates a nice readily printable Table for a list of modes. Used in `displays list' and the candidates list in `displays set'. """ t = table.Table((( '*' if mode == current_mode else '', ...
[ "def", "format_modes", "(", "modes", ",", "full_modes", "=", "False", ",", "current_mode", "=", "None", ")", ":", "t", "=", "table", ".", "Table", "(", "(", "(", "'*'", "if", "mode", "==", "current_mode", "else", "''", ",", "# 0", "str", "(", "Q", ...
49.207547
16.471698
def corr(self): '''The correlation matrix''' cov = self.cov() N = cov.shape[0] corr = ndarray((N,N)) for r in range(N): for c in range(r): corr[r,c] = corr[c,r] = cov[r,c]/sqrt(cov[r,r]*cov[c,c]) corr[r,r] = 1. return corr
[ "def", "corr", "(", "self", ")", ":", "cov", "=", "self", ".", "cov", "(", ")", "N", "=", "cov", ".", "shape", "[", "0", "]", "corr", "=", "ndarray", "(", "(", "N", ",", "N", ")", ")", "for", "r", "in", "range", "(", "N", ")", ":", "for",...
31
15.6