text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def load_builtin_slots(): ''' Helper function to load builtin slots from the data location ''' builtin_slots = {} for index, line in enumerate(open(BUILTIN_SLOTS_LOCATION)): o = line.strip().split('\t') builtin_slots[index] = {'name' : o[0], 'descript...
[ "def", "load_builtin_slots", "(", ")", ":", "builtin_slots", "=", "{", "}", "for", "index", ",", "line", "in", "enumerate", "(", "open", "(", "BUILTIN_SLOTS_LOCATION", ")", ")", ":", "o", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "'\\t'",...
35
18.6
def init(args=None): """Initialize the rabit library with arguments""" if args is None: args = [] arr = (ctypes.c_char_p * len(args))() arr[:] = args _LIB.RabitInit(len(arr), arr)
[ "def", "init", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "arr", "=", "(", "ctypes", ".", "c_char_p", "*", "len", "(", "args", ")", ")", "(", ")", "arr", "[", ":", "]", "=", "args", "_LIB", "...
28.714286
13.428571
def get_core(self): """ Get an unsatisfiable core if the formula was previously unsatisfied. """ if self.maplesat and self.status == False: return pysolvers.maplecm_core(self.maplesat)
[ "def", "get_core", "(", "self", ")", ":", "if", "self", ".", "maplesat", "and", "self", ".", "status", "==", "False", ":", "return", "pysolvers", ".", "maplecm_core", "(", "self", ".", "maplesat", ")" ]
29.75
16.25
def check_subdomain(fqn): """ Verify that the given fqn is a subdomain >>> check_subdomain('a.b.c') True >>> check_subdomain(123) False >>> check_subdomain('a.b.c.d') False >>> check_subdomain('A.b.c') False >>> check_subdomain('abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdab...
[ "def", "check_subdomain", "(", "fqn", ")", ":", "if", "type", "(", "fqn", ")", "not", "in", "[", "str", ",", "unicode", "]", ":", "return", "False", "if", "not", "is_subdomain", "(", "fqn", ")", ":", "return", "False", "return", "True" ]
23.107143
21.607143
def get_authenticate_header(self, request): """ If a request is unauthenticated, determine the WWW-Authenticate header to use for 401 responses, if any. """ authenticators = self.get_authenticators() if authenticators: return authenticators[0].authenticate_hea...
[ "def", "get_authenticate_header", "(", "self", ",", "request", ")", ":", "authenticators", "=", "self", ".", "get_authenticators", "(", ")", "if", "authenticators", ":", "return", "authenticators", "[", "0", "]", ".", "authenticate_header", "(", "request", ")" ]
40.625
11.375
def _isrc_long(name=None): """ Creates the grammar for a short ISRC code. ISRC stands for International Standard Recording Code, which is the standard ISO 3901. This stores information identifying a particular recording. This variant contain no separator for the parts, and follows the pattern:...
[ "def", "_isrc_long", "(", "name", "=", "None", ")", ":", "config", "=", "CWRTables", "(", ")", "if", "name", "is", "None", ":", "name", "=", "'ISRC Field'", "country", "=", "config", ".", "get_data", "(", "'isrc_country_code'", ")", "# registrant = basic.alp...
24.541667
20.041667
def _process_children_elems(elem, dic, subdic, container=dict, children="@children", **options): """ :param elem: ET Element object or None :param dic: <container> (dict[-like]) object converted from elem :param subdic: Sub <container> object converted from elem :param co...
[ "def", "_process_children_elems", "(", "elem", ",", "dic", ",", "subdic", ",", "container", "=", "dict", ",", "children", "=", "\"@children\"", ",", "*", "*", "options", ")", ":", "cdics", "=", "[", "elem_to_container", "(", "c", ",", "container", "=", "...
42.72
20
def delete_firewall_rule(self, datacenter_id, server_id, nic_id, firewall_rule_id): """ Removes a firewall rule from the NIC. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The ...
[ "def", "delete_firewall_rule", "(", "self", ",", "datacenter_id", ",", "server_id", ",", "nic_id", ",", "firewall_rule_id", ")", ":", "response", "=", "self", ".", "_perform_request", "(", "url", "=", "'/datacenters/%s/servers/%s/nics/%s/firewallrules/%s'", "%", "(", ...
32.185185
18.259259
def play_track(self, track_id=DEFAULT_TRACK_ID, position=0): """Plays a track at the given position.""" self.publish( action='playTrack', resource='audioPlayback/player', publish_response=False, properties={'trackId': track_id, 'position': position} ...
[ "def", "play_track", "(", "self", ",", "track_id", "=", "DEFAULT_TRACK_ID", ",", "position", "=", "0", ")", ":", "self", ".", "publish", "(", "action", "=", "'playTrack'", ",", "resource", "=", "'audioPlayback/player'", ",", "publish_response", "=", "False", ...
39.5
14.25
def list_to_json(source_list): """ Serialise all the items in source_list to json """ result = [] for item in source_list: result.append(item.to_json()) return result
[ "def", "list_to_json", "(", "source_list", ")", ":", "result", "=", "[", "]", "for", "item", "in", "source_list", ":", "result", ".", "append", "(", "item", ".", "to_json", "(", ")", ")", "return", "result" ]
23.875
10.375
def discover_filename(label, scopes=None): ''' Check the filesystem for the existence of a .plist file matching the job label. Optionally specify one or more scopes to search (default all). :param label: string :param scope: tuple or list or oneOf(USER, USER_ADMIN, DAEMON_ADMIN, USER_OS, DAEMON_OS)...
[ "def", "discover_filename", "(", "label", ",", "scopes", "=", "None", ")", ":", "if", "scopes", "is", "None", ":", "scopes", "=", "[", "k", "for", "k", "in", "PLIST_LOCATIONS", "]", "elif", "not", "isinstance", "(", "scopes", ",", "(", "list", ",", "...
37.411765
20.705882
def is_field_remote(model, field_name): """Check whether a given model field is a remote field. A remote field is the inverse of a one-to-many or a many-to-many relationship. Arguments: model: a Django model field_name: the name of a field Returns: True if `field_name` is ...
[ "def", "is_field_remote", "(", "model", ",", "field_name", ")", ":", "if", "not", "hasattr", "(", "model", ",", "'_meta'", ")", ":", "# ephemeral model with no metaclass", "return", "False", "model_field", "=", "get_model_field", "(", "model", ",", "field_name", ...
29.789474
18.105263
def _setable_set_(name, self, func): "Used to set the attribute a single time using the given function." setattr(self._attr_data_, name, func()) if hasattr(self._attr_func_, name): delattr(self._attr_func_, name) setattr( type(self), name, ...
[ "def", "_setable_set_", "(", "name", ",", "self", ",", "func", ")", ":", "setattr", "(", "self", ".", "_attr_data_", ",", "name", ",", "func", "(", ")", ")", "if", "hasattr", "(", "self", ".", "_attr_func_", ",", "name", ")", ":", "delattr", "(", "...
26.733333
22.066667
def _permute_aux_specs(self): """Generate all permutations of the non-core specifications.""" # Convert to attr names that Calc is expecting. calc_aux_mapping = self._NAMES_SUITE_TO_CALC.copy() # Special case: manually add 'library' to mapping calc_aux_mapping[_OBJ_LIB_STR] = Non...
[ "def", "_permute_aux_specs", "(", "self", ")", ":", "# Convert to attr names that Calc is expecting.", "calc_aux_mapping", "=", "self", ".", "_NAMES_SUITE_TO_CALC", ".", "copy", "(", ")", "# Special case: manually add 'library' to mapping", "calc_aux_mapping", "[", "_OBJ_LIB_ST...
48.583333
15
def to_world(self, shape, dst_crs=None): """Return the shape (provided in pixel coordinates) in world coordinates, as GeoVector.""" if dst_crs is None: dst_crs = self.crs shp = transform(shape, self.crs, dst_crs, dst_affine=self.affine) return GeoVector(shp, dst_crs)
[ "def", "to_world", "(", "self", ",", "shape", ",", "dst_crs", "=", "None", ")", ":", "if", "dst_crs", "is", "None", ":", "dst_crs", "=", "self", ".", "crs", "shp", "=", "transform", "(", "shape", ",", "self", ".", "crs", ",", "dst_crs", ",", "dst_a...
51
9.666667
def get_user_modified_lines(self): """ Output: {file_path: [(line_a_start, line_a_end), (line_b_start, line_b_end)]} Lines ranges are sorted and not overlapping """ # I assume that git diff: # - doesn't mix diffs from different files, # - diffs are not overlappin...
[ "def", "get_user_modified_lines", "(", "self", ")", ":", "# I assume that git diff:", "# - doesn't mix diffs from different files,", "# - diffs are not overlapping", "# - diffs are sorted based on line numbers", "output", "=", "{", "}", "FILE_NAME_RE", "=", "r'^\\+\\+\\+ (.+)$'", "...
39.294118
20.117647
def setPalette(self, palette): """ Sets the palette for this node to the inputed palette. If None is provided, then the scene's palette will be used for this node. :param palette | <XNodePalette> || None """ self._palette = XNodePalette(palette) if palette ...
[ "def", "setPalette", "(", "self", ",", "palette", ")", ":", "self", ".", "_palette", "=", "XNodePalette", "(", "palette", ")", "if", "palette", "is", "not", "None", "else", "None", "self", ".", "setDirty", "(", ")" ]
39.666667
19.222222
def find_interior_point( distribution, parameters=None, cache=None, iterations=1000, retall=False, seed=None, ): """ Find interior point of the distribution where forward evaluation is guarantied to be both ``distribution.fwd(xloc) > 0`` and ``distribution...
[ "def", "find_interior_point", "(", "distribution", ",", "parameters", "=", "None", ",", "cache", "=", "None", ",", "iterations", "=", "1000", ",", "retall", "=", "False", ",", "seed", "=", "None", ",", ")", ":", "random_state", "=", "numpy", ".", "random...
32.219298
19.149123
def write_name (self, url_data): """Write url_data.name.""" args = (self.part("name"), cgi.escape(url_data.name)) self.writeln(u"<tr><td>%s</td><td>`%s'</td></tr>" % args)
[ "def", "write_name", "(", "self", ",", "url_data", ")", ":", "args", "=", "(", "self", ".", "part", "(", "\"name\"", ")", ",", "cgi", ".", "escape", "(", "url_data", ".", "name", ")", ")", "self", ".", "writeln", "(", "u\"<tr><td>%s</td><td>`%s'</td></tr...
48
13.5
def removeSubscribers(self, emails_list): """Remove subscribers from this workitem If the subscribers have not been added, no more actions will be performed. :param emails_list: a :class:`list`/:class:`tuple`/:class:`set` contains the the subscribers' emails """ ...
[ "def", "removeSubscribers", "(", "self", ",", "emails_list", ")", ":", "if", "not", "hasattr", "(", "emails_list", ",", "\"__iter__\"", ")", ":", "error_msg", "=", "\"Input parameter 'emails_list' is not iterable\"", "self", ".", "log", ".", "error", "(", "error_m...
34.206897
21.068966
def ReadAllClientGraphSeries( self, client_label, report_type, time_range = None, cursor=None): """Reads graph series for the given label and report-type from the DB.""" query = """ SELECT UNIX_TIMESTAMP(timestamp), graph_series FROM client_report_graphs WHERE cli...
[ "def", "ReadAllClientGraphSeries", "(", "self", ",", "client_label", ",", "report_type", ",", "time_range", "=", "None", ",", "cursor", "=", "None", ")", ":", "query", "=", "\"\"\"\n SELECT UNIX_TIMESTAMP(timestamp), graph_series\n FROM client_report_graphs\n W...
36.03125
20.375
def count_items(self): """Counts Items in full_soup and soup. For debugging""" soup_items = self.soup.findAll('item') full_soup_items = self.full_soup.findAll('item') return len(soup_items), len(full_soup_items)
[ "def", "count_items", "(", "self", ")", ":", "soup_items", "=", "self", ".", "soup", ".", "findAll", "(", "'item'", ")", "full_soup_items", "=", "self", ".", "full_soup", ".", "findAll", "(", "'item'", ")", "return", "len", "(", "soup_items", ")", ",", ...
47.8
10.4
def wait_for_fresh_games(self, poll_interval=15.0): """Block caller until required new games have been played. Args: poll_interval: number of seconds to wait between checks If the cell `table_state=metadata:wait_for_game_number` exists, then block the caller, checking every ...
[ "def", "wait_for_fresh_games", "(", "self", ",", "poll_interval", "=", "15.0", ")", ":", "wait_until_game", "=", "self", ".", "read_wait_cell", "(", ")", "if", "not", "wait_until_game", ":", "return", "latest_game", "=", "self", ".", "latest_game_number", "last_...
41.777778
15.814815
def add_glitch(psr, epoch, amp): """ Like pulsar term BWM event, but now differently parameterized: just an amplitude (not log-amp) parameter, and an epoch. [source: piccard] :param psr: pulsar object :param epoch: TOA time (MJD) the burst hits the earth :param amp: amplitude of the glitch ...
[ "def", "add_glitch", "(", "psr", ",", "epoch", ",", "amp", ")", ":", "# Define the heaviside function", "heaviside", "=", "lambda", "x", ":", "0.5", "*", "(", "N", ".", "sign", "(", "x", ")", "+", "1", ")", "# Glitches are spontaneous spin-up events.", "# Th...
34.055556
17.611111
def broadcast_info(team_id, date=datetime.now()): """Return BroadcastInfo object that containts information about the television and radio broadcasts for the team_id and year""" data = mlbgame.info.broadcast_info(team_id, date) return [mlbgame.info.BroadcastInfo(x) for x in data]
[ "def", "broadcast_info", "(", "team_id", ",", "date", "=", "datetime", ".", "now", "(", ")", ")", ":", "data", "=", "mlbgame", ".", "info", ".", "broadcast_info", "(", "team_id", ",", "date", ")", "return", "[", "mlbgame", ".", "info", ".", "BroadcastI...
49.166667
9.833333
def meff_lh_110(self, **kwargs): ''' Returns the light-hole band effective mass in the [110] direction, meff_lh_110, in units of electron mass. ''' return 2. / (2 * self.luttinger1(**kwargs) + self.luttinger2(**kwargs) + 3 * self.luttinger3(**kwargs))
[ "def", "meff_lh_110", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "2.", "/", "(", "2", "*", "self", ".", "luttinger1", "(", "*", "*", "kwargs", ")", "+", "self", ".", "luttinger2", "(", "*", "*", "kwargs", ")", "+", "3", "*", "sel...
43
21.857143
def build_csv_transforming_training_input_fn(schema, features, stats, analysis_output_dir, raw_data_file_pattern, ...
[ "def", "build_csv_transforming_training_input_fn", "(", "schema", ",", "features", ",", "stats", ",", "analysis_output_dir", ",", "raw_data_file_pattern", ",", "training_batch_size", ",", "num_epochs", "=", "None", ",", "randomize_input", "=", "False", ",", "min_after_d...
41.623762
22.554455
def derive_link_fields(self, context): """ Used to derive which fields should be linked. This should return a set() containing the names of those fields which should be linkable. """ if self.link_fields is not None: return self.link_fields else: ...
[ "def", "derive_link_fields", "(", "self", ",", "context", ")", ":", "if", "self", ".", "link_fields", "is", "not", "None", ":", "return", "self", ".", "link_fields", "else", ":", "link_fields", "=", "set", "(", ")", "if", "self", ".", "fields", ":", "f...
31.941176
14.294118
def file_cmd(context, tags, archive, bundle_name, path): """Add a file to a bundle.""" bundle_obj = context.obj['db'].bundle(bundle_name) if bundle_obj is None: click.echo(click.style(f"unknown bundle: {bundle_name}", fg='red')) context.abort() version_obj = bundle_obj.versions[0] ne...
[ "def", "file_cmd", "(", "context", ",", "tags", ",", "archive", ",", "bundle_name", ",", "path", ")", ":", "bundle_obj", "=", "context", ".", "obj", "[", "'db'", "]", ".", "bundle", "(", "bundle_name", ")", "if", "bundle_obj", "is", "None", ":", "click...
46.5
17.5625
def print_horiz_table(self, data): """Print a horizontal pretty table from data.""" # Build list of returned objects return_objects = list() fields = self.job_args.get('fields') if not fields: fields = set() for item_dict in data: for fiel...
[ "def", "print_horiz_table", "(", "self", ",", "data", ")", ":", "# Build list of returned objects", "return_objects", "=", "list", "(", ")", "fields", "=", "self", ".", "job_args", ".", "get", "(", "'fields'", ")", "if", "not", "fields", ":", "fields", "=", ...
29.84375
14.71875
def datapt_to_system(self, datapt, system=None, coords='data', naxispath=None): """ Map points to given coordinate system. Parameters ---------- datapt : array-like Pixel coordinates in the format of ``[[x0, y0, ...], [x1, y1, ......
[ "def", "datapt_to_system", "(", "self", ",", "datapt", ",", "system", "=", "None", ",", "coords", "=", "'data'", ",", "naxispath", "=", "None", ")", ":", "if", "self", ".", "coordsys", "==", "'raw'", ":", "raise", "common", ".", "WCSError", "(", "\"No ...
32.456522
21.413043
def add_recipients(self, id, recipients): """ Add recipients. Add recipients to an existing group conversation. Response is similar to the GET/show action, except that only includes the latest message (e.g. "joe was added to the conversation by bob") """ ...
[ "def", "add_recipients", "(", "self", ",", "id", ",", "recipients", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - id\r", "\"\"\"ID\"\"\"", "path", "[", "\"id\"", "]", "=", "id", "# REQUIRED - recipien...
42.625
25.708333
def localize(self, dt, is_dst=False): '''Convert naive time to local time. This method should be used to construct localtimes, rather than passing a tzinfo argument to a datetime constructor. is_dst is used to determine the correct timezone in the ambigous period at the end of ...
[ "def", "localize", "(", "self", ",", "dt", ",", "is_dst", "=", "False", ")", ":", "if", "dt", ".", "tzinfo", "is", "not", "None", ":", "raise", "ValueError", "(", "'Not naive datetime (tzinfo is already set)'", ")", "# Find the two best possibilities.", "possible_...
38.817518
19.79562
def listfolder(p): """ generator of list folder in the path. folders only """ for entry in scandir.scandir(p): if entry.is_dir(): yield entry.name
[ "def", "listfolder", "(", "p", ")", ":", "for", "entry", "in", "scandir", ".", "scandir", "(", "p", ")", ":", "if", "entry", ".", "is_dir", "(", ")", ":", "yield", "entry", ".", "name" ]
22.375
9.625
def sort_elements_by_child_values(obj_pyxb, child_name_list): """In-place sort simple or complex elements in a PyXB object by values they contain in child elements. Args: obj_pyxb: PyXB object child_name_list: list of str List of element names that are direct children of the PyXB objec...
[ "def", "sort_elements_by_child_values", "(", "obj_pyxb", ",", "child_name_list", ")", ":", "obj_pyxb", ".", "sort", "(", "key", "=", "lambda", "x", ":", "[", "get_auto", "(", "getattr", "(", "x", ",", "n", ")", ")", "for", "n", "in", "child_name_list", "...
33.666667
23.833333
def create_o3d_asset(self, manip=None, small_ov_set=None, large_ov_set=None, display_name='', description=''): """stub""" if manip and not isinstance(manip, ABCDataInputStream): ...
[ "def", "create_o3d_asset", "(", "self", ",", "manip", "=", "None", ",", "small_ov_set", "=", "None", ",", "large_ov_set", "=", "None", ",", "display_name", "=", "''", ",", "description", "=", "''", ")", ":", "if", "manip", "and", "not", "isinstance", "("...
59.371429
23.085714
def process_files(): """ Process files with a single progress bar """ with enlighten.Counter(total=100, desc='Simple', unit='ticks') as pbar: for num in range(100): # pylint: disable=unused-variable time.sleep(0.05) pbar.update()
[ "def", "process_files", "(", ")", ":", "with", "enlighten", ".", "Counter", "(", "total", "=", "100", ",", "desc", "=", "'Simple'", ",", "unit", "=", "'ticks'", ")", "as", "pbar", ":", "for", "num", "in", "range", "(", "100", ")", ":", "# pylint: dis...
30.111111
16.777778
def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ if not self._initialized: se...
[ "def", "report", "(", "self", ",", "simulation", ",", "state", ")", ":", "if", "not", "self", ".", "_initialized", ":", "self", ".", "_initialized", "=", "True", "self", ".", "_steps", "[", "0", "]", "+=", "self", ".", "interval", "positions", "=", "...
31.272727
15
def buildcontent(self): """build HTML content only, no header or body tags""" self.buildcontainer() self.option = json.dumps(self.options, cls = HighchartsEncoder) self.setoption = json.dumps(self.setOptions, cls = HighchartsEncoder) self.data = json.dumps(self.data_temp, cls =...
[ "def", "buildcontent", "(", "self", ")", ":", "self", ".", "buildcontainer", "(", ")", "self", ".", "option", "=", "json", ".", "dumps", "(", "self", ".", "options", ",", "cls", "=", "HighchartsEncoder", ")", "self", ".", "setoption", "=", "json", ".",...
49.764706
29.823529
def _clone_repo(cls, repo, url, path, name, **kwargs): """:return: Repo instance of newly cloned repository :param repo: our parent repository :param url: url to clone from :param path: repository-relative path to the submodule checkout location :param name: canonical of the subm...
[ "def", "_clone_repo", "(", "cls", ",", "repo", ",", "url", ",", "path", ",", "name", ",", "*", "*", "kwargs", ")", ":", "module_abspath", "=", "cls", ".", "_module_abspath", "(", "repo", ",", "path", ",", "name", ")", "module_checkout_path", "=", "modu...
49.090909
17.681818
def build_tree(self, rebuild=False): """ method builds tree by iterating from the synergy_start_timeperiod to the current time and inserting corresponding nodes """ time_qualifier = self.process_hierarchy.bottom_process.time_qualifier process_name = self.process_hierarchy.bottom_pro...
[ "def", "build_tree", "(", "self", ",", "rebuild", "=", "False", ")", ":", "time_qualifier", "=", "self", ".", "process_hierarchy", ".", "bottom_process", ".", "time_qualifier", "process_name", "=", "self", ".", "process_hierarchy", ".", "bottom_process", ".", "p...
46.736842
23.368421
def get_model(model:nn.Module): "Return the model maybe wrapped inside `model`." return model.module if isinstance(model, (DistributedDataParallel, nn.DataParallel)) else model
[ "def", "get_model", "(", "model", ":", "nn", ".", "Module", ")", ":", "return", "model", ".", "module", "if", "isinstance", "(", "model", ",", "(", "DistributedDataParallel", ",", "nn", ".", "DataParallel", ")", ")", "else", "model" ]
60.666667
26.666667
def copy_image_to_context(self, context, position, rotation=0, zoom=None): """Draw a cached image on the context :param context: The Cairo context to draw on :param position: The position od the image """ if not zoom: zoom = self.__zoom zoom_multiplicator = z...
[ "def", "copy_image_to_context", "(", "self", ",", "context", ",", "position", ",", "rotation", "=", "0", ",", "zoom", "=", "None", ")", ":", "if", "not", "zoom", ":", "zoom", "=", "self", ".", "__zoom", "zoom_multiplicator", "=", "zoom", "*", "self", "...
37.368421
20.526316
def endpoint_list(profile=None, **connection_args): ''' Return a list of available endpoints (keystone endpoints-list) CLI Example: .. code-block:: bash salt '*' keystone.endpoint_list ''' kstone = auth(profile, **connection_args) ret = {} for endpoint in kstone.endpoints.lis...
[ "def", "endpoint_list", "(", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}", "for", "endpoint", "in", "kstone", ".", "endpoints", "....
32.333333
28
def _init_auth(self, config): """ Init authentication @dict: configuration of ldapcherry """ self.auth_mode = self._get_param('auth', 'auth.mode', config) if self.auth_mode in ['and', 'or', 'none']: pass elif self.auth_mode == 'custom': # load cust...
[ "def", "_init_auth", "(", "self", ",", "config", ")", ":", "self", ".", "auth_mode", "=", "self", ".", "_get_param", "(", "'auth'", ",", "'auth.mode'", ",", "config", ")", "if", "self", ".", "auth_mode", "in", "[", "'and'", ",", "'or'", ",", "'none'", ...
38.44
17
def _get_price(self, package): """Returns valid price for ordering a dedicated host.""" for price in package['prices']: if not price.get('locationGroupId'): return price['id'] raise SoftLayer.SoftLayerError("Could not find valid price")
[ "def", "_get_price", "(", "self", ",", "package", ")", ":", "for", "price", "in", "package", "[", "'prices'", "]", ":", "if", "not", "price", ".", "get", "(", "'locationGroupId'", ")", ":", "return", "price", "[", "'id'", "]", "raise", "SoftLayer", "."...
35.375
16.625
def countSeries(requestContext, *seriesLists): """ Draws a horizontal line representing the number of nodes found in the seriesList. Example:: &target=countSeries(carbon.agents.*.*) """ if not seriesLists or not any(seriesLists): series = constantLine(requestContext, 0).pop() ...
[ "def", "countSeries", "(", "requestContext", ",", "*", "seriesLists", ")", ":", "if", "not", "seriesLists", "or", "not", "any", "(", "seriesLists", ")", ":", "series", "=", "constantLine", "(", "requestContext", ",", "0", ")", ".", "pop", "(", ")", "seri...
32.142857
20.809524
def __normalize_grades(self): """ Adjust the grades list. If a grade has been set, set All to false """ if 'grades' in self and self['grades']['All'] is True: for grade in self['grades']: if grade != 'All' and self['grades'][grade] is True: ...
[ "def", "__normalize_grades", "(", "self", ")", ":", "if", "'grades'", "in", "self", "and", "self", "[", "'grades'", "]", "[", "'All'", "]", "is", "True", ":", "for", "grade", "in", "self", "[", "'grades'", "]", ":", "if", "grade", "!=", "'All'", "and...
34.090909
13
def cellpar_to_cell(cellpar, ab_normal=(0,0,1), a_direction=None): """Return a 3x3 cell matrix from `cellpar` = [a, b, c, alpha, beta, gamma]. The returned cell is orientated such that a and b are normal to `ab_normal` and a is parallel to the projection of `a_direction` in the a-b plane. Default ...
[ "def", "cellpar_to_cell", "(", "cellpar", ",", "ab_normal", "=", "(", "0", ",", "0", ",", "1", ")", ",", "a_direction", "=", "None", ")", ":", "if", "a_direction", "is", "None", ":", "if", "np", ".", "linalg", ".", "norm", "(", "np", ".", "cross", ...
33.580645
18.290323
def grad(self, X, mean=None, lenscale=None): r""" Get the gradients of this basis w.r.t.\ the mean and length scales. Parameters ---------- x: ndarray (n, d) array of observations where n is the number of samples, and d is the dimensionality of x. ...
[ "def", "grad", "(", "self", ",", "X", ",", "mean", "=", "None", ",", "lenscale", "=", "None", ")", ":", "d", "=", "X", ".", "shape", "[", "1", "]", "mean", "=", "self", ".", "_check_dim", "(", "d", ",", "mean", ",", "paramind", "=", "0", ")",...
39.016667
21.533333
def parse(s): """Parse a string representation back into the Vector. >>> Vectors.parse('[2,1,2 ]') DenseVector([2.0, 1.0, 2.0]) >>> Vectors.parse(' ( 100, [0], [2])') SparseVector(100, {0: 2.0}) """ if s.find('(') == -1 and s.find('[') != -1: return...
[ "def", "parse", "(", "s", ")", ":", "if", "s", ".", "find", "(", "'('", ")", "==", "-", "1", "and", "s", ".", "find", "(", "'['", ")", "!=", "-", "1", ":", "return", "DenseVector", ".", "parse", "(", "s", ")", "elif", "s", ".", "find", "(",...
34.4
11.8
def check_field_cohesion(self, rec_write_fields, sig_write_fields): """ Check the cohesion of fields used to write the header """ # If there are no signal specification fields, there is nothing to check. if self.n_sig>0: # The length of all signal specification fiel...
[ "def", "check_field_cohesion", "(", "self", ",", "rec_write_fields", ",", "sig_write_fields", ")", ":", "# If there are no signal specification fields, there is nothing to check.", "if", "self", ".", "n_sig", ">", "0", ":", "# The length of all signal specification fields must ma...
48.441176
24.794118
def op_at_on(operation: ops.Operation, time: Timestamp, device: Device): """Creates a scheduled operation with a device-determined duration.""" return ScheduledOperation(time, device.duration_of(operation), ...
[ "def", "op_at_on", "(", "operation", ":", "ops", ".", "Operation", ",", "time", ":", "Timestamp", ",", "device", ":", "Device", ")", ":", "return", "ScheduledOperation", "(", "time", ",", "device", ".", "duration_of", "(", "operation", ")", ",", "operation...
47
6.428571
def compile_search(pattern, flags=0, **kwargs): """Compile with extended search references.""" return _regex.compile(_apply_search_backrefs(pattern, flags), flags, **kwargs)
[ "def", "compile_search", "(", "pattern", ",", "flags", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "_regex", ".", "compile", "(", "_apply_search_backrefs", "(", "pattern", ",", "flags", ")", ",", "flags", ",", "*", "*", "kwargs", ")" ]
44.75
22.25
def color_text(text, color): r""" SeeAlso: highlight_text lexer_shortnames = sorted(ut.flatten(ut.take_column(pygments.lexers.LEXERS.values(), 2))) """ import utool as ut if color is None or not ENABLE_COLORS: return text elif color == 'python': return highlight_t...
[ "def", "color_text", "(", "text", ",", "color", ")", ":", "import", "utool", "as", "ut", "if", "color", "is", "None", "or", "not", "ENABLE_COLORS", ":", "return", "text", "elif", "color", "==", "'python'", ":", "return", "highlight_text", "(", "text", ",...
31.866667
14.766667
def from_dict(data, ctx): """ Instantiate a new Instrument from a dict (generally from loading a JSON response). The data used to instantiate the Instrument is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ data...
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "data", "=", "data", ".", "copy", "(", ")", "if", "data", ".", "get", "(", "'minimumTradeSize'", ")", "is", "not", "None", ":", "data", "[", "'minimumTradeSize'", "]", "=", "ctx", ".", "convert_d...
35.553191
22.617021
def extract_included(cls, fields, resource, resource_instance, included_resources, included_cache): """ Adds related data to the top level included key when the request includes ?include=example,example_field2 """ # this function may be called with an emp...
[ "def", "extract_included", "(", "cls", ",", "fields", ",", "resource", ",", "resource_instance", ",", "included_resources", ",", "included_cache", ")", ":", "# this function may be called with an empty record (example: Browsable Interface)", "if", "not", "resource_instance", ...
45.314961
22.023622
def deactivate_mfa_device(self, user_name, serial_number): """Deactivate and detach MFA Device from user if device exists.""" user = self.get_user(user_name) if serial_number not in user.mfa_devices: raise IAMNotFoundException( "Device {0} not found".format(serial_num...
[ "def", "deactivate_mfa_device", "(", "self", ",", "user_name", ",", "serial_number", ")", ":", "user", "=", "self", ".", "get_user", "(", "user_name", ")", "if", "serial_number", "not", "in", "user", ".", "mfa_devices", ":", "raise", "IAMNotFoundException", "(...
42.333333
13.888889
def extract_bs(self, cutoff, ligcentroid, resis): """Return list of ids from residues belonging to the binding site""" return [obres.GetIdx() for obres in resis if self.res_belongs_to_bs(obres, cutoff, ligcentroid)]
[ "def", "extract_bs", "(", "self", ",", "cutoff", ",", "ligcentroid", ",", "resis", ")", ":", "return", "[", "obres", ".", "GetIdx", "(", ")", "for", "obres", "in", "resis", "if", "self", ".", "res_belongs_to_bs", "(", "obres", ",", "cutoff", ",", "ligc...
76.333333
24.333333
def _init_metadata(self): """stub""" self._start_timestamp_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'start_timestamp'), 'element_label': 'start timestamp', ...
[ "def", "_init_metadata", "(", "self", ")", ":", "self", ".", "_start_timestamp_metadata", "=", "{", "'element_id'", ":", "Id", "(", "self", ".", "my_osid_object_form", ".", "_authority", ",", "self", ".", "my_osid_object_form", ".", "_namespace", ",", "'start_ti...
39.147059
12.911765
def _get_registry(self, registry_path_or_url): '''dict: Return the registry as dict with profiles keyed by id.''' if registry_path_or_url.startswith('http'): profiles = self._load_json_url(registry_path_or_url) else: profiles = self._load_json_file(registry_path_or_url) ...
[ "def", "_get_registry", "(", "self", ",", "registry_path_or_url", ")", ":", "if", "registry_path_or_url", ".", "startswith", "(", "'http'", ")", ":", "profiles", "=", "self", ".", "_load_json_url", "(", "registry_path_or_url", ")", "else", ":", "profiles", "=", ...
41.3125
16.1875
def write_stats_as_csv(gtfs, path_to_csv, re_write=False): """ Writes data from get_stats to csv file Parameters ---------- gtfs: GTFS path_to_csv: str filepath to the csv file to be generated re_write: insted of appending, create a new one. """ stats_dict = get_stat...
[ "def", "write_stats_as_csv", "(", "gtfs", ",", "path_to_csv", ",", "re_write", "=", "False", ")", ":", "stats_dict", "=", "get_stats", "(", "gtfs", ")", "# check if file exist", "if", "re_write", ":", "os", ".", "remove", "(", "path_to_csv", ")", "#if not os.p...
27.695652
16.782609
def delete_tracking_beacon(self, tracking_beacons_id, **data): """ DELETE /tracking_beacons/:tracking_beacons_id/ Delete the :format:`tracking_beacons` with the specified :tracking_beacons_id. """ return self.delete("/tracking_beacons/{0}/".format(tracking_beacons_id), d...
[ "def", "delete_tracking_beacon", "(", "self", ",", "tracking_beacons_id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "delete", "(", "\"/tracking_beacons/{0}/\"", ".", "format", "(", "tracking_beacons_id", ")", ",", "data", "=", "data", ")" ]
46.142857
23.571429
def get_value(self): """ Return dictionary with values of subsettings. Returns: dict: values of subsettings. """ try: self.raw_value except (AttributeError, KeyError) as err: self._reraise_if_required(err) default_value = s...
[ "def", "get_value", "(", "self", ")", ":", "try", ":", "self", ".", "raw_value", "except", "(", "AttributeError", ",", "KeyError", ")", "as", "err", ":", "self", ".", "_reraise_if_required", "(", "err", ")", "default_value", "=", "self", ".", "default_valu...
32.52381
14.047619
def comp(seq): """ returns a seq with complement. Preserves little n's for splitters.""" ## makes base to its small complement then makes upper return seq.replace("A", 't')\ .replace('T', 'a')\ .replace('C', 'g')\ .replace('G', 'c')\ .replace('n', 'Z')...
[ "def", "comp", "(", "seq", ")", ":", "## makes base to its small complement then makes upper", "return", "seq", ".", "replace", "(", "\"A\"", ",", "'t'", ")", ".", "replace", "(", "'T'", ",", "'a'", ")", ".", "replace", "(", "'C'", ",", "'g'", ")", ".", ...
36.9
10.4
def help_for_command(command): """Get the help text (signature + docstring) for a command (function).""" help_text = pydoc.text.document(command) # remove backspaces return re.subn('.\\x08', '', help_text)[0]
[ "def", "help_for_command", "(", "command", ")", ":", "help_text", "=", "pydoc", ".", "text", ".", "document", "(", "command", ")", "# remove backspaces", "return", "re", ".", "subn", "(", "'.\\\\x08'", ",", "''", ",", "help_text", ")", "[", "0", "]" ]
44
7.4
def list_keys(self, secret=False): """List the keys currently in the keyring. The GnuPG option '--show-photos', according to the GnuPG manual, "does not work with --with-colons", but since we can't rely on all versions of GnuPG to explicitly handle this correctly, we should probably ...
[ "def", "list_keys", "(", "self", ",", "secret", "=", "False", ")", ":", "which", "=", "'public-keys'", "if", "secret", ":", "which", "=", "'secret-keys'", "args", "=", "[", "]", "args", ".", "append", "(", "\"--fixed-list-mode\"", ")", "args", ".", "appe...
36.837209
15.046512
def run(self): """Continously scan for BLE advertisements.""" self.socket = self.bluez.hci_open_dev(self.bt_device_id) filtr = self.bluez.hci_filter_new() self.bluez.hci_filter_all_events(filtr) self.bluez.hci_filter_set_ptype(filtr, self.bluez.HCI_EVENT_PKT) self.socket...
[ "def", "run", "(", "self", ")", ":", "self", ".", "socket", "=", "self", ".", "bluez", ".", "hci_open_dev", "(", "self", ".", "bt_device_id", ")", "filtr", "=", "self", ".", "bluez", ".", "hci_filter_new", "(", ")", "self", ".", "bluez", ".", "hci_fi...
38.55
17.35
def record_affiliations(self, key, value): """Populate the ``record_affiliations`` key.""" record = get_record_ref(value.get('z'), 'institutions') return { 'curated_relation': record is not None, 'record': record, 'value': value.get('a'), }
[ "def", "record_affiliations", "(", "self", ",", "key", ",", "value", ")", ":", "record", "=", "get_record_ref", "(", "value", ".", "get", "(", "'z'", ")", ",", "'institutions'", ")", "return", "{", "'curated_relation'", ":", "record", "is", "not", "None", ...
30.333333
17.111111
def init_app(self, app): """Flask application initialization.""" self.init_config(app) self.cache = Cache(app) self.is_authenticated_callback = _callback_factory( app.config['CACHE_IS_AUTHENTICATED_CALLBACK']) app.extensions['invenio-cache'] = self
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "init_config", "(", "app", ")", "self", ".", "cache", "=", "Cache", "(", "app", ")", "self", ".", "is_authenticated_callback", "=", "_callback_factory", "(", "app", ".", "config", "[", ...
42
11.285714
def get_token_from_offset(self, offset): """ Returns the token containing the given character offset (0-based position in source text), or the preceeding token if the position is between tokens. """ return self._tokens[bisect.bisect(self._token_offsets, offset) - 1]
[ "def", "get_token_from_offset", "(", "self", ",", "offset", ")", ":", "return", "self", ".", "_tokens", "[", "bisect", ".", "bisect", "(", "self", ".", "_token_offsets", ",", "offset", ")", "-", "1", "]" ]
46.833333
17.833333
def rse(label, pred): """computes the root relative squared error (condensed using standard deviation formula)""" numerator = np.sqrt(np.mean(np.square(label - pred), axis = None)) denominator = np.std(label, axis = None) return numerator / denominator
[ "def", "rse", "(", "label", ",", "pred", ")", ":", "numerator", "=", "np", ".", "sqrt", "(", "np", ".", "mean", "(", "np", ".", "square", "(", "label", "-", "pred", ")", ",", "axis", "=", "None", ")", ")", "denominator", "=", "np", ".", "std", ...
52.8
11.8
def f_add_result(self, *args, **kwargs): """Adds a result under the current node. There are two ways to add a new result either by adding a result instance: >>> new_result = Result('group1.group2.myresult', 1666, x=3, y=4, comment='Example!') >>> traj.f_add_result(new_result) ...
[ "def", "f_add_result", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_nn_interface", ".", "_add_generic", "(", "self", ",", "type_name", "=", "RESULT", ",", "group_type_name", "=", "RESULT_GROUP", ",", "args", ...
44.65625
34.375
def do_db_auth(host, connection, db_name): """ Attempts to authenticate against the mongo instance. Tries: - Auth'ing against admin as 'admin' ; credentials: <host>/arctic/admin/admin - Auth'ing against db_name (which may be None if auth'ing against admin above) returns True if authenticat...
[ "def", "do_db_auth", "(", "host", ",", "connection", ",", "db_name", ")", ":", "admin_creds", "=", "get_auth", "(", "host", ",", "'admin'", ",", "'admin'", ")", "user_creds", "=", "get_auth", "(", "host", ",", "'arctic'", ",", "db_name", ")", "# Attempt to...
47.6
27.866667
def _connect(self): """ Connect to the statsd server """ if not statsd: return if hasattr(statsd, 'StatsClient'): self.connection = statsd.StatsClient( host=self.host, port=self.port ).pipeline() else: ...
[ "def", "_connect", "(", "self", ")", ":", "if", "not", "statsd", ":", "return", "if", "hasattr", "(", "statsd", ",", "'StatsClient'", ")", ":", "self", ".", "connection", "=", "statsd", ".", "StatsClient", "(", "host", "=", "self", ".", "host", ",", ...
25.631579
13.315789
def join(left, right, key=None, lkey=None, rkey=None, presorted=False, buffersize=None, tempdir=None, cache=True, lprefix=None, rprefix=None): """ Perform an equi-join on the given tables. E.g.:: >>> import petl as etl >>> table1 = [['id', 'colour'], ... [1, 'blue'], ...
[ "def", "join", "(", "left", ",", "right", ",", "key", "=", "None", ",", "lkey", "=", "None", ",", "rkey", "=", "None", ",", "presorted", "=", "False", ",", "buffersize", "=", "None", ",", "tempdir", "=", "None", ",", "cache", "=", "True", ",", "l...
38.063158
11.852632
def _get_movielens_path(): """ Get path to the movielens dataset file. """ return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'movielens.zip')
[ "def", "_get_movielens_path", "(", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ",", "'movielens.zip'", ")" ]
27.142857
12
def uri(self, value, strip_iri=True): """ Converts py_uri or ttl uri to a http://... full uri format Args: value: the string to convert Returns: full uri of an abbreivated uri """ return self.convert_to_uri(value, strip_iri=strip_iri)
[ "def", "uri", "(", "self", ",", "value", ",", "strip_iri", "=", "True", ")", ":", "return", "self", ".", "convert_to_uri", "(", "value", ",", "strip_iri", "=", "strip_iri", ")" ]
26.454545
18
def save(self, filename): '''save fence points to a file''' f = open(filename, mode='w') for p in self.rally_points: f.write("RALLY %f\t%f\t%f\t%f\t%f\t%d\n" % (p.lat * 1e-7, p.lng * 1e-7, p.alt, p.break_alt, p.land_dir, p.flags...
[ "def", "save", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "mode", "=", "'w'", ")", "for", "p", "in", "self", ".", "rally_points", ":", "f", ".", "write", "(", "\"RALLY %f\\t%f\\t%f\\t%f\\t%f\\t%d\\n\"", "%", "(", "p...
47.714286
21.142857
def interrupt_kernel(self): """ Attempts to interrupt the running kernel. Also unsets _reading flag, to avoid runtime errors if raw_input is called again. """ if self.custom_interrupt: self._reading = False self.custom_interrupt_requested.emit() ...
[ "def", "interrupt_kernel", "(", "self", ")", ":", "if", "self", ".", "custom_interrupt", ":", "self", ".", "_reading", "=", "False", "self", ".", "custom_interrupt_requested", ".", "emit", "(", ")", "elif", "self", ".", "kernel_manager", ".", "has_kernel", "...
39.6
13.466667
def write(self, output='', flush=True, position=0): """ Args: output(str: Output string flush(bool): Flush the output stream after writing position(int): Position relative to the bottom of the screen to write output Write to stream at a given position ...
[ "def", "write", "(", "self", ",", "output", "=", "''", ",", "flush", "=", "True", ",", "position", "=", "0", ")", ":", "if", "self", ".", "enabled", ":", "term", "=", "self", ".", "term", "stream", "=", "self", ".", "stream", "try", ":", "term", ...
36.413793
21.310345
def add_item(self, item): """Updates the list of items in the current transaction""" _idx = len(self.items) self.items.update({"item_" + str(_idx + 1): item})
[ "def", "add_item", "(", "self", ",", "item", ")", ":", "_idx", "=", "len", "(", "self", ".", "items", ")", "self", ".", "items", ".", "update", "(", "{", "\"item_\"", "+", "str", "(", "_idx", "+", "1", ")", ":", "item", "}", ")" ]
44.75
10.75
def short_doc(self): """Gets the "short" documentation of a command. By default, this is the :attr:`brief` attribute. If that lookup leads to an empty string then the first line of the :attr:`help` attribute is used instead. """ if self.brief is not None: ret...
[ "def", "short_doc", "(", "self", ")", ":", "if", "self", ".", "brief", "is", "not", "None", ":", "return", "self", ".", "brief", "if", "self", ".", "help", "is", "not", "None", ":", "return", "self", ".", "help", ".", "split", "(", "'\\n'", ",", ...
35.166667
14.166667
def fetch_friend_ids(self, user): """ fethces friend id's from twitter Return: collection of friend ids """ friends = self.fetch_friends(user) friend_ids = [] for friend in friends: friend_ids.append(friend.id) return friend_ids
[ "def", "fetch_friend_ids", "(", "self", ",", "user", ")", ":", "friends", "=", "self", ".", "fetch_friends", "(", "user", ")", "friend_ids", "=", "[", "]", "for", "friend", "in", "friends", ":", "friend_ids", ".", "append", "(", "friend", ".", "id", ")...
25.5
10
def get_template_loader(self, app, subdir='templates', create=False): ''' Returns a template loader object for the given app name in the given subdir. For example, get_template_loader('homepage', 'styles') will return a loader for the styles/ directory in the homepage app. The a...
[ "def", "get_template_loader", "(", "self", ",", "app", ",", "subdir", "=", "'templates'", ",", "create", "=", "False", ")", ":", "# ensure we have an AppConfig", "if", "app", "is", "None", ":", "raise", "TemplateDoesNotExist", "(", "\"Cannot locate loader when app i...
49.8
29.65
def set_provider_links(self, resource_ids=None): """Sets a provider chain in order from the most recent source to the originating source. :param resource_ids: the new source :type resource_ids: ``osid.id.Id[]`` :raise: ``InvalidArgument`` -- ``resource_ids`` is invalid :...
[ "def", "set_provider_links", "(", "self", ",", "resource_ids", "=", "None", ")", ":", "if", "resource_ids", "is", "None", ":", "raise", "NullArgument", "(", ")", "metadata", "=", "Metadata", "(", "*", "*", "settings", ".", "METADATA", "[", "'provider_link_id...
40.458333
17
def InsertData(self, table_id, fd, schema, job_id): """Insert data into a bigquery table. If the table specified doesn't exist, it will be created with the specified schema. Args: table_id: string table id fd: open file descriptor containing the newline separated JSON schema: BigQuer...
[ "def", "InsertData", "(", "self", ",", "table_id", ",", "fd", ",", "schema", ",", "job_id", ")", ":", "configuration", "=", "{", "\"schema\"", ":", "{", "\"fields\"", ":", "schema", "}", ",", "\"destinationTable\"", ":", "{", "\"projectId\"", ":", "self", ...
30.388889
19.5
def update_property(self, name, old_value, new_value): # type: (str, Any, Any) -> None """ Handles a property changed event :param name: The changed property name :param old_value: The previous property value :param new_value: The new property value """ w...
[ "def", "update_property", "(", "self", ",", "name", ",", "old_value", ",", "new_value", ")", ":", "# type: (str, Any, Any) -> None", "with", "self", ".", "_lock", ":", "self", ".", "__safe_handlers_callback", "(", "\"on_property_change\"", ",", "name", ",", "old_v...
34.230769
11.615385
def get_code(self): """Opens the link and returns the response's content.""" if self.code is None: self.code = urlopen(self.url).read() return self.code
[ "def", "get_code", "(", "self", ")", ":", "if", "self", ".", "code", "is", "None", ":", "self", ".", "code", "=", "urlopen", "(", "self", ".", "url", ")", ".", "read", "(", ")", "return", "self", ".", "code" ]
36.8
11.2
def _get_ll_pointer_type(self, target_data, context=None): """ Convert this type object to an LLVM type. """ from . import Module, GlobalVariable from ..binding import parse_assembly if context is None: m = Module() else: m = Module(contex...
[ "def", "_get_ll_pointer_type", "(", "self", ",", "target_data", ",", "context", "=", "None", ")", ":", "from", ".", "import", "Module", ",", "GlobalVariable", "from", ".", ".", "binding", "import", "parse_assembly", "if", "context", "is", "None", ":", "m", ...
33.785714
11.785714
def commit(self): """ Insert the text at the current cursor position. """ # Backup and remove the currently selected text (may be none). tc = self.qteWidget.textCursor() self.selText = tc.selection().toHtml() self.selStart = tc.selectionStart() self.selEn...
[ "def", "commit", "(", "self", ")", ":", "# Backup and remove the currently selected text (may be none).", "tc", "=", "self", ".", "qteWidget", ".", "textCursor", "(", ")", "self", ".", "selText", "=", "tc", ".", "selection", "(", ")", ".", "toHtml", "(", ")", ...
39.21875
17.59375
def GetRunlevelsLSB(states): """Accepts a string and returns a list of strings of numeric LSB runlevels.""" if not states: return set() valid = set(["0", "1", "2", "3", "4", "5", "6"]) _LogInvalidRunLevels(states, valid) return valid.intersection(set(states.split()))
[ "def", "GetRunlevelsLSB", "(", "states", ")", ":", "if", "not", "states", ":", "return", "set", "(", ")", "valid", "=", "set", "(", "[", "\"0\"", ",", "\"1\"", ",", "\"2\"", ",", "\"3\"", ",", "\"4\"", ",", "\"5\"", ",", "\"6\"", "]", ")", "_LogInv...
39.285714
11.571429
def to_string(input_): """Format an input for representation as text This method is just a convenience that handles default LaTeX formatting """ usetex = rcParams['text.usetex'] if isinstance(input_, units.UnitBase): return input_.to_string('latex_inline') if isinstance(input_, (float, ...
[ "def", "to_string", "(", "input_", ")", ":", "usetex", "=", "rcParams", "[", "'text.usetex'", "]", "if", "isinstance", "(", "input_", ",", "units", ".", "UnitBase", ")", ":", "return", "input_", ".", "to_string", "(", "'latex_inline'", ")", "if", "isinstan...
34.384615
12.538462
def lml(self): """ Log of the marginal likelihood. Let 𝐲 = vec(Y), M = A⊗X, and H = MᵀK⁻¹M. The restricted log of the marginal likelihood is given by [R07]_:: 2⋅log(p(𝐲)) = -(n⋅p - c⋅p) log(2π) + log(|MᵀM|) - log(|K|) - log(|H|) - (𝐲-𝐦)ᵀ K⁻¹ (𝐲-𝐦), ...
[ "def", "lml", "(", "self", ")", ":", "terms", "=", "self", ".", "_terms", "yKiy", "=", "terms", "[", "\"yKiy\"", "]", "mKiy", "=", "terms", "[", "\"mKiy\"", "]", "mKim", "=", "terms", "[", "\"mKim\"", "]", "lml", "=", "-", "self", ".", "_df", "*"...
29.569231
22.8
def show_address_scope(self, address_scope, **_params): """Fetches information of a certain address scope.""" return self.get(self.address_scope_path % (address_scope), params=_params)
[ "def", "show_address_scope", "(", "self", ",", "address_scope", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "self", ".", "address_scope_path", "%", "(", "address_scope", ")", ",", "params", "=", "_params", ")" ]
55.25
10.5
def get_locations(self): ''' a method to retrieve all the locations tracked by the model :return: dictionary with location id keys NOTE: results are added to self.locations property { 'location.id': { ' ...
[ "def", "get_locations", "(", "self", ")", ":", "import", "requests", "url", "=", "self", ".", "endpoint", "+", "'/locations'", "params", "=", "{", "'group'", ":", "self", ".", "group_name", "}", "response", "=", "requests", ".", "get", "(", "url", ",", ...
26.222222
21.407407
def notebook_mode(m): """ Configure whether this module should assume that it is being run from a jupyter notebook. This sets some global variables related to how progress for long measurement sequences is indicated. :param bool m: If True, assume to be in notebook. :return: None :rtype: No...
[ "def", "notebook_mode", "(", "m", ")", ":", "global", "NOTEBOOK_MODE", "global", "TRANGE", "NOTEBOOK_MODE", "=", "m", "if", "NOTEBOOK_MODE", ":", "TRANGE", "=", "tqdm", ".", "tnrange", "else", ":", "TRANGE", "=", "tqdm", ".", "trange" ]
27.882353
22.235294
def get_user_activities(self, username, tournament=1): """Get user activities (works for all users!). Args: username (str): name of the user tournament (int): ID of the tournament (optional, defaults to 1) Returns: list: list of user activities (`dict`) ...
[ "def", "get_user_activities", "(", "self", ",", "username", ",", "tournament", "=", "1", ")", ":", "query", "=", "'''\n query($tournament: Int!\n $username: String!) {\n userActivities(tournament: $tournament\n username: $usern...
35.027778
15.388889
def get_codec(path): """Find the codec implementation for this path.""" if '.' not in path or path.rfind('/') > path.rfind('.'): return Codec for endings, codec_class in FILE_ENDINGS: if any(path.endswith(e) for e in endings): log.debug('Using {0} codec: {1}'.format(endings, pat...
[ "def", "get_codec", "(", "path", ")", ":", "if", "'.'", "not", "in", "path", "or", "path", ".", "rfind", "(", "'/'", ")", ">", "path", ".", "rfind", "(", "'.'", ")", ":", "return", "Codec", "for", "endings", ",", "codec_class", "in", "FILE_ENDINGS", ...
33.090909
19.454545
def visualize(self, show_ports=False): """Visualize the Compound using nglview. Allows for visualization of a Compound within a Jupyter Notebook. Parameters ---------- show_ports : bool, optional, default=False Visualize Ports in addition to Particles """ ...
[ "def", "visualize", "(", "self", ",", "show_ports", "=", "False", ")", ":", "nglview", "=", "import_", "(", "'nglview'", ")", "from", "mdtraj", ".", "geometry", ".", "sasa", "import", "_ATOMIC_RADII", "if", "run_from_ipython", "(", ")", ":", "remove_digits",...
43.604167
16.958333