text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _fixPe(self): """ Fixes the necessary fields in the PE file instance in order to create a valid PE32. i.e. SizeOfImage. """ sizeOfImage = 0 for sh in self.sectionHeaders: sizeOfImage += sh.misc self.ntHeaders.optionaHeader.sizeoOfImage.value = self._sectio...
[ "def", "_fixPe", "(", "self", ")", ":", "sizeOfImage", "=", "0", "for", "sh", "in", "self", ".", "sectionHeaders", ":", "sizeOfImage", "+=", "sh", ".", "misc", "self", ".", "ntHeaders", ".", "optionaHeader", ".", "sizeoOfImage", ".", "value", "=", "self"...
43.125
0.011364
async def open_pipe_connection( path=None, *, loop=None, limit=DEFAULT_LIMIT, **kwargs ): """ Connect to a server using a Windows named pipe. """ path = path.replace('/', '\\') loop = loop or asyncio.get_event_loop() reader = asyncio.StreamReader(limit=limit, loop=loop) ...
[ "async", "def", "open_pipe_connection", "(", "path", "=", "None", ",", "*", ",", "loop", "=", "None", ",", "limit", "=", "DEFAULT_LIMIT", ",", "*", "*", "kwargs", ")", ":", "path", "=", "path", ".", "replace", "(", "'/'", ",", "'\\\\'", ")", "loop", ...
24.73913
0.001692
def value(self, key, default=None): """ Returns the value from the current settings. :param key | <str> default | <variant> :return <variant> """ curr = self._stack[-1] return curr.get(key, default)
[ "def", "value", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "curr", "=", "self", ".", "_stack", "[", "-", "1", "]", "return", "curr", ".", "get", "(", "key", ",", "default", ")" ]
27.727273
0.012698
def remove_key(key: str, persists: bool = True): """ Removes the specified key from the cauldron configs if the key exists :param key: The key in the cauldron configs object to remove :param persists: """ environ.configs.remove(key, include_persists=persists) environ.configs.save()...
[ "def", "remove_key", "(", "key", ":", "str", ",", "persists", ":", "bool", "=", "True", ")", ":", "environ", ".", "configs", ".", "remove", "(", "key", ",", "include_persists", "=", "persists", ")", "environ", ".", "configs", ".", "save", "(", ")", "...
26.4
0.002439
def _EntryToEvent(entry, handlers, transformers): """Converts an APIAuditEntry to a legacy AuditEvent.""" event = rdf_events.AuditEvent( timestamp=entry.timestamp, user=entry.username, action=handlers[entry.router_method_name]) for fn in transformers: fn(entry, event) return event
[ "def", "_EntryToEvent", "(", "entry", ",", "handlers", ",", "transformers", ")", ":", "event", "=", "rdf_events", ".", "AuditEvent", "(", "timestamp", "=", "entry", ".", "timestamp", ",", "user", "=", "entry", ".", "username", ",", "action", "=", "handlers...
27.545455
0.015974
async def _connect_polling(self, url, headers, engineio_path): """Establish a long-polling connection to the Engine.IO server.""" if aiohttp is None: # pragma: no cover self.logger.error('aiohttp not installed -- cannot make HTTP ' 'requests!') retu...
[ "async", "def", "_connect_polling", "(", "self", ",", "url", ",", "headers", ",", "engineio_path", ")", ":", "if", "aiohttp", "is", "None", ":", "# pragma: no cover", "self", ".", "logger", ".", "error", "(", "'aiohttp not installed -- cannot make HTTP '", "'reque...
46.113208
0.000801
def find_objects(self, linespec): """Find lines that match the linespec regex. :param linespec: regular expression of line to match :return: list of LineItem objects """ # Note(asr1kteam): In this code we are only adding children one-level # deep to a given parent (lines...
[ "def", "find_objects", "(", "self", ",", "linespec", ")", ":", "# Note(asr1kteam): In this code we are only adding children one-level", "# deep to a given parent (linespec), as that satisfies the IOS conf", "# parsing.", "# Note(asr1kteam): Not tested with tabs in the config. Currently used", ...
45.75
0.001529
def generate_report(out_dir, latex_summaries, nb_markers, nb_samples, options): """Generates the report. :param out_dir: the output directory. :param latex_summaries: the list of LaTeX summaries. :param nb_markers: the final number of markers. :param nb_samples: the final number of samples. :pa...
[ "def", "generate_report", "(", "out_dir", ",", "latex_summaries", ",", "nb_markers", ",", "nb_samples", ",", "options", ")", ":", "# Getting the graphic paths file", "graphic_paths_fn", "=", "None", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path",...
36.95
0.000659
def _parse_typed_parameter_typed_value(values): ''' Creates Arguments in a TypedParametervalue. ''' type_, value = _expand_one_key_dictionary(values) _current_parameter_value.type = type_ if _is_simple_type(value): arg = Argument(value) _current_parameter_value.add_argument(arg)...
[ "def", "_parse_typed_parameter_typed_value", "(", "values", ")", ":", "type_", ",", "value", "=", "_expand_one_key_dictionary", "(", "values", ")", "_current_parameter_value", ".", "type", "=", "type_", "if", "_is_simple_type", "(", "value", ")", ":", "arg", "=", ...
32.428571
0.002141
def ReadVFS(pathspec, offset, length, progress_callback=None): """Read from the VFS and return the contents. Args: pathspec: path to read from offset: number of bytes to skip length: number of bytes to read progress_callback: A callback to indicate that the open call is still working but need...
[ "def", "ReadVFS", "(", "pathspec", ",", "offset", ",", "length", ",", "progress_callback", "=", "None", ")", ":", "fd", "=", "VFSOpen", "(", "pathspec", ",", "progress_callback", "=", "progress_callback", ")", "fd", ".", "Seek", "(", "offset", ")", "return...
28.875
0.010482
def post(self, page, payload, parms=None ): '''Posts a string payload to the server - used to make new Redmine items. Returns an JSON string or error.''' if self.readonlytest: print 'Redmine read only test: Pretending to create: ' + page return payload else: ...
[ "def", "post", "(", "self", ",", "page", ",", "payload", ",", "parms", "=", "None", ")", ":", "if", "self", ".", "readonlytest", ":", "print", "'Redmine read only test: Pretending to create: '", "+", "page", "return", "payload", "else", ":", "return", "self", ...
50.571429
0.016667
def reduce_activities(stmts_in, **kwargs): """Reduce the activity types in a list of statements Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to reduce activity types in. save : Optional[str] The name of a pickle file to save the results (stm...
[ "def", "reduce_activities", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Reducing activities on %d statements...'", "%", "len", "(", "stmts_in", ")", ")", "stmts_out", "=", "[", "deepcopy", "(", "st", ")", "for", "st", ...
32.16
0.001208
def run_simulation(wdir, arp=True, **kwargs): """ Example ------- 100-nm silica sphere with 10-nm thick Ag coating, embedded in water; arprec 20 digits; illuminated with YAG (1064nm); scan xz plane (21x21, +-200nm) bhfield-arp-db.exe mpdigit wl r_core r_coat n_grid_x ...
[ "def", "run_simulation", "(", "wdir", ",", "arp", "=", "True", ",", "*", "*", "kwargs", ")", ":", "wdir", "=", "pathlib", ".", "Path", "(", "wdir", ")", "cmd", "=", "\"{pathbhfield} {mpdigit} {wl:f} {r_core:f} {r_coat:f} \"", "+", "\"{n_grid_x:d} {xspan_min:f} {xs...
34.0625
0.000357
def mps_device_name(): """ Returns name of MPS device that will be used, else None. """ lib = _load_tcmps_lib() if lib is None: return None n = 256 c_name = (_ctypes.c_char * n)() ret = lib.TCMPSMetalDeviceName(_ctypes.byref(c_name), _ctypes.c_int32(n)) if ret == 0: ...
[ "def", "mps_device_name", "(", ")", ":", "lib", "=", "_load_tcmps_lib", "(", ")", "if", "lib", "is", "None", ":", "return", "None", "n", "=", "256", "c_name", "=", "(", "_ctypes", ".", "c_char", "*", "n", ")", "(", ")", "ret", "=", "lib", ".", "T...
25.8
0.002494
def sport_delete(self, sport_id="0.0.0", account=None, **kwargs): """ Remove a sport. This needs to be **proposed**. :param str sport_id: Sport ID to identify the Sport to be deleted :param str account: (optional) Account used to verify the operation """ if not accoun...
[ "def", "sport_delete", "(", "self", ",", "sport_id", "=", "\"0.0.0\"", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "config", ":", "account", "=", "config", "[", "\"defaul...
32.538462
0.002296
def reduce_loss_dict(loss_dict): """ Reduce the loss dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as loss_dict, after reduction. """ world_size = get_world_size() if world_size < 2: return loss_dict with t...
[ "def", "reduce_loss_dict", "(", "loss_dict", ")", ":", "world_size", "=", "get_world_size", "(", ")", "if", "world_size", "<", "2", ":", "return", "loss_dict", "with", "torch", ".", "no_grad", "(", ")", ":", "loss_names", "=", "[", "]", "all_losses", "=", ...
36.782609
0.001152
def traverse_rootdistorder(self, ascending=True, leaves=True, internal=True): '''Perform a traversal of the ``Node`` objects in this ``Tree`` in either ascending (``ascending=True``) or descending (``ascending=False``) order of distance from the root Args: ``ascending`` (``bool``): ``True``...
[ "def", "traverse_rootdistorder", "(", "self", ",", "ascending", "=", "True", ",", "leaves", "=", "True", ",", "internal", "=", "True", ")", ":", "for", "node", "in", "self", ".", "root", ".", "traverse_rootdistorder", "(", "ascending", "=", "ascending", ",...
60.333333
0.009524
def api_retrieve(self, api_key=None): """ Call the stripe API's retrieve operation for this model. :param api_key: The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY. :type api_key: string """ api_key = api_key or self.default_api_key return self.stripe_class.retrieve( id=sel...
[ "def", "api_retrieve", "(", "self", ",", "api_key", "=", "None", ")", ":", "api_key", "=", "api_key", "or", "self", ".", "default_api_key", "return", "self", ".", "stripe_class", ".", "retrieve", "(", "id", "=", "self", ".", "id", ",", "api_key", "=", ...
30.083333
0.032258
def public_key_to_xrb_address(public_key): """ Convert `public_key` (bytes) to an xrb address >>> public_key_to_xrb_address(b'00000000000000000000000000000000') 'xrb_1e3i81r51e3i81r51e3i81r51e3i81r51e3i81r51e3i81r51e3imxssakuq' :param public_key: public key in bytes :type public_key: bytes ...
[ "def", "public_key_to_xrb_address", "(", "public_key", ")", ":", "if", "not", "len", "(", "public_key", ")", "==", "32", ":", "raise", "ValueError", "(", "'public key must be 32 chars'", ")", "padded", "=", "b'000'", "+", "public_key", "address", "=", "b32xrb_en...
30.52381
0.001513
def _do_exec(self, cmd, args): """Execute a command using subprocess.Popen(). """ if not args: self.stderr.write("execute: empty command\n") return proc = subprocess.Popen(subprocess.list2cmdline(args), shell = True, stdout = self.stdout) p...
[ "def", "_do_exec", "(", "self", ",", "cmd", ",", "args", ")", ":", "if", "not", "args", ":", "self", ".", "stderr", ".", "write", "(", "\"execute: empty command\\n\"", ")", "return", "proc", "=", "subprocess", ".", "Popen", "(", "subprocess", ".", "list2...
35.777778
0.021212
async def get(cls, websession, lat, lon): """Retrieve the nearest station.""" self = Station(websession) stations = await self.api.stations() self.station = self._filter_closest(lat, lon, stations) logger.info("Using %s as weather station", self.station.local) ...
[ "async", "def", "get", "(", "cls", ",", "websession", ",", "lat", ",", "lon", ")", ":", "self", "=", "Station", "(", "websession", ")", "stations", "=", "await", "self", ".", "api", ".", "stations", "(", ")", "self", ".", "station", "=", "self", "....
26.833333
0.009009
def meet(self, featuresets): """Return the nearest featureset that implies all given ones.""" concepts = (f.concept for f in featuresets) meet = self.lattice.meet(concepts) return self._featuresets[meet.index]
[ "def", "meet", "(", "self", ",", "featuresets", ")", ":", "concepts", "=", "(", "f", ".", "concept", "for", "f", "in", "featuresets", ")", "meet", "=", "self", ".", "lattice", ".", "meet", "(", "concepts", ")", "return", "self", ".", "_featuresets", ...
47.4
0.008299
def grant_sudo_privileges(request, max_age=COOKIE_AGE): """ Assigns a random token to the user's session that allows them to have elevated permissions """ user = getattr(request, 'user', None) # If there's not a user on the request, just noop if user is None: return if not user...
[ "def", "grant_sudo_privileges", "(", "request", ",", "max_age", "=", "COOKIE_AGE", ")", ":", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "# If there's not a user on the request, just noop", "if", "user", "is", "None", ":", "return", ...
31.545455
0.001399
def get_args(request_args, allowed_int_args=[], allowed_str_args=[]): """Check allowed argument names and return is as dictionary""" args = {} for allowed_int_arg in allowed_int_args: int_value = request_args.get(allowed_int_arg, default=None, type=None) if int_value: args[allow...
[ "def", "get_args", "(", "request_args", ",", "allowed_int_args", "=", "[", "]", ",", "allowed_str_args", "=", "[", "]", ")", ":", "args", "=", "{", "}", "for", "allowed_int_arg", "in", "allowed_int_args", ":", "int_value", "=", "request_args", ".", "get", ...
36.266667
0.001792
def execute_notebook_with_engine(self, engine_name, nb, kernel_name, **kwargs): """Fetch a named engine and execute the nb object against it.""" return self.get_engine(engine_name).execute_notebook(nb, kernel_name, **kwargs)
[ "def", "execute_notebook_with_engine", "(", "self", ",", "engine_name", ",", "nb", ",", "kernel_name", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get_engine", "(", "engine_name", ")", ".", "execute_notebook", "(", "nb", ",", "kernel_name", ",...
79.333333
0.0125
def omit_wells(self, uwis=None): """ Returns a new project where wells with specified uwis have been omitted Args: uwis (list): list or tuple of UWI strings. Returns: project """ if uwis is None: raise ValueError('Must specify at le...
[ "def", "omit_wells", "(", "self", ",", "uwis", "=", "None", ")", ":", "if", "uwis", "is", "None", ":", "raise", "ValueError", "(", "'Must specify at least one uwi'", ")", "return", "Project", "(", "[", "w", "for", "w", "in", "self", "if", "w", ".", "uw...
29.538462
0.010101
def read(source, channels, start=None, end=None, scaled=None, type=None, series_class=TimeSeries): # pylint: disable=redefined-builtin """Read a dict of series from one or more GWF files Parameters ---------- source : `str`, `list` Source of data, any of the following: - `...
[ "def", "read", "(", "source", ",", "channels", ",", "start", "=", "None", ",", "end", "=", "None", ",", "scaled", "=", "None", ",", "type", "=", "None", ",", "series_class", "=", "TimeSeries", ")", ":", "# pylint: disable=redefined-builtin", "# parse input s...
33.736842
0.000505
def constrained_sections(self, constraints=None, options=None): """ Takes a dictionary of option/values (constraints) that must be present in a section, and returns a dictionary of sections and optionally a dictionary of option/values defined by a list of options called options t...
[ "def", "constrained_sections", "(", "self", ",", "constraints", "=", "None", ",", "options", "=", "None", ")", ":", "sections", "=", "{", "}", "if", "not", "constraints", ":", "constraints", "=", "{", "}", "if", "not", "options", ":", "options", "=", "...
41.387097
0.001523
def add_operation_recorder(self, operation_recorder): # pylint: disable=line-too-long """ **Experimental:** Add an operation recorder to this connection. *New in pywbem 0.12 as experimental.* If the connection already has a recorder with the same class, the request to a...
[ "def", "add_operation_recorder", "(", "self", ",", "operation_recorder", ")", ":", "# pylint: disable=line-too-long", "# noqa: E501", "if", "operation_recorder", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value None for new operation recorder\"", ")", "for", ...
39.382353
0.002187
def ensure_ajax(valid_request_methods, error_response_context=None): """ Intends to ensure the received the request is ajax request and it is included in the valid request methods :param valid_request_methods: list: list of valid request methods, such as 'GET', 'POST' :param error_response_co...
[ "def", "ensure_ajax", "(", "valid_request_methods", ",", "error_response_context", "=", "None", ")", ":", "def", "real_decorator", "(", "view_func", ")", ":", "def", "wrap_func", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "n...
48.451613
0.000653
def anonymous_required(func=None, url=None): """Required that the user is not logged in.""" url = url or "/" def _dec(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): ...
[ "def", "anonymous_required", "(", "func", "=", "None", ",", "url", "=", "None", ")", ":", "url", "=", "url", "or", "\"/\"", "def", "_dec", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_f...
28.388889
0.001894
def __print_namespace_help(self, session, namespace, cmd_name=None): """ Prints the documentation of all the commands in the given name space, or only of the given command :param session: Session Handler :param namespace: Name space of the command :param cmd_name: Name o...
[ "def", "__print_namespace_help", "(", "self", ",", "session", ",", "namespace", ",", "cmd_name", "=", "None", ")", ":", "session", ".", "write_line", "(", "\"=== Name space '{0}' ===\"", ",", "namespace", ")", "# Get all commands in this name space", "if", "cmd_name",...
34.5
0.002169
def GetCpuStolenMs(self): '''Retrieves the number of milliseconds that the virtual machine was in a ready state (able to transition to a run state), but was not scheduled to run.''' counter = c_uint64() ret = vmGuestLib.VMGuestLib_GetCpuStolenMs(self.handle.value, byref(counter)) ...
[ "def", "GetCpuStolenMs", "(", "self", ")", ":", "counter", "=", "c_uint64", "(", ")", "ret", "=", "vmGuestLib", ".", "VMGuestLib_GetCpuStolenMs", "(", "self", ".", "handle", ".", "value", ",", "byref", "(", "counter", ")", ")", "if", "ret", "!=", "VMGUES...
59
0.01432
def show_menu(title, options, default=None, height=None, width=None, multiselect=False, precolored=False): """ Shows an interactive menu in the terminal. Arguments: options: list of menu options default: initial option to highlight height: maximum height of the menu width: m...
[ "def", "show_menu", "(", "title", ",", "options", ",", "default", "=", "None", ",", "height", "=", "None", ",", "width", "=", "None", ",", "multiselect", "=", "False", ",", "precolored", "=", "False", ")", ":", "plugins", "=", "[", "FilterPlugin", "(",...
38.235294
0.0015
def set(verbose, # pylint:disable=redefined-builtin host, http_port, ws_port, use_https, verify_ssl): """Set the global config values. Example: \b ```bash $ polyaxon config set --hots=localhost http_port=80 ``` """ _config = GlobalConfigManager....
[ "def", "set", "(", "verbose", ",", "# pylint:disable=redefined-builtin", "host", ",", "http_port", ",", "ws_port", ",", "use_https", ",", "verify_ssl", ")", ":", "_config", "=", "GlobalConfigManager", ".", "get_config_or_default", "(", ")", "if", "verbose", "is", ...
21.487179
0.001142
def __load_enrollments(self, enrollments, uuid, verbose): """Store enrollments""" self.log("-- loading enrollments", verbose) organizations = [] for enrollment in enrollments: organization = enrollment.organization.name try: api.add_organizatio...
[ "def", "__load_enrollments", "(", "self", ",", "enrollments", ",", "uuid", ",", "verbose", ")", ":", "self", ".", "log", "(", "\"-- loading enrollments\"", ",", "verbose", ")", "organizations", "=", "[", "]", "for", "enrollment", "in", "enrollments", ":", "o...
37.282051
0.002011
def write(self, data): """Half-duplex SPI write. The specified array of bytes will be clocked out the MOSI line. """ #check for hardware limit of FT232H and similar MPSSE chips if (len(data) > 65536): print('the FTDI chip is limited to 65536 bytes (64 KB) of input/ou...
[ "def", "write", "(", "self", ",", "data", ")", ":", "#check for hardware limit of FT232H and similar MPSSE chips", "if", "(", "len", "(", "data", ")", ">", "65536", ")", ":", "print", "(", "'the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!'", "...
48.548387
0.014984
def set(self, value): """Set the value of the bar. If the value is out of bound, sets it to an extremum""" value = min(self.max, max(self.min, value)) self._value = value start_new_thread(self.func, (self.get(),))
[ "def", "set", "(", "self", ",", "value", ")", ":", "value", "=", "min", "(", "self", ".", "max", ",", "max", "(", "self", ".", "min", ",", "value", ")", ")", "self", ".", "_value", "=", "value", "start_new_thread", "(", "self", ".", "func", ",", ...
48.2
0.012245
def get_or_none(cls, **filter_kwargs): """ Returns a video or None. """ try: video = cls.objects.get(**filter_kwargs) except cls.DoesNotExist: video = None return video
[ "def", "get_or_none", "(", "cls", ",", "*", "*", "filter_kwargs", ")", ":", "try", ":", "video", "=", "cls", ".", "objects", ".", "get", "(", "*", "*", "filter_kwargs", ")", "except", "cls", ".", "DoesNotExist", ":", "video", "=", "None", "return", "...
23.2
0.008299
def get_version(): """Get the version info from the mpld3 package without importing it""" import ast with open(os.path.join("cyvcf2", "__init__.py"), "r") as init_file: module = ast.parse(init_file.read()) version = (ast.literal_eval(node.value) for node in ast.walk(module) if isinstanc...
[ "def", "get_version", "(", ")", ":", "import", "ast", "with", "open", "(", "os", ".", "path", ".", "join", "(", "\"cyvcf2\"", ",", "\"__init__.py\"", ")", ",", "\"r\"", ")", "as", "init_file", ":", "module", "=", "ast", ".", "parse", "(", "init_file", ...
35.5
0.013725
def isCFGEnabled(self): """ Determines if the current L{PE} instance has CFG (Control Flow Guard) flag enabled. @see: U{http://blogs.msdn.com/b/vcblog/archive/2014/12/08/visual-studio-2015-preview-work-in-progress-security-feature.aspx} @see: U{https://msdn.microsoft.com/en-us/library/dn...
[ "def", "isCFGEnabled", "(", "self", ")", ":", "return", "self", ".", "ntHeaders", ".", "optionalHeader", ".", "dllCharacteristics", ".", "value", "&", "consts", ".", "IMAGE_DLL_CHARACTERISTICS_GUARD_CF", "==", "consts", ".", "IMAGE_DLL_CHARACTERISTICS_GUARD_CF" ]
64.9
0.010638
def mark_done(self): """Mark the archive status of this segment as 'done'. This is most useful when performing out-of-band parallel uploads of segments, so that Postgres doesn't try to go and upload them again. This amounts to messing with an internal bookkeeping mechanism ...
[ "def", "mark_done", "(", "self", ")", ":", "# Recheck that this is not an segment explicitly passed from Postgres", "if", "self", ".", "explicit", ":", "raise", "UserCritical", "(", "msg", "=", "'unexpected attempt to modify wal metadata detected'", ",", "detail", "=", "(",...
42.833333
0.001268
def supplementary_material(soup): """ supplementary-material tags """ supplementary_material = [] supplementary_material_tags = raw_parser.supplementary_material(soup) position = 1 for tag in supplementary_material_tags: item = {} copy_attribute(tag.attrs, 'id', item) ...
[ "def", "supplementary_material", "(", "soup", ")", ":", "supplementary_material", "=", "[", "]", "supplementary_material_tags", "=", "raw_parser", ".", "supplementary_material", "(", "soup", ")", "position", "=", "1", "for", "tag", "in", "supplementary_material_tags",...
30.028571
0.000922
def cmd_part(self, connection, sender, target, payload): """ Asks the bot to leave a channel """ if payload: connection.part(payload) else: raise ValueError("No channel given")
[ "def", "cmd_part", "(", "self", ",", "connection", ",", "sender", ",", "target", ",", "payload", ")", ":", "if", "payload", ":", "connection", ".", "part", "(", "payload", ")", "else", ":", "raise", "ValueError", "(", "\"No channel given\"", ")" ]
29.125
0.008333
def critical(self, text): """ Posts a critical message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but t...
[ "def", "critical", "(", "self", ",", "text", ")", ":", "self", ".", "queue", ".", "put", "(", "dill", ".", "dumps", "(", "LogMessageCommand", "(", "text", "=", "text", ",", "level", "=", "logging", ".", "CRITICAL", ")", ")", ")" ]
72.3
0.009563
def mfe_multi(self, strands, permutation=None, degenerate=False, temp=37.0, pseudo=False, material=None, dangles='some', sodium=1.0, magnesium=0.0): '''Compute the MFE for an ordered complex of strands. Runs the \'mfe\' command. :param strands: Strands on whi...
[ "def", "mfe_multi", "(", "self", ",", "strands", ",", "permutation", "=", "None", ",", "degenerate", "=", "False", ",", "temp", "=", "37.0", ",", "pseudo", "=", "False", ",", "material", "=", "None", ",", "dangles", "=", "'some'", ",", "sodium", "=", ...
48.690141
0.001134
def find_safe_starting_point(self): """ finds a place on the grid which is clear on all sides to avoid starting in the middle of a blockage """ y = random.randint(2,self.grid_height-4) x = random.randint(2,self.grid_width-4) return y, x
[ "def", "find_safe_starting_point", "(", "self", ")", ":", "y", "=", "random", ".", "randint", "(", "2", ",", "self", ".", "grid_height", "-", "4", ")", "x", "=", "random", ".", "randint", "(", "2", ",", "self", ".", "grid_width", "-", "4", ")", "re...
35.75
0.017065
def handle_new_tuple_set_2(self, hts2): """Called when new HeronTupleSet2 arrives Convert(Assemble) HeronTupleSet2(raw byte array) to HeronTupleSet See more at GitHub PR #1421 :param tuple_msg_set: HeronTupleSet2 type """ if self.my_pplan_helper is None or self.my_instance is None: L...
[ "def", "handle_new_tuple_set_2", "(", "self", ",", "hts2", ")", ":", "if", "self", ".", "my_pplan_helper", "is", "None", "or", "self", ".", "my_instance", "is", "None", ":", "Log", ".", "error", "(", "\"Got tuple set when no instance assigned yet\"", ")", "else"...
39.64
0.008867
def read_hdf (self, key, **kwargs): """Open as an HDF5 file using :mod:`pandas` and return the item stored under the key *key*. *kwargs* are passed to :func:`pandas.read_hdf`. """ # This one needs special handling because of the "key" and path input. import pandas return...
[ "def", "read_hdf", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")", ":", "# This one needs special handling because of the \"key\" and path input.", "import", "pandas", "return", "pandas", ".", "read_hdf", "(", "text_type", "(", "self", ")", ",", "key", ",",...
45.375
0.016216
def get_conn(): ''' Return a conn object for the passed VM data ''' vm_ = get_configured_provider() kwargs = vm_.copy() # pylint: disable=E1103 kwargs['username'] = vm_['user'] kwargs['project_id'] = vm_['tenant'] kwargs['auth_url'] = vm_['identity_url'] kwargs['region_name'] = vm...
[ "def", "get_conn", "(", ")", ":", "vm_", "=", "get_configured_provider", "(", ")", "kwargs", "=", "vm_", ".", "copy", "(", ")", "# pylint: disable=E1103", "kwargs", "[", "'username'", "]", "=", "vm_", "[", "'user'", "]", "kwargs", "[", "'project_id'", "]",...
32.916667
0.00246
def concatenate(arrays, axis=0, always_copy=True): """DEPRECATED, use ``concat`` instead Parameters ---------- arrays : list of `NDArray` Arrays to be concatenate. They must have identical shape except the first dimension. They also must have the same data type. axis : int T...
[ "def", "concatenate", "(", "arrays", ",", "axis", "=", "0", ",", "always_copy", "=", "True", ")", ":", "assert", "isinstance", "(", "arrays", ",", "list", ")", "assert", "len", "(", "arrays", ")", ">", "0", "assert", "isinstance", "(", "arrays", "[", ...
32.872727
0.000537
def memoize(func): """Cache forever.""" cache = {} def memoizer(): if 0 not in cache: cache[0] = func() return cache[0] return functools.wraps(func)(memoizer)
[ "def", "memoize", "(", "func", ")", ":", "cache", "=", "{", "}", "def", "memoizer", "(", ")", ":", "if", "0", "not", "in", "cache", ":", "cache", "[", "0", "]", "=", "func", "(", ")", "return", "cache", "[", "0", "]", "return", "functools", "."...
24.375
0.009901
def get_console_output( name=None, location=None, instance_id=None, call=None, kwargs=None, ): ''' Show the console output from the instance. By default, returns decoded data, not the Base64-encoded data that is actually returned from the EC2 API. ''' ...
[ "def", "get_console_output", "(", "name", "=", "None", ",", "location", "=", "None", ",", "instance_id", "=", "None", ",", "call", "=", "None", ",", "kwargs", "=", "None", ",", ")", ":", "if", "call", "!=", "'action'", ":", "raise", "SaltCloudSystemExit"...
26.333333
0.002154
def dumper(args, config, transform_func=None): """Dumper main function.""" args = process_args(args) submit_args = get_submit_args(args) submit_outcome = submit_if_ready(args, submit_args, config) if submit_outcome is not None: # submitted, nothing more to do return submit_outcome ...
[ "def", "dumper", "(", "args", ",", "config", ",", "transform_func", "=", "None", ")", ":", "args", "=", "process_args", "(", "args", ")", "submit_args", "=", "get_submit_args", "(", "args", ")", "submit_outcome", "=", "submit_if_ready", "(", "args", ",", "...
34.609756
0.002056
def create_collection(cls, href, collection=None, props=None): """Create a collection. If the collection already exists and neither ``collection`` nor ``props`` are set, this method shouldn't do anything. Otherwise the existing collection must be replaced. ``collection`` is a l...
[ "def", "create_collection", "(", "cls", ",", "href", ",", "collection", "=", "None", ",", "props", "=", "None", ")", ":", "# Path should already be sanitized", "attributes", "=", "_get_attributes_from_path", "(", "href", ")", "if", "len", "(", "attributes", ")",...
39.465753
0.001693
def parse_denovo_params(user_params=None): """Return default GimmeMotifs parameters. Defaults will be replaced with parameters defined in user_params. Parameters ---------- user_params : dict, optional User-defined parameters. Returns ------- params : dict """ config ...
[ "def", "parse_denovo_params", "(", "user_params", "=", "None", ")", ":", "config", "=", "MotifConfig", "(", ")", "if", "user_params", "is", "None", ":", "user_params", "=", "{", "}", "params", "=", "config", ".", "get_default_params", "(", ")", "params", "...
27.122449
0.002179
def convertToNative(self, aVal): """ Convert to native bool; interpret certain strings. """ if aVal is None: return None if isinstance(aVal, bool): return aVal # otherwise interpret strings return str(aVal).lower() in ('1','on','yes','true')
[ "def", "convertToNative", "(", "self", ",", "aVal", ")", ":", "if", "aVal", "is", "None", ":", "return", "None", "if", "isinstance", "(", "aVal", ",", "bool", ")", ":", "return", "aVal", "# otherwise interpret strings", "return", "str", "(", "aVal", ")", ...
41
0.020478
def _http_parser(self): """ Meat of the parsing algorithm. This is a generator that data is 'sent' to by the consume method. Using the generator type allows state to be maintained despite not having all data. It is assumed that this is more efficient than checking state (headers ...
[ "def", "_http_parser", "(", "self", ")", ":", "# first, find first EOL (i.e. get request line)", "yield", "from", "self", ".", "_receive_eol_token", "(", ")", "# split the request line and headers (modifies buffer)", "yield", "from", "self", ".", "_parse_and_store_req_line", ...
43.607143
0.001603
def walk(self, top): """ Generate infos for all paths in the tree rooted at ``top`` (included). The ``top`` parameter can be either an HDFS path string or a dictionary of properties as returned by :meth:`get_path_info`. :type top: str, dict :param top: an HDFS path or p...
[ "def", "walk", "(", "self", ",", "top", ")", ":", "if", "not", "top", ":", "raise", "ValueError", "(", "\"Empty path\"", ")", "if", "isinstance", "(", "top", ",", "basestring", ")", ":", "top", "=", "self", ".", "get_path_info", "(", "top", ")", "yie...
36.708333
0.002212
def input_(data, field_path): """Return a hydrated value of the ``input`` field.""" data_obj = Data.objects.get(id=data['__id']) inputs = copy.deepcopy(data_obj.input) # XXX: Optimize by hydrating only the required field (major refactoring). hydrate_input_references(inputs, data_obj.process.input_s...
[ "def", "input_", "(", "data", ",", "field_path", ")", ":", "data_obj", "=", "Data", ".", "objects", ".", "get", "(", "id", "=", "data", "[", "'__id'", "]", ")", "inputs", "=", "copy", ".", "deepcopy", "(", "data_obj", ".", "input", ")", "# XXX: Optim...
42.3
0.002315
def get_statistics_24h(self, endtime): """Return statistical data last 24h from time""" js = json.dumps( {'attrs': ["bytes", "num_sta", "time"], 'start': int(endtime - 86400) * 1000, 'end': int(endtime - 3600) * 1000}) params = urllib.urlencode({'json': js}) return self._rea...
[ "def", "get_statistics_24h", "(", "self", ",", "endtime", ")", ":", "js", "=", "json", ".", "dumps", "(", "{", "'attrs'", ":", "[", "\"bytes\"", ",", "\"num_sta\"", ",", "\"time\"", "]", ",", "'start'", ":", "int", "(", "endtime", "-", "86400", ")", ...
52.428571
0.008043
def _getphoto_originalsize(self,pid): """Asks flickr for photo original size returns tuple with width,height """ logger.debug('%s - Getting original size from flickr'%(pid)) width=None height=None resp=self.flickr.photos_getSizes(photo_id=pid) if resp.a...
[ "def", "_getphoto_originalsize", "(", "self", ",", "pid", ")", ":", "logger", ".", "debug", "(", "'%s - Getting original size from flickr'", "%", "(", "pid", ")", ")", "width", "=", "None", "height", "=", "None", "resp", "=", "self", ".", "flickr", ".", "p...
34.958333
0.027842
def dict(self, var, default=NOTSET, cast=None, force=True): """Convenience method for casting to a dict Note: Casting """ return self._get(var, default=default, cast={str: cast}, force=force)
[ "def", "dict", "(", "self", ",", "var", ",", "default", "=", "NOTSET", ",", "cast", "=", "None", ",", "force", "=", "True", ")", ":", "return", "self", ".", "_get", "(", "var", ",", "default", "=", "default", ",", "cast", "=", "{", "str", ":", ...
32.857143
0.008475
def get_arguments(options): """ This function handles and validates the wrapper arguments. """ # These the next couple of lines defines the header of the Help output parser = ArgumentParser( formatter_class=RawDescriptionHelpFormatter, usage=("""%(prog)s --------------------------------------------...
[ "def", "get_arguments", "(", "options", ")", ":", "# These the next couple of lines defines the header of the Help output", "parser", "=", "ArgumentParser", "(", "formatter_class", "=", "RawDescriptionHelpFormatter", ",", "usage", "=", "(", "\"\"\"%(prog)s\n----------------------...
35.3125
0.017222
def _get_cartocss(self, basemap, has_time=False): """Generate cartocss for class properties""" if isinstance(self.size, (int, float)): size_style = self.size elif isinstance(self.size, dict): self.size['range'] = ( [1, 5] if self.size['range'] == [5, 25] ...
[ "def", "_get_cartocss", "(", "self", ",", "basemap", ",", "has_time", "=", "False", ")", ":", "if", "isinstance", "(", "self", ".", "size", ",", "(", "int", ",", "float", ")", ")", ":", "size_style", "=", "self", ".", "size", "elif", "isinstance", "(...
41.635514
0.000439
async def listen(self): "Listen for messages on channels this client has been subscribed to" if self.subscribed: return self.handle_message(await self.parse_response(block=True))
[ "async", "def", "listen", "(", "self", ")", ":", "if", "self", ".", "subscribed", ":", "return", "self", ".", "handle_message", "(", "await", "self", ".", "parse_response", "(", "block", "=", "True", ")", ")" ]
50.75
0.009709
def hide_errors(cls): """ Hide errors shown by validators. """ cls.select_el.style.border = "0" cls.input_el.style.border = "0"
[ "def", "hide_errors", "(", "cls", ")", ":", "cls", ".", "select_el", ".", "style", ".", "border", "=", "\"0\"", "cls", ".", "input_el", ".", "style", ".", "border", "=", "\"0\"" ]
27
0.011976
def check_taxonomy(taxonomy): """Check the consistency of the taxonomy. Outputs a list of errors and warnings. """ current_app.logger.info( "Building graph with Python RDFLib version %s" % rdflib.__version__ ) store = rdflib.ConjunctiveGraph() store.parse(taxonomy) cur...
[ "def", "check_taxonomy", "(", "taxonomy", ")", ":", "current_app", ".", "logger", ".", "info", "(", "\"Building graph with Python RDFLib version %s\"", "%", "rdflib", ".", "__version__", ")", "store", "=", "rdflib", ".", "ConjunctiveGraph", "(", ")", "store", ".",...
37.758294
0.000122
def escape_path(pth): """ Hex/unicode escapes a path. Escapes a path so that it can be represented faithfully in an HDF5 file without changing directories. This means that leading ``'.'`` must be escaped. ``'/'`` and null must be escaped to. Backslashes are escaped as double backslashes. Other esca...
[ "def", "escape_path", "(", "pth", ")", ":", "if", "isinstance", "(", "pth", ",", "bytes", ")", ":", "pth", "=", "pth", ".", "decode", "(", "'utf-8'", ")", "if", "sys", ".", "hexversion", ">=", "0x03000000", ":", "if", "not", "isinstance", "(", "pth",...
28.403509
0.000597
def _process_string(self, char): """ Process a character as part of a string token. """ if char in self.QUOTES: # end of quoted string: # 1) quote must match original quote # 2) not escaped quote (e.g. "hey there" vs "hey there\") # 3) a...
[ "def", "_process_string", "(", "self", ",", "char", ")", ":", "if", "char", "in", "self", ".", "QUOTES", ":", "# end of quoted string:", "# 1) quote must match original quote", "# 2) not escaped quote (e.g. \"hey there\" vs \"hey there\\\")", "# 3) actual escape char prior ...
32.413793
0.002066
def get_data_dirs(__pkg: str) -> List[str]: """Return all data directories for given package. Args: __pkg: Package name """ dirs = [user_data(__pkg), ] dirs.extend(path.expanduser(path.sep.join([d, __pkg])) for d in getenv('XDG_DATA_DIRS', '/u...
[ "def", "get_data_dirs", "(", "__pkg", ":", "str", ")", "->", "List", "[", "str", "]", ":", "dirs", "=", "[", "user_data", "(", "__pkg", ")", ",", "]", "dirs", ".", "extend", "(", "path", ".", "expanduser", "(", "path", ".", "sep", ".", "join", "(...
36.090909
0.002457
def p_with_statement(self, p): """with_statement : WITH LPAREN expr RPAREN statement""" p[0] = ast.With(expr=p[3], statement=p[5])
[ "def", "p_with_statement", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "With", "(", "expr", "=", "p", "[", "3", "]", ",", "statement", "=", "p", "[", "5", "]", ")" ]
48
0.013699
def updatepLvlGrid(self): ''' Update the grid of permanent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1. Identical to version in persistent shocks model, but pLvl=0 is manually a...
[ "def", "updatepLvlGrid", "(", "self", ")", ":", "# Run basic version of this method", "PersistentShockConsumerType", ".", "updatepLvlGrid", "(", "self", ")", "for", "j", "in", "range", "(", "len", "(", "self", ".", "pLvlGrid", ")", ")", ":", "# Then add 0 to the b...
37.666667
0.009864
def cumulative_density_at_times(self, times, label=None): """ Return a Pandas series of the predicted cumulative density at specific times Parameters ----------- times: iterable or float Returns -------- pd.Series """ label = coalesce(la...
[ "def", "cumulative_density_at_times", "(", "self", ",", "times", ",", "label", "=", "None", ")", ":", "label", "=", "coalesce", "(", "label", ",", "self", ".", "_label", ")", "return", "pd", ".", "Series", "(", "1", "-", "self", ".", "predict", "(", ...
27.266667
0.009456
def get_keep_score(source_counts, prediction_counts, target_counts): """Compute the keep score (Equation 5 in the paper).""" source_and_prediction_counts = source_counts & prediction_counts source_and_target_counts = source_counts & target_counts true_positives = sum((source_and_prediction_counts & ...
[ "def", "get_keep_score", "(", "source_counts", ",", "prediction_counts", ",", "target_counts", ")", ":", "source_and_prediction_counts", "=", "source_counts", "&", "prediction_counts", "source_and_target_counts", "=", "source_counts", "&", "target_counts", "true_positives", ...
58.777778
0.014898
def transition_matrix_samples(self): r""" Samples of the transition matrix """ res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :, :] = self._sampled_hmms[i].transition_matrix return res
[ "def", "transition_matrix_samples", "(", "self", ")", ":", "res", "=", "np", ".", "empty", "(", "(", "self", ".", "nsamples", ",", "self", ".", "nstates", ",", "self", ".", "nstates", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "i", ...
49
0.010033
def dictAvg(listOfDicts,key,stdErr=False): """Given a list (l) of dicts (d), return AV and SD.""" vals=dictVals(listOfDicts,key) if len(vals) and np.any(vals): av=np.nanmean(vals) er=np.nanstd(vals) if stdErr: er=er/np.sqrt(np.count_nonzero(~np.isnan(er))) else: ...
[ "def", "dictAvg", "(", "listOfDicts", ",", "key", ",", "stdErr", "=", "False", ")", ":", "vals", "=", "dictVals", "(", "listOfDicts", ",", "key", ")", "if", "len", "(", "vals", ")", "and", "np", ".", "any", "(", "vals", ")", ":", "av", "=", "np",...
31.727273
0.033426
def gen_reset_password_token(self, user=None, send_email=None): """Generates a reset password token and optionnaly (default to yes) send the reset password email """ if not user and "form" in current_context.data and request.method == "POST": form = current_context.data.form ...
[ "def", "gen_reset_password_token", "(", "self", ",", "user", "=", "None", ",", "send_email", "=", "None", ")", ":", "if", "not", "user", "and", "\"form\"", "in", "current_context", ".", "data", "and", "request", ".", "method", "==", "\"POST\"", ":", "form"...
56.666667
0.008264
def attention_lm_moe_small(): """Cheap model for single-gpu training. on lm1b_32k: ~312M params 1.6 steps/sec on [GeForce GTX TITAN X] After 50K steps on 8 GPUs (synchronous): eval_log_ppl_per_token = 3.31 Returns: an hparams object. """ hparams = attention_lm_moe_base() hparam...
[ "def", "attention_lm_moe_small", "(", ")", ":", "hparams", "=", "attention_lm_moe_base", "(", ")", "hparams", ".", "num_hidden_layers", "=", "4", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "filter_size", "=", "2048", "hparams", ".", "moe_num_expe...
24.105263
0.018908
def flatten(*seqs): """ Flattens a sequence e.g. |[(1, 2), (3, (4, 5))] -> [1, 2, 3, 4, 5]| @seq: #tuple, #list or :class:UserList -> yields an iterator .. l = [(1, 2), (3, 4)] for x in flatten(l): print(x) .. """ for seq in seqs: ...
[ "def", "flatten", "(", "*", "seqs", ")", ":", "for", "seq", "in", "seqs", ":", "for", "item", "in", "seq", ":", "if", "isinstance", "(", "item", ",", "(", "tuple", ",", "list", ",", "UserList", ")", ")", ":", "for", "subitem", "in", "flatten", "(...
25.3
0.001905
def download(dataset, node, entityids, products, api_key=None): """ The use of this request will be to obtain valid data download URLs. :param dataset: :param entityIds: list :param products: list :param node: :param api_key: API key is requir...
[ "def", "download", "(", "dataset", ",", "node", ",", "entityids", ",", "products", ",", "api_key", "=", "None", ")", ":", "payload", "=", "{", "\"datasetName\"", ":", "dataset", ",", "\"node\"", ":", "node", ",", "\"apiKey\"", ":", "api_key", ",", "\"ent...
18.592593
0.011364
def track_count(self, unique_identifier, metric, inc_amt=1, **kwargs): """ Tracks a metric just by count. If you track a metric this way, you won't be able to query the metric by day, week or month. :param unique_identifier: Unique string indetifying the object this metric is for ...
[ "def", "track_count", "(", "self", ",", "unique_identifier", ",", "metric", ",", "inc_amt", "=", "1", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_analytics_backend", ".", "incr", "(", "self", ".", "_prefix", "+", "\":\"", "+", "\"analy:%s...
61.090909
0.008798
def commit(self): """ Flushes all pending changes and commits Solr changes """ self._addFlushBatch() for core in self.endpoints: self._send_solr_command(self.endpoints[core], "{ \"commit\":{} }")
[ "def", "commit", "(", "self", ")", ":", "self", ".", "_addFlushBatch", "(", ")", "for", "core", "in", "self", ".", "endpoints", ":", "self", ".", "_send_solr_command", "(", "self", ".", "endpoints", "[", "core", "]", ",", "\"{ \\\"commit\\\":{} }\"", ")" ]
34.428571
0.008097
def calculate_cpm(x, axis=1): """Calculate counts-per-million on data where the rows are genes. Parameters ---------- x : array_like axis : int Axis accross which to compute CPM. 0 for genes being in rows and 1 for genes in columns. """ normalization = np.sum(x, axis=ax...
[ "def", "calculate_cpm", "(", "x", ",", "axis", "=", "1", ")", ":", "normalization", "=", "np", ".", "sum", "(", "x", ",", "axis", "=", "axis", ")", "# On sparse matrices, the sum will be 2d. We want a 1d array", "normalization", "=", "np", ".", "squeeze", "(",...
36.26087
0.002336
def dateTimeAt( self, point ): """ Returns the date time at the inputed point. :param point | <QPoint> """ for dtime, data in self._dateTimeGrid.items(): if ( data[1].contains(point) ): return QDateTime.fromTime_t(dtime) ...
[ "def", "dateTimeAt", "(", "self", ",", "point", ")", ":", "for", "dtime", ",", "data", "in", "self", ".", "_dateTimeGrid", ".", "items", "(", ")", ":", "if", "(", "data", "[", "1", "]", ".", "contains", "(", "point", ")", ")", ":", "return", "QDa...
32.9
0.02071
def new(self, limit=None): """GETs new links from this subreddit. Calls :meth:`narwal.Reddit.new`. :param limit: max number of links to return """ return self._reddit.new(self.display_name, limit=limit)
[ "def", "new", "(", "self", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "_reddit", ".", "new", "(", "self", ".", "display_name", ",", "limit", "=", "limit", ")" ]
39.833333
0.016393
def create_normal(mu=0., sigma=1., mu_err=0., sigma_err=1., seed=None, **kwargs): """Generate a data with magnitudes that follows a Gaussian distribution. Also their errors are gaussian. Parameters ---------- mu : float (default=0) Mean of the gaussian distribution of ma...
[ "def", "create_normal", "(", "mu", "=", "0.", ",", "sigma", "=", "1.", ",", "mu_err", "=", "0.", ",", "sigma_err", "=", "1.", ",", "seed", "=", "None", ",", "*", "*", "kwargs", ")", ":", "random", "=", "np", ".", "random", ".", "RandomState", "("...
34.886792
0.000526
def get_chassis_name(host=None, admin_username=None, admin_password=None): ''' Get the name of a chassis. host The chassis host. admin_username The username used to access the chassis. admin_password The password used to access the chassis. CLI Example: .. code-b...
[ "def", "get_chassis_name", "(", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ")", ":", "return", "bare_rac_cmd", "(", "'getchassisname'", ",", "host", "=", "host", ",", "admin_username", "=", "admin_username", ",...
24.833333
0.001616
def assign_constant(self, value, dtype=None): """ Assign a constant value to all nonzeros in the pianoroll. If the pianoroll is not binarized, its data type will be preserved. If the pianoroll is binarized, it will be casted to the type of `value`. Arguments --------- ...
[ "def", "assign_constant", "(", "self", ",", "value", ",", "dtype", "=", "None", ")", ":", "if", "not", "self", ".", "is_binarized", "(", ")", ":", "self", ".", "pianoroll", "[", "self", ".", "pianoroll", ".", "nonzero", "(", ")", "]", "=", "value", ...
35.833333
0.002265
def _add_cloud_pocket(pocket): """Add a cloud pocket as /etc/apt/sources.d/cloud-archive.list Note that this overwrites the existing file if there is one. This function also converts the simple pocket in to the actual pocket using the CLOUD_ARCHIVE_POCKETS mapping. :param pocket: string represent...
[ "def", "_add_cloud_pocket", "(", "pocket", ")", ":", "apt_install", "(", "filter_installed_packages", "(", "[", "'ubuntu-cloud-keyring'", "]", ")", ",", "fatal", "=", "True", ")", "if", "pocket", "not", "in", "CLOUD_ARCHIVE_POCKETS", ":", "raise", "SourceConfigErr...
43.285714
0.001076
def _loadDummyModelParameters(self, params): """ Loads all the parameters for this dummy model. For any paramters specified as lists, read the appropriate value for this model using the model index """ for key, value in params.iteritems(): if type(value) == list: index = self.modelIndex %...
[ "def", "_loadDummyModelParameters", "(", "self", ",", "params", ")", ":", "for", "key", ",", "value", "in", "params", ".", "iteritems", "(", ")", ":", "if", "type", "(", "value", ")", "==", "list", ":", "index", "=", "self", ".", "modelIndex", "%", "...
38.727273
0.009174
def fixed_point_density_preserving(points, cells, *args, **kwargs): """Idea: Move interior mesh points into the weighted averages of the circumcenters of their adjacent cells. If a triangle cell switches orientation in the process, don't move quite so far. """ def get_new_points(mesh): ...
[ "def", "fixed_point_density_preserving", "(", "points", ",", "cells", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "get_new_points", "(", "mesh", ")", ":", "# Get circumcenters everywhere except at cells adjacent to the boundary;", "# barycenters there.", ...
40.85
0.002392
def get_inters_direct(r, L, R_cut): ''' Return points within a given cut-off of each other, in a periodic system. Uses a direct algorithm, which may be very slow for large numbers of points. Parameters ---------- r: array, shape (n, d) where d is one of (2, 3). A set of n point...
[ "def", "get_inters_direct", "(", "r", ",", "L", ",", "R_cut", ")", ":", "_cell_list", ".", "cell_list_direct", ".", "make_inters", "(", "r", ".", "T", ",", "L", ",", "R_cut", ")", "return", "_parse_inters", "(", ")" ]
32.46875
0.000935
def tree2text(tree_obj, indent=4): # type: (TreeInfo, int) -> str """ Return text representation of a decision tree. """ parts = [] def _format_node(node, depth=0): # type: (NodeInfo, int) -> None def p(*args): # type: (*str) -> None parts.append(" " * de...
[ "def", "tree2text", "(", "tree_obj", ",", "indent", "=", "4", ")", ":", "# type: (TreeInfo, int) -> str", "parts", "=", "[", "]", "def", "_format_node", "(", "node", ",", "depth", "=", "0", ")", ":", "# type: (NodeInfo, int) -> None", "def", "p", "(", "*", ...
32.651163
0.000692
def _expand_subsystems(self, scope_infos): """Add all subsystems tied to a scope, right after that scope.""" # Get non-global subsystem dependencies of the specified subsystem client. def subsys_deps(subsystem_client_cls): for dep in subsystem_client_cls.subsystem_dependencies_iter(): if dep....
[ "def", "_expand_subsystems", "(", "self", ",", "scope_infos", ")", ":", "# Get non-global subsystem dependencies of the specified subsystem client.", "def", "subsys_deps", "(", "subsystem_client_cls", ")", ":", "for", "dep", "in", "subsystem_client_cls", ".", "subsystem_depen...
50.153846
0.010534
async def call_with_fd_list(proxy, method_name, signature, args, fds, flags=0, timeout_msec=-1): """ Asynchronously call the specified method on a DBus proxy object. :param Gio.DBusProxy proxy: :param str method_name: :param str signature: :param tuple args: :par...
[ "async", "def", "call_with_fd_list", "(", "proxy", ",", "method_name", ",", "signature", ",", "args", ",", "fds", ",", "flags", "=", "0", ",", "timeout_msec", "=", "-", "1", ")", ":", "future", "=", "Future", "(", ")", "cancellable", "=", "None", "fd_l...
27.724138
0.001202
def get_initial(self): """Used during adding/editing of data.""" self.query = self.get_queryset() mongo_ids = {'mongo_id': [str(x.id) for x in self.query]} return mongo_ids
[ "def", "get_initial", "(", "self", ")", ":", "self", ".", "query", "=", "self", ".", "get_queryset", "(", ")", "mongo_ids", "=", "{", "'mongo_id'", ":", "[", "str", "(", "x", ".", "id", ")", "for", "x", "in", "self", ".", "query", "]", "}", "retu...
40
0.009804
def sections(self) -> list: """List of sections.""" self.config.read(self.filepath) return self.config.sections()
[ "def", "sections", "(", "self", ")", "->", "list", ":", "self", ".", "config", ".", "read", "(", "self", ".", "filepath", ")", "return", "self", ".", "config", ".", "sections", "(", ")" ]
33.5
0.014599
def dataSetMissingValue(h5Dataset): """ Returns the missingData given a HDF-5 dataset Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. HDF-EOS and NetCDF files seem to put the attributes in 1-e...
[ "def", "dataSetMissingValue", "(", "h5Dataset", ")", ":", "attributes", "=", "h5Dataset", ".", "attrs", "if", "not", "attributes", ":", "return", "None", "# a premature optimization :-)", "for", "key", "in", "(", "'missing_value'", ",", "'MissingValue'", ",", "'mi...
44.333333
0.008412
def default_output_mask(file_out, texture=True, vert_normals=True, vert_colors=False, face_colors=False, ml_version=ML_VERSION): """ Set default output mask options based on file extension Note: v1.34BETA changed -om switch to -m Possible options (not all options are available fo...
[ "def", "default_output_mask", "(", "file_out", ",", "texture", "=", "True", ",", "vert_normals", "=", "True", ",", "vert_colors", "=", "False", ",", "face_colors", "=", "False", ",", "ml_version", "=", "ML_VERSION", ")", ":", "vn", "=", "''", "wt", "=", ...
25.346939
0.00155