text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_definition(self): """Checks variable and executable code elements based on the current context for a code element whose name matches context.exact_match perfectly. """ #Check the variables first, then the functions. match = self._bracket_exact_var(self.context.exa...
[ "def", "get_definition", "(", "self", ")", ":", "#Check the variables first, then the functions.", "match", "=", "self", ".", "_bracket_exact_var", "(", "self", ".", "context", ".", "exact_match", ")", "if", "match", "is", "None", ":", "match", "=", "self", ".",...
39.727273
0.008949
def woa_profile_from_dap(var, d, lat, lon, depth, cfg): """ Monthly Climatologic Mean and Standard Deviation from WOA, used either for temperature or salinity. INPUTS time: [day of the year] lat: [-90<lat<90] lon: [-180<lon<180] depth: [meters] Reads the WOA Monthly...
[ "def", "woa_profile_from_dap", "(", "var", ",", "d", ",", "lat", ",", "lon", ",", "depth", ",", "cfg", ")", ":", "if", "lon", "<", "0", ":", "lon", "=", "lon", "+", "360", "url", "=", "cfg", "[", "'url'", "]", "doy", "=", "int", "(", "d", "."...
41.338983
0.001201
def delete_bond(self, n, m): """ implementation of bond removing """ self.remove_edge(n, m) self.flush_cache()
[ "def", "delete_bond", "(", "self", ",", "n", ",", "m", ")", ":", "self", ".", "remove_edge", "(", "n", ",", "m", ")", "self", ".", "flush_cache", "(", ")" ]
24.166667
0.013333
def get_sound(self, title, group): ''' Retrieve sound @title from group @group. ''' return self.sounds[group.lower()][title.lower()]
[ "def", "get_sound", "(", "self", ",", "title", ",", "group", ")", ":", "return", "self", ".", "sounds", "[", "group", ".", "lower", "(", ")", "]", "[", "title", ".", "lower", "(", ")", "]" ]
32
0.012195
def get_fb_token(): """Returns access token, optionally launches browser session to get the token via a facebook login. esterhui: got this code from the interweb, but can't find the reference now. """ global ACCESS_TOKEN if not os.path.exists(TOKEN_FILE): print "Logging you in to facebo...
[ "def", "get_fb_token", "(", ")", ":", "global", "ACCESS_TOKEN", "if", "not", "os", ".", "path", ".", "exists", "(", "TOKEN_FILE", ")", ":", "print", "\"Logging you in to facebook...\"", "webbrowser", ".", "open", "(", "get_url", "(", "'/oauth/authorize'", ",", ...
41
0.009535
def random( self ): """ Select a jump at random with appropriate relative probabilities. Args: None Returns: (Jump): The randomly selected Jump. """ j = np.searchsorted( self.cumulative_probabilities(), random.random() ) return self.jumps...
[ "def", "random", "(", "self", ")", ":", "j", "=", "np", ".", "searchsorted", "(", "self", ".", "cumulative_probabilities", "(", ")", ",", "random", ".", "random", "(", ")", ")", "return", "self", ".", "jumps", "[", "j", "]" ]
26.166667
0.024615
def pub_connect(self): ''' Create and connect this thread's zmq socket. If a publisher socket already exists "pub_close" is called before creating and connecting a new socket. ''' if self.pub_sock: self.pub_close() ctx = zmq.Context.instance() ...
[ "def", "pub_connect", "(", "self", ")", ":", "if", "self", ".", "pub_sock", ":", "self", ".", "pub_close", "(", ")", "ctx", "=", "zmq", ".", "Context", ".", "instance", "(", ")", "self", ".", "_sock_data", ".", "sock", "=", "ctx", ".", "socket", "(...
39.045455
0.002273
def reset(self): """Reset the dataset to zero elements.""" self.data = [] self.size = 0 self.kdtree = None # KDTree self.nn_ready = False
[ "def", "reset", "(", "self", ")", ":", "self", ".", "data", "=", "[", "]", "self", ".", "size", "=", "0", "self", ".", "kdtree", "=", "None", "# KDTree", "self", ".", "nn_ready", "=", "False" ]
30.5
0.026596
def _should_recompile(self,e): """Utility routine for edit_syntax_error""" if e.filename in ('<ipython console>','<input>','<string>', '<console>','<BackgroundJob compilation>', None): return False try: if (self.autoed...
[ "def", "_should_recompile", "(", "self", ",", "e", ")", ":", "if", "e", ".", "filename", "in", "(", "'<ipython console>'", ",", "'<input>'", ",", "'<string>'", ",", "'<console>'", ",", "'<BackgroundJob compilation>'", ",", "None", ")", ":", "return", "False", ...
32.137931
0.0125
def _add_future(cls, future): """Adds a future to the list of in-order futures thus far. Args: future: The future to add to the list. """ if cls._local._activated: cls._local._in_order_futures.add(future)
[ "def", "_add_future", "(", "cls", ",", "future", ")", ":", "if", "cls", ".", "_local", ".", "_activated", ":", "cls", ".", "_local", ".", "_in_order_futures", ".", "add", "(", "future", ")" ]
28.25
0.008584
def register(self,obj,cls=type(None),hist={}): """ Takes a FortranObject and adds it to the appropriate list, if not already present. """ #~ ident = getattr(obj,'ident',obj) if is_submodule(obj,cls): if obj not in self.submodules: self.submodules[obj] = Submod...
[ "def", "register", "(", "self", ",", "obj", ",", "cls", "=", "type", "(", "None", ")", ",", "hist", "=", "{", "}", ")", ":", "#~ ident = getattr(obj,'ident',obj)", "if", "is_submodule", "(", "obj", ",", "cls", ")", ":", "if", "obj", "not", "in", "sel...
51.272727
0.030461
def generate_slug(value): """ Generates a slug using a Hashid of `value`. COPIED from spectator.core.models.SluggedModelMixin() because migrations don't make this happen automatically and perhaps the least bad thing is to copy the method here, ugh. """ alphabet = app_settings.SLUG_ALPHABET ...
[ "def", "generate_slug", "(", "value", ")", ":", "alphabet", "=", "app_settings", ".", "SLUG_ALPHABET", "salt", "=", "app_settings", ".", "SLUG_SALT", "hashids", "=", "Hashids", "(", "alphabet", "=", "alphabet", ",", "salt", "=", "salt", ",", "min_length", "=...
31.5
0.002203
def draw(self, y, **kwargs): """ Draws a histogram with the reference value for binning as vertical lines. Parameters ---------- y : an array of one dimension or a pandas Series """ # draw the histogram hist, bin_edges = np.histogram(y, bins=self...
[ "def", "draw", "(", "self", ",", "y", ",", "*", "*", "kwargs", ")", ":", "# draw the histogram", "hist", ",", "bin_edges", "=", "np", ".", "histogram", "(", "y", ",", "bins", "=", "self", ".", "bins", ")", "self", ".", "bin_edges_", "=", "bin_edges",...
33.352941
0.010292
def is_tiff_format(self): """ Checks whether file format is a TIFF image format Example: ``MimeType.TIFF.is_tiff_format()`` or ``MimeType.is_tiff_format(MimeType.TIFF)`` :param self: File format :type self: MimeType :return: ``True`` if file is in image format, ``False`` otherw...
[ "def", "is_tiff_format", "(", "self", ")", ":", "return", "self", "in", "frozenset", "(", "[", "MimeType", ".", "TIFF", ",", "MimeType", ".", "TIFF_d8", ",", "MimeType", ".", "TIFF_d16", ",", "MimeType", ".", "TIFF_d32f", "]", ")" ]
41.181818
0.008639
def confirm(question: str, default: bool = True) -> bool: """ Requests confirmation of the specified question and returns that result :param question: The question to print to the console for the confirmation :param default: The default value if the user hits enter without entering a va...
[ "def", "confirm", "(", "question", ":", "str", ",", "default", ":", "bool", "=", "True", ")", "->", "bool", ":", "result", "=", "input", "(", "'{question} [{yes}/{no}]:'", ".", "format", "(", "question", "=", "question", ",", "yes", "=", "'(Y)'", "if", ...
27.318182
0.001608
def create_value(cls, prop_name, val, model=None): # @NoSelf """This is used to create a value to be assigned to a property. Depending on the type of the value, different values are created and returned. For example, for a list, a ListWrapper is created to wrap it, and returned for the ...
[ "def", "create_value", "(", "cls", ",", "prop_name", ",", "val", ",", "model", "=", "None", ")", ":", "# @NoSelf", "if", "isinstance", "(", "val", ",", "tuple", ")", ":", "# this might be a class instance to be wrapped", "# (thanks to Tobias Weber for", "# providing...
39.173913
0.001083
def featurecreep(): "Generate feature creep (P+C http://www.dack.com/web/bullshit.html)" verb = random.choice(phrases.fcverbs).capitalize() adjective = random.choice(phrases.fcadjectives) noun = random.choice(phrases.fcnouns) return '%s %s %s!' % (verb, adjective, noun)
[ "def", "featurecreep", "(", ")", ":", "verb", "=", "random", ".", "choice", "(", "phrases", ".", "fcverbs", ")", ".", "capitalize", "(", ")", "adjective", "=", "random", ".", "choice", "(", "phrases", ".", "fcadjectives", ")", "noun", "=", "random", "....
45
0.021818
def fasta_motif_scan( fasta_fname, input_tuples, regex_ready=False, allow_overlaps=True, file_buffer=False, molecule='dna' ): """ fasta_fname = string path to FASTA file input_tuples = tuple containing (1) motif sequence, (2) contig name, (3) start position*, (4) end position, (5) strand to search *start is expec...
[ "def", "fasta_motif_scan", "(", "fasta_fname", ",", "input_tuples", ",", "regex_ready", "=", "False", ",", "allow_overlaps", "=", "True", ",", "file_buffer", "=", "False", ",", "molecule", "=", "'dna'", ")", ":", "###################", "# validity checks #", "####...
34.547945
0.062452
def calculate_start_time(df): """Calculate the star_time per read. Time data is either a "time" (in seconds, derived from summary files) or a "timestamp" (in UTC, derived from fastq_rich format) and has to be converted appropriately in a datetime format time_arr For both the time_zero is the m...
[ "def", "calculate_start_time", "(", "df", ")", ":", "if", "\"time\"", "in", "df", ":", "df", "[", "\"time_arr\"", "]", "=", "pd", ".", "Series", "(", "df", "[", "\"time\"", "]", ",", "dtype", "=", "'datetime64[s]'", ")", "elif", "\"timestamp\"", "in", ...
41
0.000851
def elcm_session_list(irmc_info): """send an eLCM request to list all sessions :param irmc_info: node info :returns: dict object of sessions if succeed { 'SessionList': { 'Contains': [ { 'Id': id1, 'Name': name1 }, { 'Id': id2,...
[ "def", "elcm_session_list", "(", "irmc_info", ")", ":", "# Send GET request to the server", "resp", "=", "elcm_request", "(", "irmc_info", ",", "method", "=", "'GET'", ",", "path", "=", "'/sessionInformation/'", ")", "if", "resp", ".", "status_code", "==", "200", ...
30.142857
0.001148
def read_nem_file(file_path: str) -> NEMFile: """ Read in NEM file and return meter readings named tuple :param file_path: The NEM file to process :returns: The file that was created """ _, file_extension = os.path.splitext(file_path) if file_extension.lower() == '.zip': with zipfile.Z...
[ "def", "read_nem_file", "(", "file_path", ":", "str", ")", "->", "NEMFile", ":", "_", ",", "file_extension", "=", "os", ".", "path", ".", "splitext", "(", "file_path", ")", "if", "file_extension", ".", "lower", "(", ")", "==", "'.zip'", ":", "with", "z...
42.1
0.001161
def isSnappedToGrid( self ): """ Returns if both the x and y directions are snapping to the grid. :return <bool> """ shift = QtCore.QCoreApplication.keyboardModifiers() == QtCore.Qt.ShiftModifier return (self._xSnapToGrid and self._ySnapToGrid) or shift
[ "def", "isSnappedToGrid", "(", "self", ")", ":", "shift", "=", "QtCore", ".", "QCoreApplication", ".", "keyboardModifiers", "(", ")", "==", "QtCore", ".", "Qt", ".", "ShiftModifier", "return", "(", "self", ".", "_xSnapToGrid", "and", "self", ".", "_ySnapToGr...
38.375
0.019108
def _build_gene_disease_model( self, gene_id, relation_id, disease_id, variant_label, consequence_predicate=None, consequence_id=None, allelic_requirement=None, pmids=None): """ Builds gene varian...
[ "def", "_build_gene_disease_model", "(", "self", ",", "gene_id", ",", "relation_id", ",", "disease_id", ",", "variant_label", ",", "consequence_predicate", "=", "None", ",", "consequence_id", "=", "None", ",", "allelic_requirement", "=", "None", ",", "pmids", "=",...
36.241935
0.000867
def tolist(self): """produce a list representation of the partition """ return [[x.val for x in theclass.items] for theclass in self.classes]
[ "def", "tolist", "(", "self", ")", ":", "return", "[", "[", "x", ".", "val", "for", "x", "in", "theclass", ".", "items", "]", "for", "theclass", "in", "self", ".", "classes", "]" ]
40.5
0.012121
def operands(self, value): """Set instruction operands. """ if len(value) != 3: raise Exception("Invalid instruction operands : %s" % str(value)) self._operands = value
[ "def", "operands", "(", "self", ",", "value", ")", ":", "if", "len", "(", "value", ")", "!=", "3", ":", "raise", "Exception", "(", "\"Invalid instruction operands : %s\"", "%", "str", "(", "value", ")", ")", "self", ".", "_operands", "=", "value" ]
29.571429
0.00939
def locate(desktop_filename_or_name): '''Locate a .desktop from the standard locations. Find the path to the .desktop file of a given .desktop filename or application name. Standard locations: - ``~/.local/share/applications/`` - ``/usr/share/applications`` Args: desktop_filename_or_name (str): Either the ...
[ "def", "locate", "(", "desktop_filename_or_name", ")", ":", "paths", "=", "[", "os", ".", "path", ".", "expanduser", "(", "'~/.local/share/applications'", ")", ",", "'/usr/share/applications'", "]", "result", "=", "[", "]", "for", "path", "in", "paths", ":", ...
27.478261
0.030558
def probConn (self, preCellsTags, postCellsTags, connParam): from .. import sim ''' Generates connections between all pre and post-syn cells based on probability values''' if sim.cfg.verbose: print('Generating set of probabilistic connections (rule: %s) ...' % (connParam['label'])) allRands = self.gen...
[ "def", "probConn", "(", "self", ",", "preCellsTags", ",", "postCellsTags", ",", "connParam", ")", ":", "from", ".", ".", "import", "sim", "if", "sim", ".", "cfg", ".", "verbose", ":", "print", "(", "'Generating set of probabilistic connections (rule: %s) ...'", ...
76.020408
0.012457
def remove_from_bin(self, name): """ Remove an object from the bin folder. """ self.__remove_path(os.path.join(self.root_dir, "bin", name))
[ "def", "remove_from_bin", "(", "self", ",", "name", ")", ":", "self", ".", "__remove_path", "(", "os", ".", "path", ".", "join", "(", "self", ".", "root_dir", ",", "\"bin\"", ",", "name", ")", ")" ]
51
0.012903
def get_transformed_feature_indices(features, stats): """Returns information about the transformed features. Returns: List in the from [(transformed_feature_name, {size: int, index_start: int})] """ feature_indices = [] index_start = 1 for name, transform in sorted(six.iteritems(features)): tr...
[ "def", "get_transformed_feature_indices", "(", "features", ",", "stats", ")", ":", "feature_indices", "=", "[", "]", "index_start", "=", "1", "for", "name", ",", "transform", "in", "sorted", "(", "six", ".", "iteritems", "(", "features", ")", ")", ":", "tr...
33.5
0.010638
def exit_config_mode(self, exit_config="exit", pattern=""): """Exit config_mode.""" if not pattern: pattern = re.escape(self.base_prompt) return super(CiscoWlcSSH, self).exit_config_mode(exit_config, pattern)
[ "def", "exit_config_mode", "(", "self", ",", "exit_config", "=", "\"exit\"", ",", "pattern", "=", "\"\"", ")", ":", "if", "not", "pattern", ":", "pattern", "=", "re", ".", "escape", "(", "self", ".", "base_prompt", ")", "return", "super", "(", "CiscoWlcS...
48
0.008197
def reset(self): """ Recursively resets values of all items contained in this section and its subsections to their default values. """ for _, item in self.iter_items(recursive=True): item.reset()
[ "def", "reset", "(", "self", ")", ":", "for", "_", ",", "item", "in", "self", ".", "iter_items", "(", "recursive", "=", "True", ")", ":", "item", ".", "reset", "(", ")" ]
34.428571
0.008097
def updateObjectFromXML(xml_doc, obj, mapping): """ Handle updating an object. Based on XML input. """ nsmap = None if isinstance(mapping, dict): # The special key @namespaces is used to pass # namespaces and prefix mappings for xpath selectors. # e.g. {'x': 'http://example....
[ "def", "updateObjectFromXML", "(", "xml_doc", ",", "obj", ",", "mapping", ")", ":", "nsmap", "=", "None", "if", "isinstance", "(", "mapping", ",", "dict", ")", ":", "# The special key @namespaces is used to pass", "# namespaces and prefix mappings for xpath selectors.", ...
39.880952
0.000583
def get_argument_parser(): """Create the argument parser for the script. Parameters ---------- Returns ------- `argparse.ArgumentParser` The arguemnt parser. """ desc = 'Generate a sample sheet based on a GEO series matrix.' parser = cli.get_argument_parser(desc=desc) ...
[ "def", "get_argument_parser", "(", ")", ":", "desc", "=", "'Generate a sample sheet based on a GEO series matrix.'", "parser", "=", "cli", ".", "get_argument_parser", "(", "desc", "=", "desc", ")", "g", "=", "parser", ".", "add_argument_group", "(", "'Input and output...
24.805556
0.001078
def displayMakewcsWarningBox(display=True, parent=None): """ Displays a warning box for the 'makewcs' parameter. """ if sys.version_info[0] >= 3: from tkinter.messagebox import showwarning else: from tkMessageBox import showwarning ans = {'yes':True,'no':False} if ans[display]: ...
[ "def", "displayMakewcsWarningBox", "(", "display", "=", "True", ",", "parent", "=", "None", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "from", "tkinter", ".", "messagebox", "import", "showwarning", "else", ":", "from", "tk...
39.066667
0.013333
def connect(self): """Connect to device.""" return self.loop.create_connection(lambda: self, self.host, self.port)
[ "def", "connect", "(", "self", ")", ":", "return", "self", ".", "loop", ".", "create_connection", "(", "lambda", ":", "self", ",", "self", ".", "host", ",", "self", ".", "port", ")" ]
42.666667
0.015385
def parse(readDataInstance, nEntries): """ Returns a new L{ImageImportDescriptor} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{ImageImportDescriptor} object. @type nEntries: int ...
[ "def", "parse", "(", "readDataInstance", ",", "nEntries", ")", ":", "importEntries", "=", "ImageImportDescriptor", "(", ")", "dataLength", "=", "len", "(", "readDataInstance", ")", "toRead", "=", "nEntries", "*", "consts", ".", "SIZEOF_IMAGE_IMPORT_ENTRY32", "if",...
40.074074
0.009928
def fromdelta(args): """ %prog fromdelta deltafile Convert deltafile to coordsfile. """ p = OptionParser(fromdelta.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) deltafile, = args coordsfile = deltafile.rsplit(".", 1)[0] + ".coords...
[ "def", "fromdelta", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "fromdelta", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "("...
22.833333
0.002336
def u_base(self, theta, phi, lam, q): """Apply U to q.""" return self.append(UBase(theta, phi, lam), [q], [])
[ "def", "u_base", "(", "self", ",", "theta", ",", "phi", ",", "lam", ",", "q", ")", ":", "return", "self", ".", "append", "(", "UBase", "(", "theta", ",", "phi", ",", "lam", ")", ",", "[", "q", "]", ",", "[", "]", ")" ]
38.333333
0.008547
def build_from_yamlfile(yamlfile): """ Build a list of components from a yaml file """ d = yaml.load(open(yamlfile)) return MktimeFilterDict(d['aliases'], d['selections'])
[ "def", "build_from_yamlfile", "(", "yamlfile", ")", ":", "d", "=", "yaml", ".", "load", "(", "open", "(", "yamlfile", ")", ")", "return", "MktimeFilterDict", "(", "d", "[", "'aliases'", "]", ",", "d", "[", "'selections'", "]", ")" ]
39.8
0.009852
def onset_strength(y=None, sr=22050, S=None, lag=1, max_size=1, ref=None, detrend=False, center=True, feature=None, aggregate=None, centering=None, **kwargs): """Compute a spectral flux onset strength envelope. Onset...
[ "def", "onset_strength", "(", "y", "=", "None", ",", "sr", "=", "22050", ",", "S", "=", "None", ",", "lag", "=", "1", ",", "max_size", "=", "1", ",", "ref", "=", "None", ",", "detrend", "=", "False", ",", "center", "=", "True", ",", "feature", ...
31.536913
0.000619
def set_color_temp(self, color_temp): """Set device color.""" if self._json_state['control_url']: url = CONST.INTEGRATIONS_URL + self._device_uuid color_data = { 'action': 'setcolortemperature', 'colorTemperature': int(color_temp) } ...
[ "def", "set_color_temp", "(", "self", ",", "color_temp", ")", ":", "if", "self", ".", "_json_state", "[", "'control_url'", "]", ":", "url", "=", "CONST", ".", "INTEGRATIONS_URL", "+", "self", ".", "_device_uuid", "color_data", "=", "{", "'action'", ":", "'...
36.1875
0.001682
def add_command_line_options_optparse(cls, optparser): """function to inject command line parameters into a Python OptionParser.""" def set_parameter(option, opt, value, parser): """callback function for OptionParser""" cls.config[opt] = value if opt == "--st...
[ "def", "add_command_line_options_optparse", "(", "cls", ",", "optparser", ")", ":", "def", "set_parameter", "(", "option", ",", "opt", ",", "value", ",", "parser", ")", ":", "\"\"\"callback function for OptionParser\"\"\"", "cls", ".", "config", "[", "opt", "]", ...
32.428571
0.001283
def operate_and_get_next(event): """ Accept the current line for execution and fetch the next line relative to the current line from the history for editing. """ buff = event.current_buffer new_index = buff.working_index + 1 # Accept the current input. (This will also redraw the interface i...
[ "def", "operate_and_get_next", "(", "event", ")", ":", "buff", "=", "event", ".", "current_buffer", "new_index", "=", "buff", ".", "working_index", "+", "1", "# Accept the current input. (This will also redraw the interface in the", "# 'done' state.)", "buff", ".", "accep...
34.666667
0.00156
def cut(self): """ Cuts the text from the serial to the clipboard. """ text = self.selectedText() for editor in self.editors(): editor.cut() QtGui.QApplication.clipboard().setText(text)
[ "def", "cut", "(", "self", ")", ":", "text", "=", "self", ".", "selectedText", "(", ")", "for", "editor", "in", "self", ".", "editors", "(", ")", ":", "editor", ".", "cut", "(", ")", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", ...
28.222222
0.01145
def gffselect(args): """ %prog gffselect gmaplocation.bed expectedlocation.bed translated.ids tag Try to match up the expected location and gmap locations for particular genes. translated.ids was generated by fasta.translate --ids. tag must be one of "complete|pseudogene|partial". """ from ...
[ "def", "gffselect", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "bed", "import", "intersectBed_wao", "p", "=", "OptionParser", "(", "gffselect", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "i...
30.170732
0.002349
def on_yaml_imported(self, yaml): """ The `pyyaml <https://pypi.org/project/pyyaml/>`_ import hook. :param module yaml: The ``yaml`` module """ def represent_ordereddict(dumper, data): """ A custom data representer for ``OrderedDict`` instances. .. note:: Credi...
[ "def", "on_yaml_imported", "(", "self", ",", "yaml", ")", ":", "def", "represent_ordereddict", "(", "dumper", ",", "data", ")", ":", "\"\"\" A custom data representer for ``OrderedDict`` instances.\n\n .. note:: Credit to https://stackoverflow.com/a/16782282/7828560.\n\n ...
36.28
0.002148
def create_v4flowspec_actions(actions=None): """ Create list of traffic filtering actions for Ipv4 Flow Specification and VPNv4 Flow Specification. `` actions`` specifies Traffic Filtering Actions of Flow Specification as a dictionary type value. Returns a list of extended community values. ...
[ "def", "create_v4flowspec_actions", "(", "actions", "=", "None", ")", ":", "from", "ryu", ".", "services", ".", "protocols", ".", "bgp", ".", "api", ".", "prefix", "import", "(", "FLOWSPEC_ACTION_TRAFFIC_RATE", ",", "FLOWSPEC_ACTION_TRAFFIC_ACTION", ",", "FLOWSPEC...
35.730769
0.001048
def string_pieces(s, maxlen=1024): """ Takes a (unicode) string and yields pieces of it that are at most `maxlen` characters, trying to break it at punctuation/whitespace. This is an important step before using a tokenizer with a maximum buffer size. """ if not s: return i = 0 wh...
[ "def", "string_pieces", "(", "s", ",", "maxlen", "=", "1024", ")", ":", "if", "not", "s", ":", "return", "i", "=", "0", "while", "True", ":", "j", "=", "i", "+", "maxlen", "if", "j", ">=", "len", "(", "s", ")", ":", "yield", "s", "[", "i", ...
31.304348
0.001348
def _start_claim_channels(self, grpc_channel, channels_ids): """ Safely run StartClaim for given channels """ unclaimed_payments = self._call_GetListUnclaimed(grpc_channel) unclaimed_payments_dict = {p["channel_id"] : p for p in unclaimed_payments} to_claim = [] for channel_id i...
[ "def", "_start_claim_channels", "(", "self", ",", "grpc_channel", ",", "channels_ids", ")", ":", "unclaimed_payments", "=", "self", ".", "_call_GetListUnclaimed", "(", "grpc_channel", ")", "unclaimed_payments_dict", "=", "{", "p", "[", "\"channel_id\"", "]", ":", ...
59.833333
0.010055
def stop_processes(self): """Iterate through all of the consumer processes shutting them down.""" self.set_state(self.STATE_SHUTTING_DOWN) LOGGER.info('Stopping consumer processes') signal.signal(signal.SIGABRT, signal.SIG_IGN) signal.signal(signal.SIGALRM, signal.SIG_IGN) ...
[ "def", "stop_processes", "(", "self", ")", ":", "self", ".", "set_state", "(", "self", ".", "STATE_SHUTTING_DOWN", ")", "LOGGER", ".", "info", "(", "'Stopping consumer processes'", ")", "signal", ".", "signal", "(", "signal", ".", "SIGABRT", ",", "signal", "...
37.421053
0.001371
def _activate_logger(cls, logger_name, simple_name, detail_level, handler, connection, propagate): """ Configure the specified logger, and activate logging and set detail level for connections. The specified logger is always a single pywbem logger; the simple ...
[ "def", "_activate_logger", "(", "cls", ",", "logger_name", ",", "simple_name", ",", "detail_level", ",", "handler", ",", "connection", ",", "propagate", ")", ":", "if", "handler", "is", "not", "None", ":", "assert", "isinstance", "(", "handler", ",", "loggin...
43.625
0.000841
def enbw(wnd): """ Equivalent Noise Bandwidth in bins (Processing Gain reciprocal). """ return sum(el ** 2 for el in wnd) / sum(wnd) ** 2 * len(wnd)
[ "def", "enbw", "(", "wnd", ")", ":", "return", "sum", "(", "el", "**", "2", "for", "el", "in", "wnd", ")", "/", "sum", "(", "wnd", ")", "**", "2", "*", "len", "(", "wnd", ")" ]
50
0.019737
def fetch_items(self, category, **kwargs): """Fetch the messages :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] latest = kwargs['latest'] logger.info("F...
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "latest", "=", "kwargs", "[", "'latest'", "]", "logger", ".", "info", "(", "\"Fetching messages of '%s' channel from %s\...
33.213115
0.001438
def _fetch_page_async(self, page_size, **q_options): """Internal version of fetch_page_async().""" q_options.setdefault('batch_size', page_size) q_options.setdefault('produce_cursors', True) it = self.iter(limit=page_size + 1, **q_options) results = [] while (yield it.has_next_async()): re...
[ "def", "_fetch_page_async", "(", "self", ",", "page_size", ",", "*", "*", "q_options", ")", ":", "q_options", ".", "setdefault", "(", "'batch_size'", ",", "page_size", ")", "q_options", ".", "setdefault", "(", "'produce_cursors'", ",", "True", ")", "it", "="...
36.933333
0.008803
def mouseMoveEvent(self, event): """ Handle the mouse move event for a drag operation. """ self.declaration.mouse_move_event(event) super(QtGraphicsView, self).mouseMoveEvent(event)
[ "def", "mouseMoveEvent", "(", "self", ",", "event", ")", ":", "self", ".", "declaration", ".", "mouse_move_event", "(", "event", ")", "super", "(", "QtGraphicsView", ",", "self", ")", ".", "mouseMoveEvent", "(", "event", ")" ]
34.833333
0.009346
def coda(df, window, level): """ CODA processing from Windig, Phalp, & Payne 1996 Anal Chem """ # pull out the data d = df.values # smooth the data and standardize it smooth_data = movingaverage(d, df.index, window)[0] stand_data = (smooth_data - smooth_data.mean()) / smooth_data.std() ...
[ "def", "coda", "(", "df", ",", "window", ",", "level", ")", ":", "# pull out the data", "d", "=", "df", ".", "values", "# smooth the data and standardize it", "smooth_data", "=", "movingaverage", "(", "d", ",", "df", ".", "index", ",", "window", ")", "[", ...
33.5
0.001451
def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node)
[ "def", "start_write", "(", "self", ",", "frame", ",", "node", "=", "None", ")", ":", "if", "frame", ".", "buffer", "is", "None", ":", "self", ".", "writeline", "(", "'yield '", ",", "node", ")", "else", ":", "self", ".", "writeline", "(", "'%s.append...
39.833333
0.008197
def getDXGIOutputInfo(self): """ [D3D10/11 Only] Returns the adapter index and output index that the user should pass into EnumAdapters and EnumOutputs to create the device and swap chain in DX10 and DX11. If an error occurs both indices will be set to -1. """ fn = self....
[ "def", "getDXGIOutputInfo", "(", "self", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getDXGIOutputInfo", "pnAdapterIndex", "=", "c_int32", "(", ")", "fn", "(", "byref", "(", "pnAdapterIndex", ")", ")", "return", "pnAdapterIndex", ".", "value" ]
40.636364
0.008753
def mtf_unitransformer_all_layers_tiny(): """Test out all the layers on local CPU.""" hparams = mtf_unitransformer_tiny() hparams.moe_num_experts = 4 hparams.moe_expert_x = 4 hparams.moe_expert_y = 4 hparams.moe_hidden_size = 512 hparams.layers = ["self_att", "local_self_att", "moe_1d", "moe_2d", "drd"] ...
[ "def", "mtf_unitransformer_all_layers_tiny", "(", ")", ":", "hparams", "=", "mtf_unitransformer_tiny", "(", ")", "hparams", ".", "moe_num_experts", "=", "4", "hparams", ".", "moe_expert_x", "=", "4", "hparams", ".", "moe_expert_y", "=", "4", "hparams", ".", "moe...
36.333333
0.026866
def send_request(self, send_function=None): """ Sends the assembled request on the child object. @type send_function: function reference @keyword send_function: A function reference (passed without the parenthesis) to a function that will send the request. This al...
[ "def", "send_request", "(", "self", ",", "send_function", "=", "None", ")", ":", "# Send the request and get the response back.", "try", ":", "# If the user has overridden the send function, use theirs", "# instead of the default.", "if", "send_function", ":", "# Follow the overr...
44.853659
0.001064
def add(ctx, secret, name, issuer, period, oath_type, digits, touch, algorithm, counter, force): """ Add a new credential. This will add a new credential to your YubiKey. """ oath_type = OATH_TYPE[oath_type] algorithm = ALGO[algorithm] digits = int(digits) if not secret: ...
[ "def", "add", "(", "ctx", ",", "secret", ",", "name", ",", "issuer", ",", "period", ",", "oath_type", ",", "digits", ",", "touch", ",", "algorithm", ",", "counter", ",", "force", ")", ":", "oath_type", "=", "OATH_TYPE", "[", "oath_type", "]", "algorith...
28.64
0.001351
def output_paas(gandi, paas, datacenters, vhosts, output_keys, justify=11): """ Helper to output a paas information.""" output_generic(gandi, paas, output_keys, justify) if 'sftp_server' in output_keys: output_line(gandi, 'sftp_server', paas['ftp_server'], justify) if 'vhost' in output_keys: ...
[ "def", "output_paas", "(", "gandi", ",", "paas", ",", "datacenters", ",", "vhosts", ",", "output_keys", ",", "justify", "=", "11", ")", ":", "output_generic", "(", "gandi", ",", "paas", ",", "output_keys", ",", "justify", ")", "if", "'sftp_server'", "in", ...
37.162162
0.000709
def plot_cylinder(ax, start, end, start_radius, end_radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT): '''plot a 3d cylinder''' assert not np.all(start == end), 'Cylinder must have length' x, y, z = generate_cylindrical_points(start, end, start_radius, end_radius, ...
[ "def", "plot_cylinder", "(", "ax", ",", "start", ",", "end", ",", "start_radius", ",", "end_radius", ",", "color", "=", "'black'", ",", "alpha", "=", "1.", ",", "linspace_count", "=", "_LINSPACE_COUNT", ")", ":", "assert", "not", "np", ".", "all", "(", ...
61.571429
0.002288
def is_authenticode_signed(filename): """Returns True if the file is signed with authenticode""" with open(filename, 'rb') as fp: fp.seek(0) magic = fp.read(2) if magic != b'MZ': return False # First grab the pointer to the coff_header, which is at offset 60 ...
[ "def", "is_authenticode_signed", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fp", ":", "fp", ".", "seek", "(", "0", ")", "magic", "=", "fp", ".", "read", "(", "2", ")", "if", "magic", "!=", "b'MZ'", ":", "...
32
0.000583
def padded_variance_explained(predictions, labels, weights_fn=common_layers.weights_all): """Explained variance, also known as R^2.""" predictions, labels = common_layers.pad_with_zeros(predictions, labels) targets = labels weights = weights_fn(targets...
[ "def", "padded_variance_explained", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "common_layers", ".", "weights_all", ")", ":", "predictions", ",", "labels", "=", "common_layers", ".", "pad_with_zeros", "(", "predictions", ",", "labels", ")", "target...
42.307692
0.017794
def parseExtensionArgs(self, ax_args): """Parse attribute exchange key/value arguments into this object. @param ax_args: The attribute exchange fetch_response arguments, with namespacing removed. @type ax_args: {unicode:unicode} @returns: None @raises Value...
[ "def", "parseExtensionArgs", "(", "self", ",", "ax_args", ")", ":", "self", ".", "_checkMode", "(", "ax_args", ")", "aliases", "=", "NamespaceMap", "(", ")", "for", "key", ",", "value", "in", "ax_args", ".", "iteritems", "(", ")", ":", "if", "key", "."...
30.652174
0.001375
def citation_director(**kwargs): """Direct the citation elements based on their qualifier.""" qualifier = kwargs.get('qualifier', '') content = kwargs.get('content', '') if qualifier == 'publicationTitle': return CitationJournalTitle(content=content) elif qualifier == 'volume': retur...
[ "def", "citation_director", "(", "*", "*", "kwargs", ")", ":", "qualifier", "=", "kwargs", ".", "get", "(", "'qualifier'", ",", "''", ")", "content", "=", "kwargs", ".", "get", "(", "'content'", ",", "''", ")", "if", "qualifier", "==", "'publicationTitle...
38.25
0.001595
def split(self, data): """ Split data into list of string, each (self.width() - 1) length or less. If nul-length string specified then empty list is returned :param data: data to split :return: list of str """ line = deepcopy(data) line_width = (self.width() - 1) lines = [] while len(line): new_...
[ "def", "split", "(", "self", ",", "data", ")", ":", "line", "=", "deepcopy", "(", "data", ")", "line_width", "=", "(", "self", ".", "width", "(", ")", "-", "1", ")", "lines", "=", "[", "]", "while", "len", "(", "line", ")", ":", "new_line", "="...
21.48
0.037433
def createEllipse(self, cx, cy, rx, ry, strokewidth=1, stroke='black', fill='none'): """ Creates an ellipse @type cx: string or int @param cx: starting x-coordinate @type cy: string or int @param cy: starting y-coordinate @type rx: string or int @p...
[ "def", "createEllipse", "(", "self", ",", "cx", ",", "cy", ",", "rx", ",", "ry", ",", "strokewidth", "=", "1", ",", "stroke", "=", "'black'", ",", "fill", "=", "'none'", ")", ":", "style_dict", "=", "{", "'fill'", ":", "fill", ",", "'stroke-width'", ...
46.5
0.010536
def abstract(class_): """Mark the class as _abstract_ base class, forbidding its instantiation. .. note:: Unlike other modifiers, ``@abstract`` can be applied to all Python classes, not just subclasses of :class:`Object`. .. versionadded:: 0.0.3 """ if not inspect.isclass(class_):...
[ "def", "abstract", "(", "class_", ")", ":", "if", "not", "inspect", ".", "isclass", "(", "class_", ")", ":", "raise", "TypeError", "(", "\"@abstract can only be applied to classes\"", ")", "abc_meta", "=", "None", "# if the class is not already using a metaclass specifi...
37.193548
0.001691
def log_loss(targets, predictions, index_map=None): r""" Compute the logloss for the given targets and the given predicted probabilities. This quantity is defined to be the negative of the sum of the log probability of each observation, normalized by the number of observations: .. math:: ...
[ "def", "log_loss", "(", "targets", ",", "predictions", ",", "index_map", "=", "None", ")", ":", "_supervised_evaluation_error_checking", "(", "targets", ",", "predictions", ")", "_check_prob_and_prob_vector", "(", "predictions", ")", "_check_target_not_float", "(", "t...
37.943396
0.001131
def cmd_arp_poison(victim1, victim2, iface, verbose): """Send ARP 'is-at' packets to each victim, poisoning their ARP tables for send the traffic to your system. Note: If you want a full working Man In The Middle attack, you need to enable the packet forwarding on your operating system to act like a ...
[ "def", "cmd_arp_poison", "(", "victim1", ",", "victim2", ",", "iface", ",", "verbose", ")", ":", "conf", ".", "verb", "=", "False", "if", "iface", ":", "conf", ".", "iface", "=", "iface", "mac1", "=", "getmacbyip", "(", "victim1", ")", "mac2", "=", "...
26.106383
0.002357
def direct_messages(self, since_id=None, max_id=None, count=None, include_entities=None, skip_status=None): """ Gets the 20 most recent direct messages received by the authenticating user. https://dev.twitter.com/docs/api/1.1/get/direct_messages :param s...
[ "def", "direct_messages", "(", "self", ",", "since_id", "=", "None", ",", "max_id", "=", "None", ",", "count", "=", "None", ",", "include_entities", "=", "None", ",", "skip_status", "=", "None", ")", ":", "params", "=", "{", "}", "set_str_param", "(", ...
42.428571
0.001646
def runserver(app=None, reloader=None, debug=None, host=None, port=None): """Run the Flask development server i.e. app.run()""" debug = debug or app.config.get('DEBUG', False) reloader = reloader or app.config.get('RELOADER', False) host = host or app.config.get('HOST', '127.0.0.1') port = port or a...
[ "def", "runserver", "(", "app", "=", "None", ",", "reloader", "=", "None", ",", "debug", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ")", ":", "debug", "=", "debug", "or", "app", ".", "config", ".", "get", "(", "'DEBUG'", ","...
37
0.002198
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title self.set_title( ...
[ "def", "finalize", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Set the title", "self", ".", "set_title", "(", "'Parallel Coordinates for {} Features'", ".", "format", "(", "len", "(", "self", ".", "features_", ")", ")", ")", "# Add the vertical lines", ...
31.878788
0.001845
def find_lemma(self, verb): """ Returns the base form of the given inflected verb, using a rule-based approach. """ v = verb.lower() # Common prefixes: be-finden and emp-finden probably inflect like finden. if not (v.startswith("ge") and v.endswith("t")): # Probably gerund. ...
[ "def", "find_lemma", "(", "self", ",", "verb", ")", ":", "v", "=", "verb", ".", "lower", "(", ")", "# Common prefixes: be-finden and emp-finden probably inflect like finden.", "if", "not", "(", "v", ".", "startswith", "(", "\"ge\"", ")", "and", "v", ".", "ends...
48.857143
0.013378
def Gooey(f=None, advanced=True, language='english', auto_start=False, # TODO: add this to the docs. Used to be `show_config=True` target=None, program_name=None, program_description=None, default_size=(610, 530), use_legacy_titles...
[ "def", "Gooey", "(", "f", "=", "None", ",", "advanced", "=", "True", ",", "language", "=", "'english'", ",", "auto_start", "=", "False", ",", "# TODO: add this to the docs. Used to be `show_config=True`\r", "target", "=", "None", ",", "program_name", "=", "None", ...
32.230769
0.010035
def processes(self): """The proccesses for this app.""" return self._h._get_resources( resource=('apps', self.name, 'ps'), obj=Process, app=self, map=ProcessListResource )
[ "def", "processes", "(", "self", ")", ":", "return", "self", ".", "_h", ".", "_get_resources", "(", "resource", "=", "(", "'apps'", ",", "self", ".", "name", ",", "'ps'", ")", ",", "obj", "=", "Process", ",", "app", "=", "self", ",", "map", "=", ...
35.666667
0.009132
def save_graph_only_from_checkpoint(input_checkpoint, output_file_path, output_node_names, as_text=False): """Save a small version of the graph based on a checkpoint and the output node names.""" check_input_checkpoint(input_checkpoint) output_node_names = output_node_names_string_as_list(output_node_names...
[ "def", "save_graph_only_from_checkpoint", "(", "input_checkpoint", ",", "output_file_path", ",", "output_node_names", ",", "as_text", "=", "False", ")", ":", "check_input_checkpoint", "(", "input_checkpoint", ")", "output_node_names", "=", "output_node_names_string_as_list", ...
53.888889
0.008114
def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in c...
[ "def", "rebuild_proxies", "(", "self", ",", "prepared_request", ",", "proxies", ")", ":", "proxies", "=", "proxies", "if", "proxies", "is", "not", "None", "else", "{", "}", "headers", "=", "prepared_request", ".", "headers", "url", "=", "prepared_request", "...
36.3
0.002012
def _to_ascii(s): """ Converts given string to ascii ignoring non ascii. Args: s (text or binary): Returns: str: """ # TODO: Always use unicode within ambry. from six import text_type, binary_type if isinstance(s, text_type): ascii_ = s.encode('ascii', 'ignore') ...
[ "def", "_to_ascii", "(", "s", ")", ":", "# TODO: Always use unicode within ambry.", "from", "six", "import", "text_type", ",", "binary_type", "if", "isinstance", "(", "s", ",", "text_type", ")", ":", "ascii_", "=", "s", ".", "encode", "(", "'ascii'", ",", "'...
28.882353
0.001972
def _get_I(self, a, b, size, plus_transpose=True): """Return I matrix in Chaput's PRL paper. None is returned if I is zero matrix. """ r_sum = np.zeros((3, 3), dtype='double', order='C') for r in self._rotations_cartesian: for i in range(3): for j in...
[ "def", "_get_I", "(", "self", ",", "a", ",", "b", ",", "size", ",", "plus_transpose", "=", "True", ")", ":", "r_sum", "=", "np", ".", "zeros", "(", "(", "3", ",", "3", ")", ",", "dtype", "=", "'double'", ",", "order", "=", "'C'", ")", "for", ...
35.4
0.0022
def revoke_access_token(credential): """Revoke an access token. All future requests with the access token will be invalid. Parameters credential (OAuth2Credential) An authorized user's OAuth 2.0 credentials. Raises ClientError (APIError) Thrown if there was an HTT...
[ "def", "revoke_access_token", "(", "credential", ")", ":", "url", "=", "build_url", "(", "auth", ".", "SERVER_HOST", ",", "auth", ".", "REVOKE_PATH", ")", "args", "=", "{", "'token'", ":", "credential", ".", "access_token", ",", "}", "response", "=", "post...
27.916667
0.001443
def setSample(self, sample): """Set sample points from the population. Should be a RDD""" if not isinstance(sample, RDD): raise TypeError("samples should be a RDD, received %s" % type(sample)) self._sample = sample
[ "def", "setSample", "(", "self", ",", "sample", ")", ":", "if", "not", "isinstance", "(", "sample", ",", "RDD", ")", ":", "raise", "TypeError", "(", "\"samples should be a RDD, received %s\"", "%", "type", "(", "sample", ")", ")", "self", ".", "_sample", "...
49.2
0.012
def add_cli_clear_bel_namespace(main: click.Group) -> click.Group: # noqa: D202 """Add a ``clear_bel_namespace`` command to main :mod:`click` function.""" @main.command() @click.pass_obj def drop(manager: BELNamespaceManagerMixin): """Clear names/identifiers to terminology store.""" na...
[ "def", "add_cli_clear_bel_namespace", "(", "main", ":", "click", ".", "Group", ")", "->", "click", ".", "Group", ":", "# noqa: D202", "@", "main", ".", "command", "(", ")", "@", "click", ".", "pass_obj", "def", "drop", "(", "manager", ":", "BELNamespaceMan...
34.384615
0.002179
def GaussianBlur(X, ksize_width, ksize_height, sigma_x, sigma_y): """Apply Gaussian blur to the given data. Args: X: data to blur kernel_size: Gaussian kernel size stddev: Gaussian kernel standard deviation (in both X and Y directions) """ return image_transform( X, ...
[ "def", "GaussianBlur", "(", "X", ",", "ksize_width", ",", "ksize_height", ",", "sigma_x", ",", "sigma_y", ")", ":", "return", "image_transform", "(", "X", ",", "cv2", ".", "GaussianBlur", ",", "ksize", "=", "(", "ksize_width", ",", "ksize_height", ")", ","...
28.2
0.002288
def getReceivers( sender = Any, signal = Any ): """Get list of receivers from global tables This utility function allows you to retrieve the raw list of receivers from the connections table for the given sender and signal pair. Note: there is no guarantee that this is the actual list ...
[ "def", "getReceivers", "(", "sender", "=", "Any", ",", "signal", "=", "Any", ")", ":", "try", ":", "return", "connections", "[", "id", "(", "sender", ")", "]", "[", "signal", "]", "except", "KeyError", ":", "return", "[", "]" ]
33.227273
0.009309
def prune(self): """ Remove anything which shouldn't be displayed. """ self.boundprocs = [ obj for obj in self.boundprocs if obj.permission in self.display ] self.variables = [ obj for obj in self.variables if obj.permission in self.display ] for obj in self.boundprocs + ...
[ "def", "prune", "(", "self", ")", ":", "self", ".", "boundprocs", "=", "[", "obj", "for", "obj", "in", "self", ".", "boundprocs", "if", "obj", ".", "permission", "in", "self", ".", "display", "]", "self", ".", "variables", "=", "[", "obj", "for", "...
44.875
0.021858
def append_row(self, index, value): """ Appends a row of value to the end of the data. Be very careful with this function as for sorted Series it will not enforce sort order. Use this only for speed when needed, be careful. :param index: index :param value: value :retur...
[ "def", "append_row", "(", "self", ",", "index", ",", "value", ")", ":", "if", "index", "in", "self", ".", "_index", ":", "raise", "IndexError", "(", "'index already in Series'", ")", "self", ".", "_index", ".", "append", "(", "index", ")", "self", ".", ...
34.714286
0.01002
def availableRoles(self): ''' Some instructors only offer private lessons for certain roles, so we should only allow booking for the roles that have been selected for the instructor. ''' if not hasattr(self.instructor,'instructorprivatelessondetails'): return [] ...
[ "def", "availableRoles", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ".", "instructor", ",", "'instructorprivatelessondetails'", ")", ":", "return", "[", "]", "return", "[", "[", "x", ".", "id", ",", "x", ".", "name", "]", "for", "x", ...
39.727273
0.011186
def _update_config(self,directory,filename): """Manages FB config files""" basefilename=os.path.splitext(filename)[0] ext=os.path.splitext(filename)[1].lower() #if filename==LOCATION_FILE: #return self._update_config_location(directory) #FIXME #elif filename==...
[ "def", "_update_config", "(", "self", ",", "directory", ",", "filename", ")", ":", "basefilename", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "["...
45.3
0.024865
def search_maintenance_window_for_facets(self, **kwargs): # noqa: E501 """Lists the values of one or more facets over the customer's maintenance windows # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pa...
[ "def", "search_maintenance_window_for_facets", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "search...
47.904762
0.001949
def to_bytes(s, encoding=None, errors='strict'): """Returns a bytestring version of 's', encoded as specified in 'encoding'.""" encoding = encoding or 'utf-8' if isinstance(s, bytes): if encoding != 'utf-8': return s.decode('utf-8', errors).encode(encoding, errors) else: ...
[ "def", "to_bytes", "(", "s", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "encoding", "=", "encoding", "or", "'utf-8'", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "if", "encoding", "!=", "'utf-8'", ":", "return", ...
35.166667
0.002309
def evaluate(self, num_eval_batches=None): """Run one round of evaluation, return loss and accuracy.""" num_eval_batches = num_eval_batches or self.num_eval_batches with tf.Graph().as_default() as graph: self.tensors = self.model.build_eval_graph(self.eval_data_paths, ...
[ "def", "evaluate", "(", "self", ",", "num_eval_batches", "=", "None", ")", ":", "num_eval_batches", "=", "num_eval_batches", "or", "self", ".", "num_eval_batches", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", "as", "graph", ":", "self...
40.756757
0.009715
def add(i): """ Input: { (repo_uoa) - repo UOA module_uoa - module UOA data_uoa - data UOA (data_uid) - data UID (if uoa is an alias) (data_name) - user friendly data name ...
[ "def", "add", "(", "i", ")", ":", "o", "=", "i", ".", "get", "(", "'out'", ",", "''", ")", "t", "=", "'added'", "ra", "=", "i", ".", "get", "(", "'repo_uoa'", ",", "''", ")", "m", "=", "i", ".", "get", "(", "'module_uoa'", ",", "''", ")", ...
28.589812
0.040594
def new_space_from_excel( self, book, range_, sheet=None, name=None, names_row=None, param_cols=None, space_param_order=None, cells_param_order=None, transpose=False, names_col=None, param_rows=None, ): """Create...
[ "def", "new_space_from_excel", "(", "self", ",", "book", ",", "range_", ",", "sheet", "=", "None", ",", "name", "=", "None", ",", "names_row", "=", "None", ",", "param_cols", "=", "None", ",", "space_param_order", "=", "None", ",", "cells_param_order", "="...
41.040541
0.000965
def showOperandLines(rh): """ Produce help output related to operands. Input: Request Handle """ if rh.function == 'HELP': rh.printLn("N", " For the ChangeVM function:") else: rh.printLn("N", "Sub-Functions(s):") rh.printLn("N", " add3390 - Add a 3390 (EC...
[ "def", "showOperandLines", "(", "rh", ")", ":", "if", "rh", ".", "function", "==", "'HELP'", ":", "rh", ".", "printLn", "(", "\"N\"", ",", "\" For the ChangeVM function:\"", ")", "else", ":", "rh", ".", "printLn", "(", "\"N\"", ",", "\"Sub-Functions(s):\"",...
52.717949
0.000637
def smooth_gaps(self,min_intron): """any gaps smaller than min_intron are joined, andreturns a new mapping with gaps smoothed :param min_intron: the smallest an intron can be, smaller gaps will be sealed :type min_intron: int :return: a mapping with small gaps closed :rtype: MappingGeneric """ ...
[ "def", "smooth_gaps", "(", "self", ",", "min_intron", ")", ":", "rngs", "=", "[", "self", ".", "_rngs", "[", "0", "]", ".", "copy", "(", ")", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_rngs", ")", "-", "1", ")", ":", "dis...
37.388889
0.013043
def to_timeseries(self, delta_t=None): """ Return the Fourier transform of this time series. Note that this assumes even length time series! Parameters ---------- delta_t : {None, float}, optional The time resolution of the returned series. By default the ...
[ "def", "to_timeseries", "(", "self", ",", "delta_t", "=", "None", ")", ":", "from", "pycbc", ".", "fft", "import", "ifft", "from", "pycbc", ".", "types", "import", "TimeSeries", ",", "real_same_precision_as", "nat_delta_t", "=", "1.0", "/", "(", "(", "len"...
35.348837
0.011524
def bs_param_dists(run_list, **kwargs): """Creates posterior distributions and their bootstrap error functions for input runs and estimators. For a more detailed description and some example use cases, see 'nestcheck: diagnostic tests for nested sampling calculations' (Higson et al. 2019). Paramet...
[ "def", "bs_param_dists", "(", "run_list", ",", "*", "*", "kwargs", ")", ":", "fthetas", "=", "kwargs", ".", "pop", "(", "'fthetas'", ",", "[", "lambda", "theta", ":", "theta", "[", ":", ",", "0", "]", ",", "lambda", "theta", ":", "theta", "[", ":",...
44.267857
0.000197