text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def bumperEvent2BumperData(event): ''' Translates from ROS BumperScan to JderobotTypes BumperData. @param event: ROS BumperScan to translate @type event: BumperScan @return a BumperData translated from event # bumper LEFT = 0 CENTER = 1 RIGHT = 2 # state RELEASED = ...
[ "def", "bumperEvent2BumperData", "(", "event", ")", ":", "bump", "=", "BumperData", "(", ")", "bump", ".", "state", "=", "event", ".", "state", "bump", ".", "bumper", "=", "event", ".", "bumper", "#bump.timeStamp = event.header.stamp.secs + (event.header.stamp.nsecs...
19.538462
0.009381
def compile_into_spirv(raw, stage, filepath, language="glsl", optimization='size', suppress_warnings=False, warnings_as_errors=False): """Compile shader code into Spir-V binary. This function uses shaderc to compile your glsl or hlsl code into Spir-V code. You ...
[ "def", "compile_into_spirv", "(", "raw", ",", "stage", ",", "filepath", ",", "language", "=", "\"glsl\"", ",", "optimization", "=", "'size'", ",", "suppress_warnings", "=", "False", ",", "warnings_as_errors", "=", "False", ")", ":", "# extract parameters", "stag...
37.297297
0.000353
def _calculate_order_value_amount(self, asset, value): """ Calculates how many shares/contracts to order based on the type of asset being ordered. """ if not self.executor.current_data.can_trade(asset): raise CannotOrderDelistedAsset( msg="Cannot order...
[ "def", "_calculate_order_value_amount", "(", "self", ",", "asset", ",", "value", ")", ":", "if", "not", "self", ".", "executor", ".", "current_data", ".", "can_trade", "(", "asset", ")", ":", "raise", "CannotOrderDelistedAsset", "(", "msg", "=", "\"Cannot orde...
35.310345
0.001901
def PROFILE_SDRAUTIAN(sg0,GamD,Gam0,Gam2,Shift0,Shift2,anuVC,sg): """ # Speed dependent Rautian profile based on HTP. # Input parameters: # sg0 : Unperturbed line position in cm-1 (Input). # GamD : Doppler HWHM in cm-1 (Input) # Gam0 : Speed-averaged line-width in cm-1 (...
[ "def", "PROFILE_SDRAUTIAN", "(", "sg0", ",", "GamD", ",", "Gam0", ",", "Gam2", ",", "Shift0", ",", "Shift2", ",", "anuVC", ",", "sg", ")", ":", "return", "pcqsdhc", "(", "sg0", ",", "GamD", ",", "Gam0", ",", "Gam2", ",", "Shift0", ",", "Shift2", ",...
53.928571
0.023438
def post_mortem(traceback): """Work with an exception in a post-mortem debugger. Try to use `ipdb` first, falling back to `pdb`. """ try: from ipdb import post_mortem except ImportError: from pdb import post_mortem message = "Entering post-mortem debugger. Type `help` for help....
[ "def", "post_mortem", "(", "traceback", ")", ":", "try", ":", "from", "ipdb", "import", "post_mortem", "except", "ImportError", ":", "from", "pdb", "import", "post_mortem", "message", "=", "\"Entering post-mortem debugger. Type `help` for help.\"", "redline", "=", "co...
26.65
0.001812
def cotangent(x, null=(-np.inf, np.inf), rtol=default_rtol, atol=default_atol): ''' cotangent(x) is equivalent to cot(x) except that it also works on sparse arrays. The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what value(s) should be assigned when x == 0 or...
[ "def", "cotangent", "(", "x", ",", "null", "=", "(", "-", "np", ".", "inf", ",", "np", ".", "inf", ")", ",", "rtol", "=", "default_rtol", ",", "atol", "=", "default_atol", ")", ":", "if", "sps", ".", "issparse", "(", "x", ")", ":", "x", "=", ...
47.192308
0.017572
def serialize(self, obj, fields=None, exclude=None, **options): """Recursively attempts to find ``Model`` and ``QuerySet`` instances to convert them into their representative datastructure per their ``Resource`` (if one exists). """ options = _merge({}, self.options, options) ...
[ "def", "serialize", "(", "self", ",", "obj", ",", "fields", "=", "None", ",", "exclude", "=", "None", ",", "*", "*", "options", ")", ":", "options", "=", "_merge", "(", "{", "}", ",", "self", ".", "options", ",", "options", ")", "# Handle model insta...
39.466667
0.001649
def _parameterize_string(raw): """Substitute placeholders in a string using CloudFormation references Args: raw (`str`): String to be processed. Byte strings are not supported; decode them before passing them to this function. Returns: `str` | :class:`troposphere.GenericHelperFn`: ...
[ "def", "_parameterize_string", "(", "raw", ")", ":", "parts", "=", "[", "]", "s_index", "=", "0", "for", "match", "in", "_PARAMETER_PATTERN", ".", "finditer", "(", "raw", ")", ":", "parts", ".", "append", "(", "raw", "[", "s_index", ":", "match", ".", ...
34.785714
0.000999
def decode(self, dataset_split=None, decode_from_file=False, checkpoint_path=None): """Decodes from dataset or file.""" if decode_from_file: decoding.decode_from_file(self._estimator, self._decode_hparams.decode_from_file, ...
[ "def", "decode", "(", "self", ",", "dataset_split", "=", "None", ",", "decode_from_file", "=", "False", ",", "checkpoint_path", "=", "None", ")", ":", "if", "decode_from_file", ":", "decoding", ".", "decode_from_file", "(", "self", ".", "_estimator", ",", "s...
37.315789
0.008253
def get_smooth_step_function(min_val, max_val, switch_point, smooth_factor): """Returns a function that moves smoothly between a minimal value and a maximal one when its value increases from a given witch point to infinity. Arguments --------- min_val: float max_val value the function will ...
[ "def", "get_smooth_step_function", "(", "min_val", ",", "max_val", ",", "switch_point", ",", "smooth_factor", ")", ":", "dif", "=", "max_val", "-", "min_val", "def", "_smooth_step", "(", "x", ")", ":", "return", "min_val", "+", "dif", "*", "tanh", "(", "("...
35.88
0.002172
def data_received(self, data): """Message was received from device.""" # A message might be split over several reads, so we store a buffer and # try to decode messages from that buffer self._buffer += data log_binary(_LOGGER, '<< Receive', Data=data) while self._buffer: ...
[ "def", "data_received", "(", "self", ",", "data", ")", ":", "# A message might be split over several reads, so we store a buffer and", "# try to decode messages from that buffer", "self", ".", "_buffer", "+=", "data", "log_binary", "(", "_LOGGER", ",", "'<< Receive'", ",", ...
41.5
0.002141
def publish(obj, event, event_state, **kwargs): """Publish an event from an object. This is a really basic pub-sub event system to allow for tracking progress on methods externally. It fires the events for the first match it finds in the object hierarchy, going most specific to least. If no match is ...
[ "def", "publish", "(", "obj", ",", "event", ",", "event_state", ",", "*", "*", "kwargs", ")", ":", "# short-circuit if nothing is listening", "if", "len", "(", "EVENT_HANDLERS", ")", "==", "0", ":", "return", "if", "inspect", ".", "isclass", "(", "obj", ")...
34.902439
0.00068
def _ci_to_hgvs_coord(s, e): """ Convert continuous interbase (right-open) coordinates (..,-2,-1,0,1,..) to discontinuous HGVS coordinates (..,-2,-1,1,2,..) """ def _ci_to_hgvs(c): return c + 1 if c >= 0 else c return (None if s is None else _ci_to_hgvs(s), None if e is None else _ci_to_hg...
[ "def", "_ci_to_hgvs_coord", "(", "s", ",", "e", ")", ":", "def", "_ci_to_hgvs", "(", "c", ")", ":", "return", "c", "+", "1", "if", "c", ">=", "0", "else", "c", "return", "(", "None", "if", "s", "is", "None", "else", "_ci_to_hgvs", "(", "s", ")", ...
35.777778
0.009091
def copy_dir_if_newer( src_fs, # type: Union[FS, Text] src_path, # type: Text dst_fs, # type: Union[FS, Text] dst_path, # type: Text walker=None, # type: Optional[Walker] on_copy=None, # type: Optional[_OnCopy] workers=0, # type: int ): # type: (...) -> None """Copy a director...
[ "def", "copy_dir_if_newer", "(", "src_fs", ",", "# type: Union[FS, Text]", "src_path", ",", "# type: Text", "dst_fs", ",", "# type: Union[FS, Text]", "dst_path", ",", "# type: Text", "walker", "=", "None", ",", "# type: Optional[Walker]", "on_copy", "=", "None", ",", ...
42.621951
0.001398
def dist_abs( self, src, tar, weights='exponential', max_length=8, normalized=False ): """Calculate the distance between the Eudex hashes of two terms. Parameters ---------- src : str Source string for comparison tar : str Target string for co...
[ "def", "dist_abs", "(", "self", ",", "src", ",", "tar", ",", "weights", "=", "'exponential'", ",", "max_length", "=", "8", ",", "normalized", "=", "False", ")", ":", "# Calculate the eudex hashes and XOR them", "xored", "=", "eudex", "(", "src", ",", "max_le...
33.061404
0.000773
def smoothscale(self, surface): """ Smooth scaling using MMX or SSE extensions if available """ return self._pygame.transform.smoothscale(surface, self._output_size)
[ "def", "smoothscale", "(", "self", ",", "surface", ")", ":", "return", "self", ".", "_pygame", ".", "transform", ".", "smoothscale", "(", "surface", ",", "self", ".", "_output_size", ")" ]
38.6
0.010152
def main(): """ NAME sort_specimens.py DESCRIPTION Reads in a pmag_specimen formatted file and separates it into different components (A,B...etc.) SYNTAX sort_specimens.py [-h] [command line options] INPUT takes pmag_specimens.txt formatted input file OPTIONS...
[ "def", "main", "(", ")", ":", "dir_path", "=", "'.'", "inspec", "=", "\"pmag_specimens.txt\"", "if", "'-WD'", "in", "sys", ".", "argv", ":", "ind", "=", "sys", ".", "argv", ".", "index", "(", "'-WD'", ")", "dir_path", "=", "sys", ".", "argv", "[", ...
37.758065
0.022481
def _prune(self): """Primitive way to keep dict in sync with RB.""" delkeys = [k for k in self.keys() if k not in self.__ringbuffer] for k in delkeys: # necessary because dict is changed during iterations super(KRingbuffer,self).__delitem__(k)
[ "def", "_prune", "(", "self", ")", ":", "delkeys", "=", "[", "k", "for", "k", "in", "self", ".", "keys", "(", ")", "if", "k", "not", "in", "self", ".", "__ringbuffer", "]", "for", "k", "in", "delkeys", ":", "# necessary because dict is changed during ite...
55.2
0.014286
def get_core(self): """ Get an unsatisfiable core if the formula was previously unsatisfied. """ if self.minisat and self.status == False: return pysolvers.minisat22_core(self.minisat)
[ "def", "get_core", "(", "self", ")", ":", "if", "self", ".", "minisat", "and", "self", ".", "status", "==", "False", ":", "return", "pysolvers", ".", "minisat22_core", "(", "self", ".", "minisat", ")" ]
29.75
0.012245
def _configure_io_handler(self, handler): """Register an io-handler at the polling object.""" if self.check_events(): return if handler in self._unprepared_handlers: old_fileno = self._unprepared_handlers[handler] prepared = self._prepare_io_handler(handler) ...
[ "def", "_configure_io_handler", "(", "self", ",", "handler", ")", ":", "if", "self", ".", "check_events", "(", ")", ":", "return", "if", "handler", "in", "self", ".", "_unprepared_handlers", ":", "old_fileno", "=", "self", ".", "_unprepared_handlers", "[", "...
40.536585
0.001763
def send_message(self, message, sign=True): """Sends the given message to the connection. @type message: OmapiMessage @type sign: bool @param sign: whether the message needs to be signed @raises OmapiError: @raises socket.error: """ self.check_connected() self.protocol.send_message(message, sign)
[ "def", "send_message", "(", "self", ",", "message", ",", "sign", "=", "True", ")", ":", "self", ".", "check_connected", "(", ")", "self", ".", "protocol", ".", "send_message", "(", "message", ",", "sign", ")" ]
30.6
0.034921
def create_channel( target: str, options: Optional[List[Tuple[str, Any]]] = None, interceptors: Optional[List[ClientInterceptor]] = None, ) -> grpc.Channel: """Creates a gRPC channel The gRPC channel is created with the provided options and intercepts each invocation via the provide...
[ "def", "create_channel", "(", "target", ":", "str", ",", "options", ":", "Optional", "[", "List", "[", "Tuple", "[", "str", ",", "Any", "]", "]", "]", "=", "None", ",", "interceptors", ":", "Optional", "[", "List", "[", "ClientInterceptor", "]", "]", ...
39.034483
0.000862
def pdfdump(self, filename=None, **kargs): """ pdfdump(filename=None, layer_shift=0, rebuild=1) Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called. :param filename: the file's filename """ from scap...
[ "def", "pdfdump", "(", "self", ",", "filename", "=", "None", ",", "*", "*", "kargs", ")", ":", "from", "scapy", ".", "config", "import", "conf", "from", "scapy", ".", "utils", "import", "get_temp_file", ",", "ContextManagerSubprocess", "canvas", "=", "self...
39.458333
0.002062
def _print(self, tree, prefix, carryon): """Compute and print a new line of the tree. This is a recursive function. arguments tree -- tree to print prefix -- prefix to the current line to print carryon -- prefix which is used to carry on the vertical lines """ ...
[ "def", "_print", "(", "self", ",", "tree", ",", "prefix", ",", "carryon", ")", ":", "level", "=", "prefix", ".", "count", "(", "self", ".", "cross", ")", "+", "prefix", ".", "count", "(", "self", ".", "vline", ")", "len_children", "=", "0", "if", ...
39.9
0.001468
def normalize_q_value(self): ''' Normalize q-value. Override. This method is called in each learning steps. For example: self.q_df.q_value = self.q_df.q_value / self.q_df.q_value.sum() ''' if self.q_df is not None and self.q_...
[ "def", "normalize_q_value", "(", "self", ")", ":", "if", "self", ".", "q_df", "is", "not", "None", "and", "self", ".", "q_df", ".", "shape", "[", "0", "]", ":", "# min-max normalization", "self", ".", "q_df", ".", "q_value", "=", "(", "self", ".", "q...
34.785714
0.012
def _print_results_to_stdout( self, classifications, crossmatches): """*print the classification and crossmatch results for a single transient object to stdout* **Key Arguments:** - ``crossmatches`` -- the unranked crossmatch classifications -...
[ "def", "_print_results_to_stdout", "(", "self", ",", "classifications", ",", "crossmatches", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_print_results_to_stdout`` method'", ")", "if", "self", ".", "verbose", "==", "0", ":", "return", "if", ...
43.504505
0.002227
def insert_code(filename, code, save=True, marker='# ATX CODE END'): """ Auto append code """ content = '' found = False for line in open(filename, 'rb'): if not found and line.strip() == marker: found = True cnt = line.find(marker) content += line[:cnt] + cod...
[ "def", "insert_code", "(", "filename", ",", "code", ",", "save", "=", "True", ",", "marker", "=", "'# ATX CODE END'", ")", ":", "content", "=", "''", "found", "=", "False", "for", "line", "in", "open", "(", "filename", ",", "'rb'", ")", ":", "if", "n...
30.777778
0.001751
def ascii_native_(s): ''' Python 3: If ``s`` is an instance of ``text_type``, return ``s.encode('ascii')``, otherwise return ``str(s, 'ascii', 'strict')`` Python 2: If ``s`` is an instance of ``text_type``, return ``s.encode('ascii')``, otherwise return ``str(s)`` ''' if isinstance(s, text_...
[ "def", "ascii_native_", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "text_type", ")", ":", "s", "=", "s", ".", "encode", "(", "'ascii'", ")", "return", "str", "(", "s", ",", "'ascii'", ",", "'strict'", ")", "if", "PY3", "else", "s" ]
33.083333
0.002451
def maxchord(A, ve = None): """ Maximal chordal subgraph of sparsity graph. Returns a lower triangular sparse matrix which is the projection of :math:`A` on a maximal chordal subgraph and a perfect elimination order :math:`p`. Only the lower triangular part of :math:`A` is accessed. The opt...
[ "def", "maxchord", "(", "A", ",", "ve", "=", "None", ")", ":", "n", "=", "A", ".", "size", "[", "0", "]", "assert", "A", ".", "size", "[", "1", "]", "==", "n", ",", "\"A must be a square matrix\"", "assert", "type", "(", "A", ")", "is", "spmatrix...
32.670886
0.01053
def calc_rfc_sfc_v1(self): """Calculate the corrected fractions rainfall/snowfall and total precipitation. Required control parameters: |NmbZones| |RfCF| |SfCF| Calculated flux sequences: |RfC| |SfC| Basic equations: :math:`RfC = RfCF \\cdot FracRain` \n ...
[ "def", "calc_rfc_sfc_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", "fastaccess", "for", "k", "in", "range", "(", "con", ".", "nmbzones", "...
29.482143
0.000586
def _uminUmaxFindStart(u, E,Lz,I3U,delta,u0,sinh2u0,v0,sin2v0, potu0v0,pot,umax=False): """ NAME: _uminUmaxFindStart PURPOSE: Find adequate start or end points to solve for umin and umax INPUT: same as JRStaeckelIntegrandSquared OUTP...
[ "def", "_uminUmaxFindStart", "(", "u", ",", "E", ",", "Lz", ",", "I3U", ",", "delta", ",", "u0", ",", "sinh2u0", ",", "v0", ",", "sin2v0", ",", "potu0v0", ",", "pot", ",", "umax", "=", "False", ")", ":", "if", "umax", ":", "utry", "=", "u", "*"...
28.757576
0.028542
def from_custom_template(cls, searchpath, name): """ Factory function for creating a subclass of ``Styler`` with a custom template and Jinja environment. Parameters ---------- searchpath : str or list Path or paths of directories containing the templates ...
[ "def", "from_custom_template", "(", "cls", ",", "searchpath", ",", "name", ")", ":", "loader", "=", "ChoiceLoader", "(", "[", "FileSystemLoader", "(", "searchpath", ")", ",", "cls", ".", "loader", ",", "]", ")", "class", "MyStyler", "(", "cls", ")", ":",...
29
0.002472
def compute_rmsd_by_matrix(dataframe_1, dataframe_2, use_assertion = False): '''Computes the RMSD of two pandas dataframes. The dataframes are expected to be of equal dimensions and use_assertion can be set to assert that the row indices match. ''' if use_assertion: assert([i for i in dataframe_1.index] ...
[ "def", "compute_rmsd_by_matrix", "(", "dataframe_1", ",", "dataframe_2", ",", "use_assertion", "=", "False", ")", ":", "if", "use_assertion", ":", "assert", "(", "[", "i", "for", "i", "in", "dataframe_1", ".", "index", "]", "==", "[", "i", "for", "i", "i...
87.666667
0.015066
def update_service(name, service_map): """Get an update from the specified service. Arguments: name (:py:class:`str`): The name of the service. service_map (:py:class:`dict`): A mapping of service names to :py:class:`flash.service.core.Service` instances. Returns: :py:class:`dict...
[ "def", "update_service", "(", "name", ",", "service_map", ")", ":", "if", "name", "in", "service_map", ":", "service", "=", "service_map", "[", "name", "]", "data", "=", "service", ".", "update", "(", ")", "if", "not", "data", ":", "logger", ".", "warn...
31.36
0.001238
def t_prepro_define_defargs_defargsopt_defexpr_pragma_if_NEWLINE(self, t): r'\r?\n' t.lexer.lineno += 1 t.lexer.pop_state() return t
[ "def", "t_prepro_define_defargs_defargsopt_defexpr_pragma_if_NEWLINE", "(", "self", ",", "t", ")", ":", "t", ".", "lexer", ".", "lineno", "+=", "1", "t", ".", "lexer", ".", "pop_state", "(", ")", "return", "t" ]
32
0.012195
def _format_causes(err, level=0): """Return a cascading explanation of the validation error. Returns a cascading explanation of the validation error in the form of:: <validator> failed @ <subfield_path> because of: <validator> failed @ <subfield_path> because of: ... ...
[ "def", "_format_causes", "(", "err", ",", "level", "=", "0", ")", ":", "lines", "=", "[", "]", "def", "_print", "(", "string", ",", "offset", "=", "0", ")", ":", "lines", ".", "append", "(", "_pad", "(", "string", ",", "offset", "=", "offset", ")...
31.53125
0.000481
def parse_operand(string, location, tokens): """Parse an ARM instruction operand. """ if "immediate_operand" in tokens: size = arch_info.operand_size oprnd = ArmImmediateOperand("".join(tokens["immediate_operand"]), size) if "register_operand" in tokens: oprnd = process_registe...
[ "def", "parse_operand", "(", "string", ",", "location", ",", "tokens", ")", ":", "if", "\"immediate_operand\"", "in", "tokens", ":", "size", "=", "arch_info", ".", "operand_size", "oprnd", "=", "ArmImmediateOperand", "(", "\"\"", ".", "join", "(", "tokens", ...
36.059701
0.001612
def git_ssh_or_die(username, key_dir='~/.ssh'): ''' Check if a ssh-key is created and imported in github. Else, exit with return value 1 (die). ''' key_dir_expanded = os.path.expanduser(key_dir) # ssh pub key dictionary pub_keys = [] # check if ~/.ssh exists, if not die if not os.path....
[ "def", "git_ssh_or_die", "(", "username", ",", "key_dir", "=", "'~/.ssh'", ")", ":", "key_dir_expanded", "=", "os", ".", "path", ".", "expanduser", "(", "key_dir", ")", "# ssh pub key dictionary", "pub_keys", "=", "[", "]", "# check if ~/.ssh exists, if not die", ...
40.64
0.000961
def query(self, criteria, **opts): """ Returns a dict of the query, including the results :param critera: string of search criteria :param **opts: :formats: json/xml (default: json) :timezone: timezone to use (default: UTC) :time_from: 15m ...
[ "def", "query", "(", "self", ",", "criteria", ",", "*", "*", "opts", ")", ":", "time_now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "replace", "(", "second", "=", "0", ",", "microsecond", "=", "0", ")", "right_now", "=", "time_n...
33.595238
0.001377
def get_object(brain_object_uid, default=_marker): """Get the full content object :param brain_object_uid: A catalog brain or content object or uid :type brain_object_uid: PortalObject/ATContentType/DexterityContentType /CatalogBrain/basestring :returns: The full object """ if is_uid(brain_...
[ "def", "get_object", "(", "brain_object_uid", ",", "default", "=", "_marker", ")", ":", "if", "is_uid", "(", "brain_object_uid", ")", ":", "return", "get_object_by_uid", "(", "brain_object_uid", ")", "if", "not", "is_object", "(", "brain_object_uid", ")", ":", ...
37.647059
0.001524
def get_cpu_property(self, property_p): """Returns the virtual CPU boolean value of the specified property. in property_p of type :class:`CPUPropertyType` Property type to query. return value of type bool Property value. raises :class:`OleErrorInvalidarg` ...
[ "def", "get_cpu_property", "(", "self", ",", "property_p", ")", ":", "if", "not", "isinstance", "(", "property_p", ",", "CPUPropertyType", ")", ":", "raise", "TypeError", "(", "\"property_p can only be an instance of type CPUPropertyType\"", ")", "value", "=", "self",...
33.333333
0.008104
def get_completion_args(self, is_completion=False, comp_line=None): # pylint: disable=no-self-use """ Get the args that will be used to tab completion if completion is active. """ is_completion = is_completion or os.environ.get(ARGCOMPLETE_ENV_NAME) comp_line = comp_line or os.environ.get('COMP...
[ "def", "get_completion_args", "(", "self", ",", "is_completion", "=", "False", ",", "comp_line", "=", "None", ")", ":", "# pylint: disable=no-self-use", "is_completion", "=", "is_completion", "or", "os", ".", "environ", ".", "get", "(", "ARGCOMPLETE_ENV_NAME", ")"...
76.166667
0.008658
def _subclassed(base, *classes): """Check if all classes are subclassed from base. """ return all(map(lambda obj: isinstance(obj, base), classes))
[ "def", "_subclassed", "(", "base", ",", "*", "classes", ")", ":", "return", "all", "(", "map", "(", "lambda", "obj", ":", "isinstance", "(", "obj", ",", "base", ")", ",", "classes", ")", ")" ]
41.75
0.011765
def mugshot2to3(old): """ Upgrader for L{Mugshot} from version 2 to version 3, which re-thumbnails the mugshot to take into account the new value of L{Mugshot.smallerSize}. """ new = old.upgradeVersion(Mugshot.typeName, 2, 3, person=old.person, ...
[ "def", "mugshot2to3", "(", "old", ")", ":", "new", "=", "old", ".", "upgradeVersion", "(", "Mugshot", ".", "typeName", ",", "2", ",", "3", ",", "person", "=", "old", ".", "person", ",", "type", "=", "old", ".", "type", ",", "body", "=", "old", "....
43.076923
0.001748
def _printDescription(self, hrlinetop=True): """generic method to print out a description""" if hrlinetop: self._print("----------------") NOTFOUND = "[not found]" if self.currentEntity: obj = self.currentEntity['object'] label = obj.bestLabel() or NOT...
[ "def", "_printDescription", "(", "self", ",", "hrlinetop", "=", "True", ")", ":", "if", "hrlinetop", ":", "self", ".", "_print", "(", "\"----------------\"", ")", "NOTFOUND", "=", "\"[not found]\"", "if", "self", ".", "currentEntity", ":", "obj", "=", "self"...
54.742857
0.001538
def run_outdated(cls, options): """Print outdated user packages.""" latest_versions = sorted( cls.find_packages_latest_versions(cls.options), key=lambda p: p[0].project_name.lower()) for dist, latest_version, typ in latest_versions: if latest_version > dist.p...
[ "def", "run_outdated", "(", "cls", ",", "options", ")", ":", "latest_versions", "=", "sorted", "(", "cls", ".", "find_packages_latest_versions", "(", "cls", ".", "options", ")", ",", "key", "=", "lambda", "p", ":", "p", "[", "0", "]", ".", "project_name"...
45.571429
0.001535
def damping_kraus_map(p=0.10): """ Generate the Kraus operators corresponding to an amplitude damping noise channel. :param float p: The one-step damping probability. :return: A list [k1, k2] of the Kraus operators that parametrize the map. :rtype: list """ damping_op = np.sqrt(p) * np....
[ "def", "damping_kraus_map", "(", "p", "=", "0.10", ")", ":", "damping_op", "=", "np", ".", "sqrt", "(", "p", ")", "*", "np", ".", "array", "(", "[", "[", "0", ",", "1", "]", ",", "[", "0", ",", "0", "]", "]", ")", "residual_kraus", "=", "np",...
32.928571
0.00211
def calc_accounts(S, L, Y, nr_sectors): """ Calculate sector specific cba and pba based accounts, imp and exp accounts The total industry output x for the calculation is recalculated from L and y Parameters ---------- L : pandas.DataFrame Leontief input output table L S : pandas.Da...
[ "def", "calc_accounts", "(", "S", ",", "L", ",", "Y", ",", "nr_sectors", ")", ":", "# diagonalize each sector block per country", "# this results in a disaggregated y with final demand per country per", "# sector in one column", "Y_diag", "=", "ioutil", ".", "diagonalize_blocks...
34.6
0.000865
def evaluate(self): """Evaluate functional value of previous iteration.""" if self.opt['AccurateDFid']: if self.dmethod == 'fista': D = self.dstep.getdict(crop=False) else: D = self.dstep.var_y() if self.xmethod == 'fista': ...
[ "def", "evaluate", "(", "self", ")", ":", "if", "self", ".", "opt", "[", "'AccurateDFid'", "]", ":", "if", "self", ".", "dmethod", "==", "'fista'", ":", "D", "=", "self", ".", "dstep", ".", "getdict", "(", "crop", "=", "False", ")", "else", ":", ...
40
0.002123
def assign(self, node): """ Translate an assign node into SQLQuery. :param node: a treebrd node :return: a SQLQuery object for the tree rooted at node """ child_object = self.translate(node.child) child_object.prefix = 'CREATE TEMPORARY TABLE {name}({attributes}) ...
[ "def", "assign", "(", "self", ",", "node", ")", ":", "child_object", "=", "self", ".", "translate", "(", "node", ".", "child", ")", "child_object", ".", "prefix", "=", "'CREATE TEMPORARY TABLE {name}({attributes}) AS '", ".", "format", "(", "name", "=", "node"...
42.5
0.009217
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` clas...
[ "def", "checkArgs", "(", "args", ")", ":", "# Checking the input file", "if", "not", "os", ".", "path", ".", "isfile", "(", "args", ".", "problematic_samples", ")", ":", "msg", "=", "\"{}: no such file\"", ".", "format", "(", "args", ".", "problematic_samples"...
29.533333
0.001093
def gpsWeek(year, month, day): "returns (full) gpsWeek for given date (in UTC)" hr = 12 #make sure you fall into right day, middle is save return gpsFromUTC(year, month, day, hr, 0, 0.0)[0]
[ "def", "gpsWeek", "(", "year", ",", "month", ",", "day", ")", ":", "hr", "=", "12", "#make sure you fall into right day, middle is save", "return", "gpsFromUTC", "(", "year", ",", "month", ",", "day", ",", "hr", ",", "0", ",", "0.0", ")", "[", "0", "]" ]
49.75
0.009901
def Montillet_Akkari_Comiti(dp, voidage, vs, rho, mu, L=1, Dt=None): r'''Calculates pressure drop across a packed bed of spheres as in [2]_, originally in [1]_. Wall effect adjustment is used if `Dt` is provided. .. math:: \frac{\Delta P}{L\rho V_s^2} D_p \frac{\epsilon^3}{(1-\epsilon)} = a...
[ "def", "Montillet_Akkari_Comiti", "(", "dp", ",", "voidage", ",", "vs", ",", "rho", ",", "mu", ",", "L", "=", "1", ",", "Dt", "=", "None", ")", ":", "Re", "=", "rho", "*", "vs", "*", "dp", "/", "mu", "if", "voidage", "<", "0.4", ":", "a", "="...
31.305556
0.00129
def set_classes(self): """Set field properties and custom classes. """ # Custom field classes on field wrapper if self.attrs.get("_field_class"): self.values["class"].append(escape(self.attrs.get("_field_class"))) # Inline class if self.attrs.get("_inline"): self.values["class"].append("inli...
[ "def", "set_classes", "(", "self", ")", ":", "# Custom field classes on field wrapper\r", "if", "self", ".", "attrs", ".", "get", "(", "\"_field_class\"", ")", ":", "self", ".", "values", "[", "\"class\"", "]", ".", "append", "(", "escape", "(", "self", ".",...
32.85
0.026627
def _substitute(self, var_map, safe=False): """Implementation of :meth:`substitute`. For internal use, the `safe` keyword argument allows to perform a substitution on the `args` and `kwargs` of the expression only, guaranteeing that the type of the expression does not change, at the ...
[ "def", "_substitute", "(", "self", ",", "var_map", ",", "safe", "=", "False", ")", ":", "if", "self", "in", "var_map", ":", "if", "not", "safe", "or", "(", "type", "(", "var_map", "[", "self", "]", ")", "==", "type", "(", "self", ")", ")", ":", ...
47.954545
0.001859
def get_repo_relpath(repo, relpath): """Returns the absolute path to the 'relpath' taken relative to the base directory of the repository. """ from os import path if relpath[0:2] == "./": return path.join(repo, relpath[2::]) else: from os import chdir, getcwd cd = getcwd(...
[ "def", "get_repo_relpath", "(", "repo", ",", "relpath", ")", ":", "from", "os", "import", "path", "if", "relpath", "[", "0", ":", "2", "]", "==", "\"./\"", ":", "return", "path", ".", "join", "(", "repo", ",", "relpath", "[", "2", ":", ":", "]", ...
30.285714
0.002288
def _get_template(path, option_key): ''' Get the contents of a template file and provide it as a module type :param path: path to the template.yml file :type path: ``str`` :param option_key: The unique key of this template :type option_key: ``str`` :returns: Details about the template ...
[ "def", "_get_template", "(", "path", ",", "option_key", ")", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "path", ",", "'r'", ")", "as", "template_f", ":", "template", "=", "deserialize", "(", "template_f", ")", "info", "=", "(",...
30.588235
0.001866
def get_health(self): """Summarize health of managed system This provides a summary of the health of the managed system. It additionally provides an iterable list of reasons for warning, critical, or failed assessments. """ summary = {'badreadings': [], 'health': const.H...
[ "def", "get_health", "(", "self", ")", ":", "summary", "=", "{", "'badreadings'", ":", "[", "]", ",", "'health'", ":", "const", ".", "Health", ".", "Ok", "}", "fallbackreadings", "=", "[", "]", "try", ":", "self", ".", "oem_init", "(", ")", "fallback...
39.809524
0.002336
def once(self): """ Inspected function should be called one time Return: self """ def check(): #pylint: disable=missing-docstring return super(SinonExpectation, self).calledOnce self.valid_list.append(check) return self
[ "def", "once", "(", "self", ")", ":", "def", "check", "(", ")", ":", "#pylint: disable=missing-docstring", "return", "super", "(", "SinonExpectation", ",", "self", ")", ".", "calledOnce", "self", ".", "valid_list", ".", "append", "(", "check", ")", "return",...
31
0.013937
def key_regen(): ''' This routine is used to regenerate all keys in an environment. This is invasive! ALL KEYS IN THE SALT ENVIRONMENT WILL BE REGENERATED!! The key_regen routine sends a command out to minions to revoke the master key and remove all minion keys, it then removes all keys from the ma...
[ "def", "key_regen", "(", ")", ":", "client", "=", "salt", ".", "client", ".", "get_local_client", "(", "__opts__", "[", "'conf_file'", "]", ")", "try", ":", "client", ".", "cmd", "(", "'*'", ",", "'saltutil.regen_keys'", ")", "except", "SaltClientError", "...
38.96
0.000501
def get_url_for_service(service, region, endpoint_type): if 'type' not in service: return None identity_version = get_version_from_service(service) service_endpoints = service.get('endpoints', []) available_endpoints = [endpoint for endpoint in service_endpoints if re...
[ "def", "get_url_for_service", "(", "service", ",", "region", ",", "endpoint_type", ")", ":", "if", "'type'", "not", "in", "service", ":", "return", "None", "identity_version", "=", "get_version_from_service", "(", "service", ")", "service_endpoints", "=", "service...
43.37931
0.000778
def calc_total_error(data, bkg_error, effective_gain): """ Calculate a total error array, combining a background-only error array with the Poisson noise of sources. Parameters ---------- data : array_like or `~astropy.units.Quantity` The data array. bkg_error : array_like or `~astr...
[ "def", "calc_total_error", "(", "data", ",", "bkg_error", ",", "effective_gain", ")", ":", "data", "=", "np", ".", "asanyarray", "(", "data", ")", "bkg_error", "=", "np", ".", "asanyarray", "(", "bkg_error", ")", "inputs", "=", "[", "data", ",", "bkg_err...
44.196721
0.000181
def fileno(self): """ Returns an OS-level file descriptor which can be used for polling, but but not for reading or writing. This is primarily to allow Python's ``select`` module to work. The first time ``fileno`` is called on a channel, a pipe is created to simulate re...
[ "def", "fileno", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "_pipe", "is", "not", "None", ":", "return", "self", ".", "_pipe", ".", "fileno", "(", ")", "# create the pipe and feed in any existing ...
39.862069
0.001689
def findBalanced(text, openDelim, closeDelim): """ Assuming that text contains a properly balanced expression :param openDelim: as opening delimiters and :param closeDelim: as closing delimiters. :return: an iterator producing pairs (start, end) of start and end positions in text containing a ba...
[ "def", "findBalanced", "(", "text", ",", "openDelim", ",", "closeDelim", ")", ":", "openPat", "=", "'|'", ".", "join", "(", "[", "re", ".", "escape", "(", "x", ")", "for", "x", "in", "openDelim", "]", ")", "# pattern for delimiters expected after each openin...
33.95
0.002147
def verify_strain_options_multi_ifo(opts, parser, ifos): """Sanity check provided strain arguments. Parses the strain data CLI options and verifies that they are consistent and reasonable. Parameters ---------- opt : object Result of parsing the CLI with OptionParser, or any object wit...
[ "def", "verify_strain_options_multi_ifo", "(", "opts", ",", "parser", ",", "ifos", ")", ":", "for", "ifo", "in", "ifos", ":", "for", "opt_group", "in", "ensure_one_opt_groups", ":", "ensure_one_opt_multi_ifo", "(", "opts", ",", "parser", ",", "ifo", ",", "opt_...
37.5
0.001182
def mkdir_interactive(dirpath): """ Create a directory if required. This will query the user for a confirmation. Args: dirname: The path to create. """ from benchbuild.utils.cmd import mkdir if os.path.exists(dirpath): return response = ui.ask( "The directory {...
[ "def", "mkdir_interactive", "(", "dirpath", ")", ":", "from", "benchbuild", ".", "utils", ".", "cmd", "import", "mkdir", "if", "os", ".", "path", ".", "exists", "(", "dirpath", ")", ":", "return", "response", "=", "ui", ".", "ask", "(", "\"The directory ...
25
0.001751
def generalized_fma(mult_pairs, add_wires, signed=False, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): """Generated an opimitized fused multiply adder. A generalized FMA unit that multiplies each pair of numbers in mult_pairs, then adds the resulting numbers and and th...
[ "def", "generalized_fma", "(", "mult_pairs", ",", "add_wires", ",", "signed", "=", "False", ",", "reducer", "=", "adders", ".", "wallace_reducer", ",", "adder_func", "=", "adders", ".", "kogge_stone", ")", ":", "# first need to figure out the max length", "if", "m...
41.254902
0.001857
def add_gwb(psr, dist=1, ngw=1000, seed=None, flow=1e-8, fhigh=1e-5, gwAmp=1e-20, alpha=-0.66, logspacing=True): """Add a stochastic background from inspiraling binaries, using the tempo2 code that underlies the GWbkgrd plugin. Here 'dist' is the pulsar distance [in kpc]; 'ngw' is the number of...
[ "def", "add_gwb", "(", "psr", ",", "dist", "=", "1", ",", "ngw", "=", "1000", ",", "seed", "=", "None", ",", "flow", "=", "1e-8", ",", "fhigh", "=", "1e-5", ",", "gwAmp", "=", "1e-20", ",", "alpha", "=", "-", "0.66", ",", "logspacing", "=", "Tr...
39.28
0.010934
def delayed_close(self): """Delayed close - won't close immediately, but on next ioloop tick.""" self.state = CLOSING self.server.io_loop.add_callback(self.close)
[ "def", "delayed_close", "(", "self", ")", ":", "self", ".", "state", "=", "CLOSING", "self", ".", "server", ".", "io_loop", ".", "add_callback", "(", "self", ".", "close", ")" ]
45.75
0.010753
def p_block_0(self, p): "block : blockId object" if DEBUG: self.print_p(p) p[0] = (p[1], p[2])
[ "def", "p_block_0", "(", "self", ",", "p", ")", ":", "if", "DEBUG", ":", "self", ".", "print_p", "(", "p", ")", "p", "[", "0", "]", "=", "(", "p", "[", "1", "]", ",", "p", "[", "2", "]", ")" ]
25.2
0.015385
def _convert_type(data_type): # @NoSelf ''' Converts CDF data types into python types ''' if data_type in (1, 41): dt_string = 'b' elif data_type == 2: dt_string = 'h' elif data_type == 4: dt_string = 'i' elif data_type in (8, ...
[ "def", "_convert_type", "(", "data_type", ")", ":", "# @NoSelf", "if", "data_type", "in", "(", "1", ",", "41", ")", ":", "dt_string", "=", "'b'", "elif", "data_type", "==", "2", ":", "dt_string", "=", "'h'", "elif", "data_type", "==", "4", ":", "dt_str...
27.266667
0.002361
def generate_dir_rst(src_dir, target_dir, gallery_conf, seen_backrefs): """Generate the gallery reStructuredText for an example directory""" if not os.path.exists(os.path.join(src_dir, 'README.txt')): print(80 * '_') print('Example directory %s does not have a README.txt file' % sr...
[ "def", "generate_dir_rst", "(", "src_dir", ",", "target_dir", ",", "gallery_conf", ",", "seen_backrefs", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "src_dir", ",", "'README.txt'", ")", ")", ":", "...
36.5
0.000635
def createuser(ctx, email, password, superuser, no_password, prompt): 'Create a new user.' if prompt: if not email: email = click.prompt('Email') if not (password or no_password): password = click.prompt('Password') if superuser is None: superuser =...
[ "def", "createuser", "(", "ctx", ",", "email", ",", "password", ",", "superuser", ",", "no_password", ",", "prompt", ")", ":", "if", "prompt", ":", "if", "not", "email", ":", "email", "=", "click", ".", "prompt", "(", "'Email'", ")", "if", "not", "("...
26.288136
0.002486
def check_sizes(size, width, height): """ Check that these arguments, in supplied, are consistent. Return a (width, height) pair. """ if not size: return width, height if len(size) != 2: raise ValueError( "size argument should be a pair (width, height)") if width ...
[ "def", "check_sizes", "(", "size", ",", "width", ",", "height", ")", ":", "if", "not", "size", ":", "return", "width", ",", "height", "if", "len", "(", "size", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"size argument should be a pair (width, height)...
31.333333
0.001475
def load_eggs(entry_point_name): """Loader that loads any eggs in `sys.path`.""" def _load_eggs(env): distributions, errors = working_set.find_plugins( pkg_resources.Environment() ) for dist in distributions: if dist not in working_set: env.log.deb...
[ "def", "load_eggs", "(", "entry_point_name", ")", ":", "def", "_load_eggs", "(", "env", ")", ":", "distributions", ",", "errors", "=", "working_set", ".", "find_plugins", "(", "pkg_resources", ".", "Environment", "(", ")", ")", "for", "dist", "in", "distribu...
38.731707
0.000614
def select_proxy(url, proxies): """Select a proxy for the url, if applicable. :param url: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs """ proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: retur...
[ "def", "select_proxy", "(", "url", ",", "proxies", ")", ":", "proxies", "=", "proxies", "or", "{", "}", "urlparts", "=", "urlparse", "(", "url", ")", "if", "urlparts", ".", "hostname", "is", "None", ":", "return", "proxies", ".", "get", "(", "urlparts"...
27.583333
0.00146
def write_genotypes(self, genotypes): """Write genotypes to binary file. Args: genotypes (numpy.ndarray): The genotypes to write in the BED file. """ if self._mode != "w": raise UnsupportedOperation("not available in 'r' mode") # Initializing the number...
[ "def", "write_genotypes", "(", "self", ",", "genotypes", ")", ":", "if", "self", ".", "_mode", "!=", "\"w\"", ":", "raise", "UnsupportedOperation", "(", "\"not available in 'r' mode\"", ")", "# Initializing the number of samples if required", "if", "self", ".", "_nb_v...
33.185185
0.002169
def nextClass(self, classuri): """Returns the next class in the list of classes. If it's the last one, returns the first one.""" if classuri == self.classes[-1].uri: return self.classes[0] flag = False for x in self.classes: if flag == True: return...
[ "def", "nextClass", "(", "self", ",", "classuri", ")", ":", "if", "classuri", "==", "self", ".", "classes", "[", "-", "1", "]", ".", "uri", ":", "return", "self", ".", "classes", "[", "0", "]", "flag", "=", "False", "for", "x", "in", "self", ".",...
35.818182
0.009901
def get_items(self, scenario_id): """ Get all the items in this group, in the given scenario """ items = get_session().query(ResourceGroupItem)\ .filter(ResourceGroupItem.group_id==self.id).\ filter(ResourceGroupItem.scenario_id==scenario_id).all() ...
[ "def", "get_items", "(", "self", ",", "scenario_id", ")", ":", "items", "=", "get_session", "(", ")", ".", "query", "(", "ResourceGroupItem", ")", ".", "filter", "(", "ResourceGroupItem", ".", "group_id", "==", "self", ".", "id", ")", ".", "filter", "(",...
36.666667
0.017751
def _GetPkgResources(package_name, filepath): """A wrapper for the `pkg_resource.resource_filename` function.""" requirement = pkg_resources.Requirement.parse(package_name) try: return pkg_resources.resource_filename(requirement, filepath) except pkg_resources.DistributionNotFound: # It may be that the ...
[ "def", "_GetPkgResources", "(", "package_name", ",", "filepath", ")", ":", "requirement", "=", "pkg_resources", ".", "Requirement", ".", "parse", "(", "package_name", ")", "try", ":", "return", "pkg_resources", ".", "resource_filename", "(", "requirement", ",", ...
49.142857
0.012839
def adjoint(self): """Adjoint of this operator. The adjoint is given by taking the transpose of the matrix and the adjoint of each component operator. In weighted product spaces, the adjoint needs to take the weightings into account. This is currently not supported. Re...
[ "def", "adjoint", "(", "self", ")", ":", "# Lazy import to improve `import odl` time", "import", "scipy", ".", "sparse", "adjoint_ops", "=", "[", "op", ".", "adjoint", "for", "op", "in", "self", ".", "ops", ".", "data", "]", "data", "=", "np", ".", "empty"...
32.829787
0.001259
def insidePoints(self, points, invert=False, tol=1e-05): """ Return the sublist of points that are inside a polydata closed surface. .. hint:: |pca| |pca.py|_ """ poly = self.polydata(True) # check if the stl file is closed #featureEdge = vtk.vtk...
[ "def", "insidePoints", "(", "self", ",", "points", ",", "invert", "=", "False", ",", "tol", "=", "1e-05", ")", ":", "poly", "=", "self", ".", "polydata", "(", "True", ")", "# check if the stl file is closed", "#featureEdge = vtk.vtkFeatureEdges()", "#featureEdge.F...
32.794872
0.009871
def pt_xml(self, values): """ Return the ``<c:ptCount>`` and sequence of ``<c:pt>`` elements corresponding to *values* as a single unicode text string. `c:ptCount` refers to the number of `c:pt` elements in this sequence. The `idx` attribute value for `c:pt` elements locates the ...
[ "def", "pt_xml", "(", "self", ",", "values", ")", ":", "xml", "=", "(", "' <c:ptCount val=\"{pt_count}\"/>\\n'", ")", ".", "format", "(", "pt_count", "=", "len", "(", "values", ")", ")", "pt_tmpl", "=", "(", "' <c:pt idx=\"{idx}\">\\n...
34.576923
0.002165
def in_labelset(xmrs, nodeids, label=None): """ Test if all nodeids share a label. Args: nodeids: iterable of nodeids label (str, optional): the label that all nodeids must share Returns: bool: `True` if all nodeids share a label, otherwise `False` """ nodeids = set(node...
[ "def", "in_labelset", "(", "xmrs", ",", "nodeids", ",", "label", "=", "None", ")", ":", "nodeids", "=", "set", "(", "nodeids", ")", "if", "label", "is", "None", ":", "label", "=", "xmrs", ".", "ep", "(", "next", "(", "iter", "(", "nodeids", ")", ...
31.857143
0.002179
def _diff_text(left, right, verbose=False): """Return the explanation for the diff between text or bytes Unless --verbose is used this will skip leading and trailing characters which are identical to keep the diff minimal. If the input are bytes they will be safely converted to text. """ from ...
[ "def", "_diff_text", "(", "left", ",", "right", ",", "verbose", "=", "False", ")", ":", "from", "difflib", "import", "ndiff", "explanation", "=", "[", "]", "if", "isinstance", "(", "left", ",", "py", ".", "builtin", ".", "bytes", ")", ":", "left", "=...
40.625
0.000601
def write(self, filename): """ Write detector to a file - uses HDF5 file format. Meta-data are stored alongside numpy data arrays. See h5py.org for \ details of the methods. :type filename: str :param filename: Filename to save the detector to. """ f = h...
[ "def", "write", "(", "self", ",", "filename", ")", ":", "f", "=", "h5py", ".", "File", "(", "filename", ",", "\"w\"", ")", "# Must store eqcorrscan version number, username would be useful too.", "data_group", "=", "f", ".", "create_group", "(", "name", "=", "\"...
46.912281
0.000733
def get_dataset(lcc_server, dataset_id, strformat=False, page=1): '''This downloads a JSON form of a dataset from the specified lcc_server. If the dataset contains more than 1000 rows, it will be paginated, so you must use the `page` kwarg to get the page you...
[ "def", "get_dataset", "(", "lcc_server", ",", "dataset_id", ",", "strformat", "=", "False", ",", "page", "=", "1", ")", ":", "urlparams", "=", "{", "'strformat'", ":", "1", "if", "strformat", "else", "0", ",", "'page'", ":", "page", ",", "'json'", ":",...
34.916667
0.001658
def seek(self, offset, whence): """Changes the current file position of this file. The file current position always applies to the :py:func:`IFile.read` method. Same for the :py:func:`IFile.write` method it except when the :py:func:`IFile.access_mode` is :py:attr:`FileAccess...
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", ")", ":", "if", "not", "isinstance", "(", "offset", ",", "baseinteger", ")", ":", "raise", "TypeError", "(", "\"offset can only be an instance of type baseinteger\"", ")", "if", "not", "isinstance", "(", ...
43.28
0.008137
def set_environment_var_options(config, env=None, prefix='CONFPY'): """Set any configuration options which have an environment var set. Args: config (confpy.core.config.Configuration): A configuration object which has been initialized with options. env (dict): Optional dictionary wh...
[ "def", "set_environment_var_options", "(", "config", ",", "env", "=", "None", ",", "prefix", "=", "'CONFPY'", ")", ":", "env", "=", "env", "or", "os", ".", "environ", "for", "section_name", ",", "section", "in", "config", ":", "for", "option_name", ",", ...
33.72973
0.000779
def add_catalogue(self, catalogue, overlay=False): ''' :param catalogue: Earthquake catalogue as instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue` :param dict config: Configuration parameters of the algorithm, containing the follo...
[ "def", "add_catalogue", "(", "self", ",", "catalogue", ",", "overlay", "=", "False", ")", ":", "# Magnitudes bins and minimum marrker size", "# min_mag = np.min(catalogue.data['magnitude'])", "# max_mag = np.max(catalogue.data['magnitude'])", "con_min", "=", "np", ".", "where",...
46
0.000722
def wmean_and_var(W, x): """Component-wise weighted mean and variance. Parameters ---------- W: (N,) ndarray normalised weights (must be >=0 and sum to one). x: ndarray (such that shape[0]==N) data Returns ------- dictionary {'mean':weighted_means, 'var':weig...
[ "def", "wmean_and_var", "(", "W", ",", "x", ")", ":", "m", "=", "np", ".", "average", "(", "x", ",", "weights", "=", "W", ",", "axis", "=", "0", ")", "m2", "=", "np", ".", "average", "(", "x", "**", "2", ",", "weights", "=", "W", ",", "axis...
24.315789
0.008333
def self_ip(public=False): ''' Utility for logbook information injection ''' try: if public: data = str(urlopen('http://checkip.dyndns.com/').read()) ip_addr = re.compile( r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1) else: sock = soc...
[ "def", "self_ip", "(", "public", "=", "False", ")", ":", "try", ":", "if", "public", ":", "data", "=", "str", "(", "urlopen", "(", "'http://checkip.dyndns.com/'", ")", ".", "read", "(", ")", ")", "ip_addr", "=", "re", ".", "compile", "(", "r'Address: (...
37.066667
0.001754
def __getDecision(self, result, multiple=False, **values): """ The main method for decision picking. Args: result (array of str): What values you want to get in return array. multiple (bolean, optional): Do you want multiple result if it finds many maching decisions. **values (dict): What should finder ...
[ "def", "__getDecision", "(", "self", ",", "result", ",", "multiple", "=", "False", ",", "*", "*", "values", ")", ":", "values", "=", "self", ".", "__toString", "(", "values", ")", "__valueKeyWithHeaderIndex", "=", "self", ".", "__valueKeyWithHeaderIndex", "(...
28.428571
0.028452
def cnn_learner(data:DataBunch, base_arch:Callable, cut:Union[int,Callable]=None, pretrained:bool=True, lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None, split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, init=nn.init.kaiming_norm...
[ "def", "cnn_learner", "(", "data", ":", "DataBunch", ",", "base_arch", ":", "Callable", ",", "cut", ":", "Union", "[", "int", ",", "Callable", "]", "=", "None", ",", "pretrained", ":", "bool", "=", "True", ",", "lin_ftrs", ":", "Optional", "[", "Collec...
61.384615
0.045679
def describe(self, resource=None): """Describe dataset or resource within dataset :param resource: The name of a specific resource (i.e. file or table) contained in the dataset. If ``resource`` is None, this method will describe the dataset itself. (Default value = None) ...
[ "def", "describe", "(", "self", ",", "resource", "=", "None", ")", ":", "if", "resource", "is", "None", ":", "# Show simpler descriptor, omitting schema definitions", "simple_descriptor", "=", "copy", ".", "deepcopy", "(", "self", ".", "_datapackage", ".", "descri...
46.052632
0.00224
def transition_to_rollback(self): """Transition to rollback""" assert self.state in [AQStateMachineStates.execute, AQStateMachineStates.execute_complete] self.state = AQStateMachineStates.rollback
[ "def", "transition_to_rollback", "(", "self", ")", ":", "assert", "self", ".", "state", "in", "[", "AQStateMachineStates", ".", "execute", ",", "AQStateMachineStates", ".", "execute_complete", "]", "self", ".", "state", "=", "AQStateMachineStates", ".", "rollback"...
54.25
0.013636
def log_reject( self, block_id, vtxindex, op, op_data ): """ Log a rejected operation """ debug_op = self.sanitize_op( op_data ) if 'history' in debug_op: del debug_op['history'] log.debug("REJECT %s at (%s, %s) data: %s", op_get_opcode_name( op ), block_id,...
[ "def", "log_reject", "(", "self", ",", "block_id", ",", "vtxindex", ",", "op", ",", "op_data", ")", ":", "debug_op", "=", "self", ".", "sanitize_op", "(", "op_data", ")", "if", "'history'", "in", "debug_op", ":", "del", "debug_op", "[", "'history'", "]",...
32.923077
0.029545
def module_ids(self, rev=False): """Gets a list of module ids guaranteed to be sorted by run_order, ignoring conn modules (run order < 0). """ shutit_global.shutit_global_object.yield_to_draw() ids = sorted(list(self.shutit_map.keys()),key=lambda module_id: self.shutit_map[module_id].run_order) if rev: r...
[ "def", "module_ids", "(", "self", ",", "rev", "=", "False", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "ids", "=", "sorted", "(", "list", "(", "self", ".", "shutit_map", ".", "keys", "(", ")", ")", ",", "key...
38.888889
0.036313
def from_json(json_string): """ Returns a new MessageReceived from the provided json_string string """ # parse the provided json_message try: parsed_msg = json.loads(json_string) except ValueError as ex: # if the provided json_message is not a ...
[ "def", "from_json", "(", "json_string", ")", ":", "# parse the provided json_message", "try", ":", "parsed_msg", "=", "json", ".", "loads", "(", "json_string", ")", "except", "ValueError", "as", "ex", ":", "# if the provided json_message is not a valid JSON", "return", ...
51.037736
0.010519
def disable(gandi, resource, backend, port, probe): """ Disable a backend or a probe on a webaccelerator """ result = [] if backend: backends = backend for backend in backends: if 'port' not in backend: if not port: backend['port'] = click.prom...
[ "def", "disable", "(", "gandi", ",", "resource", ",", "backend", ",", "port", ",", "probe", ")", ":", "result", "=", "[", "]", "if", "backend", ":", "backends", "=", "backend", "for", "backend", "in", "backends", ":", "if", "'port'", "not", "in", "ba...
39.708333
0.001025