text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_qseq_dir(fc_dir): """Retrieve the qseq directory within Solexa flowcell output. """ machine_bc = os.path.join(fc_dir, "Data", "Intensities", "BaseCalls") if os.path.exists(machine_bc): return machine_bc # otherwise assume we are in the qseq directory # XXX What other cases can we...
[ "def", "get_qseq_dir", "(", "fc_dir", ")", ":", "machine_bc", "=", "os", ".", "path", ".", "join", "(", "fc_dir", ",", "\"Data\"", ",", "\"Intensities\"", ",", "\"BaseCalls\"", ")", "if", "os", ".", "path", ".", "exists", "(", "machine_bc", ")", ":", "...
36.1
14.1
def app0(self): """ First APP0 marker in image markers. """ for m in self._markers: if m.marker_code == JPEG_MARKER_CODE.APP0: return m raise KeyError('no APP0 marker in image')
[ "def", "app0", "(", "self", ")", ":", "for", "m", "in", "self", ".", "_markers", ":", "if", "m", ".", "marker_code", "==", "JPEG_MARKER_CODE", ".", "APP0", ":", "return", "m", "raise", "KeyError", "(", "'no APP0 marker in image'", ")" ]
29.75
9.5
def parse_plotFingerprint(self): """Find plotFingerprint output. Both --outQualityMetrics and --outRawCounts""" self.deeptools_plotFingerprintOutQualityMetrics = dict() for f in self.find_log_files('deeptools/plotFingerprintOutQualityMetrics'): parsed_data = self.parsePlotFingerprint...
[ "def", "parse_plotFingerprint", "(", "self", ")", ":", "self", ".", "deeptools_plotFingerprintOutQualityMetrics", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "'deeptools/plotFingerprintOutQualityMetrics'", ")", ":", "parsed_data", "=",...
56.746032
25.603175
def _validate_message(self, message): """ Is C{message} a valid direct child of this action? @param message: Either a C{WrittenAction} or a C{WrittenMessage}. @raise WrongTask: If C{message} has a C{task_uuid} that differs from the action's C{task_uuid}. @raise Wron...
[ "def", "_validate_message", "(", "self", ",", "message", ")", ":", "if", "message", ".", "task_uuid", "!=", "self", ".", "task_uuid", ":", "raise", "WrongTask", "(", "self", ",", "message", ")", "if", "not", "message", ".", "task_level", ".", "parent", "...
40.866667
17.133333
def pk_prom(word): '''Return the number of stressed light syllables.''' LIGHT = r'[ieaAoO]{1}[\.]*(u|y)(\.|$)' # # if the word is not monosyllabic, lop off the final syllable, which is # # extrametrical # if '.' in word: # word = word[:word.rindex('.')] # gather the indices of syllable...
[ "def", "pk_prom", "(", "word", ")", ":", "LIGHT", "=", "r'[ieaAoO]{1}[\\.]*(u|y)(\\.|$)'", "# # if the word is not monosyllabic, lop off the final syllable, which is", "# # extrametrical", "# if '.' in word:", "# word = word[:word.rindex('.')]", "# gather the indices of syllable bounda...
30.407407
21.222222
def namedb_get_names_by_sender( cur, sender, current_block ): """ Given a sender pubkey script, find all the non-expired non-revoked names owned by it. Return None if the sender owns no names. """ unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block ) query = "S...
[ "def", "namedb_get_names_by_sender", "(", "cur", ",", "sender", ",", "current_block", ")", ":", "unexpired_query", ",", "unexpired_args", "=", "namedb_select_where_unexpired_names", "(", "current_block", ")", "query", "=", "\"SELECT name_records.name FROM name_records JOIN na...
36.2
29.8
def show_help(command_name: str = None, raw_args: str = '') -> Response: """ Prints the basic command help to the console """ response = Response() cmds = fetch() if command_name and command_name in cmds: parser, result = parse.get_parser( cmds[command_name], parse.expl...
[ "def", "show_help", "(", "command_name", ":", "str", "=", "None", ",", "raw_args", ":", "str", "=", "''", ")", "->", "Response", ":", "response", "=", "Response", "(", ")", "cmds", "=", "fetch", "(", ")", "if", "command_name", "and", "command_name", "i...
27.175
17.45
def editor_js_initialization(selector, **extra_settings): """ Return script tag with initialization code. """ init_template = loader.get_template( settings.MARKDOWN_EDITOR_INIT_TEMPLATE) options = dict( previewParserPath=reverse('django_markdown_preview'), **settings.MARKDOWN_EDITO...
[ "def", "editor_js_initialization", "(", "selector", ",", "*", "*", "extra_settings", ")", ":", "init_template", "=", "loader", ".", "get_template", "(", "settings", ".", "MARKDOWN_EDITOR_INIT_TEMPLATE", ")", "options", "=", "dict", "(", "previewParserPath", "=", "...
32.466667
16.133333
def send_photo(self, peer: Peer, photo: str, caption: str=None, reply: int=None, on_success: callable=None, reply_markup: botapi.ReplyMarkup=None): """ Send photo to peer. :param peer: Peer to send message to. :param photo: File path to photo to send. :param ca...
[ "def", "send_photo", "(", "self", ",", "peer", ":", "Peer", ",", "photo", ":", "str", ",", "caption", ":", "str", "=", "None", ",", "reply", ":", "int", "=", "None", ",", "on_success", ":", "callable", "=", "None", ",", "reply_markup", ":", "botapi",...
46.842105
25.894737
def _parse(self, source, accept_encoded_idn, only_icann=False): """ PSL parser core """ publicsuffix = set() maxlabel = 0 section_is_icann = None if isinstance(source, decodablestr): source = source.splitlines() ln = 0 for line in source: ...
[ "def", "_parse", "(", "self", ",", "source", ",", "accept_encoded_idn", ",", "only_icann", "=", "False", ")", ":", "publicsuffix", "=", "set", "(", ")", "maxlabel", "=", "0", "section_is_icann", "=", "None", "if", "isinstance", "(", "source", ",", "decodab...
31.051282
14.923077
def _slice(expr, start=None, stop=None, step=None): """ Slice substrings from each element in the sequence or scalar :param expr: :param start: int or None :param stop: int or None :param step: int or None :return: sliced """ return _string_op(expr, Slice, _start=start, _end=stop, ...
[ "def", "_slice", "(", "expr", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "step", "=", "None", ")", ":", "return", "_string_op", "(", "expr", ",", "Slice", ",", "_start", "=", "start", ",", "_end", "=", "stop", ",", "_step", "=", "s...
26.666667
18.833333
def com_google_fonts_check_version_bump(ttFont, api_gfonts_ttFont, github_gfonts_ttFont): """Version number has increased since previous release on Google Fonts?""" v_number = ttFont["head"].fontRevision api_gfonts_v_number = api_gfon...
[ "def", "com_google_fonts_check_version_bump", "(", "ttFont", ",", "api_gfonts_ttFont", ",", "github_gfonts_ttFont", ")", ":", "v_number", "=", "ttFont", "[", "\"head\"", "]", ".", "fontRevision", "api_gfonts_v_number", "=", "api_gfonts_ttFont", "[", "\"head\"", "]", "...
38.731707
15.414634
def load(self, record_key, secret_key=''): ''' a method to retrieve byte data of an S3 record :param record_key: string with name of record :param secret_key: [optional] string used to decrypt data :return: byte data for record body ''' titl...
[ "def", "load", "(", "self", ",", "record_key", ",", "secret_key", "=", "''", ")", ":", "title", "=", "'%s.load'", "%", "self", ".", "__class__", ".", "__name__", "# validate inputs", "input_fields", "=", "{", "'record_key'", ":", "record_key", ",", "'secret_...
37.439024
23.04878
def unordered_pair_eq(pair1, pair2): '''Performs pairwise unordered equality. ``pair1`` == ``pair2`` if and only if ``frozenset(pair1)`` == ``frozenset(pair2)``. ''' (x1, y1), (x2, y2) = pair1, pair2 return (x1 == x2 and y1 == y2) or (x1 == y2 and y1 == x2)
[ "def", "unordered_pair_eq", "(", "pair1", ",", "pair2", ")", ":", "(", "x1", ",", "y1", ")", ",", "(", "x2", ",", "y2", ")", "=", "pair1", ",", "pair2", "return", "(", "x1", "==", "x2", "and", "y1", "==", "y2", ")", "or", "(", "x1", "==", "y2...
34.375
14.375
def slurpChompedLines(file, expand=False): r"""Return ``file`` a list of chomped lines. See `slurpLines`.""" f=_normalizeToFile(file, "r", expand) try: return list(chompLines(f)) finally: f.close()
[ "def", "slurpChompedLines", "(", "file", ",", "expand", "=", "False", ")", ":", "f", "=", "_normalizeToFile", "(", "file", ",", "\"r\"", ",", "expand", ")", "try", ":", "return", "list", "(", "chompLines", "(", "f", ")", ")", "finally", ":", "f", "."...
41.8
5.2
def Blaster(inputfile, databases, db_path, out_path='.', min_cov=0.6, threshold=0.9, blast='blastn', cut_off=True): ''' BLAST wrapper method, that takes a simple input and produces a overview list of the hits to templates, and their alignments Usage >>> import os, subprocess, collections ...
[ "def", "Blaster", "(", "inputfile", ",", "databases", ",", "db_path", ",", "out_path", "=", "'.'", ",", "min_cov", "=", "0.6", ",", "threshold", "=", "0.9", ",", "blast", "=", "'blastn'", ",", "cut_off", "=", "True", ")", ":", "min_cov", "=", "100", ...
47.05102
21.428571
def _parse_epsilon(line, lines): """Parse Energy [eV] Re_eps_xx Im_eps_xx Re_eps_zz Im_eps_zz""" split_line = line.split() energy = float(split_line[0]) re_eps_xx = float(split_line[1]) im_eps_xx = float(split_line[2]) re_eps_zz = float(split_line[3]) im_eps_zz = float(split_li...
[ "def", "_parse_epsilon", "(", "line", ",", "lines", ")", ":", "split_line", "=", "line", ".", "split", "(", ")", "energy", "=", "float", "(", "split_line", "[", "0", "]", ")", "re_eps_xx", "=", "float", "(", "split_line", "[", "1", "]", ")", "im_eps_...
34.846154
17.538462
def data(self, index, role): """ Get the data for the header. This is used when a header has levels. """ if not index.isValid() or \ index.row() >= self._shape[0] or \ index.column() >= self._shape[1]: return None row, col = ((...
[ "def", "data", "(", "self", ",", "index", ",", "role", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", "or", "index", ".", "row", "(", ")", ">=", "self", ".", "_shape", "[", "0", "]", "or", "index", ".", "column", "(", ")", ">=", "s...
33.222222
13.962963
def sensor_values(self): """ Returns the values of all sensors for this cluster """ self.update_instance_sensors(opt="all") return { "light": self.lux, "water": self.soil_moisture, "humidity": self.humidity, "temperature": ...
[ "def", "sensor_values", "(", "self", ")", ":", "self", ".", "update_instance_sensors", "(", "opt", "=", "\"all\"", ")", "return", "{", "\"light\"", ":", "self", ".", "lux", ",", "\"water\"", ":", "self", ".", "soil_moisture", ",", "\"humidity\"", ":", "sel...
30
10
def NetFxSdkDir(self): """ Microsoft .NET Framework SDK directory. """ for ver in self.NetFxSdkVersion: loc = os.path.join(self.ri.netfx_sdk, ver) sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder') if sdkdir: break return sd...
[ "def", "NetFxSdkDir", "(", "self", ")", ":", "for", "ver", "in", "self", ".", "NetFxSdkVersion", ":", "loc", "=", "os", ".", "path", ".", "join", "(", "self", ".", "ri", ".", "netfx_sdk", ",", "ver", ")", "sdkdir", "=", "self", ".", "ri", ".", "l...
32.1
11.5
def _get_type(self, s): """ Converts a string from Scratch to its proper type in Python. Expects a string with its delimiting quotes in place. Returns either a string, int or float. """ # TODO: what if the number is bigger than an int or float? if s.startswith('...
[ "def", "_get_type", "(", "self", ",", "s", ")", ":", "# TODO: what if the number is bigger than an int or float?", "if", "s", ".", "startswith", "(", "'\"'", ")", "and", "s", ".", "endswith", "(", "'\"'", ")", ":", "return", "s", "[", "1", ":", "-", "1", ...
35.538462
16.923077
def original_query_sequence_length(self): """Similar to get_get_query_sequence_length, but it also includes hard clipped bases if there is no cigar, then default to trying the sequence :return: the length of the query before any clipping :rtype: int """ if not self.is_aligned() or not self....
[ "def", "original_query_sequence_length", "(", "self", ")", ":", "if", "not", "self", ".", "is_aligned", "(", ")", "or", "not", "self", ".", "entries", ".", "cigar", ":", "return", "self", ".", "query_sequence_length", "# take the naive approach", "# we are here wi...
45.666667
19.833333
def _clean_salt_variables(params, variable_prefix="__"): ''' Pops out variables from params which starts with `variable_prefix`. ''' list(list(map(params.pop, [k for k in params if k.startswith(variable_prefix)]))) return params
[ "def", "_clean_salt_variables", "(", "params", ",", "variable_prefix", "=", "\"__\"", ")", ":", "list", "(", "list", "(", "map", "(", "params", ".", "pop", ",", "[", "k", "for", "k", "in", "params", "if", "k", ".", "startswith", "(", "variable_prefix", ...
40.5
30.166667
def from_bytes(self, raw): '''Return a Null header object reconstructed from raw bytes, or an Exception if we can't resurrect the packet.''' if len(raw) < 4: raise NotEnoughDataError("Not enough bytes ({}) to reconstruct a Null object".format(len(raw))) fields = struct.unpack...
[ "def", "from_bytes", "(", "self", ",", "raw", ")", ":", "if", "len", "(", "raw", ")", "<", "4", ":", "raise", "NotEnoughDataError", "(", "\"Not enough bytes ({}) to reconstruct a Null object\"", ".", "format", "(", "len", "(", "raw", ")", ")", ")", "fields",...
47.5
22.5
def create_interface_method_ref(self, class_: str, if_method: str, descriptor: str) -> InterfaceMethodRef: """ Creates a new :class:`ConstantInterfaceMethodRef`, adding it to the pool and returning it. :param class_: The name of the class to which `if...
[ "def", "create_interface_method_ref", "(", "self", ",", "class_", ":", "str", ",", "if_method", ":", "str", ",", "descriptor", ":", "str", ")", "->", "InterfaceMethodRef", ":", "self", ".", "append", "(", "(", "11", ",", "self", ".", "create_class", "(", ...
41.125
20.25
def multi_ping(dest_addrs, timeout, retry=0, ignore_lookup_errors=False): """ Combine send and receive measurement into single function. This offers a retry mechanism: Overall timeout time is divided by number of retries. Additional ICMPecho packets are sent to those addresses from which we have no...
[ "def", "multi_ping", "(", "dest_addrs", ",", "timeout", ",", "retry", "=", "0", ",", "ignore_lookup_errors", "=", "False", ")", ":", "retry", "=", "int", "(", "retry", ")", "if", "retry", "<", "0", ":", "retry", "=", "0", "timeout", "=", "float", "("...
32.87234
24.829787
def SetEncoding(sval): """Sets the encoding variable according to the text passed :param sval: text specification for the desired model """ global encoding s=sval.lower() if s == "additive": encoding = Encoding.Additive elif s == "dominant": encoding = Encoding.Dominant ...
[ "def", "SetEncoding", "(", "sval", ")", ":", "global", "encoding", "s", "=", "sval", ".", "lower", "(", ")", "if", "s", "==", "\"additive\"", ":", "encoding", "=", "Encoding", ".", "Additive", "elif", "s", "==", "\"dominant\"", ":", "encoding", "=", "E...
29.578947
15.105263
def DefaultSelector(): """ This function serves as a first call for DefaultSelector to detect if the select module is being monkey-patched incorrectly by eventlet, greenlet, and preserve proper behavior. """ global _DEFAULT_SELECTOR if _DEFAULT_SELECTOR is None: if platform.python_implementa...
[ "def", "DefaultSelector", "(", ")", ":", "global", "_DEFAULT_SELECTOR", "if", "_DEFAULT_SELECTOR", "is", "None", ":", "if", "platform", ".", "python_implementation", "(", ")", "==", "'Jython'", ":", "# Platform-specific: Jython", "_DEFAULT_SELECTOR", "=", "JythonSelec...
46.190476
9.857143
def instantiate(self, value_of_n): """Instantiates the template""" template = Cheetah.Template.Template( self.content, searchList={'n': value_of_n} ) template.random_string = random_string return str(template)
[ "def", "instantiate", "(", "self", ",", "value_of_n", ")", ":", "template", "=", "Cheetah", ".", "Template", ".", "Template", "(", "self", ".", "content", ",", "searchList", "=", "{", "'n'", ":", "value_of_n", "}", ")", "template", ".", "random_string", ...
33.25
9.375
def plot_fracs(self, Q=None, ax=None, fignum=None): """ Plot fractions of Eigenvalues sorted in descending order. """ from ..plotting import Tango Tango.reset() col = Tango.nextMedium() if ax is None: fig = pylab.figure(fignum) ax = fig.add...
[ "def", "plot_fracs", "(", "self", ",", "Q", "=", "None", ",", "ax", "=", "None", ",", "fignum", "=", "None", ")", ":", "from", ".", ".", "plotting", "import", "Tango", "Tango", ".", "reset", "(", ")", "col", "=", "Tango", ".", "nextMedium", "(", ...
32.875
13.625
def count_lightning(datain, time_step): """**Count lightning strikes detected within a defined time_step** Generate time intervals according to the time_step defined and count lightning strikes in these intervals. Statistics are also calculated for lightning detection errors and the number of stations ...
[ "def", "count_lightning", "(", "datain", ",", "time_step", ")", ":", "if", "(", "1440", "%", "time_step", "==", "0", ")", ":", "# check if time_step is multiple of 1 day", "i", "=", "0", "# run for loop for all time steps in one day", "for", "time_interval", "in", "...
46.882353
20.098039
def _get_attributes(self, path): """ :param path: filepath within fast5 :return: dictionary of attributes found at ``path`` :rtype dict """ path_grp = self.handle[path] path_attr = path_grp.attrs return dict(path_attr)
[ "def", "_get_attributes", "(", "self", ",", "path", ")", ":", "path_grp", "=", "self", ".", "handle", "[", "path", "]", "path_attr", "=", "path_grp", ".", "attrs", "return", "dict", "(", "path_attr", ")" ]
30.444444
7.777778
def generate_password_hash(password, method='pbkdf2:sha1', salt_length=8): """Hash a password with the given method and salt with with a string of the given length. The format of the string returned includes the method that was used so that :func:`check_password_hash` can check the hash. The format fo...
[ "def", "generate_password_hash", "(", "password", ",", "method", "=", "'pbkdf2:sha1'", ",", "salt_length", "=", "8", ")", ":", "salt", "=", "method", "!=", "'plain'", "and", "gen_salt", "(", "salt_length", ")", "or", "''", "h", ",", "actual_method", "=", "...
44.142857
23.857143
def sample_orbit(self, Npts=100, primary=None, trailing=True, timespan=None, useTrueAnomaly=True): """ Returns a nested list of xyz positions along the osculating orbit of the particle. If primary is not passed, returns xyz positions along the Jacobi osculating orbit (with mu = G*Minc, ...
[ "def", "sample_orbit", "(", "self", ",", "Npts", "=", "100", ",", "primary", "=", "None", ",", "trailing", "=", "True", ",", "timespan", "=", "None", ",", "useTrueAnomaly", "=", "True", ")", ":", "pts", "=", "[", "]", "if", "primary", "is", "None", ...
55.212766
36.957447
def request(self, url: str, method: str = 'GET', *, callback=None, encoding: typing.Optional[str] = None, headers: dict = None, metadata: dict = None, request_config: dict = None, ...
[ "def", "request", "(", "self", ",", "url", ":", "str", ",", "method", ":", "str", "=", "'GET'", ",", "*", ",", "callback", "=", "None", ",", "encoding", ":", "typing", ".", "Optional", "[", "str", "]", "=", "None", ",", "headers", ":", "dict", "=...
33
12.225806
def equalizer(self, frequency, width_q, gain_db): '''Apply a two-pole peaking equalisation (EQ) filter to boost or reduce around a given frequency. This effect can be applied multiple times to produce complex EQ curves. Parameters ---------- frequency : float ...
[ "def", "equalizer", "(", "self", ",", "frequency", ",", "width_q", ",", "gain_db", ")", ":", "if", "not", "is_number", "(", "frequency", ")", "or", "frequency", "<=", "0", ":", "raise", "ValueError", "(", "\"frequency must be a positive number.\"", ")", "if", ...
30.675676
19.756757
def download(date_array, tag, sat_id='', data_path=None, user=None, password=None, baseline='all', delta='none', options='all', file_fmt='ascii'): """Routine to download SuperMAG data Parameters ----------- date_array : np.array Array of datetime objects tag : stri...
[ "def", "download", "(", "date_array", ",", "tag", ",", "sat_id", "=", "''", ",", "data_path", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "baseline", "=", "'all'", ",", "delta", "=", "'none'", ",", "options", "=", "'all'...
38.677419
21.069124
def _do_layout(self): """Adds widgets to the aui manager and controls the layout""" # Set background color for the toolbar via the manager ap = self._mgr.GetArtProvider() ap.SetColour(aui.AUI_DOCKART_BACKGROUND_GRADIENT_COLOUR, get_color(config["background_color"]))...
[ "def", "_do_layout", "(", "self", ")", ":", "# Set background color for the toolbar via the manager", "ap", "=", "self", ".", "_mgr", ".", "GetArtProvider", "(", ")", "ap", ".", "SetColour", "(", "aui", ".", "AUI_DOCKART_BACKGROUND_GRADIENT_COLOUR", ",", "get_color", ...
41.352113
23.84507
def create_connection(self, session=None): """ Create connection in the Connection table, according to whether it uses proxy, TCP, UNIX sockets, SSL. Connection ID will be randomly generated. :param session: Session of the SQL Alchemy ORM (automatically generated with ...
[ "def", "create_connection", "(", "self", ",", "session", "=", "None", ")", ":", "connection", "=", "Connection", "(", "conn_id", "=", "self", ".", "db_conn_id", ")", "uri", "=", "self", ".", "_generate_connection_uri", "(", ")", "self", ".", "log", ".", ...
42.857143
17.285714
def _annotate_crossmatch_with_value_added_parameters( self, crossmatchDict, catalogueName, searchPara, search_name): """*annotate each crossmatch with physical parameters such are distances etc* **Key Arguments:** - ``crossmatchDic...
[ "def", "_annotate_crossmatch_with_value_added_parameters", "(", "self", ",", "crossmatchDict", ",", "catalogueName", ",", "searchPara", ",", "search_name", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``_annotate_crossmatch_with_value_added_parameters`` met...
41.574074
19.981481
def iter_orgs(self, number=-1, etag=None): """Iterate over organizations the user is member of :param int number: (optional), number of organizations to return. Default: -1 returns all available organization :param str etag: (optional), ETag from a previous request to the same ...
[ "def", "iter_orgs", "(", "self", ",", "number", "=", "-", "1", ",", "etag", "=", "None", ")", ":", "# Import here, because a toplevel import causes an import loop", "from", ".", "orgs", "import", "Organization", "url", "=", "self", ".", "_build_url", "(", "'orgs...
49.538462
19.846154
def new_scheduler(self, tasks, root_subject_types, build_root, work_dir, local_store_dir, ignore_patterns, execution_options, construct_directory_digest, ...
[ "def", "new_scheduler", "(", "self", ",", "tasks", ",", "root_subject_types", ",", "build_root", ",", "work_dir", ",", "local_store_dir", ",", "ignore_patterns", ",", "execution_options", ",", "construct_directory_digest", ",", "construct_snapshot", ",", "construct_file...
39.607595
13.177215
def plot_network(symbol, title="plot", save_format='pdf', shape=None, dtype=None, node_attrs={}, hide_weights=True): """Creates a visualization (Graphviz digraph object) of the given computation graph. Graphviz must be installed for this function to work. Parameters ---------- titl...
[ "def", "plot_network", "(", "symbol", ",", "title", "=", "\"plot\"", ",", "save_format", "=", "'pdf'", ",", "shape", "=", "None", ",", "dtype", "=", "None", ",", "node_attrs", "=", "{", "}", ",", "hide_weights", "=", "True", ")", ":", "# todo add shape s...
44.638498
21.661972
def content(): """Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.3 :returns: A message object without brand element. :rtype: safe.messaging.message.Message """ message = m.Message() ...
[ "def", "content", "(", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "paragraph", "=", "m", ".", "Paragraph", "(", "m", ".", "Image", "(", "'file:///%s/img/screenshots/'", "'petabencana-screenshot.png'", "%", "resources_path", "(", ")", ")", ",", ...
37.140351
22.54386
def question_encoder(question, question_self_attention_bias, hparams, name="question_encoder", save_weights_to=None, make_image_summary=True): """A stack of self attention layers.""" x = question with tf.varia...
[ "def", "question_encoder", "(", "question", ",", "question_self_attention_bias", ",", "hparams", ",", "name", "=", "\"question_encoder\"", ",", "save_weights_to", "=", "None", ",", "make_image_summary", "=", "True", ")", ":", "x", "=", "question", "with", "tf", ...
45.901961
13.137255
def GetFirstWrittenEventSource(self): """Retrieves the first event source that was written after open. Using GetFirstWrittenEventSource and GetNextWrittenEventSource newly added event sources can be retrieved in order of addition. Returns: EventSource: event source or None if there are no newly ...
[ "def", "GetFirstWrittenEventSource", "(", "self", ")", ":", "if", "not", "self", ".", "_storage_file", ":", "raise", "IOError", "(", "'Unable to read from closed storage writer.'", ")", "event_source", "=", "self", ".", "_storage_file", ".", "GetEventSourceByIndex", "...
34
20.913043
def get_default_margins(self): """get default margins""" trans = self.fig.transFigure.inverted().transform # Static margins l, t, r, b = self.axesmargins (l, b), (r, t) = trans(((l, b), (r, t))) # Extent dl, dt, dr, db = 0, 0, 0, 0 for i, ax in enumerate...
[ "def", "get_default_margins", "(", "self", ")", ":", "trans", "=", "self", ".", "fig", ".", "transFigure", ".", "inverted", "(", ")", ".", "transform", "# Static margins", "l", ",", "t", ",", "r", ",", "b", "=", "self", ".", "axesmargins", "(", "l", ...
37.608696
19.043478
def _brute_force_install_pip(self): """A brute force install of pip itself.""" if os.path.exists(self.pip_installer_fname): logger.debug("Using pip installer from %r", self.pip_installer_fname) else: logger.debug( "Installer for pip not found in %r, downlo...
[ "def", "_brute_force_install_pip", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "pip_installer_fname", ")", ":", "logger", ".", "debug", "(", "\"Using pip installer from %r\"", ",", "self", ".", "pip_installer_fname", ")", "...
48.076923
21.769231
def power(self, n): """The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: Kraus: the matrix power of the SuperOp converted to a Kraus channel. Raises: QiskitError: if the input and output d...
[ "def", "power", "(", "self", ",", "n", ")", ":", "if", "n", ">", "0", ":", "return", "super", "(", ")", ".", "power", "(", "n", ")", "return", "Kraus", "(", "SuperOp", "(", "self", ")", ".", "power", "(", "n", ")", ")" ]
31.625
23.875
def computeActivity(self, activeInputsBySource, permanenceThreshold=None): """ Calculate the number of active synapses per segment. @param activeInputsBySource (dict) The active cells in each source. Example: {"customInputName1": np.array([42, 69])} """ overlaps = None for source, co...
[ "def", "computeActivity", "(", "self", ",", "activeInputsBySource", ",", "permanenceThreshold", "=", "None", ")", ":", "overlaps", "=", "None", "for", "source", ",", "connections", "in", "self", ".", "connectionsBySource", ".", "iteritems", "(", ")", ":", "o",...
30.631579
20
def set_text(self, text=None, **kwargs): """ Add textual information passed as dictionary. All pairs in dictionary will be written, but keys should be latin-1; registered keywords could be used as arguments. When called more than once overwrite exist data. """ i...
[ "def", "set_text", "(", "self", ",", "text", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "text", "is", "None", ":", "text", "=", "{", "}", "text", ".", "update", "(", "popdict", "(", "kwargs", ",", "_registered_kw", ")", ")", "if", "'Cr...
38.823529
17.764706
def printActiveIndices(self, state, andValues=False): """Print the list of [column, cellIdx] indices for each of the active cells in state. """ (cols, cellIdxs) = state.nonzero() if len(cols) == 0: print "NONE" return prevCol = -1 for (col,cellIdx) in zip(cols, cellIdxs): if ...
[ "def", "printActiveIndices", "(", "self", ",", "state", ",", "andValues", "=", "False", ")", ":", "(", "cols", ",", "cellIdxs", ")", "=", "state", ".", "nonzero", "(", ")", "if", "len", "(", "cols", ")", "==", "0", ":", "print", "\"NONE\"", "return",...
25.272727
18.545455
def _remove_rule(self, group, role, value=None): """Implementation detail""" if role not in group: return if value is None: group.pop(role, None) else: group[role].remove(value) self.invalidate()
[ "def", "_remove_rule", "(", "self", ",", "group", ",", "role", ",", "value", "=", "None", ")", ":", "if", "role", "not", "in", "group", ":", "return", "if", "value", "is", "None", ":", "group", ".", "pop", "(", "role", ",", "None", ")", "else", "...
23.909091
17.090909
def cs_encode(s): """Encode URI component like CloudStack would do before signing. java.net.URLEncoder.encode(s).replace('+', '%20') """ if PY2 and isinstance(s, text_type): s = s.encode("utf-8") return quote(s, safe="*")
[ "def", "cs_encode", "(", "s", ")", ":", "if", "PY2", "and", "isinstance", "(", "s", ",", "text_type", ")", ":", "s", "=", "s", ".", "encode", "(", "\"utf-8\"", ")", "return", "quote", "(", "s", ",", "safe", "=", "\"*\"", ")" ]
30.375
12.25
def json(value, schema = None, allow_empty = False, json_serializer = None, **kwargs): """Validate that ``value`` conforms to the supplied JSON Schema. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using...
[ "def", "json", "(", "value", ",", "schema", "=", "None", ",", "allow_empty", "=", "False", ",", "json_serializer", "=", "None", ",", "*", "*", "kwargs", ")", ":", "original_value", "=", "value", "original_schema", "=", "schema", "if", "not", "value", "an...
36.821053
25
def get_results(self, metadata=False): """ Return results of the analysis. """ results_data = [] self.process_har() self.process_from_splash() for rt in sorted(self._results.get_results()): rdict = {'name': rt.name} if rt.version: rdict['...
[ "def", "get_results", "(", "self", ",", "metadata", "=", "False", ")", ":", "results_data", "=", "[", "]", "self", ".", "process_har", "(", ")", "self", ".", "process_from_splash", "(", ")", "for", "rt", "in", "sorted", "(", "self", ".", "_results", "....
28.428571
15.333333
def start(self, max_transitions=None, keep_active=False): """ Start the driver. This method creates a thread which runs the event loop. The method returns immediately. To wait until the driver finishes, use `stmpy.Driver.wait_until_finished`. `max_transitions`: execute ...
[ "def", "start", "(", "self", ",", "max_transitions", "=", "None", ",", "keep_active", "=", "False", ")", ":", "self", ".", "_active", "=", "True", "self", ".", "_max_transitions", "=", "max_transitions", "self", ".", "_keep_active", "=", "keep_active", "self...
38.941176
18.235294
def error(self, text): """ Ajout d'un message de log de type ERROR """ self.logger.error("{}{}".format(self.message_prefix, text))
[ "def", "error", "(", "self", ",", "text", ")", ":", "self", ".", "logger", ".", "error", "(", "\"{}{}\"", ".", "format", "(", "self", ".", "message_prefix", ",", "text", ")", ")" ]
44
13
def rotate(self, shift): ''' Rotate 90 degrees clockwise `shift` times. If `shift` is negative, rotate counter-clockwise. ''' self.child_corners.values[:] = np.roll(self.child_corners .values, shift, axis=0) self.update_tr...
[ "def", "rotate", "(", "self", ",", "shift", ")", ":", "self", ".", "child_corners", ".", "values", "[", ":", "]", "=", "np", ".", "roll", "(", "self", ".", "child_corners", ".", "values", ",", "shift", ",", "axis", "=", "0", ")", "self", ".", "up...
40.25
22.75
def batch_step(self, batch_idx=None): """Updates the learning rate for the batch index: ``batch_idx``. If ``batch_idx`` is None, ``CyclicLR`` will use an internal batch index to keep track of the index. """ if batch_idx is None: batch_idx = self.last_batch_idx + 1 ...
[ "def", "batch_step", "(", "self", ",", "batch_idx", "=", "None", ")", ":", "if", "batch_idx", "is", "None", ":", "batch_idx", "=", "self", ".", "last_batch_idx", "+", "1", "self", ".", "last_batch_idx", "=", "batch_idx", "for", "param_group", ",", "lr", ...
46.2
10.1
def interpolate_curve(points, degree, **kwargs): """ Curve interpolation through the data points. Please refer to Algorithm A9.1 on The NURBS Book (2nd Edition), pp.369-370 for details. Keyword Arguments: * ``centripetal``: activates centripetal parametrization method. *Default: False* :param...
[ "def", "interpolate_curve", "(", "points", ",", "degree", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "use_centripetal", "=", "kwargs", ".", "get", "(", "'centripetal'", ",", "False", ")", "# Number of control points", "num_points", "=", "len", "("...
27.973684
21.052632
def skopeo_pull(self): """ Pull image from Docker to local Docker daemon using skopeo :return: pulled image """ return self.copy(self.name, self.tag, SkopeoTransport.DOCKER, SkopeoTransport.DOCKER_DAEMON)\ .using_transport(SkopeoTransport.DOCKER_DAEM...
[ "def", "skopeo_pull", "(", "self", ")", ":", "return", "self", ".", "copy", "(", "self", ".", "name", ",", "self", ".", "tag", ",", "SkopeoTransport", ".", "DOCKER", ",", "SkopeoTransport", ".", "DOCKER_DAEMON", ")", ".", "using_transport", "(", "SkopeoTra...
39.5
16.625
def _reset(self, framer): """ Reset the state for the framer. It is safe to call this method multiple times with the same framer; the ID of the framer object will be saved and the state only reset if the IDs are different. After resetting the state, the framer's ``init_...
[ "def", "_reset", "(", "self", ",", "framer", ")", ":", "# Do nothing if we're already properly initialized", "if", "id", "(", "framer", ")", "==", "self", ".", "_framer_id", ":", "return", "# Reset the state", "self", ".", "_other", "=", "{", "}", "# Initialize ...
33.842105
18.052632
def classify(self, token, previous=None, next=None, **kwargs): """ Returns the predicted tag for the given token, in context of the given previous and next (token, tag)-tuples. """ return self._classifier.classify(self._v(token, previous, next), **kwargs)
[ "def", "classify", "(", "self", ",", "token", ",", "previous", "=", "None", ",", "next", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_classifier", ".", "classify", "(", "self", ".", "_v", "(", "token", ",", "previous", "...
57.4
19.6
def edit_files(patterns, expressions=None, functions=None, executables=None, start_dirs=None, max_depth=1, dry_run=True, output=sys.stdout, encoding=None, newline=None): """Process patterns with MassEdit. Arguments: patterns: file pattern to identify the files...
[ "def", "edit_files", "(", "patterns", ",", "expressions", "=", "None", ",", "functions", "=", "None", ",", "executables", "=", "None", ",", "start_dirs", "=", "None", ",", "max_depth", "=", "1", ",", "dry_run", "=", "True", ",", "output", "=", "sys", "...
41.758065
19.741935
def dump(obj, fp, imports=None, binary=True, sequence_as_stream=False, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=Fals...
[ "def", "dump", "(", "obj", ",", "fp", ",", "imports", "=", "None", ",", "binary", "=", "True", ",", "sequence_as_stream", "=", "False", ",", "skipkeys", "=", "False", ",", "ensure_ascii", "=", "True", ",", "check_circular", "=", "True", ",", "allow_nan",...
52.27
19.72
def cache_scan(self): """ Scan the lineage for the index of the most recent cache. :return: Index of most recent cache """ try: return len(self.transformations) - self.transformations[::-1].index(CACHE_T) except ValueError: return 0
[ "def", "cache_scan", "(", "self", ")", ":", "try", ":", "return", "len", "(", "self", ".", "transformations", ")", "-", "self", ".", "transformations", "[", ":", ":", "-", "1", "]", ".", "index", "(", "CACHE_T", ")", "except", "ValueError", ":", "ret...
32.888889
17.333333
def cget(self, key): """ Query widget option. :param key: option name :type key: str :return: value of the option To get the list of options for this widget, call the method :meth:`~Balloon.keys`. """ if key == "headertext": return self.__hea...
[ "def", "cget", "(", "self", ",", "key", ")", ":", "if", "key", "==", "\"headertext\"", ":", "return", "self", ".", "__headertext", "elif", "key", "==", "\"text\"", ":", "return", "self", ".", "__text", "elif", "key", "==", "\"width\"", ":", "return", "...
28.181818
14.090909
def wait_for_winexe(host, port, username, password, timeout=900): ''' Wait until winexe connection can be established. ''' start = time.time() log.debug( 'Attempting winexe connection to host %s on port %s', host, port ) try_count = 0 while True: try_count += 1 ...
[ "def", "wait_for_winexe", "(", "host", ",", "port", ",", "username", ",", "password", ",", "timeout", "=", "900", ")", ":", "start", "=", "time", ".", "time", "(", ")", "log", ".", "debug", "(", "'Attempting winexe connection to host %s on port %s'", ",", "h...
31.222222
20.185185
def colorize_output(output, colors, indent=0): r"""Print output to console using provided color mappings. Color mapping is dict with regular expressions as key and tuple of two as values. Key is used to match if line should be colorized and tuple contains color to be used and boolean value that in...
[ "def", "colorize_output", "(", "output", ",", "colors", ",", "indent", "=", "0", ")", ":", "for", "line", "in", "output", ".", "split", "(", "\"\\n\"", ")", ":", "cprint", "(", "\" \"", "*", "indent", ")", "if", "line", "==", "\"\"", ":", "cprint", ...
36.642857
23.238095
def osm_filter(network_type): """ Create a filter to query Overpass API for the specified OSM network type. Parameters ---------- network_type : string, {'walk', 'drive'} denoting the type of street network to extract Returns ------- osm_filter : string """ filters = {} ...
[ "def", "osm_filter", "(", "network_type", ")", ":", "filters", "=", "{", "}", "# drive: select only roads that are drivable by normal 2 wheel drive", "# passenger vehicles both private and public", "# roads. Filter out un-drivable roads and service roads tagged as parking,", "# driveway, o...
37.512821
24.025641
def get_sleep_timer(self): """Retrieves remaining sleep time, if any Returns: int or NoneType: Number of seconds left in timer. If there is no sleep timer currently set it will return None. """ resp = self.avTransport.GetRemainingSleepTimerDuration([ ...
[ "def", "get_sleep_timer", "(", "self", ")", ":", "resp", "=", "self", ".", "avTransport", ".", "GetRemainingSleepTimerDuration", "(", "[", "(", "'InstanceID'", ",", "0", ")", ",", "]", ")", "if", "resp", "[", "'RemainingSleepTimerDuration'", "]", ":", "times...
35.823529
16.764706
def _get_calling_module(self): """Get the last module in the call stack that is not this module or ``None`` if the call originated from this module. """ for frame in inspect.stack(): mod = inspect.getmodule(frame[0]) logger.debug(f'calling module: {mod}') ...
[ "def", "_get_calling_module", "(", "self", ")", ":", "for", "frame", "in", "inspect", ".", "stack", "(", ")", ":", "mod", "=", "inspect", ".", "getmodule", "(", "frame", "[", "0", "]", ")", "logger", ".", "debug", "(", "f'calling module: {mod}'", ")", ...
37.083333
7.75
def _find_wikipedia_names(self, name_en): """ Finds all Wikipedia pages referring to the specified name in English and returns a dictionary where the keys are the language code and the values are the titles of the corresponding pages. """ url = 'https://en.wikipedia.org/w...
[ "def", "_find_wikipedia_names", "(", "self", ",", "name_en", ")", ":", "url", "=", "'https://en.wikipedia.org/w/api.php'", "params", "=", "{", "'action'", ":", "'query'", ",", "'titles'", ":", "name_en", ",", "'prop'", ":", "'langlinks'", ",", "'lllimit'", ":", ...
36.791667
16.041667
def folderitems(self, full_objects=False, classic=True): """Sort by Categories """ bsc = getToolByName(self.context, "bika_setup_catalog") self.an_cats = bsc( portal_type="AnalysisCategory", sort_on="sortable_title") self.an_cats_order = dict([ ...
[ "def", "folderitems", "(", "self", ",", "full_objects", "=", "False", ",", "classic", "=", "True", ")", ":", "bsc", "=", "getToolByName", "(", "self", ".", "context", ",", "\"bika_setup_catalog\"", ")", "self", ".", "an_cats", "=", "bsc", "(", "portal_type...
39.470588
12.411765
def polls_get(self, **kwargs): """ Polls A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question...
[ "def", "polls_get", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "polls_get_with_http_info", "(", "*", "*", "k...
69.413793
45.827586
def skip_format_url(format_, url): """ Checks whether a give format/url should be skipped and not downloaded. @param format_: Filename format (extension). @type format_: str (e.g. html, txt, zip, pdf) @param url: URL. @type url: str @return: True if format/url should be skipped, False oth...
[ "def", "skip_format_url", "(", "format_", ",", "url", ")", ":", "# Do not download empty formats", "if", "format_", "==", "''", ":", "return", "True", "# Do not download email addresses", "if", "(", "'mailto:'", "in", "url", ")", "and", "(", "'@'", "in", "url", ...
24.97561
19.804878
def chord_counts(im): r""" Finds the length of each chord in the supplied image and returns a list of their individual sizes Parameters ---------- im : ND-array An image containing chords drawn in the void space. Returns ------- result : 1D-array A 1D array with one...
[ "def", "chord_counts", "(", "im", ")", ":", "labels", ",", "N", "=", "spim", ".", "label", "(", "im", ">", "0", ")", "props", "=", "regionprops", "(", "labels", ",", "coordinates", "=", "'xy'", ")", "chord_lens", "=", "sp", ".", "array", "(", "[", ...
31.230769
23.730769
def generate_key(url, page_number): """ >>> url_a = 'http://localhost:5009/search?keywords=a' >>> generate_key(url_a, 10) 'http://localhost:5009/search?keywords=a&page=10' >>> url_b = 'http://localhost:5009/search?keywords=b&page=1' >>> generate_key(url_b, 10) 'http://localhost:5009/search?k...
[ "def", "generate_key", "(", "url", ",", "page_number", ")", ":", "index", "=", "url", ".", "rfind", "(", "'page'", ")", "if", "index", "!=", "-", "1", ":", "result", "=", "url", "[", "0", ":", "index", "]", "result", "+=", "'page=%s'", "%", "page_n...
32
12.352941
def RegisterCustomFieldCodec(encoder, decoder): """Register a custom encoder/decoder for this field.""" def Register(field): _CUSTOM_FIELD_CODECS[field] = _Codec(encoder=encoder, decoder=decoder) return field return Register
[ "def", "RegisterCustomFieldCodec", "(", "encoder", ",", "decoder", ")", ":", "def", "Register", "(", "field", ")", ":", "_CUSTOM_FIELD_CODECS", "[", "field", "]", "=", "_Codec", "(", "encoder", "=", "encoder", ",", "decoder", "=", "decoder", ")", "return", ...
41.166667
17
def order_phase_diagram(lines, stable_entries, unstable_entries, ordering): """ Orders the entries (their coordinates) in a phase diagram plot according to the user specified ordering. Ordering should be given as ['Up', 'Left', 'Right'], where Up, Left and Right are the names of the entries in the u...
[ "def", "order_phase_diagram", "(", "lines", ",", "stable_entries", ",", "unstable_entries", ",", "ordering", ")", ":", "yup", "=", "-", "1000.0", "xleft", "=", "1000.0", "xright", "=", "-", "1000.0", "for", "coord", "in", "stable_entries", ":", "if", "coord"...
47.102041
18.639456
def kill(self): """Kill the browser. This is useful when the browser is stuck. """ if self.process: self.process.kill() self.process.wait()
[ "def", "kill", "(", "self", ")", ":", "if", "self", ".", "process", ":", "self", ".", "process", ".", "kill", "(", ")", "self", ".", "process", ".", "wait", "(", ")" ]
23.625
13.5
def try_open (*args, **kwargs): """Simply a wrapper for io.open(), unless an IOError with errno=2 (ENOENT) is raised, in which case None is retured. """ try: return io.open (*args, **kwargs) except IOError as e: if e.errno == 2: return None raise
[ "def", "try_open", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "io", ".", "open", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "IOError", "as", "e", ":", "if", "e", ".", "errno", "==", "2", ":", "re...
26.636364
14.454545
def _elect_source_broker(self, victim_partition, broker_subset=None): """Select first over loaded broker having victim_partition. Note: The broker with maximum siblings of victim-partitions (same topic) is selected to reduce topic-partition imbalance. """ broker_subset = broker_...
[ "def", "_elect_source_broker", "(", "self", ",", "victim_partition", ",", "broker_subset", "=", "None", ")", ":", "broker_subset", "=", "broker_subset", "or", "self", ".", "_brokers", "over_loaded_brokers", "=", "sorted", "(", "[", "broker", "for", "broker", "in...
35.25
17.535714
def import_classes(names, src, dst): """Import classes in package from their implementation modules.""" for name in names: module = importlib.import_module('pygsp.' + src + '.' + name.lower()) setattr(sys.modules['pygsp.' + dst], name, getattr(module, name))
[ "def", "import_classes", "(", "names", ",", "src", ",", "dst", ")", ":", "for", "name", "in", "names", ":", "module", "=", "importlib", ".", "import_module", "(", "'pygsp.'", "+", "src", "+", "'.'", "+", "name", ".", "lower", "(", ")", ")", "setattr"...
55.6
18.4
def remember_order(self): """Verify that subsequent :func:`fudge.Fake.expects` are called in the right order. For example:: >>> import fudge >>> db = fudge.Fake('db').remember_order().expects('insert').expects('update') >>> db.update() Traceback (most re...
[ "def", "remember_order", "(", "self", ")", ":", "if", "self", ".", "_callable", ":", "raise", "FakeDeclarationError", "(", "\"remember_order() cannot be used for Fake(callable=True) or Fake(expect_call=True)\"", ")", "self", ".", "_expected_call_order", "=", "ExpectedCallOrde...
38.578947
24.736842
def indir(path): """ Context manager for switching the current path of the process. Can be used: with indir('/tmp'): <do something in tmp> """ cwd = os.getcwd() try: os.chdir(path) yield except Exception as e: raise finally: os.chdir(cwd)
[ "def", "indir", "(", "path", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "try", ":", "os", ".", "chdir", "(", "path", ")", "yield", "except", "Exception", "as", "e", ":", "raise", "finally", ":", "os", ".", "chdir", "(", "cwd", ")" ]
19.0625
21.6875
def find(cls, name): """Returns the NDS2 channel type corresponding to the given name """ try: return cls._member_map_[name] except KeyError: for ctype in cls._member_map_.values(): if ctype.name == name: return ctype ...
[ "def", "find", "(", "cls", ",", "name", ")", ":", "try", ":", "return", "cls", ".", "_member_map_", "[", "name", "]", "except", "KeyError", ":", "for", "ctype", "in", "cls", ".", "_member_map_", ".", "values", "(", ")", ":", "if", "ctype", ".", "na...
37.6
12.1
def SetPixelColorsHorizontally(self, x: int, y: int, colors: Iterable) -> bool: """ Set pixel colors form x,y horizontally. x: int. y: int. colors: Iterable, an iterable list of int color values in argb. Return bool, True if succeed otherwise False. """ co...
[ "def", "SetPixelColorsHorizontally", "(", "self", ",", "x", ":", "int", ",", "y", ":", "int", ",", "colors", ":", "Iterable", ")", "->", "bool", ":", "count", "=", "len", "(", "colors", ")", "arrayType", "=", "ctypes", ".", "c_uint32", "*", "count", ...
43.916667
20.083333
def sessions_in_range(self, start_session_label, end_session_label): """ Given start and end session labels, return all the sessions in that range, inclusive. Parameters ---------- start_session_label: pd.Timestamp (midnight UTC) The label representing the fi...
[ "def", "sessions_in_range", "(", "self", ",", "start_session_label", ",", "end_session_label", ")", ":", "return", "self", ".", "all_sessions", "[", "self", ".", "all_sessions", ".", "slice_indexer", "(", "start_session_label", ",", "end_session_label", ")", "]" ]
30.75
20.5
def validate(self, object_dict, partial=False): """Validate given internal object returned by ``to_representation()``. Internal object is validated against missing/forbidden/invalid fields values using fields definitions defined in serializer. Args: object_dict (dict): inte...
[ "def", "validate", "(", "self", ",", "object_dict", ",", "partial", "=", "False", ")", ":", "# we are working on object_dict not an representation so there", "# is a need to annotate sources differently", "sources", "=", "{", "_source", "(", "name", ",", "field", ")", "...
37.423077
20.948718
def gradient_plots(self, analytes=None, win=15, samples=None, ranges=False, focus=None, outdir=None, figsize=[10, 4], subset='All_Analyses'): """ Plot analyte gradients as a function of time. Parameters ---------- analytes : optional...
[ "def", "gradient_plots", "(", "self", ",", "analytes", "=", "None", ",", "win", "=", "15", ",", "samples", "=", "None", ",", "ranges", "=", "False", ",", "focus", "=", "None", ",", "outdir", "=", "None", ",", "figsize", "=", "[", "10", ",", "4", ...
39.266667
18.493333
def create_label(self, label, doc=None, callback=dummy_progress_cb): """ Create a new label Arguments: doc --- first document on which the label must be added (required for now) """ if doc: clone = doc.clone() # make sure it's seriali...
[ "def", "create_label", "(", "self", ",", "label", ",", "doc", "=", "None", ",", "callback", "=", "dummy_progress_cb", ")", ":", "if", "doc", ":", "clone", "=", "doc", ".", "clone", "(", ")", "# make sure it's serializable", "r", "=", "self", ".", "index"...
32.083333
19.75
def split(self, grouper): '''Split the current DenseRunVariable into multiple columns. Parameters ---------- grouper : :obj:`pandas.DataFrame` Binary DF specifying the design matrix to use for splitting. Number of rows must match current ``DenseRunVariable``; a n...
[ "def", "split", "(", "self", ",", "grouper", ")", ":", "values", "=", "grouper", ".", "values", "*", "self", ".", "values", ".", "values", "df", "=", "pd", ".", "DataFrame", "(", "values", ",", "columns", "=", "grouper", ".", "columns", ")", "return"...
44.090909
23.909091
def remove_core_element(self, model): """Remove respective core element of handed global variable name :param str model: String that is the key/gv_name of core element which should be removed :return: """ gv_name = model if self.global_variable_is_editable(gv_name, "Dele...
[ "def", "remove_core_element", "(", "self", ",", "model", ")", ":", "gv_name", "=", "model", "if", "self", ".", "global_variable_is_editable", "(", "gv_name", ",", "\"Deletion\"", ")", ":", "try", ":", "self", ".", "model", ".", "global_variable_manager", ".", ...
45.769231
22.307692
def dropna(self, axis=0, how='any', thresh=None, subset=None, inplace=False): """ Remove missing values. See the :ref:`User Guide <missing_data>` for more on which values are considered missing, and how to work with missing data. Parameters ---------- ...
[ "def", "dropna", "(", "self", ",", "axis", "=", "0", ",", "how", "=", "'any'", ",", "thresh", "=", "None", ",", "subset", "=", "None", ",", "inplace", "=", "False", ")", ":", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "'inplace'", ")...
33.722973
19.52027
def execute(tokens): """ Perform the actions described by the input tokens. """ if not validate_rc(): print('Your .vacationrc file has errors!') echo_vacation_rc() return for action, value in tokens: if action == 'show': show() elif action == 'log': ...
[ "def", "execute", "(", "tokens", ")", ":", "if", "not", "validate_rc", "(", ")", ":", "print", "(", "'Your .vacationrc file has errors!'", ")", "echo_vacation_rc", "(", ")", "return", "for", "action", ",", "value", "in", "tokens", ":", "if", "action", "==", ...
28.318182
13.590909
def send_offer_email(self, offer_id, email_dict): """ Sends an offer by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param offer_id: the invoice id :param email_dict: the email d...
[ "def", "send_offer_email", "(", "self", ",", "offer_id", ",", "email_dict", ")", ":", "return", "self", ".", "_create_post_request", "(", "resource", "=", "OFFERS", ",", "billomat_id", "=", "offer_id", ",", "send_data", "=", "email_dict", ",", "command", "=", ...
32.3125
13.5625
def create_oracle(self, **kwargs): """ :rtype: Engine """ return self._ce( self._ccs(self.DialectAndDriver.oracle), **kwargs )
[ "def", "create_oracle", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_ce", "(", "self", ".", "_ccs", "(", "self", ".", "DialectAndDriver", ".", "oracle", ")", ",", "*", "*", "kwargs", ")" ]
24.571429
13.142857
def createEditor( self, parent, option, index ): """ Overloads the create editor method to assign the parent's completer to any line edit created. :param parent | <QWidget> option | <QStyleOption> index | <QModelIndex> ...
[ "def", "createEditor", "(", "self", ",", "parent", ",", "option", ",", "index", ")", ":", "multi_tag", "=", "projexui", ".", "ancestor", "(", "self", ",", "XMultiTagEdit", ")", "edit", "=", "QLineEdit", "(", "parent", ")", "edit", ".", "setFrame", "(", ...
32.368421
13.736842