text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def start(self, user_func, refresh): """ Start the SNMP's protocol handler and the updater thread user_func is a reference to an update function, ran every 'refresh' seconds. """ self.update=user_func self.refresh=refresh self.error=None # First load self.update() self.commit() # Start updater t...
[ "def", "start", "(", "self", ",", "user_func", ",", "refresh", ")", ":", "self", ".", "update", "=", "user_func", "self", ".", "refresh", "=", "refresh", "self", ".", "error", "=", "None", "# First load", "self", ".", "update", "(", ")", "self", ".", ...
22.32
0.051546
def getKeyword(filename, keyword, default=None, handle=None): """ General, write-safe method for returning a keyword value from the header of a IRAF recognized image. Returns the value as a string. """ # Insure that there is at least 1 extension specified... if filename.find('[') < 0: ...
[ "def", "getKeyword", "(", "filename", ",", "keyword", ",", "default", "=", "None", ",", "handle", "=", "None", ")", ":", "# Insure that there is at least 1 extension specified...", "if", "filename", ".", "find", "(", "'['", ")", "<", "0", ":", "filename", "+="...
31.560606
0.001862
def build_h5_array(data, samples, nloci): """ Sets up all of the h5 arrays that we will fill. The catg array of prefiltered loci is 4-dimensional (Big), so one big array would overload memory, we need to fill it in slices. This will be done in multicat (singlecat) and fill_superseqs. """ ...
[ "def", "build_h5_array", "(", "data", ",", "samples", ",", "nloci", ")", ":", "## sort to ensure samples will be in alphabetical order, tho they should be.", "samples", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "name", ")", "## get maxlen dim", "ma...
44.863014
0.008963
def unqueue_and_display(self, filename): """Unqueue messages and give feedback to user (if necessary).""" if self.running and self.ws: self.editor.lazy_display_error(filename) self.unqueue()
[ "def", "unqueue_and_display", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "running", "and", "self", ".", "ws", ":", "self", ".", "editor", ".", "lazy_display_error", "(", "filename", ")", "self", ".", "unqueue", "(", ")" ]
45.2
0.008696
def _get_project_conf(): """Loads configuration from project config file.""" config_settings = {} project_root = find_vcs_root(".") if project_root is None: return config_settings for conf_dir in PROJECT_CONF_DIRS: conf_dir = conf_dir.lstrip("./") joined_dir = os.path.join(...
[ "def", "_get_project_conf", "(", ")", ":", "config_settings", "=", "{", "}", "project_root", "=", "find_vcs_root", "(", "\".\"", ")", "if", "project_root", "is", "None", ":", "return", "config_settings", "for", "conf_dir", "in", "PROJECT_CONF_DIRS", ":", "conf_d...
33.933333
0.00191
def get_3D_coordmap(img): ''' Gets a 3D CoordinateMap from img. Parameters ---------- img: nib.Nifti1Image or nipy Image Returns ------- nipy.core.reference.coordinate_map.CoordinateMap ''' if isinstance(img, nib.Nifti1Image): img = nifti2nipy(img) if img.ndim == 4...
[ "def", "get_3D_coordmap", "(", "img", ")", ":", "if", "isinstance", "(", "img", ",", "nib", ".", "Nifti1Image", ")", ":", "img", "=", "nifti2nipy", "(", "img", ")", "if", "img", ".", "ndim", "==", "4", ":", "from", "nipy", ".", "core", ".", "refere...
20.909091
0.002079
def collect_exceptions(rdict_or_list, method='unspecified'): """check a result dict for errors, and raise CompositeError if any exist. Passthrough otherwise.""" elist = [] if isinstance(rdict_or_list, dict): rlist = rdict_or_list.values() else: rlist = rdict_or_list for r in rlis...
[ "def", "collect_exceptions", "(", "rdict_or_list", ",", "method", "=", "'unspecified'", ")", ":", "elist", "=", "[", "]", "if", "isinstance", "(", "rdict_or_list", ",", "dict", ")", ":", "rlist", "=", "rdict_or_list", ".", "values", "(", ")", "else", ":", ...
40.066667
0.002437
def _get_best_effort_ndims(x, expect_ndims=None, expect_ndims_at_least=None, expect_ndims_no_more_than=None): """Get static ndims if possible. Fallback on `tf.rank(x)`.""" ndims_static = _get_static_ndims( x, expect_ndims=...
[ "def", "_get_best_effort_ndims", "(", "x", ",", "expect_ndims", "=", "None", ",", "expect_ndims_at_least", "=", "None", ",", "expect_ndims_no_more_than", "=", "None", ")", ":", "ndims_static", "=", "_get_static_ndims", "(", "x", ",", "expect_ndims", "=", "expect_n...
38.923077
0.009653
def populate_readme( version, circleci_build, appveyor_build, coveralls_build, travis_build ): """Populates ``README.rst`` with release-specific data. This is because ``README.rst`` is used on PyPI. Args: version (str): The current version. circleci_build (Union[str, int]): The CircleC...
[ "def", "populate_readme", "(", "version", ",", "circleci_build", ",", "appveyor_build", ",", "coveralls_build", ",", "travis_build", ")", ":", "with", "open", "(", "RELEASE_README_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".",...
35.62069
0.000943
def establish_connection(self, width=None, height=None): """Establish SSH connection to the network device Timeout will generate a NetMikoTimeoutException Authentication failure will generate a NetMikoAuthenticationException width and height are needed for Fortinet paging setting. ...
[ "def", "establish_connection", "(", "self", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "if", "self", ".", "protocol", "==", "\"telnet\"", ":", "self", ".", "remote_conn", "=", "telnetlib", ".", "Telnet", "(", "self", ".", "host", ...
41.761905
0.001857
def load_data_and_labels(filename, encoding='utf-8'): """Loads data and label from a file. Args: filename (str): path to the file. encoding (str): file encoding format. The file format is tab-separated values. A blank line is required at the end of a sentence. For exam...
[ "def", "load_data_and_labels", "(", "filename", ",", "encoding", "=", "'utf-8'", ")", ":", "sents", ",", "labels", "=", "[", "]", ",", "[", "]", "words", ",", "tags", "=", "[", "]", ",", "[", "]", "with", "open", "(", "filename", ",", "encoding", "...
23.632653
0.000829
def _normalize_data(stream, date_format=None): """ This function is meant to normalize data for upload to the Luminoso Analytics system. Currently it only normalizes dates. If date_format is not specified, or if there's no date in a particular doc, the the doc is yielded unchanged. """ for ...
[ "def", "_normalize_data", "(", "stream", ",", "date_format", "=", "None", ")", ":", "for", "doc", "in", "stream", ":", "if", "'date'", "in", "doc", "and", "date_format", "is", "not", "None", ":", "try", ":", "doc", "[", "'date'", "]", "=", "_convert_da...
43.315789
0.001189
def nlargest(self, n, columns, keep='first'): """ Return the first `n` rows ordered by `columns` in descending order. Return the first `n` rows with the largest values in `columns`, in descending order. The columns that are not specified are returned as well, but not used for or...
[ "def", "nlargest", "(", "self", ",", "n", ",", "columns", ",", "keep", "=", "'first'", ")", ":", "return", "algorithms", ".", "SelectNFrame", "(", "self", ",", "n", "=", "n", ",", "keep", "=", "keep", ",", "columns", "=", "columns", ")", ".", "nlar...
39.54955
0.000444
def make_commodity_future_info(first_sid, root_symbols, years, month_codes=None, multiplier=500): """ Make futures testing data that simulates the notice/expiration date behavior of ph...
[ "def", "make_commodity_future_info", "(", "first_sid", ",", "root_symbols", ",", "years", ",", "month_codes", "=", "None", ",", "multiplier", "=", "500", ")", ":", "nineteen_days", "=", "pd", ".", "Timedelta", "(", "days", "=", "19", ")", "one_year", "=", ...
37.5
0.000591
def cancel_reservation(self): """ This method cancel record set for hotel room reservation line ------------------------------------------------------------------ @param self: The object pointer @return: cancel record set for hotel room reservation line. """ room_...
[ "def", "cancel_reservation", "(", "self", ")", ":", "room_res_line_obj", "=", "self", ".", "env", "[", "'hotel.room.reservation.line'", "]", "hotel_res_line_obj", "=", "self", ".", "env", "[", "'hotel_reservation.line'", "]", "self", ".", "state", "=", "'cancel'",...
52.15
0.001883
def autocomplete(self, sources): """Autocomplete unique identities profiles. Autocomplete unique identities profiles using the information of their identities. The selection of the data used to fill the profile is prioritized using a list of sources. """ email_pattern = ...
[ "def", "autocomplete", "(", "self", ",", "sources", ")", ":", "email_pattern", "=", "re", ".", "compile", "(", "EMAIL_ADDRESS_REGEX", ")", "identities", "=", "self", ".", "__select_autocomplete_identities", "(", "sources", ")", "for", "uuid", ",", "ids", "in",...
34.565217
0.001223
def config_keys(self, sortkey = False): """ Return all configuration keys in this node, including configurations on children nodes. """ if sortkey: items = sorted(self.items()) else: items = self.items() for k,v in items: if isinstance(...
[ "def", "config_keys", "(", "self", ",", "sortkey", "=", "False", ")", ":", "if", "sortkey", ":", "items", "=", "sorted", "(", "self", ".", "items", "(", ")", ")", "else", ":", "items", "=", "self", ".", "items", "(", ")", "for", "k", ",", "v", ...
32.357143
0.012876
def fetch_vest_scores(vest_dict, ref_aa, somatic_aa, codon_pos, default_vest=0.0): """Get VEST scores from pre-computed scores in dictionary. Note: either all mutations should be missense or non-missense intended to have value equal to default. Parameters ...
[ "def", "fetch_vest_scores", "(", "vest_dict", ",", "ref_aa", ",", "somatic_aa", ",", "codon_pos", ",", "default_vest", "=", "0.0", ")", ":", "vest_score_list", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "somatic_aa", ")", ")", ":", "# mak...
32.571429
0.001704
def _compute_zs_mat(sz:TensorImageSize, scale:float, squish:float, invert:bool, row_pct:float, col_pct:float)->AffineMatrix: "Utility routine to compute zoom/squish matrix." orig_ratio = math.sqrt(sz[1]/sz[0]) for s,r,i in zip(scale,squish, invert): s,r = 1/math.sqrt(s),math.sqrt(...
[ "def", "_compute_zs_mat", "(", "sz", ":", "TensorImageSize", ",", "scale", ":", "float", ",", "squish", ":", "float", ",", "invert", ":", "bool", ",", "row_pct", ":", "float", ",", "col_pct", ":", "float", ")", "->", "AffineMatrix", ":", "orig_ratio", "=...
53.266667
0.02829
def calc_gradient(beta, design, alt_IDs, rows_to_obs, rows_to_alts, choice_vector, utility_transform, transform_first_deriv_c, transform_first_deriv_v, transf...
[ "def", "calc_gradient", "(", "beta", ",", "design", ",", "alt_IDs", ",", "rows_to_obs", ",", "rows_to_alts", ",", "choice_vector", ",", "utility_transform", ",", "transform_first_deriv_c", ",", "transform_first_deriv_v", ",", "transform_deriv_alpha", ",", "intercept_par...
51.639594
0.000096
def finalize(self): """finalize for StatisticsConsumer""" super(StatisticsConsumer, self).finalize() # run statistics on timewave slice w at grid point g # self.result = [(g, self.statistics(w)) for g, w in zip(self.grid, self.result)] # self.result = zip(self.grid, (self.statist...
[ "def", "finalize", "(", "self", ")", ":", "super", "(", "StatisticsConsumer", ",", "self", ")", ".", "finalize", "(", ")", "# run statistics on timewave slice w at grid point g", "# self.result = [(g, self.statistics(w)) for g, w in zip(self.grid, self.result)]", "# self.result =...
59.285714
0.009501
def do_paste(self, event): """ Read clipboard into dataframe Paste data into grid, adding extra rows if needed and ignoring extra columns. """ # find where the user has clicked col_ind = self.GetGridCursorCol() row_ind = self.GetGridCursorRow() # r...
[ "def", "do_paste", "(", "self", ",", "event", ")", ":", "# find where the user has clicked", "col_ind", "=", "self", ".", "GetGridCursorCol", "(", ")", "row_ind", "=", "self", ".", "GetGridCursorRow", "(", ")", "# read in clipboard text", "text_df", "=", "pd", "...
43.081081
0.00184
def diff_one(model1, model2, **kwargs): """Find difference between given peewee models.""" changes = [] fields1 = model1._meta.fields fields2 = model2._meta.fields # Add fields names1 = set(fields1) - set(fields2) if names1: fields = [fields1[name] for name in names1] chang...
[ "def", "diff_one", "(", "model1", ",", "model2", ",", "*", "*", "kwargs", ")", ":", "changes", "=", "[", "]", "fields1", "=", "model1", ".", "_meta", ".", "fields", "fields2", "=", "model2", ".", "_meta", ".", "fields", "# Add fields", "names1", "=", ...
28.461538
0.000653
def add_dependency(self, from_task_name, to_task_name): """ Add a dependency between two tasks. """ logger.debug('Adding dependency from {0} to {1}'.format(from_task_name, to_task_name)) if not self.state.allow_change_graph: raise DagobahError("job's graph is immutable in its curren...
[ "def", "add_dependency", "(", "self", ",", "from_task_name", ",", "to_task_name", ")", ":", "logger", ".", "debug", "(", "'Adding dependency from {0} to {1}'", ".", "format", "(", "from_task_name", ",", "to_task_name", ")", ")", "if", "not", "self", ".", "state"...
45
0.008715
def decimal_date(dateobs, timeobs=None): """Convert DATE-OBS (and optional TIME-OBS) into a decimal year.""" year, month, day = dateobs.split('-') if timeobs is not None: hr, min, sec = timeobs.split(':') else: hr, min, sec = 0, 0, 0 rdate = datetime.datetime(int(year), int(month),...
[ "def", "decimal_date", "(", "dateobs", ",", "timeobs", "=", "None", ")", ":", "year", ",", "month", ",", "day", "=", "dateobs", ".", "split", "(", "'-'", ")", "if", "timeobs", "is", "not", "None", ":", "hr", ",", "min", ",", "sec", "=", "timeobs", ...
35.0625
0.001736
def load_pyassimp(file_obj, file_type=None, resolver=None, **kwargs): """ Use the pyassimp library to load a mesh from a file object and type or file name if file_obj is a string Parameters --------- file_obj: str, or file object File ...
[ "def", "load_pyassimp", "(", "file_obj", ",", "file_type", "=", "None", ",", "resolver", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "LP_to_TM", "(", "lp", ")", ":", "# try to get the vertex colors attribute", "colors", "=", "(", "np", ".", "res...
33.541096
0.000198
def check_time_only(time, signal, verb): r"""Check time and signal parameters. This check-function is called from one of the modelling routines in :mod:`model`. Consult these modelling routines for a detailed description of the input parameters. Parameters ---------- time : array_like ...
[ "def", "check_time_only", "(", "time", ",", "signal", ",", "verb", ")", ":", "global", "_min_time", "# Check input signal", "if", "int", "(", "signal", ")", "not", "in", "[", "-", "1", ",", "0", ",", "1", "]", ":", "print", "(", "\"* ERROR :: <signal> ...
27.106383
0.000758
def group_perms_for_user(cls, instance, user, db_session=None): """ returns permissions that given user has for this resource that are inherited from groups :param instance: :param user: :param db_session: :return: """ db_session = get_db_sess...
[ "def", "group_perms_for_user", "(", "cls", ",", "instance", ",", "user", ",", "db_session", "=", "None", ")", ":", "db_session", "=", "get_db_session", "(", "db_session", ",", "instance", ")", "perms", "=", "resource_permissions_for_users", "(", "cls", ".", "m...
33.117647
0.001726
def verify_multi(self, otp_list, max_time_window=DEFAULT_MAX_TIME_WINDOW, sl=None, timeout=None): """ Verify a provided list of OTPs. :param max_time_window: Maximum number of seconds which can pass between the first and last OTP generation f...
[ "def", "verify_multi", "(", "self", ",", "otp_list", ",", "max_time_window", "=", "DEFAULT_MAX_TIME_WINDOW", ",", "sl", "=", "None", ",", "timeout", "=", "None", ")", ":", "# Create the OTP objects", "otps", "=", "[", "]", "for", "otp", "in", "otp_list", ":"...
36.070175
0.00142
def com_google_fonts_check_all_glyphs_have_codepoints(ttFont): """Check all glyphs have codepoints assigned.""" failed = False for subtable in ttFont['cmap'].tables: if subtable.isUnicode(): for item in subtable.cmap.items(): codepoint = item[0] if codepoint is None: failed = T...
[ "def", "com_google_fonts_check_all_glyphs_have_codepoints", "(", "ttFont", ")", ":", "failed", "=", "False", "for", "subtable", "in", "ttFont", "[", "'cmap'", "]", ".", "tables", ":", "if", "subtable", ".", "isUnicode", "(", ")", ":", "for", "item", "in", "s...
38.923077
0.015444
def open( self, hostname: Optional[str], username: Optional[str], password: Optional[str], port: Optional[int], platform: Optional[str], extras: Optional[Dict[str, Any]] = None, configuration: Optional[Config] = None, ) -> None: """ Con...
[ "def", "open", "(", "self", ",", "hostname", ":", "Optional", "[", "str", "]", ",", "username", ":", "Optional", "[", "str", "]", ",", "password", ":", "Optional", "[", "str", "]", ",", "port", ":", "Optional", "[", "int", "]", ",", "platform", ":"...
28.933333
0.008929
def log_handlers(opts): ''' Returns the custom logging handler modules :param dict opts: The Salt options dictionary ''' ret = LazyLoader( _module_dirs( opts, 'log_handlers', int_type='handlers', base_path=os.path.join(SALT_BASE_PATH, 'log'), ...
[ "def", "log_handlers", "(", "opts", ")", ":", "ret", "=", "LazyLoader", "(", "_module_dirs", "(", "opts", ",", "'log_handlers'", ",", "int_type", "=", "'handlers'", ",", "base_path", "=", "os", ".", "path", ".", "join", "(", "SALT_BASE_PATH", ",", "'log'",...
24.411765
0.00232
def get_nodes(self, request): """ Return menu's node for entries """ nodes = [] archives = [] attributes = {'hidden': HIDE_ENTRY_MENU} for entry in Entry.published.all(): year = entry.creation_date.strftime('%Y') month = entry.creation_date...
[ "def", "get_nodes", "(", "self", ",", "request", ")", ":", "nodes", "=", "[", "]", "archives", "=", "[", "]", "attributes", "=", "{", "'hidden'", ":", "HIDE_ENTRY_MENU", "}", "for", "entry", "in", "Entry", ".", "published", ".", "all", "(", ")", ":",...
41.714286
0.001115
def read(self, addr, size): """! @brief Read program data from the elf file. @param addr Physical address (load address) to read from. @param size Number of bytes to read. @return Requested data or None if address is unmapped. """ for segment in self._elf.iter_segments()...
[ "def", "read", "(", "self", ",", "addr", ",", "size", ")", ":", "for", "segment", "in", "self", ".", "_elf", ".", "iter_segments", "(", ")", ":", "seg_addr", "=", "segment", "[", "\"p_paddr\"", "]", "seg_size", "=", "min", "(", "segment", "[", "\"p_m...
39.666667
0.002345
def recursive_glob_with_tree(new_base, old_base, treeroot, pattern): '''generate a list of tuples(new_base, list(paths to put there) where the files are found inside of old_base/treeroot. ''' results = [] old_cwd = os.getcwd() os.chdir(old_base) for rel_base, dirs, files in os.walk(treeroot)...
[ "def", "recursive_glob_with_tree", "(", "new_base", ",", "old_base", ",", "treeroot", ",", "pattern", ")", ":", "results", "=", "[", "]", "old_cwd", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "old_base", ")", "for", "rel_base", ",", "...
40.266667
0.001618
def list_sets(family='ipv4'): ''' .. versionadded:: 2014.7.0 List all ipset sets. CLI Example: .. code-block:: bash salt '*' ipset.list_sets ''' cmd = '{0} list -t'.format(_ipset_cmd()) out = __salt__['cmd.run'](cmd, python_shell=False) _tmp = out.split('\n') count...
[ "def", "list_sets", "(", "family", "=", "'ipv4'", ")", ":", "cmd", "=", "'{0} list -t'", ".", "format", "(", "_ipset_cmd", "(", ")", ")", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ",", "python_shell", "=", "False", ")", "_tmp", "=", ...
18.793103
0.001745
def user_info(user, host='localhost', **connection_args): ''' Get full info on a MySQL user CLI Example: .. code-block:: bash salt '*' mysql.user_info root localhost ''' dbc = _connect(**connection_args) if dbc is None: return False cur = dbc.cursor(MySQLdb.cursors.Di...
[ "def", "user_info", "(", "user", ",", "host", "=", "'localhost'", ",", "*", "*", "connection_args", ")", ":", "dbc", "=", "_connect", "(", "*", "*", "connection_args", ")", "if", "dbc", "is", "None", ":", "return", "False", "cur", "=", "dbc", ".", "c...
24.225806
0.00128
def get_certificate_signing_request(self, **kwargs): """Construct a certificate signing request (CSR) for signing by a certificate authority (CA). :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: ...
[ "def", "get_certificate_signing_request", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_rest_version", ">=", "LooseVersion", "(", "\"1.12\"", ")", ":", "return", "self", ".", "_request", "(", "\"GET\"", ",", "\"cert/certificate_signing_req...
43
0.008936
def parseCatalogFile(filename): """parse an XML file and build a tree. It's like xmlParseFile() except it bypass all catalog lookups. """ ret = libxml2mod.xmlParseCatalogFile(filename) if ret is None:raise parserError('xmlParseCatalogFile() failed') return xmlDoc(_obj=ret)
[ "def", "parseCatalogFile", "(", "filename", ")", ":", "ret", "=", "libxml2mod", ".", "xmlParseCatalogFile", "(", "filename", ")", "if", "ret", "is", "None", ":", "raise", "parserError", "(", "'xmlParseCatalogFile() failed'", ")", "return", "xmlDoc", "(", "_obj",...
48.5
0.010135
def SlotSentinel(*args): """Provides exception handling for all slots""" # (NOTE) davidlatwe # Thanks to this answer # https://stackoverflow.com/questions/18740884 if len(args) == 0 or isinstance(args[0], types.FunctionType): args = [] @QtCore.pyqtSlot(*args) def slotdecorator(fun...
[ "def", "SlotSentinel", "(", "*", "args", ")", ":", "# (NOTE) davidlatwe", "# Thanks to this answer", "# https://stackoverflow.com/questions/18740884", "if", "len", "(", "args", ")", "==", "0", "or", "isinstance", "(", "args", "[", "0", "]", ",", "types", ".", "F...
24.952381
0.001838
def _Moran_BV_Matrix_array(variables, w, permutations=0, varnames=None): """ Base calculation for MORAN_BV_Matrix """ if varnames is None: varnames = ['x{}'.format(i) for i in range(k)] k = len(variables) rk = list(range(0, k - 1)) results = {} for i in rk: for j in rang...
[ "def", "_Moran_BV_Matrix_array", "(", "variables", ",", "w", ",", "permutations", "=", "0", ",", "varnames", "=", "None", ")", ":", "if", "varnames", "is", "None", ":", "varnames", "=", "[", "'x{}'", ".", "format", "(", "i", ")", "for", "i", "in", "r...
36.368421
0.00141
def terminate_process(self, idf): """ Terminate a process by id """ try: p = self.q.pop(idf) p.terminate() return p except: return None
[ "def", "terminate_process", "(", "self", ",", "idf", ")", ":", "try", ":", "p", "=", "self", ".", "q", ".", "pop", "(", "idf", ")", "p", ".", "terminate", "(", ")", "return", "p", "except", ":", "return", "None" ]
25
0.014493
def intersect(self, other, strategy=_STRATEGY.GEOMETRIC, _verify=True): """Find the common intersection with another surface. Args: other (Surface): Other surface to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorit...
[ "def", "intersect", "(", "self", ",", "other", ",", "strategy", "=", "_STRATEGY", ".", "GEOMETRIC", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "if", "not", "isinstance", "(", "other", ",", "Surface", ")", ":", "raise", "TypeError", "(...
38.241379
0.000879
def add_basic_block(self, basic_block): """Adds the given basic block in the function""" assert(isinstance(basic_block, BasicBlock)) self.basic_block_list.append(basic_block)
[ "def", "add_basic_block", "(", "self", ",", "basic_block", ")", ":", "assert", "(", "isinstance", "(", "basic_block", ",", "BasicBlock", ")", ")", "self", ".", "basic_block_list", ".", "append", "(", "basic_block", ")" ]
48.75
0.010101
def align(self, referencewords, datatuple): """align the reference sentence with the tagged data""" targetwords = [] for i, (word,lemma,postag) in enumerate(zip(datatuple[0],datatuple[1],datatuple[2])): if word: subwords = word.split("_") for w in subw...
[ "def", "align", "(", "self", ",", "referencewords", ",", "datatuple", ")", ":", "targetwords", "=", "[", "]", "for", "i", ",", "(", "word", ",", "lemma", ",", "postag", ")", "in", "enumerate", "(", "zip", "(", "datatuple", "[", "0", "]", ",", "data...
44.111111
0.026294
def main(): """Generate a TPIP report.""" parser = argparse.ArgumentParser(description='Generate a TPIP report as a CSV file.') parser.add_argument('output_filename', type=str, metavar='output-file', help='the output path and filename', nargs='?') parser.add_argument('--only', ty...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Generate a TPIP report as a CSV file.'", ")", "parser", ".", "add_argument", "(", "'output_filename'", ",", "type", "=", "str", ",", "metavar", "=", "'outp...
40.931034
0.002469
def itertuples(self, index=True, name="Pandas"): """ Iterate over DataFrame rows as namedtuples. Parameters ---------- index : bool, default True If True, return the index as the first element of the tuple. name : str or None, default "Pandas" The...
[ "def", "itertuples", "(", "self", ",", "index", "=", "True", ",", "name", "=", "\"Pandas\"", ")", ":", "arrays", "=", "[", "]", "fields", "=", "list", "(", "self", ".", "columns", ")", "if", "index", ":", "arrays", ".", "append", "(", "self", ".", ...
34.202532
0.000719
def djfrontend_jquery(version=None): """ Returns jQuery JavaScript file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback. Included in HTML5 Boilerplate. """ if version is None: version = getattr(settings, '...
[ "def", "djfrontend_jquery", "(", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "version", "=", "getattr", "(", "settings", ",", "'DJFRONTEND_JQUERY'", ",", "DJFRONTEND_JQUERY_DEFAULT", ")", "if", "getattr", "(", "settings", ",", "'TEMPL...
51.375
0.008363
def sortByName(self): """Qt Override.""" self.servers = sorted(self.servers, key=lambda x: x.language) self.reset()
[ "def", "sortByName", "(", "self", ")", ":", "self", ".", "servers", "=", "sorted", "(", "self", ".", "servers", ",", "key", "=", "lambda", "x", ":", "x", ".", "language", ")", "self", ".", "reset", "(", ")" ]
34
0.014388
def get_attributes(self, obj): """ Get all object's attributes. Sends multi-parameter info/config queries and returns the result as dictionary. :param obj: requested object. :returns: dictionary of <name, value> of all attributes returned by the query. :rtype: dict of (str, str...
[ "def", "get_attributes", "(", "self", ",", "obj", ")", ":", "return", "self", ".", "_get_attributes", "(", "'{}/{}'", ".", "format", "(", "self", ".", "session_url", ",", "obj", ".", "ref", ")", ")" ]
40.3
0.009709
def idmap_get_new(connection, old, tbl): """ From the old ID string, obtain a replacement ID string by either grabbing it from the _idmap_ table if one has already been assigned to the old ID, or by using the current value of the Table instance's next_id class attribute. In the latter case, the new ID is recorde...
[ "def", "idmap_get_new", "(", "connection", ",", "old", ",", "tbl", ")", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "\"SELECT new FROM _idmap_ WHERE old == ?\"", ",", "(", "old", ",", ")", ")", "new", "=", "cur...
38.869565
0.024017
def compute_sha256(path): """ Compute the SHA-256 hash of the file at the given path Parameters ---------- path: str The path of the file Returns ------- str The SHA-256 HEX digest """ hasher = hashlib.sha256() with open(path, 'rb') as f: # 10MB chun...
[ "def", "compute_sha256", "(", "path", ")", ":", "hasher", "=", "hashlib", ".", "sha256", "(", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "# 10MB chunks", "for", "chunk", "in", "iter", "(", "lambda", ":", "f", ".", "read", "...
21.6
0.002217
def handle_extra_source(self, source_df, sim_params): """ Extra sources always have a sid column. We expand the given data (by forward filling) to the full range of the simulation dates, so that lookup is fast during simulation. """ if source_df is None: retu...
[ "def", "handle_extra_source", "(", "self", ",", "source_df", ",", "sim_params", ")", ":", "if", "source_df", "is", "None", ":", "return", "# Normalize all the dates in the df", "source_df", ".", "index", "=", "source_df", ".", "index", ".", "normalize", "(", ")"...
43.887324
0.000628
def link(self): """str: full path of the linked file entry.""" if self._link is None: self._link = '' if not self.IsLink(): return self._link location = getattr(self.path_spec, 'location', None) if location is None: return self._link self._link = os.readlink(loca...
[ "def", "link", "(", "self", ")", ":", "if", "self", ".", "_link", "is", "None", ":", "self", ".", "_link", "=", "''", "if", "not", "self", ".", "IsLink", "(", ")", ":", "return", "self", ".", "_link", "location", "=", "getattr", "(", "self", ".",...
25.333333
0.017766
def route_frequencies(gtfs, results_by_mode=False): """ Return the frequency of all types of routes per day. Parameters ----------- gtfs: GTFS Returns ------- pandas.DataFrame with columns route_I, type, frequency """ day = gtfs.get_suitable_date_for_daily_extract() ...
[ "def", "route_frequencies", "(", "gtfs", ",", "results_by_mode", "=", "False", ")", ":", "day", "=", "gtfs", ".", "get_suitable_date_for_daily_extract", "(", ")", "query", "=", "(", "\" SELECT f.route_I, type, frequency FROM routes as r\"", "\" JOIN\"", "\" (SELECT route_...
28.071429
0.00246
def setup_errors(app, error_template="error.html"): """Add a handler for each of the available HTTP error responses.""" def error_handler(error): if isinstance(error, HTTPException): description = error.get_description(request.environ) code = error.code name = error.n...
[ "def", "setup_errors", "(", "app", ",", "error_template", "=", "\"error.html\"", ")", ":", "def", "error_handler", "(", "error", ")", ":", "if", "isinstance", "(", "error", ",", "HTTPException", ")", ":", "description", "=", "error", ".", "get_description", ...
40.684211
0.001264
def do_get(url, params, to=3): """ 使用 ``request.get`` 从指定 url 获取数据 :param params: ``输入参数, 可为空`` :type params: dict :param url: ``接口地址`` :type url: :param to: ``响应超时返回时间`` :type to: :return: ``接口返回的数据`` :rtype: dict """ try: rs = requests.get(url, params=params, t...
[ "def", "do_get", "(", "url", ",", "params", ",", "to", "=", "3", ")", ":", "try", ":", "rs", "=", "requests", ".", "get", "(", "url", ",", "params", "=", "params", ",", "timeout", "=", "to", ")", "if", "rs", ".", "status_code", "==", "200", ":"...
25.08
0.001536
def download(data_dir): """Download census data if it is not already present.""" tf.gfile.MakeDirs(data_dir) training_file_path = os.path.join(data_dir, TRAINING_FILE) if not tf.gfile.Exists(training_file_path): _download_and_clean_file(training_file_path, TRAINING_URL) eval_file_path = os.path.join(dat...
[ "def", "download", "(", "data_dir", ")", ":", "tf", ".", "gfile", ".", "MakeDirs", "(", "data_dir", ")", "training_file_path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "TRAINING_FILE", ")", "if", "not", "tf", ".", "gfile", ".", "Exist...
38.545455
0.016129
def get_compute_sig(self) -> Signature: """ Compute a signature Using resolution!!! TODO: discuss of relevance of a final generation for a signature """ tret = [] tparams = [] for t in self.tret.components: if t in self.resolution and self.resolution[...
[ "def", "get_compute_sig", "(", "self", ")", "->", "Signature", ":", "tret", "=", "[", "]", "tparams", "=", "[", "]", "for", "t", "in", "self", ".", "tret", ".", "components", ":", "if", "t", "in", "self", ".", "resolution", "and", "self", ".", "res...
41.292683
0.001731
def notice(self, msg, *args, **kw): """Log a message with level :data:`NOTICE`. The arguments are interpreted as for :func:`logging.debug()`.""" if self.isEnabledFor(NOTICE): self._log(NOTICE, msg, args, **kw)
[ "def", "notice", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "self", ".", "isEnabledFor", "(", "NOTICE", ")", ":", "self", ".", "_log", "(", "NOTICE", ",", "msg", ",", "args", ",", "*", "*", "kw", ")" ]
58.5
0.012658
def is_dicom_file(filepath): """ Tries to read the file using dicom.read_file, if the file exists and dicom.read_file does not raise and Exception returns True. False otherwise. :param filepath: str Path to DICOM file :return: bool """ if not os.path.exists(filepath): rais...
[ "def", "is_dicom_file", "(", "filepath", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "raise", "IOError", "(", "'File {} not found.'", ".", "format", "(", "filepath", ")", ")", "filename", "=", "os", ".", "path", ...
25.423077
0.001458
def sendline(command, method='cli_show_ascii', **kwargs): ''' Send arbitrary show or config commands to the NX-OS device. command The command to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ``cli_show``: Return structured output. ``cli_co...
[ "def", "sendline", "(", "command", ",", "method", "=", "'cli_show_ascii'", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "CONNECTION", "==", "'ssh'", ":", "result", "=", "_sendline_ssh", "(", "command", ",", "*", "*", "kwargs", ")", "elif", "CON...
33.096774
0.001894
def set_auto_page_break(self, auto,margin=0): "Set auto page break mode and triggering margin" self.auto_page_break=auto self.b_margin=margin self.page_break_trigger=self.h-margin
[ "def", "set_auto_page_break", "(", "self", ",", "auto", ",", "margin", "=", "0", ")", ":", "self", ".", "auto_page_break", "=", "auto", "self", ".", "b_margin", "=", "margin", "self", ".", "page_break_trigger", "=", "self", ".", "h", "-", "margin" ]
41.4
0.028436
def import_certificate( ctx, slot, management_key, pin, cert, password, verify): """ Import a X.509 certificate. Write a certificate to one of the slots on the YubiKey. \b SLOT PIV slot to import the certificate to. CERTIFICATE File containing the certificate. Use '-' to...
[ "def", "import_certificate", "(", "ctx", ",", "slot", ",", "management_key", ",", "pin", ",", "cert", ",", "password", ",", "verify", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "contr...
30.983607
0.000513
def _get_upload_session_status(res): """Parse the image upload response to obtain status. Args: res: http_utils.FetchResponse instance, the upload response Returns: dict, sessionStatus of the response Raises: hangups.NetworkError: If the upload requ...
[ "def", "_get_upload_session_status", "(", "res", ")", ":", "response", "=", "json", ".", "loads", "(", "res", ".", "body", ".", "decode", "(", ")", ")", "if", "'sessionStatus'", "not", "in", "response", ":", "try", ":", "info", "=", "(", "response", "[...
35.703704
0.00202
def checkcache(filename=None, opts=False): """Discard cache entries that are out of date. If *filename* is *None* all entries in the file cache *file_cache* are checked. If we do not have stat information about a file it will be kept. Return a list of invalidated filenames. None is returned if a filen...
[ "def", "checkcache", "(", "filename", "=", "None", ",", "opts", "=", "False", ")", ":", "if", "isinstance", "(", "opts", ",", "dict", ")", ":", "use_linecache_lines", "=", "opts", "[", "'use_linecache_lines'", "]", "else", ":", "use_linecache_lines", "=", ...
33.815789
0.002269
def show_page(self): """ Display main course list page """ username = self.user_manager.session_username() user_info = self.database.users.find_one({"username": username}) all_courses = self.course_factory.get_all_courses() # Display open_courses = {courseid: course for...
[ "def", "show_page", "(", "self", ")", ":", "username", "=", "self", ".", "user_manager", ".", "session_username", "(", ")", "user_info", "=", "self", ".", "database", ".", "users", ".", "find_one", "(", "{", "\"username\"", ":", "username", "}", ")", "al...
55
0.00813
def init_lsh(self): """ Initializes locality-sensitive hashing with FALCONN to find nearest neighbors in training data. """ self.query_objects = { } # contains the object that can be queried to find nearest neighbors at each layer. # mean of training data representation per layer (that needs to...
[ "def", "init_lsh", "(", "self", ")", ":", "self", ".", "query_objects", "=", "{", "}", "# contains the object that can be queried to find nearest neighbors at each layer.", "# mean of training data representation per layer (that needs to be substracted before LSH).", "self", ".", "ce...
46.288889
0.017395
def create_module(self, spec): """Creates the module, and also insert it into sys.modules, adding this onto py2 import logic.""" mod = sys.modules.setdefault(spec.name, types.ModuleType(spec.name)) # we are using setdefault to satisfy https://docs.python.org/3/reference/import.html#loaders ...
[ "def", "create_module", "(", "self", ",", "spec", ")", ":", "mod", "=", "sys", ".", "modules", ".", "setdefault", "(", "spec", ".", "name", ",", "types", ".", "ModuleType", "(", "spec", ".", "name", ")", ")", "# we are using setdefault to satisfy https://doc...
65.8
0.012012
def create_choice(klass, choices, subsets, kwargs): """Create an instance of a ``Choices`` object. Parameters ---------- klass : type The class to use to recreate the object. choices : list(tuple) A list of choices as expected by the ``__init__`` method of ``klass``. subsets : l...
[ "def", "create_choice", "(", "klass", ",", "choices", ",", "subsets", ",", "kwargs", ")", ":", "obj", "=", "klass", "(", "*", "choices", ",", "*", "*", "kwargs", ")", "for", "subset", "in", "subsets", ":", "obj", ".", "add_subset", "(", "*", "subset"...
30.296296
0.00237
def minus(repo_list_a, repo_list_b): """Method to create a list of repositories such that the repository belongs to repo list a but not repo list b. In an ideal scenario we should be able to do this by set(a) - set(b) but as GithubRepositories have shown that set() on them is not reliab...
[ "def", "minus", "(", "repo_list_a", ",", "repo_list_b", ")", ":", "included", "=", "defaultdict", "(", "lambda", ":", "False", ")", "for", "repo", "in", "repo_list_b", ":", "included", "[", "repo", ".", "full_name", "]", "=", "True", "a_minus_b", "=", "l...
35.086957
0.002413
def _check_and_uninstall_ruby(ret, ruby, user=None): ''' Verify that ruby is uninstalled ''' ret = _ruby_installed(ret, ruby, user=user) if ret['result']: if ret['default']: __salt__['rbenv.default']('system', runas=user) if __salt__['rbenv.uninstall_ruby'](ruby, runas=u...
[ "def", "_check_and_uninstall_ruby", "(", "ret", ",", "ruby", ",", "user", "=", "None", ")", ":", "ret", "=", "_ruby_installed", "(", "ret", ",", "ruby", ",", "user", "=", "user", ")", "if", "ret", "[", "'result'", "]", ":", "if", "ret", "[", "'defaul...
31.043478
0.001359
def render(self, context): """ The default Django render() method for the tag. This method resolves the filter expressions, and calls :func:`render_tag`. """ # Resolve token kwargs tag_args = [expr.resolve(context) for expr in self.args] if self.compile_args else self.ar...
[ "def", "render", "(", "self", ",", "context", ")", ":", "# Resolve token kwargs", "tag_args", "=", "[", "expr", ".", "resolve", "(", "context", ")", "for", "expr", "in", "self", ".", "args", "]", "if", "self", ".", "compile_args", "else", "self", ".", ...
47.454545
0.009398
def system_channel(self): """Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages. Currently this is only for new member joins. If no channel is set, then this returns ``None``. """ channel_id = self._system_channel_id return channel_id and self._...
[ "def", "system_channel", "(", "self", ")", ":", "channel_id", "=", "self", ".", "_system_channel_id", "return", "channel_id", "and", "self", ".", "_channels", ".", "get", "(", "channel_id", ")" ]
48.285714
0.011628
def authorization_code_grant_flow(credentials, storage_filename): """Get an access token through Authorization Code Grant. Parameters credentials (dict) All your app credentials and information imported from the configuration file. storage_filename (str) File...
[ "def", "authorization_code_grant_flow", "(", "credentials", ",", "storage_filename", ")", ":", "auth_flow", "=", "AuthorizationCodeGrant", "(", "credentials", ".", "get", "(", "'client_id'", ")", ",", "credentials", ".", "get", "(", "'scopes'", ")", ",", "credenti...
32.981132
0.000556
def set(self, key, items): """Set key to a copy of items""" if not isinstance(items, list): raise ValueError("items must be a list") with self._lock: self._dict[key] = items.copy()
[ "def", "set", "(", "self", ",", "key", ",", "items", ")", ":", "if", "not", "isinstance", "(", "items", ",", "list", ")", ":", "raise", "ValueError", "(", "\"items must be a list\"", ")", "with", "self", ".", "_lock", ":", "self", ".", "_dict", "[", ...
37.166667
0.008772
def resume(self): """Resume tracing after a `pause`.""" for tracer in self.tracers: tracer.start() threading.settrace(self._installation_trace)
[ "def", "resume", "(", "self", ")", ":", "for", "tracer", "in", "self", ".", "tracers", ":", "tracer", ".", "start", "(", ")", "threading", ".", "settrace", "(", "self", ".", "_installation_trace", ")" ]
35
0.011173
def make_sequence(content, error=None, version=None, mode=None, mask=None, encoding=None, boost_error=True, symbol_count=None): """\ Creates a sequence of QR Codes. If the content fits into one QR Code and neither ``version`` nor ``symbol_count`` is provided, this function may return ...
[ "def", "make_sequence", "(", "content", ",", "error", "=", "None", ",", "version", "=", "None", ",", "mode", "=", "None", ",", "mask", "=", "None", ",", "encoding", "=", "None", ",", "boost_error", "=", "True", ",", "symbol_count", "=", "None", ")", ...
43.74359
0.001147
def CaseGroups(unicode_dir=_UNICODE_DIR): """Returns list of Unicode code groups equivalent under case folding. Each group is a sorted list of code points, and the list of groups is sorted by first code point in the group. Args: unicode_dir: Unicode data directory Returns: list of Unicode code gr...
[ "def", "CaseGroups", "(", "unicode_dir", "=", "_UNICODE_DIR", ")", ":", "# Dict mapping lowercase code point to fold-equivalent group.", "togroup", "=", "{", "}", "def", "DoLine", "(", "codes", ",", "fields", ")", ":", "\"\"\"Process single CaseFolding.txt line, updating to...
25.0625
0.013205
def diff_config(self, second_host, mode='stanza'): """ Generate configuration differences with a second device. Purpose: Open a second ncclient.manager.Manager with second_host, and | and pull the configuration from it. We then use difflib to | get the delta between the tw...
[ "def", "diff_config", "(", "self", ",", "second_host", ",", "mode", "=", "'stanza'", ")", ":", "second_conn", "=", "manager", ".", "connect", "(", "host", "=", "second_host", ",", "port", "=", "self", ".", "port", ",", "username", "=", "self", ".", "us...
39.857143
0.001166
def kappa_se_calc(PA, PE, POP): """ Calculate kappa standard error. :param PA: observed agreement among raters (overall accuracy) :type PA : float :param PE: hypothetical probability of chance agreement (random accuracy) :type PE : float :param POP: population :type POP:int :return...
[ "def", "kappa_se_calc", "(", "PA", ",", "PE", ",", "POP", ")", ":", "try", ":", "result", "=", "math", ".", "sqrt", "(", "(", "PA", "*", "(", "1", "-", "PA", ")", ")", "/", "(", "POP", "*", "(", "(", "1", "-", "PE", ")", "**", "2", ")", ...
28.588235
0.001992
def iter_content(self, chunk_size=1, warn_only=False): """ yields stdout data, chunk by chunk :param chunk_size: size of each chunk (in bytes) """ self._state = "not finished" if self.return_code is not None: stdout = io.BytesIO(self._stdout) data...
[ "def", "iter_content", "(", "self", ",", "chunk_size", "=", "1", ",", "warn_only", "=", "False", ")", ":", "self", ".", "_state", "=", "\"not finished\"", "if", "self", ".", "return_code", "is", "not", "None", ":", "stdout", "=", "io", ".", "BytesIO", ...
33.452381
0.001383
def show(self): """Override the QWidget::show() method to properly recalculate the editor viewport. """ if self.isHidden(): QWidget.show(self) self._qpart.updateViewport()
[ "def", "show", "(", "self", ")", ":", "if", "self", ".", "isHidden", "(", ")", ":", "QWidget", ".", "show", "(", "self", ")", "self", ".", "_qpart", ".", "updateViewport", "(", ")" ]
32
0.008696
def set_do_not_order_list(self, restricted_list, on_error='fail'): """Set a restriction on which assets can be ordered. Parameters ---------- restricted_list : container[Asset], SecurityList The assets that cannot be ordered. """ if isinstance(restricted_list...
[ "def", "set_do_not_order_list", "(", "self", ",", "restricted_list", ",", "on_error", "=", "'fail'", ")", ":", "if", "isinstance", "(", "restricted_list", ",", "SecurityList", ")", ":", "warnings", ".", "warn", "(", "\"`set_do_not_order_list(security_lists.leveraged_e...
42.933333
0.001519
def storeServiceSpecialCase(st, pups): """ Adapt a store to L{IServiceCollection}. @param st: The L{Store} to adapt. @param pups: A list of L{IServiceCollection} powerups on C{st}. @return: An L{IServiceCollection} which has all of C{pups} as children. """ if st.parent is not None: ...
[ "def", "storeServiceSpecialCase", "(", "st", ",", "pups", ")", ":", "if", "st", ".", "parent", "is", "not", "None", ":", "# If for some bizarre reason we're starting a substore's service, let's", "# just assume that its parent is running its upgraders, rather than", "# risk start...
37.135135
0.000709
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
[ "def", "as_xml", "(", "self", ",", "parent", ")", ":", "n", "=", "parent", ".", "newChild", "(", "None", ",", "\"CATEGORIES\"", ",", "None", ")", "for", "k", "in", "self", ".", "keywords", ":", "n", ".", "newTextChild", "(", "None", ",", "\"KEYWORD\"...
31.928571
0.017391
def runGenome(bfile, options): """Runs the genome command from plink. :param bfile: the input file prefix. :param options: the options. :type bfile: str :type options: argparse.Namespace :returns: the name of the ``genome`` file. Runs Plink with the ``genome`` option. If the user asks fo...
[ "def", "runGenome", "(", "bfile", ",", "options", ")", ":", "outPrefix", "=", "options", ".", "out", "+", "\".genome\"", "if", "options", ".", "sge", ":", "# We run genome using SGE", "# We need to create a frequency file using plink", "plinkCommand", "=", "[", "\"p...
35.395349
0.000639
def is_json_file(abspath): """Parse file extension. - *.json: uncompressed, utf-8 encode json file - *.gz: compressed, utf-8 encode json file """ abspath = abspath.lower() fname, ext = os.path.splitext(abspath) if ext in [".json", ".js"]: is_json = True elif ext == ".gz": ...
[ "def", "is_json_file", "(", "abspath", ")", ":", "abspath", "=", "abspath", ".", "lower", "(", ")", "fname", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "abspath", ")", "if", "ext", "in", "[", "\".json\"", ",", "\".js\"", "]", ":", "i...
29.4
0.001647
def _correlation_normalization(self, corr): """Do within-subject normalization. This method uses scipy.zscore to normalize the data, but is much slower than its C++ counterpart. It is doing in-place z-score. Parameters ---------- corr: 3D array in shape [num_pro...
[ "def", "_correlation_normalization", "(", "self", ",", "corr", ")", ":", "time1", "=", "time", ".", "time", "(", ")", "(", "sv", ",", "e", ",", "av", ")", "=", "corr", ".", "shape", "for", "i", "in", "range", "(", "sv", ")", ":", "start", "=", ...
38.230769
0.001308
def pdist_squareformed_numpy(a): """ Compute spatial distance using pure numpy (similar to scipy.spatial.distance.cdist()) Thanks to Divakar Roy (@droyed) at stackoverflow.com Note this needs at least np.float64 precision! Returns: dist """ a = np.array(a, dtype=np.float64) a_sumr...
[ "def", "pdist_squareformed_numpy", "(", "a", ")", ":", "a", "=", "np", ".", "array", "(", "a", ",", "dtype", "=", "np", ".", "float64", ")", "a_sumrows", "=", "np", ".", "einsum", "(", "'ij,ij->i'", ",", "a", ",", "a", ")", "dist", "=", "a_sumrows"...
27.9375
0.002165
def filter_styles(style, group, other_groups, blacklist=[]): """ Filters styles which are specific to a particular artist, e.g. for a GraphPlot this will filter options specific to the nodes and edges. Arguments --------- style: dict Dictionary of styles and values group: str ...
[ "def", "filter_styles", "(", "style", ",", "group", ",", "other_groups", ",", "blacklist", "=", "[", "]", ")", ":", "group", "=", "group", "+", "'_'", "filtered", "=", "{", "}", "for", "k", ",", "v", "in", "style", ".", "items", "(", ")", ":", "i...
27.529412
0.002064
def weights(self): """! @brief Return weight of each neuron. @return (list) Weights of each neuron. """ if self.__ccore_som_pointer is not None: self._weights = wrapper.som_get_weights(self.__ccore_som_pointer) return sel...
[ "def", "weights", "(", "self", ")", ":", "if", "self", ".", "__ccore_som_pointer", "is", "not", "None", ":", "self", ".", "_weights", "=", "wrapper", ".", "som_get_weights", "(", "self", ".", "__ccore_som_pointer", ")", "return", "self", ".", "_weights" ]
26.583333
0.015152
def try_wrapper(fxn): """Wraps a function, returning (True, fxn(val)) if successful, (False, val) if not.""" def wrapper(val): """Try to call fxn with the given value. If successful, return (True, fxn(val)), otherwise returns (False, val). """ try: return (True, fxn(val)) except Exception:...
[ "def", "try_wrapper", "(", "fxn", ")", ":", "def", "wrapper", "(", "val", ")", ":", "\"\"\"Try to call fxn with the given value. If successful, return (True, fxn(val)), otherwise\n returns (False, val).\n \"\"\"", "try", ":", "return", "(", "True", ",", "fxn", "(", "v...
32.090909
0.022039
def _axis_size(x, axis=None): """Get number of elements of `x` in `axis`, as type `x.dtype`.""" if axis is None: return tf.cast(tf.size(input=x), x.dtype) return tf.cast( tf.reduce_prod(input_tensor=tf.gather(tf.shape(input=x), axis)), x.dtype)
[ "def", "_axis_size", "(", "x", ",", "axis", "=", "None", ")", ":", "if", "axis", "is", "None", ":", "return", "tf", ".", "cast", "(", "tf", ".", "size", "(", "input", "=", "x", ")", ",", "x", ".", "dtype", ")", "return", "tf", ".", "cast", "(...
42.5
0.015385
def checkSubstitute(self, typecode): '''If this is True, allow typecode to be substituted for "self" typecode. ''' if not isinstance(typecode, ElementDeclaration): return False try: nsuri,ncname = typecode.substitutionGroup except (AttributeError...
[ "def", "checkSubstitute", "(", "self", ",", "typecode", ")", ":", "if", "not", "isinstance", "(", "typecode", ",", "ElementDeclaration", ")", ":", "return", "False", "try", ":", "nsuri", ",", "ncname", "=", "typecode", ".", "substitutionGroup", "except", "("...
29.625
0.012262
def seek(self,index): """Move the current seek pointer to the given block. You can use negative indices to seek from the end, with identical semantics to those of Python lists.""" if index<0: index = self.nblocks + index self._validate_index(index) self.block...
[ "def", "seek", "(", "self", ",", "index", ")", ":", "if", "index", "<", "0", ":", "index", "=", "self", ".", "nblocks", "+", "index", "self", ".", "_validate_index", "(", "index", ")", "self", ".", "block_index", "=", "index", "self", ".", "finished"...
35.5
0.010989
def _Region3(rho, T): """Basic equation for region 3 Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] Returns ------- prop : dict Dict with calculated properties. The available properties are: * v: Specific volume, [m³/k...
[ "def", "_Region3", "(", "rho", ",", "T", ")", ":", "I", "=", "[", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "1", ",", "1", ",", "1", ",", "1", ",", "2", ",", "2", ",", "2", ",", "2", ",", "2", ",", "2",...
35.29
0.000551
def get_unique_column(self, table): """Determine if any of the columns in a table contain exclusively unique values.""" for col in self.get_columns(table): if self.count_rows_duplicates(table, col) == 0: return col
[ "def", "get_unique_column", "(", "self", ",", "table", ")", ":", "for", "col", "in", "self", ".", "get_columns", "(", "table", ")", ":", "if", "self", ".", "count_rows_duplicates", "(", "table", ",", "col", ")", "==", "0", ":", "return", "col" ]
50.8
0.011628
def bank_short_name(self): """str or None: The short name of the bank associated with the BIC.""" entry = registry.get('bic').get(self.compact) if entry: return entry.get('short_name')
[ "def", "bank_short_name", "(", "self", ")", ":", "entry", "=", "registry", ".", "get", "(", "'bic'", ")", ".", "get", "(", "self", ".", "compact", ")", "if", "entry", ":", "return", "entry", ".", "get", "(", "'short_name'", ")" ]
43.2
0.009091
def cast(type_, value, default=ABSENT): """Cast a value to given type, optionally returning a default, if provided. :param type_: Type to cast the ``value`` into :param value: Value to cast into ``type_`` :return: ``value`` casted to ``type_``. If cast was unsuccessful and ``default`` was...
[ "def", "cast", "(", "type_", ",", "value", ",", "default", "=", "ABSENT", ")", ":", "# ``type_`` not being a type would theoretically be grounds for TypeError,", "# but since that kind of exception is a valid and expected outcome here", "# in some cases, we use the closest Python has to ...
41.736842
0.000616